babylon.2.0-beta.debug.js 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629
  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 getWebGLTextureType = function (gl, type) {
  3279. var textureType = gl.UNSIGNED_BYTE;
  3280. if (type === Engine.TEXTURETYPE_FLOAT)
  3281. textureType = gl.FLOAT;
  3282. return textureType;
  3283. };
  3284. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3285. var magFilter = gl.NEAREST;
  3286. var minFilter = gl.NEAREST;
  3287. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3288. magFilter = gl.LINEAR;
  3289. if (generateMipMaps) {
  3290. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3291. } else {
  3292. minFilter = gl.LINEAR;
  3293. }
  3294. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3295. magFilter = gl.LINEAR;
  3296. if (generateMipMaps) {
  3297. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3298. } else {
  3299. minFilter = gl.LINEAR;
  3300. }
  3301. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3302. magFilter = gl.NEAREST;
  3303. if (generateMipMaps) {
  3304. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3305. } else {
  3306. minFilter = gl.NEAREST;
  3307. }
  3308. }
  3309. return {
  3310. min: minFilter,
  3311. mag: magFilter
  3312. };
  3313. };
  3314. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3315. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3316. var engine = scene.getEngine();
  3317. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3318. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3319. gl.bindTexture(gl.TEXTURE_2D, texture);
  3320. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3321. processFunction(potWidth, potHeight);
  3322. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3323. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3324. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3325. if (!noMipmap && !isCompressed) {
  3326. gl.generateMipmap(gl.TEXTURE_2D);
  3327. }
  3328. gl.bindTexture(gl.TEXTURE_2D, null);
  3329. engine._activeTexturesCache = [];
  3330. texture._baseWidth = width;
  3331. texture._baseHeight = height;
  3332. texture._width = potWidth;
  3333. texture._height = potHeight;
  3334. texture.isReady = true;
  3335. texture.samplingMode = samplingMode;
  3336. scene._removePendingData(texture);
  3337. };
  3338. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3339. var onload = function () {
  3340. loadedImages[index] = img;
  3341. loadedImages._internalCount++;
  3342. scene._removePendingData(img);
  3343. if (loadedImages._internalCount === 6) {
  3344. onfinish(loadedImages);
  3345. }
  3346. };
  3347. var onerror = function () {
  3348. scene._removePendingData(img);
  3349. };
  3350. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3351. scene._addPendingData(img);
  3352. };
  3353. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3354. var loadedImages = [];
  3355. loadedImages._internalCount = 0;
  3356. for (var index = 0; index < 6; index++) {
  3357. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3358. }
  3359. };
  3360. var EngineCapabilities = (function () {
  3361. function EngineCapabilities() {
  3362. }
  3363. return EngineCapabilities;
  3364. })();
  3365. BABYLON.EngineCapabilities = EngineCapabilities;
  3366. /**
  3367. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3368. */
  3369. var Engine = (function () {
  3370. /**
  3371. * @constructor
  3372. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3373. * @param {boolean} [antialias] - enable antialias
  3374. * @param options - further options to be sent to the getContext function
  3375. */
  3376. function Engine(canvas, antialias, options) {
  3377. var _this = this;
  3378. // Public members
  3379. this.isFullscreen = false;
  3380. this.isPointerLock = false;
  3381. this.cullBackFaces = true;
  3382. this.renderEvenInBackground = true;
  3383. this.scenes = new Array();
  3384. this._windowIsBackground = false;
  3385. this._loadingDivBackgroundColor = "black";
  3386. this._drawCalls = 0;
  3387. this._renderingQueueLaunched = false;
  3388. this._activeRenderLoops = [];
  3389. // FPS
  3390. this.fpsRange = 60;
  3391. this.previousFramesDuration = [];
  3392. this.fps = 60;
  3393. this.deltaTime = 0;
  3394. // States
  3395. this._depthCullingState = new _DepthCullingState();
  3396. this._alphaState = new _AlphaState();
  3397. this._alphaMode = Engine.ALPHA_DISABLE;
  3398. // Cache
  3399. this._loadedTexturesCache = new Array();
  3400. this._activeTexturesCache = new Array();
  3401. this._compiledEffects = {};
  3402. this._uintIndicesCurrentlySet = false;
  3403. this._renderingCanvas = canvas;
  3404. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3405. options = options || {};
  3406. options.antialias = antialias;
  3407. try {
  3408. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3409. } catch (e) {
  3410. throw new Error("WebGL not supported");
  3411. }
  3412. if (!this._gl) {
  3413. throw new Error("WebGL not supported");
  3414. }
  3415. this._onBlur = function () {
  3416. _this._windowIsBackground = true;
  3417. };
  3418. this._onFocus = function () {
  3419. _this._windowIsBackground = false;
  3420. };
  3421. window.addEventListener("blur", this._onBlur);
  3422. window.addEventListener("focus", this._onFocus);
  3423. // Textures
  3424. this._workingCanvas = document.createElement("canvas");
  3425. this._workingContext = this._workingCanvas.getContext("2d");
  3426. // Viewport
  3427. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3428. this.resize();
  3429. // Caps
  3430. this._caps = new EngineCapabilities();
  3431. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3432. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3433. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3434. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3435. // Infos
  3436. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3437. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3438. if (rendererInfo != null) {
  3439. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3440. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3441. }
  3442. if (!this._glVendor) {
  3443. this._glVendor = "Unknown vendor";
  3444. }
  3445. if (!this._glRenderer) {
  3446. this._glRenderer = "Unknown renderer";
  3447. }
  3448. // Extensions
  3449. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3450. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3451. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3452. 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');
  3453. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3454. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3455. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3456. // Depth buffer
  3457. this.setDepthBuffer(true);
  3458. this.setDepthFunctionToLessOrEqual();
  3459. this.setDepthWrite(true);
  3460. // Fullscreen
  3461. this._onFullscreenChange = function () {
  3462. if (document.fullscreen !== undefined) {
  3463. _this.isFullscreen = document.fullscreen;
  3464. } else if (document.mozFullScreen !== undefined) {
  3465. _this.isFullscreen = document.mozFullScreen;
  3466. } else if (document.webkitIsFullScreen !== undefined) {
  3467. _this.isFullscreen = document.webkitIsFullScreen;
  3468. } else if (document.msIsFullScreen !== undefined) {
  3469. _this.isFullscreen = document.msIsFullScreen;
  3470. }
  3471. // Pointer lock
  3472. if (_this.isFullscreen && _this._pointerLockRequested) {
  3473. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3474. if (canvas.requestPointerLock) {
  3475. canvas.requestPointerLock();
  3476. }
  3477. }
  3478. };
  3479. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3480. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3481. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3482. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3483. // Pointer lock
  3484. this._onPointerLockChange = function () {
  3485. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3486. };
  3487. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3488. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3489. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3490. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3491. this._audioEngine = new BABYLON.AudioEngine();
  3492. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3493. }
  3494. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3495. get: function () {
  3496. return Engine._ALPHA_DISABLE;
  3497. },
  3498. enumerable: true,
  3499. configurable: true
  3500. });
  3501. Object.defineProperty(Engine, "ALPHA_ADD", {
  3502. get: function () {
  3503. return Engine._ALPHA_ADD;
  3504. },
  3505. enumerable: true,
  3506. configurable: true
  3507. });
  3508. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3509. get: function () {
  3510. return Engine._ALPHA_COMBINE;
  3511. },
  3512. enumerable: true,
  3513. configurable: true
  3514. });
  3515. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3516. get: function () {
  3517. return Engine._DELAYLOADSTATE_NONE;
  3518. },
  3519. enumerable: true,
  3520. configurable: true
  3521. });
  3522. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3523. get: function () {
  3524. return Engine._DELAYLOADSTATE_LOADED;
  3525. },
  3526. enumerable: true,
  3527. configurable: true
  3528. });
  3529. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3530. get: function () {
  3531. return Engine._DELAYLOADSTATE_LOADING;
  3532. },
  3533. enumerable: true,
  3534. configurable: true
  3535. });
  3536. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3537. get: function () {
  3538. return Engine._DELAYLOADSTATE_NOTLOADED;
  3539. },
  3540. enumerable: true,
  3541. configurable: true
  3542. });
  3543. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3544. get: function () {
  3545. return Engine._TEXTUREFORMAT_ALPHA;
  3546. },
  3547. enumerable: true,
  3548. configurable: true
  3549. });
  3550. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3551. get: function () {
  3552. return Engine._TEXTUREFORMAT_LUMINANCE;
  3553. },
  3554. enumerable: true,
  3555. configurable: true
  3556. });
  3557. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3558. get: function () {
  3559. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3560. },
  3561. enumerable: true,
  3562. configurable: true
  3563. });
  3564. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3565. get: function () {
  3566. return Engine._TEXTUREFORMAT_RGB;
  3567. },
  3568. enumerable: true,
  3569. configurable: true
  3570. });
  3571. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3572. get: function () {
  3573. return Engine._TEXTUREFORMAT_RGBA;
  3574. },
  3575. enumerable: true,
  3576. configurable: true
  3577. });
  3578. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3579. get: function () {
  3580. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3581. },
  3582. enumerable: true,
  3583. configurable: true
  3584. });
  3585. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3586. get: function () {
  3587. return Engine._TEXTURETYPE_FLOAT;
  3588. },
  3589. enumerable: true,
  3590. configurable: true
  3591. });
  3592. Object.defineProperty(Engine, "Version", {
  3593. get: function () {
  3594. return "2.0.0";
  3595. },
  3596. enumerable: true,
  3597. configurable: true
  3598. });
  3599. Engine.prototype.getGlInfo = function () {
  3600. return {
  3601. vendor: this._glVendor,
  3602. renderer: this._glRenderer,
  3603. version: this._glVersion
  3604. };
  3605. };
  3606. Engine.prototype.getAudioEngine = function () {
  3607. return this._audioEngine;
  3608. };
  3609. Engine.prototype.getAspectRatio = function (camera) {
  3610. var viewport = camera.viewport;
  3611. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3612. };
  3613. Engine.prototype.getRenderWidth = function () {
  3614. if (this._currentRenderTarget) {
  3615. return this._currentRenderTarget._width;
  3616. }
  3617. return this._renderingCanvas.width;
  3618. };
  3619. Engine.prototype.getRenderHeight = function () {
  3620. if (this._currentRenderTarget) {
  3621. return this._currentRenderTarget._height;
  3622. }
  3623. return this._renderingCanvas.height;
  3624. };
  3625. Engine.prototype.getRenderingCanvas = function () {
  3626. return this._renderingCanvas;
  3627. };
  3628. Engine.prototype.getRenderingCanvasClientRect = function () {
  3629. return this._renderingCanvas.getBoundingClientRect();
  3630. };
  3631. Engine.prototype.setHardwareScalingLevel = function (level) {
  3632. this._hardwareScalingLevel = level;
  3633. this.resize();
  3634. };
  3635. Engine.prototype.getHardwareScalingLevel = function () {
  3636. return this._hardwareScalingLevel;
  3637. };
  3638. Engine.prototype.getLoadedTexturesCache = function () {
  3639. return this._loadedTexturesCache;
  3640. };
  3641. Engine.prototype.getCaps = function () {
  3642. return this._caps;
  3643. };
  3644. Object.defineProperty(Engine.prototype, "drawCalls", {
  3645. get: function () {
  3646. return this._drawCalls;
  3647. },
  3648. enumerable: true,
  3649. configurable: true
  3650. });
  3651. // Methods
  3652. Engine.prototype.resetDrawCalls = function () {
  3653. this._drawCalls = 0;
  3654. };
  3655. Engine.prototype.setDepthFunctionToGreater = function () {
  3656. this._depthCullingState.depthFunc = this._gl.GREATER;
  3657. };
  3658. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3659. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3660. };
  3661. Engine.prototype.setDepthFunctionToLess = function () {
  3662. this._depthCullingState.depthFunc = this._gl.LESS;
  3663. };
  3664. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3665. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3666. };
  3667. /**
  3668. * stop executing a render loop function and remove it from the execution array
  3669. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3670. */
  3671. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3672. if (!renderFunction) {
  3673. this._activeRenderLoops = [];
  3674. return;
  3675. }
  3676. var index = this._activeRenderLoops.indexOf(renderFunction);
  3677. if (index >= 0) {
  3678. this._activeRenderLoops.splice(index, 1);
  3679. }
  3680. };
  3681. Engine.prototype._renderLoop = function () {
  3682. var _this = this;
  3683. var shouldRender = true;
  3684. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3685. shouldRender = false;
  3686. }
  3687. if (shouldRender) {
  3688. // Start new frame
  3689. this.beginFrame();
  3690. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3691. var renderFunction = this._activeRenderLoops[index];
  3692. renderFunction();
  3693. }
  3694. // Present
  3695. this.endFrame();
  3696. }
  3697. if (this._activeRenderLoops.length > 0) {
  3698. // Register new frame
  3699. BABYLON.Tools.QueueNewFrame(function () {
  3700. _this._renderLoop();
  3701. });
  3702. } else {
  3703. this._renderingQueueLaunched = false;
  3704. }
  3705. };
  3706. /**
  3707. * Register and execute a render loop. The engine can have more than one render function.
  3708. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3709. * @example
  3710. * engine.runRenderLoop(function () {
  3711. * scene.render()
  3712. * })
  3713. */
  3714. Engine.prototype.runRenderLoop = function (renderFunction) {
  3715. var _this = this;
  3716. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3717. return;
  3718. }
  3719. this._activeRenderLoops.push(renderFunction);
  3720. if (!this._renderingQueueLaunched) {
  3721. this._renderingQueueLaunched = true;
  3722. BABYLON.Tools.QueueNewFrame(function () {
  3723. _this._renderLoop();
  3724. });
  3725. }
  3726. };
  3727. /**
  3728. * Toggle full screen mode.
  3729. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3730. */
  3731. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3732. if (this.isFullscreen) {
  3733. BABYLON.Tools.ExitFullscreen();
  3734. } else {
  3735. this._pointerLockRequested = requestPointerLock;
  3736. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3737. }
  3738. };
  3739. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3740. this.applyStates();
  3741. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3742. if (this._depthCullingState.depthMask) {
  3743. this._gl.clearDepth(1.0);
  3744. }
  3745. var mode = 0;
  3746. if (backBuffer)
  3747. mode |= this._gl.COLOR_BUFFER_BIT;
  3748. if (depthStencil && this._depthCullingState.depthMask)
  3749. mode |= this._gl.DEPTH_BUFFER_BIT;
  3750. this._gl.clear(mode);
  3751. };
  3752. /**
  3753. * Set the WebGL's viewport
  3754. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3755. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3756. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3757. */
  3758. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3759. var width = requiredWidth || this._renderingCanvas.width;
  3760. var height = requiredHeight || this._renderingCanvas.height;
  3761. var x = viewport.x || 0;
  3762. var y = viewport.y || 0;
  3763. this._cachedViewport = viewport;
  3764. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3765. };
  3766. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3767. this._cachedViewport = null;
  3768. this._gl.viewport(x, y, width, height);
  3769. };
  3770. Engine.prototype.beginFrame = function () {
  3771. this._measureFps();
  3772. };
  3773. Engine.prototype.endFrame = function () {
  3774. this.flushFramebuffer();
  3775. };
  3776. /**
  3777. * resize the view according to the canvas' size.
  3778. * @example
  3779. * window.addEventListener("resize", function () {
  3780. * engine.resize();
  3781. * });
  3782. */
  3783. Engine.prototype.resize = function () {
  3784. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3785. };
  3786. /**
  3787. * force a specific size of the canvas
  3788. * @param {number} width - the new canvas' width
  3789. * @param {number} height - the new canvas' height
  3790. */
  3791. Engine.prototype.setSize = function (width, height) {
  3792. this._renderingCanvas.width = width;
  3793. this._renderingCanvas.height = height;
  3794. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3795. };
  3796. Engine.prototype.bindFramebuffer = function (texture) {
  3797. this._currentRenderTarget = texture;
  3798. var gl = this._gl;
  3799. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3800. this._gl.viewport(0, 0, texture._width, texture._height);
  3801. this.wipeCaches();
  3802. };
  3803. Engine.prototype.unBindFramebuffer = function (texture) {
  3804. this._currentRenderTarget = null;
  3805. if (texture.generateMipMaps) {
  3806. var gl = this._gl;
  3807. gl.bindTexture(gl.TEXTURE_2D, texture);
  3808. gl.generateMipmap(gl.TEXTURE_2D);
  3809. gl.bindTexture(gl.TEXTURE_2D, null);
  3810. }
  3811. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3812. };
  3813. Engine.prototype.flushFramebuffer = function () {
  3814. // this._gl.flush();
  3815. };
  3816. Engine.prototype.restoreDefaultFramebuffer = function () {
  3817. this._currentRenderTarget = null;
  3818. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3819. this.setViewport(this._cachedViewport);
  3820. this.wipeCaches();
  3821. };
  3822. // VBOs
  3823. Engine.prototype._resetVertexBufferBinding = function () {
  3824. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3825. this._cachedVertexBuffers = null;
  3826. };
  3827. Engine.prototype.createVertexBuffer = function (vertices) {
  3828. var vbo = this._gl.createBuffer();
  3829. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3830. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3831. this._resetVertexBufferBinding();
  3832. vbo.references = 1;
  3833. return vbo;
  3834. };
  3835. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3836. var vbo = this._gl.createBuffer();
  3837. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3838. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3839. this._resetVertexBufferBinding();
  3840. vbo.references = 1;
  3841. return vbo;
  3842. };
  3843. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3844. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3845. if (offset === undefined) {
  3846. offset = 0;
  3847. }
  3848. if (vertices instanceof Float32Array) {
  3849. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3850. } else {
  3851. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3852. }
  3853. this._resetVertexBufferBinding();
  3854. };
  3855. Engine.prototype._resetIndexBufferBinding = function () {
  3856. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3857. this._cachedIndexBuffer = null;
  3858. };
  3859. Engine.prototype.createIndexBuffer = function (indices) {
  3860. var vbo = this._gl.createBuffer();
  3861. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3862. // Check for 32 bits indices
  3863. var arrayBuffer;
  3864. var need32Bits = false;
  3865. if (this._caps.uintIndices) {
  3866. for (var index = 0; index < indices.length; index++) {
  3867. if (indices[index] > 65535) {
  3868. need32Bits = true;
  3869. break;
  3870. }
  3871. }
  3872. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3873. } else {
  3874. arrayBuffer = new Uint16Array(indices);
  3875. }
  3876. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3877. this._resetIndexBufferBinding();
  3878. vbo.references = 1;
  3879. vbo.is32Bits = need32Bits;
  3880. return vbo;
  3881. };
  3882. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3883. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3884. this._cachedVertexBuffers = vertexBuffer;
  3885. this._cachedEffectForVertexBuffers = effect;
  3886. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3887. var offset = 0;
  3888. for (var index = 0; index < vertexDeclaration.length; index++) {
  3889. var order = effect.getAttributeLocation(index);
  3890. if (order >= 0) {
  3891. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3892. }
  3893. offset += vertexDeclaration[index] * 4;
  3894. }
  3895. }
  3896. if (this._cachedIndexBuffer !== indexBuffer) {
  3897. this._cachedIndexBuffer = indexBuffer;
  3898. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3899. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3900. }
  3901. };
  3902. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3903. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3904. this._cachedVertexBuffers = vertexBuffers;
  3905. this._cachedEffectForVertexBuffers = effect;
  3906. var attributes = effect.getAttributesNames();
  3907. for (var index = 0; index < attributes.length; index++) {
  3908. var order = effect.getAttributeLocation(index);
  3909. if (order >= 0) {
  3910. var vertexBuffer = vertexBuffers[attributes[index]];
  3911. if (!vertexBuffer) {
  3912. continue;
  3913. }
  3914. var stride = vertexBuffer.getStrideSize();
  3915. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3916. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3917. }
  3918. }
  3919. }
  3920. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3921. this._cachedIndexBuffer = indexBuffer;
  3922. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3923. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3924. }
  3925. };
  3926. Engine.prototype._releaseBuffer = function (buffer) {
  3927. buffer.references--;
  3928. if (buffer.references === 0) {
  3929. this._gl.deleteBuffer(buffer);
  3930. return true;
  3931. }
  3932. return false;
  3933. };
  3934. Engine.prototype.createInstancesBuffer = function (capacity) {
  3935. var buffer = this._gl.createBuffer();
  3936. buffer.capacity = capacity;
  3937. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3938. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3939. return buffer;
  3940. };
  3941. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3942. this._gl.deleteBuffer(buffer);
  3943. };
  3944. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3945. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3946. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3947. for (var index = 0; index < 4; index++) {
  3948. var offsetLocation = offsetLocations[index];
  3949. this._gl.enableVertexAttribArray(offsetLocation);
  3950. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3951. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3952. }
  3953. };
  3954. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3955. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3956. for (var index = 0; index < 4; index++) {
  3957. var offsetLocation = offsetLocations[index];
  3958. this._gl.disableVertexAttribArray(offsetLocation);
  3959. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3960. }
  3961. };
  3962. Engine.prototype.applyStates = function () {
  3963. this._depthCullingState.apply(this._gl);
  3964. this._alphaState.apply(this._gl);
  3965. };
  3966. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3967. // Apply states
  3968. this.applyStates();
  3969. this._drawCalls++;
  3970. // Render
  3971. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3972. if (instancesCount) {
  3973. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3974. return;
  3975. }
  3976. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3977. };
  3978. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3979. // Apply states
  3980. this.applyStates();
  3981. this._drawCalls++;
  3982. if (instancesCount) {
  3983. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3984. return;
  3985. }
  3986. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3987. };
  3988. // Shaders
  3989. Engine.prototype._releaseEffect = function (effect) {
  3990. if (this._compiledEffects[effect._key]) {
  3991. delete this._compiledEffects[effect._key];
  3992. if (effect.getProgram()) {
  3993. this._gl.deleteProgram(effect.getProgram());
  3994. }
  3995. }
  3996. };
  3997. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3998. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3999. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4000. var name = vertex + "+" + fragment + "@" + defines;
  4001. if (this._compiledEffects[name]) {
  4002. return this._compiledEffects[name];
  4003. }
  4004. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4005. effect._key = name;
  4006. this._compiledEffects[name] = effect;
  4007. return effect;
  4008. };
  4009. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4010. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  4011. if (typeof samplers === "undefined") { samplers = []; }
  4012. if (typeof defines === "undefined") { defines = ""; }
  4013. return this.createEffect({
  4014. vertex: "particles",
  4015. fragmentElement: fragmentName
  4016. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4017. };
  4018. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4019. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4020. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4021. var shaderProgram = this._gl.createProgram();
  4022. this._gl.attachShader(shaderProgram, vertexShader);
  4023. this._gl.attachShader(shaderProgram, fragmentShader);
  4024. this._gl.linkProgram(shaderProgram);
  4025. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4026. if (!linked) {
  4027. var error = this._gl.getProgramInfoLog(shaderProgram);
  4028. if (error) {
  4029. throw new Error(error);
  4030. }
  4031. }
  4032. this._gl.deleteShader(vertexShader);
  4033. this._gl.deleteShader(fragmentShader);
  4034. return shaderProgram;
  4035. };
  4036. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4037. var results = [];
  4038. for (var index = 0; index < uniformsNames.length; index++) {
  4039. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4040. }
  4041. return results;
  4042. };
  4043. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4044. var results = [];
  4045. for (var index = 0; index < attributesNames.length; index++) {
  4046. try {
  4047. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4048. } catch (e) {
  4049. results.push(-1);
  4050. }
  4051. }
  4052. return results;
  4053. };
  4054. Engine.prototype.enableEffect = function (effect) {
  4055. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4056. if (effect && effect.onBind) {
  4057. effect.onBind(effect);
  4058. }
  4059. return;
  4060. }
  4061. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4062. // Use program
  4063. this._gl.useProgram(effect.getProgram());
  4064. for (var i in this._vertexAttribArrays) {
  4065. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4066. continue;
  4067. }
  4068. this._vertexAttribArrays[i] = false;
  4069. this._gl.disableVertexAttribArray(i);
  4070. }
  4071. var attributesCount = effect.getAttributesCount();
  4072. for (var index = 0; index < attributesCount; index++) {
  4073. // Attributes
  4074. var order = effect.getAttributeLocation(index);
  4075. if (order >= 0) {
  4076. this._vertexAttribArrays[order] = true;
  4077. this._gl.enableVertexAttribArray(order);
  4078. }
  4079. }
  4080. this._currentEffect = effect;
  4081. if (effect.onBind) {
  4082. effect.onBind(effect);
  4083. }
  4084. };
  4085. Engine.prototype.setArray = function (uniform, array) {
  4086. if (!uniform)
  4087. return;
  4088. this._gl.uniform1fv(uniform, array);
  4089. };
  4090. Engine.prototype.setMatrices = function (uniform, matrices) {
  4091. if (!uniform)
  4092. return;
  4093. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4094. };
  4095. Engine.prototype.setMatrix = function (uniform, matrix) {
  4096. if (!uniform)
  4097. return;
  4098. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4099. };
  4100. Engine.prototype.setFloat = function (uniform, value) {
  4101. if (!uniform)
  4102. return;
  4103. this._gl.uniform1f(uniform, value);
  4104. };
  4105. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4106. if (!uniform)
  4107. return;
  4108. this._gl.uniform2f(uniform, x, y);
  4109. };
  4110. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4111. if (!uniform)
  4112. return;
  4113. this._gl.uniform3f(uniform, x, y, z);
  4114. };
  4115. Engine.prototype.setBool = function (uniform, bool) {
  4116. if (!uniform)
  4117. return;
  4118. this._gl.uniform1i(uniform, bool);
  4119. };
  4120. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4121. if (!uniform)
  4122. return;
  4123. this._gl.uniform4f(uniform, x, y, z, w);
  4124. };
  4125. Engine.prototype.setColor3 = function (uniform, color3) {
  4126. if (!uniform)
  4127. return;
  4128. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4129. };
  4130. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4131. if (!uniform)
  4132. return;
  4133. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4134. };
  4135. // States
  4136. Engine.prototype.setState = function (culling, force) {
  4137. // Culling
  4138. if (this._depthCullingState.cull !== culling || force) {
  4139. if (culling) {
  4140. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4141. this._depthCullingState.cull = true;
  4142. } else {
  4143. this._depthCullingState.cull = false;
  4144. }
  4145. }
  4146. };
  4147. Engine.prototype.setDepthBuffer = function (enable) {
  4148. this._depthCullingState.depthTest = enable;
  4149. };
  4150. Engine.prototype.getDepthWrite = function () {
  4151. return this._depthCullingState.depthMask;
  4152. };
  4153. Engine.prototype.setDepthWrite = function (enable) {
  4154. this._depthCullingState.depthMask = enable;
  4155. };
  4156. Engine.prototype.setColorWrite = function (enable) {
  4157. this._gl.colorMask(enable, enable, enable, enable);
  4158. };
  4159. Engine.prototype.setAlphaMode = function (mode) {
  4160. switch (mode) {
  4161. case Engine.ALPHA_DISABLE:
  4162. this.setDepthWrite(true);
  4163. this._alphaState.alphaBlend = false;
  4164. break;
  4165. case Engine.ALPHA_COMBINE:
  4166. this.setDepthWrite(false);
  4167. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4168. this._alphaState.alphaBlend = true;
  4169. break;
  4170. case Engine.ALPHA_ADD:
  4171. this.setDepthWrite(false);
  4172. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4173. this._alphaState.alphaBlend = true;
  4174. break;
  4175. }
  4176. this._alphaMode = mode;
  4177. };
  4178. Engine.prototype.getAlphaMode = function () {
  4179. return this._alphaMode;
  4180. };
  4181. Engine.prototype.setAlphaTesting = function (enable) {
  4182. this._alphaTest = enable;
  4183. };
  4184. Engine.prototype.getAlphaTesting = function () {
  4185. return this._alphaTest;
  4186. };
  4187. // Textures
  4188. Engine.prototype.wipeCaches = function () {
  4189. this._activeTexturesCache = [];
  4190. this._currentEffect = null;
  4191. this._depthCullingState.reset();
  4192. this._alphaState.reset();
  4193. this._cachedVertexBuffers = null;
  4194. this._cachedIndexBuffer = null;
  4195. this._cachedEffectForVertexBuffers = null;
  4196. };
  4197. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4198. var gl = this._gl;
  4199. gl.bindTexture(gl.TEXTURE_2D, texture);
  4200. var magFilter = gl.NEAREST;
  4201. var minFilter = gl.NEAREST;
  4202. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4203. magFilter = gl.LINEAR;
  4204. minFilter = gl.LINEAR;
  4205. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4206. magFilter = gl.LINEAR;
  4207. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4208. }
  4209. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4210. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4211. gl.bindTexture(gl.TEXTURE_2D, null);
  4212. texture.samplingMode = samplingMode;
  4213. };
  4214. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4215. var _this = this;
  4216. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4217. if (typeof onLoad === "undefined") { onLoad = null; }
  4218. if (typeof onError === "undefined") { onError = null; }
  4219. if (typeof buffer === "undefined") { buffer = null; }
  4220. var texture = this._gl.createTexture();
  4221. var extension;
  4222. var fromData = false;
  4223. if (url.substr(0, 5) === "data:") {
  4224. fromData = true;
  4225. }
  4226. if (!fromData)
  4227. extension = url.substr(url.length - 4, 4).toLowerCase();
  4228. else {
  4229. var oldUrl = url;
  4230. fromData = oldUrl.split(':');
  4231. url = oldUrl;
  4232. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4233. }
  4234. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4235. var isTGA = (extension === ".tga");
  4236. scene._addPendingData(texture);
  4237. texture.url = url;
  4238. texture.noMipmap = noMipmap;
  4239. texture.references = 1;
  4240. this._loadedTexturesCache.push(texture);
  4241. var onerror = function () {
  4242. scene._removePendingData(texture);
  4243. if (onError) {
  4244. onError();
  4245. }
  4246. };
  4247. if (isTGA) {
  4248. var callback = function (arrayBuffer) {
  4249. var data = new Uint8Array(arrayBuffer);
  4250. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4251. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4252. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4253. if (onLoad) {
  4254. onLoad();
  4255. }
  4256. }, samplingMode);
  4257. };
  4258. if (!(fromData instanceof Array))
  4259. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4260. callback(arrayBuffer);
  4261. }, onerror, scene.database, true);
  4262. else
  4263. callback(buffer);
  4264. } else if (isDDS) {
  4265. callback = function (data) {
  4266. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4267. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4268. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4269. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4270. if (onLoad) {
  4271. onLoad();
  4272. }
  4273. }, samplingMode);
  4274. };
  4275. if (!(fromData instanceof Array))
  4276. BABYLON.Tools.LoadFile(url, function (data) {
  4277. callback(data);
  4278. }, onerror, scene.database, true);
  4279. else
  4280. callback(buffer);
  4281. } else {
  4282. var onload = function (img) {
  4283. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4284. var isPot = (img.width === potWidth && img.height === potHeight);
  4285. if (!isPot) {
  4286. _this._workingCanvas.width = potWidth;
  4287. _this._workingCanvas.height = potHeight;
  4288. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4289. _this._workingContext.imageSmoothingEnabled = false;
  4290. _this._workingContext.mozImageSmoothingEnabled = false;
  4291. _this._workingContext.oImageSmoothingEnabled = false;
  4292. _this._workingContext.webkitImageSmoothingEnabled = false;
  4293. _this._workingContext.msImageSmoothingEnabled = false;
  4294. }
  4295. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4296. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4297. _this._workingContext.imageSmoothingEnabled = true;
  4298. _this._workingContext.mozImageSmoothingEnabled = true;
  4299. _this._workingContext.oImageSmoothingEnabled = true;
  4300. _this._workingContext.webkitImageSmoothingEnabled = true;
  4301. _this._workingContext.msImageSmoothingEnabled = true;
  4302. }
  4303. }
  4304. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4305. if (onLoad) {
  4306. onLoad();
  4307. }
  4308. }, samplingMode);
  4309. };
  4310. if (!(fromData instanceof Array))
  4311. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4312. else
  4313. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4314. }
  4315. return texture;
  4316. };
  4317. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4318. var texture = this._gl.createTexture();
  4319. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4320. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4321. // Format
  4322. var internalFormat = this._gl.RGBA;
  4323. switch (format) {
  4324. case Engine.TEXTUREFORMAT_ALPHA:
  4325. internalFormat = this._gl.ALPHA;
  4326. break;
  4327. case Engine.TEXTUREFORMAT_LUMINANCE:
  4328. internalFormat = this._gl.LUMINANCE;
  4329. break;
  4330. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4331. internalFormat = this._gl.LUMINANCE_ALPHA;
  4332. break;
  4333. case Engine.TEXTUREFORMAT_RGB:
  4334. internalFormat = this._gl.RGB;
  4335. break;
  4336. case Engine.TEXTUREFORMAT_RGBA:
  4337. internalFormat = this._gl.RGBA;
  4338. break;
  4339. }
  4340. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4341. if (generateMipMaps) {
  4342. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4343. }
  4344. // Filters
  4345. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4346. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4347. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4348. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4349. this._activeTexturesCache = [];
  4350. texture._baseWidth = width;
  4351. texture._baseHeight = height;
  4352. texture._width = width;
  4353. texture._height = height;
  4354. texture.isReady = true;
  4355. texture.references = 1;
  4356. texture.samplingMode = samplingMode;
  4357. this._loadedTexturesCache.push(texture);
  4358. return texture;
  4359. };
  4360. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4361. var texture = this._gl.createTexture();
  4362. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4363. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4364. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4365. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4366. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4367. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4368. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4369. this._activeTexturesCache = [];
  4370. texture._baseWidth = width;
  4371. texture._baseHeight = height;
  4372. texture._width = width;
  4373. texture._height = height;
  4374. texture.isReady = false;
  4375. texture.generateMipMaps = generateMipMaps;
  4376. texture.references = 1;
  4377. texture.samplingMode = samplingMode;
  4378. this._loadedTexturesCache.push(texture);
  4379. return texture;
  4380. };
  4381. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4382. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4383. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4384. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4385. if (texture.generateMipMaps) {
  4386. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4387. }
  4388. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4389. this._activeTexturesCache = [];
  4390. texture.isReady = true;
  4391. };
  4392. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4393. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4394. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4395. // Scale the video if it is a NPOT using the current working canvas
  4396. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4397. if (!texture._workingCanvas) {
  4398. texture._workingCanvas = document.createElement("canvas");
  4399. texture._workingContext = texture._workingCanvas.getContext("2d");
  4400. texture._workingCanvas.width = texture._width;
  4401. texture._workingCanvas.height = texture._height;
  4402. }
  4403. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4404. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4405. } else {
  4406. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4407. }
  4408. if (texture.generateMipMaps) {
  4409. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4410. }
  4411. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4412. this._activeTexturesCache = [];
  4413. texture.isReady = true;
  4414. };
  4415. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4416. // old version had a "generateMipMaps" arg instead of options.
  4417. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4418. // in the same way, generateDepthBuffer is defaulted to true
  4419. var generateMipMaps = false;
  4420. var generateDepthBuffer = true;
  4421. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4422. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4423. if (options !== undefined) {
  4424. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4425. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4426. type = options.type === undefined ? type : options.type;
  4427. if (options.samplingMode !== undefined) {
  4428. samplingMode = options.samplingMode;
  4429. }
  4430. if (type === Engine.TEXTURETYPE_FLOAT) {
  4431. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4432. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4433. }
  4434. }
  4435. var gl = this._gl;
  4436. var texture = gl.createTexture();
  4437. gl.bindTexture(gl.TEXTURE_2D, texture);
  4438. var width = size.width || size;
  4439. var height = size.height || size;
  4440. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4441. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4442. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4443. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4444. }
  4445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4449. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4450. var depthBuffer;
  4451. // Create the depth buffer
  4452. if (generateDepthBuffer) {
  4453. depthBuffer = gl.createRenderbuffer();
  4454. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4455. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4456. }
  4457. // Create the framebuffer
  4458. var framebuffer = gl.createFramebuffer();
  4459. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4460. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4461. if (generateDepthBuffer) {
  4462. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4463. }
  4464. // Unbind
  4465. gl.bindTexture(gl.TEXTURE_2D, null);
  4466. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4467. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4468. texture._framebuffer = framebuffer;
  4469. if (generateDepthBuffer) {
  4470. texture._depthBuffer = depthBuffer;
  4471. }
  4472. texture._width = width;
  4473. texture._height = height;
  4474. texture.isReady = true;
  4475. texture.generateMipMaps = generateMipMaps;
  4476. texture.references = 1;
  4477. texture.samplingMode = samplingMode;
  4478. this._activeTexturesCache = [];
  4479. this._loadedTexturesCache.push(texture);
  4480. return texture;
  4481. };
  4482. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4483. var _this = this;
  4484. var gl = this._gl;
  4485. var texture = gl.createTexture();
  4486. texture.isCube = true;
  4487. texture.url = rootUrl;
  4488. texture.references = 1;
  4489. this._loadedTexturesCache.push(texture);
  4490. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4491. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4492. if (isDDS) {
  4493. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4494. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4495. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4496. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4497. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4498. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4499. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4500. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4501. }
  4502. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4503. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4504. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4505. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4506. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4507. _this._activeTexturesCache = [];
  4508. texture._width = info.width;
  4509. texture._height = info.height;
  4510. texture.isReady = true;
  4511. }, null, null, true);
  4512. } else {
  4513. cascadeLoad(rootUrl, scene, function (imgs) {
  4514. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4515. var height = width;
  4516. _this._workingCanvas.width = width;
  4517. _this._workingCanvas.height = height;
  4518. var faces = [
  4519. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4520. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4521. ];
  4522. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4523. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4524. for (var index = 0; index < faces.length; index++) {
  4525. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4526. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4527. }
  4528. if (!noMipmap) {
  4529. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4530. }
  4531. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4532. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4533. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4534. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4535. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4536. _this._activeTexturesCache = [];
  4537. texture._width = width;
  4538. texture._height = height;
  4539. texture.isReady = true;
  4540. }, extensions);
  4541. }
  4542. return texture;
  4543. };
  4544. Engine.prototype._releaseTexture = function (texture) {
  4545. var gl = this._gl;
  4546. if (texture._framebuffer) {
  4547. gl.deleteFramebuffer(texture._framebuffer);
  4548. }
  4549. if (texture._depthBuffer) {
  4550. gl.deleteRenderbuffer(texture._depthBuffer);
  4551. }
  4552. gl.deleteTexture(texture);
  4553. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4554. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4555. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4556. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4557. this._activeTexturesCache[channel] = null;
  4558. }
  4559. var index = this._loadedTexturesCache.indexOf(texture);
  4560. if (index !== -1) {
  4561. this._loadedTexturesCache.splice(index, 1);
  4562. }
  4563. };
  4564. Engine.prototype.bindSamplers = function (effect) {
  4565. this._gl.useProgram(effect.getProgram());
  4566. var samplers = effect.getSamplers();
  4567. for (var index = 0; index < samplers.length; index++) {
  4568. var uniform = effect.getUniform(samplers[index]);
  4569. this._gl.uniform1i(uniform, index);
  4570. }
  4571. this._currentEffect = null;
  4572. };
  4573. Engine.prototype._bindTexture = function (channel, texture) {
  4574. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4575. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4576. this._activeTexturesCache[channel] = null;
  4577. };
  4578. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4579. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4580. };
  4581. Engine.prototype.setTexture = function (channel, texture) {
  4582. if (channel < 0) {
  4583. return;
  4584. }
  4585. // Not ready?
  4586. if (!texture || !texture.isReady()) {
  4587. if (this._activeTexturesCache[channel] != null) {
  4588. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4589. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4590. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4591. this._activeTexturesCache[channel] = null;
  4592. }
  4593. return;
  4594. }
  4595. // Video
  4596. if (texture instanceof BABYLON.VideoTexture) {
  4597. if (texture.update()) {
  4598. this._activeTexturesCache[channel] = null;
  4599. }
  4600. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4601. texture.delayLoad();
  4602. return;
  4603. }
  4604. if (this._activeTexturesCache[channel] === texture) {
  4605. return;
  4606. }
  4607. this._activeTexturesCache[channel] = texture;
  4608. var internalTexture = texture.getInternalTexture();
  4609. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4610. if (internalTexture.isCube) {
  4611. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4612. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4613. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4614. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4615. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4616. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4617. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4618. }
  4619. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4620. } else {
  4621. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4622. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4623. internalTexture._cachedWrapU = texture.wrapU;
  4624. switch (texture.wrapU) {
  4625. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4626. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4627. break;
  4628. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4629. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4630. break;
  4631. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4632. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4633. break;
  4634. }
  4635. }
  4636. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4637. internalTexture._cachedWrapV = texture.wrapV;
  4638. switch (texture.wrapV) {
  4639. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4640. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4641. break;
  4642. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4643. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4644. break;
  4645. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4646. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4647. break;
  4648. }
  4649. }
  4650. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4651. }
  4652. };
  4653. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4654. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4655. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4656. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4657. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4658. }
  4659. };
  4660. Engine.prototype.readPixels = function (x, y, width, height) {
  4661. var data = new Uint8Array(height * width * 4);
  4662. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4663. return data;
  4664. };
  4665. // Dispose
  4666. Engine.prototype.dispose = function () {
  4667. this.hideLoadingUI();
  4668. this.stopRenderLoop();
  4669. while (this.scenes.length) {
  4670. this.scenes[0].dispose();
  4671. }
  4672. // Release audio engine
  4673. this._audioEngine.dispose();
  4674. for (var name in this._compiledEffects) {
  4675. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4676. }
  4677. for (var i in this._vertexAttribArrays) {
  4678. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4679. continue;
  4680. }
  4681. this._gl.disableVertexAttribArray(i);
  4682. }
  4683. // Events
  4684. window.removeEventListener("blur", this._onBlur);
  4685. window.removeEventListener("focus", this._onFocus);
  4686. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4687. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4688. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4689. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4690. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4691. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4692. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4693. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4694. };
  4695. // Loading screen
  4696. Engine.prototype.displayLoadingUI = function () {
  4697. var _this = this;
  4698. this._loadingDiv = document.createElement("div");
  4699. this._loadingDiv.style.opacity = "0";
  4700. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4701. // Loading text
  4702. this._loadingTextDiv = document.createElement("div");
  4703. this._loadingTextDiv.style.position = "absolute";
  4704. this._loadingTextDiv.style.left = "0";
  4705. this._loadingTextDiv.style.top = "50%";
  4706. this._loadingTextDiv.style.marginTop = "80px";
  4707. this._loadingTextDiv.style.width = "100%";
  4708. this._loadingTextDiv.style.height = "20px";
  4709. this._loadingTextDiv.style.fontFamily = "Arial";
  4710. this._loadingTextDiv.style.fontSize = "14px";
  4711. this._loadingTextDiv.style.color = "white";
  4712. this._loadingTextDiv.style.textAlign = "center";
  4713. this._loadingTextDiv.innerHTML = "Loading";
  4714. this._loadingDiv.appendChild(this._loadingTextDiv);
  4715. // Loading img
  4716. var imgBack = new Image();
  4717. 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==";
  4718. imgBack.style.position = "absolute";
  4719. imgBack.style.left = "50%";
  4720. imgBack.style.top = "50%";
  4721. imgBack.style.marginLeft = "-50px";
  4722. imgBack.style.marginTop = "-50px";
  4723. imgBack.style.transition = "transform 1.0s ease";
  4724. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4725. var deg = 360;
  4726. var onTransitionEnd = function () {
  4727. deg += 360;
  4728. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4729. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4730. };
  4731. imgBack.addEventListener("transitionend", onTransitionEnd);
  4732. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4733. this._loadingDiv.appendChild(imgBack);
  4734. // front image
  4735. var imgFront = new Image();
  4736. 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=";
  4737. imgFront.style.position = "absolute";
  4738. imgFront.style.left = "50%";
  4739. imgFront.style.top = "50%";
  4740. imgFront.style.marginLeft = "-50px";
  4741. imgFront.style.marginTop = "-50px";
  4742. this._loadingDiv.appendChild(imgFront);
  4743. // Resize
  4744. this._resizeLoadingUI = function () {
  4745. var canvasRect = _this.getRenderingCanvasClientRect();
  4746. _this._loadingDiv.style.position = "absolute";
  4747. _this._loadingDiv.style.left = canvasRect.left + "px";
  4748. _this._loadingDiv.style.top = canvasRect.top + "px";
  4749. _this._loadingDiv.style.width = canvasRect.width + "px";
  4750. _this._loadingDiv.style.height = canvasRect.height + "px";
  4751. };
  4752. this._resizeLoadingUI();
  4753. window.addEventListener("resize", this._resizeLoadingUI);
  4754. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4755. document.body.appendChild(this._loadingDiv);
  4756. setTimeout(function () {
  4757. _this._loadingDiv.style.opacity = "1";
  4758. imgBack.style.transform = "rotateZ(360deg)";
  4759. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4760. }, 0);
  4761. };
  4762. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4763. set: function (text) {
  4764. if (!this._loadingDiv) {
  4765. return;
  4766. }
  4767. this._loadingTextDiv.innerHTML = text;
  4768. },
  4769. enumerable: true,
  4770. configurable: true
  4771. });
  4772. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4773. get: function () {
  4774. return this._loadingDivBackgroundColor;
  4775. },
  4776. set: function (color) {
  4777. this._loadingDivBackgroundColor = color;
  4778. if (!this._loadingDiv) {
  4779. return;
  4780. }
  4781. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4782. },
  4783. enumerable: true,
  4784. configurable: true
  4785. });
  4786. Engine.prototype.hideLoadingUI = function () {
  4787. var _this = this;
  4788. if (!this._loadingDiv) {
  4789. return;
  4790. }
  4791. var onTransitionEnd = function () {
  4792. if (!_this._loadingDiv) {
  4793. return;
  4794. }
  4795. document.body.removeChild(_this._loadingDiv);
  4796. window.removeEventListener("resize", _this._resizeLoadingUI);
  4797. _this._loadingDiv = null;
  4798. };
  4799. this._loadingDiv.style.opacity = "0";
  4800. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4801. };
  4802. // FPS
  4803. Engine.prototype.getFps = function () {
  4804. return this.fps;
  4805. };
  4806. Engine.prototype.getDeltaTime = function () {
  4807. return this.deltaTime;
  4808. };
  4809. Engine.prototype._measureFps = function () {
  4810. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4811. var length = this.previousFramesDuration.length;
  4812. if (length >= 2) {
  4813. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4814. }
  4815. if (length >= this.fpsRange) {
  4816. if (length > this.fpsRange) {
  4817. this.previousFramesDuration.splice(0, 1);
  4818. length = this.previousFramesDuration.length;
  4819. }
  4820. var sum = 0;
  4821. for (var id = 0; id < length - 1; id++) {
  4822. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4823. }
  4824. this.fps = 1000.0 / (sum / (length - 1));
  4825. }
  4826. };
  4827. // Statics
  4828. Engine.isSupported = function () {
  4829. try {
  4830. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4831. if (navigator.isCocoonJS) {
  4832. return true;
  4833. }
  4834. var tempcanvas = document.createElement("canvas");
  4835. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4836. return gl != null && !!window.WebGLRenderingContext;
  4837. } catch (e) {
  4838. return false;
  4839. }
  4840. };
  4841. Engine._ALPHA_DISABLE = 0;
  4842. Engine._ALPHA_ADD = 1;
  4843. Engine._ALPHA_COMBINE = 2;
  4844. Engine._DELAYLOADSTATE_NONE = 0;
  4845. Engine._DELAYLOADSTATE_LOADED = 1;
  4846. Engine._DELAYLOADSTATE_LOADING = 2;
  4847. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4848. Engine._TEXTUREFORMAT_ALPHA = 0;
  4849. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4850. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4851. Engine._TEXTUREFORMAT_RGB = 4;
  4852. Engine._TEXTUREFORMAT_RGBA = 4;
  4853. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  4854. Engine._TEXTURETYPE_FLOAT = 1;
  4855. Engine.Epsilon = 0.001;
  4856. Engine.CollisionsEpsilon = 0.001;
  4857. Engine.ShadersRepository = "Babylon/Shaders/";
  4858. return Engine;
  4859. })();
  4860. BABYLON.Engine = Engine;
  4861. })(BABYLON || (BABYLON = {}));
  4862. //# sourceMappingURL=babylon.engine.js.map
  4863. var BABYLON;
  4864. (function (BABYLON) {
  4865. /**
  4866. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4867. */
  4868. var Node = (function () {
  4869. /**
  4870. * @constructor
  4871. * @param {string} name - the name and id to be given to this node
  4872. * @param {BABYLON.Scene} the scene this node will be added to
  4873. */
  4874. function Node(name, scene) {
  4875. this.state = "";
  4876. this.animations = new Array();
  4877. this._childrenFlag = -1;
  4878. this._isEnabled = true;
  4879. this._isReady = true;
  4880. this._currentRenderId = -1;
  4881. this.name = name;
  4882. this.id = name;
  4883. this._scene = scene;
  4884. this._initCache();
  4885. }
  4886. Node.prototype.getScene = function () {
  4887. return this._scene;
  4888. };
  4889. Node.prototype.getEngine = function () {
  4890. return this._scene.getEngine();
  4891. };
  4892. // override it in derived class
  4893. Node.prototype.getWorldMatrix = function () {
  4894. return BABYLON.Matrix.Identity();
  4895. };
  4896. // override it in derived class if you add new variables to the cache
  4897. // and call the parent class method
  4898. Node.prototype._initCache = function () {
  4899. this._cache = {};
  4900. this._cache.parent = undefined;
  4901. };
  4902. Node.prototype.updateCache = function (force) {
  4903. if (!force && this.isSynchronized())
  4904. return;
  4905. this._cache.parent = this.parent;
  4906. this._updateCache();
  4907. };
  4908. // override it in derived class if you add new variables to the cache
  4909. // and call the parent class method if !ignoreParentClass
  4910. Node.prototype._updateCache = function (ignoreParentClass) {
  4911. };
  4912. // override it in derived class if you add new variables to the cache
  4913. Node.prototype._isSynchronized = function () {
  4914. return true;
  4915. };
  4916. Node.prototype.isSynchronizedWithParent = function () {
  4917. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4918. };
  4919. Node.prototype.isSynchronized = function (updateCache) {
  4920. var check = this.hasNewParent();
  4921. check = check || !this.isSynchronizedWithParent();
  4922. check = check || !this._isSynchronized();
  4923. if (updateCache)
  4924. this.updateCache(true);
  4925. return !check;
  4926. };
  4927. Node.prototype.hasNewParent = function (update) {
  4928. if (this._cache.parent === this.parent)
  4929. return false;
  4930. if (update)
  4931. this._cache.parent = this.parent;
  4932. return true;
  4933. };
  4934. /**
  4935. * Is this node ready to be used/rendered
  4936. * @return {boolean} is it ready
  4937. */
  4938. Node.prototype.isReady = function () {
  4939. return this._isReady;
  4940. };
  4941. /**
  4942. * Is this node enabled.
  4943. * If the node has a parent and is enabled, the parent will be inspected as well.
  4944. * @return {boolean} whether this node (and its parent) is enabled.
  4945. * @see setEnabled
  4946. */
  4947. Node.prototype.isEnabled = function () {
  4948. if (!this._isEnabled) {
  4949. return false;
  4950. }
  4951. if (this.parent) {
  4952. return this.parent.isEnabled();
  4953. }
  4954. return true;
  4955. };
  4956. /**
  4957. * Set the enabled state of this node.
  4958. * @param {boolean} value - the new enabled state
  4959. * @see isEnabled
  4960. */
  4961. Node.prototype.setEnabled = function (value) {
  4962. this._isEnabled = value;
  4963. };
  4964. /**
  4965. * Is this node a descendant of the given node.
  4966. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  4967. * @param {BABYLON.Node} ancestor - The parent node to inspect
  4968. * @see parent
  4969. */
  4970. Node.prototype.isDescendantOf = function (ancestor) {
  4971. if (this.parent) {
  4972. if (this.parent === ancestor) {
  4973. return true;
  4974. }
  4975. return this.parent.isDescendantOf(ancestor);
  4976. }
  4977. return false;
  4978. };
  4979. Node.prototype._getDescendants = function (list, results) {
  4980. for (var index = 0; index < list.length; index++) {
  4981. var item = list[index];
  4982. if (item.isDescendantOf(this)) {
  4983. results.push(item);
  4984. }
  4985. }
  4986. };
  4987. /**
  4988. * Will return all nodes that have this node as parent.
  4989. * @return {BABYLON.Node[]} all children nodes of all types.
  4990. */
  4991. Node.prototype.getDescendants = function () {
  4992. var results = [];
  4993. this._getDescendants(this._scene.meshes, results);
  4994. this._getDescendants(this._scene.lights, results);
  4995. this._getDescendants(this._scene.cameras, results);
  4996. return results;
  4997. };
  4998. Node.prototype._setReady = function (state) {
  4999. if (state == this._isReady) {
  5000. return;
  5001. }
  5002. if (!state) {
  5003. this._isReady = false;
  5004. return;
  5005. }
  5006. this._isReady = true;
  5007. if (this.onReady) {
  5008. this.onReady(this);
  5009. }
  5010. };
  5011. return Node;
  5012. })();
  5013. BABYLON.Node = Node;
  5014. })(BABYLON || (BABYLON = {}));
  5015. //# sourceMappingURL=babylon.node.js.map
  5016. var BABYLON;
  5017. (function (BABYLON) {
  5018. var BoundingSphere = (function () {
  5019. function BoundingSphere(minimum, maximum) {
  5020. this.minimum = minimum;
  5021. this.maximum = maximum;
  5022. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5023. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5024. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5025. this.radius = distance * 0.5;
  5026. this.centerWorld = BABYLON.Vector3.Zero();
  5027. this._update(BABYLON.Matrix.Identity());
  5028. }
  5029. // Methods
  5030. BoundingSphere.prototype._update = function (world) {
  5031. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5032. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5033. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5034. };
  5035. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5036. for (var i = 0; i < 6; i++) {
  5037. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5038. return false;
  5039. }
  5040. return true;
  5041. };
  5042. BoundingSphere.prototype.intersectsPoint = function (point) {
  5043. var x = this.centerWorld.x - point.x;
  5044. var y = this.centerWorld.y - point.y;
  5045. var z = this.centerWorld.z - point.z;
  5046. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5047. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5048. return false;
  5049. return true;
  5050. };
  5051. // Statics
  5052. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5053. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5054. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5055. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5056. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5057. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5058. return false;
  5059. return true;
  5060. };
  5061. return BoundingSphere;
  5062. })();
  5063. BABYLON.BoundingSphere = BoundingSphere;
  5064. })(BABYLON || (BABYLON = {}));
  5065. //# sourceMappingURL=babylon.boundingSphere.js.map
  5066. var BABYLON;
  5067. (function (BABYLON) {
  5068. var BoundingBox = (function () {
  5069. function BoundingBox(minimum, maximum) {
  5070. this.minimum = minimum;
  5071. this.maximum = maximum;
  5072. this.vectors = new Array();
  5073. this.vectorsWorld = new Array();
  5074. // Bounding vectors
  5075. this.vectors.push(this.minimum.clone());
  5076. this.vectors.push(this.maximum.clone());
  5077. this.vectors.push(this.minimum.clone());
  5078. this.vectors[2].x = this.maximum.x;
  5079. this.vectors.push(this.minimum.clone());
  5080. this.vectors[3].y = this.maximum.y;
  5081. this.vectors.push(this.minimum.clone());
  5082. this.vectors[4].z = this.maximum.z;
  5083. this.vectors.push(this.maximum.clone());
  5084. this.vectors[5].z = this.minimum.z;
  5085. this.vectors.push(this.maximum.clone());
  5086. this.vectors[6].x = this.minimum.x;
  5087. this.vectors.push(this.maximum.clone());
  5088. this.vectors[7].y = this.minimum.y;
  5089. // OBB
  5090. this.center = this.maximum.add(this.minimum).scale(0.5);
  5091. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5092. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5093. for (var index = 0; index < this.vectors.length; index++) {
  5094. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5095. }
  5096. this.minimumWorld = BABYLON.Vector3.Zero();
  5097. this.maximumWorld = BABYLON.Vector3.Zero();
  5098. this._update(BABYLON.Matrix.Identity());
  5099. }
  5100. // Methods
  5101. BoundingBox.prototype.getWorldMatrix = function () {
  5102. return this._worldMatrix;
  5103. };
  5104. BoundingBox.prototype._update = function (world) {
  5105. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5106. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5107. for (var index = 0; index < this.vectors.length; index++) {
  5108. var v = this.vectorsWorld[index];
  5109. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5110. if (v.x < this.minimumWorld.x)
  5111. this.minimumWorld.x = v.x;
  5112. if (v.y < this.minimumWorld.y)
  5113. this.minimumWorld.y = v.y;
  5114. if (v.z < this.minimumWorld.z)
  5115. this.minimumWorld.z = v.z;
  5116. if (v.x > this.maximumWorld.x)
  5117. this.maximumWorld.x = v.x;
  5118. if (v.y > this.maximumWorld.y)
  5119. this.maximumWorld.y = v.y;
  5120. if (v.z > this.maximumWorld.z)
  5121. this.maximumWorld.z = v.z;
  5122. }
  5123. // OBB
  5124. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5125. this.center.scaleInPlace(0.5);
  5126. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5127. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5128. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5129. this._worldMatrix = world;
  5130. };
  5131. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5132. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5133. };
  5134. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5135. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5136. };
  5137. BoundingBox.prototype.intersectsPoint = function (point) {
  5138. var delta = BABYLON.Engine.Epsilon;
  5139. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5140. return false;
  5141. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5142. return false;
  5143. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5144. return false;
  5145. return true;
  5146. };
  5147. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5148. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5149. };
  5150. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5151. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5152. return false;
  5153. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5154. return false;
  5155. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5156. return false;
  5157. return true;
  5158. };
  5159. // Statics
  5160. BoundingBox.Intersects = function (box0, box1) {
  5161. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5162. return false;
  5163. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5164. return false;
  5165. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5166. return false;
  5167. return true;
  5168. };
  5169. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5170. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5171. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5172. return (num <= (sphereRadius * sphereRadius));
  5173. };
  5174. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5175. for (var p = 0; p < 6; p++) {
  5176. for (var i = 0; i < 8; i++) {
  5177. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5178. return false;
  5179. }
  5180. }
  5181. }
  5182. return true;
  5183. };
  5184. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5185. for (var p = 0; p < 6; p++) {
  5186. var inCount = 8;
  5187. for (var i = 0; i < 8; i++) {
  5188. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5189. --inCount;
  5190. } else {
  5191. break;
  5192. }
  5193. }
  5194. if (inCount == 0)
  5195. return false;
  5196. }
  5197. return true;
  5198. };
  5199. return BoundingBox;
  5200. })();
  5201. BABYLON.BoundingBox = BoundingBox;
  5202. })(BABYLON || (BABYLON = {}));
  5203. //# sourceMappingURL=babylon.boundingBox.js.map
  5204. var BABYLON;
  5205. (function (BABYLON) {
  5206. var computeBoxExtents = function (axis, box) {
  5207. var p = BABYLON.Vector3.Dot(box.center, axis);
  5208. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5209. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5210. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5211. var r = r0 + r1 + r2;
  5212. return {
  5213. min: p - r,
  5214. max: p + r
  5215. };
  5216. };
  5217. var extentsOverlap = function (min0, max0, min1, max1) {
  5218. return !(min0 > max1 || min1 > max0);
  5219. };
  5220. var axisOverlap = function (axis, box0, box1) {
  5221. var result0 = computeBoxExtents(axis, box0);
  5222. var result1 = computeBoxExtents(axis, box1);
  5223. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5224. };
  5225. var BoundingInfo = (function () {
  5226. function BoundingInfo(minimum, maximum) {
  5227. this.minimum = minimum;
  5228. this.maximum = maximum;
  5229. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5230. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5231. }
  5232. // Methods
  5233. BoundingInfo.prototype._update = function (world) {
  5234. this.boundingBox._update(world);
  5235. this.boundingSphere._update(world);
  5236. };
  5237. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5238. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5239. return false;
  5240. return this.boundingBox.isInFrustum(frustumPlanes);
  5241. };
  5242. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5243. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5244. };
  5245. BoundingInfo.prototype._checkCollision = function (collider) {
  5246. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5247. };
  5248. BoundingInfo.prototype.intersectsPoint = function (point) {
  5249. if (!this.boundingSphere.centerWorld) {
  5250. return false;
  5251. }
  5252. if (!this.boundingSphere.intersectsPoint(point)) {
  5253. return false;
  5254. }
  5255. if (!this.boundingBox.intersectsPoint(point)) {
  5256. return false;
  5257. }
  5258. return true;
  5259. };
  5260. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5261. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5262. return false;
  5263. }
  5264. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5265. return false;
  5266. }
  5267. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5268. return false;
  5269. }
  5270. if (!precise) {
  5271. return true;
  5272. }
  5273. var box0 = this.boundingBox;
  5274. var box1 = boundingInfo.boundingBox;
  5275. if (!axisOverlap(box0.directions[0], box0, box1))
  5276. return false;
  5277. if (!axisOverlap(box0.directions[1], box0, box1))
  5278. return false;
  5279. if (!axisOverlap(box0.directions[2], box0, box1))
  5280. return false;
  5281. if (!axisOverlap(box1.directions[0], box0, box1))
  5282. return false;
  5283. if (!axisOverlap(box1.directions[1], box0, box1))
  5284. return false;
  5285. if (!axisOverlap(box1.directions[2], box0, box1))
  5286. return false;
  5287. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5288. return false;
  5289. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5290. return false;
  5291. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5292. return false;
  5293. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5294. return false;
  5295. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5296. return false;
  5297. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5298. return false;
  5299. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5300. return false;
  5301. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5302. return false;
  5303. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5304. return false;
  5305. return true;
  5306. };
  5307. return BoundingInfo;
  5308. })();
  5309. BABYLON.BoundingInfo = BoundingInfo;
  5310. })(BABYLON || (BABYLON = {}));
  5311. //# sourceMappingURL=babylon.boundingInfo.js.map
  5312. var BABYLON;
  5313. (function (BABYLON) {
  5314. var Light = (function (_super) {
  5315. __extends(Light, _super);
  5316. function Light(name, scene) {
  5317. _super.call(this, name, scene);
  5318. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5319. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5320. this.intensity = 1.0;
  5321. this.range = Number.MAX_VALUE;
  5322. this.includedOnlyMeshes = new Array();
  5323. this.excludedMeshes = new Array();
  5324. this._excludedMeshesIds = new Array();
  5325. this._includedOnlyMeshesIds = new Array();
  5326. scene.lights.push(this);
  5327. }
  5328. Light.prototype.getShadowGenerator = function () {
  5329. return this._shadowGenerator;
  5330. };
  5331. Light.prototype.getAbsolutePosition = function () {
  5332. return BABYLON.Vector3.Zero();
  5333. };
  5334. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5335. };
  5336. Light.prototype._getWorldMatrix = function () {
  5337. return BABYLON.Matrix.Identity();
  5338. };
  5339. Light.prototype.canAffectMesh = function (mesh) {
  5340. if (!mesh) {
  5341. return true;
  5342. }
  5343. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5344. return false;
  5345. }
  5346. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5347. return false;
  5348. }
  5349. return true;
  5350. };
  5351. Light.prototype.getWorldMatrix = function () {
  5352. this._currentRenderId = this.getScene().getRenderId();
  5353. var worldMatrix = this._getWorldMatrix();
  5354. if (this.parent && this.parent.getWorldMatrix) {
  5355. if (!this._parentedWorldMatrix) {
  5356. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5357. }
  5358. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5359. return this._parentedWorldMatrix;
  5360. }
  5361. return worldMatrix;
  5362. };
  5363. Light.prototype.dispose = function () {
  5364. if (this._shadowGenerator) {
  5365. this._shadowGenerator.dispose();
  5366. this._shadowGenerator = null;
  5367. }
  5368. // Remove from scene
  5369. var index = this.getScene().lights.indexOf(this);
  5370. this.getScene().lights.splice(index, 1);
  5371. };
  5372. return Light;
  5373. })(BABYLON.Node);
  5374. BABYLON.Light = Light;
  5375. })(BABYLON || (BABYLON = {}));
  5376. //# sourceMappingURL=babylon.light.js.map
  5377. var BABYLON;
  5378. (function (BABYLON) {
  5379. var PointLight = (function (_super) {
  5380. __extends(PointLight, _super);
  5381. function PointLight(name, position, scene) {
  5382. _super.call(this, name, scene);
  5383. this.position = position;
  5384. }
  5385. PointLight.prototype.getAbsolutePosition = function () {
  5386. return this._transformedPosition ? this._transformedPosition : this.position;
  5387. };
  5388. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5389. if (this.parent && this.parent.getWorldMatrix) {
  5390. if (!this._transformedPosition) {
  5391. this._transformedPosition = BABYLON.Vector3.Zero();
  5392. }
  5393. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5394. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5395. return;
  5396. }
  5397. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5398. };
  5399. PointLight.prototype.getShadowGenerator = function () {
  5400. return null;
  5401. };
  5402. PointLight.prototype._getWorldMatrix = function () {
  5403. if (!this._worldMatrix) {
  5404. this._worldMatrix = BABYLON.Matrix.Identity();
  5405. }
  5406. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5407. return this._worldMatrix;
  5408. };
  5409. return PointLight;
  5410. })(BABYLON.Light);
  5411. BABYLON.PointLight = PointLight;
  5412. })(BABYLON || (BABYLON = {}));
  5413. //# sourceMappingURL=babylon.pointLight.js.map
  5414. var BABYLON;
  5415. (function (BABYLON) {
  5416. var SpotLight = (function (_super) {
  5417. __extends(SpotLight, _super);
  5418. function SpotLight(name, position, direction, angle, exponent, scene) {
  5419. _super.call(this, name, scene);
  5420. this.position = position;
  5421. this.direction = direction;
  5422. this.angle = angle;
  5423. this.exponent = exponent;
  5424. }
  5425. SpotLight.prototype.getAbsolutePosition = function () {
  5426. return this.transformedPosition ? this.transformedPosition : this.position;
  5427. };
  5428. SpotLight.prototype.setDirectionToTarget = function (target) {
  5429. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5430. return this.direction;
  5431. };
  5432. SpotLight.prototype.computeTransformedPosition = function () {
  5433. if (this.parent && this.parent.getWorldMatrix) {
  5434. if (!this.transformedPosition) {
  5435. this.transformedPosition = BABYLON.Vector3.Zero();
  5436. }
  5437. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5438. return true;
  5439. }
  5440. return false;
  5441. };
  5442. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5443. var normalizeDirection;
  5444. if (this.parent && this.parent.getWorldMatrix) {
  5445. if (!this._transformedDirection) {
  5446. this._transformedDirection = BABYLON.Vector3.Zero();
  5447. }
  5448. this.computeTransformedPosition();
  5449. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5450. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5451. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5452. } else {
  5453. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5454. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5455. }
  5456. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5457. };
  5458. SpotLight.prototype._getWorldMatrix = function () {
  5459. if (!this._worldMatrix) {
  5460. this._worldMatrix = BABYLON.Matrix.Identity();
  5461. }
  5462. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5463. return this._worldMatrix;
  5464. };
  5465. return SpotLight;
  5466. })(BABYLON.Light);
  5467. BABYLON.SpotLight = SpotLight;
  5468. })(BABYLON || (BABYLON = {}));
  5469. //# sourceMappingURL=babylon.spotLight.js.map
  5470. var BABYLON;
  5471. (function (BABYLON) {
  5472. var DirectionalLight = (function (_super) {
  5473. __extends(DirectionalLight, _super);
  5474. function DirectionalLight(name, direction, scene) {
  5475. _super.call(this, name, scene);
  5476. this.direction = direction;
  5477. this.position = direction.scale(-1);
  5478. }
  5479. DirectionalLight.prototype.getAbsolutePosition = function () {
  5480. return this.transformedPosition ? this.transformedPosition : this.position;
  5481. };
  5482. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5483. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5484. return this.direction;
  5485. };
  5486. DirectionalLight.prototype.computeTransformedPosition = function () {
  5487. if (this.parent && this.parent.getWorldMatrix) {
  5488. if (!this.transformedPosition) {
  5489. this.transformedPosition = BABYLON.Vector3.Zero();
  5490. }
  5491. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5492. return true;
  5493. }
  5494. return false;
  5495. };
  5496. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5497. if (this.parent && this.parent.getWorldMatrix) {
  5498. if (!this._transformedDirection) {
  5499. this._transformedDirection = BABYLON.Vector3.Zero();
  5500. }
  5501. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5502. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5503. return;
  5504. }
  5505. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5506. };
  5507. DirectionalLight.prototype._getWorldMatrix = function () {
  5508. if (!this._worldMatrix) {
  5509. this._worldMatrix = BABYLON.Matrix.Identity();
  5510. }
  5511. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5512. return this._worldMatrix;
  5513. };
  5514. return DirectionalLight;
  5515. })(BABYLON.Light);
  5516. BABYLON.DirectionalLight = DirectionalLight;
  5517. })(BABYLON || (BABYLON = {}));
  5518. //# sourceMappingURL=babylon.directionalLight.js.map
  5519. var BABYLON;
  5520. (function (BABYLON) {
  5521. var ShadowGenerator = (function () {
  5522. function ShadowGenerator(mapSize, light) {
  5523. var _this = this;
  5524. // Members
  5525. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5526. this._darkness = 0;
  5527. this._transparencyShadow = false;
  5528. this._viewMatrix = BABYLON.Matrix.Zero();
  5529. this._projectionMatrix = BABYLON.Matrix.Zero();
  5530. this._transformMatrix = BABYLON.Matrix.Zero();
  5531. this._worldViewProjection = BABYLON.Matrix.Zero();
  5532. this._light = light;
  5533. this._scene = light.getScene();
  5534. light._shadowGenerator = this;
  5535. // Render target
  5536. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5537. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5538. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5539. this._shadowMap.renderParticles = false;
  5540. // Custom render function
  5541. var renderSubMesh = function (subMesh) {
  5542. var mesh = subMesh.getRenderingMesh();
  5543. var scene = _this._scene;
  5544. var engine = scene.getEngine();
  5545. // Culling
  5546. engine.setState(subMesh.getMaterial().backFaceCulling);
  5547. // Managing instances
  5548. var batch = mesh._getInstancesRenderList(subMesh._id);
  5549. if (batch.mustReturn) {
  5550. return;
  5551. }
  5552. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5553. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5554. engine.enableEffect(_this._effect);
  5555. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5556. var material = subMesh.getMaterial();
  5557. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5558. // Alpha test
  5559. if (material && material.needAlphaTesting()) {
  5560. var alphaTexture = material.getAlphaTestTexture();
  5561. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5562. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5563. }
  5564. // Bones
  5565. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5566. if (useBones) {
  5567. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5568. }
  5569. if (hardwareInstancedRendering) {
  5570. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5571. } else {
  5572. if (batch.renderSelf[subMesh._id]) {
  5573. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5574. // Draw
  5575. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5576. }
  5577. if (batch.visibleInstances[subMesh._id]) {
  5578. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5579. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5580. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5581. // Draw
  5582. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5583. }
  5584. }
  5585. }
  5586. } else {
  5587. // Need to reset refresh rate of the shadowMap
  5588. _this._shadowMap.resetRefreshCounter();
  5589. }
  5590. };
  5591. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5592. var index;
  5593. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5594. renderSubMesh(opaqueSubMeshes.data[index]);
  5595. }
  5596. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5597. renderSubMesh(alphaTestSubMeshes.data[index]);
  5598. }
  5599. if (_this._transparencyShadow) {
  5600. for (index = 0; index < transparentSubMeshes.length; index++) {
  5601. renderSubMesh(transparentSubMeshes.data[index]);
  5602. }
  5603. }
  5604. };
  5605. }
  5606. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5607. // Static
  5608. get: function () {
  5609. return ShadowGenerator._FILTER_NONE;
  5610. },
  5611. enumerable: true,
  5612. configurable: true
  5613. });
  5614. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5615. get: function () {
  5616. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5617. },
  5618. enumerable: true,
  5619. configurable: true
  5620. });
  5621. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5622. get: function () {
  5623. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5624. },
  5625. enumerable: true,
  5626. configurable: true
  5627. });
  5628. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5629. get: function () {
  5630. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5631. },
  5632. set: function (value) {
  5633. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5634. },
  5635. enumerable: true,
  5636. configurable: true
  5637. });
  5638. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5639. get: function () {
  5640. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5641. },
  5642. set: function (value) {
  5643. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5644. },
  5645. enumerable: true,
  5646. configurable: true
  5647. });
  5648. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5649. var defines = [];
  5650. if (this.useVarianceShadowMap) {
  5651. defines.push("#define VSM");
  5652. }
  5653. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5654. var mesh = subMesh.getMesh();
  5655. var scene = mesh.getScene();
  5656. var material = subMesh.getMaterial();
  5657. // Alpha test
  5658. if (material && material.needAlphaTesting()) {
  5659. defines.push("#define ALPHATEST");
  5660. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5661. attribs.push(BABYLON.VertexBuffer.UVKind);
  5662. defines.push("#define UV1");
  5663. }
  5664. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5665. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5666. defines.push("#define UV2");
  5667. }
  5668. }
  5669. // Bones
  5670. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5671. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5672. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5673. defines.push("#define BONES");
  5674. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5675. }
  5676. // Instances
  5677. if (useInstances) {
  5678. defines.push("#define INSTANCES");
  5679. attribs.push("world0");
  5680. attribs.push("world1");
  5681. attribs.push("world2");
  5682. attribs.push("world3");
  5683. }
  5684. // Get correct effect
  5685. var join = defines.join("\n");
  5686. if (this._cachedDefines !== join) {
  5687. this._cachedDefines = join;
  5688. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5689. }
  5690. return this._effect.isReady();
  5691. };
  5692. ShadowGenerator.prototype.getShadowMap = function () {
  5693. return this._shadowMap;
  5694. };
  5695. ShadowGenerator.prototype.getLight = function () {
  5696. return this._light;
  5697. };
  5698. // Methods
  5699. ShadowGenerator.prototype.getTransformMatrix = function () {
  5700. var lightPosition = this._light.position;
  5701. var lightDirection = this._light.direction;
  5702. if (this._light.computeTransformedPosition()) {
  5703. lightPosition = this._light.transformedPosition;
  5704. }
  5705. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5706. this._cachedPosition = lightPosition.clone();
  5707. this._cachedDirection = lightDirection.clone();
  5708. var activeCamera = this._scene.activeCamera;
  5709. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5710. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5711. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5712. }
  5713. return this._transformMatrix;
  5714. };
  5715. ShadowGenerator.prototype.getDarkness = function () {
  5716. return this._darkness;
  5717. };
  5718. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5719. if (darkness >= 1.0)
  5720. this._darkness = 1.0;
  5721. else if (darkness <= 0.0)
  5722. this._darkness = 0.0;
  5723. else
  5724. this._darkness = darkness;
  5725. };
  5726. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5727. this._transparencyShadow = hasShadow;
  5728. };
  5729. ShadowGenerator.prototype.dispose = function () {
  5730. this._shadowMap.dispose();
  5731. };
  5732. ShadowGenerator._FILTER_NONE = 0;
  5733. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5734. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5735. return ShadowGenerator;
  5736. })();
  5737. BABYLON.ShadowGenerator = ShadowGenerator;
  5738. })(BABYLON || (BABYLON = {}));
  5739. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5740. var BABYLON;
  5741. (function (BABYLON) {
  5742. var HemisphericLight = (function (_super) {
  5743. __extends(HemisphericLight, _super);
  5744. function HemisphericLight(name, direction, scene) {
  5745. _super.call(this, name, scene);
  5746. this.direction = direction;
  5747. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5748. }
  5749. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5750. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5751. return this.direction;
  5752. };
  5753. HemisphericLight.prototype.getShadowGenerator = function () {
  5754. return null;
  5755. };
  5756. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5757. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5758. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5759. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5760. };
  5761. HemisphericLight.prototype._getWorldMatrix = function () {
  5762. if (!this._worldMatrix) {
  5763. this._worldMatrix = BABYLON.Matrix.Identity();
  5764. }
  5765. return this._worldMatrix;
  5766. };
  5767. return HemisphericLight;
  5768. })(BABYLON.Light);
  5769. BABYLON.HemisphericLight = HemisphericLight;
  5770. })(BABYLON || (BABYLON = {}));
  5771. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5772. var BABYLON;
  5773. (function (BABYLON) {
  5774. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5775. if (boxMin.x > sphereCenter.x + sphereRadius)
  5776. return false;
  5777. if (sphereCenter.x - sphereRadius > boxMax.x)
  5778. return false;
  5779. if (boxMin.y > sphereCenter.y + sphereRadius)
  5780. return false;
  5781. if (sphereCenter.y - sphereRadius > boxMax.y)
  5782. return false;
  5783. if (boxMin.z > sphereCenter.z + sphereRadius)
  5784. return false;
  5785. if (sphereCenter.z - sphereRadius > boxMax.z)
  5786. return false;
  5787. return true;
  5788. };
  5789. var getLowestRoot = function (a, b, c, maxR) {
  5790. var determinant = b * b - 4.0 * a * c;
  5791. var result = { root: 0, found: false };
  5792. if (determinant < 0)
  5793. return result;
  5794. var sqrtD = Math.sqrt(determinant);
  5795. var r1 = (-b - sqrtD) / (2.0 * a);
  5796. var r2 = (-b + sqrtD) / (2.0 * a);
  5797. if (r1 > r2) {
  5798. var temp = r2;
  5799. r2 = r1;
  5800. r1 = temp;
  5801. }
  5802. if (r1 > 0 && r1 < maxR) {
  5803. result.root = r1;
  5804. result.found = true;
  5805. return result;
  5806. }
  5807. if (r2 > 0 && r2 < maxR) {
  5808. result.root = r2;
  5809. result.found = true;
  5810. return result;
  5811. }
  5812. return result;
  5813. };
  5814. var Collider = (function () {
  5815. function Collider() {
  5816. this.radius = new BABYLON.Vector3(1, 1, 1);
  5817. this.retry = 0;
  5818. this.basePointWorld = BABYLON.Vector3.Zero();
  5819. this.velocityWorld = BABYLON.Vector3.Zero();
  5820. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5821. this._collisionPoint = BABYLON.Vector3.Zero();
  5822. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5823. this._tempVector = BABYLON.Vector3.Zero();
  5824. this._tempVector2 = BABYLON.Vector3.Zero();
  5825. this._tempVector3 = BABYLON.Vector3.Zero();
  5826. this._tempVector4 = BABYLON.Vector3.Zero();
  5827. this._edge = BABYLON.Vector3.Zero();
  5828. this._baseToVertex = BABYLON.Vector3.Zero();
  5829. this._destinationPoint = BABYLON.Vector3.Zero();
  5830. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5831. this._displacementVector = BABYLON.Vector3.Zero();
  5832. }
  5833. // Methods
  5834. Collider.prototype._initialize = function (source, dir, e) {
  5835. this.velocity = dir;
  5836. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5837. this.basePoint = source;
  5838. source.multiplyToRef(this.radius, this.basePointWorld);
  5839. dir.multiplyToRef(this.radius, this.velocityWorld);
  5840. this.velocityWorldLength = this.velocityWorld.length();
  5841. this.epsilon = e;
  5842. this.collisionFound = false;
  5843. };
  5844. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5845. pa.subtractToRef(point, this._tempVector);
  5846. pb.subtractToRef(point, this._tempVector2);
  5847. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5848. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5849. if (d < 0)
  5850. return false;
  5851. pc.subtractToRef(point, this._tempVector3);
  5852. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5853. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5854. if (d < 0)
  5855. return false;
  5856. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5857. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5858. return d >= 0;
  5859. };
  5860. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5861. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5862. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5863. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5864. return false;
  5865. }
  5866. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5867. return false;
  5868. return true;
  5869. };
  5870. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5871. var t0;
  5872. var embeddedInPlane = false;
  5873. if (!subMesh._trianglePlanes) {
  5874. subMesh._trianglePlanes = [];
  5875. }
  5876. if (!subMesh._trianglePlanes[faceIndex]) {
  5877. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5878. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5879. }
  5880. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5881. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5882. return;
  5883. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5884. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5885. if (normalDotVelocity == 0) {
  5886. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5887. return;
  5888. embeddedInPlane = true;
  5889. t0 = 0;
  5890. } else {
  5891. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5892. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5893. if (t0 > t1) {
  5894. var temp = t1;
  5895. t1 = t0;
  5896. t0 = temp;
  5897. }
  5898. if (t0 > 1.0 || t1 < 0.0)
  5899. return;
  5900. if (t0 < 0)
  5901. t0 = 0;
  5902. if (t0 > 1.0)
  5903. t0 = 1.0;
  5904. }
  5905. this._collisionPoint.copyFromFloats(0, 0, 0);
  5906. var found = false;
  5907. var t = 1.0;
  5908. if (!embeddedInPlane) {
  5909. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5910. this.velocity.scaleToRef(t0, this._tempVector);
  5911. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5912. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5913. found = true;
  5914. t = t0;
  5915. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5916. }
  5917. }
  5918. if (!found) {
  5919. var velocitySquaredLength = this.velocity.lengthSquared();
  5920. var a = velocitySquaredLength;
  5921. this.basePoint.subtractToRef(p1, this._tempVector);
  5922. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5923. var c = this._tempVector.lengthSquared() - 1.0;
  5924. var lowestRoot = getLowestRoot(a, b, c, t);
  5925. if (lowestRoot.found) {
  5926. t = lowestRoot.root;
  5927. found = true;
  5928. this._collisionPoint.copyFrom(p1);
  5929. }
  5930. this.basePoint.subtractToRef(p2, this._tempVector);
  5931. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5932. c = this._tempVector.lengthSquared() - 1.0;
  5933. lowestRoot = getLowestRoot(a, b, c, t);
  5934. if (lowestRoot.found) {
  5935. t = lowestRoot.root;
  5936. found = true;
  5937. this._collisionPoint.copyFrom(p2);
  5938. }
  5939. this.basePoint.subtractToRef(p3, this._tempVector);
  5940. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5941. c = this._tempVector.lengthSquared() - 1.0;
  5942. lowestRoot = getLowestRoot(a, b, c, t);
  5943. if (lowestRoot.found) {
  5944. t = lowestRoot.root;
  5945. found = true;
  5946. this._collisionPoint.copyFrom(p3);
  5947. }
  5948. p2.subtractToRef(p1, this._edge);
  5949. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5950. var edgeSquaredLength = this._edge.lengthSquared();
  5951. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5952. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5953. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5954. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5955. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5956. lowestRoot = getLowestRoot(a, b, c, t);
  5957. if (lowestRoot.found) {
  5958. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5959. if (f >= 0.0 && f <= 1.0) {
  5960. t = lowestRoot.root;
  5961. found = true;
  5962. this._edge.scaleInPlace(f);
  5963. p1.addToRef(this._edge, this._collisionPoint);
  5964. }
  5965. }
  5966. p3.subtractToRef(p2, this._edge);
  5967. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5968. edgeSquaredLength = this._edge.lengthSquared();
  5969. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5970. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5971. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5972. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5973. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5974. lowestRoot = getLowestRoot(a, b, c, t);
  5975. if (lowestRoot.found) {
  5976. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5977. if (f >= 0.0 && f <= 1.0) {
  5978. t = lowestRoot.root;
  5979. found = true;
  5980. this._edge.scaleInPlace(f);
  5981. p2.addToRef(this._edge, this._collisionPoint);
  5982. }
  5983. }
  5984. p1.subtractToRef(p3, this._edge);
  5985. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5986. edgeSquaredLength = this._edge.lengthSquared();
  5987. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5988. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5989. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5990. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5991. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5992. lowestRoot = getLowestRoot(a, b, c, t);
  5993. if (lowestRoot.found) {
  5994. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5995. if (f >= 0.0 && f <= 1.0) {
  5996. t = lowestRoot.root;
  5997. found = true;
  5998. this._edge.scaleInPlace(f);
  5999. p3.addToRef(this._edge, this._collisionPoint);
  6000. }
  6001. }
  6002. }
  6003. if (found) {
  6004. var distToCollision = t * this.velocity.length();
  6005. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6006. if (!this.intersectionPoint) {
  6007. this.intersectionPoint = this._collisionPoint.clone();
  6008. } else {
  6009. this.intersectionPoint.copyFrom(this._collisionPoint);
  6010. }
  6011. this.nearestDistance = distToCollision;
  6012. this.collisionFound = true;
  6013. this.collidedMesh = subMesh.getMesh();
  6014. }
  6015. }
  6016. };
  6017. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6018. for (var i = indexStart; i < indexEnd; i += 3) {
  6019. var p1 = pts[indices[i] - decal];
  6020. var p2 = pts[indices[i + 1] - decal];
  6021. var p3 = pts[indices[i + 2] - decal];
  6022. this._testTriangle(i, subMesh, p3, p2, p1);
  6023. }
  6024. };
  6025. Collider.prototype._getResponse = function (pos, vel) {
  6026. pos.addToRef(vel, this._destinationPoint);
  6027. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6028. this.basePoint.addToRef(vel, pos);
  6029. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6030. this._slidePlaneNormal.normalize();
  6031. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6032. pos.addInPlace(this._displacementVector);
  6033. this.intersectionPoint.addInPlace(this._displacementVector);
  6034. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6035. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6036. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6037. };
  6038. return Collider;
  6039. })();
  6040. BABYLON.Collider = Collider;
  6041. })(BABYLON || (BABYLON = {}));
  6042. //# sourceMappingURL=babylon.collider.js.map
  6043. var BABYLON;
  6044. (function (BABYLON) {
  6045. var Camera = (function (_super) {
  6046. __extends(Camera, _super);
  6047. function Camera(name, position, scene) {
  6048. _super.call(this, name, scene);
  6049. this.position = position;
  6050. // Members
  6051. this.upVector = BABYLON.Vector3.Up();
  6052. this.orthoLeft = null;
  6053. this.orthoRight = null;
  6054. this.orthoBottom = null;
  6055. this.orthoTop = null;
  6056. this.fov = 0.8;
  6057. this.minZ = 1.0;
  6058. this.maxZ = 10000.0;
  6059. this.inertia = 0.9;
  6060. this.mode = Camera.PERSPECTIVE_CAMERA;
  6061. this.isIntermediate = false;
  6062. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6063. this.subCameras = [];
  6064. this.layerMask = 0xFFFFFFFF;
  6065. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6066. this._projectionMatrix = new BABYLON.Matrix();
  6067. this._postProcesses = new Array();
  6068. this._postProcessesTakenIndices = [];
  6069. scene.cameras.push(this);
  6070. if (!scene.activeCamera) {
  6071. scene.activeCamera = this;
  6072. }
  6073. }
  6074. //Cache
  6075. Camera.prototype._initCache = function () {
  6076. _super.prototype._initCache.call(this);
  6077. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6078. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6079. this._cache.mode = undefined;
  6080. this._cache.minZ = undefined;
  6081. this._cache.maxZ = undefined;
  6082. this._cache.fov = undefined;
  6083. this._cache.aspectRatio = undefined;
  6084. this._cache.orthoLeft = undefined;
  6085. this._cache.orthoRight = undefined;
  6086. this._cache.orthoBottom = undefined;
  6087. this._cache.orthoTop = undefined;
  6088. this._cache.renderWidth = undefined;
  6089. this._cache.renderHeight = undefined;
  6090. };
  6091. Camera.prototype._updateCache = function (ignoreParentClass) {
  6092. if (!ignoreParentClass) {
  6093. _super.prototype._updateCache.call(this);
  6094. }
  6095. var engine = this.getEngine();
  6096. this._cache.position.copyFrom(this.position);
  6097. this._cache.upVector.copyFrom(this.upVector);
  6098. this._cache.mode = this.mode;
  6099. this._cache.minZ = this.minZ;
  6100. this._cache.maxZ = this.maxZ;
  6101. this._cache.fov = this.fov;
  6102. this._cache.aspectRatio = engine.getAspectRatio(this);
  6103. this._cache.orthoLeft = this.orthoLeft;
  6104. this._cache.orthoRight = this.orthoRight;
  6105. this._cache.orthoBottom = this.orthoBottom;
  6106. this._cache.orthoTop = this.orthoTop;
  6107. this._cache.renderWidth = engine.getRenderWidth();
  6108. this._cache.renderHeight = engine.getRenderHeight();
  6109. };
  6110. Camera.prototype._updateFromScene = function () {
  6111. this.updateCache();
  6112. this._update();
  6113. };
  6114. // Synchronized
  6115. Camera.prototype._isSynchronized = function () {
  6116. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6117. };
  6118. Camera.prototype._isSynchronizedViewMatrix = function () {
  6119. if (!_super.prototype._isSynchronized.call(this))
  6120. return false;
  6121. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6122. };
  6123. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6124. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6125. if (!check) {
  6126. return false;
  6127. }
  6128. var engine = this.getEngine();
  6129. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6130. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6131. } else {
  6132. 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();
  6133. }
  6134. return check;
  6135. };
  6136. // Controls
  6137. Camera.prototype.attachControl = function (element) {
  6138. };
  6139. Camera.prototype.detachControl = function (element) {
  6140. };
  6141. Camera.prototype._update = function () {
  6142. };
  6143. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6144. if (typeof insertAt === "undefined") { insertAt = null; }
  6145. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6146. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6147. return 0;
  6148. }
  6149. if (insertAt == null || insertAt < 0) {
  6150. this._postProcesses.push(postProcess);
  6151. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6152. return this._postProcesses.length - 1;
  6153. }
  6154. var add = 0;
  6155. if (this._postProcesses[insertAt]) {
  6156. var start = this._postProcesses.length - 1;
  6157. for (var i = start; i >= insertAt + 1; --i) {
  6158. this._postProcesses[i + 1] = this._postProcesses[i];
  6159. }
  6160. add = 1;
  6161. }
  6162. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6163. if (this._postProcessesTakenIndices[i] < insertAt) {
  6164. continue;
  6165. }
  6166. start = this._postProcessesTakenIndices.length - 1;
  6167. for (var j = start; j >= i; --j) {
  6168. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6169. }
  6170. this._postProcessesTakenIndices[i] = insertAt;
  6171. break;
  6172. }
  6173. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6174. this._postProcessesTakenIndices.push(insertAt);
  6175. }
  6176. var result = insertAt + add;
  6177. this._postProcesses[result] = postProcess;
  6178. return result;
  6179. };
  6180. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6181. if (typeof atIndices === "undefined") { atIndices = null; }
  6182. var result = [];
  6183. if (!atIndices) {
  6184. var length = this._postProcesses.length;
  6185. for (var i = 0; i < length; i++) {
  6186. if (this._postProcesses[i] !== postProcess) {
  6187. continue;
  6188. }
  6189. delete this._postProcesses[i];
  6190. var index = this._postProcessesTakenIndices.indexOf(i);
  6191. this._postProcessesTakenIndices.splice(index, 1);
  6192. }
  6193. } else {
  6194. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6195. for (i = 0; i < atIndices.length; i++) {
  6196. var foundPostProcess = this._postProcesses[atIndices[i]];
  6197. if (foundPostProcess !== postProcess) {
  6198. result.push(i);
  6199. continue;
  6200. }
  6201. delete this._postProcesses[atIndices[i]];
  6202. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6203. this._postProcessesTakenIndices.splice(index, 1);
  6204. }
  6205. }
  6206. return result;
  6207. };
  6208. Camera.prototype.getWorldMatrix = function () {
  6209. if (!this._worldMatrix) {
  6210. this._worldMatrix = BABYLON.Matrix.Identity();
  6211. }
  6212. var viewMatrix = this.getViewMatrix();
  6213. viewMatrix.invertToRef(this._worldMatrix);
  6214. return this._worldMatrix;
  6215. };
  6216. Camera.prototype._getViewMatrix = function () {
  6217. return BABYLON.Matrix.Identity();
  6218. };
  6219. Camera.prototype.getViewMatrix = function () {
  6220. this._computedViewMatrix = this._computeViewMatrix();
  6221. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6222. return this._computedViewMatrix;
  6223. }
  6224. if (!this._worldMatrix) {
  6225. this._worldMatrix = BABYLON.Matrix.Identity();
  6226. }
  6227. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6228. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6229. this._computedViewMatrix.invert();
  6230. this._currentRenderId = this.getScene().getRenderId();
  6231. return this._computedViewMatrix;
  6232. };
  6233. Camera.prototype._computeViewMatrix = function (force) {
  6234. if (!force && this._isSynchronizedViewMatrix()) {
  6235. return this._computedViewMatrix;
  6236. }
  6237. this._computedViewMatrix = this._getViewMatrix();
  6238. if (!this.parent || !this.parent.getWorldMatrix) {
  6239. this._currentRenderId = this.getScene().getRenderId();
  6240. }
  6241. return this._computedViewMatrix;
  6242. };
  6243. Camera.prototype.getProjectionMatrix = function (force) {
  6244. if (!force && this._isSynchronizedProjectionMatrix()) {
  6245. return this._projectionMatrix;
  6246. }
  6247. var engine = this.getEngine();
  6248. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6249. if (this.minZ <= 0) {
  6250. this.minZ = 0.1;
  6251. }
  6252. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6253. return this._projectionMatrix;
  6254. }
  6255. var halfWidth = engine.getRenderWidth() / 2.0;
  6256. var halfHeight = engine.getRenderHeight() / 2.0;
  6257. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6258. return this._projectionMatrix;
  6259. };
  6260. Camera.prototype.dispose = function () {
  6261. // Remove from scene
  6262. var index = this.getScene().cameras.indexOf(this);
  6263. this.getScene().cameras.splice(index, 1);
  6264. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6265. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6266. }
  6267. };
  6268. Camera.PERSPECTIVE_CAMERA = 0;
  6269. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6270. return Camera;
  6271. })(BABYLON.Node);
  6272. BABYLON.Camera = Camera;
  6273. })(BABYLON || (BABYLON = {}));
  6274. //# sourceMappingURL=babylon.camera.js.map
  6275. var BABYLON;
  6276. (function (BABYLON) {
  6277. var TargetCamera = (function (_super) {
  6278. __extends(TargetCamera, _super);
  6279. function TargetCamera(name, position, scene) {
  6280. _super.call(this, name, position, scene);
  6281. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6282. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6283. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6284. this.speed = 2.0;
  6285. this.noRotationConstraint = false;
  6286. this.lockedTarget = null;
  6287. this._currentTarget = BABYLON.Vector3.Zero();
  6288. this._viewMatrix = BABYLON.Matrix.Zero();
  6289. this._camMatrix = BABYLON.Matrix.Zero();
  6290. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6291. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6292. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6293. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6294. this._lookAtTemp = BABYLON.Matrix.Zero();
  6295. this._tempMatrix = BABYLON.Matrix.Zero();
  6296. }
  6297. TargetCamera.prototype._getLockedTargetPosition = function () {
  6298. if (!this.lockedTarget) {
  6299. return null;
  6300. }
  6301. return this.lockedTarget.position || this.lockedTarget;
  6302. };
  6303. // Cache
  6304. TargetCamera.prototype._initCache = function () {
  6305. _super.prototype._initCache.call(this);
  6306. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6307. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6308. };
  6309. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6310. if (!ignoreParentClass) {
  6311. _super.prototype._updateCache.call(this);
  6312. }
  6313. var lockedTargetPosition = this._getLockedTargetPosition();
  6314. if (!lockedTargetPosition) {
  6315. this._cache.lockedTarget = null;
  6316. } else {
  6317. if (!this._cache.lockedTarget) {
  6318. this._cache.lockedTarget = lockedTargetPosition.clone();
  6319. } else {
  6320. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6321. }
  6322. }
  6323. this._cache.rotation.copyFrom(this.rotation);
  6324. };
  6325. // Synchronized
  6326. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6327. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6328. return false;
  6329. }
  6330. var lockedTargetPosition = this._getLockedTargetPosition();
  6331. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6332. };
  6333. // Methods
  6334. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6335. var engine = this.getEngine();
  6336. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6337. };
  6338. // Target
  6339. TargetCamera.prototype.setTarget = function (target) {
  6340. this.upVector.normalize();
  6341. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6342. this._camMatrix.invert();
  6343. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6344. var vDir = target.subtract(this.position);
  6345. if (vDir.x >= 0.0) {
  6346. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6347. } else {
  6348. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6349. }
  6350. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6351. if (isNaN(this.rotation.x)) {
  6352. this.rotation.x = 0;
  6353. }
  6354. if (isNaN(this.rotation.y)) {
  6355. this.rotation.y = 0;
  6356. }
  6357. if (isNaN(this.rotation.z)) {
  6358. this.rotation.z = 0;
  6359. }
  6360. };
  6361. TargetCamera.prototype.getTarget = function () {
  6362. return this._currentTarget;
  6363. };
  6364. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6365. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6366. };
  6367. TargetCamera.prototype._updatePosition = function () {
  6368. this.position.addInPlace(this.cameraDirection);
  6369. };
  6370. TargetCamera.prototype._update = function () {
  6371. var needToMove = this._decideIfNeedsToMove();
  6372. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6373. // Move
  6374. if (needToMove) {
  6375. this._updatePosition();
  6376. }
  6377. // Rotate
  6378. if (needToRotate) {
  6379. this.rotation.x += this.cameraRotation.x;
  6380. this.rotation.y += this.cameraRotation.y;
  6381. if (!this.noRotationConstraint) {
  6382. var limit = (Math.PI / 2) * 0.95;
  6383. if (this.rotation.x > limit)
  6384. this.rotation.x = limit;
  6385. if (this.rotation.x < -limit)
  6386. this.rotation.x = -limit;
  6387. }
  6388. }
  6389. // Inertia
  6390. if (needToMove) {
  6391. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6392. this.cameraDirection.x = 0;
  6393. }
  6394. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6395. this.cameraDirection.y = 0;
  6396. }
  6397. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6398. this.cameraDirection.z = 0;
  6399. }
  6400. this.cameraDirection.scaleInPlace(this.inertia);
  6401. }
  6402. if (needToRotate) {
  6403. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6404. this.cameraRotation.x = 0;
  6405. }
  6406. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6407. this.cameraRotation.y = 0;
  6408. }
  6409. this.cameraRotation.scaleInPlace(this.inertia);
  6410. }
  6411. };
  6412. TargetCamera.prototype._getViewMatrix = function () {
  6413. if (!this.lockedTarget) {
  6414. // Compute
  6415. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6416. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6417. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6418. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6419. this._lookAtTemp.invert();
  6420. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6421. } else {
  6422. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6423. }
  6424. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6425. // Computing target and final matrix
  6426. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6427. } else {
  6428. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6429. }
  6430. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6431. return this._viewMatrix;
  6432. };
  6433. return TargetCamera;
  6434. })(BABYLON.Camera);
  6435. BABYLON.TargetCamera = TargetCamera;
  6436. })(BABYLON || (BABYLON = {}));
  6437. //# sourceMappingURL=babylon.targetCamera.js.map
  6438. var BABYLON;
  6439. (function (BABYLON) {
  6440. var FollowCamera = (function (_super) {
  6441. __extends(FollowCamera, _super);
  6442. function FollowCamera(name, position, scene) {
  6443. _super.call(this, name, position, scene);
  6444. this.radius = 12;
  6445. this.rotationOffset = 0;
  6446. this.heightOffset = 4;
  6447. this.cameraAcceleration = 0.05;
  6448. this.maxCameraSpeed = 20;
  6449. }
  6450. FollowCamera.prototype.getRadians = function (degrees) {
  6451. return degrees * Math.PI / 180;
  6452. };
  6453. FollowCamera.prototype.follow = function (cameraTarget) {
  6454. if (!cameraTarget)
  6455. return;
  6456. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6457. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6458. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6459. var dx = targetX - this.position.x;
  6460. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6461. var dz = (targetZ) - this.position.z;
  6462. var vx = dx * this.cameraAcceleration * 2;
  6463. var vy = dy * this.cameraAcceleration;
  6464. var vz = dz * this.cameraAcceleration * 2;
  6465. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6466. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6467. }
  6468. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6469. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6470. }
  6471. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6472. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6473. }
  6474. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6475. this.setTarget(cameraTarget.position);
  6476. };
  6477. FollowCamera.prototype._update = function () {
  6478. _super.prototype._update.call(this);
  6479. this.follow(this.target);
  6480. };
  6481. return FollowCamera;
  6482. })(BABYLON.TargetCamera);
  6483. BABYLON.FollowCamera = FollowCamera;
  6484. })(BABYLON || (BABYLON = {}));
  6485. //# sourceMappingURL=babylon.followCamera.js.map
  6486. var BABYLON;
  6487. (function (BABYLON) {
  6488. var FreeCamera = (function (_super) {
  6489. __extends(FreeCamera, _super);
  6490. function FreeCamera(name, position, scene) {
  6491. _super.call(this, name, position, scene);
  6492. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6493. this.keysUp = [38];
  6494. this.keysDown = [40];
  6495. this.keysLeft = [37];
  6496. this.keysRight = [39];
  6497. this.checkCollisions = false;
  6498. this.applyGravity = false;
  6499. this.angularSensibility = 2000.0;
  6500. this._keys = [];
  6501. this._collider = new BABYLON.Collider();
  6502. this._needMoveForGravity = true;
  6503. this._oldPosition = BABYLON.Vector3.Zero();
  6504. this._diffPosition = BABYLON.Vector3.Zero();
  6505. this._newPosition = BABYLON.Vector3.Zero();
  6506. }
  6507. // Controls
  6508. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6509. var _this = this;
  6510. var previousPosition;
  6511. var engine = this.getEngine();
  6512. if (this._attachedElement) {
  6513. return;
  6514. }
  6515. this._attachedElement = element;
  6516. if (this._onMouseDown === undefined) {
  6517. this._onMouseDown = function (evt) {
  6518. previousPosition = {
  6519. x: evt.clientX,
  6520. y: evt.clientY
  6521. };
  6522. if (!noPreventDefault) {
  6523. evt.preventDefault();
  6524. }
  6525. };
  6526. this._onMouseUp = function (evt) {
  6527. previousPosition = null;
  6528. if (!noPreventDefault) {
  6529. evt.preventDefault();
  6530. }
  6531. };
  6532. this._onMouseOut = function (evt) {
  6533. previousPosition = null;
  6534. _this._keys = [];
  6535. if (!noPreventDefault) {
  6536. evt.preventDefault();
  6537. }
  6538. };
  6539. this._onMouseMove = function (evt) {
  6540. if (!previousPosition && !engine.isPointerLock) {
  6541. return;
  6542. }
  6543. var offsetX;
  6544. var offsetY;
  6545. if (!engine.isPointerLock) {
  6546. offsetX = evt.clientX - previousPosition.x;
  6547. offsetY = evt.clientY - previousPosition.y;
  6548. } else {
  6549. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6550. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6551. }
  6552. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6553. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6554. previousPosition = {
  6555. x: evt.clientX,
  6556. y: evt.clientY
  6557. };
  6558. if (!noPreventDefault) {
  6559. evt.preventDefault();
  6560. }
  6561. };
  6562. this._onKeyDown = function (evt) {
  6563. 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) {
  6564. var index = _this._keys.indexOf(evt.keyCode);
  6565. if (index === -1) {
  6566. _this._keys.push(evt.keyCode);
  6567. }
  6568. if (!noPreventDefault) {
  6569. evt.preventDefault();
  6570. }
  6571. }
  6572. };
  6573. this._onKeyUp = function (evt) {
  6574. 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) {
  6575. var index = _this._keys.indexOf(evt.keyCode);
  6576. if (index >= 0) {
  6577. _this._keys.splice(index, 1);
  6578. }
  6579. if (!noPreventDefault) {
  6580. evt.preventDefault();
  6581. }
  6582. }
  6583. };
  6584. this._onLostFocus = function () {
  6585. _this._keys = [];
  6586. };
  6587. this._reset = function () {
  6588. _this._keys = [];
  6589. previousPosition = null;
  6590. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6591. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6592. };
  6593. }
  6594. element.addEventListener("mousedown", this._onMouseDown, false);
  6595. element.addEventListener("mouseup", this._onMouseUp, false);
  6596. element.addEventListener("mouseout", this._onMouseOut, false);
  6597. element.addEventListener("mousemove", this._onMouseMove, false);
  6598. BABYLON.Tools.RegisterTopRootEvents([
  6599. { name: "keydown", handler: this._onKeyDown },
  6600. { name: "keyup", handler: this._onKeyUp },
  6601. { name: "blur", handler: this._onLostFocus }
  6602. ]);
  6603. };
  6604. FreeCamera.prototype.detachControl = function (element) {
  6605. if (this._attachedElement != element) {
  6606. return;
  6607. }
  6608. element.removeEventListener("mousedown", this._onMouseDown);
  6609. element.removeEventListener("mouseup", this._onMouseUp);
  6610. element.removeEventListener("mouseout", this._onMouseOut);
  6611. element.removeEventListener("mousemove", this._onMouseMove);
  6612. BABYLON.Tools.UnregisterTopRootEvents([
  6613. { name: "keydown", handler: this._onKeyDown },
  6614. { name: "keyup", handler: this._onKeyUp },
  6615. { name: "blur", handler: this._onLostFocus }
  6616. ]);
  6617. this._attachedElement = null;
  6618. if (this._reset) {
  6619. this._reset();
  6620. }
  6621. };
  6622. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6623. var globalPosition;
  6624. if (this.parent) {
  6625. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6626. } else {
  6627. globalPosition = this.position;
  6628. }
  6629. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6630. this._collider.radius = this.ellipsoid;
  6631. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6632. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6633. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6634. this.position.addInPlace(this._diffPosition);
  6635. if (this.onCollide) {
  6636. this.onCollide(this._collider.collidedMesh);
  6637. }
  6638. }
  6639. };
  6640. FreeCamera.prototype._checkInputs = function () {
  6641. if (!this._localDirection) {
  6642. this._localDirection = BABYLON.Vector3.Zero();
  6643. this._transformedDirection = BABYLON.Vector3.Zero();
  6644. }
  6645. for (var index = 0; index < this._keys.length; index++) {
  6646. var keyCode = this._keys[index];
  6647. var speed = this._computeLocalCameraSpeed();
  6648. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6649. this._localDirection.copyFromFloats(-speed, 0, 0);
  6650. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6651. this._localDirection.copyFromFloats(0, 0, speed);
  6652. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6653. this._localDirection.copyFromFloats(speed, 0, 0);
  6654. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6655. this._localDirection.copyFromFloats(0, 0, -speed);
  6656. }
  6657. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6658. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6659. this.cameraDirection.addInPlace(this._transformedDirection);
  6660. }
  6661. };
  6662. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6663. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6664. };
  6665. FreeCamera.prototype._updatePosition = function () {
  6666. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6667. this._collideWithWorld(this.cameraDirection);
  6668. if (this.applyGravity) {
  6669. var oldPosition = this.position;
  6670. this._collideWithWorld(this.getScene().gravity);
  6671. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6672. }
  6673. } else {
  6674. this.position.addInPlace(this.cameraDirection);
  6675. }
  6676. };
  6677. FreeCamera.prototype._update = function () {
  6678. this._checkInputs();
  6679. _super.prototype._update.call(this);
  6680. };
  6681. return FreeCamera;
  6682. })(BABYLON.TargetCamera);
  6683. BABYLON.FreeCamera = FreeCamera;
  6684. })(BABYLON || (BABYLON = {}));
  6685. //# sourceMappingURL=babylon.freeCamera.js.map
  6686. var BABYLON;
  6687. (function (BABYLON) {
  6688. // We're mainly based on the logic defined into the FreeCamera code
  6689. var TouchCamera = (function (_super) {
  6690. __extends(TouchCamera, _super);
  6691. function TouchCamera(name, position, scene) {
  6692. _super.call(this, name, position, scene);
  6693. this._offsetX = null;
  6694. this._offsetY = null;
  6695. this._pointerCount = 0;
  6696. this._pointerPressed = [];
  6697. this.angularSensibility = 200000.0;
  6698. this.moveSensibility = 500.0;
  6699. }
  6700. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6701. var _this = this;
  6702. var previousPosition;
  6703. if (this._attachedCanvas) {
  6704. return;
  6705. }
  6706. this._attachedCanvas = canvas;
  6707. if (this._onPointerDown === undefined) {
  6708. this._onPointerDown = function (evt) {
  6709. if (!noPreventDefault) {
  6710. evt.preventDefault();
  6711. }
  6712. _this._pointerPressed.push(evt.pointerId);
  6713. if (_this._pointerPressed.length !== 1) {
  6714. return;
  6715. }
  6716. previousPosition = {
  6717. x: evt.clientX,
  6718. y: evt.clientY
  6719. };
  6720. };
  6721. this._onPointerUp = function (evt) {
  6722. if (!noPreventDefault) {
  6723. evt.preventDefault();
  6724. }
  6725. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6726. if (index === -1) {
  6727. return;
  6728. }
  6729. _this._pointerPressed.splice(index, 1);
  6730. if (index != 0) {
  6731. return;
  6732. }
  6733. previousPosition = null;
  6734. _this._offsetX = null;
  6735. _this._offsetY = null;
  6736. };
  6737. this._onPointerMove = function (evt) {
  6738. if (!noPreventDefault) {
  6739. evt.preventDefault();
  6740. }
  6741. if (!previousPosition) {
  6742. return;
  6743. }
  6744. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6745. if (index != 0) {
  6746. return;
  6747. }
  6748. _this._offsetX = evt.clientX - previousPosition.x;
  6749. _this._offsetY = -(evt.clientY - previousPosition.y);
  6750. };
  6751. this._onLostFocus = function () {
  6752. _this._offsetX = null;
  6753. _this._offsetY = null;
  6754. };
  6755. }
  6756. canvas.addEventListener("pointerdown", this._onPointerDown);
  6757. canvas.addEventListener("pointerup", this._onPointerUp);
  6758. canvas.addEventListener("pointerout", this._onPointerUp);
  6759. canvas.addEventListener("pointermove", this._onPointerMove);
  6760. BABYLON.Tools.RegisterTopRootEvents([
  6761. { name: "blur", handler: this._onLostFocus }
  6762. ]);
  6763. };
  6764. TouchCamera.prototype.detachControl = function (canvas) {
  6765. if (this._attachedCanvas != canvas) {
  6766. return;
  6767. }
  6768. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6769. canvas.removeEventListener("pointerup", this._onPointerUp);
  6770. canvas.removeEventListener("pointerout", this._onPointerUp);
  6771. canvas.removeEventListener("pointermove", this._onPointerMove);
  6772. BABYLON.Tools.UnregisterTopRootEvents([
  6773. { name: "blur", handler: this._onLostFocus }
  6774. ]);
  6775. this._attachedCanvas = null;
  6776. };
  6777. TouchCamera.prototype._checkInputs = function () {
  6778. if (!this._offsetX) {
  6779. return;
  6780. }
  6781. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6782. if (this._pointerPressed.length > 1) {
  6783. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6784. } else {
  6785. var speed = this._computeLocalCameraSpeed();
  6786. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6787. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6788. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6789. }
  6790. };
  6791. return TouchCamera;
  6792. })(BABYLON.FreeCamera);
  6793. BABYLON.TouchCamera = TouchCamera;
  6794. })(BABYLON || (BABYLON = {}));
  6795. //# sourceMappingURL=babylon.touchCamera.js.map
  6796. var BABYLON;
  6797. (function (BABYLON) {
  6798. // We're mainly based on the logic defined into the FreeCamera code
  6799. var DeviceOrientationCamera = (function (_super) {
  6800. __extends(DeviceOrientationCamera, _super);
  6801. function DeviceOrientationCamera(name, position, scene) {
  6802. var _this = this;
  6803. _super.call(this, name, position, scene);
  6804. this._offsetX = null;
  6805. this._offsetY = null;
  6806. this._orientationGamma = 0;
  6807. this._orientationBeta = 0;
  6808. this._initialOrientationGamma = 0;
  6809. this._initialOrientationBeta = 0;
  6810. this.angularSensibility = 10000.0;
  6811. this.moveSensibility = 50.0;
  6812. window.addEventListener("resize", function () {
  6813. _this._initialOrientationGamma = null;
  6814. }, false);
  6815. }
  6816. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6817. var _this = this;
  6818. if (this._attachedCanvas) {
  6819. return;
  6820. }
  6821. this._attachedCanvas = canvas;
  6822. if (!this._orientationChanged) {
  6823. this._orientationChanged = function (evt) {
  6824. if (!_this._initialOrientationGamma) {
  6825. _this._initialOrientationGamma = evt.gamma;
  6826. _this._initialOrientationBeta = evt.beta;
  6827. }
  6828. _this._orientationGamma = evt.gamma;
  6829. _this._orientationBeta = evt.beta;
  6830. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6831. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6832. };
  6833. }
  6834. window.addEventListener("deviceorientation", this._orientationChanged);
  6835. };
  6836. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6837. if (this._attachedCanvas != canvas) {
  6838. return;
  6839. }
  6840. window.removeEventListener("deviceorientation", this._orientationChanged);
  6841. this._attachedCanvas = null;
  6842. this._orientationGamma = 0;
  6843. this._orientationBeta = 0;
  6844. this._initialOrientationGamma = 0;
  6845. this._initialOrientationBeta = 0;
  6846. };
  6847. DeviceOrientationCamera.prototype._checkInputs = function () {
  6848. if (!this._offsetX) {
  6849. return;
  6850. }
  6851. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6852. var speed = this._computeLocalCameraSpeed();
  6853. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6854. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6855. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6856. };
  6857. return DeviceOrientationCamera;
  6858. })(BABYLON.FreeCamera);
  6859. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6860. })(BABYLON || (BABYLON = {}));
  6861. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6862. var BABYLON;
  6863. (function (BABYLON) {
  6864. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6865. var ArcRotateCamera = (function (_super) {
  6866. __extends(ArcRotateCamera, _super);
  6867. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6868. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6869. this.alpha = alpha;
  6870. this.beta = beta;
  6871. this.radius = radius;
  6872. this.target = target;
  6873. this.inertialAlphaOffset = 0;
  6874. this.inertialBetaOffset = 0;
  6875. this.inertialRadiusOffset = 0;
  6876. this.lowerAlphaLimit = null;
  6877. this.upperAlphaLimit = null;
  6878. this.lowerBetaLimit = 0.01;
  6879. this.upperBetaLimit = Math.PI;
  6880. this.lowerRadiusLimit = null;
  6881. this.upperRadiusLimit = null;
  6882. this.angularSensibility = 1000.0;
  6883. this.wheelPrecision = 3.0;
  6884. this.keysUp = [38];
  6885. this.keysDown = [40];
  6886. this.keysLeft = [37];
  6887. this.keysRight = [39];
  6888. this.zoomOnFactor = 1;
  6889. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6890. this._keys = [];
  6891. this._viewMatrix = new BABYLON.Matrix();
  6892. this.checkCollisions = false;
  6893. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6894. this._collider = new BABYLON.Collider();
  6895. this._previousPosition = BABYLON.Vector3.Zero();
  6896. this._collisionVelocity = BABYLON.Vector3.Zero();
  6897. this._newPosition = BABYLON.Vector3.Zero();
  6898. // Pinch
  6899. // value for pinch step scaling
  6900. // set to 20 by default
  6901. this.pinchPrecision = 20;
  6902. this.getViewMatrix();
  6903. }
  6904. ArcRotateCamera.prototype._getTargetPosition = function () {
  6905. return this.target.position || this.target;
  6906. };
  6907. // Cache
  6908. ArcRotateCamera.prototype._initCache = function () {
  6909. _super.prototype._initCache.call(this);
  6910. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6911. this._cache.alpha = undefined;
  6912. this._cache.beta = undefined;
  6913. this._cache.radius = undefined;
  6914. this._cache.targetScreenOffset = undefined;
  6915. };
  6916. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6917. if (!ignoreParentClass) {
  6918. _super.prototype._updateCache.call(this);
  6919. }
  6920. this._cache.target.copyFrom(this._getTargetPosition());
  6921. this._cache.alpha = this.alpha;
  6922. this._cache.beta = this.beta;
  6923. this._cache.radius = this.radius;
  6924. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6925. };
  6926. // Synchronized
  6927. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6928. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6929. return false;
  6930. 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);
  6931. };
  6932. // Methods
  6933. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6934. var _this = this;
  6935. var previousPosition;
  6936. var pointerId;
  6937. // to know if pinch started
  6938. var pinchStarted = false;
  6939. // two pinch point on X
  6940. // that will use for find if user action is pinch open or pinch close
  6941. var pinchPointX1, pinchPointX2;
  6942. if (this._attachedElement) {
  6943. return;
  6944. }
  6945. this._attachedElement = element;
  6946. var engine = this.getEngine();
  6947. if (this._onPointerDown === undefined) {
  6948. this._onPointerDown = function (evt) {
  6949. if (pointerId) {
  6950. return;
  6951. }
  6952. pointerId = evt.pointerId;
  6953. previousPosition = {
  6954. x: evt.clientX,
  6955. y: evt.clientY
  6956. };
  6957. if (!noPreventDefault) {
  6958. evt.preventDefault();
  6959. }
  6960. };
  6961. this._onPointerUp = function (evt) {
  6962. previousPosition = null;
  6963. pointerId = null;
  6964. if (!noPreventDefault) {
  6965. evt.preventDefault();
  6966. }
  6967. };
  6968. this._onPointerMove = function (evt) {
  6969. if (!previousPosition) {
  6970. return;
  6971. }
  6972. if (pointerId !== evt.pointerId) {
  6973. return;
  6974. }
  6975. // return pinch is started
  6976. if (pinchStarted) {
  6977. return;
  6978. }
  6979. var offsetX = evt.clientX - previousPosition.x;
  6980. var offsetY = evt.clientY - previousPosition.y;
  6981. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6982. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6983. previousPosition = {
  6984. x: evt.clientX,
  6985. y: evt.clientY
  6986. };
  6987. if (!noPreventDefault) {
  6988. evt.preventDefault();
  6989. }
  6990. };
  6991. this._onMouseMove = function (evt) {
  6992. if (!engine.isPointerLock) {
  6993. return;
  6994. }
  6995. // return pinch is started
  6996. if (pinchStarted) {
  6997. return;
  6998. }
  6999. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7000. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7001. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7002. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7003. if (!noPreventDefault) {
  7004. evt.preventDefault();
  7005. }
  7006. };
  7007. this._wheel = function (event) {
  7008. var delta = 0;
  7009. if (event.wheelDelta) {
  7010. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7011. } else if (event.detail) {
  7012. delta = -event.detail / _this.wheelPrecision;
  7013. }
  7014. if (delta)
  7015. _this.inertialRadiusOffset += delta;
  7016. if (event.preventDefault) {
  7017. if (!noPreventDefault) {
  7018. event.preventDefault();
  7019. }
  7020. }
  7021. };
  7022. this._onKeyDown = function (evt) {
  7023. 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) {
  7024. var index = _this._keys.indexOf(evt.keyCode);
  7025. if (index === -1) {
  7026. _this._keys.push(evt.keyCode);
  7027. }
  7028. if (evt.preventDefault) {
  7029. if (!noPreventDefault) {
  7030. evt.preventDefault();
  7031. }
  7032. }
  7033. }
  7034. };
  7035. this._onKeyUp = function (evt) {
  7036. 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) {
  7037. var index = _this._keys.indexOf(evt.keyCode);
  7038. if (index >= 0) {
  7039. _this._keys.splice(index, 1);
  7040. }
  7041. if (evt.preventDefault) {
  7042. if (!noPreventDefault) {
  7043. evt.preventDefault();
  7044. }
  7045. }
  7046. }
  7047. };
  7048. this._onLostFocus = function () {
  7049. _this._keys = [];
  7050. pointerId = null;
  7051. };
  7052. this._onGestureStart = function (e) {
  7053. if (window.MSGesture === undefined) {
  7054. return;
  7055. }
  7056. if (!_this._MSGestureHandler) {
  7057. _this._MSGestureHandler = new MSGesture();
  7058. _this._MSGestureHandler.target = element;
  7059. }
  7060. _this._MSGestureHandler.addPointer(e.pointerId);
  7061. };
  7062. this._onGesture = function (e) {
  7063. _this.radius *= e.scale;
  7064. if (e.preventDefault) {
  7065. if (!noPreventDefault) {
  7066. e.stopPropagation();
  7067. e.preventDefault();
  7068. }
  7069. }
  7070. };
  7071. this._reset = function () {
  7072. _this._keys = [];
  7073. _this.inertialAlphaOffset = 0;
  7074. _this.inertialBetaOffset = 0;
  7075. _this.inertialRadiusOffset = 0;
  7076. previousPosition = null;
  7077. pointerId = null;
  7078. };
  7079. this._touchStart = function (event) {
  7080. if (event.touches.length === 2) {
  7081. //-- start pinch if two fingers on the screen
  7082. pinchStarted = true;
  7083. _this._pinchStart(event);
  7084. }
  7085. };
  7086. this._touchMove = function (event) {
  7087. if (pinchStarted) {
  7088. //-- make scaling
  7089. _this._pinchMove(event);
  7090. }
  7091. };
  7092. this._touchEnd = function (event) {
  7093. if (pinchStarted) {
  7094. //-- end of pinch
  7095. _this._pinchEnd(event);
  7096. }
  7097. };
  7098. this._pinchStart = function (event) {
  7099. // save origin touch point
  7100. pinchPointX1 = event.touches[0].clientX;
  7101. pinchPointX2 = event.touches[1].clientX;
  7102. // block the camera
  7103. // if not it rotate around target during pinch
  7104. pinchStarted = true;
  7105. };
  7106. this._pinchMove = function (event) {
  7107. // variable for new camera's radius
  7108. var delta = 0;
  7109. // variables to know if pinch open or pinch close
  7110. var direction = 1;
  7111. var distanceXOrigine, distanceXNow;
  7112. if (event.touches.length !== 2)
  7113. return;
  7114. // calculate absolute distances of the two fingers
  7115. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7116. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7117. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7118. if (distanceXNow < distanceXOrigine) {
  7119. direction = -1;
  7120. }
  7121. // calculate new radius
  7122. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7123. // set new radius
  7124. _this.inertialRadiusOffset -= delta;
  7125. // save origin touch point
  7126. pinchPointX1 = event.touches[0].clientX;
  7127. pinchPointX2 = event.touches[1].clientX;
  7128. };
  7129. this._pinchEnd = function (event) {
  7130. // cancel pinch and deblock camera rotation
  7131. pinchStarted = false;
  7132. };
  7133. }
  7134. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7135. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7136. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7137. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7138. element.addEventListener("mousemove", this._onMouseMove, false);
  7139. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7140. element.addEventListener("MSGestureChange", this._onGesture, false);
  7141. element.addEventListener('mousewheel', this._wheel, false);
  7142. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7143. // pinch
  7144. element.addEventListener('touchstart', this._touchStart, false);
  7145. element.addEventListener('touchmove', this._touchMove, false);
  7146. element.addEventListener('touchend', this._touchEnd, false);
  7147. BABYLON.Tools.RegisterTopRootEvents([
  7148. { name: "keydown", handler: this._onKeyDown },
  7149. { name: "keyup", handler: this._onKeyUp },
  7150. { name: "blur", handler: this._onLostFocus }
  7151. ]);
  7152. };
  7153. ArcRotateCamera.prototype.detachControl = function (element) {
  7154. if (this._attachedElement != element) {
  7155. return;
  7156. }
  7157. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7158. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7159. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7160. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7161. element.removeEventListener("mousemove", this._onMouseMove);
  7162. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7163. element.removeEventListener("MSGestureChange", this._onGesture);
  7164. element.removeEventListener('mousewheel', this._wheel);
  7165. element.removeEventListener('DOMMouseScroll', this._wheel);
  7166. // pinch
  7167. element.removeEventListener('touchstart', this._touchStart);
  7168. element.removeEventListener('touchmove', this._touchMove);
  7169. element.removeEventListener('touchend', this._touchEnd);
  7170. BABYLON.Tools.UnregisterTopRootEvents([
  7171. { name: "keydown", handler: this._onKeyDown },
  7172. { name: "keyup", handler: this._onKeyUp },
  7173. { name: "blur", handler: this._onLostFocus }
  7174. ]);
  7175. this._MSGestureHandler = null;
  7176. this._attachedElement = null;
  7177. if (this._reset) {
  7178. this._reset();
  7179. }
  7180. };
  7181. ArcRotateCamera.prototype._update = function () {
  7182. for (var index = 0; index < this._keys.length; index++) {
  7183. var keyCode = this._keys[index];
  7184. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7185. this.inertialAlphaOffset -= 0.01;
  7186. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  7187. this.inertialBetaOffset -= 0.01;
  7188. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  7189. this.inertialAlphaOffset += 0.01;
  7190. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  7191. this.inertialBetaOffset += 0.01;
  7192. }
  7193. }
  7194. // Inertia
  7195. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7196. this.alpha += this.inertialAlphaOffset;
  7197. this.beta += this.inertialBetaOffset;
  7198. this.radius -= this.inertialRadiusOffset;
  7199. this.inertialAlphaOffset *= this.inertia;
  7200. this.inertialBetaOffset *= this.inertia;
  7201. this.inertialRadiusOffset *= this.inertia;
  7202. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7203. this.inertialAlphaOffset = 0;
  7204. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7205. this.inertialBetaOffset = 0;
  7206. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7207. this.inertialRadiusOffset = 0;
  7208. }
  7209. // Limits
  7210. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7211. this.alpha = this.lowerAlphaLimit;
  7212. }
  7213. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7214. this.alpha = this.upperAlphaLimit;
  7215. }
  7216. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7217. this.beta = this.lowerBetaLimit;
  7218. }
  7219. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7220. this.beta = this.upperBetaLimit;
  7221. }
  7222. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7223. this.radius = this.lowerRadiusLimit;
  7224. }
  7225. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7226. this.radius = this.upperRadiusLimit;
  7227. }
  7228. };
  7229. ArcRotateCamera.prototype.setPosition = function (position) {
  7230. var radiusv3 = position.subtract(this._getTargetPosition());
  7231. this.radius = radiusv3.length();
  7232. // Alpha
  7233. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7234. if (radiusv3.z < 0) {
  7235. this.alpha = 2 * Math.PI - this.alpha;
  7236. }
  7237. // Beta
  7238. this.beta = Math.acos(radiusv3.y / this.radius);
  7239. };
  7240. ArcRotateCamera.prototype._getViewMatrix = function () {
  7241. // Compute
  7242. var cosa = Math.cos(this.alpha);
  7243. var sina = Math.sin(this.alpha);
  7244. var cosb = Math.cos(this.beta);
  7245. var sinb = Math.sin(this.beta);
  7246. var target = this._getTargetPosition();
  7247. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7248. if (this.checkCollisions) {
  7249. this._collider.radius = this.collisionRadius;
  7250. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7251. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7252. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7253. this.position.copyFrom(this._previousPosition);
  7254. this.alpha = this._previousAlpha;
  7255. this.beta = this._previousBeta;
  7256. this.radius = this._previousRadius;
  7257. if (this.onCollide) {
  7258. this.onCollide(this._collider.collidedMesh);
  7259. }
  7260. }
  7261. }
  7262. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7263. this._previousAlpha = this.alpha;
  7264. this._previousBeta = this.beta;
  7265. this._previousRadius = this.radius;
  7266. this._previousPosition.copyFrom(this.position);
  7267. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7268. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7269. return this._viewMatrix;
  7270. };
  7271. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7272. meshes = meshes || this.getScene().meshes;
  7273. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7274. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7275. this.radius = distance * this.zoomOnFactor;
  7276. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7277. };
  7278. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7279. var meshesOrMinMaxVector;
  7280. var distance;
  7281. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7282. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7283. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7284. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7285. } else {
  7286. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7287. distance = meshesOrMinMaxVectorAndDistance.distance;
  7288. }
  7289. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7290. this.maxZ = distance * 2;
  7291. };
  7292. return ArcRotateCamera;
  7293. })(BABYLON.Camera);
  7294. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7295. })(BABYLON || (BABYLON = {}));
  7296. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7297. var BABYLON;
  7298. (function (BABYLON) {
  7299. /**
  7300. * Represents a scene to be rendered by the engine.
  7301. * @see http://doc.babylonjs.com/page.php?p=21911
  7302. */
  7303. var Scene = (function () {
  7304. /**
  7305. * @constructor
  7306. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7307. */
  7308. function Scene(engine) {
  7309. // Members
  7310. this.autoClear = true;
  7311. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7312. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7313. this.forceWireframe = false;
  7314. this.forcePointsCloud = false;
  7315. this.forceShowBoundingBoxes = false;
  7316. this.animationsEnabled = true;
  7317. this.cameraToUseForPointers = null;
  7318. // Fog
  7319. /**
  7320. * is fog enabled on this scene.
  7321. * @type {boolean}
  7322. */
  7323. this.fogEnabled = true;
  7324. this.fogMode = Scene.FOGMODE_NONE;
  7325. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7326. this.fogDensity = 0.1;
  7327. this.fogStart = 0;
  7328. this.fogEnd = 1000.0;
  7329. // Lights
  7330. /**
  7331. * is shadow enabled on this scene.
  7332. * @type {boolean}
  7333. */
  7334. this.shadowsEnabled = true;
  7335. /**
  7336. * is light enabled on this scene.
  7337. * @type {boolean}
  7338. */
  7339. this.lightsEnabled = true;
  7340. /**
  7341. * All of the lights added to this scene.
  7342. * @see BABYLON.Light
  7343. * @type {BABYLON.Light[]}
  7344. */
  7345. this.lights = new Array();
  7346. // Cameras
  7347. /**
  7348. * All of the cameras added to this scene.
  7349. * @see BABYLON.Camera
  7350. * @type {BABYLON.Camera[]}
  7351. */
  7352. this.cameras = new Array();
  7353. this.activeCameras = new Array();
  7354. // Meshes
  7355. /**
  7356. * All of the (abstract) meshes added to this scene.
  7357. * @see BABYLON.AbstractMesh
  7358. * @type {BABYLON.AbstractMesh[]}
  7359. */
  7360. this.meshes = new Array();
  7361. // Geometries
  7362. this._geometries = new Array();
  7363. this.materials = new Array();
  7364. this.multiMaterials = new Array();
  7365. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7366. // Textures
  7367. this.texturesEnabled = true;
  7368. this.textures = new Array();
  7369. // Particles
  7370. this.particlesEnabled = true;
  7371. this.particleSystems = new Array();
  7372. // Sprites
  7373. this.spriteManagers = new Array();
  7374. // Layers
  7375. this.layers = new Array();
  7376. // Skeletons
  7377. this.skeletonsEnabled = true;
  7378. this.skeletons = new Array();
  7379. // Lens flares
  7380. this.lensFlaresEnabled = true;
  7381. this.lensFlareSystems = new Array();
  7382. // Collisions
  7383. this.collisionsEnabled = true;
  7384. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7385. // Postprocesses
  7386. this.postProcessesEnabled = true;
  7387. // Customs render targets
  7388. this.renderTargetsEnabled = true;
  7389. this.customRenderTargets = new Array();
  7390. // Imported meshes
  7391. this.importedMeshesFiles = new Array();
  7392. this._actionManagers = new Array();
  7393. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7394. // Procedural textures
  7395. this.proceduralTexturesEnabled = true;
  7396. this._proceduralTextures = new Array();
  7397. this.soundTracks = new Array();
  7398. this._totalVertices = 0;
  7399. this._activeVertices = 0;
  7400. this._activeParticles = 0;
  7401. this._lastFrameDuration = 0;
  7402. this._evaluateActiveMeshesDuration = 0;
  7403. this._renderTargetsDuration = 0;
  7404. this._particlesDuration = 0;
  7405. this._renderDuration = 0;
  7406. this._spritesDuration = 0;
  7407. this._animationRatio = 0;
  7408. this._renderId = 0;
  7409. this._executeWhenReadyTimeoutId = -1;
  7410. this._toBeDisposed = new BABYLON.SmartArray(256);
  7411. this._onReadyCallbacks = new Array();
  7412. this._pendingData = [];
  7413. this._onBeforeRenderCallbacks = new Array();
  7414. this._onAfterRenderCallbacks = new Array();
  7415. this._activeMeshes = new BABYLON.SmartArray(256);
  7416. this._processedMaterials = new BABYLON.SmartArray(256);
  7417. this._renderTargets = new BABYLON.SmartArray(256);
  7418. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7419. this._activeSkeletons = new BABYLON.SmartArray(32);
  7420. this._activeBones = 0;
  7421. this._activeAnimatables = new Array();
  7422. this._transformMatrix = BABYLON.Matrix.Zero();
  7423. this._scaledPosition = BABYLON.Vector3.Zero();
  7424. this._scaledVelocity = BABYLON.Vector3.Zero();
  7425. this._engine = engine;
  7426. engine.scenes.push(this);
  7427. this._renderingManager = new BABYLON.RenderingManager(this);
  7428. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7429. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7430. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7431. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7432. this.attachControl();
  7433. this._debugLayer = new BABYLON.DebugLayer(this);
  7434. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7435. }
  7436. Object.defineProperty(Scene.prototype, "debugLayer", {
  7437. // Properties
  7438. get: function () {
  7439. return this._debugLayer;
  7440. },
  7441. enumerable: true,
  7442. configurable: true
  7443. });
  7444. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7445. /**
  7446. * The mesh that is currently under the pointer.
  7447. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7448. */
  7449. get: function () {
  7450. return this._meshUnderPointer;
  7451. },
  7452. enumerable: true,
  7453. configurable: true
  7454. });
  7455. Object.defineProperty(Scene.prototype, "pointerX", {
  7456. /**
  7457. * Current on-screen X position of the pointer
  7458. * @return {number} X position of the pointer
  7459. */
  7460. get: function () {
  7461. return this._pointerX;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(Scene.prototype, "pointerY", {
  7467. /**
  7468. * Current on-screen Y position of the pointer
  7469. * @return {number} Y position of the pointer
  7470. */
  7471. get: function () {
  7472. return this._pointerY;
  7473. },
  7474. enumerable: true,
  7475. configurable: true
  7476. });
  7477. Scene.prototype.getCachedMaterial = function () {
  7478. return this._cachedMaterial;
  7479. };
  7480. Scene.prototype.getBoundingBoxRenderer = function () {
  7481. return this._boundingBoxRenderer;
  7482. };
  7483. Scene.prototype.getOutlineRenderer = function () {
  7484. return this._outlineRenderer;
  7485. };
  7486. Scene.prototype.getEngine = function () {
  7487. return this._engine;
  7488. };
  7489. Scene.prototype.getTotalVertices = function () {
  7490. return this._totalVertices;
  7491. };
  7492. Scene.prototype.getActiveVertices = function () {
  7493. return this._activeVertices;
  7494. };
  7495. Scene.prototype.getActiveParticles = function () {
  7496. return this._activeParticles;
  7497. };
  7498. Scene.prototype.getActiveBones = function () {
  7499. return this._activeBones;
  7500. };
  7501. // Stats
  7502. Scene.prototype.getLastFrameDuration = function () {
  7503. return this._lastFrameDuration;
  7504. };
  7505. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7506. return this._evaluateActiveMeshesDuration;
  7507. };
  7508. Scene.prototype.getActiveMeshes = function () {
  7509. return this._activeMeshes;
  7510. };
  7511. Scene.prototype.getRenderTargetsDuration = function () {
  7512. return this._renderTargetsDuration;
  7513. };
  7514. Scene.prototype.getRenderDuration = function () {
  7515. return this._renderDuration;
  7516. };
  7517. Scene.prototype.getParticlesDuration = function () {
  7518. return this._particlesDuration;
  7519. };
  7520. Scene.prototype.getSpritesDuration = function () {
  7521. return this._spritesDuration;
  7522. };
  7523. Scene.prototype.getAnimationRatio = function () {
  7524. return this._animationRatio;
  7525. };
  7526. Scene.prototype.getRenderId = function () {
  7527. return this._renderId;
  7528. };
  7529. Scene.prototype._updatePointerPosition = function (evt) {
  7530. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7531. this._pointerX = evt.clientX - canvasRect.left;
  7532. this._pointerY = evt.clientY - canvasRect.top;
  7533. if (this.cameraToUseForPointers) {
  7534. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7535. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7536. }
  7537. };
  7538. // Pointers handling
  7539. Scene.prototype.attachControl = function () {
  7540. var _this = this;
  7541. this._onPointerMove = function (evt) {
  7542. var canvas = _this._engine.getRenderingCanvas();
  7543. _this._updatePointerPosition(evt);
  7544. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7545. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7546. }, false, _this.cameraToUseForPointers);
  7547. if (pickResult.hit) {
  7548. _this._meshUnderPointer = pickResult.pickedMesh;
  7549. _this.setPointerOverMesh(pickResult.pickedMesh);
  7550. canvas.style.cursor = "pointer";
  7551. } else {
  7552. _this.setPointerOverMesh(null);
  7553. canvas.style.cursor = "";
  7554. _this._meshUnderPointer = null;
  7555. }
  7556. };
  7557. this._onPointerDown = function (evt) {
  7558. var predicate = null;
  7559. if (!_this.onPointerDown) {
  7560. predicate = function (mesh) {
  7561. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7562. };
  7563. }
  7564. _this._updatePointerPosition(evt);
  7565. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7566. if (pickResult.hit) {
  7567. if (pickResult.pickedMesh.actionManager) {
  7568. switch (evt.button) {
  7569. case 0:
  7570. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7571. break;
  7572. case 1:
  7573. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7574. break;
  7575. case 2:
  7576. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7577. break;
  7578. }
  7579. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7580. }
  7581. }
  7582. if (_this.onPointerDown) {
  7583. _this.onPointerDown(evt, pickResult);
  7584. }
  7585. };
  7586. this._onKeyDown = function (evt) {
  7587. if (_this.actionManager) {
  7588. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7589. }
  7590. };
  7591. this._onKeyUp = function (evt) {
  7592. if (_this.actionManager) {
  7593. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7594. }
  7595. };
  7596. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7597. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7598. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7599. window.addEventListener("keydown", this._onKeyDown, false);
  7600. window.addEventListener("keyup", this._onKeyUp, false);
  7601. };
  7602. Scene.prototype.detachControl = function () {
  7603. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7604. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7605. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7606. window.removeEventListener("keydown", this._onKeyDown);
  7607. window.removeEventListener("keyup", this._onKeyUp);
  7608. };
  7609. // Ready
  7610. Scene.prototype.isReady = function () {
  7611. if (this._pendingData.length > 0) {
  7612. return false;
  7613. }
  7614. for (var index = 0; index < this._geometries.length; index++) {
  7615. var geometry = this._geometries[index];
  7616. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7617. return false;
  7618. }
  7619. }
  7620. for (index = 0; index < this.meshes.length; index++) {
  7621. var mesh = this.meshes[index];
  7622. if (!mesh.isReady()) {
  7623. return false;
  7624. }
  7625. var mat = mesh.material;
  7626. if (mat) {
  7627. if (!mat.isReady(mesh)) {
  7628. return false;
  7629. }
  7630. }
  7631. }
  7632. return true;
  7633. };
  7634. Scene.prototype.resetCachedMaterial = function () {
  7635. this._cachedMaterial = null;
  7636. };
  7637. Scene.prototype.registerBeforeRender = function (func) {
  7638. this._onBeforeRenderCallbacks.push(func);
  7639. };
  7640. Scene.prototype.unregisterBeforeRender = function (func) {
  7641. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7642. if (index > -1) {
  7643. this._onBeforeRenderCallbacks.splice(index, 1);
  7644. }
  7645. };
  7646. Scene.prototype.registerAfterRender = function (func) {
  7647. this._onAfterRenderCallbacks.push(func);
  7648. };
  7649. Scene.prototype.unregisterAfterRender = function (func) {
  7650. var index = this._onAfterRenderCallbacks.indexOf(func);
  7651. if (index > -1) {
  7652. this._onAfterRenderCallbacks.splice(index, 1);
  7653. }
  7654. };
  7655. Scene.prototype._addPendingData = function (data) {
  7656. this._pendingData.push(data);
  7657. };
  7658. Scene.prototype._removePendingData = function (data) {
  7659. var index = this._pendingData.indexOf(data);
  7660. if (index !== -1) {
  7661. this._pendingData.splice(index, 1);
  7662. }
  7663. };
  7664. Scene.prototype.getWaitingItemsCount = function () {
  7665. return this._pendingData.length;
  7666. };
  7667. /**
  7668. * Registers a function to be executed when the scene is ready.
  7669. * @param {Function} func - the function to be executed.
  7670. */
  7671. Scene.prototype.executeWhenReady = function (func) {
  7672. var _this = this;
  7673. this._onReadyCallbacks.push(func);
  7674. if (this._executeWhenReadyTimeoutId !== -1) {
  7675. return;
  7676. }
  7677. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7678. _this._checkIsReady();
  7679. }, 150);
  7680. };
  7681. Scene.prototype._checkIsReady = function () {
  7682. var _this = this;
  7683. if (this.isReady()) {
  7684. this._onReadyCallbacks.forEach(function (func) {
  7685. func();
  7686. });
  7687. this._onReadyCallbacks = [];
  7688. this._executeWhenReadyTimeoutId = -1;
  7689. return;
  7690. }
  7691. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7692. _this._checkIsReady();
  7693. }, 150);
  7694. };
  7695. // Animations
  7696. /**
  7697. * Will start the animation sequence of a given target
  7698. * @param target - the target
  7699. * @param {number} from - from which frame should animation start
  7700. * @param {number} to - till which frame should animation run.
  7701. * @param {boolean} [loop] - should the animation loop
  7702. * @param {number} [speedRatio] - the speed in which to run the animation
  7703. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7704. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7705. * @return {BABYLON.Animatable} the animatable object created for this animation
  7706. * @see BABYLON.Animatable
  7707. * @see http://doc.babylonjs.com/page.php?p=22081
  7708. */
  7709. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7710. if (speedRatio === undefined) {
  7711. speedRatio = 1.0;
  7712. }
  7713. this.stopAnimation(target);
  7714. if (!animatable) {
  7715. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7716. }
  7717. // Local animations
  7718. if (target.animations) {
  7719. animatable.appendAnimations(target, target.animations);
  7720. }
  7721. // Children animations
  7722. if (target.getAnimatables) {
  7723. var animatables = target.getAnimatables();
  7724. for (var index = 0; index < animatables.length; index++) {
  7725. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7726. }
  7727. }
  7728. return animatable;
  7729. };
  7730. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7731. if (speedRatio === undefined) {
  7732. speedRatio = 1.0;
  7733. }
  7734. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7735. return animatable;
  7736. };
  7737. Scene.prototype.getAnimatableByTarget = function (target) {
  7738. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7739. if (this._activeAnimatables[index].target === target) {
  7740. return this._activeAnimatables[index];
  7741. }
  7742. }
  7743. return null;
  7744. };
  7745. /**
  7746. * Will stop the animation of the given target
  7747. * @param target - the target
  7748. * @see beginAnimation
  7749. */
  7750. Scene.prototype.stopAnimation = function (target) {
  7751. var animatable = this.getAnimatableByTarget(target);
  7752. if (animatable) {
  7753. animatable.stop();
  7754. }
  7755. };
  7756. Scene.prototype._animate = function () {
  7757. if (!this.animationsEnabled) {
  7758. return;
  7759. }
  7760. if (!this._animationStartDate) {
  7761. this._animationStartDate = BABYLON.Tools.Now;
  7762. }
  7763. // Getting time
  7764. var now = BABYLON.Tools.Now;
  7765. var delay = now - this._animationStartDate;
  7766. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7767. if (!this._activeAnimatables[index]._animate(delay)) {
  7768. this._activeAnimatables.splice(index, 1);
  7769. index--;
  7770. }
  7771. }
  7772. };
  7773. // Matrix
  7774. Scene.prototype.getViewMatrix = function () {
  7775. return this._viewMatrix;
  7776. };
  7777. Scene.prototype.getProjectionMatrix = function () {
  7778. return this._projectionMatrix;
  7779. };
  7780. Scene.prototype.getTransformMatrix = function () {
  7781. return this._transformMatrix;
  7782. };
  7783. Scene.prototype.setTransformMatrix = function (view, projection) {
  7784. this._viewMatrix = view;
  7785. this._projectionMatrix = projection;
  7786. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7787. };
  7788. // Methods
  7789. /**
  7790. * sets the active camera of the scene using its ID
  7791. * @param {string} id - the camera's ID
  7792. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7793. * @see activeCamera
  7794. */
  7795. Scene.prototype.setActiveCameraByID = function (id) {
  7796. var camera = this.getCameraByID(id);
  7797. if (camera) {
  7798. this.activeCamera = camera;
  7799. return camera;
  7800. }
  7801. return null;
  7802. };
  7803. /**
  7804. * sets the active camera of the scene using its name
  7805. * @param {string} name - the camera's name
  7806. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7807. * @see activeCamera
  7808. */
  7809. Scene.prototype.setActiveCameraByName = function (name) {
  7810. var camera = this.getCameraByName(name);
  7811. if (camera) {
  7812. this.activeCamera = camera;
  7813. return camera;
  7814. }
  7815. return null;
  7816. };
  7817. /**
  7818. * get a material using its id
  7819. * @param {string} the material's ID
  7820. * @return {BABYLON.Material|null} the material or null if none found.
  7821. */
  7822. Scene.prototype.getMaterialByID = function (id) {
  7823. for (var index = 0; index < this.materials.length; index++) {
  7824. if (this.materials[index].id === id) {
  7825. return this.materials[index];
  7826. }
  7827. }
  7828. return null;
  7829. };
  7830. /**
  7831. * get a material using its name
  7832. * @param {string} the material's name
  7833. * @return {BABYLON.Material|null} the material or null if none found.
  7834. */
  7835. Scene.prototype.getMaterialByName = function (name) {
  7836. for (var index = 0; index < this.materials.length; index++) {
  7837. if (this.materials[index].name === name) {
  7838. return this.materials[index];
  7839. }
  7840. }
  7841. return null;
  7842. };
  7843. Scene.prototype.getCameraByID = function (id) {
  7844. for (var index = 0; index < this.cameras.length; index++) {
  7845. if (this.cameras[index].id === id) {
  7846. return this.cameras[index];
  7847. }
  7848. }
  7849. return null;
  7850. };
  7851. /**
  7852. * get a camera using its name
  7853. * @param {string} the camera's name
  7854. * @return {BABYLON.Camera|null} the camera or null if none found.
  7855. */
  7856. Scene.prototype.getCameraByName = function (name) {
  7857. for (var index = 0; index < this.cameras.length; index++) {
  7858. if (this.cameras[index].name === name) {
  7859. return this.cameras[index];
  7860. }
  7861. }
  7862. return null;
  7863. };
  7864. /**
  7865. * get a light node using its name
  7866. * @param {string} the light's name
  7867. * @return {BABYLON.Light|null} the light or null if none found.
  7868. */
  7869. Scene.prototype.getLightByName = function (name) {
  7870. for (var index = 0; index < this.lights.length; index++) {
  7871. if (this.lights[index].name === name) {
  7872. return this.lights[index];
  7873. }
  7874. }
  7875. return null;
  7876. };
  7877. /**
  7878. * get a light node using its ID
  7879. * @param {string} the light's id
  7880. * @return {BABYLON.Light|null} the light or null if none found.
  7881. */
  7882. Scene.prototype.getLightByID = function (id) {
  7883. for (var index = 0; index < this.lights.length; index++) {
  7884. if (this.lights[index].id === id) {
  7885. return this.lights[index];
  7886. }
  7887. }
  7888. return null;
  7889. };
  7890. /**
  7891. * get a geometry using its ID
  7892. * @param {string} the geometry's id
  7893. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  7894. */
  7895. Scene.prototype.getGeometryByID = function (id) {
  7896. for (var index = 0; index < this._geometries.length; index++) {
  7897. if (this._geometries[index].id === id) {
  7898. return this._geometries[index];
  7899. }
  7900. }
  7901. return null;
  7902. };
  7903. /**
  7904. * add a new geometry to this scene.
  7905. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  7906. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  7907. * @return {boolean} was the geometry added or not
  7908. */
  7909. Scene.prototype.pushGeometry = function (geometry, force) {
  7910. if (!force && this.getGeometryByID(geometry.id)) {
  7911. return false;
  7912. }
  7913. this._geometries.push(geometry);
  7914. return true;
  7915. };
  7916. Scene.prototype.getGeometries = function () {
  7917. return this._geometries;
  7918. };
  7919. /**
  7920. * Get a the first added mesh found of a given ID
  7921. * @param {string} id - the id to search for
  7922. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  7923. */
  7924. Scene.prototype.getMeshByID = function (id) {
  7925. for (var index = 0; index < this.meshes.length; index++) {
  7926. if (this.meshes[index].id === id) {
  7927. return this.meshes[index];
  7928. }
  7929. }
  7930. return null;
  7931. };
  7932. /**
  7933. * Get a the last added mesh found of a given ID
  7934. * @param {string} id - the id to search for
  7935. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  7936. */
  7937. Scene.prototype.getLastMeshByID = function (id) {
  7938. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7939. if (this.meshes[index].id === id) {
  7940. return this.meshes[index];
  7941. }
  7942. }
  7943. return null;
  7944. };
  7945. /**
  7946. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  7947. * @param {string} id - the id to search for
  7948. * @return {BABYLON.Node|null} the node found or null if not found at all.
  7949. */
  7950. Scene.prototype.getLastEntryByID = function (id) {
  7951. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7952. if (this.meshes[index].id === id) {
  7953. return this.meshes[index];
  7954. }
  7955. }
  7956. for (index = this.cameras.length - 1; index >= 0; index--) {
  7957. if (this.cameras[index].id === id) {
  7958. return this.cameras[index];
  7959. }
  7960. }
  7961. for (index = this.lights.length - 1; index >= 0; index--) {
  7962. if (this.lights[index].id === id) {
  7963. return this.lights[index];
  7964. }
  7965. }
  7966. return null;
  7967. };
  7968. Scene.prototype.getNodeByName = function (name) {
  7969. var mesh = this.getMeshByName(name);
  7970. if (mesh) {
  7971. return mesh;
  7972. }
  7973. var light = this.getLightByName(name);
  7974. if (light) {
  7975. return light;
  7976. }
  7977. return this.getCameraByName(name);
  7978. };
  7979. Scene.prototype.getMeshByName = function (name) {
  7980. for (var index = 0; index < this.meshes.length; index++) {
  7981. if (this.meshes[index].name === name) {
  7982. return this.meshes[index];
  7983. }
  7984. }
  7985. return null;
  7986. };
  7987. Scene.prototype.getSoundByName = function (name) {
  7988. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  7989. if (this.mainSoundTrack.soundCollection[index].name === name) {
  7990. return this.mainSoundTrack.soundCollection[index];
  7991. }
  7992. }
  7993. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  7994. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  7995. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  7996. return this.soundTracks[sdIndex].soundCollection[index];
  7997. }
  7998. }
  7999. }
  8000. return null;
  8001. };
  8002. Scene.prototype.getLastSkeletonByID = function (id) {
  8003. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8004. if (this.skeletons[index].id === id) {
  8005. return this.skeletons[index];
  8006. }
  8007. }
  8008. return null;
  8009. };
  8010. Scene.prototype.getSkeletonById = function (id) {
  8011. for (var index = 0; index < this.skeletons.length; index++) {
  8012. if (this.skeletons[index].id === id) {
  8013. return this.skeletons[index];
  8014. }
  8015. }
  8016. return null;
  8017. };
  8018. Scene.prototype.getSkeletonByName = function (name) {
  8019. for (var index = 0; index < this.skeletons.length; index++) {
  8020. if (this.skeletons[index].name === name) {
  8021. return this.skeletons[index];
  8022. }
  8023. }
  8024. return null;
  8025. };
  8026. Scene.prototype.isActiveMesh = function (mesh) {
  8027. return (this._activeMeshes.indexOf(mesh) !== -1);
  8028. };
  8029. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8030. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8031. var material = subMesh.getMaterial();
  8032. if (mesh.showSubMeshesBoundingBox) {
  8033. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8034. }
  8035. if (material) {
  8036. // Render targets
  8037. if (material.getRenderTargetTextures) {
  8038. if (this._processedMaterials.indexOf(material) === -1) {
  8039. this._processedMaterials.push(material);
  8040. this._renderTargets.concat(material.getRenderTargetTextures());
  8041. }
  8042. }
  8043. // Dispatch
  8044. this._activeVertices += subMesh.indexCount;
  8045. this._renderingManager.dispatch(subMesh);
  8046. }
  8047. }
  8048. };
  8049. Scene.prototype._evaluateActiveMeshes = function () {
  8050. this._activeMeshes.reset();
  8051. this._renderingManager.reset();
  8052. this._processedMaterials.reset();
  8053. this._activeParticleSystems.reset();
  8054. this._activeSkeletons.reset();
  8055. this._boundingBoxRenderer.reset();
  8056. if (!this._frustumPlanes) {
  8057. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8058. } else {
  8059. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8060. }
  8061. // Meshes
  8062. var meshes;
  8063. var len;
  8064. if (this._selectionOctree) {
  8065. var selection = this._selectionOctree.select(this._frustumPlanes);
  8066. meshes = selection.data;
  8067. len = selection.length;
  8068. } else {
  8069. len = this.meshes.length;
  8070. meshes = this.meshes;
  8071. }
  8072. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8073. var mesh = meshes[meshIndex];
  8074. if (mesh.isBlocked) {
  8075. continue;
  8076. }
  8077. this._totalVertices += mesh.getTotalVertices();
  8078. if (!mesh.isReady()) {
  8079. continue;
  8080. }
  8081. mesh.computeWorldMatrix();
  8082. // Intersections
  8083. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8084. this._meshesForIntersections.pushNoDuplicate(mesh);
  8085. }
  8086. // Switch to current LOD
  8087. var meshLOD = mesh.getLOD(this.activeCamera);
  8088. if (!meshLOD) {
  8089. continue;
  8090. }
  8091. mesh._preActivate();
  8092. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8093. this._activeMeshes.push(mesh);
  8094. mesh._activate(this._renderId);
  8095. this._activeMesh(meshLOD);
  8096. }
  8097. }
  8098. // Particle systems
  8099. var beforeParticlesDate = BABYLON.Tools.Now;
  8100. if (this.particlesEnabled) {
  8101. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8102. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8103. var particleSystem = this.particleSystems[particleIndex];
  8104. if (!particleSystem.isStarted()) {
  8105. continue;
  8106. }
  8107. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8108. this._activeParticleSystems.push(particleSystem);
  8109. particleSystem.animate();
  8110. }
  8111. }
  8112. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8113. }
  8114. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8115. };
  8116. Scene.prototype._activeMesh = function (mesh) {
  8117. if (mesh.skeleton && this.skeletonsEnabled) {
  8118. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8119. }
  8120. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8121. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8122. }
  8123. if (mesh && mesh.subMeshes) {
  8124. // Submeshes Octrees
  8125. var len;
  8126. var subMeshes;
  8127. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8128. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8129. len = intersections.length;
  8130. subMeshes = intersections.data;
  8131. } else {
  8132. subMeshes = mesh.subMeshes;
  8133. len = subMeshes.length;
  8134. }
  8135. for (var subIndex = 0; subIndex < len; subIndex++) {
  8136. var subMesh = subMeshes[subIndex];
  8137. this._evaluateSubMesh(subMesh, mesh);
  8138. }
  8139. }
  8140. };
  8141. Scene.prototype.updateTransformMatrix = function (force) {
  8142. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8143. };
  8144. Scene.prototype._renderForCamera = function (camera) {
  8145. var engine = this._engine;
  8146. this.activeCamera = camera;
  8147. if (!this.activeCamera)
  8148. throw new Error("Active camera not set");
  8149. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8150. // Viewport
  8151. engine.setViewport(this.activeCamera.viewport);
  8152. // Camera
  8153. this._renderId++;
  8154. this.updateTransformMatrix();
  8155. if (this.beforeCameraRender) {
  8156. this.beforeCameraRender(this.activeCamera);
  8157. }
  8158. // Meshes
  8159. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8160. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8161. this._evaluateActiveMeshes();
  8162. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8163. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8164. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8165. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8166. skeleton.prepare();
  8167. this._activeBones += skeleton.bones.length;
  8168. }
  8169. // Render targets
  8170. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8171. if (this.renderTargetsEnabled) {
  8172. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8173. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8174. var renderTarget = this._renderTargets.data[renderIndex];
  8175. if (renderTarget._shouldRender()) {
  8176. this._renderId++;
  8177. renderTarget.render();
  8178. }
  8179. }
  8180. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8181. this._renderId++;
  8182. }
  8183. if (this._renderTargets.length > 0) {
  8184. engine.restoreDefaultFramebuffer();
  8185. }
  8186. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8187. // Prepare Frame
  8188. this.postProcessManager._prepareFrame();
  8189. var beforeRenderDate = BABYLON.Tools.Now;
  8190. // Backgrounds
  8191. if (this.layers.length) {
  8192. engine.setDepthBuffer(false);
  8193. var layerIndex;
  8194. var layer;
  8195. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8196. layer = this.layers[layerIndex];
  8197. if (layer.isBackground) {
  8198. layer.render();
  8199. }
  8200. }
  8201. engine.setDepthBuffer(true);
  8202. }
  8203. // Render
  8204. BABYLON.Tools.StartPerformanceCounter("Main render");
  8205. this._renderingManager.render(null, null, true, true);
  8206. BABYLON.Tools.EndPerformanceCounter("Main render");
  8207. // Bounding boxes
  8208. this._boundingBoxRenderer.render();
  8209. // Lens flares
  8210. if (this.lensFlaresEnabled) {
  8211. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8212. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8213. this.lensFlareSystems[lensFlareSystemIndex].render();
  8214. }
  8215. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8216. }
  8217. // Foregrounds
  8218. if (this.layers.length) {
  8219. engine.setDepthBuffer(false);
  8220. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8221. layer = this.layers[layerIndex];
  8222. if (!layer.isBackground) {
  8223. layer.render();
  8224. }
  8225. }
  8226. engine.setDepthBuffer(true);
  8227. }
  8228. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8229. // Finalize frame
  8230. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8231. // Update camera
  8232. this.activeCamera._updateFromScene();
  8233. // Reset some special arrays
  8234. this._renderTargets.reset();
  8235. if (this.afterCameraRender) {
  8236. this.afterCameraRender(this.activeCamera);
  8237. }
  8238. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8239. };
  8240. Scene.prototype._processSubCameras = function (camera) {
  8241. if (camera.subCameras.length === 0) {
  8242. this._renderForCamera(camera);
  8243. return;
  8244. }
  8245. for (var index = 0; index < camera.subCameras.length; index++) {
  8246. this._renderForCamera(camera.subCameras[index]);
  8247. }
  8248. this.activeCamera = camera;
  8249. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8250. // Update camera
  8251. this.activeCamera._updateFromScene();
  8252. };
  8253. Scene.prototype._checkIntersections = function () {
  8254. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8255. var sourceMesh = this._meshesForIntersections.data[index];
  8256. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8257. var action = sourceMesh.actionManager.actions[actionIndex];
  8258. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8259. var otherMesh = action.getTriggerParameter();
  8260. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  8261. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8262. if (areIntersecting && currentIntersectionInProgress === -1) {
  8263. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8264. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8265. sourceMesh._intersectionsInProgress.push(otherMesh);
  8266. } else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8267. sourceMesh._intersectionsInProgress.push(otherMesh);
  8268. }
  8269. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8270. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8271. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8272. if (indexOfOther > -1) {
  8273. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8274. }
  8275. }
  8276. }
  8277. }
  8278. }
  8279. };
  8280. Scene.prototype.render = function () {
  8281. var startDate = BABYLON.Tools.Now;
  8282. this._particlesDuration = 0;
  8283. this._spritesDuration = 0;
  8284. this._activeParticles = 0;
  8285. this._renderDuration = 0;
  8286. this._renderTargetsDuration = 0;
  8287. this._evaluateActiveMeshesDuration = 0;
  8288. this._totalVertices = 0;
  8289. this._activeVertices = 0;
  8290. this._activeBones = 0;
  8291. this.getEngine().resetDrawCalls();
  8292. this._meshesForIntersections.reset();
  8293. this.resetCachedMaterial();
  8294. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8295. // Actions
  8296. if (this.actionManager) {
  8297. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8298. }
  8299. // Before render
  8300. if (this.beforeRender) {
  8301. this.beforeRender();
  8302. }
  8303. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8304. this._onBeforeRenderCallbacks[callbackIndex]();
  8305. }
  8306. // Animations
  8307. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8308. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8309. this._animate();
  8310. // Physics
  8311. if (this._physicsEngine) {
  8312. BABYLON.Tools.StartPerformanceCounter("Physics");
  8313. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8314. BABYLON.Tools.EndPerformanceCounter("Physics");
  8315. }
  8316. // Customs render targets
  8317. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8318. var engine = this.getEngine();
  8319. if (this.renderTargetsEnabled) {
  8320. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8321. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8322. var renderTarget = this.customRenderTargets[customIndex];
  8323. if (renderTarget._shouldRender()) {
  8324. this._renderId++;
  8325. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8326. if (!this.activeCamera)
  8327. throw new Error("Active camera not set");
  8328. // Viewport
  8329. engine.setViewport(this.activeCamera.viewport);
  8330. // Camera
  8331. this.updateTransformMatrix();
  8332. renderTarget.render();
  8333. }
  8334. }
  8335. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8336. this._renderId++;
  8337. }
  8338. if (this.customRenderTargets.length > 0) {
  8339. engine.restoreDefaultFramebuffer();
  8340. }
  8341. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8342. // Procedural textures
  8343. if (this.proceduralTexturesEnabled) {
  8344. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8345. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8346. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8347. if (proceduralTexture._shouldRender()) {
  8348. proceduralTexture.render();
  8349. }
  8350. }
  8351. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8352. }
  8353. // Clear
  8354. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8355. // Shadows
  8356. if (this.shadowsEnabled) {
  8357. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8358. var light = this.lights[lightIndex];
  8359. var shadowGenerator = light.getShadowGenerator();
  8360. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8361. this._renderTargets.push(shadowGenerator.getShadowMap());
  8362. }
  8363. }
  8364. }
  8365. // Depth renderer
  8366. if (this._depthRenderer) {
  8367. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8368. }
  8369. // RenderPipeline
  8370. this.postProcessRenderPipelineManager.update();
  8371. // Multi-cameras?
  8372. if (this.activeCameras.length > 0) {
  8373. var currentRenderId = this._renderId;
  8374. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8375. this._renderId = currentRenderId;
  8376. this._processSubCameras(this.activeCameras[cameraIndex]);
  8377. }
  8378. } else {
  8379. if (!this.activeCamera) {
  8380. throw new Error("No camera defined");
  8381. }
  8382. this._processSubCameras(this.activeCamera);
  8383. }
  8384. // Intersection checks
  8385. this._checkIntersections();
  8386. // Update the audio listener attached to the camera
  8387. this._updateAudioParameters();
  8388. // After render
  8389. if (this.afterRender) {
  8390. this.afterRender();
  8391. }
  8392. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8393. this._onAfterRenderCallbacks[callbackIndex]();
  8394. }
  8395. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8396. this._toBeDisposed.data[index].dispose();
  8397. this._toBeDisposed[index] = null;
  8398. }
  8399. this._toBeDisposed.reset();
  8400. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8401. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8402. };
  8403. Scene.prototype._updateAudioParameters = function () {
  8404. var listeningCamera;
  8405. var audioEngine = this._engine.getAudioEngine();
  8406. if (this.activeCameras.length > 0) {
  8407. listeningCamera = this.activeCameras[0];
  8408. } else {
  8409. listeningCamera = this.activeCamera;
  8410. }
  8411. if (listeningCamera && audioEngine.canUseWebAudio) {
  8412. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8413. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8414. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8415. cameraDirection.normalize();
  8416. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8417. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8418. var sound = this.mainSoundTrack.soundCollection[i];
  8419. if (sound.useCustomAttenuation) {
  8420. sound.updateDistanceFromListener();
  8421. }
  8422. }
  8423. for (i = 0; i < this.soundTracks.length; i++) {
  8424. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8425. sound = this.soundTracks[i].soundCollection[j];
  8426. if (sound.useCustomAttenuation) {
  8427. sound.updateDistanceFromListener();
  8428. }
  8429. }
  8430. }
  8431. }
  8432. };
  8433. Scene.prototype.enableDepthRenderer = function () {
  8434. if (this._depthRenderer) {
  8435. return this._depthRenderer;
  8436. }
  8437. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8438. return this._depthRenderer;
  8439. };
  8440. Scene.prototype.disableDepthRenderer = function () {
  8441. if (!this._depthRenderer) {
  8442. return;
  8443. }
  8444. this._depthRenderer.dispose();
  8445. this._depthRenderer = null;
  8446. };
  8447. Scene.prototype.dispose = function () {
  8448. this.beforeRender = null;
  8449. this.afterRender = null;
  8450. this.skeletons = [];
  8451. this._boundingBoxRenderer.dispose();
  8452. if (this._depthRenderer) {
  8453. this._depthRenderer.dispose();
  8454. }
  8455. // Debug layer
  8456. this.debugLayer.hide();
  8457. // Events
  8458. if (this.onDispose) {
  8459. this.onDispose();
  8460. }
  8461. this._onBeforeRenderCallbacks = [];
  8462. this._onAfterRenderCallbacks = [];
  8463. this.detachControl();
  8464. // Release sounds & sounds tracks
  8465. this.mainSoundTrack.dispose();
  8466. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8467. this.soundTracks[scIndex].dispose();
  8468. }
  8469. // Detach cameras
  8470. var canvas = this._engine.getRenderingCanvas();
  8471. var index;
  8472. for (index = 0; index < this.cameras.length; index++) {
  8473. this.cameras[index].detachControl(canvas);
  8474. }
  8475. while (this.lights.length) {
  8476. this.lights[0].dispose();
  8477. }
  8478. while (this.meshes.length) {
  8479. this.meshes[0].dispose(true);
  8480. }
  8481. while (this.cameras.length) {
  8482. this.cameras[0].dispose();
  8483. }
  8484. while (this.materials.length) {
  8485. this.materials[0].dispose();
  8486. }
  8487. while (this.particleSystems.length) {
  8488. this.particleSystems[0].dispose();
  8489. }
  8490. while (this.spriteManagers.length) {
  8491. this.spriteManagers[0].dispose();
  8492. }
  8493. while (this.layers.length) {
  8494. this.layers[0].dispose();
  8495. }
  8496. while (this.textures.length) {
  8497. this.textures[0].dispose();
  8498. }
  8499. // Post-processes
  8500. this.postProcessManager.dispose();
  8501. // Physics
  8502. if (this._physicsEngine) {
  8503. this.disablePhysicsEngine();
  8504. }
  8505. // Remove from engine
  8506. index = this._engine.scenes.indexOf(this);
  8507. if (index > -1) {
  8508. this._engine.scenes.splice(index, 1);
  8509. }
  8510. this._engine.wipeCaches();
  8511. };
  8512. // Collisions
  8513. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8514. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8515. position.divideToRef(collider.radius, this._scaledPosition);
  8516. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8517. collider.retry = 0;
  8518. collider.initialVelocity = this._scaledVelocity;
  8519. collider.initialPosition = this._scaledPosition;
  8520. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8521. finalPosition.multiplyInPlace(collider.radius);
  8522. };
  8523. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8524. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8525. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8526. if (collider.retry >= maximumRetry) {
  8527. finalPosition.copyFrom(position);
  8528. return;
  8529. }
  8530. collider._initialize(position, velocity, closeDistance);
  8531. for (var index = 0; index < this.meshes.length; index++) {
  8532. var mesh = this.meshes[index];
  8533. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8534. mesh._checkCollision(collider);
  8535. }
  8536. }
  8537. if (!collider.collisionFound) {
  8538. position.addToRef(velocity, finalPosition);
  8539. return;
  8540. }
  8541. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8542. collider._getResponse(position, velocity);
  8543. }
  8544. if (velocity.length() <= closeDistance) {
  8545. finalPosition.copyFrom(position);
  8546. return;
  8547. }
  8548. collider.retry++;
  8549. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8550. };
  8551. // Octrees
  8552. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8553. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8554. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8555. if (!this._selectionOctree) {
  8556. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8557. }
  8558. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8559. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8560. for (var index = 0; index < this.meshes.length; index++) {
  8561. var mesh = this.meshes[index];
  8562. mesh.computeWorldMatrix(true);
  8563. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8564. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8565. BABYLON.Tools.CheckExtends(minBox, min, max);
  8566. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8567. }
  8568. // Update octree
  8569. this._selectionOctree.update(min, max, this.meshes);
  8570. return this._selectionOctree;
  8571. };
  8572. // Picking
  8573. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8574. var engine = this._engine;
  8575. if (!camera) {
  8576. if (!this.activeCamera)
  8577. throw new Error("Active camera not set");
  8578. camera = this.activeCamera;
  8579. }
  8580. var cameraViewport = camera.viewport;
  8581. var viewport = cameraViewport.toGlobal(engine);
  8582. // Moving coordinates to local viewport world
  8583. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8584. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8585. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8586. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8587. };
  8588. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8589. var pickingInfo = null;
  8590. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8591. var mesh = this.meshes[meshIndex];
  8592. if (predicate) {
  8593. if (!predicate(mesh)) {
  8594. continue;
  8595. }
  8596. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8597. continue;
  8598. }
  8599. var world = mesh.getWorldMatrix();
  8600. var ray = rayFunction(world);
  8601. var result = mesh.intersects(ray, fastCheck);
  8602. if (!result || !result.hit)
  8603. continue;
  8604. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8605. continue;
  8606. pickingInfo = result;
  8607. if (fastCheck) {
  8608. break;
  8609. }
  8610. }
  8611. return pickingInfo || new BABYLON.PickingInfo();
  8612. };
  8613. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8614. var _this = this;
  8615. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8616. /// <param name="x">X position on screen</param>
  8617. /// <param name="y">Y position on screen</param>
  8618. /// <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>
  8619. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8620. /// <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>
  8621. return this._internalPick(function (world) {
  8622. return _this.createPickingRay(x, y, world, camera);
  8623. }, predicate, fastCheck);
  8624. };
  8625. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8626. var _this = this;
  8627. return this._internalPick(function (world) {
  8628. if (!_this._pickWithRayInverseMatrix) {
  8629. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8630. }
  8631. world.invertToRef(_this._pickWithRayInverseMatrix);
  8632. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8633. }, predicate, fastCheck);
  8634. };
  8635. Scene.prototype.setPointerOverMesh = function (mesh) {
  8636. if (this._pointerOverMesh === mesh) {
  8637. return;
  8638. }
  8639. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8640. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8641. }
  8642. this._pointerOverMesh = mesh;
  8643. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8644. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8645. }
  8646. };
  8647. Scene.prototype.getPointerOverMesh = function () {
  8648. return this._pointerOverMesh;
  8649. };
  8650. // Physics
  8651. Scene.prototype.getPhysicsEngine = function () {
  8652. return this._physicsEngine;
  8653. };
  8654. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8655. if (this._physicsEngine) {
  8656. return true;
  8657. }
  8658. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8659. if (!this._physicsEngine.isSupported()) {
  8660. this._physicsEngine = null;
  8661. return false;
  8662. }
  8663. this._physicsEngine._initialize(gravity);
  8664. return true;
  8665. };
  8666. Scene.prototype.disablePhysicsEngine = function () {
  8667. if (!this._physicsEngine) {
  8668. return;
  8669. }
  8670. this._physicsEngine.dispose();
  8671. this._physicsEngine = undefined;
  8672. };
  8673. Scene.prototype.isPhysicsEnabled = function () {
  8674. return this._physicsEngine !== undefined;
  8675. };
  8676. Scene.prototype.setGravity = function (gravity) {
  8677. if (!this._physicsEngine) {
  8678. return;
  8679. }
  8680. this._physicsEngine._setGravity(gravity);
  8681. };
  8682. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8683. if (parts.parts) {
  8684. options = parts;
  8685. parts = parts.parts;
  8686. }
  8687. if (!this._physicsEngine) {
  8688. return null;
  8689. }
  8690. for (var index = 0; index < parts.length; index++) {
  8691. var mesh = parts[index].mesh;
  8692. mesh._physicImpostor = parts[index].impostor;
  8693. mesh._physicsMass = options.mass / parts.length;
  8694. mesh._physicsFriction = options.friction;
  8695. mesh._physicRestitution = options.restitution;
  8696. }
  8697. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8698. };
  8699. //ANY
  8700. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8701. for (var index = 0; index < compound.parts.length; index++) {
  8702. var mesh = compound.parts[index].mesh;
  8703. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8704. this._physicsEngine._unregisterMesh(mesh);
  8705. }
  8706. };
  8707. // Tags
  8708. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8709. if (tagsQuery === undefined) {
  8710. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8711. return list;
  8712. }
  8713. var listByTags = [];
  8714. forEach = forEach || (function (item) {
  8715. return;
  8716. });
  8717. for (var i in list) {
  8718. var item = list[i];
  8719. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8720. listByTags.push(item);
  8721. forEach(item);
  8722. }
  8723. }
  8724. return listByTags;
  8725. };
  8726. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  8727. return this._getByTags(this.meshes, tagsQuery, forEach);
  8728. };
  8729. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  8730. return this._getByTags(this.cameras, tagsQuery, forEach);
  8731. };
  8732. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  8733. return this._getByTags(this.lights, tagsQuery, forEach);
  8734. };
  8735. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  8736. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  8737. };
  8738. Scene.FOGMODE_NONE = 0;
  8739. Scene.FOGMODE_EXP = 1;
  8740. Scene.FOGMODE_EXP2 = 2;
  8741. Scene.FOGMODE_LINEAR = 3;
  8742. Scene.MinDeltaTime = 1.0;
  8743. Scene.MaxDeltaTime = 1000.0;
  8744. return Scene;
  8745. })();
  8746. BABYLON.Scene = Scene;
  8747. })(BABYLON || (BABYLON = {}));
  8748. //# sourceMappingURL=babylon.scene.js.map
  8749. var BABYLON;
  8750. (function (BABYLON) {
  8751. var VertexBuffer = (function () {
  8752. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8753. if (engine instanceof BABYLON.Mesh) {
  8754. this._engine = engine.getScene().getEngine();
  8755. } else {
  8756. this._engine = engine;
  8757. }
  8758. this._updatable = updatable;
  8759. this._data = data;
  8760. if (!postponeInternalCreation) {
  8761. this.create();
  8762. }
  8763. this._kind = kind;
  8764. if (stride) {
  8765. this._strideSize = stride;
  8766. return;
  8767. }
  8768. switch (kind) {
  8769. case VertexBuffer.PositionKind:
  8770. this._strideSize = 3;
  8771. break;
  8772. case VertexBuffer.NormalKind:
  8773. this._strideSize = 3;
  8774. break;
  8775. case VertexBuffer.UVKind:
  8776. this._strideSize = 2;
  8777. break;
  8778. case VertexBuffer.UV2Kind:
  8779. this._strideSize = 2;
  8780. break;
  8781. case VertexBuffer.ColorKind:
  8782. this._strideSize = 4;
  8783. break;
  8784. case VertexBuffer.MatricesIndicesKind:
  8785. this._strideSize = 4;
  8786. break;
  8787. case VertexBuffer.MatricesWeightsKind:
  8788. this._strideSize = 4;
  8789. break;
  8790. }
  8791. }
  8792. // Properties
  8793. VertexBuffer.prototype.isUpdatable = function () {
  8794. return this._updatable;
  8795. };
  8796. VertexBuffer.prototype.getData = function () {
  8797. return this._data;
  8798. };
  8799. VertexBuffer.prototype.getBuffer = function () {
  8800. return this._buffer;
  8801. };
  8802. VertexBuffer.prototype.getStrideSize = function () {
  8803. return this._strideSize;
  8804. };
  8805. // Methods
  8806. VertexBuffer.prototype.create = function (data) {
  8807. if (!data && this._buffer) {
  8808. return;
  8809. }
  8810. data = data || this._data;
  8811. if (!this._buffer) {
  8812. if (this._updatable) {
  8813. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8814. } else {
  8815. this._buffer = this._engine.createVertexBuffer(data);
  8816. }
  8817. }
  8818. if (this._updatable) {
  8819. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8820. this._data = data;
  8821. }
  8822. };
  8823. VertexBuffer.prototype.update = function (data) {
  8824. this.create(data);
  8825. };
  8826. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8827. if (!this._buffer) {
  8828. return;
  8829. }
  8830. if (this._updatable) {
  8831. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8832. this._data = null;
  8833. }
  8834. };
  8835. VertexBuffer.prototype.dispose = function () {
  8836. if (!this._buffer) {
  8837. return;
  8838. }
  8839. if (this._engine._releaseBuffer(this._buffer)) {
  8840. this._buffer = null;
  8841. }
  8842. };
  8843. Object.defineProperty(VertexBuffer, "PositionKind", {
  8844. get: function () {
  8845. return VertexBuffer._PositionKind;
  8846. },
  8847. enumerable: true,
  8848. configurable: true
  8849. });
  8850. Object.defineProperty(VertexBuffer, "NormalKind", {
  8851. get: function () {
  8852. return VertexBuffer._NormalKind;
  8853. },
  8854. enumerable: true,
  8855. configurable: true
  8856. });
  8857. Object.defineProperty(VertexBuffer, "UVKind", {
  8858. get: function () {
  8859. return VertexBuffer._UVKind;
  8860. },
  8861. enumerable: true,
  8862. configurable: true
  8863. });
  8864. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8865. get: function () {
  8866. return VertexBuffer._UV2Kind;
  8867. },
  8868. enumerable: true,
  8869. configurable: true
  8870. });
  8871. Object.defineProperty(VertexBuffer, "ColorKind", {
  8872. get: function () {
  8873. return VertexBuffer._ColorKind;
  8874. },
  8875. enumerable: true,
  8876. configurable: true
  8877. });
  8878. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8879. get: function () {
  8880. return VertexBuffer._MatricesIndicesKind;
  8881. },
  8882. enumerable: true,
  8883. configurable: true
  8884. });
  8885. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8886. get: function () {
  8887. return VertexBuffer._MatricesWeightsKind;
  8888. },
  8889. enumerable: true,
  8890. configurable: true
  8891. });
  8892. VertexBuffer._PositionKind = "position";
  8893. VertexBuffer._NormalKind = "normal";
  8894. VertexBuffer._UVKind = "uv";
  8895. VertexBuffer._UV2Kind = "uv2";
  8896. VertexBuffer._ColorKind = "color";
  8897. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8898. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8899. return VertexBuffer;
  8900. })();
  8901. BABYLON.VertexBuffer = VertexBuffer;
  8902. })(BABYLON || (BABYLON = {}));
  8903. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8904. var BABYLON;
  8905. (function (BABYLON) {
  8906. var AbstractMesh = (function (_super) {
  8907. __extends(AbstractMesh, _super);
  8908. function AbstractMesh(name, scene) {
  8909. _super.call(this, name, scene);
  8910. // Properties
  8911. this.definedFacingForward = true;
  8912. this.position = new BABYLON.Vector3(0, 0, 0);
  8913. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8914. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8915. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8916. this.visibility = 1.0;
  8917. this.alphaIndex = Number.MAX_VALUE;
  8918. this.infiniteDistance = false;
  8919. this.isVisible = true;
  8920. this.isPickable = true;
  8921. this.showBoundingBox = false;
  8922. this.showSubMeshesBoundingBox = false;
  8923. this.onDispose = null;
  8924. this.checkCollisions = false;
  8925. this.isBlocker = false;
  8926. this.renderingGroupId = 0;
  8927. this.receiveShadows = false;
  8928. this.renderOutline = false;
  8929. this.outlineColor = BABYLON.Color3.Red();
  8930. this.outlineWidth = 0.02;
  8931. this.renderOverlay = false;
  8932. this.overlayColor = BABYLON.Color3.Red();
  8933. this.overlayAlpha = 0.5;
  8934. this.hasVertexAlpha = false;
  8935. this.useVertexColors = true;
  8936. this.applyFog = true;
  8937. this.useOctreeForRenderingSelection = true;
  8938. this.useOctreeForPicking = true;
  8939. this.useOctreeForCollisions = true;
  8940. this.layerMask = 0xFFFFFFFF;
  8941. // Physics
  8942. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8943. // Collisions
  8944. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8945. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8946. this._collider = new BABYLON.Collider();
  8947. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8948. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8949. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8950. // Cache
  8951. this._localScaling = BABYLON.Matrix.Zero();
  8952. this._localRotation = BABYLON.Matrix.Zero();
  8953. this._localTranslation = BABYLON.Matrix.Zero();
  8954. this._localBillboard = BABYLON.Matrix.Zero();
  8955. this._localPivotScaling = BABYLON.Matrix.Zero();
  8956. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8957. this._localWorld = BABYLON.Matrix.Zero();
  8958. this._worldMatrix = BABYLON.Matrix.Zero();
  8959. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8960. this._absolutePosition = BABYLON.Vector3.Zero();
  8961. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8962. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8963. this._isDirty = false;
  8964. this._pivotMatrix = BABYLON.Matrix.Identity();
  8965. this._isDisposed = false;
  8966. this._renderId = 0;
  8967. this._intersectionsInProgress = new Array();
  8968. this._onAfterWorldMatrixUpdate = new Array();
  8969. scene.meshes.push(this);
  8970. }
  8971. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8972. get: function () {
  8973. return AbstractMesh._BILLBOARDMODE_NONE;
  8974. },
  8975. enumerable: true,
  8976. configurable: true
  8977. });
  8978. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8979. get: function () {
  8980. return AbstractMesh._BILLBOARDMODE_X;
  8981. },
  8982. enumerable: true,
  8983. configurable: true
  8984. });
  8985. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8986. get: function () {
  8987. return AbstractMesh._BILLBOARDMODE_Y;
  8988. },
  8989. enumerable: true,
  8990. configurable: true
  8991. });
  8992. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8993. get: function () {
  8994. return AbstractMesh._BILLBOARDMODE_Z;
  8995. },
  8996. enumerable: true,
  8997. configurable: true
  8998. });
  8999. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9000. get: function () {
  9001. return AbstractMesh._BILLBOARDMODE_ALL;
  9002. },
  9003. enumerable: true,
  9004. configurable: true
  9005. });
  9006. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9007. // Methods
  9008. get: function () {
  9009. return false;
  9010. },
  9011. enumerable: true,
  9012. configurable: true
  9013. });
  9014. AbstractMesh.prototype.getLOD = function (camera) {
  9015. return this;
  9016. };
  9017. AbstractMesh.prototype.getTotalVertices = function () {
  9018. return 0;
  9019. };
  9020. AbstractMesh.prototype.getIndices = function () {
  9021. return null;
  9022. };
  9023. AbstractMesh.prototype.getVerticesData = function (kind) {
  9024. return null;
  9025. };
  9026. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9027. return false;
  9028. };
  9029. AbstractMesh.prototype.getBoundingInfo = function () {
  9030. if (this._masterMesh) {
  9031. return this._masterMesh.getBoundingInfo();
  9032. }
  9033. if (!this._boundingInfo) {
  9034. this._updateBoundingInfo();
  9035. }
  9036. return this._boundingInfo;
  9037. };
  9038. AbstractMesh.prototype._preActivate = function () {
  9039. };
  9040. AbstractMesh.prototype._activate = function (renderId) {
  9041. this._renderId = renderId;
  9042. };
  9043. AbstractMesh.prototype.getWorldMatrix = function () {
  9044. if (this._masterMesh) {
  9045. return this._masterMesh.getWorldMatrix();
  9046. }
  9047. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9048. this.computeWorldMatrix();
  9049. }
  9050. return this._worldMatrix;
  9051. };
  9052. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9053. get: function () {
  9054. return this._worldMatrix;
  9055. },
  9056. enumerable: true,
  9057. configurable: true
  9058. });
  9059. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9060. get: function () {
  9061. return this._absolutePosition;
  9062. },
  9063. enumerable: true,
  9064. configurable: true
  9065. });
  9066. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9067. if (!this.rotationQuaternion) {
  9068. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9069. this.rotation = BABYLON.Vector3.Zero();
  9070. }
  9071. if (!space || space == 0 /* LOCAL */) {
  9072. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9073. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9074. } else {
  9075. if (this.parent) {
  9076. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9077. invertParentWorldMatrix.invert();
  9078. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9079. }
  9080. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9081. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9082. }
  9083. };
  9084. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9085. var displacementVector = axis.scale(distance);
  9086. if (!space || space == 0 /* LOCAL */) {
  9087. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9088. this.setPositionWithLocalVector(tempV3);
  9089. } else {
  9090. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9091. }
  9092. };
  9093. AbstractMesh.prototype.getAbsolutePosition = function () {
  9094. this.computeWorldMatrix();
  9095. return this._absolutePosition;
  9096. };
  9097. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9098. if (!absolutePosition) {
  9099. return;
  9100. }
  9101. var absolutePositionX;
  9102. var absolutePositionY;
  9103. var absolutePositionZ;
  9104. if (absolutePosition.x === undefined) {
  9105. if (arguments.length < 3) {
  9106. return;
  9107. }
  9108. absolutePositionX = arguments[0];
  9109. absolutePositionY = arguments[1];
  9110. absolutePositionZ = arguments[2];
  9111. } else {
  9112. absolutePositionX = absolutePosition.x;
  9113. absolutePositionY = absolutePosition.y;
  9114. absolutePositionZ = absolutePosition.z;
  9115. }
  9116. if (this.parent) {
  9117. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9118. invertParentWorldMatrix.invert();
  9119. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9120. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9121. } else {
  9122. this.position.x = absolutePositionX;
  9123. this.position.y = absolutePositionY;
  9124. this.position.z = absolutePositionZ;
  9125. }
  9126. };
  9127. // ================================== Point of View Movement =================================
  9128. /**
  9129. * Perform relative position change from the point of view of behind the front of the mesh.
  9130. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9131. * Supports definition of mesh facing forward or backward.
  9132. * @param {number} amountRight
  9133. * @param {number} amountUp
  9134. * @param {number} amountForward
  9135. */
  9136. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9137. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9138. };
  9139. /**
  9140. * Calculate relative position change from the point of view of behind the front of the mesh.
  9141. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9142. * Supports definition of mesh facing forward or backward.
  9143. * @param {number} amountRight
  9144. * @param {number} amountUp
  9145. * @param {number} amountForward
  9146. */
  9147. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9148. var rotMatrix = new BABYLON.Matrix();
  9149. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9150. rotQuaternion.toRotationMatrix(rotMatrix);
  9151. var translationDelta = BABYLON.Vector3.Zero();
  9152. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9153. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9154. return translationDelta;
  9155. };
  9156. // ================================== Point of View Rotation =================================
  9157. /**
  9158. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9159. * Supports definition of mesh facing forward or backward.
  9160. * @param {number} flipBack
  9161. * @param {number} twirlClockwise
  9162. * @param {number} tiltRight
  9163. */
  9164. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9165. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9166. };
  9167. /**
  9168. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9169. * Supports definition of mesh facing forward or backward.
  9170. * @param {number} flipBack
  9171. * @param {number} twirlClockwise
  9172. * @param {number} tiltRight
  9173. */
  9174. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9175. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9176. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9177. };
  9178. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9179. this._pivotMatrix = matrix;
  9180. this._cache.pivotMatrixUpdated = true;
  9181. };
  9182. AbstractMesh.prototype.getPivotMatrix = function () {
  9183. return this._pivotMatrix;
  9184. };
  9185. AbstractMesh.prototype._isSynchronized = function () {
  9186. if (this._isDirty) {
  9187. return false;
  9188. }
  9189. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9190. return false;
  9191. if (this._cache.pivotMatrixUpdated) {
  9192. return false;
  9193. }
  9194. if (this.infiniteDistance) {
  9195. return false;
  9196. }
  9197. if (!this._cache.position.equals(this.position))
  9198. return false;
  9199. if (this.rotationQuaternion) {
  9200. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9201. return false;
  9202. } else {
  9203. if (!this._cache.rotation.equals(this.rotation))
  9204. return false;
  9205. }
  9206. if (!this._cache.scaling.equals(this.scaling))
  9207. return false;
  9208. return true;
  9209. };
  9210. AbstractMesh.prototype._initCache = function () {
  9211. _super.prototype._initCache.call(this);
  9212. this._cache.localMatrixUpdated = false;
  9213. this._cache.position = BABYLON.Vector3.Zero();
  9214. this._cache.scaling = BABYLON.Vector3.Zero();
  9215. this._cache.rotation = BABYLON.Vector3.Zero();
  9216. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9217. };
  9218. AbstractMesh.prototype.markAsDirty = function (property) {
  9219. if (property === "rotation") {
  9220. this.rotationQuaternion = null;
  9221. }
  9222. this._currentRenderId = Number.MAX_VALUE;
  9223. this._isDirty = true;
  9224. };
  9225. AbstractMesh.prototype._updateBoundingInfo = function () {
  9226. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9227. this._boundingInfo._update(this.worldMatrixFromCache);
  9228. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9229. };
  9230. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9231. if (!this.subMeshes) {
  9232. return;
  9233. }
  9234. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9235. var subMesh = this.subMeshes[subIndex];
  9236. subMesh.updateBoundingInfo(matrix);
  9237. }
  9238. };
  9239. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9240. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9241. return this._worldMatrix;
  9242. }
  9243. this._cache.position.copyFrom(this.position);
  9244. this._cache.scaling.copyFrom(this.scaling);
  9245. this._cache.pivotMatrixUpdated = false;
  9246. this._currentRenderId = this.getScene().getRenderId();
  9247. this._isDirty = false;
  9248. // Scaling
  9249. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9250. // Rotation
  9251. if (this.rotationQuaternion) {
  9252. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9253. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9254. } else {
  9255. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9256. this._cache.rotation.copyFrom(this.rotation);
  9257. }
  9258. // Translation
  9259. if (this.infiniteDistance && !this.parent) {
  9260. var camera = this.getScene().activeCamera;
  9261. var cameraWorldMatrix = camera.getWorldMatrix();
  9262. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9263. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9264. } else {
  9265. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9266. }
  9267. // Composing transformations
  9268. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9269. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9270. // Billboarding
  9271. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9272. var localPosition = this.position.clone();
  9273. var zero = this.getScene().activeCamera.position.clone();
  9274. if (this.parent && this.parent.position) {
  9275. localPosition.addInPlace(this.parent.position);
  9276. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9277. }
  9278. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9279. zero = this.getScene().activeCamera.position;
  9280. } else {
  9281. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9282. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9283. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9284. zero.y = localPosition.y + 0.001;
  9285. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9286. zero.z = localPosition.z + 0.001;
  9287. }
  9288. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9289. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9290. this._localBillboard.invert();
  9291. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9292. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9293. }
  9294. // Local world
  9295. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9296. // Parent
  9297. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9298. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9299. } else {
  9300. this._worldMatrix.copyFrom(this._localWorld);
  9301. }
  9302. // Bounding info
  9303. this._updateBoundingInfo();
  9304. // Absolute position
  9305. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9306. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9307. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9308. }
  9309. return this._worldMatrix;
  9310. };
  9311. /**
  9312. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9313. * @param func: callback function to add
  9314. */
  9315. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9316. this._onAfterWorldMatrixUpdate.push(func);
  9317. };
  9318. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9319. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9320. if (index > -1) {
  9321. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9322. }
  9323. };
  9324. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9325. this.computeWorldMatrix();
  9326. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9327. };
  9328. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9329. this.computeWorldMatrix();
  9330. var invLocalWorldMatrix = this._localWorld.clone();
  9331. invLocalWorldMatrix.invert();
  9332. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9333. };
  9334. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9335. this.computeWorldMatrix();
  9336. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9337. };
  9338. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9339. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9340. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9341. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9342. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9343. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9344. /// <returns>Mesh oriented towards targetMesh</returns>
  9345. yawCor = yawCor || 0; // default to zero if undefined
  9346. pitchCor = pitchCor || 0;
  9347. rollCor = rollCor || 0;
  9348. var dv = targetPoint.subtract(this.position);
  9349. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9350. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9351. var pitch = Math.atan2(dv.y, len);
  9352. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9353. };
  9354. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9355. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9356. return false;
  9357. }
  9358. return true;
  9359. };
  9360. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9361. if (!camera) {
  9362. camera = this.getScene().activeCamera;
  9363. }
  9364. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9365. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9366. return false;
  9367. }
  9368. return true;
  9369. };
  9370. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9371. if (!this._boundingInfo || !mesh._boundingInfo) {
  9372. return false;
  9373. }
  9374. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9375. };
  9376. AbstractMesh.prototype.intersectsPoint = function (point) {
  9377. if (!this._boundingInfo) {
  9378. return false;
  9379. }
  9380. return this._boundingInfo.intersectsPoint(point);
  9381. };
  9382. // Physics
  9383. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9384. var physicsEngine = this.getScene().getPhysicsEngine();
  9385. if (!physicsEngine) {
  9386. return;
  9387. }
  9388. if (impostor.impostor) {
  9389. // Old API
  9390. options = impostor;
  9391. impostor = impostor.impostor;
  9392. }
  9393. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9394. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9395. physicsEngine._unregisterMesh(this);
  9396. return;
  9397. }
  9398. options.mass = options.mass || 0;
  9399. options.friction = options.friction || 0.2;
  9400. options.restitution = options.restitution || 0.2;
  9401. this._physicImpostor = impostor;
  9402. this._physicsMass = options.mass;
  9403. this._physicsFriction = options.friction;
  9404. this._physicRestitution = options.restitution;
  9405. return physicsEngine._registerMesh(this, impostor, options);
  9406. };
  9407. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9408. if (!this._physicImpostor) {
  9409. return BABYLON.PhysicsEngine.NoImpostor;
  9410. }
  9411. return this._physicImpostor;
  9412. };
  9413. AbstractMesh.prototype.getPhysicsMass = function () {
  9414. if (!this._physicsMass) {
  9415. return 0;
  9416. }
  9417. return this._physicsMass;
  9418. };
  9419. AbstractMesh.prototype.getPhysicsFriction = function () {
  9420. if (!this._physicsFriction) {
  9421. return 0;
  9422. }
  9423. return this._physicsFriction;
  9424. };
  9425. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9426. if (!this._physicRestitution) {
  9427. return 0;
  9428. }
  9429. return this._physicRestitution;
  9430. };
  9431. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9432. if (!camera) {
  9433. camera = this.getScene().activeCamera;
  9434. }
  9435. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9436. };
  9437. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9438. if (!camera) {
  9439. camera = this.getScene().activeCamera;
  9440. }
  9441. return this.absolutePosition.subtract(camera.position).length();
  9442. };
  9443. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9444. if (!this._physicImpostor) {
  9445. return;
  9446. }
  9447. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9448. };
  9449. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9450. if (!this._physicImpostor) {
  9451. return;
  9452. }
  9453. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9454. };
  9455. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9456. if (!this._physicImpostor) {
  9457. return;
  9458. }
  9459. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9460. };
  9461. // Collisions
  9462. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9463. var globalPosition = this.getAbsolutePosition();
  9464. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9465. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9466. this._collider.radius = this.ellipsoid;
  9467. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9468. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9469. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9470. this.position.addInPlace(this._diffPositionForCollisions);
  9471. }
  9472. };
  9473. // Submeshes octree
  9474. /**
  9475. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9476. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9477. */
  9478. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9479. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  9480. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  9481. if (!this._submeshesOctree) {
  9482. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9483. }
  9484. this.computeWorldMatrix(true);
  9485. // Update octree
  9486. var bbox = this.getBoundingInfo().boundingBox;
  9487. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9488. return this._submeshesOctree;
  9489. };
  9490. // Collisions
  9491. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9492. this._generatePointsArray();
  9493. // Transformation
  9494. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9495. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9496. subMesh._lastColliderWorldVertices = [];
  9497. subMesh._trianglePlanes = [];
  9498. var start = subMesh.verticesStart;
  9499. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9500. for (var i = start; i < end; i++) {
  9501. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9502. }
  9503. }
  9504. // Collide
  9505. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9506. };
  9507. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9508. var subMeshes;
  9509. var len;
  9510. // Octrees
  9511. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9512. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9513. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9514. len = intersections.length;
  9515. subMeshes = intersections.data;
  9516. } else {
  9517. subMeshes = this.subMeshes;
  9518. len = subMeshes.length;
  9519. }
  9520. for (var index = 0; index < len; index++) {
  9521. var subMesh = subMeshes[index];
  9522. // Bounding test
  9523. if (len > 1 && !subMesh._checkCollision(collider))
  9524. continue;
  9525. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9526. }
  9527. };
  9528. AbstractMesh.prototype._checkCollision = function (collider) {
  9529. // Bounding box test
  9530. if (!this._boundingInfo._checkCollision(collider))
  9531. return;
  9532. // Transformation matrix
  9533. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9534. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9535. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9536. };
  9537. // Picking
  9538. AbstractMesh.prototype._generatePointsArray = function () {
  9539. return false;
  9540. };
  9541. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9542. var pickingInfo = new BABYLON.PickingInfo();
  9543. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9544. return pickingInfo;
  9545. }
  9546. if (!this._generatePointsArray()) {
  9547. return pickingInfo;
  9548. }
  9549. var intersectInfo = null;
  9550. // Octrees
  9551. var subMeshes;
  9552. var len;
  9553. if (this._submeshesOctree && this.useOctreeForPicking) {
  9554. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9555. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9556. len = intersections.length;
  9557. subMeshes = intersections.data;
  9558. } else {
  9559. subMeshes = this.subMeshes;
  9560. len = subMeshes.length;
  9561. }
  9562. for (var index = 0; index < len; index++) {
  9563. var subMesh = subMeshes[index];
  9564. // Bounding test
  9565. if (len > 1 && !subMesh.canIntersects(ray))
  9566. continue;
  9567. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9568. if (currentIntersectInfo) {
  9569. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9570. intersectInfo = currentIntersectInfo;
  9571. if (fastCheck) {
  9572. break;
  9573. }
  9574. }
  9575. }
  9576. }
  9577. if (intersectInfo) {
  9578. // Get picked point
  9579. var world = this.getWorldMatrix();
  9580. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9581. var direction = ray.direction.clone();
  9582. direction.normalize();
  9583. direction = direction.scale(intersectInfo.distance);
  9584. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9585. var pickedPoint = worldOrigin.add(worldDirection);
  9586. // Return result
  9587. pickingInfo.hit = true;
  9588. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9589. pickingInfo.pickedPoint = pickedPoint;
  9590. pickingInfo.pickedMesh = this;
  9591. pickingInfo.bu = intersectInfo.bu;
  9592. pickingInfo.bv = intersectInfo.bv;
  9593. pickingInfo.faceId = intersectInfo.faceId;
  9594. return pickingInfo;
  9595. }
  9596. return pickingInfo;
  9597. };
  9598. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9599. return null;
  9600. };
  9601. AbstractMesh.prototype.releaseSubMeshes = function () {
  9602. if (this.subMeshes) {
  9603. while (this.subMeshes.length) {
  9604. this.subMeshes[0].dispose();
  9605. }
  9606. } else {
  9607. this.subMeshes = new Array();
  9608. }
  9609. };
  9610. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9611. // Physics
  9612. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9613. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9614. }
  9615. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9616. var other = this._intersectionsInProgress[index];
  9617. var pos = other._intersectionsInProgress.indexOf(this);
  9618. other._intersectionsInProgress.splice(pos, 1);
  9619. }
  9620. this._intersectionsInProgress = [];
  9621. // SubMeshes
  9622. this.releaseSubMeshes();
  9623. // Remove from scene
  9624. var index = this.getScene().meshes.indexOf(this);
  9625. if (index != -1) {
  9626. // Remove from the scene if mesh found
  9627. this.getScene().meshes.splice(index, 1);
  9628. }
  9629. if (!doNotRecurse) {
  9630. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9631. if (this.getScene().particleSystems[index].emitter == this) {
  9632. this.getScene().particleSystems[index].dispose();
  9633. index--;
  9634. }
  9635. }
  9636. // Children
  9637. var objects = this.getScene().meshes.slice(0);
  9638. for (index = 0; index < objects.length; index++) {
  9639. if (objects[index].parent == this) {
  9640. objects[index].dispose();
  9641. }
  9642. }
  9643. } else {
  9644. for (index = 0; index < this.getScene().meshes.length; index++) {
  9645. var obj = this.getScene().meshes[index];
  9646. if (obj.parent === this) {
  9647. obj.parent = null;
  9648. obj.computeWorldMatrix(true);
  9649. }
  9650. }
  9651. }
  9652. this._onAfterWorldMatrixUpdate = [];
  9653. this._isDisposed = true;
  9654. // Callback
  9655. if (this.onDispose) {
  9656. this.onDispose();
  9657. }
  9658. };
  9659. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9660. AbstractMesh._BILLBOARDMODE_X = 1;
  9661. AbstractMesh._BILLBOARDMODE_Y = 2;
  9662. AbstractMesh._BILLBOARDMODE_Z = 4;
  9663. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9664. return AbstractMesh;
  9665. })(BABYLON.Node);
  9666. BABYLON.AbstractMesh = AbstractMesh;
  9667. })(BABYLON || (BABYLON = {}));
  9668. //# sourceMappingURL=babylon.abstractMesh.js.map
  9669. var BABYLON;
  9670. (function (BABYLON) {
  9671. var _InstancesBatch = (function () {
  9672. function _InstancesBatch() {
  9673. this.mustReturn = false;
  9674. this.visibleInstances = new Array();
  9675. this.renderSelf = new Array();
  9676. }
  9677. return _InstancesBatch;
  9678. })();
  9679. BABYLON._InstancesBatch = _InstancesBatch;
  9680. var Mesh = (function (_super) {
  9681. __extends(Mesh, _super);
  9682. /**
  9683. * @constructor
  9684. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9685. * @param {Scene} scene - The scene to add this mesh to.
  9686. * @param {Node} parent - The parent of this mesh, if it has one
  9687. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9688. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9689. * When false, achieved by calling a clone(), also passing False.
  9690. * This will make creation of children, recursive.
  9691. */
  9692. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9693. if (typeof parent === "undefined") { parent = null; }
  9694. _super.call(this, name, scene);
  9695. // Members
  9696. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9697. this.instances = new Array();
  9698. this._LODLevels = new Array();
  9699. this._onBeforeRenderCallbacks = new Array();
  9700. this._onAfterRenderCallbacks = new Array();
  9701. this._visibleInstances = {};
  9702. this._renderIdForInstances = new Array();
  9703. this._batchCache = new _InstancesBatch();
  9704. this._instancesBufferSize = 32 * 16 * 4;
  9705. if (source) {
  9706. // Geometry
  9707. if (source._geometry) {
  9708. source._geometry.applyToMesh(this);
  9709. }
  9710. // Deep copy
  9711. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9712. // Material
  9713. this.material = source.material;
  9714. if (!doNotCloneChildren) {
  9715. for (var index = 0; index < scene.meshes.length; index++) {
  9716. var mesh = scene.meshes[index];
  9717. if (mesh.parent === source) {
  9718. // doNotCloneChildren is always going to be False
  9719. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9720. }
  9721. }
  9722. }
  9723. for (index = 0; index < scene.particleSystems.length; index++) {
  9724. var system = scene.particleSystems[index];
  9725. if (system.emitter === source) {
  9726. system.clone(system.name, this);
  9727. }
  9728. }
  9729. this.computeWorldMatrix(true);
  9730. }
  9731. // Parent
  9732. if (parent !== null) {
  9733. this.parent = parent;
  9734. }
  9735. }
  9736. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9737. // Methods
  9738. get: function () {
  9739. return this._LODLevels.length > 0;
  9740. },
  9741. enumerable: true,
  9742. configurable: true
  9743. });
  9744. Mesh.prototype._sortLODLevels = function () {
  9745. this._LODLevels.sort(function (a, b) {
  9746. if (a.distance < b.distance) {
  9747. return 1;
  9748. }
  9749. if (a.distance > b.distance) {
  9750. return -1;
  9751. }
  9752. return 0;
  9753. });
  9754. };
  9755. /**
  9756. * Add a mesh as LOD level triggered at the given distance.
  9757. * @param {number} distance - the distance from the center of the object to show this level
  9758. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  9759. * @return {BABYLON.Mesh} this mesh (for chaining)
  9760. */
  9761. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9762. if (mesh && mesh._masterMesh) {
  9763. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9764. return this;
  9765. }
  9766. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9767. this._LODLevels.push(level);
  9768. if (mesh) {
  9769. mesh._masterMesh = this;
  9770. }
  9771. this._sortLODLevels();
  9772. return this;
  9773. };
  9774. /**
  9775. * Remove a mesh from the LOD array
  9776. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  9777. * @return {BABYLON.Mesh} this mesh (for chaining)
  9778. */
  9779. Mesh.prototype.removeLODLevel = function (mesh) {
  9780. for (var index = 0; index < this._LODLevels.length; index++) {
  9781. if (this._LODLevels[index].mesh === mesh) {
  9782. this._LODLevels.splice(index, 1);
  9783. if (mesh) {
  9784. mesh._masterMesh = null;
  9785. }
  9786. }
  9787. }
  9788. this._sortLODLevels();
  9789. return this;
  9790. };
  9791. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9792. if (!this._LODLevels || this._LODLevels.length === 0) {
  9793. return this;
  9794. }
  9795. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9796. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9797. return this;
  9798. }
  9799. for (var index = 0; index < this._LODLevels.length; index++) {
  9800. var level = this._LODLevels[index];
  9801. if (level.distance < distanceToCamera) {
  9802. if (level.mesh) {
  9803. level.mesh._preActivate();
  9804. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9805. }
  9806. return level.mesh;
  9807. }
  9808. }
  9809. return this;
  9810. };
  9811. Object.defineProperty(Mesh.prototype, "geometry", {
  9812. get: function () {
  9813. return this._geometry;
  9814. },
  9815. enumerable: true,
  9816. configurable: true
  9817. });
  9818. Mesh.prototype.getTotalVertices = function () {
  9819. if (!this._geometry) {
  9820. return 0;
  9821. }
  9822. return this._geometry.getTotalVertices();
  9823. };
  9824. Mesh.prototype.getVerticesData = function (kind) {
  9825. if (!this._geometry) {
  9826. return null;
  9827. }
  9828. return this._geometry.getVerticesData(kind);
  9829. };
  9830. Mesh.prototype.getVertexBuffer = function (kind) {
  9831. if (!this._geometry) {
  9832. return undefined;
  9833. }
  9834. return this._geometry.getVertexBuffer(kind);
  9835. };
  9836. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9837. if (!this._geometry) {
  9838. if (this._delayInfo) {
  9839. return this._delayInfo.indexOf(kind) !== -1;
  9840. }
  9841. return false;
  9842. }
  9843. return this._geometry.isVerticesDataPresent(kind);
  9844. };
  9845. Mesh.prototype.getVerticesDataKinds = function () {
  9846. if (!this._geometry) {
  9847. var result = [];
  9848. if (this._delayInfo) {
  9849. for (var kind in this._delayInfo) {
  9850. result.push(kind);
  9851. }
  9852. }
  9853. return result;
  9854. }
  9855. return this._geometry.getVerticesDataKinds();
  9856. };
  9857. Mesh.prototype.getTotalIndices = function () {
  9858. if (!this._geometry) {
  9859. return 0;
  9860. }
  9861. return this._geometry.getTotalIndices();
  9862. };
  9863. Mesh.prototype.getIndices = function () {
  9864. if (!this._geometry) {
  9865. return [];
  9866. }
  9867. return this._geometry.getIndices();
  9868. };
  9869. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9870. get: function () {
  9871. return this._masterMesh !== null && this._masterMesh !== undefined;
  9872. },
  9873. enumerable: true,
  9874. configurable: true
  9875. });
  9876. Mesh.prototype.isReady = function () {
  9877. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9878. return false;
  9879. }
  9880. return _super.prototype.isReady.call(this);
  9881. };
  9882. Mesh.prototype.isDisposed = function () {
  9883. return this._isDisposed;
  9884. };
  9885. // Methods
  9886. Mesh.prototype._preActivate = function () {
  9887. var sceneRenderId = this.getScene().getRenderId();
  9888. if (this._preActivateId == sceneRenderId) {
  9889. return;
  9890. }
  9891. this._preActivateId = sceneRenderId;
  9892. this._visibleInstances = null;
  9893. };
  9894. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9895. if (!this._visibleInstances) {
  9896. this._visibleInstances = {};
  9897. this._visibleInstances.defaultRenderId = renderId;
  9898. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9899. }
  9900. if (!this._visibleInstances[renderId]) {
  9901. this._visibleInstances[renderId] = new Array();
  9902. }
  9903. this._visibleInstances[renderId].push(instance);
  9904. };
  9905. Mesh.prototype.refreshBoundingInfo = function () {
  9906. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9907. if (data) {
  9908. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9909. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9910. }
  9911. if (this.subMeshes) {
  9912. for (var index = 0; index < this.subMeshes.length; index++) {
  9913. this.subMeshes[index].refreshBoundingInfo();
  9914. }
  9915. }
  9916. this._updateBoundingInfo();
  9917. };
  9918. Mesh.prototype._createGlobalSubMesh = function () {
  9919. var totalVertices = this.getTotalVertices();
  9920. if (!totalVertices || !this.getIndices()) {
  9921. return null;
  9922. }
  9923. this.releaseSubMeshes();
  9924. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9925. };
  9926. Mesh.prototype.subdivide = function (count) {
  9927. if (count < 1) {
  9928. return;
  9929. }
  9930. var totalIndices = this.getTotalIndices();
  9931. var subdivisionSize = (totalIndices / count) | 0;
  9932. var offset = 0;
  9933. while (subdivisionSize % 3 != 0) {
  9934. subdivisionSize++;
  9935. }
  9936. this.releaseSubMeshes();
  9937. for (var index = 0; index < count; index++) {
  9938. if (offset >= totalIndices) {
  9939. break;
  9940. }
  9941. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9942. offset += subdivisionSize;
  9943. }
  9944. this.synchronizeInstances();
  9945. };
  9946. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9947. if (kind instanceof Array) {
  9948. var temp = data;
  9949. data = kind;
  9950. kind = temp;
  9951. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9952. }
  9953. if (!this._geometry) {
  9954. var vertexData = new BABYLON.VertexData();
  9955. vertexData.set(data, kind);
  9956. var scene = this.getScene();
  9957. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9958. } else {
  9959. this._geometry.setVerticesData(kind, data, updatable, stride);
  9960. }
  9961. };
  9962. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9963. if (!this._geometry) {
  9964. return;
  9965. }
  9966. if (!makeItUnique) {
  9967. this._geometry.updateVerticesData(kind, data, updateExtends);
  9968. } else {
  9969. this.makeGeometryUnique();
  9970. this.updateVerticesData(kind, data, updateExtends, false);
  9971. }
  9972. };
  9973. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9974. if (!this._geometry) {
  9975. return;
  9976. }
  9977. if (!makeItUnique) {
  9978. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9979. } else {
  9980. this.makeGeometryUnique();
  9981. this.updateVerticesDataDirectly(kind, data, offset, false);
  9982. }
  9983. };
  9984. Mesh.prototype.makeGeometryUnique = function () {
  9985. if (!this._geometry) {
  9986. return;
  9987. }
  9988. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9989. geometry.applyToMesh(this);
  9990. };
  9991. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9992. if (!this._geometry) {
  9993. var vertexData = new BABYLON.VertexData();
  9994. vertexData.indices = indices;
  9995. var scene = this.getScene();
  9996. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9997. } else {
  9998. this._geometry.setIndices(indices, totalVertices);
  9999. }
  10000. };
  10001. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10002. var engine = this.getScene().getEngine();
  10003. // Wireframe
  10004. var indexToBind;
  10005. switch (fillMode) {
  10006. case BABYLON.Material.PointFillMode:
  10007. indexToBind = null;
  10008. break;
  10009. case BABYLON.Material.WireFrameFillMode:
  10010. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10011. break;
  10012. default:
  10013. case BABYLON.Material.TriangleFillMode:
  10014. indexToBind = this._geometry.getIndexBuffer();
  10015. break;
  10016. }
  10017. // VBOs
  10018. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10019. };
  10020. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10021. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10022. return;
  10023. }
  10024. var engine = this.getScene().getEngine();
  10025. switch (fillMode) {
  10026. case BABYLON.Material.PointFillMode:
  10027. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10028. break;
  10029. case BABYLON.Material.WireFrameFillMode:
  10030. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10031. break;
  10032. default:
  10033. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10034. }
  10035. };
  10036. Mesh.prototype.registerBeforeRender = function (func) {
  10037. this._onBeforeRenderCallbacks.push(func);
  10038. };
  10039. Mesh.prototype.unregisterBeforeRender = function (func) {
  10040. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10041. if (index > -1) {
  10042. this._onBeforeRenderCallbacks.splice(index, 1);
  10043. }
  10044. };
  10045. Mesh.prototype.registerAfterRender = function (func) {
  10046. this._onAfterRenderCallbacks.push(func);
  10047. };
  10048. Mesh.prototype.unregisterAfterRender = function (func) {
  10049. var index = this._onAfterRenderCallbacks.indexOf(func);
  10050. if (index > -1) {
  10051. this._onAfterRenderCallbacks.splice(index, 1);
  10052. }
  10053. };
  10054. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10055. var scene = this.getScene();
  10056. this._batchCache.mustReturn = false;
  10057. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10058. this._batchCache.visibleInstances[subMeshId] = null;
  10059. if (this._visibleInstances) {
  10060. var currentRenderId = scene.getRenderId();
  10061. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10062. var selfRenderId = this._renderId;
  10063. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10064. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10065. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10066. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10067. }
  10068. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10069. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10070. this._batchCache.mustReturn = true;
  10071. return this._batchCache;
  10072. }
  10073. if (currentRenderId !== selfRenderId) {
  10074. this._batchCache.renderSelf[subMeshId] = false;
  10075. }
  10076. }
  10077. this._renderIdForInstances[subMeshId] = currentRenderId;
  10078. }
  10079. return this._batchCache;
  10080. };
  10081. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10082. var visibleInstances = batch.visibleInstances[subMesh._id];
  10083. var matricesCount = visibleInstances.length + 1;
  10084. var bufferSize = matricesCount * 16 * 4;
  10085. while (this._instancesBufferSize < bufferSize) {
  10086. this._instancesBufferSize *= 2;
  10087. }
  10088. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10089. if (this._worldMatricesInstancesBuffer) {
  10090. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10091. }
  10092. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10093. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10094. }
  10095. var offset = 0;
  10096. var instancesCount = 0;
  10097. var world = this.getWorldMatrix();
  10098. if (batch.renderSelf[subMesh._id]) {
  10099. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10100. offset += 16;
  10101. instancesCount++;
  10102. }
  10103. if (visibleInstances) {
  10104. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10105. var instance = visibleInstances[instanceIndex];
  10106. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10107. offset += 16;
  10108. instancesCount++;
  10109. }
  10110. }
  10111. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10112. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10113. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10114. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10115. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10116. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10117. this._draw(subMesh, fillMode, instancesCount);
  10118. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10119. };
  10120. Mesh.prototype.render = function (subMesh) {
  10121. var scene = this.getScene();
  10122. // Managing instances
  10123. var batch = this._getInstancesRenderList(subMesh._id);
  10124. if (batch.mustReturn) {
  10125. return;
  10126. }
  10127. // Checking geometry state
  10128. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10129. return;
  10130. }
  10131. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10132. this._onBeforeRenderCallbacks[callbackIndex]();
  10133. }
  10134. var engine = scene.getEngine();
  10135. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10136. // Material
  10137. var effectiveMaterial = subMesh.getMaterial();
  10138. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10139. return;
  10140. }
  10141. // Outline - step 1
  10142. var savedDepthWrite = engine.getDepthWrite();
  10143. if (this.renderOutline) {
  10144. engine.setDepthWrite(false);
  10145. scene.getOutlineRenderer().render(subMesh, batch);
  10146. engine.setDepthWrite(savedDepthWrite);
  10147. }
  10148. effectiveMaterial._preBind();
  10149. var effect = effectiveMaterial.getEffect();
  10150. // Bind
  10151. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10152. this._bind(subMesh, effect, fillMode);
  10153. var world = this.getWorldMatrix();
  10154. effectiveMaterial.bind(world, this);
  10155. // Instances rendering
  10156. if (hardwareInstancedRendering) {
  10157. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10158. } else {
  10159. if (batch.renderSelf[subMesh._id]) {
  10160. // Draw
  10161. this._draw(subMesh, fillMode);
  10162. }
  10163. if (batch.visibleInstances[subMesh._id]) {
  10164. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10165. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10166. // World
  10167. world = instance.getWorldMatrix();
  10168. effectiveMaterial.bindOnlyWorldMatrix(world);
  10169. // Draw
  10170. this._draw(subMesh, fillMode);
  10171. }
  10172. }
  10173. }
  10174. // Unbind
  10175. effectiveMaterial.unbind();
  10176. // Outline - step 2
  10177. if (this.renderOutline && savedDepthWrite) {
  10178. engine.setDepthWrite(true);
  10179. engine.setColorWrite(false);
  10180. scene.getOutlineRenderer().render(subMesh, batch);
  10181. engine.setColorWrite(true);
  10182. }
  10183. // Overlay
  10184. if (this.renderOverlay) {
  10185. var currentMode = engine.getAlphaMode();
  10186. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10187. scene.getOutlineRenderer().render(subMesh, batch, true);
  10188. engine.setAlphaMode(currentMode);
  10189. }
  10190. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10191. this._onAfterRenderCallbacks[callbackIndex]();
  10192. }
  10193. };
  10194. Mesh.prototype.getEmittedParticleSystems = function () {
  10195. var results = new Array();
  10196. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10197. var particleSystem = this.getScene().particleSystems[index];
  10198. if (particleSystem.emitter === this) {
  10199. results.push(particleSystem);
  10200. }
  10201. }
  10202. return results;
  10203. };
  10204. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10205. var results = new Array();
  10206. var descendants = this.getDescendants();
  10207. descendants.push(this);
  10208. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10209. var particleSystem = this.getScene().particleSystems[index];
  10210. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10211. results.push(particleSystem);
  10212. }
  10213. }
  10214. return results;
  10215. };
  10216. Mesh.prototype.getChildren = function () {
  10217. var results = [];
  10218. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10219. var mesh = this.getScene().meshes[index];
  10220. if (mesh.parent == this) {
  10221. results.push(mesh);
  10222. }
  10223. }
  10224. return results;
  10225. };
  10226. Mesh.prototype._checkDelayState = function () {
  10227. var _this = this;
  10228. var that = this;
  10229. var scene = this.getScene();
  10230. if (this._geometry) {
  10231. this._geometry.load(scene);
  10232. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10233. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10234. scene._addPendingData(that);
  10235. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10236. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10237. if (data instanceof ArrayBuffer) {
  10238. _this._delayLoadingFunction(data, _this);
  10239. } else {
  10240. _this._delayLoadingFunction(JSON.parse(data), _this);
  10241. }
  10242. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10243. scene._removePendingData(_this);
  10244. }, function () {
  10245. }, scene.database, getBinaryData);
  10246. }
  10247. };
  10248. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10249. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10250. return false;
  10251. }
  10252. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10253. return false;
  10254. }
  10255. this._checkDelayState();
  10256. return true;
  10257. };
  10258. Mesh.prototype.setMaterialByID = function (id) {
  10259. var materials = this.getScene().materials;
  10260. for (var index = 0; index < materials.length; index++) {
  10261. if (materials[index].id == id) {
  10262. this.material = materials[index];
  10263. return;
  10264. }
  10265. }
  10266. // Multi
  10267. var multiMaterials = this.getScene().multiMaterials;
  10268. for (index = 0; index < multiMaterials.length; index++) {
  10269. if (multiMaterials[index].id == id) {
  10270. this.material = multiMaterials[index];
  10271. return;
  10272. }
  10273. }
  10274. };
  10275. Mesh.prototype.getAnimatables = function () {
  10276. var results = [];
  10277. if (this.material) {
  10278. results.push(this.material);
  10279. }
  10280. if (this.skeleton) {
  10281. results.push(this.skeleton);
  10282. }
  10283. return results;
  10284. };
  10285. // Geometry
  10286. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10287. // Position
  10288. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10289. return;
  10290. }
  10291. this._resetPointsArrayCache();
  10292. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10293. var temp = [];
  10294. for (var index = 0; index < data.length; index += 3) {
  10295. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10296. }
  10297. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10298. // Normals
  10299. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10300. return;
  10301. }
  10302. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10303. for (index = 0; index < data.length; index += 3) {
  10304. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10305. }
  10306. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10307. };
  10308. // Cache
  10309. Mesh.prototype._resetPointsArrayCache = function () {
  10310. this._positions = null;
  10311. };
  10312. Mesh.prototype._generatePointsArray = function () {
  10313. if (this._positions)
  10314. return true;
  10315. this._positions = [];
  10316. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10317. if (!data) {
  10318. return false;
  10319. }
  10320. for (var index = 0; index < data.length; index += 3) {
  10321. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10322. }
  10323. return true;
  10324. };
  10325. // Clone
  10326. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10327. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10328. };
  10329. // Dispose
  10330. Mesh.prototype.dispose = function (doNotRecurse) {
  10331. if (this._geometry) {
  10332. this._geometry.releaseForMesh(this, true);
  10333. }
  10334. // Instances
  10335. if (this._worldMatricesInstancesBuffer) {
  10336. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10337. this._worldMatricesInstancesBuffer = null;
  10338. }
  10339. while (this.instances.length) {
  10340. this.instances[0].dispose();
  10341. }
  10342. _super.prototype.dispose.call(this, doNotRecurse);
  10343. };
  10344. // Geometric tools
  10345. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  10346. var _this = this;
  10347. var scene = this.getScene();
  10348. var onload = function (img) {
  10349. // Getting height map data
  10350. var canvas = document.createElement("canvas");
  10351. var context = canvas.getContext("2d");
  10352. var heightMapWidth = img.width;
  10353. var heightMapHeight = img.height;
  10354. canvas.width = heightMapWidth;
  10355. canvas.height = heightMapHeight;
  10356. context.drawImage(img, 0, 0);
  10357. // Create VertexData from map data
  10358. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10359. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10360. };
  10361. BABYLON.Tools.LoadImage(url, onload, function () {
  10362. }, scene.database);
  10363. };
  10364. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10365. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10366. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10367. return;
  10368. }
  10369. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10370. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10371. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10372. var position = BABYLON.Vector3.Zero();
  10373. var normal = BABYLON.Vector3.Zero();
  10374. var uv = BABYLON.Vector2.Zero();
  10375. for (var index = 0; index < positions.length; index += 3) {
  10376. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10377. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10378. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10379. // Compute height
  10380. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10381. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10382. var pos = (u + v * heightMapWidth) * 4;
  10383. var r = buffer[pos] / 255.0;
  10384. var g = buffer[pos + 1] / 255.0;
  10385. var b = buffer[pos + 2] / 255.0;
  10386. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10387. normal.normalize();
  10388. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10389. position = position.add(normal);
  10390. position.toArray(positions, index);
  10391. }
  10392. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10393. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10394. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10395. };
  10396. Mesh.prototype.convertToFlatShadedMesh = function () {
  10397. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10398. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10399. var kinds = this.getVerticesDataKinds();
  10400. var vbs = [];
  10401. var data = [];
  10402. var newdata = [];
  10403. var updatableNormals = false;
  10404. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10405. var kind = kinds[kindIndex];
  10406. var vertexBuffer = this.getVertexBuffer(kind);
  10407. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10408. updatableNormals = vertexBuffer.isUpdatable();
  10409. kinds.splice(kindIndex, 1);
  10410. kindIndex--;
  10411. continue;
  10412. }
  10413. vbs[kind] = vertexBuffer;
  10414. data[kind] = vbs[kind].getData();
  10415. newdata[kind] = [];
  10416. }
  10417. // Save previous submeshes
  10418. var previousSubmeshes = this.subMeshes.slice(0);
  10419. var indices = this.getIndices();
  10420. var totalIndices = this.getTotalIndices();
  10421. for (var index = 0; index < totalIndices; index++) {
  10422. var vertexIndex = indices[index];
  10423. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10424. kind = kinds[kindIndex];
  10425. var stride = vbs[kind].getStrideSize();
  10426. for (var offset = 0; offset < stride; offset++) {
  10427. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10428. }
  10429. }
  10430. }
  10431. // Updating faces & normal
  10432. var normals = [];
  10433. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10434. for (index = 0; index < totalIndices; index += 3) {
  10435. indices[index] = index;
  10436. indices[index + 1] = index + 1;
  10437. indices[index + 2] = index + 2;
  10438. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10439. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10440. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10441. var p1p2 = p1.subtract(p2);
  10442. var p3p2 = p3.subtract(p2);
  10443. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10444. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10445. normals.push(normal.x);
  10446. normals.push(normal.y);
  10447. normals.push(normal.z);
  10448. }
  10449. }
  10450. this.setIndices(indices);
  10451. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10452. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10453. kind = kinds[kindIndex];
  10454. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10455. }
  10456. // Updating submeshes
  10457. this.releaseSubMeshes();
  10458. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10459. var previousOne = previousSubmeshes[submeshIndex];
  10460. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10461. }
  10462. this.synchronizeInstances();
  10463. };
  10464. // Instances
  10465. Mesh.prototype.createInstance = function (name) {
  10466. return new BABYLON.InstancedMesh(name, this);
  10467. };
  10468. Mesh.prototype.synchronizeInstances = function () {
  10469. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10470. var instance = this.instances[instanceIndex];
  10471. instance._syncSubMeshes();
  10472. }
  10473. };
  10474. /**
  10475. * Simplify the mesh according to the given array of settings.
  10476. * Function will return immediately and will simplify async.
  10477. * @param settings a collection of simplification settings.
  10478. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10479. * @param type the type of simplification to run.
  10480. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10481. */
  10482. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10483. var _this = this;
  10484. if (typeof parallelProcessing === "undefined") { parallelProcessing = true; }
  10485. if (typeof type === "undefined") { type = 0 /* QUADRATIC */; }
  10486. var getSimplifier = function () {
  10487. switch (type) {
  10488. case 0 /* QUADRATIC */:
  10489. default:
  10490. return new BABYLON.QuadraticErrorSimplification(_this);
  10491. }
  10492. };
  10493. if (parallelProcessing) {
  10494. //parallel simplifier
  10495. settings.forEach(function (setting) {
  10496. var simplifier = getSimplifier();
  10497. simplifier.simplify(setting, function (newMesh) {
  10498. _this.addLODLevel(setting.distance, newMesh);
  10499. //check if it is the last
  10500. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10501. //all done, run the success callback.
  10502. successCallback();
  10503. }
  10504. });
  10505. });
  10506. } else {
  10507. //single simplifier.
  10508. var simplifier = getSimplifier();
  10509. var runDecimation = function (setting, callback) {
  10510. simplifier.simplify(setting, function (newMesh) {
  10511. _this.addLODLevel(setting.distance, newMesh);
  10512. //run the next quality level
  10513. callback();
  10514. });
  10515. };
  10516. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10517. runDecimation(settings[loop.index], function () {
  10518. loop.executeNext();
  10519. });
  10520. }, function () {
  10521. //execution ended, run the success callback.
  10522. if (successCallback) {
  10523. successCallback();
  10524. }
  10525. });
  10526. }
  10527. };
  10528. // Statics
  10529. Mesh.CreateBox = function (name, size, scene, updatable) {
  10530. var box = new Mesh(name, scene);
  10531. var vertexData = BABYLON.VertexData.CreateBox(size);
  10532. vertexData.applyToMesh(box, updatable);
  10533. return box;
  10534. };
  10535. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10536. var sphere = new Mesh(name, scene);
  10537. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10538. vertexData.applyToMesh(sphere, updatable);
  10539. return sphere;
  10540. };
  10541. // Cylinder and cone (Code inspired by SharpDX.org)
  10542. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10543. // subdivisions is a new parameter, we need to support old signature
  10544. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10545. if (scene !== undefined) {
  10546. updatable = scene;
  10547. }
  10548. scene = subdivisions;
  10549. subdivisions = 1;
  10550. }
  10551. var cylinder = new Mesh(name, scene);
  10552. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10553. vertexData.applyToMesh(cylinder, updatable);
  10554. return cylinder;
  10555. };
  10556. // Torus (Code from SharpDX.org)
  10557. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10558. var torus = new Mesh(name, scene);
  10559. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10560. vertexData.applyToMesh(torus, updatable);
  10561. return torus;
  10562. };
  10563. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10564. var torusKnot = new Mesh(name, scene);
  10565. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10566. vertexData.applyToMesh(torusKnot, updatable);
  10567. return torusKnot;
  10568. };
  10569. // Lines
  10570. Mesh.CreateLines = function (name, points, scene, updatable) {
  10571. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10572. var vertexData = BABYLON.VertexData.CreateLines(points);
  10573. vertexData.applyToMesh(lines, updatable);
  10574. return lines;
  10575. };
  10576. // Plane & ground
  10577. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10578. var plane = new Mesh(name, scene);
  10579. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10580. vertexData.applyToMesh(plane, updatable);
  10581. return plane;
  10582. };
  10583. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10584. var ground = new BABYLON.GroundMesh(name, scene);
  10585. ground._setReady(false);
  10586. ground._subdivisions = subdivisions;
  10587. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10588. vertexData.applyToMesh(ground, updatable);
  10589. ground._setReady(true);
  10590. return ground;
  10591. };
  10592. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10593. var tiledGround = new Mesh(name, scene);
  10594. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10595. vertexData.applyToMesh(tiledGround, updatable);
  10596. return tiledGround;
  10597. };
  10598. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10599. var ground = new BABYLON.GroundMesh(name, scene);
  10600. ground._subdivisions = subdivisions;
  10601. ground._setReady(false);
  10602. var onload = function (img) {
  10603. // Getting height map data
  10604. var canvas = document.createElement("canvas");
  10605. var context = canvas.getContext("2d");
  10606. var heightMapWidth = img.width;
  10607. var heightMapHeight = img.height;
  10608. canvas.width = heightMapWidth;
  10609. canvas.height = heightMapHeight;
  10610. context.drawImage(img, 0, 0);
  10611. // Create VertexData from map data
  10612. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10613. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10614. vertexData.applyToMesh(ground, updatable);
  10615. ground._setReady(true);
  10616. };
  10617. BABYLON.Tools.LoadImage(url, onload, function () {
  10618. }, scene.database);
  10619. return ground;
  10620. };
  10621. // Tools
  10622. Mesh.MinMax = function (meshes) {
  10623. var minVector = null;
  10624. var maxVector = null;
  10625. for (var i in meshes) {
  10626. var mesh = meshes[i];
  10627. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10628. if (!minVector) {
  10629. minVector = boundingBox.minimumWorld;
  10630. maxVector = boundingBox.maximumWorld;
  10631. continue;
  10632. }
  10633. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10634. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10635. }
  10636. return {
  10637. min: minVector,
  10638. max: maxVector
  10639. };
  10640. };
  10641. Mesh.Center = function (meshesOrMinMaxVector) {
  10642. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10643. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10644. };
  10645. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10646. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10647. var source = meshes[0];
  10648. var material = source.material;
  10649. var scene = source.getScene();
  10650. if (!allow32BitsIndices) {
  10651. var totalVertices = 0;
  10652. for (var index = 0; index < meshes.length; index++) {
  10653. totalVertices += meshes[index].getTotalVertices();
  10654. if (totalVertices > 65536) {
  10655. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10656. return null;
  10657. }
  10658. }
  10659. }
  10660. // Merge
  10661. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10662. vertexData.transform(source.getWorldMatrix());
  10663. for (index = 1; index < meshes.length; index++) {
  10664. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10665. otherVertexData.transform(meshes[index].getWorldMatrix());
  10666. vertexData.merge(otherVertexData);
  10667. }
  10668. var newMesh = new Mesh(source.name + "_merged", scene);
  10669. vertexData.applyToMesh(newMesh);
  10670. // Setting properties
  10671. newMesh.material = material;
  10672. newMesh.checkCollisions = source.checkCollisions;
  10673. // Cleaning
  10674. if (disposeSource) {
  10675. for (index = 0; index < meshes.length; index++) {
  10676. meshes[index].dispose();
  10677. }
  10678. }
  10679. return newMesh;
  10680. };
  10681. return Mesh;
  10682. })(BABYLON.AbstractMesh);
  10683. BABYLON.Mesh = Mesh;
  10684. })(BABYLON || (BABYLON = {}));
  10685. //# sourceMappingURL=babylon.mesh.js.map
  10686. var BABYLON;
  10687. (function (BABYLON) {
  10688. var GroundMesh = (function (_super) {
  10689. __extends(GroundMesh, _super);
  10690. function GroundMesh(name, scene) {
  10691. _super.call(this, name, scene);
  10692. this.generateOctree = false;
  10693. this._worldInverse = new BABYLON.Matrix();
  10694. }
  10695. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10696. get: function () {
  10697. return this._subdivisions;
  10698. },
  10699. enumerable: true,
  10700. configurable: true
  10701. });
  10702. GroundMesh.prototype.optimize = function (chunksCount) {
  10703. this.subdivide(this._subdivisions);
  10704. this.createOrUpdateSubmeshesOctree(32);
  10705. };
  10706. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10707. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10708. this.getWorldMatrix().invertToRef(this._worldInverse);
  10709. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10710. var pickInfo = this.intersects(ray);
  10711. if (pickInfo.hit) {
  10712. return pickInfo.pickedPoint.y;
  10713. }
  10714. return 0;
  10715. };
  10716. return GroundMesh;
  10717. })(BABYLON.Mesh);
  10718. BABYLON.GroundMesh = GroundMesh;
  10719. })(BABYLON || (BABYLON = {}));
  10720. //# sourceMappingURL=babylon.groundMesh.js.map
  10721. var BABYLON;
  10722. (function (BABYLON) {
  10723. /**
  10724. * Creates an instance based on a source mesh.
  10725. */
  10726. var InstancedMesh = (function (_super) {
  10727. __extends(InstancedMesh, _super);
  10728. function InstancedMesh(name, source) {
  10729. _super.call(this, name, source.getScene());
  10730. source.instances.push(this);
  10731. this._sourceMesh = source;
  10732. this.position.copyFrom(source.position);
  10733. this.rotation.copyFrom(source.rotation);
  10734. this.scaling.copyFrom(source.scaling);
  10735. if (source.rotationQuaternion) {
  10736. this.rotationQuaternion = source.rotationQuaternion.clone();
  10737. }
  10738. this.infiniteDistance = source.infiniteDistance;
  10739. this.setPivotMatrix(source.getPivotMatrix());
  10740. this.refreshBoundingInfo();
  10741. this._syncSubMeshes();
  10742. }
  10743. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10744. // Methods
  10745. get: function () {
  10746. return this._sourceMesh.receiveShadows;
  10747. },
  10748. enumerable: true,
  10749. configurable: true
  10750. });
  10751. Object.defineProperty(InstancedMesh.prototype, "material", {
  10752. get: function () {
  10753. return this._sourceMesh.material;
  10754. },
  10755. enumerable: true,
  10756. configurable: true
  10757. });
  10758. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10759. get: function () {
  10760. return this._sourceMesh.visibility;
  10761. },
  10762. enumerable: true,
  10763. configurable: true
  10764. });
  10765. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10766. get: function () {
  10767. return this._sourceMesh.skeleton;
  10768. },
  10769. enumerable: true,
  10770. configurable: true
  10771. });
  10772. InstancedMesh.prototype.getTotalVertices = function () {
  10773. return this._sourceMesh.getTotalVertices();
  10774. };
  10775. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10776. get: function () {
  10777. return this._sourceMesh;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. InstancedMesh.prototype.getVerticesData = function (kind) {
  10783. return this._sourceMesh.getVerticesData(kind);
  10784. };
  10785. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10786. return this._sourceMesh.isVerticesDataPresent(kind);
  10787. };
  10788. InstancedMesh.prototype.getIndices = function () {
  10789. return this._sourceMesh.getIndices();
  10790. };
  10791. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10792. get: function () {
  10793. return this._sourceMesh._positions;
  10794. },
  10795. enumerable: true,
  10796. configurable: true
  10797. });
  10798. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10799. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10800. if (data) {
  10801. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10802. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10803. }
  10804. this._updateBoundingInfo();
  10805. };
  10806. InstancedMesh.prototype._preActivate = function () {
  10807. if (this._currentLOD) {
  10808. this._currentLOD._preActivate();
  10809. }
  10810. };
  10811. InstancedMesh.prototype._activate = function (renderId) {
  10812. if (this._currentLOD) {
  10813. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10814. }
  10815. };
  10816. InstancedMesh.prototype.getLOD = function (camera) {
  10817. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10818. if (this._currentLOD === this.sourceMesh) {
  10819. return this;
  10820. }
  10821. return this._currentLOD;
  10822. };
  10823. InstancedMesh.prototype._syncSubMeshes = function () {
  10824. this.releaseSubMeshes();
  10825. if (this._sourceMesh.subMeshes) {
  10826. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10827. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10828. }
  10829. }
  10830. };
  10831. InstancedMesh.prototype._generatePointsArray = function () {
  10832. return this._sourceMesh._generatePointsArray();
  10833. };
  10834. // Clone
  10835. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10836. var result = this._sourceMesh.createInstance(name);
  10837. // Deep copy
  10838. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10839. // Bounding info
  10840. this.refreshBoundingInfo();
  10841. // Parent
  10842. if (newParent) {
  10843. result.parent = newParent;
  10844. }
  10845. if (!doNotCloneChildren) {
  10846. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10847. var mesh = this.getScene().meshes[index];
  10848. if (mesh.parent === this) {
  10849. mesh.clone(mesh.name, result);
  10850. }
  10851. }
  10852. }
  10853. result.computeWorldMatrix(true);
  10854. return result;
  10855. };
  10856. // Dispoe
  10857. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10858. // Remove from mesh
  10859. var index = this._sourceMesh.instances.indexOf(this);
  10860. this._sourceMesh.instances.splice(index, 1);
  10861. _super.prototype.dispose.call(this, doNotRecurse);
  10862. };
  10863. return InstancedMesh;
  10864. })(BABYLON.AbstractMesh);
  10865. BABYLON.InstancedMesh = InstancedMesh;
  10866. })(BABYLON || (BABYLON = {}));
  10867. //# sourceMappingURL=babylon.instancedMesh.js.map
  10868. var BABYLON;
  10869. (function (BABYLON) {
  10870. var SubMesh = (function () {
  10871. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10872. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10873. this.materialIndex = materialIndex;
  10874. this.verticesStart = verticesStart;
  10875. this.verticesCount = verticesCount;
  10876. this.indexStart = indexStart;
  10877. this.indexCount = indexCount;
  10878. this._renderId = 0;
  10879. this._mesh = mesh;
  10880. this._renderingMesh = renderingMesh || mesh;
  10881. mesh.subMeshes.push(this);
  10882. this._id = mesh.subMeshes.length - 1;
  10883. if (createBoundingBox) {
  10884. this.refreshBoundingInfo();
  10885. }
  10886. }
  10887. SubMesh.prototype.getBoundingInfo = function () {
  10888. return this._boundingInfo;
  10889. };
  10890. SubMesh.prototype.getMesh = function () {
  10891. return this._mesh;
  10892. };
  10893. SubMesh.prototype.getRenderingMesh = function () {
  10894. return this._renderingMesh;
  10895. };
  10896. SubMesh.prototype.getMaterial = function () {
  10897. var rootMaterial = this._renderingMesh.material;
  10898. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10899. var multiMaterial = rootMaterial;
  10900. return multiMaterial.getSubMaterial(this.materialIndex);
  10901. }
  10902. if (!rootMaterial) {
  10903. return this._mesh.getScene().defaultMaterial;
  10904. }
  10905. return rootMaterial;
  10906. };
  10907. // Methods
  10908. SubMesh.prototype.refreshBoundingInfo = function () {
  10909. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10910. if (!data) {
  10911. this._boundingInfo = this._mesh._boundingInfo;
  10912. return;
  10913. }
  10914. var indices = this._renderingMesh.getIndices();
  10915. var extend;
  10916. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10917. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10918. } else {
  10919. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10920. }
  10921. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10922. };
  10923. SubMesh.prototype._checkCollision = function (collider) {
  10924. return this._boundingInfo._checkCollision(collider);
  10925. };
  10926. SubMesh.prototype.updateBoundingInfo = function (world) {
  10927. if (!this._boundingInfo) {
  10928. this.refreshBoundingInfo();
  10929. }
  10930. this._boundingInfo._update(world);
  10931. };
  10932. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10933. return this._boundingInfo.isInFrustum(frustumPlanes);
  10934. };
  10935. SubMesh.prototype.render = function () {
  10936. this._renderingMesh.render(this);
  10937. };
  10938. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10939. if (!this._linesIndexBuffer) {
  10940. var linesIndices = [];
  10941. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10942. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10943. }
  10944. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10945. this.linesIndexCount = linesIndices.length;
  10946. }
  10947. return this._linesIndexBuffer;
  10948. };
  10949. SubMesh.prototype.canIntersects = function (ray) {
  10950. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10951. };
  10952. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10953. var intersectInfo = null;
  10954. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10955. var p0 = positions[indices[index]];
  10956. var p1 = positions[indices[index + 1]];
  10957. var p2 = positions[indices[index + 2]];
  10958. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10959. if (currentIntersectInfo) {
  10960. if (currentIntersectInfo.distance < 0) {
  10961. continue;
  10962. }
  10963. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10964. intersectInfo = currentIntersectInfo;
  10965. intersectInfo.faceId = index / 3;
  10966. if (fastCheck) {
  10967. break;
  10968. }
  10969. }
  10970. }
  10971. }
  10972. return intersectInfo;
  10973. };
  10974. // Clone
  10975. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10976. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10977. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10978. return result;
  10979. };
  10980. // Dispose
  10981. SubMesh.prototype.dispose = function () {
  10982. if (this._linesIndexBuffer) {
  10983. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10984. this._linesIndexBuffer = null;
  10985. }
  10986. // Remove from mesh
  10987. var index = this._mesh.subMeshes.indexOf(this);
  10988. this._mesh.subMeshes.splice(index, 1);
  10989. };
  10990. // Statics
  10991. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10992. var minVertexIndex = Number.MAX_VALUE;
  10993. var maxVertexIndex = -Number.MAX_VALUE;
  10994. renderingMesh = renderingMesh || mesh;
  10995. var indices = renderingMesh.getIndices();
  10996. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10997. var vertexIndex = indices[index];
  10998. if (vertexIndex < minVertexIndex)
  10999. minVertexIndex = vertexIndex;
  11000. if (vertexIndex > maxVertexIndex)
  11001. maxVertexIndex = vertexIndex;
  11002. }
  11003. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11004. };
  11005. return SubMesh;
  11006. })();
  11007. BABYLON.SubMesh = SubMesh;
  11008. })(BABYLON || (BABYLON = {}));
  11009. //# sourceMappingURL=babylon.subMesh.js.map
  11010. var BABYLON;
  11011. (function (BABYLON) {
  11012. var BaseTexture = (function () {
  11013. function BaseTexture(scene) {
  11014. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11015. this.hasAlpha = false;
  11016. this.getAlphaFromRGB = false;
  11017. this.level = 1;
  11018. this.isCube = false;
  11019. this.isRenderTarget = false;
  11020. this.animations = new Array();
  11021. this.coordinatesIndex = 0;
  11022. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11023. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11024. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11025. this.anisotropicFilteringLevel = 4;
  11026. this._scene = scene;
  11027. this._scene.textures.push(this);
  11028. }
  11029. BaseTexture.prototype.getScene = function () {
  11030. return this._scene;
  11031. };
  11032. BaseTexture.prototype.getTextureMatrix = function () {
  11033. return null;
  11034. };
  11035. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11036. return null;
  11037. };
  11038. BaseTexture.prototype.getInternalTexture = function () {
  11039. return this._texture;
  11040. };
  11041. BaseTexture.prototype.isReady = function () {
  11042. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11043. return true;
  11044. }
  11045. if (this._texture) {
  11046. return this._texture.isReady;
  11047. }
  11048. return false;
  11049. };
  11050. BaseTexture.prototype.getSize = function () {
  11051. if (this._texture._width) {
  11052. return { width: this._texture._width, height: this._texture._height };
  11053. }
  11054. if (this._texture._size) {
  11055. return { width: this._texture._size, height: this._texture._size };
  11056. }
  11057. return { width: 0, height: 0 };
  11058. };
  11059. BaseTexture.prototype.getBaseSize = function () {
  11060. if (!this.isReady())
  11061. return { width: 0, height: 0 };
  11062. if (this._texture._size) {
  11063. return { width: this._texture._size, height: this._texture._size };
  11064. }
  11065. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11066. };
  11067. BaseTexture.prototype.scale = function (ratio) {
  11068. };
  11069. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11070. get: function () {
  11071. return false;
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11077. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11078. for (var index = 0; index < texturesCache.length; index++) {
  11079. var texturesCacheEntry = texturesCache[index];
  11080. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11081. texturesCache.splice(index, 1);
  11082. return;
  11083. }
  11084. }
  11085. };
  11086. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11087. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11088. for (var index = 0; index < texturesCache.length; index++) {
  11089. var texturesCacheEntry = texturesCache[index];
  11090. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11091. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11092. texturesCacheEntry.references++;
  11093. return texturesCacheEntry;
  11094. }
  11095. }
  11096. }
  11097. return null;
  11098. };
  11099. BaseTexture.prototype.delayLoad = function () {
  11100. };
  11101. BaseTexture.prototype.releaseInternalTexture = function () {
  11102. if (!this._texture) {
  11103. return;
  11104. }
  11105. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11106. this._texture.references--;
  11107. // Final reference ?
  11108. if (this._texture.references === 0) {
  11109. var index = texturesCache.indexOf(this._texture);
  11110. texturesCache.splice(index, 1);
  11111. this._scene.getEngine()._releaseTexture(this._texture);
  11112. delete this._texture;
  11113. }
  11114. };
  11115. BaseTexture.prototype.clone = function () {
  11116. return null;
  11117. };
  11118. BaseTexture.prototype.dispose = function () {
  11119. // Remove from scene
  11120. var index = this._scene.textures.indexOf(this);
  11121. if (index >= 0) {
  11122. this._scene.textures.splice(index, 1);
  11123. }
  11124. if (this._texture === undefined) {
  11125. return;
  11126. }
  11127. this.releaseInternalTexture();
  11128. // Callback
  11129. if (this.onDispose) {
  11130. this.onDispose();
  11131. }
  11132. };
  11133. return BaseTexture;
  11134. })();
  11135. BABYLON.BaseTexture = BaseTexture;
  11136. })(BABYLON || (BABYLON = {}));
  11137. //# sourceMappingURL=babylon.baseTexture.js.map
  11138. var BABYLON;
  11139. (function (BABYLON) {
  11140. var RenderingGroup = (function () {
  11141. function RenderingGroup(index, scene) {
  11142. this.index = index;
  11143. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11144. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11145. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11146. this._scene = scene;
  11147. }
  11148. RenderingGroup.prototype.render = function (customRenderFunction) {
  11149. if (customRenderFunction) {
  11150. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11151. return true;
  11152. }
  11153. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11154. return false;
  11155. }
  11156. var engine = this._scene.getEngine();
  11157. // Opaque
  11158. var subIndex;
  11159. var submesh;
  11160. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11161. submesh = this._opaqueSubMeshes.data[subIndex];
  11162. submesh.render();
  11163. }
  11164. // Alpha test
  11165. engine.setAlphaTesting(true);
  11166. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11167. submesh = this._alphaTestSubMeshes.data[subIndex];
  11168. submesh.render();
  11169. }
  11170. engine.setAlphaTesting(false);
  11171. // Transparent
  11172. if (this._transparentSubMeshes.length) {
  11173. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11174. submesh = this._transparentSubMeshes.data[subIndex];
  11175. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11176. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11177. }
  11178. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11179. sortedArray.sort(function (a, b) {
  11180. // Alpha index first
  11181. if (a._alphaIndex > b._alphaIndex) {
  11182. return 1;
  11183. }
  11184. if (a._alphaIndex < b._alphaIndex) {
  11185. return -1;
  11186. }
  11187. // Then distance to camera
  11188. if (a._distanceToCamera < b._distanceToCamera) {
  11189. return 1;
  11190. }
  11191. if (a._distanceToCamera > b._distanceToCamera) {
  11192. return -1;
  11193. }
  11194. return 0;
  11195. });
  11196. // Rendering
  11197. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11198. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11199. submesh = sortedArray[subIndex];
  11200. submesh.render();
  11201. }
  11202. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11203. }
  11204. return true;
  11205. };
  11206. RenderingGroup.prototype.prepare = function () {
  11207. this._opaqueSubMeshes.reset();
  11208. this._transparentSubMeshes.reset();
  11209. this._alphaTestSubMeshes.reset();
  11210. };
  11211. RenderingGroup.prototype.dispatch = function (subMesh) {
  11212. var material = subMesh.getMaterial();
  11213. var mesh = subMesh.getMesh();
  11214. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11215. this._transparentSubMeshes.push(subMesh);
  11216. } else if (material.needAlphaTesting()) {
  11217. this._alphaTestSubMeshes.push(subMesh);
  11218. } else {
  11219. this._opaqueSubMeshes.push(subMesh); // Opaque
  11220. }
  11221. };
  11222. return RenderingGroup;
  11223. })();
  11224. BABYLON.RenderingGroup = RenderingGroup;
  11225. })(BABYLON || (BABYLON = {}));
  11226. //# sourceMappingURL=babylon.renderingGroup.js.map
  11227. var BABYLON;
  11228. (function (BABYLON) {
  11229. var RenderingManager = (function () {
  11230. function RenderingManager(scene) {
  11231. this._renderingGroups = new Array();
  11232. this._scene = scene;
  11233. }
  11234. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11235. if (this._scene._activeParticleSystems.length === 0) {
  11236. return;
  11237. }
  11238. // Particles
  11239. var beforeParticlesDate = BABYLON.Tools.Now;
  11240. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11241. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11242. if (particleSystem.renderingGroupId !== index) {
  11243. continue;
  11244. }
  11245. this._clearDepthBuffer();
  11246. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11247. this._scene._activeParticles += particleSystem.render();
  11248. }
  11249. }
  11250. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11251. };
  11252. RenderingManager.prototype._renderSprites = function (index) {
  11253. if (this._scene.spriteManagers.length === 0) {
  11254. return;
  11255. }
  11256. // Sprites
  11257. var beforeSpritessDate = BABYLON.Tools.Now;
  11258. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11259. var spriteManager = this._scene.spriteManagers[id];
  11260. if (spriteManager.renderingGroupId === index) {
  11261. this._clearDepthBuffer();
  11262. spriteManager.render();
  11263. }
  11264. }
  11265. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11266. };
  11267. RenderingManager.prototype._clearDepthBuffer = function () {
  11268. if (this._depthBufferAlreadyCleaned) {
  11269. return;
  11270. }
  11271. this._scene.getEngine().clear(0, false, true);
  11272. this._depthBufferAlreadyCleaned = true;
  11273. };
  11274. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11275. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11276. this._depthBufferAlreadyCleaned = false;
  11277. var renderingGroup = this._renderingGroups[index];
  11278. if (renderingGroup) {
  11279. this._clearDepthBuffer();
  11280. if (!renderingGroup.render(customRenderFunction)) {
  11281. this._renderingGroups.splice(index, 1);
  11282. }
  11283. }
  11284. this._renderSprites(index);
  11285. if (renderParticles) {
  11286. this._renderParticles(index, activeMeshes);
  11287. }
  11288. }
  11289. };
  11290. RenderingManager.prototype.reset = function () {
  11291. for (var index in this._renderingGroups) {
  11292. var renderingGroup = this._renderingGroups[index];
  11293. renderingGroup.prepare();
  11294. }
  11295. };
  11296. RenderingManager.prototype.dispatch = function (subMesh) {
  11297. var mesh = subMesh.getMesh();
  11298. var renderingGroupId = mesh.renderingGroupId || 0;
  11299. if (!this._renderingGroups[renderingGroupId]) {
  11300. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11301. }
  11302. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11303. };
  11304. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11305. return RenderingManager;
  11306. })();
  11307. BABYLON.RenderingManager = RenderingManager;
  11308. })(BABYLON || (BABYLON = {}));
  11309. //# sourceMappingURL=babylon.renderingManager.js.map
  11310. var BABYLON;
  11311. (function (BABYLON) {
  11312. var Texture = (function (_super) {
  11313. __extends(Texture, _super);
  11314. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11315. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11316. if (typeof onLoad === "undefined") { onLoad = null; }
  11317. if (typeof onError === "undefined") { onError = null; }
  11318. if (typeof buffer === "undefined") { buffer = null; }
  11319. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  11320. _super.call(this, scene);
  11321. this.uOffset = 0;
  11322. this.vOffset = 0;
  11323. this.uScale = 1.0;
  11324. this.vScale = 1.0;
  11325. this.uAng = 0;
  11326. this.vAng = 0;
  11327. this.wAng = 0;
  11328. this.name = url;
  11329. this.url = url;
  11330. this._noMipmap = noMipmap;
  11331. this._invertY = invertY;
  11332. this._samplingMode = samplingMode;
  11333. this._buffer = buffer;
  11334. this._deleteBuffer = deleteBuffer;
  11335. if (!url) {
  11336. return;
  11337. }
  11338. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11339. if (!this._texture) {
  11340. if (!scene.useDelayedTextureLoading) {
  11341. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11342. if (deleteBuffer) {
  11343. delete this._buffer;
  11344. }
  11345. } else {
  11346. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11347. }
  11348. }
  11349. }
  11350. Texture.prototype.delayLoad = function () {
  11351. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11352. return;
  11353. }
  11354. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11355. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11356. if (!this._texture) {
  11357. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11358. if (this._deleteBuffer) {
  11359. delete this._buffer;
  11360. }
  11361. }
  11362. };
  11363. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11364. x -= this.uOffset + 0.5;
  11365. y -= this.vOffset + 0.5;
  11366. z -= 0.5;
  11367. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11368. t.x *= this.uScale;
  11369. t.y *= this.vScale;
  11370. t.x += 0.5;
  11371. t.y += 0.5;
  11372. t.z += 0.5;
  11373. };
  11374. Texture.prototype.getTextureMatrix = function () {
  11375. 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) {
  11376. return this._cachedTextureMatrix;
  11377. }
  11378. this._cachedUOffset = this.uOffset;
  11379. this._cachedVOffset = this.vOffset;
  11380. this._cachedUScale = this.uScale;
  11381. this._cachedVScale = this.vScale;
  11382. this._cachedUAng = this.uAng;
  11383. this._cachedVAng = this.vAng;
  11384. this._cachedWAng = this.wAng;
  11385. if (!this._cachedTextureMatrix) {
  11386. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11387. this._rowGenerationMatrix = new BABYLON.Matrix();
  11388. this._t0 = BABYLON.Vector3.Zero();
  11389. this._t1 = BABYLON.Vector3.Zero();
  11390. this._t2 = BABYLON.Vector3.Zero();
  11391. }
  11392. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11393. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11394. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11395. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11396. this._t1.subtractInPlace(this._t0);
  11397. this._t2.subtractInPlace(this._t0);
  11398. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11399. this._cachedTextureMatrix.m[0] = this._t1.x;
  11400. this._cachedTextureMatrix.m[1] = this._t1.y;
  11401. this._cachedTextureMatrix.m[2] = this._t1.z;
  11402. this._cachedTextureMatrix.m[4] = this._t2.x;
  11403. this._cachedTextureMatrix.m[5] = this._t2.y;
  11404. this._cachedTextureMatrix.m[6] = this._t2.z;
  11405. this._cachedTextureMatrix.m[8] = this._t0.x;
  11406. this._cachedTextureMatrix.m[9] = this._t0.y;
  11407. this._cachedTextureMatrix.m[10] = this._t0.z;
  11408. return this._cachedTextureMatrix;
  11409. };
  11410. Texture.prototype.getReflectionTextureMatrix = function () {
  11411. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11412. return this._cachedTextureMatrix;
  11413. }
  11414. if (!this._cachedTextureMatrix) {
  11415. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11416. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11417. }
  11418. this._cachedCoordinatesMode = this.coordinatesMode;
  11419. switch (this.coordinatesMode) {
  11420. case BABYLON.Texture.SPHERICAL_MODE:
  11421. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11422. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11423. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11424. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11425. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11426. break;
  11427. case BABYLON.Texture.PLANAR_MODE:
  11428. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11429. this._cachedTextureMatrix[0] = this.uScale;
  11430. this._cachedTextureMatrix[5] = this.vScale;
  11431. this._cachedTextureMatrix[12] = this.uOffset;
  11432. this._cachedTextureMatrix[13] = this.vOffset;
  11433. break;
  11434. case BABYLON.Texture.PROJECTION_MODE:
  11435. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11436. this._projectionModeMatrix.m[0] = 0.5;
  11437. this._projectionModeMatrix.m[5] = -0.5;
  11438. this._projectionModeMatrix.m[10] = 0.0;
  11439. this._projectionModeMatrix.m[12] = 0.5;
  11440. this._projectionModeMatrix.m[13] = 0.5;
  11441. this._projectionModeMatrix.m[14] = 1.0;
  11442. this._projectionModeMatrix.m[15] = 1.0;
  11443. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11444. break;
  11445. default:
  11446. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11447. break;
  11448. }
  11449. return this._cachedTextureMatrix;
  11450. };
  11451. Texture.prototype.clone = function () {
  11452. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11453. // Base texture
  11454. newTexture.hasAlpha = this.hasAlpha;
  11455. newTexture.level = this.level;
  11456. newTexture.wrapU = this.wrapU;
  11457. newTexture.wrapV = this.wrapV;
  11458. newTexture.coordinatesIndex = this.coordinatesIndex;
  11459. newTexture.coordinatesMode = this.coordinatesMode;
  11460. // Texture
  11461. newTexture.uOffset = this.uOffset;
  11462. newTexture.vOffset = this.vOffset;
  11463. newTexture.uScale = this.uScale;
  11464. newTexture.vScale = this.vScale;
  11465. newTexture.uAng = this.uAng;
  11466. newTexture.vAng = this.vAng;
  11467. newTexture.wAng = this.wAng;
  11468. return newTexture;
  11469. };
  11470. // Statics
  11471. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11472. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11473. if (typeof onLoad === "undefined") { onLoad = null; }
  11474. if (typeof onError === "undefined") { onError = null; }
  11475. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11476. };
  11477. Texture.NEAREST_SAMPLINGMODE = 1;
  11478. Texture.BILINEAR_SAMPLINGMODE = 2;
  11479. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11480. Texture.EXPLICIT_MODE = 0;
  11481. Texture.SPHERICAL_MODE = 1;
  11482. Texture.PLANAR_MODE = 2;
  11483. Texture.CUBIC_MODE = 3;
  11484. Texture.PROJECTION_MODE = 4;
  11485. Texture.SKYBOX_MODE = 5;
  11486. Texture.CLAMP_ADDRESSMODE = 0;
  11487. Texture.WRAP_ADDRESSMODE = 1;
  11488. Texture.MIRROR_ADDRESSMODE = 2;
  11489. return Texture;
  11490. })(BABYLON.BaseTexture);
  11491. BABYLON.Texture = Texture;
  11492. })(BABYLON || (BABYLON = {}));
  11493. //# sourceMappingURL=babylon.texture.js.map
  11494. var BABYLON;
  11495. (function (BABYLON) {
  11496. var CubeTexture = (function (_super) {
  11497. __extends(CubeTexture, _super);
  11498. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11499. _super.call(this, scene);
  11500. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11501. this.name = rootUrl;
  11502. this.url = rootUrl;
  11503. this._noMipmap = noMipmap;
  11504. this.hasAlpha = false;
  11505. this._texture = this._getFromCache(rootUrl, noMipmap);
  11506. if (!extensions) {
  11507. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11508. }
  11509. this._extensions = extensions;
  11510. if (!this._texture) {
  11511. if (!scene.useDelayedTextureLoading) {
  11512. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11513. } else {
  11514. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11515. }
  11516. }
  11517. this.isCube = true;
  11518. this._textureMatrix = BABYLON.Matrix.Identity();
  11519. }
  11520. CubeTexture.prototype.clone = function () {
  11521. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11522. // Base texture
  11523. newTexture.level = this.level;
  11524. newTexture.wrapU = this.wrapU;
  11525. newTexture.wrapV = this.wrapV;
  11526. newTexture.coordinatesIndex = this.coordinatesIndex;
  11527. newTexture.coordinatesMode = this.coordinatesMode;
  11528. return newTexture;
  11529. };
  11530. // Methods
  11531. CubeTexture.prototype.delayLoad = function () {
  11532. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11533. return;
  11534. }
  11535. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11536. this._texture = this._getFromCache(this.url, this._noMipmap);
  11537. if (!this._texture) {
  11538. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11539. }
  11540. };
  11541. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11542. return this._textureMatrix;
  11543. };
  11544. return CubeTexture;
  11545. })(BABYLON.BaseTexture);
  11546. BABYLON.CubeTexture = CubeTexture;
  11547. })(BABYLON || (BABYLON = {}));
  11548. //# sourceMappingURL=babylon.cubeTexture.js.map
  11549. var BABYLON;
  11550. (function (BABYLON) {
  11551. var RenderTargetTexture = (function (_super) {
  11552. __extends(RenderTargetTexture, _super);
  11553. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11554. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  11555. if (typeof type === "undefined") { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11556. _super.call(this, null, scene, !generateMipMaps);
  11557. this.renderList = new Array();
  11558. this.renderParticles = true;
  11559. this.renderSprites = false;
  11560. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11561. this._currentRefreshId = -1;
  11562. this._refreshRate = 1;
  11563. this.name = name;
  11564. this.isRenderTarget = true;
  11565. this._size = size;
  11566. this._generateMipMaps = generateMipMaps;
  11567. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11568. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11569. // Rendering groups
  11570. this._renderingManager = new BABYLON.RenderingManager(scene);
  11571. }
  11572. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11573. this._currentRefreshId = -1;
  11574. };
  11575. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11576. get: function () {
  11577. return this._refreshRate;
  11578. },
  11579. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11580. set: function (value) {
  11581. this._refreshRate = value;
  11582. this.resetRefreshCounter();
  11583. },
  11584. enumerable: true,
  11585. configurable: true
  11586. });
  11587. RenderTargetTexture.prototype._shouldRender = function () {
  11588. if (this._currentRefreshId === -1) {
  11589. this._currentRefreshId = 1;
  11590. return true;
  11591. }
  11592. if (this.refreshRate === this._currentRefreshId) {
  11593. this._currentRefreshId = 1;
  11594. return true;
  11595. }
  11596. this._currentRefreshId++;
  11597. return false;
  11598. };
  11599. RenderTargetTexture.prototype.isReady = function () {
  11600. if (!this.getScene().renderTargetsEnabled) {
  11601. return false;
  11602. }
  11603. return _super.prototype.isReady.call(this);
  11604. };
  11605. RenderTargetTexture.prototype.getRenderSize = function () {
  11606. return this._size;
  11607. };
  11608. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11609. get: function () {
  11610. return true;
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. RenderTargetTexture.prototype.scale = function (ratio) {
  11616. var newSize = this._size * ratio;
  11617. this.resize(newSize, this._generateMipMaps);
  11618. };
  11619. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11620. this.releaseInternalTexture();
  11621. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11622. };
  11623. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11624. var scene = this.getScene();
  11625. var engine = scene.getEngine();
  11626. if (this._waitingRenderList) {
  11627. this.renderList = [];
  11628. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11629. var id = this._waitingRenderList[index];
  11630. this.renderList.push(scene.getMeshByID(id));
  11631. }
  11632. delete this._waitingRenderList;
  11633. }
  11634. if (this.renderList && this.renderList.length === 0) {
  11635. return;
  11636. }
  11637. // Bind
  11638. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11639. engine.bindFramebuffer(this._texture);
  11640. }
  11641. // Clear
  11642. engine.clear(scene.clearColor, true, true);
  11643. this._renderingManager.reset();
  11644. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11645. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11646. var mesh = currentRenderList[meshIndex];
  11647. if (mesh) {
  11648. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11649. // Reset _currentRefreshId
  11650. this.resetRefreshCounter();
  11651. continue;
  11652. }
  11653. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  11654. mesh._activate(scene.getRenderId());
  11655. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11656. var subMesh = mesh.subMeshes[subIndex];
  11657. scene._activeVertices += subMesh.indexCount;
  11658. this._renderingManager.dispatch(subMesh);
  11659. }
  11660. }
  11661. }
  11662. }
  11663. if (!this._doNotChangeAspectRatio) {
  11664. scene.updateTransformMatrix(true);
  11665. }
  11666. if (this.onBeforeRender) {
  11667. this.onBeforeRender();
  11668. }
  11669. // Render
  11670. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  11671. if (useCameraPostProcess) {
  11672. scene.postProcessManager._finalizeFrame(false, this._texture);
  11673. }
  11674. if (this.onAfterRender) {
  11675. this.onAfterRender();
  11676. }
  11677. // Unbind
  11678. engine.unBindFramebuffer(this._texture);
  11679. if (!this._doNotChangeAspectRatio) {
  11680. scene.updateTransformMatrix(true);
  11681. }
  11682. };
  11683. RenderTargetTexture.prototype.clone = function () {
  11684. var textureSize = this.getSize();
  11685. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11686. // Base texture
  11687. newTexture.hasAlpha = this.hasAlpha;
  11688. newTexture.level = this.level;
  11689. // RenderTarget Texture
  11690. newTexture.coordinatesMode = this.coordinatesMode;
  11691. newTexture.renderList = this.renderList.slice(0);
  11692. return newTexture;
  11693. };
  11694. return RenderTargetTexture;
  11695. })(BABYLON.Texture);
  11696. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11697. })(BABYLON || (BABYLON = {}));
  11698. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11699. var BABYLON;
  11700. (function (BABYLON) {
  11701. var ProceduralTexture = (function (_super) {
  11702. __extends(ProceduralTexture, _super);
  11703. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11704. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11705. _super.call(this, null, scene, !generateMipMaps);
  11706. this._currentRefreshId = -1;
  11707. this._refreshRate = 1;
  11708. this._vertexDeclaration = [2];
  11709. this._vertexStrideSize = 2 * 4;
  11710. this._uniforms = new Array();
  11711. this._samplers = new Array();
  11712. this._textures = new Array();
  11713. this._floats = new Array();
  11714. this._floatsArrays = {};
  11715. this._colors3 = new Array();
  11716. this._colors4 = new Array();
  11717. this._vectors2 = new Array();
  11718. this._vectors3 = new Array();
  11719. this._matrices = new Array();
  11720. this._fallbackTextureUsed = false;
  11721. scene._proceduralTextures.push(this);
  11722. this.name = name;
  11723. this.isRenderTarget = true;
  11724. this._size = size;
  11725. this._generateMipMaps = generateMipMaps;
  11726. this.setFragment(fragment);
  11727. this._fallbackTexture = fallbackTexture;
  11728. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11729. // VBO
  11730. var vertices = [];
  11731. vertices.push(1, 1);
  11732. vertices.push(-1, 1);
  11733. vertices.push(-1, -1);
  11734. vertices.push(1, -1);
  11735. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11736. // Indices
  11737. var indices = [];
  11738. indices.push(0);
  11739. indices.push(1);
  11740. indices.push(2);
  11741. indices.push(0);
  11742. indices.push(2);
  11743. indices.push(3);
  11744. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11745. }
  11746. ProceduralTexture.prototype.reset = function () {
  11747. if (this._effect === undefined) {
  11748. return;
  11749. }
  11750. var engine = this.getScene().getEngine();
  11751. engine._releaseEffect(this._effect);
  11752. };
  11753. ProceduralTexture.prototype.isReady = function () {
  11754. var _this = this;
  11755. var engine = this.getScene().getEngine();
  11756. var shaders;
  11757. if (!this._fragment) {
  11758. return false;
  11759. }
  11760. if (this._fallbackTextureUsed) {
  11761. return true;
  11762. }
  11763. if (this._fragment.fragmentElement !== undefined) {
  11764. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11765. } else {
  11766. shaders = { vertex: "procedural", fragment: this._fragment };
  11767. }
  11768. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11769. _this.releaseInternalTexture();
  11770. if (_this._fallbackTexture) {
  11771. _this._texture = _this._fallbackTexture._texture;
  11772. _this._texture.references++;
  11773. }
  11774. _this._fallbackTextureUsed = true;
  11775. });
  11776. return this._effect.isReady();
  11777. };
  11778. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11779. this._currentRefreshId = -1;
  11780. };
  11781. ProceduralTexture.prototype.setFragment = function (fragment) {
  11782. this._fragment = fragment;
  11783. };
  11784. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11785. get: function () {
  11786. return this._refreshRate;
  11787. },
  11788. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11789. set: function (value) {
  11790. this._refreshRate = value;
  11791. this.resetRefreshCounter();
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. ProceduralTexture.prototype._shouldRender = function () {
  11797. if (!this.isReady() || !this._texture) {
  11798. return false;
  11799. }
  11800. if (this._fallbackTextureUsed) {
  11801. return false;
  11802. }
  11803. if (this._currentRefreshId === -1) {
  11804. this._currentRefreshId = 1;
  11805. return true;
  11806. }
  11807. if (this.refreshRate === this._currentRefreshId) {
  11808. this._currentRefreshId = 1;
  11809. return true;
  11810. }
  11811. this._currentRefreshId++;
  11812. return false;
  11813. };
  11814. ProceduralTexture.prototype.getRenderSize = function () {
  11815. return this._size;
  11816. };
  11817. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11818. if (this._fallbackTextureUsed) {
  11819. return;
  11820. }
  11821. this.releaseInternalTexture();
  11822. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11823. };
  11824. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11825. if (this._uniforms.indexOf(uniformName) === -1) {
  11826. this._uniforms.push(uniformName);
  11827. }
  11828. };
  11829. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11830. if (this._samplers.indexOf(name) === -1) {
  11831. this._samplers.push(name);
  11832. }
  11833. this._textures[name] = texture;
  11834. return this;
  11835. };
  11836. ProceduralTexture.prototype.setFloat = function (name, value) {
  11837. this._checkUniform(name);
  11838. this._floats[name] = value;
  11839. return this;
  11840. };
  11841. ProceduralTexture.prototype.setFloats = function (name, value) {
  11842. this._checkUniform(name);
  11843. this._floatsArrays[name] = value;
  11844. return this;
  11845. };
  11846. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11847. this._checkUniform(name);
  11848. this._colors3[name] = value;
  11849. return this;
  11850. };
  11851. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11852. this._checkUniform(name);
  11853. this._colors4[name] = value;
  11854. return this;
  11855. };
  11856. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11857. this._checkUniform(name);
  11858. this._vectors2[name] = value;
  11859. return this;
  11860. };
  11861. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11862. this._checkUniform(name);
  11863. this._vectors3[name] = value;
  11864. return this;
  11865. };
  11866. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11867. this._checkUniform(name);
  11868. this._matrices[name] = value;
  11869. return this;
  11870. };
  11871. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11872. var scene = this.getScene();
  11873. var engine = scene.getEngine();
  11874. engine.bindFramebuffer(this._texture);
  11875. // Clear
  11876. engine.clear(scene.clearColor, true, true);
  11877. // Render
  11878. engine.enableEffect(this._effect);
  11879. engine.setState(false);
  11880. for (var name in this._textures) {
  11881. this._effect.setTexture(name, this._textures[name]);
  11882. }
  11883. for (name in this._floats) {
  11884. this._effect.setFloat(name, this._floats[name]);
  11885. }
  11886. for (name in this._floatsArrays) {
  11887. this._effect.setArray(name, this._floatsArrays[name]);
  11888. }
  11889. for (name in this._colors3) {
  11890. this._effect.setColor3(name, this._colors3[name]);
  11891. }
  11892. for (name in this._colors4) {
  11893. var color = this._colors4[name];
  11894. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11895. }
  11896. for (name in this._vectors2) {
  11897. this._effect.setVector2(name, this._vectors2[name]);
  11898. }
  11899. for (name in this._vectors3) {
  11900. this._effect.setVector3(name, this._vectors3[name]);
  11901. }
  11902. for (name in this._matrices) {
  11903. this._effect.setMatrix(name, this._matrices[name]);
  11904. }
  11905. // VBOs
  11906. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11907. // Draw order
  11908. engine.draw(true, 0, 6);
  11909. // Unbind
  11910. engine.unBindFramebuffer(this._texture);
  11911. };
  11912. ProceduralTexture.prototype.clone = function () {
  11913. var textureSize = this.getSize();
  11914. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11915. // Base texture
  11916. newTexture.hasAlpha = this.hasAlpha;
  11917. newTexture.level = this.level;
  11918. // RenderTarget Texture
  11919. newTexture.coordinatesMode = this.coordinatesMode;
  11920. return newTexture;
  11921. };
  11922. ProceduralTexture.prototype.dispose = function () {
  11923. var index = this.getScene()._proceduralTextures.indexOf(this);
  11924. if (index >= 0) {
  11925. this.getScene()._proceduralTextures.splice(index, 1);
  11926. }
  11927. _super.prototype.dispose.call(this);
  11928. };
  11929. return ProceduralTexture;
  11930. })(BABYLON.Texture);
  11931. BABYLON.ProceduralTexture = ProceduralTexture;
  11932. })(BABYLON || (BABYLON = {}));
  11933. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11934. var BABYLON;
  11935. (function (BABYLON) {
  11936. var WoodProceduralTexture = (function (_super) {
  11937. __extends(WoodProceduralTexture, _super);
  11938. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11939. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11940. this._ampScale = 100.0;
  11941. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11942. this.updateShaderUniforms();
  11943. this.refreshRate = 0;
  11944. }
  11945. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11946. this.setFloat("ampScale", this._ampScale);
  11947. this.setColor3("woodColor", this._woodColor);
  11948. };
  11949. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11950. get: function () {
  11951. return this._ampScale;
  11952. },
  11953. set: function (value) {
  11954. this._ampScale = value;
  11955. this.updateShaderUniforms();
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11961. get: function () {
  11962. return this._woodColor;
  11963. },
  11964. set: function (value) {
  11965. this._woodColor = value;
  11966. this.updateShaderUniforms();
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. return WoodProceduralTexture;
  11972. })(BABYLON.ProceduralTexture);
  11973. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11974. var FireProceduralTexture = (function (_super) {
  11975. __extends(FireProceduralTexture, _super);
  11976. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11977. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11978. this._time = 0.0;
  11979. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11980. this._shift = 1.6;
  11981. this._autoGenerateTime = true;
  11982. this._alphaThreshold = 0.5;
  11983. this._fireColors = FireProceduralTexture.RedFireColors;
  11984. this.updateShaderUniforms();
  11985. this.refreshRate = 1;
  11986. }
  11987. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11988. this.setFloat("time", this._time);
  11989. this.setVector2("speed", this._speed);
  11990. this.setFloat("shift", this._shift);
  11991. this.setColor3("c1", this._fireColors[0]);
  11992. this.setColor3("c2", this._fireColors[1]);
  11993. this.setColor3("c3", this._fireColors[2]);
  11994. this.setColor3("c4", this._fireColors[3]);
  11995. this.setColor3("c5", this._fireColors[4]);
  11996. this.setColor3("c6", this._fireColors[5]);
  11997. this.setFloat("alphaThreshold", this._alphaThreshold);
  11998. };
  11999. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12000. if (this._autoGenerateTime) {
  12001. this._time += this.getScene().getAnimationRatio() * 0.03;
  12002. this.updateShaderUniforms();
  12003. }
  12004. _super.prototype.render.call(this, useCameraPostProcess);
  12005. };
  12006. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12007. get: function () {
  12008. return [
  12009. new BABYLON.Color3(0.5, 0.0, 1.0),
  12010. new BABYLON.Color3(0.9, 0.0, 1.0),
  12011. new BABYLON.Color3(0.2, 0.0, 1.0),
  12012. new BABYLON.Color3(1.0, 0.9, 1.0),
  12013. new BABYLON.Color3(0.1, 0.1, 1.0),
  12014. new BABYLON.Color3(0.9, 0.9, 1.0)
  12015. ];
  12016. },
  12017. enumerable: true,
  12018. configurable: true
  12019. });
  12020. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12021. get: function () {
  12022. return [
  12023. new BABYLON.Color3(0.5, 1.0, 0.0),
  12024. new BABYLON.Color3(0.5, 1.0, 0.0),
  12025. new BABYLON.Color3(0.3, 0.4, 0.0),
  12026. new BABYLON.Color3(0.5, 1.0, 0.0),
  12027. new BABYLON.Color3(0.2, 0.0, 0.0),
  12028. new BABYLON.Color3(0.5, 1.0, 0.0)
  12029. ];
  12030. },
  12031. enumerable: true,
  12032. configurable: true
  12033. });
  12034. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12035. get: function () {
  12036. return [
  12037. new BABYLON.Color3(0.5, 0.0, 0.1),
  12038. new BABYLON.Color3(0.9, 0.0, 0.0),
  12039. new BABYLON.Color3(0.2, 0.0, 0.0),
  12040. new BABYLON.Color3(1.0, 0.9, 0.0),
  12041. new BABYLON.Color3(0.1, 0.1, 0.1),
  12042. new BABYLON.Color3(0.9, 0.9, 0.9)
  12043. ];
  12044. },
  12045. enumerable: true,
  12046. configurable: true
  12047. });
  12048. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12049. get: function () {
  12050. return [
  12051. new BABYLON.Color3(0.1, 0.0, 0.5),
  12052. new BABYLON.Color3(0.0, 0.0, 0.5),
  12053. new BABYLON.Color3(0.1, 0.0, 0.2),
  12054. new BABYLON.Color3(0.0, 0.0, 1.0),
  12055. new BABYLON.Color3(0.1, 0.2, 0.3),
  12056. new BABYLON.Color3(0.0, 0.2, 0.9)
  12057. ];
  12058. },
  12059. enumerable: true,
  12060. configurable: true
  12061. });
  12062. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12063. get: function () {
  12064. return this._fireColors;
  12065. },
  12066. set: function (value) {
  12067. this._fireColors = value;
  12068. this.updateShaderUniforms();
  12069. },
  12070. enumerable: true,
  12071. configurable: true
  12072. });
  12073. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12074. get: function () {
  12075. return this._time;
  12076. },
  12077. set: function (value) {
  12078. this._time = value;
  12079. this.updateShaderUniforms();
  12080. },
  12081. enumerable: true,
  12082. configurable: true
  12083. });
  12084. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12085. get: function () {
  12086. return this._speed;
  12087. },
  12088. set: function (value) {
  12089. this._speed = value;
  12090. this.updateShaderUniforms();
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12096. get: function () {
  12097. return this._shift;
  12098. },
  12099. set: function (value) {
  12100. this._shift = value;
  12101. this.updateShaderUniforms();
  12102. },
  12103. enumerable: true,
  12104. configurable: true
  12105. });
  12106. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12107. get: function () {
  12108. return this._alphaThreshold;
  12109. },
  12110. set: function (value) {
  12111. this._alphaThreshold = value;
  12112. this.updateShaderUniforms();
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. return FireProceduralTexture;
  12118. })(BABYLON.ProceduralTexture);
  12119. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12120. var CloudProceduralTexture = (function (_super) {
  12121. __extends(CloudProceduralTexture, _super);
  12122. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12123. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12124. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12125. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12126. this.updateShaderUniforms();
  12127. this.refreshRate = 0;
  12128. }
  12129. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12130. this.setColor3("skyColor", this._skyColor);
  12131. this.setColor3("cloudColor", this._cloudColor);
  12132. };
  12133. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12134. get: function () {
  12135. return this._skyColor;
  12136. },
  12137. set: function (value) {
  12138. this._skyColor = value;
  12139. this.updateShaderUniforms();
  12140. },
  12141. enumerable: true,
  12142. configurable: true
  12143. });
  12144. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12145. get: function () {
  12146. return this._cloudColor;
  12147. },
  12148. set: function (value) {
  12149. this._cloudColor = value;
  12150. this.updateShaderUniforms();
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. return CloudProceduralTexture;
  12156. })(BABYLON.ProceduralTexture);
  12157. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12158. var GrassProceduralTexture = (function (_super) {
  12159. __extends(GrassProceduralTexture, _super);
  12160. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12161. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12162. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12163. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12164. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12165. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12166. this._grassColors = [
  12167. new BABYLON.Color3(0.29, 0.38, 0.02),
  12168. new BABYLON.Color3(0.36, 0.49, 0.09),
  12169. new BABYLON.Color3(0.51, 0.6, 0.28)
  12170. ];
  12171. this.updateShaderUniforms();
  12172. this.refreshRate = 0;
  12173. }
  12174. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12175. this.setColor3("herb1Color", this._grassColors[0]);
  12176. this.setColor3("herb2Color", this._grassColors[1]);
  12177. this.setColor3("herb3Color", this._grassColors[2]);
  12178. this.setColor3("groundColor", this._groundColor);
  12179. };
  12180. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12181. get: function () {
  12182. return this._grassColors;
  12183. },
  12184. set: function (value) {
  12185. this._grassColors = value;
  12186. this.updateShaderUniforms();
  12187. },
  12188. enumerable: true,
  12189. configurable: true
  12190. });
  12191. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12192. get: function () {
  12193. return this._groundColor;
  12194. },
  12195. set: function (value) {
  12196. this.groundColor = value;
  12197. this.updateShaderUniforms();
  12198. },
  12199. enumerable: true,
  12200. configurable: true
  12201. });
  12202. return GrassProceduralTexture;
  12203. })(BABYLON.ProceduralTexture);
  12204. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12205. var RoadProceduralTexture = (function (_super) {
  12206. __extends(RoadProceduralTexture, _super);
  12207. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12208. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12209. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12210. this.updateShaderUniforms();
  12211. this.refreshRate = 0;
  12212. }
  12213. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12214. this.setColor3("roadColor", this._roadColor);
  12215. };
  12216. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12217. get: function () {
  12218. return this._roadColor;
  12219. },
  12220. set: function (value) {
  12221. this._roadColor = value;
  12222. this.updateShaderUniforms();
  12223. },
  12224. enumerable: true,
  12225. configurable: true
  12226. });
  12227. return RoadProceduralTexture;
  12228. })(BABYLON.ProceduralTexture);
  12229. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12230. var BrickProceduralTexture = (function (_super) {
  12231. __extends(BrickProceduralTexture, _super);
  12232. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12233. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12234. this._numberOfBricksHeight = 15;
  12235. this._numberOfBricksWidth = 5;
  12236. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12237. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12238. this.updateShaderUniforms();
  12239. this.refreshRate = 0;
  12240. }
  12241. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12242. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12243. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12244. this.setColor3("brickColor", this._brickColor);
  12245. this.setColor3("jointColor", this._jointColor);
  12246. };
  12247. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12248. get: function () {
  12249. return this._numberOfBricksHeight;
  12250. },
  12251. enumerable: true,
  12252. configurable: true
  12253. });
  12254. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12255. set: function (value) {
  12256. this._numberOfBricksHeight = value;
  12257. this.updateShaderUniforms();
  12258. },
  12259. enumerable: true,
  12260. configurable: true
  12261. });
  12262. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12263. get: function () {
  12264. return this._numberOfBricksWidth;
  12265. },
  12266. set: function (value) {
  12267. this._numberOfBricksHeight = value;
  12268. this.updateShaderUniforms();
  12269. },
  12270. enumerable: true,
  12271. configurable: true
  12272. });
  12273. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12274. get: function () {
  12275. return this._jointColor;
  12276. },
  12277. set: function (value) {
  12278. this._jointColor = value;
  12279. this.updateShaderUniforms();
  12280. },
  12281. enumerable: true,
  12282. configurable: true
  12283. });
  12284. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12285. get: function () {
  12286. return this._brickColor;
  12287. },
  12288. set: function (value) {
  12289. this._brickColor = value;
  12290. this.updateShaderUniforms();
  12291. },
  12292. enumerable: true,
  12293. configurable: true
  12294. });
  12295. return BrickProceduralTexture;
  12296. })(BABYLON.ProceduralTexture);
  12297. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12298. var MarbleProceduralTexture = (function (_super) {
  12299. __extends(MarbleProceduralTexture, _super);
  12300. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12301. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12302. this._numberOfTilesHeight = 3;
  12303. this._numberOfTilesWidth = 3;
  12304. this._amplitude = 9.0;
  12305. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12306. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12307. this.updateShaderUniforms();
  12308. this.refreshRate = 0;
  12309. }
  12310. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12311. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12312. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12313. this.setFloat("amplitude", this._amplitude);
  12314. this.setColor3("marbleColor", this._marbleColor);
  12315. this.setColor3("jointColor", this._jointColor);
  12316. };
  12317. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12318. get: function () {
  12319. return this._numberOfTilesHeight;
  12320. },
  12321. set: function (value) {
  12322. this._numberOfTilesHeight = value;
  12323. this.updateShaderUniforms();
  12324. },
  12325. enumerable: true,
  12326. configurable: true
  12327. });
  12328. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12329. get: function () {
  12330. return this._numberOfTilesWidth;
  12331. },
  12332. set: function (value) {
  12333. this._numberOfTilesWidth = value;
  12334. this.updateShaderUniforms();
  12335. },
  12336. enumerable: true,
  12337. configurable: true
  12338. });
  12339. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12340. get: function () {
  12341. return this._jointColor;
  12342. },
  12343. set: function (value) {
  12344. this._jointColor = value;
  12345. this.updateShaderUniforms();
  12346. },
  12347. enumerable: true,
  12348. configurable: true
  12349. });
  12350. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12351. get: function () {
  12352. return this._marbleColor;
  12353. },
  12354. set: function (value) {
  12355. this._marbleColor = value;
  12356. this.updateShaderUniforms();
  12357. },
  12358. enumerable: true,
  12359. configurable: true
  12360. });
  12361. return MarbleProceduralTexture;
  12362. })(BABYLON.ProceduralTexture);
  12363. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12364. })(BABYLON || (BABYLON = {}));
  12365. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12366. var BABYLON;
  12367. (function (BABYLON) {
  12368. var CustomProceduralTexture = (function (_super) {
  12369. __extends(CustomProceduralTexture, _super);
  12370. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12371. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12372. this._animate = true;
  12373. this._time = 0;
  12374. this._texturePath = texturePath;
  12375. //Try to load json
  12376. this.loadJson(texturePath);
  12377. this.refreshRate = 1;
  12378. }
  12379. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12380. var _this = this;
  12381. var that = this;
  12382. function noConfigFile() {
  12383. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12384. try {
  12385. that.setFragment(that._texturePath);
  12386. } catch (ex) {
  12387. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12388. }
  12389. }
  12390. var configFileUrl = jsonUrl + "/config.json";
  12391. var xhr = new XMLHttpRequest();
  12392. xhr.open("GET", configFileUrl, true);
  12393. xhr.addEventListener("load", function () {
  12394. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12395. try {
  12396. _this._config = JSON.parse(xhr.response);
  12397. _this.updateShaderUniforms();
  12398. _this.updateTextures();
  12399. _this.setFragment(_this._texturePath + "/custom");
  12400. _this._animate = _this._config.animate;
  12401. _this.refreshRate = _this._config.refreshrate;
  12402. } catch (ex) {
  12403. noConfigFile();
  12404. }
  12405. } else {
  12406. noConfigFile();
  12407. }
  12408. }, false);
  12409. xhr.addEventListener("error", function (event) {
  12410. noConfigFile();
  12411. }, false);
  12412. try {
  12413. xhr.send();
  12414. } catch (ex) {
  12415. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12416. }
  12417. };
  12418. CustomProceduralTexture.prototype.isReady = function () {
  12419. if (!_super.prototype.isReady.call(this)) {
  12420. return false;
  12421. }
  12422. for (var name in this._textures) {
  12423. var texture = this._textures[name];
  12424. if (!texture.isReady()) {
  12425. return false;
  12426. }
  12427. }
  12428. return true;
  12429. };
  12430. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12431. if (this._animate) {
  12432. this._time += this.getScene().getAnimationRatio() * 0.03;
  12433. this.updateShaderUniforms();
  12434. }
  12435. _super.prototype.render.call(this, useCameraPostProcess);
  12436. };
  12437. CustomProceduralTexture.prototype.updateTextures = function () {
  12438. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12439. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12440. }
  12441. };
  12442. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12443. if (this._config) {
  12444. for (var j = 0; j < this._config.uniforms.length; j++) {
  12445. var uniform = this._config.uniforms[j];
  12446. switch (uniform.type) {
  12447. case "float":
  12448. this.setFloat(uniform.name, uniform.value);
  12449. break;
  12450. case "color3":
  12451. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12452. break;
  12453. case "color4":
  12454. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12455. break;
  12456. case "vector2":
  12457. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12458. break;
  12459. case "vector3":
  12460. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12461. break;
  12462. }
  12463. }
  12464. }
  12465. this.setFloat("time", this._time);
  12466. };
  12467. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12468. get: function () {
  12469. return this._animate;
  12470. },
  12471. set: function (value) {
  12472. this._animate = value;
  12473. },
  12474. enumerable: true,
  12475. configurable: true
  12476. });
  12477. return CustomProceduralTexture;
  12478. })(BABYLON.ProceduralTexture);
  12479. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12480. })(BABYLON || (BABYLON = {}));
  12481. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12482. var BABYLON;
  12483. (function (BABYLON) {
  12484. var MirrorTexture = (function (_super) {
  12485. __extends(MirrorTexture, _super);
  12486. function MirrorTexture(name, size, scene, generateMipMaps) {
  12487. var _this = this;
  12488. _super.call(this, name, size, scene, generateMipMaps, true);
  12489. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12490. this._transformMatrix = BABYLON.Matrix.Zero();
  12491. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12492. this.onBeforeRender = function () {
  12493. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12494. _this._savedViewMatrix = scene.getViewMatrix();
  12495. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12496. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12497. scene.clipPlane = _this.mirrorPlane;
  12498. scene.getEngine().cullBackFaces = false;
  12499. };
  12500. this.onAfterRender = function () {
  12501. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12502. scene.getEngine().cullBackFaces = true;
  12503. delete scene.clipPlane;
  12504. };
  12505. }
  12506. MirrorTexture.prototype.clone = function () {
  12507. var textureSize = this.getSize();
  12508. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12509. // Base texture
  12510. newTexture.hasAlpha = this.hasAlpha;
  12511. newTexture.level = this.level;
  12512. // Mirror Texture
  12513. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12514. newTexture.renderList = this.renderList.slice(0);
  12515. return newTexture;
  12516. };
  12517. return MirrorTexture;
  12518. })(BABYLON.RenderTargetTexture);
  12519. BABYLON.MirrorTexture = MirrorTexture;
  12520. })(BABYLON || (BABYLON = {}));
  12521. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12522. var BABYLON;
  12523. (function (BABYLON) {
  12524. var DynamicTexture = (function (_super) {
  12525. __extends(DynamicTexture, _super);
  12526. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12527. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12528. _super.call(this, null, scene, !generateMipMaps);
  12529. this.name = name;
  12530. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12531. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12532. this._generateMipMaps = generateMipMaps;
  12533. if (options.getContext) {
  12534. this._canvas = options;
  12535. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12536. } else {
  12537. this._canvas = document.createElement("canvas");
  12538. if (options.width) {
  12539. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12540. } else {
  12541. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12542. }
  12543. }
  12544. var textureSize = this.getSize();
  12545. this._canvas.width = textureSize.width;
  12546. this._canvas.height = textureSize.height;
  12547. this._context = this._canvas.getContext("2d");
  12548. }
  12549. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12550. get: function () {
  12551. return true;
  12552. },
  12553. enumerable: true,
  12554. configurable: true
  12555. });
  12556. DynamicTexture.prototype.scale = function (ratio) {
  12557. var textureSize = this.getSize();
  12558. textureSize.width *= ratio;
  12559. textureSize.height *= ratio;
  12560. this._canvas.width = textureSize.width;
  12561. this._canvas.height = textureSize.height;
  12562. this.releaseInternalTexture();
  12563. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12564. };
  12565. DynamicTexture.prototype.getContext = function () {
  12566. return this._context;
  12567. };
  12568. DynamicTexture.prototype.clear = function () {
  12569. var size = this.getSize();
  12570. this._context.fillRect(0, 0, size.width, size.height);
  12571. };
  12572. DynamicTexture.prototype.update = function (invertY) {
  12573. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12574. };
  12575. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12576. if (typeof update === "undefined") { update = true; }
  12577. var size = this.getSize();
  12578. if (clearColor) {
  12579. this._context.fillStyle = clearColor;
  12580. this._context.fillRect(0, 0, size.width, size.height);
  12581. }
  12582. this._context.font = font;
  12583. if (x === null) {
  12584. var textSize = this._context.measureText(text);
  12585. x = (size.width - textSize.width) / 2;
  12586. }
  12587. this._context.fillStyle = color;
  12588. this._context.fillText(text, x, y);
  12589. if (update) {
  12590. this.update(invertY);
  12591. }
  12592. };
  12593. DynamicTexture.prototype.clone = function () {
  12594. var textureSize = this.getSize();
  12595. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12596. // Base texture
  12597. newTexture.hasAlpha = this.hasAlpha;
  12598. newTexture.level = this.level;
  12599. // Dynamic Texture
  12600. newTexture.wrapU = this.wrapU;
  12601. newTexture.wrapV = this.wrapV;
  12602. return newTexture;
  12603. };
  12604. return DynamicTexture;
  12605. })(BABYLON.Texture);
  12606. BABYLON.DynamicTexture = DynamicTexture;
  12607. })(BABYLON || (BABYLON = {}));
  12608. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12609. var BABYLON;
  12610. (function (BABYLON) {
  12611. var VideoTexture = (function (_super) {
  12612. __extends(VideoTexture, _super);
  12613. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12614. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12615. var _this = this;
  12616. _super.call(this, null, scene, !generateMipMaps, invertY);
  12617. this._autoLaunch = true;
  12618. this.name = name;
  12619. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12620. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12621. var requiredWidth = size.width || size;
  12622. var requiredHeight = size.height || size;
  12623. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12624. var textureSize = this.getSize();
  12625. this.video = document.createElement("video");
  12626. this.video.width = textureSize.width;
  12627. this.video.height = textureSize.height;
  12628. this.video.autoplay = false;
  12629. this.video.loop = true;
  12630. this.video.addEventListener("canplaythrough", function () {
  12631. if (_this._texture) {
  12632. _this._texture.isReady = true;
  12633. }
  12634. });
  12635. urls.forEach(function (url) {
  12636. var source = document.createElement("source");
  12637. source.src = url;
  12638. _this.video.appendChild(source);
  12639. });
  12640. this._lastUpdate = BABYLON.Tools.Now;
  12641. }
  12642. VideoTexture.prototype.update = function () {
  12643. if (this._autoLaunch) {
  12644. this._autoLaunch = false;
  12645. this.video.play();
  12646. }
  12647. var now = BABYLON.Tools.Now;
  12648. if (now - this._lastUpdate < 15) {
  12649. return false;
  12650. }
  12651. this._lastUpdate = now;
  12652. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12653. return true;
  12654. };
  12655. return VideoTexture;
  12656. })(BABYLON.Texture);
  12657. BABYLON.VideoTexture = VideoTexture;
  12658. })(BABYLON || (BABYLON = {}));
  12659. //# sourceMappingURL=babylon.videoTexture.js.map
  12660. var BABYLON;
  12661. (function (BABYLON) {
  12662. var EffectFallbacks = (function () {
  12663. function EffectFallbacks() {
  12664. this._defines = {};
  12665. this._currentRank = 32;
  12666. this._maxRank = -1;
  12667. }
  12668. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12669. if (!this._defines[rank]) {
  12670. if (rank < this._currentRank) {
  12671. this._currentRank = rank;
  12672. }
  12673. if (rank > this._maxRank) {
  12674. this._maxRank = rank;
  12675. }
  12676. this._defines[rank] = new Array();
  12677. }
  12678. this._defines[rank].push(define);
  12679. };
  12680. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12681. get: function () {
  12682. return this._currentRank <= this._maxRank;
  12683. },
  12684. enumerable: true,
  12685. configurable: true
  12686. });
  12687. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12688. var currentFallbacks = this._defines[this._currentRank];
  12689. for (var index = 0; index < currentFallbacks.length; index++) {
  12690. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12691. }
  12692. this._currentRank++;
  12693. return currentDefines;
  12694. };
  12695. return EffectFallbacks;
  12696. })();
  12697. BABYLON.EffectFallbacks = EffectFallbacks;
  12698. var Effect = (function () {
  12699. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12700. var _this = this;
  12701. this._isReady = false;
  12702. this._compilationError = "";
  12703. this._valueCache = [];
  12704. this._engine = engine;
  12705. this.name = baseName;
  12706. this.defines = defines;
  12707. this._uniformsNames = uniformsNames.concat(samplers);
  12708. this._samplers = samplers;
  12709. this._attributesNames = attributesNames;
  12710. this.onError = onError;
  12711. this.onCompiled = onCompiled;
  12712. var vertexSource;
  12713. var fragmentSource;
  12714. if (baseName.vertexElement) {
  12715. vertexSource = document.getElementById(baseName.vertexElement);
  12716. if (!vertexSource) {
  12717. vertexSource = baseName.vertexElement;
  12718. }
  12719. } else {
  12720. vertexSource = baseName.vertex || baseName;
  12721. }
  12722. if (baseName.fragmentElement) {
  12723. fragmentSource = document.getElementById(baseName.fragmentElement);
  12724. if (!fragmentSource) {
  12725. fragmentSource = baseName.fragmentElement;
  12726. }
  12727. } else {
  12728. fragmentSource = baseName.fragment || baseName;
  12729. }
  12730. this._loadVertexShader(vertexSource, function (vertexCode) {
  12731. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12732. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12733. });
  12734. });
  12735. }
  12736. // Properties
  12737. Effect.prototype.isReady = function () {
  12738. return this._isReady;
  12739. };
  12740. Effect.prototype.getProgram = function () {
  12741. return this._program;
  12742. };
  12743. Effect.prototype.getAttributesNames = function () {
  12744. return this._attributesNames;
  12745. };
  12746. Effect.prototype.getAttributeLocation = function (index) {
  12747. return this._attributes[index];
  12748. };
  12749. Effect.prototype.getAttributeLocationByName = function (name) {
  12750. var index = this._attributesNames.indexOf(name);
  12751. return this._attributes[index];
  12752. };
  12753. Effect.prototype.getAttributesCount = function () {
  12754. return this._attributes.length;
  12755. };
  12756. Effect.prototype.getUniformIndex = function (uniformName) {
  12757. return this._uniformsNames.indexOf(uniformName);
  12758. };
  12759. Effect.prototype.getUniform = function (uniformName) {
  12760. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12761. };
  12762. Effect.prototype.getSamplers = function () {
  12763. return this._samplers;
  12764. };
  12765. Effect.prototype.getCompilationError = function () {
  12766. return this._compilationError;
  12767. };
  12768. // Methods
  12769. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12770. // DOM element ?
  12771. if (vertex instanceof HTMLElement) {
  12772. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12773. callback(vertexCode);
  12774. return;
  12775. }
  12776. // Is in local store ?
  12777. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12778. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12779. return;
  12780. }
  12781. var vertexShaderUrl;
  12782. if (vertex[0] === ".") {
  12783. vertexShaderUrl = vertex;
  12784. } else {
  12785. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12786. }
  12787. // Vertex shader
  12788. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12789. };
  12790. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12791. // DOM element ?
  12792. if (fragment instanceof HTMLElement) {
  12793. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12794. callback(fragmentCode);
  12795. return;
  12796. }
  12797. // Is in local store ?
  12798. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12799. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12800. return;
  12801. }
  12802. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12803. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12804. return;
  12805. }
  12806. var fragmentShaderUrl;
  12807. if (fragment[0] === ".") {
  12808. fragmentShaderUrl = fragment;
  12809. } else {
  12810. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12811. }
  12812. // Fragment shader
  12813. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12814. };
  12815. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12816. try {
  12817. var engine = this._engine;
  12818. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12819. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12820. this._attributes = engine.getAttributes(this._program, attributesNames);
  12821. for (var index = 0; index < this._samplers.length; index++) {
  12822. var sampler = this.getUniform(this._samplers[index]);
  12823. if (sampler == null) {
  12824. this._samplers.splice(index, 1);
  12825. index--;
  12826. }
  12827. }
  12828. engine.bindSamplers(this);
  12829. this._isReady = true;
  12830. if (this.onCompiled) {
  12831. this.onCompiled(this);
  12832. }
  12833. } catch (e) {
  12834. // Is it a problem with precision?
  12835. if (e.message.indexOf("highp") !== -1) {
  12836. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12837. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12838. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12839. return;
  12840. }
  12841. // Let's go through fallbacks then
  12842. if (fallbacks && fallbacks.isMoreFallbacks) {
  12843. defines = fallbacks.reduce(defines);
  12844. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12845. } else {
  12846. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12847. BABYLON.Tools.Error("Defines: " + defines);
  12848. BABYLON.Tools.Error("Error: " + e.message);
  12849. this._compilationError = e.message;
  12850. if (this.onError) {
  12851. this.onError(this, this._compilationError);
  12852. }
  12853. }
  12854. }
  12855. };
  12856. Effect.prototype._bindTexture = function (channel, texture) {
  12857. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12858. };
  12859. Effect.prototype.setTexture = function (channel, texture) {
  12860. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12861. };
  12862. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12863. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12864. };
  12865. //public _cacheMatrix(uniformName, matrix) {
  12866. // if (!this._valueCache[uniformName]) {
  12867. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12868. // }
  12869. // for (var index = 0; index < 16; index++) {
  12870. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12871. // }
  12872. //};
  12873. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12874. if (!this._valueCache[uniformName]) {
  12875. this._valueCache[uniformName] = [x, y];
  12876. return;
  12877. }
  12878. this._valueCache[uniformName][0] = x;
  12879. this._valueCache[uniformName][1] = y;
  12880. };
  12881. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12882. if (!this._valueCache[uniformName]) {
  12883. this._valueCache[uniformName] = [x, y, z];
  12884. return;
  12885. }
  12886. this._valueCache[uniformName][0] = x;
  12887. this._valueCache[uniformName][1] = y;
  12888. this._valueCache[uniformName][2] = z;
  12889. };
  12890. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12891. if (!this._valueCache[uniformName]) {
  12892. this._valueCache[uniformName] = [x, y, z, w];
  12893. return;
  12894. }
  12895. this._valueCache[uniformName][0] = x;
  12896. this._valueCache[uniformName][1] = y;
  12897. this._valueCache[uniformName][2] = z;
  12898. this._valueCache[uniformName][3] = w;
  12899. };
  12900. Effect.prototype.setArray = function (uniformName, array) {
  12901. this._engine.setArray(this.getUniform(uniformName), array);
  12902. return this;
  12903. };
  12904. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12905. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12906. return this;
  12907. };
  12908. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12909. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12910. // return;
  12911. //this._cacheMatrix(uniformName, matrix);
  12912. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12913. return this;
  12914. };
  12915. Effect.prototype.setFloat = function (uniformName, value) {
  12916. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12917. return this;
  12918. this._valueCache[uniformName] = value;
  12919. this._engine.setFloat(this.getUniform(uniformName), value);
  12920. return this;
  12921. };
  12922. Effect.prototype.setBool = function (uniformName, bool) {
  12923. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12924. return this;
  12925. this._valueCache[uniformName] = bool;
  12926. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12927. return this;
  12928. };
  12929. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12930. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12931. return this;
  12932. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12933. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12934. return this;
  12935. };
  12936. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12937. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12938. return this;
  12939. this._cacheFloat2(uniformName, x, y);
  12940. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12941. return this;
  12942. };
  12943. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12944. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12945. return this;
  12946. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12947. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12948. return this;
  12949. };
  12950. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12951. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12952. return this;
  12953. this._cacheFloat3(uniformName, x, y, z);
  12954. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12955. return this;
  12956. };
  12957. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12958. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12959. return this;
  12960. this._cacheFloat4(uniformName, x, y, z, w);
  12961. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12962. return this;
  12963. };
  12964. Effect.prototype.setColor3 = function (uniformName, color3) {
  12965. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12966. return this;
  12967. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12968. this._engine.setColor3(this.getUniform(uniformName), color3);
  12969. return this;
  12970. };
  12971. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12972. 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)
  12973. return this;
  12974. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12975. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12976. return this;
  12977. };
  12978. 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}",
  12979. 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}",
  12980. 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}",
  12981. 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}",
  12982. 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}",
  12983. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12984. 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}",
  12985. 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}",
  12986. 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}",
  12987. 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}",
  12988. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = gl_FragCoord.z / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  12989. depthVertexShader:"#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#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 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}",
  12990. 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}",
  12991. 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}",
  12992. 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}",
  12993. 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}",
  12994. 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}",
  12995. 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}",
  12996. 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}",
  12997. 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}",
  12998. 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}",
  12999. 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}",
  13000. 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}",
  13001. 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}",
  13002. 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}",
  13003. 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}",
  13004. 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}",
  13005. 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}",
  13006. 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}",
  13007. 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}",
  13008. 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}",
  13009. 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}",
  13010. 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}",
  13011. 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}",
  13012. 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}",
  13013. 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}",
  13014. 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}",
  13015. 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}",
  13016. 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}",
  13017. };
  13018. return Effect;
  13019. })();
  13020. BABYLON.Effect = Effect;
  13021. })(BABYLON || (BABYLON = {}));
  13022. //# sourceMappingURL=babylon.effect.js.map
  13023. var BABYLON;
  13024. (function (BABYLON) {
  13025. var Material = (function () {
  13026. function Material(name, scene, doNotAdd) {
  13027. this.name = name;
  13028. this.checkReadyOnEveryCall = true;
  13029. this.checkReadyOnlyOnce = false;
  13030. this.state = "";
  13031. this.alpha = 1.0;
  13032. this.backFaceCulling = true;
  13033. this._wasPreviouslyReady = false;
  13034. this._fillMode = Material.TriangleFillMode;
  13035. this.pointSize = 1.0;
  13036. this.id = name;
  13037. this._scene = scene;
  13038. if (!doNotAdd) {
  13039. scene.materials.push(this);
  13040. }
  13041. }
  13042. Object.defineProperty(Material, "TriangleFillMode", {
  13043. get: function () {
  13044. return Material._TriangleFillMode;
  13045. },
  13046. enumerable: true,
  13047. configurable: true
  13048. });
  13049. Object.defineProperty(Material, "WireFrameFillMode", {
  13050. get: function () {
  13051. return Material._WireFrameFillMode;
  13052. },
  13053. enumerable: true,
  13054. configurable: true
  13055. });
  13056. Object.defineProperty(Material, "PointFillMode", {
  13057. get: function () {
  13058. return Material._PointFillMode;
  13059. },
  13060. enumerable: true,
  13061. configurable: true
  13062. });
  13063. Object.defineProperty(Material.prototype, "wireframe", {
  13064. get: function () {
  13065. return this._fillMode === Material.WireFrameFillMode;
  13066. },
  13067. set: function (value) {
  13068. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13069. },
  13070. enumerable: true,
  13071. configurable: true
  13072. });
  13073. Object.defineProperty(Material.prototype, "pointsCloud", {
  13074. get: function () {
  13075. return this._fillMode === Material.PointFillMode;
  13076. },
  13077. set: function (value) {
  13078. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13079. },
  13080. enumerable: true,
  13081. configurable: true
  13082. });
  13083. Object.defineProperty(Material.prototype, "fillMode", {
  13084. get: function () {
  13085. return this._fillMode;
  13086. },
  13087. set: function (value) {
  13088. this._fillMode = value;
  13089. },
  13090. enumerable: true,
  13091. configurable: true
  13092. });
  13093. Material.prototype.isReady = function (mesh, useInstances) {
  13094. return true;
  13095. };
  13096. Material.prototype.getEffect = function () {
  13097. return this._effect;
  13098. };
  13099. Material.prototype.getScene = function () {
  13100. return this._scene;
  13101. };
  13102. Material.prototype.needAlphaBlending = function () {
  13103. return (this.alpha < 1.0);
  13104. };
  13105. Material.prototype.needAlphaTesting = function () {
  13106. return false;
  13107. };
  13108. Material.prototype.getAlphaTestTexture = function () {
  13109. return null;
  13110. };
  13111. Material.prototype.trackCreation = function (onCompiled, onError) {
  13112. };
  13113. Material.prototype._preBind = function () {
  13114. var engine = this._scene.getEngine();
  13115. engine.enableEffect(this._effect);
  13116. engine.setState(this.backFaceCulling);
  13117. };
  13118. Material.prototype.bind = function (world, mesh) {
  13119. this._scene._cachedMaterial = this;
  13120. if (this.onBind) {
  13121. this.onBind(this);
  13122. }
  13123. };
  13124. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13125. };
  13126. Material.prototype.unbind = function () {
  13127. };
  13128. Material.prototype.dispose = function (forceDisposeEffect) {
  13129. // Remove from scene
  13130. var index = this._scene.materials.indexOf(this);
  13131. this._scene.materials.splice(index, 1);
  13132. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13133. if (forceDisposeEffect && this._effect) {
  13134. this._scene.getEngine()._releaseEffect(this._effect);
  13135. this._effect = null;
  13136. }
  13137. // Callback
  13138. if (this.onDispose) {
  13139. this.onDispose();
  13140. }
  13141. };
  13142. Material._TriangleFillMode = 0;
  13143. Material._WireFrameFillMode = 1;
  13144. Material._PointFillMode = 2;
  13145. return Material;
  13146. })();
  13147. BABYLON.Material = Material;
  13148. })(BABYLON || (BABYLON = {}));
  13149. //# sourceMappingURL=babylon.material.js.map
  13150. var BABYLON;
  13151. (function (BABYLON) {
  13152. var maxSimultaneousLights = 4;
  13153. var FresnelParameters = (function () {
  13154. function FresnelParameters() {
  13155. this.isEnabled = true;
  13156. this.leftColor = BABYLON.Color3.White();
  13157. this.rightColor = BABYLON.Color3.Black();
  13158. this.bias = 0;
  13159. this.power = 1;
  13160. }
  13161. return FresnelParameters;
  13162. })();
  13163. BABYLON.FresnelParameters = FresnelParameters;
  13164. var StandardMaterial = (function (_super) {
  13165. __extends(StandardMaterial, _super);
  13166. function StandardMaterial(name, scene) {
  13167. var _this = this;
  13168. _super.call(this, name, scene);
  13169. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13170. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13171. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13172. this.specularPower = 64;
  13173. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13174. this.useAlphaFromDiffuseTexture = false;
  13175. this.useSpecularOverAlpha = true;
  13176. this.fogEnabled = true;
  13177. this._cachedDefines = null;
  13178. this._renderTargets = new BABYLON.SmartArray(16);
  13179. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13180. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13181. this._scaledDiffuse = new BABYLON.Color3();
  13182. this._scaledSpecular = new BABYLON.Color3();
  13183. this.getRenderTargetTextures = function () {
  13184. _this._renderTargets.reset();
  13185. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13186. _this._renderTargets.push(_this.reflectionTexture);
  13187. }
  13188. return _this._renderTargets;
  13189. };
  13190. }
  13191. StandardMaterial.prototype.needAlphaBlending = function () {
  13192. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13193. };
  13194. StandardMaterial.prototype.needAlphaTesting = function () {
  13195. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13196. };
  13197. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13198. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13199. };
  13200. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13201. return this.diffuseTexture;
  13202. };
  13203. // Methods
  13204. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13205. if (this.checkReadyOnlyOnce) {
  13206. if (this._wasPreviouslyReady) {
  13207. return true;
  13208. }
  13209. }
  13210. var scene = this.getScene();
  13211. if (!this.checkReadyOnEveryCall) {
  13212. if (this._renderId === scene.getRenderId()) {
  13213. return true;
  13214. }
  13215. }
  13216. var engine = scene.getEngine();
  13217. var defines = [];
  13218. var fallbacks = new BABYLON.EffectFallbacks();
  13219. // Textures
  13220. if (scene.texturesEnabled) {
  13221. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13222. if (!this.diffuseTexture.isReady()) {
  13223. return false;
  13224. } else {
  13225. defines.push("#define DIFFUSE");
  13226. }
  13227. }
  13228. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13229. if (!this.ambientTexture.isReady()) {
  13230. return false;
  13231. } else {
  13232. defines.push("#define AMBIENT");
  13233. }
  13234. }
  13235. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13236. if (!this.opacityTexture.isReady()) {
  13237. return false;
  13238. } else {
  13239. defines.push("#define OPACITY");
  13240. if (this.opacityTexture.getAlphaFromRGB) {
  13241. defines.push("#define OPACITYRGB");
  13242. }
  13243. }
  13244. }
  13245. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13246. if (!this.reflectionTexture.isReady()) {
  13247. return false;
  13248. } else {
  13249. defines.push("#define REFLECTION");
  13250. fallbacks.addFallback(0, "REFLECTION");
  13251. }
  13252. }
  13253. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13254. if (!this.emissiveTexture.isReady()) {
  13255. return false;
  13256. } else {
  13257. defines.push("#define EMISSIVE");
  13258. }
  13259. }
  13260. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13261. if (!this.specularTexture.isReady()) {
  13262. return false;
  13263. } else {
  13264. defines.push("#define SPECULAR");
  13265. fallbacks.addFallback(0, "SPECULAR");
  13266. }
  13267. }
  13268. }
  13269. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13270. if (!this.bumpTexture.isReady()) {
  13271. return false;
  13272. } else {
  13273. defines.push("#define BUMP");
  13274. fallbacks.addFallback(0, "BUMP");
  13275. }
  13276. }
  13277. // Effect
  13278. if (this.useSpecularOverAlpha) {
  13279. defines.push("#define SPECULAROVERALPHA");
  13280. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13281. }
  13282. if (scene.clipPlane) {
  13283. defines.push("#define CLIPPLANE");
  13284. }
  13285. if (engine.getAlphaTesting()) {
  13286. defines.push("#define ALPHATEST");
  13287. }
  13288. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13289. defines.push("#define ALPHAFROMDIFFUSE");
  13290. }
  13291. // Point size
  13292. if (this.pointsCloud || scene.forcePointsCloud) {
  13293. defines.push("#define POINTSIZE");
  13294. }
  13295. // Fog
  13296. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13297. defines.push("#define FOG");
  13298. fallbacks.addFallback(1, "FOG");
  13299. }
  13300. var shadowsActivated = false;
  13301. var lightIndex = 0;
  13302. if (scene.lightsEnabled) {
  13303. for (var index = 0; index < scene.lights.length; index++) {
  13304. var light = scene.lights[index];
  13305. if (!light.isEnabled()) {
  13306. continue;
  13307. }
  13308. // Excluded check
  13309. if (light._excludedMeshesIds.length > 0) {
  13310. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13311. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13312. if (excludedMesh) {
  13313. light.excludedMeshes.push(excludedMesh);
  13314. }
  13315. }
  13316. light._excludedMeshesIds = [];
  13317. }
  13318. // Included check
  13319. if (light._includedOnlyMeshesIds.length > 0) {
  13320. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13321. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13322. if (includedOnlyMesh) {
  13323. light.includedOnlyMeshes.push(includedOnlyMesh);
  13324. }
  13325. }
  13326. light._includedOnlyMeshesIds = [];
  13327. }
  13328. if (!light.canAffectMesh(mesh)) {
  13329. continue;
  13330. }
  13331. defines.push("#define LIGHT" + lightIndex);
  13332. if (lightIndex > 0) {
  13333. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13334. }
  13335. var type;
  13336. if (light instanceof BABYLON.SpotLight) {
  13337. type = "#define SPOTLIGHT" + lightIndex;
  13338. } else if (light instanceof BABYLON.HemisphericLight) {
  13339. type = "#define HEMILIGHT" + lightIndex;
  13340. } else {
  13341. type = "#define POINTDIRLIGHT" + lightIndex;
  13342. }
  13343. defines.push(type);
  13344. if (lightIndex > 0) {
  13345. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13346. }
  13347. // Shadows
  13348. if (scene.shadowsEnabled) {
  13349. var shadowGenerator = light.getShadowGenerator();
  13350. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13351. defines.push("#define SHADOW" + lightIndex);
  13352. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13353. if (!shadowsActivated) {
  13354. defines.push("#define SHADOWS");
  13355. shadowsActivated = true;
  13356. }
  13357. if (shadowGenerator.useVarianceShadowMap) {
  13358. defines.push("#define SHADOWVSM" + lightIndex);
  13359. if (lightIndex > 0) {
  13360. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13361. }
  13362. }
  13363. if (shadowGenerator.usePoissonSampling) {
  13364. defines.push("#define SHADOWPCF" + lightIndex);
  13365. if (lightIndex > 0) {
  13366. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13367. }
  13368. }
  13369. }
  13370. }
  13371. lightIndex++;
  13372. if (lightIndex === maxSimultaneousLights)
  13373. break;
  13374. }
  13375. }
  13376. if (StandardMaterial.FresnelEnabled) {
  13377. // Fresnel
  13378. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13379. var fresnelRank = 1;
  13380. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13381. defines.push("#define DIFFUSEFRESNEL");
  13382. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13383. fresnelRank++;
  13384. }
  13385. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13386. defines.push("#define OPACITYFRESNEL");
  13387. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13388. fresnelRank++;
  13389. }
  13390. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13391. defines.push("#define REFLECTIONFRESNEL");
  13392. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13393. fresnelRank++;
  13394. }
  13395. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13396. defines.push("#define EMISSIVEFRESNEL");
  13397. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13398. fresnelRank++;
  13399. }
  13400. defines.push("#define FRESNEL");
  13401. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13402. }
  13403. }
  13404. // Attribs
  13405. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13406. if (mesh) {
  13407. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13408. attribs.push(BABYLON.VertexBuffer.UVKind);
  13409. defines.push("#define UV1");
  13410. }
  13411. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13412. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13413. defines.push("#define UV2");
  13414. }
  13415. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13416. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13417. defines.push("#define VERTEXCOLOR");
  13418. if (mesh.hasVertexAlpha) {
  13419. defines.push("#define VERTEXALPHA");
  13420. }
  13421. }
  13422. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13423. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13424. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13425. defines.push("#define BONES");
  13426. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13427. defines.push("#define BONES4");
  13428. fallbacks.addFallback(0, "BONES4");
  13429. }
  13430. // Instances
  13431. if (useInstances) {
  13432. defines.push("#define INSTANCES");
  13433. attribs.push("world0");
  13434. attribs.push("world1");
  13435. attribs.push("world2");
  13436. attribs.push("world3");
  13437. }
  13438. }
  13439. // Get correct effect
  13440. var join = defines.join("\n");
  13441. if (this._cachedDefines !== join) {
  13442. this._cachedDefines = join;
  13443. scene.resetCachedMaterial();
  13444. // Legacy browser patch
  13445. var shaderName = "default";
  13446. if (!scene.getEngine().getCaps().standardDerivatives) {
  13447. shaderName = "legacydefault";
  13448. }
  13449. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  13450. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  13451. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  13452. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  13453. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  13454. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  13455. "vFogInfos", "vFogColor", "pointSize",
  13456. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  13457. "mBones",
  13458. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  13459. "darkness0", "darkness1", "darkness2", "darkness3",
  13460. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  13461. ], [
  13462. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  13463. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  13464. ], join, fallbacks, this.onCompiled, this.onError);
  13465. }
  13466. if (!this._effect.isReady()) {
  13467. return false;
  13468. }
  13469. this._renderId = scene.getRenderId();
  13470. this._wasPreviouslyReady = true;
  13471. return true;
  13472. };
  13473. StandardMaterial.prototype.unbind = function () {
  13474. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13475. this._effect.setTexture("reflection2DSampler", null);
  13476. }
  13477. };
  13478. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13479. this._effect.setMatrix("world", world);
  13480. };
  13481. StandardMaterial.prototype.bind = function (world, mesh) {
  13482. var scene = this.getScene();
  13483. // Matrices
  13484. this.bindOnlyWorldMatrix(world);
  13485. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13486. // Bones
  13487. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13488. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13489. }
  13490. if (scene.getCachedMaterial() !== this) {
  13491. if (StandardMaterial.FresnelEnabled) {
  13492. // Fresnel
  13493. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13494. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13495. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13496. }
  13497. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13498. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13499. }
  13500. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13501. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13502. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13503. }
  13504. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13505. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13506. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13507. }
  13508. }
  13509. // Textures
  13510. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13511. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13512. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13513. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13514. }
  13515. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13516. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13517. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13518. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13519. }
  13520. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13521. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13522. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13523. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13524. }
  13525. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13526. if (this.reflectionTexture.isCube) {
  13527. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13528. } else {
  13529. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13530. }
  13531. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13532. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13533. }
  13534. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13535. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13536. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13537. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13538. }
  13539. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13540. this._effect.setTexture("specularSampler", this.specularTexture);
  13541. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13542. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13543. }
  13544. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13545. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13546. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13547. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13548. }
  13549. // Clip plane
  13550. if (scene.clipPlane) {
  13551. var clipPlane = scene.clipPlane;
  13552. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13553. }
  13554. // Point size
  13555. if (this.pointsCloud) {
  13556. this._effect.setFloat("pointSize", this.pointSize);
  13557. }
  13558. // Colors
  13559. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13560. // Scaling down color according to emissive
  13561. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13562. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13563. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13564. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13565. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13566. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13567. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13568. }
  13569. // Scaling down color according to emissive
  13570. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13571. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13572. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13573. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13574. if (scene.lightsEnabled) {
  13575. var lightIndex = 0;
  13576. for (var index = 0; index < scene.lights.length; index++) {
  13577. var light = scene.lights[index];
  13578. if (!light.isEnabled()) {
  13579. continue;
  13580. }
  13581. if (!light.canAffectMesh(mesh)) {
  13582. continue;
  13583. }
  13584. if (light instanceof BABYLON.PointLight) {
  13585. // Point Light
  13586. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13587. } else if (light instanceof BABYLON.DirectionalLight) {
  13588. // Directional Light
  13589. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13590. } else if (light instanceof BABYLON.SpotLight) {
  13591. // Spot Light
  13592. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13593. } else if (light instanceof BABYLON.HemisphericLight) {
  13594. // Hemispheric Light
  13595. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13596. }
  13597. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13598. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13599. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13600. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13601. // Shadows
  13602. if (scene.shadowsEnabled) {
  13603. var shadowGenerator = light.getShadowGenerator();
  13604. if (mesh.receiveShadows && shadowGenerator) {
  13605. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13606. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13607. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13608. }
  13609. }
  13610. lightIndex++;
  13611. if (lightIndex === maxSimultaneousLights)
  13612. break;
  13613. }
  13614. }
  13615. // View
  13616. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13617. this._effect.setMatrix("view", scene.getViewMatrix());
  13618. }
  13619. // Fog
  13620. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13621. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13622. this._effect.setColor3("vFogColor", scene.fogColor);
  13623. }
  13624. _super.prototype.bind.call(this, world, mesh);
  13625. };
  13626. StandardMaterial.prototype.getAnimatables = function () {
  13627. var results = [];
  13628. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13629. results.push(this.diffuseTexture);
  13630. }
  13631. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13632. results.push(this.ambientTexture);
  13633. }
  13634. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13635. results.push(this.opacityTexture);
  13636. }
  13637. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13638. results.push(this.reflectionTexture);
  13639. }
  13640. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13641. results.push(this.emissiveTexture);
  13642. }
  13643. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13644. results.push(this.specularTexture);
  13645. }
  13646. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13647. results.push(this.bumpTexture);
  13648. }
  13649. return results;
  13650. };
  13651. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13652. if (this.diffuseTexture) {
  13653. this.diffuseTexture.dispose();
  13654. }
  13655. if (this.ambientTexture) {
  13656. this.ambientTexture.dispose();
  13657. }
  13658. if (this.opacityTexture) {
  13659. this.opacityTexture.dispose();
  13660. }
  13661. if (this.reflectionTexture) {
  13662. this.reflectionTexture.dispose();
  13663. }
  13664. if (this.emissiveTexture) {
  13665. this.emissiveTexture.dispose();
  13666. }
  13667. if (this.specularTexture) {
  13668. this.specularTexture.dispose();
  13669. }
  13670. if (this.bumpTexture) {
  13671. this.bumpTexture.dispose();
  13672. }
  13673. _super.prototype.dispose.call(this, forceDisposeEffect);
  13674. };
  13675. StandardMaterial.prototype.clone = function (name) {
  13676. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13677. // Base material
  13678. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13679. newStandardMaterial.alpha = this.alpha;
  13680. newStandardMaterial.fillMode = this.fillMode;
  13681. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13682. // Standard material
  13683. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13684. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13685. }
  13686. if (this.ambientTexture && this.ambientTexture.clone) {
  13687. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13688. }
  13689. if (this.opacityTexture && this.opacityTexture.clone) {
  13690. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13691. }
  13692. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13693. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13694. }
  13695. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13696. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13697. }
  13698. if (this.specularTexture && this.specularTexture.clone) {
  13699. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13700. }
  13701. if (this.bumpTexture && this.bumpTexture.clone) {
  13702. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13703. }
  13704. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13705. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13706. newStandardMaterial.specularColor = this.specularColor.clone();
  13707. newStandardMaterial.specularPower = this.specularPower;
  13708. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13709. return newStandardMaterial;
  13710. };
  13711. StandardMaterial.DiffuseTextureEnabled = true;
  13712. StandardMaterial.AmbientTextureEnabled = true;
  13713. StandardMaterial.OpacityTextureEnabled = true;
  13714. StandardMaterial.ReflectionTextureEnabled = true;
  13715. StandardMaterial.EmissiveTextureEnabled = true;
  13716. StandardMaterial.SpecularTextureEnabled = true;
  13717. StandardMaterial.BumpTextureEnabled = true;
  13718. StandardMaterial.FresnelEnabled = true;
  13719. return StandardMaterial;
  13720. })(BABYLON.Material);
  13721. BABYLON.StandardMaterial = StandardMaterial;
  13722. })(BABYLON || (BABYLON = {}));
  13723. //# sourceMappingURL=babylon.standardMaterial.js.map
  13724. var BABYLON;
  13725. (function (BABYLON) {
  13726. var MultiMaterial = (function (_super) {
  13727. __extends(MultiMaterial, _super);
  13728. function MultiMaterial(name, scene) {
  13729. _super.call(this, name, scene, true);
  13730. this.subMaterials = new Array();
  13731. scene.multiMaterials.push(this);
  13732. }
  13733. // Properties
  13734. MultiMaterial.prototype.getSubMaterial = function (index) {
  13735. if (index < 0 || index >= this.subMaterials.length) {
  13736. return this.getScene().defaultMaterial;
  13737. }
  13738. return this.subMaterials[index];
  13739. };
  13740. // Methods
  13741. MultiMaterial.prototype.isReady = function (mesh) {
  13742. for (var index = 0; index < this.subMaterials.length; index++) {
  13743. var subMaterial = this.subMaterials[index];
  13744. if (subMaterial) {
  13745. if (!this.subMaterials[index].isReady(mesh)) {
  13746. return false;
  13747. }
  13748. }
  13749. }
  13750. return true;
  13751. };
  13752. return MultiMaterial;
  13753. })(BABYLON.Material);
  13754. BABYLON.MultiMaterial = MultiMaterial;
  13755. })(BABYLON || (BABYLON = {}));
  13756. //# sourceMappingURL=babylon.multiMaterial.js.map
  13757. var BABYLON;
  13758. (function (BABYLON) {
  13759. var Database = (function () {
  13760. function Database(urlToScene, callbackManifestChecked) {
  13761. // Handling various flavors of prefixed version of IndexedDB
  13762. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13763. this.callbackManifestChecked = callbackManifestChecked;
  13764. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13765. this.db = null;
  13766. this.enableSceneOffline = false;
  13767. this.enableTexturesOffline = false;
  13768. this.manifestVersionFound = 0;
  13769. this.mustUpdateRessources = false;
  13770. this.hasReachedQuota = false;
  13771. this.checkManifestFile();
  13772. }
  13773. Database.prototype.checkManifestFile = function () {
  13774. var _this = this;
  13775. function noManifestFile() {
  13776. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13777. that.enableSceneOffline = false;
  13778. that.enableTexturesOffline = false;
  13779. that.callbackManifestChecked(false);
  13780. }
  13781. var that = this;
  13782. var manifestURL = this.currentSceneUrl + ".manifest";
  13783. var xhr = new XMLHttpRequest();
  13784. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13785. xhr.open("GET", manifestURLTimeStamped, true);
  13786. xhr.addEventListener("load", function () {
  13787. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13788. try {
  13789. var manifestFile = JSON.parse(xhr.response);
  13790. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13791. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13792. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13793. _this.manifestVersionFound = manifestFile.version;
  13794. }
  13795. if (_this.callbackManifestChecked) {
  13796. _this.callbackManifestChecked(true);
  13797. }
  13798. } catch (ex) {
  13799. noManifestFile();
  13800. }
  13801. } else {
  13802. noManifestFile();
  13803. }
  13804. }, false);
  13805. xhr.addEventListener("error", function (event) {
  13806. noManifestFile();
  13807. }, false);
  13808. try {
  13809. xhr.send();
  13810. } catch (ex) {
  13811. BABYLON.Tools.Error("Error on XHR send request.");
  13812. that.callbackManifestChecked(false);
  13813. }
  13814. };
  13815. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13816. var _this = this;
  13817. function handleError() {
  13818. that.isSupported = false;
  13819. if (errorCallback)
  13820. errorCallback();
  13821. }
  13822. var that = this;
  13823. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13824. // Your browser doesn't support IndexedDB
  13825. this.isSupported = false;
  13826. if (errorCallback)
  13827. errorCallback();
  13828. } else {
  13829. // If the DB hasn't been opened or created yet
  13830. if (!this.db) {
  13831. this.hasReachedQuota = false;
  13832. this.isSupported = true;
  13833. var request = this.idbFactory.open("babylonjs", 1);
  13834. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13835. request.onerror = function (event) {
  13836. handleError();
  13837. };
  13838. // executes when a version change transaction cannot complete due to other active transactions
  13839. request.onblocked = function (event) {
  13840. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13841. handleError();
  13842. };
  13843. // DB has been opened successfully
  13844. request.onsuccess = function (event) {
  13845. _this.db = request.result;
  13846. successCallback();
  13847. };
  13848. // Initialization of the DB. Creating Scenes & Textures stores
  13849. request.onupgradeneeded = function (event) {
  13850. _this.db = (event.target).result;
  13851. try {
  13852. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13853. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13854. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13855. } catch (ex) {
  13856. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13857. handleError();
  13858. }
  13859. };
  13860. } else {
  13861. if (successCallback)
  13862. successCallback();
  13863. }
  13864. }
  13865. };
  13866. Database.prototype.loadImageFromDB = function (url, image) {
  13867. var _this = this;
  13868. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13869. var saveAndLoadImage = function () {
  13870. if (!_this.hasReachedQuota && _this.db !== null) {
  13871. // the texture is not yet in the DB, let's try to save it
  13872. _this._saveImageIntoDBAsync(completeURL, image);
  13873. } else {
  13874. image.src = url;
  13875. }
  13876. };
  13877. if (!this.mustUpdateRessources) {
  13878. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13879. } else {
  13880. saveAndLoadImage();
  13881. }
  13882. };
  13883. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13884. if (this.isSupported && this.db !== null) {
  13885. var texture;
  13886. var transaction = this.db.transaction(["textures"]);
  13887. transaction.onabort = function (event) {
  13888. image.src = url;
  13889. };
  13890. transaction.oncomplete = function (event) {
  13891. var blobTextureURL;
  13892. if (texture) {
  13893. var URL = window.URL || window.webkitURL;
  13894. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13895. image.onerror = function () {
  13896. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13897. image.src = url;
  13898. };
  13899. image.src = blobTextureURL;
  13900. } else {
  13901. notInDBCallback();
  13902. }
  13903. };
  13904. var getRequest = transaction.objectStore("textures").get(url);
  13905. getRequest.onsuccess = function (event) {
  13906. texture = (event.target).result;
  13907. };
  13908. getRequest.onerror = function (event) {
  13909. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13910. image.src = url;
  13911. };
  13912. } else {
  13913. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13914. image.src = url;
  13915. }
  13916. };
  13917. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13918. var _this = this;
  13919. if (this.isSupported) {
  13920. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13921. var generateBlobUrl = function () {
  13922. var blobTextureURL;
  13923. if (blob) {
  13924. var URL = window.URL || window.webkitURL;
  13925. try {
  13926. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13927. } catch (ex) {
  13928. blobTextureURL = URL.createObjectURL(blob);
  13929. }
  13930. }
  13931. image.src = blobTextureURL;
  13932. };
  13933. if (BABYLON.Database.isUASupportingBlobStorage) {
  13934. var xhr = new XMLHttpRequest(), blob;
  13935. xhr.open("GET", url, true);
  13936. xhr.responseType = "blob";
  13937. xhr.addEventListener("load", function () {
  13938. if (xhr.status === 200) {
  13939. // Blob as response (XHR2)
  13940. blob = xhr.response;
  13941. var transaction = _this.db.transaction(["textures"], "readwrite");
  13942. // the transaction could abort because of a QuotaExceededError error
  13943. transaction.onabort = function (event) {
  13944. try {
  13945. if (event.srcElement.error.name === "QuotaExceededError") {
  13946. this.hasReachedQuota = true;
  13947. }
  13948. } catch (ex) {
  13949. }
  13950. generateBlobUrl();
  13951. };
  13952. transaction.oncomplete = function (event) {
  13953. generateBlobUrl();
  13954. };
  13955. var newTexture = { textureUrl: url, data: blob };
  13956. try {
  13957. // Put the blob into the dabase
  13958. var addRequest = transaction.objectStore("textures").put(newTexture);
  13959. addRequest.onsuccess = function (event) {
  13960. };
  13961. addRequest.onerror = function (event) {
  13962. generateBlobUrl();
  13963. };
  13964. } catch (ex) {
  13965. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13966. if (ex.code === 25) {
  13967. BABYLON.Database.isUASupportingBlobStorage = false;
  13968. }
  13969. image.src = url;
  13970. }
  13971. } else {
  13972. image.src = url;
  13973. }
  13974. }, false);
  13975. xhr.addEventListener("error", function (event) {
  13976. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13977. image.src = url;
  13978. }, false);
  13979. xhr.send();
  13980. } else {
  13981. image.src = url;
  13982. }
  13983. } else {
  13984. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13985. image.src = url;
  13986. }
  13987. };
  13988. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13989. var _this = this;
  13990. var updateVersion = function (event) {
  13991. // the version is not yet in the DB or we need to update it
  13992. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13993. };
  13994. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13995. };
  13996. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13997. var _this = this;
  13998. if (this.isSupported) {
  13999. var version;
  14000. try {
  14001. var transaction = this.db.transaction(["versions"]);
  14002. transaction.oncomplete = function (event) {
  14003. if (version) {
  14004. // If the version in the JSON file is > than the version in DB
  14005. if (_this.manifestVersionFound > version.data) {
  14006. _this.mustUpdateRessources = true;
  14007. updateInDBCallback();
  14008. } else {
  14009. callback(version.data);
  14010. }
  14011. } else {
  14012. _this.mustUpdateRessources = true;
  14013. updateInDBCallback();
  14014. }
  14015. };
  14016. transaction.onabort = function (event) {
  14017. callback(-1);
  14018. };
  14019. var getRequest = transaction.objectStore("versions").get(url);
  14020. getRequest.onsuccess = function (event) {
  14021. version = (event.target).result;
  14022. };
  14023. getRequest.onerror = function (event) {
  14024. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14025. callback(-1);
  14026. };
  14027. } catch (ex) {
  14028. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14029. callback(-1);
  14030. }
  14031. } else {
  14032. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14033. callback(-1);
  14034. }
  14035. };
  14036. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14037. var _this = this;
  14038. if (this.isSupported && !this.hasReachedQuota) {
  14039. try {
  14040. // Open a transaction to the database
  14041. var transaction = this.db.transaction(["versions"], "readwrite");
  14042. // the transaction could abort because of a QuotaExceededError error
  14043. transaction.onabort = function (event) {
  14044. try {
  14045. if (event.srcElement.error.name === "QuotaExceededError") {
  14046. _this.hasReachedQuota = true;
  14047. }
  14048. } catch (ex) {
  14049. }
  14050. callback(-1);
  14051. };
  14052. transaction.oncomplete = function (event) {
  14053. callback(_this.manifestVersionFound);
  14054. };
  14055. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14056. // Put the scene into the database
  14057. var addRequest = transaction.objectStore("versions").put(newVersion);
  14058. addRequest.onsuccess = function (event) {
  14059. };
  14060. addRequest.onerror = function (event) {
  14061. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14062. };
  14063. } catch (ex) {
  14064. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14065. callback(-1);
  14066. }
  14067. } else {
  14068. callback(-1);
  14069. }
  14070. };
  14071. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14072. var _this = this;
  14073. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14074. var saveAndLoadFile = function (event) {
  14075. // the scene is not yet in the DB, let's try to save it
  14076. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14077. };
  14078. this._checkVersionFromDB(completeUrl, function (version) {
  14079. if (version !== -1) {
  14080. if (!_this.mustUpdateRessources) {
  14081. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14082. } else {
  14083. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14084. }
  14085. } else {
  14086. errorCallback();
  14087. }
  14088. });
  14089. };
  14090. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14091. if (this.isSupported) {
  14092. var targetStore;
  14093. if (url.indexOf(".babylon") !== -1) {
  14094. targetStore = "scenes";
  14095. } else {
  14096. targetStore = "textures";
  14097. }
  14098. var file;
  14099. var transaction = this.db.transaction([targetStore]);
  14100. transaction.oncomplete = function (event) {
  14101. if (file) {
  14102. callback(file.data);
  14103. } else {
  14104. notInDBCallback();
  14105. }
  14106. };
  14107. transaction.onabort = function (event) {
  14108. notInDBCallback();
  14109. };
  14110. var getRequest = transaction.objectStore(targetStore).get(url);
  14111. getRequest.onsuccess = function (event) {
  14112. file = (event.target).result;
  14113. };
  14114. getRequest.onerror = function (event) {
  14115. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14116. notInDBCallback();
  14117. };
  14118. } else {
  14119. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14120. callback();
  14121. }
  14122. };
  14123. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14124. var _this = this;
  14125. if (this.isSupported) {
  14126. var targetStore;
  14127. if (url.indexOf(".babylon") !== -1) {
  14128. targetStore = "scenes";
  14129. } else {
  14130. targetStore = "textures";
  14131. }
  14132. // Create XHR
  14133. var xhr = new XMLHttpRequest(), fileData;
  14134. xhr.open("GET", url, true);
  14135. if (useArrayBuffer) {
  14136. xhr.responseType = "arraybuffer";
  14137. }
  14138. xhr.onprogress = progressCallback;
  14139. xhr.addEventListener("load", function () {
  14140. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14141. // Blob as response (XHR2)
  14142. //fileData = xhr.responseText;
  14143. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14144. if (!_this.hasReachedQuota) {
  14145. // Open a transaction to the database
  14146. var transaction = _this.db.transaction([targetStore], "readwrite");
  14147. // the transaction could abort because of a QuotaExceededError error
  14148. transaction.onabort = function (event) {
  14149. try {
  14150. if (event.srcElement.error.name === "QuotaExceededError") {
  14151. this.hasReachedQuota = true;
  14152. }
  14153. } catch (ex) {
  14154. }
  14155. callback(fileData);
  14156. };
  14157. transaction.oncomplete = function (event) {
  14158. callback(fileData);
  14159. };
  14160. var newFile;
  14161. if (targetStore === "scenes") {
  14162. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14163. } else {
  14164. newFile = { textureUrl: url, data: fileData };
  14165. }
  14166. try {
  14167. // Put the scene into the database
  14168. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14169. addRequest.onsuccess = function (event) {
  14170. };
  14171. addRequest.onerror = function (event) {
  14172. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14173. };
  14174. } catch (ex) {
  14175. callback(fileData);
  14176. }
  14177. } else {
  14178. callback(fileData);
  14179. }
  14180. } else {
  14181. callback();
  14182. }
  14183. }, false);
  14184. xhr.addEventListener("error", function (event) {
  14185. BABYLON.Tools.Error("error on XHR request.");
  14186. callback();
  14187. }, false);
  14188. xhr.send();
  14189. } else {
  14190. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14191. callback();
  14192. }
  14193. };
  14194. Database.isUASupportingBlobStorage = true;
  14195. Database.parseURL = function (url) {
  14196. var a = document.createElement('a');
  14197. a.href = url;
  14198. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14199. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14200. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14201. return absLocation;
  14202. };
  14203. Database.ReturnFullUrlLocation = function (url) {
  14204. if (url.indexOf("http:/") === -1) {
  14205. return (BABYLON.Database.parseURL(window.location.href) + url);
  14206. } else {
  14207. return url;
  14208. }
  14209. };
  14210. return Database;
  14211. })();
  14212. BABYLON.Database = Database;
  14213. })(BABYLON || (BABYLON = {}));
  14214. //# sourceMappingURL=babylon.database.js.map
  14215. var BABYLON;
  14216. (function (BABYLON) {
  14217. var SpriteManager = (function () {
  14218. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14219. this.name = name;
  14220. this.cellSize = cellSize;
  14221. this.sprites = new Array();
  14222. this.renderingGroupId = 0;
  14223. this.fogEnabled = true;
  14224. this._vertexDeclaration = [3, 4, 4, 4];
  14225. this._vertexStrideSize = 15 * 4;
  14226. this._capacity = capacity;
  14227. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14228. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14229. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14230. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14231. this._scene = scene;
  14232. this._scene.spriteManagers.push(this);
  14233. // VBO
  14234. this._vertexDeclaration = [3, 4, 4, 4];
  14235. this._vertexStrideSize = 15 * 4;
  14236. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14237. var indices = [];
  14238. var index = 0;
  14239. for (var count = 0; count < capacity; count++) {
  14240. indices.push(index);
  14241. indices.push(index + 1);
  14242. indices.push(index + 2);
  14243. indices.push(index);
  14244. indices.push(index + 2);
  14245. indices.push(index + 3);
  14246. index += 4;
  14247. }
  14248. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14249. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14250. // Effects
  14251. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14252. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14253. }
  14254. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14255. var arrayOffset = index * 15;
  14256. if (offsetX == 0)
  14257. offsetX = this._epsilon;
  14258. else if (offsetX == 1)
  14259. offsetX = 1 - this._epsilon;
  14260. if (offsetY == 0)
  14261. offsetY = this._epsilon;
  14262. else if (offsetY == 1)
  14263. offsetY = 1 - this._epsilon;
  14264. this._vertices[arrayOffset] = sprite.position.x;
  14265. this._vertices[arrayOffset + 1] = sprite.position.y;
  14266. this._vertices[arrayOffset + 2] = sprite.position.z;
  14267. this._vertices[arrayOffset + 3] = sprite.angle;
  14268. this._vertices[arrayOffset + 4] = sprite.size;
  14269. this._vertices[arrayOffset + 5] = offsetX;
  14270. this._vertices[arrayOffset + 6] = offsetY;
  14271. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14272. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14273. var offset = (sprite.cellIndex / rowSize) >> 0;
  14274. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14275. this._vertices[arrayOffset + 10] = offset;
  14276. // Color
  14277. this._vertices[arrayOffset + 11] = sprite.color.r;
  14278. this._vertices[arrayOffset + 12] = sprite.color.g;
  14279. this._vertices[arrayOffset + 13] = sprite.color.b;
  14280. this._vertices[arrayOffset + 14] = sprite.color.a;
  14281. };
  14282. SpriteManager.prototype.render = function () {
  14283. // Check
  14284. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14285. return;
  14286. var engine = this._scene.getEngine();
  14287. var baseSize = this._spriteTexture.getBaseSize();
  14288. // Sprites
  14289. var deltaTime = engine.getDeltaTime();
  14290. var max = Math.min(this._capacity, this.sprites.length);
  14291. var rowSize = baseSize.width / this.cellSize;
  14292. var offset = 0;
  14293. for (var index = 0; index < max; index++) {
  14294. var sprite = this.sprites[index];
  14295. if (!sprite) {
  14296. continue;
  14297. }
  14298. sprite._animate(deltaTime);
  14299. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14300. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14301. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14302. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14303. }
  14304. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14305. // Render
  14306. var effect = this._effectBase;
  14307. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14308. effect = this._effectFog;
  14309. }
  14310. engine.enableEffect(effect);
  14311. var viewMatrix = this._scene.getViewMatrix();
  14312. effect.setTexture("diffuseSampler", this._spriteTexture);
  14313. effect.setMatrix("view", viewMatrix);
  14314. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14315. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14316. // Fog
  14317. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14318. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14319. effect.setColor3("vFogColor", this._scene.fogColor);
  14320. }
  14321. // VBOs
  14322. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14323. // Draw order
  14324. effect.setBool("alphaTest", true);
  14325. engine.setColorWrite(false);
  14326. engine.draw(true, 0, max * 6);
  14327. engine.setColorWrite(true);
  14328. effect.setBool("alphaTest", false);
  14329. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14330. engine.draw(true, 0, max * 6);
  14331. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14332. };
  14333. SpriteManager.prototype.dispose = function () {
  14334. if (this._vertexBuffer) {
  14335. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14336. this._vertexBuffer = null;
  14337. }
  14338. if (this._indexBuffer) {
  14339. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14340. this._indexBuffer = null;
  14341. }
  14342. if (this._spriteTexture) {
  14343. this._spriteTexture.dispose();
  14344. this._spriteTexture = null;
  14345. }
  14346. // Remove from scene
  14347. var index = this._scene.spriteManagers.indexOf(this);
  14348. this._scene.spriteManagers.splice(index, 1);
  14349. // Callback
  14350. if (this.onDispose) {
  14351. this.onDispose();
  14352. }
  14353. };
  14354. return SpriteManager;
  14355. })();
  14356. BABYLON.SpriteManager = SpriteManager;
  14357. })(BABYLON || (BABYLON = {}));
  14358. //# sourceMappingURL=babylon.spriteManager.js.map
  14359. var BABYLON;
  14360. (function (BABYLON) {
  14361. var Sprite = (function () {
  14362. function Sprite(name, manager) {
  14363. this.name = name;
  14364. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14365. this.size = 1.0;
  14366. this.angle = 0;
  14367. this.cellIndex = 0;
  14368. this.invertU = 0;
  14369. this.invertV = 0;
  14370. this.animations = new Array();
  14371. this._animationStarted = false;
  14372. this._loopAnimation = false;
  14373. this._fromIndex = 0;
  14374. this._toIndex = 0;
  14375. this._delay = 0;
  14376. this._direction = 1;
  14377. this._frameCount = 0;
  14378. this._time = 0;
  14379. this._manager = manager;
  14380. this._manager.sprites.push(this);
  14381. this.position = BABYLON.Vector3.Zero();
  14382. }
  14383. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14384. this._fromIndex = from;
  14385. this._toIndex = to;
  14386. this._loopAnimation = loop;
  14387. this._delay = delay;
  14388. this._animationStarted = true;
  14389. this._direction = from < to ? 1 : -1;
  14390. this.cellIndex = from;
  14391. this._time = 0;
  14392. };
  14393. Sprite.prototype.stopAnimation = function () {
  14394. this._animationStarted = false;
  14395. };
  14396. Sprite.prototype._animate = function (deltaTime) {
  14397. if (!this._animationStarted)
  14398. return;
  14399. this._time += deltaTime;
  14400. if (this._time > this._delay) {
  14401. this._time = this._time % this._delay;
  14402. this.cellIndex += this._direction;
  14403. if (this.cellIndex == this._toIndex) {
  14404. if (this._loopAnimation) {
  14405. this.cellIndex = this._fromIndex;
  14406. } else {
  14407. this._animationStarted = false;
  14408. if (this.disposeWhenFinishedAnimating) {
  14409. this.dispose();
  14410. }
  14411. }
  14412. }
  14413. }
  14414. };
  14415. Sprite.prototype.dispose = function () {
  14416. for (var i = 0; i < this._manager.sprites.length; i++) {
  14417. if (this._manager.sprites[i] == this) {
  14418. this._manager.sprites.splice(i, 1);
  14419. }
  14420. }
  14421. };
  14422. return Sprite;
  14423. })();
  14424. BABYLON.Sprite = Sprite;
  14425. })(BABYLON || (BABYLON = {}));
  14426. //# sourceMappingURL=babylon.sprite.js.map
  14427. var BABYLON;
  14428. (function (BABYLON) {
  14429. var Layer = (function () {
  14430. function Layer(name, imgUrl, scene, isBackground, color) {
  14431. this.name = name;
  14432. this._vertexDeclaration = [2];
  14433. this._vertexStrideSize = 2 * 4;
  14434. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14435. this.isBackground = isBackground === undefined ? true : isBackground;
  14436. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14437. this._scene = scene;
  14438. this._scene.layers.push(this);
  14439. // VBO
  14440. var vertices = [];
  14441. vertices.push(1, 1);
  14442. vertices.push(-1, 1);
  14443. vertices.push(-1, -1);
  14444. vertices.push(1, -1);
  14445. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14446. // Indices
  14447. var indices = [];
  14448. indices.push(0);
  14449. indices.push(1);
  14450. indices.push(2);
  14451. indices.push(0);
  14452. indices.push(2);
  14453. indices.push(3);
  14454. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14455. // Effects
  14456. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14457. }
  14458. Layer.prototype.render = function () {
  14459. // Check
  14460. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14461. return;
  14462. var engine = this._scene.getEngine();
  14463. // Render
  14464. engine.enableEffect(this._effect);
  14465. engine.setState(false);
  14466. // Texture
  14467. this._effect.setTexture("textureSampler", this.texture);
  14468. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14469. // Color
  14470. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14471. // VBOs
  14472. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14473. // Draw order
  14474. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14475. engine.draw(true, 0, 6);
  14476. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14477. };
  14478. Layer.prototype.dispose = function () {
  14479. if (this._vertexBuffer) {
  14480. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14481. this._vertexBuffer = null;
  14482. }
  14483. if (this._indexBuffer) {
  14484. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14485. this._indexBuffer = null;
  14486. }
  14487. if (this.texture) {
  14488. this.texture.dispose();
  14489. this.texture = null;
  14490. }
  14491. // Remove from scene
  14492. var index = this._scene.layers.indexOf(this);
  14493. this._scene.layers.splice(index, 1);
  14494. // Callback
  14495. if (this.onDispose) {
  14496. this.onDispose();
  14497. }
  14498. };
  14499. return Layer;
  14500. })();
  14501. BABYLON.Layer = Layer;
  14502. })(BABYLON || (BABYLON = {}));
  14503. //# sourceMappingURL=babylon.layer.js.map
  14504. var BABYLON;
  14505. (function (BABYLON) {
  14506. var Particle = (function () {
  14507. function Particle() {
  14508. this.position = BABYLON.Vector3.Zero();
  14509. this.direction = BABYLON.Vector3.Zero();
  14510. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14511. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14512. this.lifeTime = 1.0;
  14513. this.age = 0;
  14514. this.size = 0;
  14515. this.angle = 0;
  14516. this.angularSpeed = 0;
  14517. }
  14518. Particle.prototype.copyTo = function (other) {
  14519. other.position.copyFrom(this.position);
  14520. other.direction.copyFrom(this.direction);
  14521. other.color.copyFrom(this.color);
  14522. other.colorStep.copyFrom(this.colorStep);
  14523. other.lifeTime = this.lifeTime;
  14524. other.age = this.age;
  14525. other.size = this.size;
  14526. other.angle = this.angle;
  14527. other.angularSpeed = this.angularSpeed;
  14528. };
  14529. return Particle;
  14530. })();
  14531. BABYLON.Particle = Particle;
  14532. })(BABYLON || (BABYLON = {}));
  14533. //# sourceMappingURL=babylon.particle.js.map
  14534. var BABYLON;
  14535. (function (BABYLON) {
  14536. var randomNumber = function (min, max) {
  14537. if (min === max) {
  14538. return (min);
  14539. }
  14540. var random = Math.random();
  14541. return ((random * (max - min)) + min);
  14542. };
  14543. var ParticleSystem = (function () {
  14544. function ParticleSystem(name, capacity, scene, customEffect) {
  14545. var _this = this;
  14546. this.name = name;
  14547. this.renderingGroupId = 0;
  14548. this.emitter = null;
  14549. this.emitRate = 10;
  14550. this.manualEmitCount = -1;
  14551. this.updateSpeed = 0.01;
  14552. this.targetStopDuration = 0;
  14553. this.disposeOnStop = false;
  14554. this.minEmitPower = 1;
  14555. this.maxEmitPower = 1;
  14556. this.minLifeTime = 1;
  14557. this.maxLifeTime = 1;
  14558. this.minSize = 1;
  14559. this.maxSize = 1;
  14560. this.minAngularSpeed = 0;
  14561. this.maxAngularSpeed = 0;
  14562. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14563. this.forceDepthWrite = false;
  14564. this.gravity = BABYLON.Vector3.Zero();
  14565. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14566. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14567. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14568. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14569. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14570. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14571. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14572. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14573. this.particles = new Array();
  14574. this._vertexDeclaration = [3, 4, 4];
  14575. this._vertexStrideSize = 11 * 4;
  14576. this._stockParticles = new Array();
  14577. this._newPartsExcess = 0;
  14578. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14579. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14580. this._scaledDirection = BABYLON.Vector3.Zero();
  14581. this._scaledGravity = BABYLON.Vector3.Zero();
  14582. this._currentRenderId = -1;
  14583. this._started = false;
  14584. this._stopped = false;
  14585. this._actualFrame = 0;
  14586. this.id = name;
  14587. this._capacity = capacity;
  14588. this._scene = scene;
  14589. this._customEffect = customEffect;
  14590. scene.particleSystems.push(this);
  14591. // VBO
  14592. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14593. var indices = [];
  14594. var index = 0;
  14595. for (var count = 0; count < capacity; count++) {
  14596. indices.push(index);
  14597. indices.push(index + 1);
  14598. indices.push(index + 2);
  14599. indices.push(index);
  14600. indices.push(index + 2);
  14601. indices.push(index + 3);
  14602. index += 4;
  14603. }
  14604. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14605. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14606. // Default behaviors
  14607. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14608. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14609. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14610. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14611. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14612. };
  14613. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14614. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14615. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14616. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14617. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14618. };
  14619. this.updateFunction = function (particles) {
  14620. for (var index = 0; index < particles.length; index++) {
  14621. var particle = particles[index];
  14622. particle.age += _this._scaledUpdateSpeed;
  14623. if (particle.age >= particle.lifeTime) {
  14624. _this.recycleParticle(particle);
  14625. index--;
  14626. continue;
  14627. } else {
  14628. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14629. particle.color.addInPlace(_this._scaledColorStep);
  14630. if (particle.color.a < 0)
  14631. particle.color.a = 0;
  14632. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14633. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14634. particle.position.addInPlace(_this._scaledDirection);
  14635. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14636. particle.direction.addInPlace(_this._scaledGravity);
  14637. }
  14638. }
  14639. };
  14640. }
  14641. ParticleSystem.prototype.recycleParticle = function (particle) {
  14642. var lastParticle = this.particles.pop();
  14643. if (lastParticle !== particle) {
  14644. lastParticle.copyTo(particle);
  14645. this._stockParticles.push(lastParticle);
  14646. }
  14647. };
  14648. ParticleSystem.prototype.getCapacity = function () {
  14649. return this._capacity;
  14650. };
  14651. ParticleSystem.prototype.isAlive = function () {
  14652. return this._alive;
  14653. };
  14654. ParticleSystem.prototype.isStarted = function () {
  14655. return this._started;
  14656. };
  14657. ParticleSystem.prototype.start = function () {
  14658. this._started = true;
  14659. this._stopped = false;
  14660. this._actualFrame = 0;
  14661. };
  14662. ParticleSystem.prototype.stop = function () {
  14663. this._stopped = true;
  14664. };
  14665. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14666. var offset = index * 11;
  14667. this._vertices[offset] = particle.position.x;
  14668. this._vertices[offset + 1] = particle.position.y;
  14669. this._vertices[offset + 2] = particle.position.z;
  14670. this._vertices[offset + 3] = particle.color.r;
  14671. this._vertices[offset + 4] = particle.color.g;
  14672. this._vertices[offset + 5] = particle.color.b;
  14673. this._vertices[offset + 6] = particle.color.a;
  14674. this._vertices[offset + 7] = particle.angle;
  14675. this._vertices[offset + 8] = particle.size;
  14676. this._vertices[offset + 9] = offsetX;
  14677. this._vertices[offset + 10] = offsetY;
  14678. };
  14679. ParticleSystem.prototype._update = function (newParticles) {
  14680. // Update current
  14681. this._alive = this.particles.length > 0;
  14682. this.updateFunction(this.particles);
  14683. // Add new ones
  14684. var worldMatrix;
  14685. if (this.emitter.position) {
  14686. worldMatrix = this.emitter.getWorldMatrix();
  14687. } else {
  14688. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14689. }
  14690. for (var index = 0; index < newParticles; index++) {
  14691. if (this.particles.length === this._capacity) {
  14692. break;
  14693. }
  14694. if (this._stockParticles.length !== 0) {
  14695. var particle = this._stockParticles.pop();
  14696. particle.age = 0;
  14697. } else {
  14698. particle = new BABYLON.Particle();
  14699. }
  14700. this.particles.push(particle);
  14701. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14702. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14703. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14704. particle.size = randomNumber(this.minSize, this.maxSize);
  14705. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14706. this.startPositionFunction(worldMatrix, particle.position);
  14707. var step = randomNumber(0, 1.0);
  14708. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14709. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14710. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14711. }
  14712. };
  14713. ParticleSystem.prototype._getEffect = function () {
  14714. if (this._customEffect) {
  14715. return this._customEffect;
  14716. }
  14717. ;
  14718. var defines = [];
  14719. if (this._scene.clipPlane) {
  14720. defines.push("#define CLIPPLANE");
  14721. }
  14722. // Effect
  14723. var join = defines.join("\n");
  14724. if (this._cachedDefines !== join) {
  14725. this._cachedDefines = join;
  14726. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14727. }
  14728. return this._effect;
  14729. };
  14730. ParticleSystem.prototype.animate = function () {
  14731. if (!this._started)
  14732. return;
  14733. var effect = this._getEffect();
  14734. // Check
  14735. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14736. return;
  14737. if (this._currentRenderId === this._scene.getRenderId()) {
  14738. return;
  14739. }
  14740. this._currentRenderId = this._scene.getRenderId();
  14741. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14742. // determine the number of particles we need to create
  14743. var emitCout;
  14744. if (this.manualEmitCount > -1) {
  14745. emitCout = this.manualEmitCount;
  14746. this.manualEmitCount = 0;
  14747. } else {
  14748. emitCout = this.emitRate;
  14749. }
  14750. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14751. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14752. if (this._newPartsExcess > 1.0) {
  14753. newParticles += this._newPartsExcess >> 0;
  14754. this._newPartsExcess -= this._newPartsExcess >> 0;
  14755. }
  14756. this._alive = false;
  14757. if (!this._stopped) {
  14758. this._actualFrame += this._scaledUpdateSpeed;
  14759. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14760. this.stop();
  14761. } else {
  14762. newParticles = 0;
  14763. }
  14764. this._update(newParticles);
  14765. // Stopped?
  14766. if (this._stopped) {
  14767. if (!this._alive) {
  14768. this._started = false;
  14769. if (this.disposeOnStop) {
  14770. this._scene._toBeDisposed.push(this);
  14771. }
  14772. }
  14773. }
  14774. // Update VBO
  14775. var offset = 0;
  14776. for (var index = 0; index < this.particles.length; index++) {
  14777. var particle = this.particles[index];
  14778. this._appendParticleVertex(offset++, particle, 0, 0);
  14779. this._appendParticleVertex(offset++, particle, 1, 0);
  14780. this._appendParticleVertex(offset++, particle, 1, 1);
  14781. this._appendParticleVertex(offset++, particle, 0, 1);
  14782. }
  14783. var engine = this._scene.getEngine();
  14784. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14785. };
  14786. ParticleSystem.prototype.render = function () {
  14787. var effect = this._getEffect();
  14788. // Check
  14789. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14790. return 0;
  14791. var engine = this._scene.getEngine();
  14792. // Render
  14793. engine.enableEffect(effect);
  14794. engine.setState(false);
  14795. var viewMatrix = this._scene.getViewMatrix();
  14796. effect.setTexture("diffuseSampler", this.particleTexture);
  14797. effect.setMatrix("view", viewMatrix);
  14798. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14799. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14800. if (this._scene.clipPlane) {
  14801. var clipPlane = this._scene.clipPlane;
  14802. var invView = viewMatrix.clone();
  14803. invView.invert();
  14804. effect.setMatrix("invView", invView);
  14805. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14806. }
  14807. // VBOs
  14808. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14809. // Draw order
  14810. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14811. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14812. } else {
  14813. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14814. }
  14815. if (this.forceDepthWrite) {
  14816. engine.setDepthWrite(true);
  14817. }
  14818. engine.draw(true, 0, this.particles.length * 6);
  14819. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14820. return this.particles.length;
  14821. };
  14822. ParticleSystem.prototype.dispose = function () {
  14823. if (this._vertexBuffer) {
  14824. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14825. this._vertexBuffer = null;
  14826. }
  14827. if (this._indexBuffer) {
  14828. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14829. this._indexBuffer = null;
  14830. }
  14831. if (this.particleTexture) {
  14832. this.particleTexture.dispose();
  14833. this.particleTexture = null;
  14834. }
  14835. // Remove from scene
  14836. var index = this._scene.particleSystems.indexOf(this);
  14837. this._scene.particleSystems.splice(index, 1);
  14838. // Callback
  14839. if (this.onDispose) {
  14840. this.onDispose();
  14841. }
  14842. };
  14843. // Clone
  14844. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14845. var result = new ParticleSystem(name, this._capacity, this._scene);
  14846. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14847. if (newEmitter === undefined) {
  14848. newEmitter = this.emitter;
  14849. }
  14850. result.emitter = newEmitter;
  14851. if (this.particleTexture) {
  14852. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14853. }
  14854. result.start();
  14855. return result;
  14856. };
  14857. ParticleSystem.BLENDMODE_ONEONE = 0;
  14858. ParticleSystem.BLENDMODE_STANDARD = 1;
  14859. return ParticleSystem;
  14860. })();
  14861. BABYLON.ParticleSystem = ParticleSystem;
  14862. })(BABYLON || (BABYLON = {}));
  14863. //# sourceMappingURL=babylon.particleSystem.js.map
  14864. var BABYLON;
  14865. (function (BABYLON) {
  14866. var Animation = (function () {
  14867. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14868. this.name = name;
  14869. this.targetProperty = targetProperty;
  14870. this.framePerSecond = framePerSecond;
  14871. this.dataType = dataType;
  14872. this.loopMode = loopMode;
  14873. this._offsetsCache = {};
  14874. this._highLimitsCache = {};
  14875. this._stopped = false;
  14876. this.targetPropertyPath = targetProperty.split(".");
  14877. this.dataType = dataType;
  14878. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14879. }
  14880. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14881. var dataType = undefined;
  14882. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14883. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14884. } else if (from instanceof BABYLON.Quaternion) {
  14885. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14886. } else if (from instanceof BABYLON.Vector3) {
  14887. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14888. } else if (from instanceof BABYLON.Vector2) {
  14889. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14890. } else if (from instanceof BABYLON.Color3) {
  14891. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14892. }
  14893. if (dataType == undefined) {
  14894. return;
  14895. }
  14896. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14897. var keys = [];
  14898. keys.push({ frame: 0, value: from });
  14899. keys.push({ frame: totalFrame, value: to });
  14900. animation.setKeys(keys);
  14901. mesh.animations.push(animation);
  14902. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14903. };
  14904. // Methods
  14905. Animation.prototype.isStopped = function () {
  14906. return this._stopped;
  14907. };
  14908. Animation.prototype.getKeys = function () {
  14909. return this._keys;
  14910. };
  14911. Animation.prototype.getEasingFunction = function () {
  14912. return this._easingFunction;
  14913. };
  14914. Animation.prototype.setEasingFunction = function (easingFunction) {
  14915. this._easingFunction = easingFunction;
  14916. };
  14917. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14918. return startValue + (endValue - startValue) * gradient;
  14919. };
  14920. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14921. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14922. };
  14923. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14924. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14925. };
  14926. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14927. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14928. };
  14929. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14930. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14931. };
  14932. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  14933. var startScale = new BABYLON.Vector3(0, 0, 0);
  14934. var startRotation = new BABYLON.Quaternion();
  14935. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  14936. startValue.decompose(startScale, startRotation, startTranslation);
  14937. var endScale = new BABYLON.Vector3(0, 0, 0);
  14938. var endRotation = new BABYLON.Quaternion();
  14939. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  14940. endValue.decompose(endScale, endRotation, endTranslation);
  14941. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  14942. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  14943. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  14944. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  14945. return result;
  14946. };
  14947. Animation.prototype.clone = function () {
  14948. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14949. clone.setKeys(this._keys);
  14950. return clone;
  14951. };
  14952. Animation.prototype.setKeys = function (values) {
  14953. this._keys = values.slice(0);
  14954. this._offsetsCache = {};
  14955. this._highLimitsCache = {};
  14956. };
  14957. Animation.prototype._getKeyValue = function (value) {
  14958. if (typeof value === "function") {
  14959. return value();
  14960. }
  14961. return value;
  14962. };
  14963. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14964. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14965. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14966. }
  14967. this.currentFrame = currentFrame;
  14968. for (var key = 0; key < this._keys.length; key++) {
  14969. // for each frame, we need the key just before the frame superior
  14970. if (this._keys[key + 1].frame >= currentFrame) {
  14971. var startValue = this._getKeyValue(this._keys[key].value);
  14972. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14973. // gradient : percent of currentFrame between the frame inf and the frame sup
  14974. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14975. // check for easingFunction and correction of gradient
  14976. if (this._easingFunction != null) {
  14977. gradient = this._easingFunction.ease(gradient);
  14978. }
  14979. switch (this.dataType) {
  14980. case Animation.ANIMATIONTYPE_FLOAT:
  14981. switch (loopMode) {
  14982. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14983. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14984. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14985. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14986. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14987. }
  14988. break;
  14989. case Animation.ANIMATIONTYPE_QUATERNION:
  14990. var quaternion = null;
  14991. switch (loopMode) {
  14992. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14993. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14994. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14995. break;
  14996. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14997. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14998. break;
  14999. }
  15000. return quaternion;
  15001. case Animation.ANIMATIONTYPE_VECTOR3:
  15002. switch (loopMode) {
  15003. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15004. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15005. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15006. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15007. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15008. }
  15009. case Animation.ANIMATIONTYPE_VECTOR2:
  15010. switch (loopMode) {
  15011. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15012. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15013. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15014. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15015. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15016. }
  15017. case Animation.ANIMATIONTYPE_COLOR3:
  15018. switch (loopMode) {
  15019. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15020. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15021. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15022. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15023. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15024. }
  15025. case Animation.ANIMATIONTYPE_MATRIX:
  15026. switch (loopMode) {
  15027. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15028. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15029. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  15030. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15031. return startValue;
  15032. }
  15033. default:
  15034. break;
  15035. }
  15036. break;
  15037. }
  15038. }
  15039. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15040. };
  15041. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15042. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15043. this._stopped = true;
  15044. return false;
  15045. }
  15046. var returnValue = true;
  15047. // Adding a start key at frame 0 if missing
  15048. if (this._keys[0].frame !== 0) {
  15049. var newKey = { frame: 0, value: this._keys[0].value };
  15050. this._keys.splice(0, 0, newKey);
  15051. }
  15052. // Check limits
  15053. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15054. from = this._keys[0].frame;
  15055. }
  15056. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15057. to = this._keys[this._keys.length - 1].frame;
  15058. }
  15059. // Compute ratio
  15060. var range = to - from;
  15061. var offsetValue;
  15062. // ratio represents the frame delta between from and to
  15063. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15064. var highLimitValue = 0;
  15065. if (ratio > range && !loop) {
  15066. returnValue = false;
  15067. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15068. } else {
  15069. // Get max value if required
  15070. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15071. var keyOffset = to.toString() + from.toString();
  15072. if (!this._offsetsCache[keyOffset]) {
  15073. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15074. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15075. switch (this.dataType) {
  15076. case Animation.ANIMATIONTYPE_FLOAT:
  15077. this._offsetsCache[keyOffset] = toValue - fromValue;
  15078. break;
  15079. case Animation.ANIMATIONTYPE_QUATERNION:
  15080. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15081. break;
  15082. case Animation.ANIMATIONTYPE_VECTOR3:
  15083. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15084. case Animation.ANIMATIONTYPE_VECTOR2:
  15085. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15086. case Animation.ANIMATIONTYPE_COLOR3:
  15087. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15088. default:
  15089. break;
  15090. }
  15091. this._highLimitsCache[keyOffset] = toValue;
  15092. }
  15093. highLimitValue = this._highLimitsCache[keyOffset];
  15094. offsetValue = this._offsetsCache[keyOffset];
  15095. }
  15096. }
  15097. if (offsetValue === undefined) {
  15098. switch (this.dataType) {
  15099. case Animation.ANIMATIONTYPE_FLOAT:
  15100. offsetValue = 0;
  15101. break;
  15102. case Animation.ANIMATIONTYPE_QUATERNION:
  15103. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15104. break;
  15105. case Animation.ANIMATIONTYPE_VECTOR3:
  15106. offsetValue = BABYLON.Vector3.Zero();
  15107. break;
  15108. case Animation.ANIMATIONTYPE_VECTOR2:
  15109. offsetValue = BABYLON.Vector2.Zero();
  15110. break;
  15111. case Animation.ANIMATIONTYPE_COLOR3:
  15112. offsetValue = BABYLON.Color3.Black();
  15113. }
  15114. }
  15115. // Compute value
  15116. var repeatCount = (ratio / range) >> 0;
  15117. var currentFrame = returnValue ? from + ratio % range : to;
  15118. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15119. // Set value
  15120. if (this.targetPropertyPath.length > 1) {
  15121. var property = this._target[this.targetPropertyPath[0]];
  15122. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15123. property = property[this.targetPropertyPath[index]];
  15124. }
  15125. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15126. } else {
  15127. this._target[this.targetPropertyPath[0]] = currentValue;
  15128. }
  15129. if (this._target.markAsDirty) {
  15130. this._target.markAsDirty(this.targetProperty);
  15131. }
  15132. if (!returnValue) {
  15133. this._stopped = true;
  15134. }
  15135. return returnValue;
  15136. };
  15137. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15138. get: function () {
  15139. return Animation._ANIMATIONTYPE_FLOAT;
  15140. },
  15141. enumerable: true,
  15142. configurable: true
  15143. });
  15144. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15145. get: function () {
  15146. return Animation._ANIMATIONTYPE_VECTOR3;
  15147. },
  15148. enumerable: true,
  15149. configurable: true
  15150. });
  15151. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15152. get: function () {
  15153. return Animation._ANIMATIONTYPE_VECTOR2;
  15154. },
  15155. enumerable: true,
  15156. configurable: true
  15157. });
  15158. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15159. get: function () {
  15160. return Animation._ANIMATIONTYPE_QUATERNION;
  15161. },
  15162. enumerable: true,
  15163. configurable: true
  15164. });
  15165. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15166. get: function () {
  15167. return Animation._ANIMATIONTYPE_MATRIX;
  15168. },
  15169. enumerable: true,
  15170. configurable: true
  15171. });
  15172. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15173. get: function () {
  15174. return Animation._ANIMATIONTYPE_COLOR3;
  15175. },
  15176. enumerable: true,
  15177. configurable: true
  15178. });
  15179. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15180. get: function () {
  15181. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15182. },
  15183. enumerable: true,
  15184. configurable: true
  15185. });
  15186. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15187. get: function () {
  15188. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15189. },
  15190. enumerable: true,
  15191. configurable: true
  15192. });
  15193. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15194. get: function () {
  15195. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15196. },
  15197. enumerable: true,
  15198. configurable: true
  15199. });
  15200. Animation._ANIMATIONTYPE_FLOAT = 0;
  15201. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15202. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15203. Animation._ANIMATIONTYPE_MATRIX = 3;
  15204. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15205. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15206. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15207. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15208. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15209. return Animation;
  15210. })();
  15211. BABYLON.Animation = Animation;
  15212. })(BABYLON || (BABYLON = {}));
  15213. //# sourceMappingURL=babylon.animation.js.map
  15214. var BABYLON;
  15215. (function (BABYLON) {
  15216. var Animatable = (function () {
  15217. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15218. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  15219. if (typeof toFrame === "undefined") { toFrame = 100; }
  15220. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  15221. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  15222. this.target = target;
  15223. this.fromFrame = fromFrame;
  15224. this.toFrame = toFrame;
  15225. this.loopAnimation = loopAnimation;
  15226. this.speedRatio = speedRatio;
  15227. this.onAnimationEnd = onAnimationEnd;
  15228. this._animations = new Array();
  15229. this._paused = false;
  15230. this.animationStarted = false;
  15231. if (animations) {
  15232. this.appendAnimations(target, animations);
  15233. }
  15234. this._scene = scene;
  15235. scene._activeAnimatables.push(this);
  15236. }
  15237. // Methods
  15238. Animatable.prototype.appendAnimations = function (target, animations) {
  15239. for (var index = 0; index < animations.length; index++) {
  15240. var animation = animations[index];
  15241. animation._target = target;
  15242. this._animations.push(animation);
  15243. }
  15244. };
  15245. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15246. var animations = this._animations;
  15247. for (var index = 0; index < animations.length; index++) {
  15248. if (animations[index].targetProperty === property) {
  15249. return animations[index];
  15250. }
  15251. }
  15252. return null;
  15253. };
  15254. Animatable.prototype.pause = function () {
  15255. if (this._paused) {
  15256. return;
  15257. }
  15258. this._paused = true;
  15259. };
  15260. Animatable.prototype.restart = function () {
  15261. this._paused = false;
  15262. };
  15263. Animatable.prototype.stop = function () {
  15264. var index = this._scene._activeAnimatables.indexOf(this);
  15265. if (index > -1) {
  15266. this._scene._activeAnimatables.splice(index, 1);
  15267. }
  15268. if (this.onAnimationEnd) {
  15269. this.onAnimationEnd();
  15270. }
  15271. };
  15272. Animatable.prototype._animate = function (delay) {
  15273. if (this._paused) {
  15274. if (!this._pausedDelay) {
  15275. this._pausedDelay = delay;
  15276. }
  15277. return true;
  15278. }
  15279. if (!this._localDelayOffset) {
  15280. this._localDelayOffset = delay;
  15281. } else if (this._pausedDelay) {
  15282. this._localDelayOffset += delay - this._pausedDelay;
  15283. this._pausedDelay = null;
  15284. }
  15285. // Animating
  15286. var running = false;
  15287. var animations = this._animations;
  15288. for (var index = 0; index < animations.length; index++) {
  15289. var animation = animations[index];
  15290. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15291. running = running || isRunning;
  15292. }
  15293. if (!running && this.onAnimationEnd) {
  15294. this.onAnimationEnd();
  15295. }
  15296. return running;
  15297. };
  15298. return Animatable;
  15299. })();
  15300. BABYLON.Animatable = Animatable;
  15301. })(BABYLON || (BABYLON = {}));
  15302. //# sourceMappingURL=babylon.animatable.js.map
  15303. var BABYLON;
  15304. (function (BABYLON) {
  15305. var EasingFunction = (function () {
  15306. function EasingFunction() {
  15307. // Properties
  15308. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15309. }
  15310. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15311. get: function () {
  15312. return EasingFunction._EASINGMODE_EASEIN;
  15313. },
  15314. enumerable: true,
  15315. configurable: true
  15316. });
  15317. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15318. get: function () {
  15319. return EasingFunction._EASINGMODE_EASEOUT;
  15320. },
  15321. enumerable: true,
  15322. configurable: true
  15323. });
  15324. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15325. get: function () {
  15326. return EasingFunction._EASINGMODE_EASEINOUT;
  15327. },
  15328. enumerable: true,
  15329. configurable: true
  15330. });
  15331. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15332. var n = Math.min(Math.max(easingMode, 0), 2);
  15333. this._easingMode = n;
  15334. };
  15335. EasingFunction.prototype.getEasingMode = function () {
  15336. return this._easingMode;
  15337. };
  15338. EasingFunction.prototype.easeInCore = function (gradient) {
  15339. throw new Error('You must implement this method');
  15340. };
  15341. EasingFunction.prototype.ease = function (gradient) {
  15342. switch (this._easingMode) {
  15343. case EasingFunction.EASINGMODE_EASEIN:
  15344. return this.easeInCore(gradient);
  15345. case EasingFunction.EASINGMODE_EASEOUT:
  15346. return (1 - this.easeInCore(1 - gradient));
  15347. }
  15348. if (gradient >= 0.5) {
  15349. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15350. }
  15351. return (this.easeInCore(gradient * 2) * 0.5);
  15352. };
  15353. EasingFunction._EASINGMODE_EASEIN = 0;
  15354. EasingFunction._EASINGMODE_EASEOUT = 1;
  15355. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15356. return EasingFunction;
  15357. })();
  15358. BABYLON.EasingFunction = EasingFunction;
  15359. var CircleEase = (function (_super) {
  15360. __extends(CircleEase, _super);
  15361. function CircleEase() {
  15362. _super.apply(this, arguments);
  15363. }
  15364. CircleEase.prototype.easeInCore = function (gradient) {
  15365. gradient = Math.max(0, Math.min(1, gradient));
  15366. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15367. };
  15368. return CircleEase;
  15369. })(EasingFunction);
  15370. BABYLON.CircleEase = CircleEase;
  15371. var BackEase = (function (_super) {
  15372. __extends(BackEase, _super);
  15373. function BackEase(amplitude) {
  15374. if (typeof amplitude === "undefined") { amplitude = 1; }
  15375. _super.call(this);
  15376. this.amplitude = amplitude;
  15377. }
  15378. BackEase.prototype.easeInCore = function (gradient) {
  15379. var num = Math.max(0, this.amplitude);
  15380. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15381. };
  15382. return BackEase;
  15383. })(EasingFunction);
  15384. BABYLON.BackEase = BackEase;
  15385. var BounceEase = (function (_super) {
  15386. __extends(BounceEase, _super);
  15387. function BounceEase(bounces, bounciness) {
  15388. if (typeof bounces === "undefined") { bounces = 3; }
  15389. if (typeof bounciness === "undefined") { bounciness = 2; }
  15390. _super.call(this);
  15391. this.bounces = bounces;
  15392. this.bounciness = bounciness;
  15393. }
  15394. BounceEase.prototype.easeInCore = function (gradient) {
  15395. var y = Math.max(0.0, this.bounces);
  15396. var bounciness = this.bounciness;
  15397. if (bounciness <= 1.0) {
  15398. bounciness = 1.001;
  15399. }
  15400. var num9 = Math.pow(bounciness, y);
  15401. var num5 = 1.0 - bounciness;
  15402. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15403. var num15 = gradient * num4;
  15404. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15405. var num3 = Math.floor(num65);
  15406. var num13 = num3 + 1.0;
  15407. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15408. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15409. var num7 = (num8 + num12) * 0.5;
  15410. var num6 = gradient - num7;
  15411. var num2 = num7 - num8;
  15412. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15413. };
  15414. return BounceEase;
  15415. })(EasingFunction);
  15416. BABYLON.BounceEase = BounceEase;
  15417. var CubicEase = (function (_super) {
  15418. __extends(CubicEase, _super);
  15419. function CubicEase() {
  15420. _super.apply(this, arguments);
  15421. }
  15422. CubicEase.prototype.easeInCore = function (gradient) {
  15423. return (gradient * gradient * gradient);
  15424. };
  15425. return CubicEase;
  15426. })(EasingFunction);
  15427. BABYLON.CubicEase = CubicEase;
  15428. var ElasticEase = (function (_super) {
  15429. __extends(ElasticEase, _super);
  15430. function ElasticEase(oscillations, springiness) {
  15431. if (typeof oscillations === "undefined") { oscillations = 3; }
  15432. if (typeof springiness === "undefined") { springiness = 3; }
  15433. _super.call(this);
  15434. this.oscillations = oscillations;
  15435. this.springiness = springiness;
  15436. }
  15437. ElasticEase.prototype.easeInCore = function (gradient) {
  15438. var num2;
  15439. var num3 = Math.max(0.0, this.oscillations);
  15440. var num = Math.max(0.0, this.springiness);
  15441. if (num == 0) {
  15442. num2 = gradient;
  15443. } else {
  15444. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15445. }
  15446. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15447. };
  15448. return ElasticEase;
  15449. })(EasingFunction);
  15450. BABYLON.ElasticEase = ElasticEase;
  15451. var ExponentialEase = (function (_super) {
  15452. __extends(ExponentialEase, _super);
  15453. function ExponentialEase(exponent) {
  15454. if (typeof exponent === "undefined") { exponent = 2; }
  15455. _super.call(this);
  15456. this.exponent = exponent;
  15457. }
  15458. ExponentialEase.prototype.easeInCore = function (gradient) {
  15459. if (this.exponent <= 0) {
  15460. return gradient;
  15461. }
  15462. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15463. };
  15464. return ExponentialEase;
  15465. })(EasingFunction);
  15466. BABYLON.ExponentialEase = ExponentialEase;
  15467. var PowerEase = (function (_super) {
  15468. __extends(PowerEase, _super);
  15469. function PowerEase(power) {
  15470. if (typeof power === "undefined") { power = 2; }
  15471. _super.call(this);
  15472. this.power = power;
  15473. }
  15474. PowerEase.prototype.easeInCore = function (gradient) {
  15475. var y = Math.max(0.0, this.power);
  15476. return Math.pow(gradient, y);
  15477. };
  15478. return PowerEase;
  15479. })(EasingFunction);
  15480. BABYLON.PowerEase = PowerEase;
  15481. var QuadraticEase = (function (_super) {
  15482. __extends(QuadraticEase, _super);
  15483. function QuadraticEase() {
  15484. _super.apply(this, arguments);
  15485. }
  15486. QuadraticEase.prototype.easeInCore = function (gradient) {
  15487. return (gradient * gradient);
  15488. };
  15489. return QuadraticEase;
  15490. })(EasingFunction);
  15491. BABYLON.QuadraticEase = QuadraticEase;
  15492. var QuarticEase = (function (_super) {
  15493. __extends(QuarticEase, _super);
  15494. function QuarticEase() {
  15495. _super.apply(this, arguments);
  15496. }
  15497. QuarticEase.prototype.easeInCore = function (gradient) {
  15498. return (gradient * gradient * gradient * gradient);
  15499. };
  15500. return QuarticEase;
  15501. })(EasingFunction);
  15502. BABYLON.QuarticEase = QuarticEase;
  15503. var QuinticEase = (function (_super) {
  15504. __extends(QuinticEase, _super);
  15505. function QuinticEase() {
  15506. _super.apply(this, arguments);
  15507. }
  15508. QuinticEase.prototype.easeInCore = function (gradient) {
  15509. return (gradient * gradient * gradient * gradient * gradient);
  15510. };
  15511. return QuinticEase;
  15512. })(EasingFunction);
  15513. BABYLON.QuinticEase = QuinticEase;
  15514. var SineEase = (function (_super) {
  15515. __extends(SineEase, _super);
  15516. function SineEase() {
  15517. _super.apply(this, arguments);
  15518. }
  15519. SineEase.prototype.easeInCore = function (gradient) {
  15520. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15521. };
  15522. return SineEase;
  15523. })(EasingFunction);
  15524. BABYLON.SineEase = SineEase;
  15525. var BezierCurveEase = (function (_super) {
  15526. __extends(BezierCurveEase, _super);
  15527. function BezierCurveEase(x1, y1, x2, y2) {
  15528. if (typeof x1 === "undefined") { x1 = 0; }
  15529. if (typeof y1 === "undefined") { y1 = 0; }
  15530. if (typeof x2 === "undefined") { x2 = 1; }
  15531. if (typeof y2 === "undefined") { y2 = 1; }
  15532. _super.call(this);
  15533. this.x1 = x1;
  15534. this.y1 = y1;
  15535. this.x2 = x2;
  15536. this.y2 = y2;
  15537. }
  15538. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15539. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15540. };
  15541. return BezierCurveEase;
  15542. })(EasingFunction);
  15543. BABYLON.BezierCurveEase = BezierCurveEase;
  15544. })(BABYLON || (BABYLON = {}));
  15545. //# sourceMappingURL=babylon.easing.js.map
  15546. var BABYLON;
  15547. (function (BABYLON) {
  15548. var Octree = (function () {
  15549. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15550. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  15551. this.maxDepth = maxDepth;
  15552. this.dynamicContent = new Array();
  15553. this._maxBlockCapacity = maxBlockCapacity || 64;
  15554. this._selectionContent = new BABYLON.SmartArray(1024);
  15555. this._creationFunc = creationFunc;
  15556. }
  15557. // Methods
  15558. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15559. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15560. };
  15561. Octree.prototype.addMesh = function (entry) {
  15562. for (var index = 0; index < this.blocks.length; index++) {
  15563. var block = this.blocks[index];
  15564. block.addEntry(entry);
  15565. }
  15566. };
  15567. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15568. this._selectionContent.reset();
  15569. for (var index = 0; index < this.blocks.length; index++) {
  15570. var block = this.blocks[index];
  15571. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15572. }
  15573. if (allowDuplicate) {
  15574. this._selectionContent.concat(this.dynamicContent);
  15575. } else {
  15576. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15577. }
  15578. return this._selectionContent;
  15579. };
  15580. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15581. this._selectionContent.reset();
  15582. for (var index = 0; index < this.blocks.length; index++) {
  15583. var block = this.blocks[index];
  15584. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15585. }
  15586. if (allowDuplicate) {
  15587. this._selectionContent.concat(this.dynamicContent);
  15588. } else {
  15589. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15590. }
  15591. return this._selectionContent;
  15592. };
  15593. Octree.prototype.intersectsRay = function (ray) {
  15594. this._selectionContent.reset();
  15595. for (var index = 0; index < this.blocks.length; index++) {
  15596. var block = this.blocks[index];
  15597. block.intersectsRay(ray, this._selectionContent);
  15598. }
  15599. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15600. return this._selectionContent;
  15601. };
  15602. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15603. target.blocks = new Array();
  15604. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15605. for (var x = 0; x < 2; x++) {
  15606. for (var y = 0; y < 2; y++) {
  15607. for (var z = 0; z < 2; z++) {
  15608. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15609. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15610. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15611. block.addEntries(entries);
  15612. target.blocks.push(block);
  15613. }
  15614. }
  15615. }
  15616. };
  15617. Octree.CreationFuncForMeshes = function (entry, block) {
  15618. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15619. block.entries.push(entry);
  15620. }
  15621. };
  15622. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15623. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15624. block.entries.push(entry);
  15625. }
  15626. };
  15627. return Octree;
  15628. })();
  15629. BABYLON.Octree = Octree;
  15630. })(BABYLON || (BABYLON = {}));
  15631. //# sourceMappingURL=babylon.octree.js.map
  15632. var BABYLON;
  15633. (function (BABYLON) {
  15634. var OctreeBlock = (function () {
  15635. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15636. this.entries = new Array();
  15637. this._boundingVectors = new Array();
  15638. this._capacity = capacity;
  15639. this._depth = depth;
  15640. this._maxDepth = maxDepth;
  15641. this._creationFunc = creationFunc;
  15642. this._minPoint = minPoint;
  15643. this._maxPoint = maxPoint;
  15644. this._boundingVectors.push(minPoint.clone());
  15645. this._boundingVectors.push(maxPoint.clone());
  15646. this._boundingVectors.push(minPoint.clone());
  15647. this._boundingVectors[2].x = maxPoint.x;
  15648. this._boundingVectors.push(minPoint.clone());
  15649. this._boundingVectors[3].y = maxPoint.y;
  15650. this._boundingVectors.push(minPoint.clone());
  15651. this._boundingVectors[4].z = maxPoint.z;
  15652. this._boundingVectors.push(maxPoint.clone());
  15653. this._boundingVectors[5].z = minPoint.z;
  15654. this._boundingVectors.push(maxPoint.clone());
  15655. this._boundingVectors[6].x = minPoint.x;
  15656. this._boundingVectors.push(maxPoint.clone());
  15657. this._boundingVectors[7].y = minPoint.y;
  15658. }
  15659. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15660. // Property
  15661. get: function () {
  15662. return this._capacity;
  15663. },
  15664. enumerable: true,
  15665. configurable: true
  15666. });
  15667. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15668. get: function () {
  15669. return this._minPoint;
  15670. },
  15671. enumerable: true,
  15672. configurable: true
  15673. });
  15674. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15675. get: function () {
  15676. return this._maxPoint;
  15677. },
  15678. enumerable: true,
  15679. configurable: true
  15680. });
  15681. // Methods
  15682. OctreeBlock.prototype.addEntry = function (entry) {
  15683. if (this.blocks) {
  15684. for (var index = 0; index < this.blocks.length; index++) {
  15685. var block = this.blocks[index];
  15686. block.addEntry(entry);
  15687. }
  15688. return;
  15689. }
  15690. this._creationFunc(entry, this);
  15691. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15692. this.createInnerBlocks();
  15693. }
  15694. };
  15695. OctreeBlock.prototype.addEntries = function (entries) {
  15696. for (var index = 0; index < entries.length; index++) {
  15697. var mesh = entries[index];
  15698. this.addEntry(mesh);
  15699. }
  15700. };
  15701. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15702. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15703. if (this.blocks) {
  15704. for (var index = 0; index < this.blocks.length; index++) {
  15705. var block = this.blocks[index];
  15706. block.select(frustumPlanes, selection, allowDuplicate);
  15707. }
  15708. return;
  15709. }
  15710. if (allowDuplicate) {
  15711. selection.concat(this.entries);
  15712. } else {
  15713. selection.concatWithNoDuplicate(this.entries);
  15714. }
  15715. }
  15716. };
  15717. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15718. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15719. if (this.blocks) {
  15720. for (var index = 0; index < this.blocks.length; index++) {
  15721. var block = this.blocks[index];
  15722. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15723. }
  15724. return;
  15725. }
  15726. if (allowDuplicate) {
  15727. selection.concat(this.entries);
  15728. } else {
  15729. selection.concatWithNoDuplicate(this.entries);
  15730. }
  15731. }
  15732. };
  15733. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15734. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15735. if (this.blocks) {
  15736. for (var index = 0; index < this.blocks.length; index++) {
  15737. var block = this.blocks[index];
  15738. block.intersectsRay(ray, selection);
  15739. }
  15740. return;
  15741. }
  15742. selection.concatWithNoDuplicate(this.entries);
  15743. }
  15744. };
  15745. OctreeBlock.prototype.createInnerBlocks = function () {
  15746. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15747. };
  15748. return OctreeBlock;
  15749. })();
  15750. BABYLON.OctreeBlock = OctreeBlock;
  15751. })(BABYLON || (BABYLON = {}));
  15752. //# sourceMappingURL=babylon.octreeBlock.js.map
  15753. var BABYLON;
  15754. (function (BABYLON) {
  15755. var Bone = (function () {
  15756. function Bone(name, skeleton, parentBone, matrix) {
  15757. this.name = name;
  15758. this.children = new Array();
  15759. this.animations = new Array();
  15760. this._worldTransform = new BABYLON.Matrix();
  15761. this._absoluteTransform = new BABYLON.Matrix();
  15762. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15763. this._skeleton = skeleton;
  15764. this._matrix = matrix;
  15765. this._baseMatrix = matrix;
  15766. skeleton.bones.push(this);
  15767. if (parentBone) {
  15768. this._parent = parentBone;
  15769. parentBone.children.push(this);
  15770. } else {
  15771. this._parent = null;
  15772. }
  15773. this._updateDifferenceMatrix();
  15774. }
  15775. // Members
  15776. Bone.prototype.getParent = function () {
  15777. return this._parent;
  15778. };
  15779. Bone.prototype.getLocalMatrix = function () {
  15780. return this._matrix;
  15781. };
  15782. Bone.prototype.getBaseMatrix = function () {
  15783. return this._baseMatrix;
  15784. };
  15785. Bone.prototype.getWorldMatrix = function () {
  15786. return this._worldTransform;
  15787. };
  15788. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15789. return this._invertedAbsoluteTransform;
  15790. };
  15791. Bone.prototype.getAbsoluteMatrix = function () {
  15792. var matrix = this._matrix.clone();
  15793. var parent = this._parent;
  15794. while (parent) {
  15795. matrix = matrix.multiply(parent.getLocalMatrix());
  15796. parent = parent.getParent();
  15797. }
  15798. return matrix;
  15799. };
  15800. // Methods
  15801. Bone.prototype.updateMatrix = function (matrix) {
  15802. this._matrix = matrix;
  15803. this._skeleton._markAsDirty();
  15804. this._updateDifferenceMatrix();
  15805. };
  15806. Bone.prototype._updateDifferenceMatrix = function () {
  15807. if (this._parent) {
  15808. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15809. } else {
  15810. this._absoluteTransform.copyFrom(this._matrix);
  15811. }
  15812. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15813. for (var index = 0; index < this.children.length; index++) {
  15814. this.children[index]._updateDifferenceMatrix();
  15815. }
  15816. };
  15817. Bone.prototype.markAsDirty = function () {
  15818. this._skeleton._markAsDirty();
  15819. };
  15820. return Bone;
  15821. })();
  15822. BABYLON.Bone = Bone;
  15823. })(BABYLON || (BABYLON = {}));
  15824. //# sourceMappingURL=babylon.bone.js.map
  15825. var BABYLON;
  15826. (function (BABYLON) {
  15827. var Skeleton = (function () {
  15828. function Skeleton(name, id, scene) {
  15829. this.name = name;
  15830. this.id = id;
  15831. this.bones = new Array();
  15832. this._isDirty = true;
  15833. this._identity = BABYLON.Matrix.Identity();
  15834. this.bones = [];
  15835. this._scene = scene;
  15836. scene.skeletons.push(this);
  15837. }
  15838. // Members
  15839. Skeleton.prototype.getTransformMatrices = function () {
  15840. return this._transformMatrices;
  15841. };
  15842. // Methods
  15843. Skeleton.prototype._markAsDirty = function () {
  15844. this._isDirty = true;
  15845. };
  15846. Skeleton.prototype.prepare = function () {
  15847. if (!this._isDirty) {
  15848. return;
  15849. }
  15850. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15851. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15852. }
  15853. for (var index = 0; index < this.bones.length; index++) {
  15854. var bone = this.bones[index];
  15855. var parentBone = bone.getParent();
  15856. if (parentBone) {
  15857. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15858. } else {
  15859. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15860. }
  15861. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15862. }
  15863. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15864. this._isDirty = false;
  15865. };
  15866. Skeleton.prototype.getAnimatables = function () {
  15867. if (!this._animatables || this._animatables.length != this.bones.length) {
  15868. this._animatables = [];
  15869. for (var index = 0; index < this.bones.length; index++) {
  15870. this._animatables.push(this.bones[index]);
  15871. }
  15872. }
  15873. return this._animatables;
  15874. };
  15875. Skeleton.prototype.clone = function (name, id) {
  15876. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15877. for (var index = 0; index < this.bones.length; index++) {
  15878. var source = this.bones[index];
  15879. var parentBone = null;
  15880. if (source.getParent()) {
  15881. var parentIndex = this.bones.indexOf(source.getParent());
  15882. parentBone = result.bones[parentIndex];
  15883. }
  15884. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15885. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15886. }
  15887. return result;
  15888. };
  15889. return Skeleton;
  15890. })();
  15891. BABYLON.Skeleton = Skeleton;
  15892. })(BABYLON || (BABYLON = {}));
  15893. //# sourceMappingURL=babylon.skeleton.js.map
  15894. var BABYLON;
  15895. (function (BABYLON) {
  15896. var PostProcess = (function () {
  15897. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15898. this.name = name;
  15899. this.width = -1;
  15900. this.height = -1;
  15901. this._reusable = false;
  15902. this._textures = new BABYLON.SmartArray(2);
  15903. this._currentRenderTextureInd = 0;
  15904. if (camera != null) {
  15905. this._camera = camera;
  15906. this._scene = camera.getScene();
  15907. camera.attachPostProcess(this);
  15908. this._engine = this._scene.getEngine();
  15909. } else {
  15910. this._engine = engine;
  15911. }
  15912. this._renderRatio = ratio;
  15913. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15914. this._reusable = reusable || false;
  15915. samplers = samplers || [];
  15916. samplers.push("textureSampler");
  15917. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15918. }
  15919. PostProcess.prototype.isReusable = function () {
  15920. return this._reusable;
  15921. };
  15922. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15923. camera = camera || this._camera;
  15924. var scene = camera.getScene();
  15925. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15926. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15927. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15928. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15929. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15930. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15931. if (this._textures.length > 0) {
  15932. for (var i = 0; i < this._textures.length; i++) {
  15933. this._engine._releaseTexture(this._textures.data[i]);
  15934. }
  15935. this._textures.reset();
  15936. }
  15937. this.width = desiredWidth;
  15938. this.height = desiredHeight;
  15939. 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 }));
  15940. if (this._reusable) {
  15941. 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 }));
  15942. }
  15943. if (this.onSizeChanged) {
  15944. this.onSizeChanged();
  15945. }
  15946. }
  15947. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15948. if (this.onActivate) {
  15949. this.onActivate(camera);
  15950. }
  15951. // Clear
  15952. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15953. if (this._reusable) {
  15954. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15955. }
  15956. };
  15957. PostProcess.prototype.apply = function () {
  15958. // Check
  15959. if (!this._effect.isReady())
  15960. return null;
  15961. // States
  15962. this._engine.enableEffect(this._effect);
  15963. this._engine.setState(false);
  15964. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15965. this._engine.setDepthBuffer(false);
  15966. this._engine.setDepthWrite(false);
  15967. // Texture
  15968. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15969. // Parameters
  15970. if (this.onApply) {
  15971. this.onApply(this._effect);
  15972. }
  15973. return this._effect;
  15974. };
  15975. PostProcess.prototype.dispose = function (camera) {
  15976. camera = camera || this._camera;
  15977. if (this._textures.length > 0) {
  15978. for (var i = 0; i < this._textures.length; i++) {
  15979. this._engine._releaseTexture(this._textures.data[i]);
  15980. }
  15981. this._textures.reset();
  15982. }
  15983. camera.detachPostProcess(this);
  15984. var index = camera._postProcesses.indexOf(this);
  15985. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15986. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15987. }
  15988. };
  15989. return PostProcess;
  15990. })();
  15991. BABYLON.PostProcess = PostProcess;
  15992. })(BABYLON || (BABYLON = {}));
  15993. //# sourceMappingURL=babylon.postProcess.js.map
  15994. var BABYLON;
  15995. (function (BABYLON) {
  15996. var PostProcessManager = (function () {
  15997. function PostProcessManager(scene) {
  15998. this._vertexDeclaration = [2];
  15999. this._vertexStrideSize = 2 * 4;
  16000. this._scene = scene;
  16001. // VBO
  16002. var vertices = [];
  16003. vertices.push(1, 1);
  16004. vertices.push(-1, 1);
  16005. vertices.push(-1, -1);
  16006. vertices.push(1, -1);
  16007. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16008. // Indices
  16009. var indices = [];
  16010. indices.push(0);
  16011. indices.push(1);
  16012. indices.push(2);
  16013. indices.push(0);
  16014. indices.push(2);
  16015. indices.push(3);
  16016. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16017. }
  16018. // Methods
  16019. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16020. var postProcesses = this._scene.activeCamera._postProcesses;
  16021. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16022. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16023. return false;
  16024. }
  16025. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16026. return true;
  16027. };
  16028. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16029. var postProcesses = this._scene.activeCamera._postProcesses;
  16030. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16031. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16032. return;
  16033. }
  16034. var engine = this._scene.getEngine();
  16035. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16036. if (index < postProcessesTakenIndices.length - 1) {
  16037. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16038. } else {
  16039. if (targetTexture) {
  16040. engine.bindFramebuffer(targetTexture);
  16041. } else {
  16042. engine.restoreDefaultFramebuffer();
  16043. }
  16044. }
  16045. if (doNotPresent) {
  16046. break;
  16047. }
  16048. var pp = postProcesses[postProcessesTakenIndices[index]];
  16049. var effect = pp.apply();
  16050. if (effect) {
  16051. if (pp.onBeforeRender) {
  16052. pp.onBeforeRender(effect);
  16053. }
  16054. // VBOs
  16055. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16056. // Draw order
  16057. engine.draw(true, 0, 6);
  16058. }
  16059. }
  16060. // Restore depth buffer
  16061. engine.setDepthBuffer(true);
  16062. engine.setDepthWrite(true);
  16063. };
  16064. PostProcessManager.prototype.dispose = function () {
  16065. if (this._vertexBuffer) {
  16066. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16067. this._vertexBuffer = null;
  16068. }
  16069. if (this._indexBuffer) {
  16070. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16071. this._indexBuffer = null;
  16072. }
  16073. };
  16074. return PostProcessManager;
  16075. })();
  16076. BABYLON.PostProcessManager = PostProcessManager;
  16077. })(BABYLON || (BABYLON = {}));
  16078. //# sourceMappingURL=babylon.postProcessManager.js.map
  16079. var BABYLON;
  16080. (function (BABYLON) {
  16081. var PassPostProcess = (function (_super) {
  16082. __extends(PassPostProcess, _super);
  16083. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16084. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16085. }
  16086. return PassPostProcess;
  16087. })(BABYLON.PostProcess);
  16088. BABYLON.PassPostProcess = PassPostProcess;
  16089. })(BABYLON || (BABYLON = {}));
  16090. //# sourceMappingURL=babylon.passPostProcess.js.map
  16091. var BABYLON;
  16092. (function (BABYLON) {
  16093. var BlurPostProcess = (function (_super) {
  16094. __extends(BlurPostProcess, _super);
  16095. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16096. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16097. var _this = this;
  16098. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16099. this.direction = direction;
  16100. this.blurWidth = blurWidth;
  16101. this.onApply = function (effect) {
  16102. effect.setFloat2("screenSize", _this.width, _this.height);
  16103. effect.setVector2("direction", _this.direction);
  16104. effect.setFloat("blurWidth", _this.blurWidth);
  16105. };
  16106. }
  16107. return BlurPostProcess;
  16108. })(BABYLON.PostProcess);
  16109. BABYLON.BlurPostProcess = BlurPostProcess;
  16110. })(BABYLON || (BABYLON = {}));
  16111. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16112. var BABYLON;
  16113. (function (BABYLON) {
  16114. var FilterPostProcess = (function (_super) {
  16115. __extends(FilterPostProcess, _super);
  16116. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16117. var _this = this;
  16118. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16119. this.kernelMatrix = kernelMatrix;
  16120. this.onApply = function (effect) {
  16121. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16122. };
  16123. }
  16124. return FilterPostProcess;
  16125. })(BABYLON.PostProcess);
  16126. BABYLON.FilterPostProcess = FilterPostProcess;
  16127. })(BABYLON || (BABYLON = {}));
  16128. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16129. var BABYLON;
  16130. (function (BABYLON) {
  16131. var RefractionPostProcess = (function (_super) {
  16132. __extends(RefractionPostProcess, _super);
  16133. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16134. var _this = this;
  16135. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16136. this.color = color;
  16137. this.depth = depth;
  16138. this.colorLevel = colorLevel;
  16139. this.onActivate = function (cam) {
  16140. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16141. };
  16142. this.onApply = function (effect) {
  16143. effect.setColor3("baseColor", _this.color);
  16144. effect.setFloat("depth", _this.depth);
  16145. effect.setFloat("colorLevel", _this.colorLevel);
  16146. effect.setTexture("refractionSampler", _this._refRexture);
  16147. };
  16148. }
  16149. // Methods
  16150. RefractionPostProcess.prototype.dispose = function (camera) {
  16151. if (this._refRexture) {
  16152. this._refRexture.dispose();
  16153. }
  16154. _super.prototype.dispose.call(this, camera);
  16155. };
  16156. return RefractionPostProcess;
  16157. })(BABYLON.PostProcess);
  16158. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16159. })(BABYLON || (BABYLON = {}));
  16160. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16161. var BABYLON;
  16162. (function (BABYLON) {
  16163. var BlackAndWhitePostProcess = (function (_super) {
  16164. __extends(BlackAndWhitePostProcess, _super);
  16165. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16166. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16167. }
  16168. return BlackAndWhitePostProcess;
  16169. })(BABYLON.PostProcess);
  16170. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16171. })(BABYLON || (BABYLON = {}));
  16172. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16173. var BABYLON;
  16174. (function (BABYLON) {
  16175. var ConvolutionPostProcess = (function (_super) {
  16176. __extends(ConvolutionPostProcess, _super);
  16177. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16178. var _this = this;
  16179. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16180. this.kernel = kernel;
  16181. this.onApply = function (effect) {
  16182. effect.setFloat2("screenSize", _this.width, _this.height);
  16183. effect.setArray("kernel", _this.kernel);
  16184. };
  16185. }
  16186. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16187. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16188. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16189. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16190. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16191. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16192. return ConvolutionPostProcess;
  16193. })(BABYLON.PostProcess);
  16194. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16195. })(BABYLON || (BABYLON = {}));
  16196. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16197. var BABYLON;
  16198. (function (BABYLON) {
  16199. var FxaaPostProcess = (function (_super) {
  16200. __extends(FxaaPostProcess, _super);
  16201. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16202. var _this = this;
  16203. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16204. this.onSizeChanged = function () {
  16205. _this.texelWidth = 1.0 / _this.width;
  16206. _this.texelHeight = 1.0 / _this.height;
  16207. };
  16208. this.onApply = function (effect) {
  16209. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16210. };
  16211. }
  16212. return FxaaPostProcess;
  16213. })(BABYLON.PostProcess);
  16214. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16215. })(BABYLON || (BABYLON = {}));
  16216. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  16217. var BABYLON;
  16218. (function (BABYLON) {
  16219. var LensFlare = (function () {
  16220. function LensFlare(size, position, color, imgUrl, system) {
  16221. this.size = size;
  16222. this.position = position;
  16223. this.dispose = function () {
  16224. if (this.texture) {
  16225. this.texture.dispose();
  16226. }
  16227. // Remove from scene
  16228. var index = this._system.lensFlares.indexOf(this);
  16229. this._system.lensFlares.splice(index, 1);
  16230. };
  16231. this.color = color || new BABYLON.Color3(1, 1, 1);
  16232. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16233. this._system = system;
  16234. system.lensFlares.push(this);
  16235. }
  16236. return LensFlare;
  16237. })();
  16238. BABYLON.LensFlare = LensFlare;
  16239. })(BABYLON || (BABYLON = {}));
  16240. //# sourceMappingURL=babylon.lensFlare.js.map
  16241. var BABYLON;
  16242. (function (BABYLON) {
  16243. var LensFlareSystem = (function () {
  16244. function LensFlareSystem(name, emitter, scene) {
  16245. this.name = name;
  16246. this.lensFlares = new Array();
  16247. this.borderLimit = 300;
  16248. this._vertexDeclaration = [2];
  16249. this._vertexStrideSize = 2 * 4;
  16250. this._isEnabled = true;
  16251. this._scene = scene;
  16252. this._emitter = emitter;
  16253. scene.lensFlareSystems.push(this);
  16254. this.meshesSelectionPredicate = function (m) {
  16255. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  16256. };
  16257. // VBO
  16258. var vertices = [];
  16259. vertices.push(1, 1);
  16260. vertices.push(-1, 1);
  16261. vertices.push(-1, -1);
  16262. vertices.push(1, -1);
  16263. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16264. // Indices
  16265. var indices = [];
  16266. indices.push(0);
  16267. indices.push(1);
  16268. indices.push(2);
  16269. indices.push(0);
  16270. indices.push(2);
  16271. indices.push(3);
  16272. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16273. // Effects
  16274. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16275. }
  16276. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16277. get: function () {
  16278. return this._isEnabled;
  16279. },
  16280. set: function (value) {
  16281. this._isEnabled = value;
  16282. },
  16283. enumerable: true,
  16284. configurable: true
  16285. });
  16286. LensFlareSystem.prototype.getScene = function () {
  16287. return this._scene;
  16288. };
  16289. LensFlareSystem.prototype.getEmitter = function () {
  16290. return this._emitter;
  16291. };
  16292. LensFlareSystem.prototype.getEmitterPosition = function () {
  16293. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16294. };
  16295. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16296. var position = this.getEmitterPosition();
  16297. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16298. this._positionX = position.x;
  16299. this._positionY = position.y;
  16300. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16301. if (position.z > 0) {
  16302. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16303. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16304. return true;
  16305. }
  16306. }
  16307. return false;
  16308. };
  16309. LensFlareSystem.prototype._isVisible = function () {
  16310. if (!this._isEnabled) {
  16311. return false;
  16312. }
  16313. var emitterPosition = this.getEmitterPosition();
  16314. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16315. var distance = direction.length();
  16316. direction.normalize();
  16317. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16318. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16319. return !pickInfo.hit || pickInfo.distance > distance;
  16320. };
  16321. LensFlareSystem.prototype.render = function () {
  16322. if (!this._effect.isReady())
  16323. return false;
  16324. var engine = this._scene.getEngine();
  16325. var viewport = this._scene.activeCamera.viewport;
  16326. var globalViewport = viewport.toGlobal(engine);
  16327. // Position
  16328. if (!this.computeEffectivePosition(globalViewport)) {
  16329. return false;
  16330. }
  16331. // Visibility
  16332. if (!this._isVisible()) {
  16333. return false;
  16334. }
  16335. // Intensity
  16336. var awayX;
  16337. var awayY;
  16338. if (this._positionX < this.borderLimit + globalViewport.x) {
  16339. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16340. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16341. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16342. } else {
  16343. awayX = 0;
  16344. }
  16345. if (this._positionY < this.borderLimit + globalViewport.y) {
  16346. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16347. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16348. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16349. } else {
  16350. awayY = 0;
  16351. }
  16352. var away = (awayX > awayY) ? awayX : awayY;
  16353. if (away > this.borderLimit) {
  16354. away = this.borderLimit;
  16355. }
  16356. var intensity = 1.0 - (away / this.borderLimit);
  16357. if (intensity < 0) {
  16358. return false;
  16359. }
  16360. if (intensity > 1.0) {
  16361. intensity = 1.0;
  16362. }
  16363. // Position
  16364. var centerX = globalViewport.x + globalViewport.width / 2;
  16365. var centerY = globalViewport.y + globalViewport.height / 2;
  16366. var distX = centerX - this._positionX;
  16367. var distY = centerY - this._positionY;
  16368. // Effects
  16369. engine.enableEffect(this._effect);
  16370. engine.setState(false);
  16371. engine.setDepthBuffer(false);
  16372. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16373. // VBOs
  16374. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16375. for (var index = 0; index < this.lensFlares.length; index++) {
  16376. var flare = this.lensFlares[index];
  16377. var x = centerX - (distX * flare.position);
  16378. var y = centerY - (distY * flare.position);
  16379. var cw = flare.size;
  16380. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16381. var cx = 2 * (x / globalViewport.width) - 1.0;
  16382. var cy = 1.0 - 2 * (y / globalViewport.height);
  16383. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16384. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16385. // Texture
  16386. this._effect.setTexture("textureSampler", flare.texture);
  16387. // Color
  16388. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16389. // Draw order
  16390. engine.draw(true, 0, 6);
  16391. }
  16392. engine.setDepthBuffer(true);
  16393. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16394. return true;
  16395. };
  16396. LensFlareSystem.prototype.dispose = function () {
  16397. if (this._vertexBuffer) {
  16398. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16399. this._vertexBuffer = null;
  16400. }
  16401. if (this._indexBuffer) {
  16402. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16403. this._indexBuffer = null;
  16404. }
  16405. while (this.lensFlares.length) {
  16406. this.lensFlares[0].dispose();
  16407. }
  16408. // Remove from scene
  16409. var index = this._scene.lensFlareSystems.indexOf(this);
  16410. this._scene.lensFlareSystems.splice(index, 1);
  16411. };
  16412. return LensFlareSystem;
  16413. })();
  16414. BABYLON.LensFlareSystem = LensFlareSystem;
  16415. })(BABYLON || (BABYLON = {}));
  16416. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  16417. var BABYLON;
  16418. (function (BABYLON) {
  16419. var IntersectionInfo = (function () {
  16420. function IntersectionInfo(bu, bv, distance) {
  16421. this.bu = bu;
  16422. this.bv = bv;
  16423. this.distance = distance;
  16424. this.faceId = 0;
  16425. }
  16426. return IntersectionInfo;
  16427. })();
  16428. BABYLON.IntersectionInfo = IntersectionInfo;
  16429. var PickingInfo = (function () {
  16430. function PickingInfo() {
  16431. this.hit = false;
  16432. this.distance = 0;
  16433. this.pickedPoint = null;
  16434. this.pickedMesh = null;
  16435. this.bu = 0;
  16436. this.bv = 0;
  16437. this.faceId = -1;
  16438. }
  16439. // Methods
  16440. PickingInfo.prototype.getNormal = function () {
  16441. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16442. return null;
  16443. }
  16444. var indices = this.pickedMesh.getIndices();
  16445. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16446. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16447. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16448. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16449. normal0 = normal0.scale(this.bu);
  16450. normal1 = normal1.scale(this.bv);
  16451. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16452. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16453. };
  16454. PickingInfo.prototype.getTextureCoordinates = function () {
  16455. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16456. return null;
  16457. }
  16458. var indices = this.pickedMesh.getIndices();
  16459. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16460. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16461. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16462. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16463. uv0 = uv0.scale(this.bu);
  16464. uv1 = uv1.scale(this.bv);
  16465. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16466. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16467. };
  16468. return PickingInfo;
  16469. })();
  16470. BABYLON.PickingInfo = PickingInfo;
  16471. })(BABYLON || (BABYLON = {}));
  16472. //# sourceMappingURL=babylon.pickingInfo.js.map
  16473. var BABYLON;
  16474. (function (BABYLON) {
  16475. var FilesInput = (function () {
  16476. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16477. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16478. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16479. this.engine = p_engine;
  16480. this.canvas = p_canvas;
  16481. this.currentScene = p_scene;
  16482. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16483. this.progressCallback = p_progressCallback;
  16484. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16485. this.textureLoadingCallback = p_textureLoadingCallback;
  16486. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16487. }
  16488. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16489. var _this = this;
  16490. if (p_elementToMonitor) {
  16491. this.elementToMonitor = p_elementToMonitor;
  16492. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16493. _this.drag(e);
  16494. }, false);
  16495. this.elementToMonitor.addEventListener("dragover", function (e) {
  16496. _this.drag(e);
  16497. }, false);
  16498. this.elementToMonitor.addEventListener("drop", function (e) {
  16499. _this.drop(e);
  16500. }, false);
  16501. }
  16502. };
  16503. FilesInput.prototype.renderFunction = function () {
  16504. if (this.additionnalRenderLoopLogicCallback) {
  16505. this.additionnalRenderLoopLogicCallback();
  16506. }
  16507. if (this.currentScene) {
  16508. if (this.textureLoadingCallback) {
  16509. var remaining = this.currentScene.getWaitingItemsCount();
  16510. if (remaining > 0) {
  16511. this.textureLoadingCallback(remaining);
  16512. }
  16513. }
  16514. this.currentScene.render();
  16515. }
  16516. };
  16517. FilesInput.prototype.drag = function (e) {
  16518. e.stopPropagation();
  16519. e.preventDefault();
  16520. };
  16521. FilesInput.prototype.drop = function (eventDrop) {
  16522. eventDrop.stopPropagation();
  16523. eventDrop.preventDefault();
  16524. this.loadFiles(eventDrop);
  16525. };
  16526. FilesInput.prototype.loadFiles = function (event) {
  16527. var _this = this;
  16528. var that = this;
  16529. if (this.startingProcessingFilesCallback)
  16530. this.startingProcessingFilesCallback();
  16531. var sceneFileToLoad;
  16532. var filesToLoad;
  16533. // Handling data transfer via drag'n'drop
  16534. if (event && event.dataTransfer && event.dataTransfer.files) {
  16535. filesToLoad = event.dataTransfer.files;
  16536. }
  16537. // Handling files from input files
  16538. if (event && event.target && event.target.files) {
  16539. filesToLoad = event.target.files;
  16540. }
  16541. if (filesToLoad && filesToLoad.length > 0) {
  16542. for (var i = 0; i < filesToLoad.length; i++) {
  16543. switch (filesToLoad[i].type) {
  16544. case "image/jpeg":
  16545. case "image/png":
  16546. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16547. break;
  16548. case "image/targa":
  16549. case "image/vnd.ms-dds":
  16550. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16551. break;
  16552. default:
  16553. 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) {
  16554. sceneFileToLoad = filesToLoad[i];
  16555. }
  16556. break;
  16557. }
  16558. }
  16559. // If a ".babylon" file has been provided
  16560. if (sceneFileToLoad) {
  16561. if (this.currentScene) {
  16562. this.engine.stopRenderLoop();
  16563. this.currentScene.dispose();
  16564. }
  16565. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16566. that.currentScene = newScene;
  16567. // Wait for textures and shaders to be ready
  16568. that.currentScene.executeWhenReady(function () {
  16569. // Attach camera to canvas inputs
  16570. if (that.currentScene.activeCamera) {
  16571. that.currentScene.activeCamera.attachControl(that.canvas);
  16572. }
  16573. if (that.sceneLoadedCallback) {
  16574. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16575. }
  16576. that.engine.runRenderLoop(function () {
  16577. that.renderFunction();
  16578. });
  16579. });
  16580. }, function (progress) {
  16581. if (_this.progressCallback) {
  16582. _this.progressCallback(progress);
  16583. }
  16584. });
  16585. } else {
  16586. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16587. }
  16588. }
  16589. };
  16590. FilesInput.FilesTextures = new Array();
  16591. FilesInput.FilesToLoad = new Array();
  16592. return FilesInput;
  16593. })();
  16594. BABYLON.FilesInput = FilesInput;
  16595. })(BABYLON || (BABYLON = {}));
  16596. //# sourceMappingURL=babylon.filesInput.js.map
  16597. var BABYLON;
  16598. (function (BABYLON) {
  16599. var OimoJSPlugin = (function () {
  16600. function OimoJSPlugin() {
  16601. this._registeredMeshes = [];
  16602. /**
  16603. * Update the body position according to the mesh position
  16604. * @param mesh
  16605. */
  16606. this.updateBodyPosition = function (mesh) {
  16607. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16608. var registeredMesh = this._registeredMeshes[index];
  16609. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16610. var body = registeredMesh.body.body;
  16611. mesh.computeWorldMatrix(true);
  16612. var center = mesh.getBoundingInfo().boundingBox.center;
  16613. body.setPosition(center.x, center.y, center.z);
  16614. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16615. return;
  16616. }
  16617. // Case where the parent has been updated
  16618. if (registeredMesh.mesh.parent === mesh) {
  16619. mesh.computeWorldMatrix(true);
  16620. registeredMesh.mesh.computeWorldMatrix(true);
  16621. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16622. var absoluteRotation = mesh.rotation;
  16623. body = registeredMesh.body.body;
  16624. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16625. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16626. return;
  16627. }
  16628. }
  16629. };
  16630. }
  16631. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16632. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16633. };
  16634. OimoJSPlugin.prototype.initialize = function (iterations) {
  16635. this._world = new OIMO.World();
  16636. this._world.clear();
  16637. };
  16638. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16639. this._world.gravity = gravity;
  16640. };
  16641. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16642. var body = null;
  16643. this.unregisterMesh(mesh);
  16644. mesh.computeWorldMatrix(true);
  16645. switch (impostor) {
  16646. case BABYLON.PhysicsEngine.SphereImpostor:
  16647. var initialRotation = null;
  16648. if (mesh.rotationQuaternion) {
  16649. initialRotation = mesh.rotationQuaternion.clone();
  16650. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16651. mesh.computeWorldMatrix(true);
  16652. }
  16653. var bbox = mesh.getBoundingInfo().boundingBox;
  16654. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16655. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16656. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16657. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16658. // The delta between the mesh position and the mesh bounding box center
  16659. var deltaPosition = mesh.position.subtract(bbox.center);
  16660. // Transform delta position with the rotation
  16661. if (initialRotation) {
  16662. var m = new BABYLON.Matrix();
  16663. initialRotation.toRotationMatrix(m);
  16664. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16665. }
  16666. body = new OIMO.Body({
  16667. type: 'sphere',
  16668. size: [size],
  16669. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16670. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16671. move: options.mass != 0,
  16672. config: [options.mass, options.friction, options.restitution],
  16673. world: this._world
  16674. });
  16675. // Restore rotation
  16676. if (initialRotation) {
  16677. body.setQuaternion(initialRotation);
  16678. }
  16679. this._registeredMeshes.push({
  16680. mesh: mesh,
  16681. body: body,
  16682. delta: deltaPosition
  16683. });
  16684. break;
  16685. case BABYLON.PhysicsEngine.PlaneImpostor:
  16686. case BABYLON.PhysicsEngine.BoxImpostor:
  16687. initialRotation = null;
  16688. if (mesh.rotationQuaternion) {
  16689. initialRotation = mesh.rotationQuaternion.clone();
  16690. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16691. mesh.computeWorldMatrix(true);
  16692. }
  16693. bbox = mesh.getBoundingInfo().boundingBox;
  16694. var min = bbox.minimumWorld;
  16695. var max = bbox.maximumWorld;
  16696. var box = max.subtract(min);
  16697. var sizeX = this._checkWithEpsilon(box.x);
  16698. var sizeY = this._checkWithEpsilon(box.y);
  16699. var sizeZ = this._checkWithEpsilon(box.z);
  16700. // The delta between the mesh position and the mesh boudning box center
  16701. deltaPosition = mesh.position.subtract(bbox.center);
  16702. // Transform delta position with the rotation
  16703. if (initialRotation) {
  16704. m = new BABYLON.Matrix();
  16705. initialRotation.toRotationMatrix(m);
  16706. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16707. }
  16708. body = new OIMO.Body({
  16709. type: 'box',
  16710. size: [sizeX, sizeY, sizeZ],
  16711. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16712. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16713. move: options.mass != 0,
  16714. config: [options.mass, options.friction, options.restitution],
  16715. world: this._world
  16716. });
  16717. if (initialRotation) {
  16718. body.setQuaternion(initialRotation);
  16719. }
  16720. this._registeredMeshes.push({
  16721. mesh: mesh,
  16722. body: body,
  16723. delta: deltaPosition
  16724. });
  16725. break;
  16726. }
  16727. return body;
  16728. };
  16729. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16730. var types = [], sizes = [], positions = [], rotations = [];
  16731. var initialMesh = parts[0].mesh;
  16732. for (var index = 0; index < parts.length; index++) {
  16733. var part = parts[index];
  16734. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16735. types.push(bodyParameters.type);
  16736. sizes.push.apply(sizes, bodyParameters.size);
  16737. positions.push.apply(positions, bodyParameters.pos);
  16738. rotations.push.apply(rotations, bodyParameters.rot);
  16739. }
  16740. var body = new OIMO.Body({
  16741. type: types,
  16742. size: sizes,
  16743. pos: positions,
  16744. rot: rotations,
  16745. move: options.mass != 0,
  16746. config: [options.mass, options.friction, options.restitution],
  16747. world: this._world
  16748. });
  16749. this._registeredMeshes.push({
  16750. mesh: initialMesh,
  16751. body: body
  16752. });
  16753. return body;
  16754. };
  16755. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16756. var bodyParameters = null;
  16757. var mesh = part.mesh;
  16758. switch (part.impostor) {
  16759. case BABYLON.PhysicsEngine.SphereImpostor:
  16760. var bbox = mesh.getBoundingInfo().boundingBox;
  16761. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16762. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16763. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16764. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16765. bodyParameters = {
  16766. type: 'sphere',
  16767. /* bug with oimo : sphere needs 3 sizes in this case */
  16768. size: [size, -1, -1],
  16769. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16770. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16771. };
  16772. break;
  16773. case BABYLON.PhysicsEngine.PlaneImpostor:
  16774. case BABYLON.PhysicsEngine.BoxImpostor:
  16775. bbox = mesh.getBoundingInfo().boundingBox;
  16776. var min = bbox.minimumWorld;
  16777. var max = bbox.maximumWorld;
  16778. var box = max.subtract(min);
  16779. var sizeX = this._checkWithEpsilon(box.x);
  16780. var sizeY = this._checkWithEpsilon(box.y);
  16781. var sizeZ = this._checkWithEpsilon(box.z);
  16782. var relativePosition = mesh.position;
  16783. bodyParameters = {
  16784. type: 'box',
  16785. size: [sizeX, sizeY, sizeZ],
  16786. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16787. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16788. };
  16789. break;
  16790. }
  16791. return bodyParameters;
  16792. };
  16793. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16794. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16795. var registeredMesh = this._registeredMeshes[index];
  16796. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16797. if (registeredMesh.body) {
  16798. this._world.removeRigidBody(registeredMesh.body.body);
  16799. this._unbindBody(registeredMesh.body);
  16800. }
  16801. this._registeredMeshes.splice(index, 1);
  16802. return;
  16803. }
  16804. }
  16805. };
  16806. OimoJSPlugin.prototype._unbindBody = function (body) {
  16807. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16808. var registeredMesh = this._registeredMeshes[index];
  16809. if (registeredMesh.body === body) {
  16810. registeredMesh.body = null;
  16811. }
  16812. }
  16813. };
  16814. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16815. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16816. var registeredMesh = this._registeredMeshes[index];
  16817. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16818. // Get object mass to have a behaviour similar to cannon.js
  16819. var mass = registeredMesh.body.body.massInfo.mass;
  16820. // The force is scaled with the mass of object
  16821. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16822. return;
  16823. }
  16824. }
  16825. };
  16826. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16827. var body1 = null, body2 = null;
  16828. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16829. var registeredMesh = this._registeredMeshes[index];
  16830. if (registeredMesh.mesh === mesh1) {
  16831. body1 = registeredMesh.body.body;
  16832. } else if (registeredMesh.mesh === mesh2) {
  16833. body2 = registeredMesh.body.body;
  16834. }
  16835. }
  16836. if (!body1 || !body2) {
  16837. return false;
  16838. }
  16839. if (!options) {
  16840. options = {};
  16841. }
  16842. new OIMO.Link({
  16843. type: options.type,
  16844. body1: body1,
  16845. body2: body2,
  16846. min: options.min,
  16847. max: options.max,
  16848. axe1: options.axe1,
  16849. axe2: options.axe2,
  16850. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16851. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16852. collision: options.collision,
  16853. spring: options.spring,
  16854. world: this._world
  16855. });
  16856. return true;
  16857. };
  16858. OimoJSPlugin.prototype.dispose = function () {
  16859. this._world.clear();
  16860. while (this._registeredMeshes.length) {
  16861. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16862. }
  16863. };
  16864. OimoJSPlugin.prototype.isSupported = function () {
  16865. return OIMO !== undefined;
  16866. };
  16867. OimoJSPlugin.prototype._getLastShape = function (body) {
  16868. var lastShape = body.shapes;
  16869. while (lastShape.next) {
  16870. lastShape = lastShape.next;
  16871. }
  16872. return lastShape;
  16873. };
  16874. OimoJSPlugin.prototype.runOneStep = function (time) {
  16875. this._world.step();
  16876. // Update the position of all registered meshes
  16877. var i = this._registeredMeshes.length;
  16878. var m;
  16879. while (i--) {
  16880. var body = this._registeredMeshes[i].body.body;
  16881. var mesh = this._registeredMeshes[i].mesh;
  16882. var delta = this._registeredMeshes[i].delta;
  16883. if (!body.sleeping) {
  16884. if (body.shapes.next) {
  16885. var parentShape = this._getLastShape(body);
  16886. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16887. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16888. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16889. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16890. if (!mesh.rotationQuaternion) {
  16891. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16892. }
  16893. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16894. mesh.computeWorldMatrix();
  16895. } else {
  16896. m = body.getMatrix();
  16897. mtx = BABYLON.Matrix.FromArray(m);
  16898. // Body position
  16899. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16900. if (!delta) {
  16901. mesh.position.x = bodyX;
  16902. mesh.position.y = bodyY;
  16903. mesh.position.z = bodyZ;
  16904. } else {
  16905. mesh.position.x = bodyX + delta.x;
  16906. mesh.position.y = bodyY + delta.y;
  16907. mesh.position.z = bodyZ + delta.z;
  16908. }
  16909. if (!mesh.rotationQuaternion) {
  16910. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16911. }
  16912. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16913. mesh.computeWorldMatrix();
  16914. }
  16915. }
  16916. }
  16917. };
  16918. return OimoJSPlugin;
  16919. })();
  16920. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16921. })(BABYLON || (BABYLON = {}));
  16922. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16923. var BABYLON;
  16924. (function (BABYLON) {
  16925. var PhysicsEngine = (function () {
  16926. function PhysicsEngine(plugin) {
  16927. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16928. }
  16929. PhysicsEngine.prototype._initialize = function (gravity) {
  16930. this._currentPlugin.initialize();
  16931. this._setGravity(gravity);
  16932. };
  16933. PhysicsEngine.prototype._runOneStep = function (delta) {
  16934. if (delta > 0.1) {
  16935. delta = 0.1;
  16936. } else if (delta <= 0) {
  16937. delta = 1.0 / 60.0;
  16938. }
  16939. this._currentPlugin.runOneStep(delta);
  16940. };
  16941. PhysicsEngine.prototype._setGravity = function (gravity) {
  16942. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16943. this._currentPlugin.setGravity(this.gravity);
  16944. };
  16945. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16946. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16947. };
  16948. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16949. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16950. };
  16951. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16952. this._currentPlugin.unregisterMesh(mesh);
  16953. };
  16954. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16955. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16956. };
  16957. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16958. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16959. };
  16960. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16961. this._currentPlugin.updateBodyPosition(mesh);
  16962. };
  16963. PhysicsEngine.prototype.dispose = function () {
  16964. this._currentPlugin.dispose();
  16965. };
  16966. PhysicsEngine.prototype.isSupported = function () {
  16967. return this._currentPlugin.isSupported();
  16968. };
  16969. PhysicsEngine.NoImpostor = 0;
  16970. PhysicsEngine.SphereImpostor = 1;
  16971. PhysicsEngine.BoxImpostor = 2;
  16972. PhysicsEngine.PlaneImpostor = 3;
  16973. PhysicsEngine.MeshImpostor = 4;
  16974. PhysicsEngine.CapsuleImpostor = 5;
  16975. PhysicsEngine.ConeImpostor = 6;
  16976. PhysicsEngine.CylinderImpostor = 7;
  16977. PhysicsEngine.ConvexHullImpostor = 8;
  16978. PhysicsEngine.Epsilon = 0.001;
  16979. return PhysicsEngine;
  16980. })();
  16981. BABYLON.PhysicsEngine = PhysicsEngine;
  16982. })(BABYLON || (BABYLON = {}));
  16983. //# sourceMappingURL=babylon.physicsEngine.js.map
  16984. var BABYLON;
  16985. (function (BABYLON) {
  16986. var serializeLight = function (light) {
  16987. var serializationObject = {};
  16988. serializationObject.name = light.name;
  16989. serializationObject.id = light.id;
  16990. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16991. if (light instanceof BABYLON.PointLight) {
  16992. serializationObject.type = 0;
  16993. serializationObject.position = light.position.asArray();
  16994. } else if (light instanceof BABYLON.DirectionalLight) {
  16995. serializationObject.type = 1;
  16996. var directionalLight = light;
  16997. serializationObject.position = directionalLight.position.asArray();
  16998. serializationObject.direction = directionalLight.direction.asArray();
  16999. } else if (light instanceof BABYLON.SpotLight) {
  17000. serializationObject.type = 2;
  17001. var spotLight = light;
  17002. serializationObject.position = spotLight.position.asArray();
  17003. serializationObject.direction = spotLight.position.asArray();
  17004. serializationObject.angle = spotLight.angle;
  17005. serializationObject.exponent = spotLight.exponent;
  17006. } else if (light instanceof BABYLON.HemisphericLight) {
  17007. serializationObject.type = 3;
  17008. var hemisphericLight = light;
  17009. serializationObject.direction = hemisphericLight.direction.asArray();
  17010. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17011. }
  17012. if (light.intensity) {
  17013. serializationObject.intensity = light.intensity;
  17014. }
  17015. serializationObject.range = light.range;
  17016. serializationObject.diffuse = light.diffuse.asArray();
  17017. serializationObject.specular = light.specular.asArray();
  17018. return serializationObject;
  17019. };
  17020. var serializeFresnelParameter = function (fresnelParameter) {
  17021. var serializationObject = {};
  17022. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17023. serializationObject.leftColor = fresnelParameter.leftColor;
  17024. serializationObject.rightColor = fresnelParameter.rightColor;
  17025. serializationObject.bias = fresnelParameter.bias;
  17026. serializationObject.power = fresnelParameter.power;
  17027. return serializationObject;
  17028. };
  17029. var serializeCamera = function (camera) {
  17030. var serializationObject = {};
  17031. serializationObject.name = camera.name;
  17032. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17033. serializationObject.id = camera.id;
  17034. serializationObject.position = camera.position.asArray();
  17035. // Parent
  17036. if (camera.parent) {
  17037. serializationObject.parentId = camera.parent.id;
  17038. }
  17039. // Target
  17040. serializationObject.rotation = camera.rotation.asArray();
  17041. // Locked target
  17042. if (camera.lockedTarget && camera.lockedTarget.id) {
  17043. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17044. }
  17045. serializationObject.fov = camera.fov;
  17046. serializationObject.minZ = camera.minZ;
  17047. serializationObject.maxZ = camera.maxZ;
  17048. serializationObject.speed = camera.speed;
  17049. serializationObject.inertia = camera.inertia;
  17050. serializationObject.checkCollisions = camera.checkCollisions;
  17051. serializationObject.applyGravity = camera.applyGravity;
  17052. if (camera.ellipsoid) {
  17053. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17054. }
  17055. // Animations
  17056. appendAnimations(camera, serializationObject);
  17057. // Layer mask
  17058. serializationObject.layerMask = camera.layerMask;
  17059. return serializationObject;
  17060. };
  17061. var appendAnimations = function (source, destination) {
  17062. if (source.animations) {
  17063. destination.animations = [];
  17064. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17065. var animation = source.animations[animationIndex];
  17066. destination.animations.push(serializeAnimation(animation));
  17067. }
  17068. }
  17069. };
  17070. var serializeAnimation = function (animation) {
  17071. var serializationObject = {};
  17072. serializationObject.name = animation.name;
  17073. serializationObject.property = animation.targetProperty;
  17074. serializationObject.framePerSecond = animation.framePerSecond;
  17075. serializationObject.dataType = animation.dataType;
  17076. serializationObject.loopBehavior = animation.loopMode;
  17077. var dataType = animation.dataType;
  17078. serializationObject.keys = [];
  17079. var keys = animation.getKeys();
  17080. for (var index = 0; index < keys.length; index++) {
  17081. var animationKey = keys[index];
  17082. var key = {};
  17083. key.frame = animationKey.frame;
  17084. switch (dataType) {
  17085. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17086. key.values = [animationKey.value];
  17087. break;
  17088. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17089. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17090. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17091. key.values = animationKey.value.asArray();
  17092. break;
  17093. }
  17094. serializationObject.keys.push(key);
  17095. }
  17096. return serializationObject;
  17097. };
  17098. var serializeMultiMaterial = function (material) {
  17099. var serializationObject = {};
  17100. serializationObject.name = material.name;
  17101. serializationObject.id = material.id;
  17102. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17103. serializationObject.materials = [];
  17104. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17105. var subMat = material.subMaterials[matIndex];
  17106. if (subMat) {
  17107. serializationObject.materials.push(subMat.id);
  17108. } else {
  17109. serializationObject.materials.push(null);
  17110. }
  17111. }
  17112. return serializationObject;
  17113. };
  17114. var serializeMaterial = function (material) {
  17115. var serializationObject = {};
  17116. serializationObject.name = material.name;
  17117. serializationObject.ambient = material.ambientColor.asArray();
  17118. serializationObject.diffuse = material.diffuseColor.asArray();
  17119. serializationObject.specular = material.specularColor.asArray();
  17120. serializationObject.specularPower = material.specularPower;
  17121. serializationObject.emissive = material.emissiveColor.asArray();
  17122. serializationObject.alpha = material.alpha;
  17123. serializationObject.id = material.id;
  17124. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17125. serializationObject.backFaceCulling = material.backFaceCulling;
  17126. if (material.diffuseTexture) {
  17127. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17128. }
  17129. if (material.diffuseFresnelParameters) {
  17130. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17131. }
  17132. if (material.ambientTexture) {
  17133. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17134. }
  17135. if (material.opacityTexture) {
  17136. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17137. }
  17138. if (material.opacityFresnelParameters) {
  17139. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17140. }
  17141. if (material.reflectionTexture) {
  17142. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17143. }
  17144. if (material.reflectionFresnelParameters) {
  17145. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17146. }
  17147. if (material.emissiveTexture) {
  17148. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17149. }
  17150. if (material.emissiveFresnelParameters) {
  17151. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17152. }
  17153. if (material.specularTexture) {
  17154. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17155. }
  17156. if (material.bumpTexture) {
  17157. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17158. }
  17159. return serializationObject;
  17160. };
  17161. var serializeTexture = function (texture) {
  17162. var serializationObject = {};
  17163. if (!texture.name) {
  17164. return null;
  17165. }
  17166. if (texture instanceof BABYLON.CubeTexture) {
  17167. serializationObject.name = texture.name;
  17168. serializationObject.hasAlpha = texture.hasAlpha;
  17169. serializationObject.level = texture.level;
  17170. serializationObject.coordinatesMode = texture.coordinatesMode;
  17171. return serializationObject;
  17172. }
  17173. if (texture instanceof BABYLON.MirrorTexture) {
  17174. var mirrorTexture = texture;
  17175. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17176. serializationObject.renderList = [];
  17177. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17178. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17179. }
  17180. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17181. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  17182. var renderTargetTexture = texture;
  17183. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17184. serializationObject.renderList = [];
  17185. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17186. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17187. }
  17188. }
  17189. var regularTexture = texture;
  17190. serializationObject.name = texture.name;
  17191. serializationObject.hasAlpha = texture.hasAlpha;
  17192. serializationObject.level = texture.level;
  17193. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17194. serializationObject.coordinatesMode = texture.coordinatesMode;
  17195. serializationObject.uOffset = regularTexture.uOffset;
  17196. serializationObject.vOffset = regularTexture.vOffset;
  17197. serializationObject.uScale = regularTexture.uScale;
  17198. serializationObject.vScale = regularTexture.vScale;
  17199. serializationObject.uAng = regularTexture.uAng;
  17200. serializationObject.vAng = regularTexture.vAng;
  17201. serializationObject.wAng = regularTexture.wAng;
  17202. serializationObject.wrapU = texture.wrapU;
  17203. serializationObject.wrapV = texture.wrapV;
  17204. // Animations
  17205. appendAnimations(texture, serializationObject);
  17206. return serializationObject;
  17207. };
  17208. var serializeSkeleton = function (skeleton) {
  17209. var serializationObject = {};
  17210. serializationObject.name = skeleton.name;
  17211. serializationObject.id = skeleton.id;
  17212. serializationObject.bones = [];
  17213. for (var index = 0; index < skeleton.bones.length; index++) {
  17214. var bone = skeleton.bones[index];
  17215. var serializedBone = {
  17216. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17217. name: bone.name,
  17218. matrix: bone.getLocalMatrix().toArray()
  17219. };
  17220. serializationObject.bones.push(serializedBone);
  17221. if (bone.animations && bone.animations.length > 0) {
  17222. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17223. }
  17224. }
  17225. return serializationObject;
  17226. };
  17227. var serializeParticleSystem = function (particleSystem) {
  17228. var serializationObject = {};
  17229. serializationObject.emitterId = particleSystem.emitter.id;
  17230. serializationObject.capacity = particleSystem.getCapacity();
  17231. if (particleSystem.particleTexture) {
  17232. serializationObject.textureName = particleSystem.particleTexture.name;
  17233. }
  17234. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17235. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17236. serializationObject.minSize = particleSystem.minSize;
  17237. serializationObject.maxSize = particleSystem.maxSize;
  17238. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17239. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17240. serializationObject.emitRate = particleSystem.emitRate;
  17241. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17242. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17243. serializationObject.gravity = particleSystem.gravity.asArray();
  17244. serializationObject.direction1 = particleSystem.direction1.asArray();
  17245. serializationObject.direction2 = particleSystem.direction2.asArray();
  17246. serializationObject.color1 = particleSystem.color1.asArray();
  17247. serializationObject.color2 = particleSystem.color2.asArray();
  17248. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17249. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17250. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17251. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17252. serializationObject.blendMode = particleSystem.blendMode;
  17253. return serializationObject;
  17254. };
  17255. var serializeLensFlareSystem = function (lensFlareSystem) {
  17256. var serializationObject = {};
  17257. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17258. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17259. serializationObject.flares = [];
  17260. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17261. var flare = lensFlareSystem.lensFlares[index];
  17262. serializationObject.flares.push({
  17263. size: flare.size,
  17264. position: flare.position,
  17265. color: flare.color.asArray(),
  17266. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17267. });
  17268. }
  17269. return serializationObject;
  17270. };
  17271. var serializeShadowGenerator = function (light) {
  17272. var serializationObject = {};
  17273. var shadowGenerator = light.getShadowGenerator();
  17274. serializationObject.lightId = light.id;
  17275. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17276. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17277. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17278. serializationObject.renderList = [];
  17279. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17280. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17281. serializationObject.renderList.push(mesh.id);
  17282. }
  17283. return serializationObject;
  17284. };
  17285. var serializedGeometries = [];
  17286. var serializeGeometry = function (geometry, serializationGeometries) {
  17287. if (serializedGeometries[geometry.id]) {
  17288. return;
  17289. }
  17290. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17291. serializationGeometries.boxes.push(serializeBox(geometry));
  17292. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17293. serializationGeometries.spheres.push(serializeSphere(geometry));
  17294. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17295. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17296. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17297. serializationGeometries.toruses.push(serializeTorus(geometry));
  17298. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17299. serializationGeometries.grounds.push(serializeGround(geometry));
  17300. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17301. serializationGeometries.planes.push(serializePlane(geometry));
  17302. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17303. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17304. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17305. throw new Error("Unknow primitive type");
  17306. } else {
  17307. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17308. }
  17309. serializedGeometries[geometry.id] = true;
  17310. };
  17311. var serializeGeometryBase = function (geometry) {
  17312. var serializationObject = {};
  17313. serializationObject.id = geometry.id;
  17314. if (BABYLON.Tags.HasTags(geometry)) {
  17315. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17316. }
  17317. return serializationObject;
  17318. };
  17319. var serializeVertexData = function (vertexData) {
  17320. var serializationObject = serializeGeometryBase(vertexData);
  17321. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17322. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17323. }
  17324. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17325. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17326. }
  17327. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17328. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17329. }
  17330. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17331. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17332. }
  17333. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17334. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17335. }
  17336. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17337. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17338. serializationObject.matricesIndices._isExpanded = true;
  17339. }
  17340. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17341. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17342. }
  17343. serializationObject.indices = vertexData.getIndices();
  17344. return serializationObject;
  17345. };
  17346. var serializePrimitive = function (primitive) {
  17347. var serializationObject = serializeGeometryBase(primitive);
  17348. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17349. return serializationObject;
  17350. };
  17351. var serializeBox = function (box) {
  17352. var serializationObject = serializePrimitive(box);
  17353. serializationObject.size = box.size;
  17354. return serializationObject;
  17355. };
  17356. var serializeSphere = function (sphere) {
  17357. var serializationObject = serializePrimitive(sphere);
  17358. serializationObject.segments = sphere.segments;
  17359. serializationObject.diameter = sphere.diameter;
  17360. return serializationObject;
  17361. };
  17362. var serializeCylinder = function (cylinder) {
  17363. var serializationObject = serializePrimitive(cylinder);
  17364. serializationObject.height = cylinder.height;
  17365. serializationObject.diameterTop = cylinder.diameterTop;
  17366. serializationObject.diameterBottom = cylinder.diameterBottom;
  17367. serializationObject.tessellation = cylinder.tessellation;
  17368. return serializationObject;
  17369. };
  17370. var serializeTorus = function (torus) {
  17371. var serializationObject = serializePrimitive(torus);
  17372. serializationObject.diameter = torus.diameter;
  17373. serializationObject.thickness = torus.thickness;
  17374. serializationObject.tessellation = torus.tessellation;
  17375. return serializationObject;
  17376. };
  17377. var serializeGround = function (ground) {
  17378. var serializationObject = serializePrimitive(ground);
  17379. serializationObject.width = ground.width;
  17380. serializationObject.height = ground.height;
  17381. serializationObject.subdivisions = ground.subdivisions;
  17382. return serializationObject;
  17383. };
  17384. var serializePlane = function (plane) {
  17385. var serializationObject = serializePrimitive(plane);
  17386. serializationObject.size = plane.size;
  17387. return serializationObject;
  17388. };
  17389. var serializeTorusKnot = function (torusKnot) {
  17390. var serializationObject = serializePrimitive(torusKnot);
  17391. serializationObject.radius = torusKnot.radius;
  17392. serializationObject.tube = torusKnot.tube;
  17393. serializationObject.radialSegments = torusKnot.radialSegments;
  17394. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17395. serializationObject.p = torusKnot.p;
  17396. serializationObject.q = torusKnot.q;
  17397. return serializationObject;
  17398. };
  17399. var serializeMesh = function (mesh, serializationScene) {
  17400. var serializationObject = {};
  17401. serializationObject.name = mesh.name;
  17402. serializationObject.id = mesh.id;
  17403. if (BABYLON.Tags.HasTags(mesh)) {
  17404. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17405. }
  17406. serializationObject.position = mesh.position.asArray();
  17407. if (mesh.rotationQuaternion) {
  17408. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17409. } else if (mesh.rotation) {
  17410. serializationObject.rotation = mesh.rotation.asArray();
  17411. }
  17412. serializationObject.scaling = mesh.scaling.asArray();
  17413. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17414. serializationObject.isEnabled = mesh.isEnabled();
  17415. serializationObject.isVisible = mesh.isVisible;
  17416. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17417. serializationObject.pickable = mesh.isPickable;
  17418. serializationObject.receiveShadows = mesh.receiveShadows;
  17419. serializationObject.billboardMode = mesh.billboardMode;
  17420. serializationObject.visibility = mesh.visibility;
  17421. serializationObject.checkCollisions = mesh.checkCollisions;
  17422. // Parent
  17423. if (mesh.parent) {
  17424. serializationObject.parentId = mesh.parent.id;
  17425. }
  17426. // Geometry
  17427. var geometry = mesh._geometry;
  17428. if (geometry) {
  17429. var geometryId = geometry.id;
  17430. serializationObject.geometryId = geometryId;
  17431. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17432. // 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
  17433. serializeGeometry(geometry, serializationScene.geometries);
  17434. }
  17435. // SubMeshes
  17436. serializationObject.subMeshes = [];
  17437. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17438. var subMesh = mesh.subMeshes[subIndex];
  17439. serializationObject.subMeshes.push({
  17440. materialIndex: subMesh.materialIndex,
  17441. verticesStart: subMesh.verticesStart,
  17442. verticesCount: subMesh.verticesCount,
  17443. indexStart: subMesh.indexStart,
  17444. indexCount: subMesh.indexCount
  17445. });
  17446. }
  17447. }
  17448. // Material
  17449. if (mesh.material) {
  17450. serializationObject.materialId = mesh.material.id;
  17451. } else {
  17452. mesh.material = null;
  17453. }
  17454. // Skeleton
  17455. if (mesh.skeleton) {
  17456. serializationObject.skeletonId = mesh.skeleton.id;
  17457. }
  17458. // Physics
  17459. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17460. serializationObject.physicsMass = mesh.getPhysicsMass();
  17461. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17462. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17463. switch (mesh.getPhysicsImpostor()) {
  17464. case BABYLON.PhysicsEngine.BoxImpostor:
  17465. serializationObject.physicsImpostor = 1;
  17466. break;
  17467. case BABYLON.PhysicsEngine.SphereImpostor:
  17468. serializationObject.physicsImpostor = 2;
  17469. break;
  17470. }
  17471. }
  17472. // Instances
  17473. serializationObject.instances = [];
  17474. for (var index = 0; index < mesh.instances.length; index++) {
  17475. var instance = mesh.instances[index];
  17476. var serializationInstance = {
  17477. name: instance.name,
  17478. position: instance.position,
  17479. rotation: instance.rotation,
  17480. rotationQuaternion: instance.rotationQuaternion,
  17481. scaling: instance.scaling
  17482. };
  17483. serializationObject.instances.push(serializationInstance);
  17484. // Animations
  17485. appendAnimations(instance, serializationInstance);
  17486. }
  17487. // Animations
  17488. appendAnimations(mesh, serializationObject);
  17489. // Layer mask
  17490. serializationObject.layerMask = mesh.layerMask;
  17491. return serializationObject;
  17492. };
  17493. var SceneSerializer = (function () {
  17494. function SceneSerializer() {
  17495. }
  17496. SceneSerializer.Serialize = function (scene) {
  17497. var serializationObject = {};
  17498. // Scene
  17499. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17500. serializationObject.autoClear = scene.autoClear;
  17501. serializationObject.clearColor = scene.clearColor.asArray();
  17502. serializationObject.ambientColor = scene.ambientColor.asArray();
  17503. serializationObject.gravity = scene.gravity.asArray();
  17504. // Fog
  17505. if (scene.fogMode && scene.fogMode !== 0) {
  17506. serializationObject.fogMode = scene.fogMode;
  17507. serializationObject.fogColor = scene.fogColor.asArray();
  17508. serializationObject.fogStart = scene.fogStart;
  17509. serializationObject.fogEnd = scene.fogEnd;
  17510. serializationObject.fogDensity = scene.fogDensity;
  17511. }
  17512. // Lights
  17513. serializationObject.lights = [];
  17514. for (var index = 0; index < scene.lights.length; index++) {
  17515. var light = scene.lights[index];
  17516. serializationObject.lights.push(serializeLight(light));
  17517. }
  17518. // Cameras
  17519. serializationObject.cameras = [];
  17520. for (index = 0; index < scene.cameras.length; index++) {
  17521. var camera = scene.cameras[index];
  17522. if (camera instanceof BABYLON.FreeCamera) {
  17523. serializationObject.cameras.push(serializeCamera(camera));
  17524. }
  17525. }
  17526. if (scene.activeCamera) {
  17527. serializationObject.activeCameraID = scene.activeCamera.id;
  17528. }
  17529. // Materials
  17530. serializationObject.materials = [];
  17531. serializationObject.multiMaterials = [];
  17532. for (index = 0; index < scene.materials.length; index++) {
  17533. var material = scene.materials[index];
  17534. if (material instanceof BABYLON.StandardMaterial) {
  17535. serializationObject.materials.push(serializeMaterial(material));
  17536. } else if (material instanceof BABYLON.MultiMaterial) {
  17537. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17538. }
  17539. }
  17540. // Skeletons
  17541. serializationObject.skeletons = [];
  17542. for (index = 0; index < scene.skeletons.length; index++) {
  17543. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17544. }
  17545. // Geometries
  17546. serializationObject.geometries = {};
  17547. serializationObject.geometries.boxes = [];
  17548. serializationObject.geometries.spheres = [];
  17549. serializationObject.geometries.cylinders = [];
  17550. serializationObject.geometries.toruses = [];
  17551. serializationObject.geometries.grounds = [];
  17552. serializationObject.geometries.planes = [];
  17553. serializationObject.geometries.torusKnots = [];
  17554. serializationObject.geometries.vertexData = [];
  17555. serializedGeometries = [];
  17556. var geometries = scene.getGeometries();
  17557. for (var index = 0; index < geometries.length; index++) {
  17558. var geometry = geometries[index];
  17559. if (geometry.isReady()) {
  17560. serializeGeometry(geometry, serializationObject.geometries);
  17561. }
  17562. }
  17563. // Meshes
  17564. serializationObject.meshes = [];
  17565. for (index = 0; index < scene.meshes.length; index++) {
  17566. var abstractMesh = scene.meshes[index];
  17567. if (abstractMesh instanceof BABYLON.Mesh) {
  17568. var mesh = abstractMesh;
  17569. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17570. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17571. }
  17572. }
  17573. }
  17574. // Particles Systems
  17575. serializationObject.particleSystems = [];
  17576. for (index = 0; index < scene.particleSystems.length; index++) {
  17577. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17578. }
  17579. // Lens flares
  17580. serializationObject.lensFlareSystems = [];
  17581. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17582. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17583. }
  17584. // Shadows
  17585. serializationObject.shadowGenerators = [];
  17586. for (index = 0; index < scene.lights.length; index++) {
  17587. light = scene.lights[index];
  17588. if (light.getShadowGenerator()) {
  17589. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17590. }
  17591. }
  17592. return serializationObject;
  17593. };
  17594. return SceneSerializer;
  17595. })();
  17596. BABYLON.SceneSerializer = SceneSerializer;
  17597. })(BABYLON || (BABYLON = {}));
  17598. //# sourceMappingURL=babylon.sceneSerializer.js.map
  17599. var BABYLON;
  17600. (function (BABYLON) {
  17601. var SceneLoader = (function () {
  17602. function SceneLoader() {
  17603. }
  17604. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17605. get: function () {
  17606. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17607. },
  17608. set: function (value) {
  17609. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17610. },
  17611. enumerable: true,
  17612. configurable: true
  17613. });
  17614. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17615. get: function () {
  17616. return SceneLoader._ShowLoadingScreen;
  17617. },
  17618. set: function (value) {
  17619. SceneLoader._ShowLoadingScreen = value;
  17620. },
  17621. enumerable: true,
  17622. configurable: true
  17623. });
  17624. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17625. var dotPosition = sceneFilename.lastIndexOf(".");
  17626. var queryStringPosition = sceneFilename.indexOf("?");
  17627. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17628. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17629. var plugin = this._registeredPlugins[index];
  17630. if (plugin.extensions.indexOf(extension) !== -1) {
  17631. return plugin;
  17632. }
  17633. }
  17634. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17635. };
  17636. // Public functions
  17637. SceneLoader.RegisterPlugin = function (plugin) {
  17638. plugin.extensions = plugin.extensions.toLowerCase();
  17639. SceneLoader._registeredPlugins.push(plugin);
  17640. };
  17641. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17642. var manifestChecked = function (success) {
  17643. scene.database = database;
  17644. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17645. var importMeshFromData = function (data) {
  17646. var meshes = [];
  17647. var particleSystems = [];
  17648. var skeletons = [];
  17649. try {
  17650. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17651. if (onerror) {
  17652. onerror(scene, 'unable to load the scene');
  17653. }
  17654. return;
  17655. }
  17656. } catch (e) {
  17657. if (onerror) {
  17658. onerror(scene, e);
  17659. }
  17660. return;
  17661. }
  17662. if (onsuccess) {
  17663. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17664. onsuccess(meshes, particleSystems, skeletons);
  17665. }
  17666. };
  17667. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17668. // Direct load
  17669. importMeshFromData(sceneFilename.substr(5));
  17670. return;
  17671. }
  17672. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17673. importMeshFromData(data);
  17674. }, progressCallBack, database);
  17675. };
  17676. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17677. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17678. };
  17679. /**
  17680. * Load a scene
  17681. * @param rootUrl a string that defines the root url for scene and resources
  17682. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17683. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17684. */
  17685. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17686. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17687. };
  17688. /**
  17689. * Append a scene
  17690. * @param rootUrl a string that defines the root url for scene and resources
  17691. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17692. * @param scene is the instance of BABYLON.Scene to append to
  17693. */
  17694. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17695. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17696. var database;
  17697. if (SceneLoader.ShowLoadingScreen) {
  17698. scene.getEngine().displayLoadingUI();
  17699. }
  17700. var loadSceneFromData = function (data) {
  17701. scene.database = database;
  17702. if (!plugin.load(scene, data, rootUrl)) {
  17703. if (onerror) {
  17704. onerror(scene);
  17705. }
  17706. scene.getEngine().hideLoadingUI();
  17707. return;
  17708. }
  17709. if (onsuccess) {
  17710. onsuccess(scene);
  17711. }
  17712. if (SceneLoader.ShowLoadingScreen) {
  17713. scene.executeWhenReady(function () {
  17714. scene.getEngine().hideLoadingUI();
  17715. });
  17716. }
  17717. };
  17718. var manifestChecked = function (success) {
  17719. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17720. };
  17721. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17722. // Direct load
  17723. loadSceneFromData(sceneFilename.substr(5));
  17724. return;
  17725. }
  17726. if (rootUrl.indexOf("file:") === -1) {
  17727. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17728. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17729. } else {
  17730. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17731. }
  17732. };
  17733. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17734. SceneLoader._ShowLoadingScreen = true;
  17735. SceneLoader._registeredPlugins = new Array();
  17736. return SceneLoader;
  17737. })();
  17738. BABYLON.SceneLoader = SceneLoader;
  17739. ;
  17740. })(BABYLON || (BABYLON = {}));
  17741. //# sourceMappingURL=babylon.sceneLoader.js.map
  17742. var BABYLON;
  17743. (function (BABYLON) {
  17744. (function (Internals) {
  17745. var checkColors4 = function (colors, count) {
  17746. // Check if color3 was used
  17747. if (colors.length === count * 3) {
  17748. var colors4 = [];
  17749. for (var index = 0; index < colors.length; index += 3) {
  17750. var newIndex = (index / 3) * 4;
  17751. colors4[newIndex] = colors[index];
  17752. colors4[newIndex + 1] = colors[index + 1];
  17753. colors4[newIndex + 2] = colors[index + 2];
  17754. colors4[newIndex + 3] = 1.0;
  17755. }
  17756. return colors4;
  17757. }
  17758. return colors;
  17759. };
  17760. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17761. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17762. texture.name = parsedTexture.name;
  17763. texture.hasAlpha = parsedTexture.hasAlpha;
  17764. texture.level = parsedTexture.level;
  17765. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17766. return texture;
  17767. };
  17768. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17769. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17770. return null;
  17771. }
  17772. if (parsedTexture.isCube) {
  17773. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17774. }
  17775. var texture;
  17776. if (parsedTexture.mirrorPlane) {
  17777. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17778. texture._waitingRenderList = parsedTexture.renderList;
  17779. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17780. } else if (parsedTexture.isRenderTarget) {
  17781. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17782. texture._waitingRenderList = parsedTexture.renderList;
  17783. } else {
  17784. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17785. }
  17786. texture.name = parsedTexture.name;
  17787. texture.hasAlpha = parsedTexture.hasAlpha;
  17788. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17789. texture.level = parsedTexture.level;
  17790. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17791. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17792. texture.uOffset = parsedTexture.uOffset;
  17793. texture.vOffset = parsedTexture.vOffset;
  17794. texture.uScale = parsedTexture.uScale;
  17795. texture.vScale = parsedTexture.vScale;
  17796. texture.uAng = parsedTexture.uAng;
  17797. texture.vAng = parsedTexture.vAng;
  17798. texture.wAng = parsedTexture.wAng;
  17799. texture.wrapU = parsedTexture.wrapU;
  17800. texture.wrapV = parsedTexture.wrapV;
  17801. // Animations
  17802. if (parsedTexture.animations) {
  17803. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17804. var parsedAnimation = parsedTexture.animations[animationIndex];
  17805. texture.animations.push(parseAnimation(parsedAnimation));
  17806. }
  17807. }
  17808. return texture;
  17809. };
  17810. var parseSkeleton = function (parsedSkeleton, scene) {
  17811. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17812. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17813. var parsedBone = parsedSkeleton.bones[index];
  17814. var parentBone = null;
  17815. if (parsedBone.parentBoneIndex > -1) {
  17816. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17817. }
  17818. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17819. if (parsedBone.animation) {
  17820. bone.animations.push(parseAnimation(parsedBone.animation));
  17821. }
  17822. }
  17823. return skeleton;
  17824. };
  17825. var parseFresnelParameters = function (parsedFresnelParameters) {
  17826. var fresnelParameters = new BABYLON.FresnelParameters();
  17827. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17828. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17829. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17830. fresnelParameters.bias = parsedFresnelParameters.bias;
  17831. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17832. return fresnelParameters;
  17833. };
  17834. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17835. var material;
  17836. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17837. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17838. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17839. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17840. material.specularPower = parsedMaterial.specularPower;
  17841. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17842. material.alpha = parsedMaterial.alpha;
  17843. material.id = parsedMaterial.id;
  17844. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17845. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17846. material.wireframe = parsedMaterial.wireframe;
  17847. if (parsedMaterial.diffuseTexture) {
  17848. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17849. }
  17850. if (parsedMaterial.diffuseFresnelParameters) {
  17851. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17852. }
  17853. if (parsedMaterial.ambientTexture) {
  17854. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17855. }
  17856. if (parsedMaterial.opacityTexture) {
  17857. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17858. }
  17859. if (parsedMaterial.opacityFresnelParameters) {
  17860. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17861. }
  17862. if (parsedMaterial.reflectionTexture) {
  17863. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17864. }
  17865. if (parsedMaterial.reflectionFresnelParameters) {
  17866. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17867. }
  17868. if (parsedMaterial.emissiveTexture) {
  17869. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17870. }
  17871. if (parsedMaterial.emissiveFresnelParameters) {
  17872. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17873. }
  17874. if (parsedMaterial.specularTexture) {
  17875. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17876. }
  17877. if (parsedMaterial.bumpTexture) {
  17878. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17879. }
  17880. return material;
  17881. };
  17882. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17883. for (var index = 0; index < parsedData.materials.length; index++) {
  17884. var parsedMaterial = parsedData.materials[index];
  17885. if (parsedMaterial.id === id) {
  17886. return parseMaterial(parsedMaterial, scene, rootUrl);
  17887. }
  17888. }
  17889. return null;
  17890. };
  17891. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17892. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17893. multiMaterial.id = parsedMultiMaterial.id;
  17894. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17895. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17896. var subMatId = parsedMultiMaterial.materials[matIndex];
  17897. if (subMatId) {
  17898. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17899. } else {
  17900. multiMaterial.subMaterials.push(null);
  17901. }
  17902. }
  17903. return multiMaterial;
  17904. };
  17905. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17906. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17907. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17908. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17909. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17910. var parsedFlare = parsedLensFlareSystem.flares[index];
  17911. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17912. }
  17913. return lensFlareSystem;
  17914. };
  17915. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17916. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17917. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17918. if (parsedParticleSystem.textureName) {
  17919. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17920. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17921. }
  17922. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17923. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17924. particleSystem.minSize = parsedParticleSystem.minSize;
  17925. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17926. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17927. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17928. particleSystem.emitter = emitter;
  17929. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17930. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17931. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17932. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17933. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17934. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17935. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17936. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17937. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17938. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17939. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17940. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17941. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17942. particleSystem.start();
  17943. return particleSystem;
  17944. };
  17945. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17946. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17947. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17948. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17949. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17950. shadowGenerator.getShadowMap().renderList.push(mesh);
  17951. }
  17952. if (parsedShadowGenerator.usePoissonSampling) {
  17953. shadowGenerator.usePoissonSampling = true;
  17954. } else {
  17955. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17956. }
  17957. return shadowGenerator;
  17958. };
  17959. var parseAnimation = function (parsedAnimation) {
  17960. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17961. var dataType = parsedAnimation.dataType;
  17962. var keys = [];
  17963. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17964. var key = parsedAnimation.keys[index];
  17965. var data;
  17966. switch (dataType) {
  17967. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17968. data = key.values[0];
  17969. break;
  17970. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17971. data = BABYLON.Quaternion.FromArray(key.values);
  17972. break;
  17973. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17974. data = BABYLON.Matrix.FromArray(key.values);
  17975. break;
  17976. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17977. default:
  17978. data = BABYLON.Vector3.FromArray(key.values);
  17979. break;
  17980. }
  17981. keys.push({
  17982. frame: key.frame,
  17983. value: data
  17984. });
  17985. }
  17986. animation.setKeys(keys);
  17987. return animation;
  17988. };
  17989. var parseLight = function (parsedLight, scene) {
  17990. var light;
  17991. switch (parsedLight.type) {
  17992. case 0:
  17993. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17994. break;
  17995. case 1:
  17996. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17997. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17998. break;
  17999. case 2:
  18000. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18001. break;
  18002. case 3:
  18003. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18004. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18005. break;
  18006. }
  18007. light.id = parsedLight.id;
  18008. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18009. if (parsedLight.intensity !== undefined) {
  18010. light.intensity = parsedLight.intensity;
  18011. }
  18012. if (parsedLight.range) {
  18013. light.range = parsedLight.range;
  18014. }
  18015. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18016. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18017. if (parsedLight.excludedMeshesIds) {
  18018. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18019. }
  18020. // Parent
  18021. if (parsedLight.parentId) {
  18022. light._waitingParentId = parsedLight.parentId;
  18023. }
  18024. if (parsedLight.includedOnlyMeshesIds) {
  18025. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18026. }
  18027. // Animations
  18028. if (parsedLight.animations) {
  18029. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18030. var parsedAnimation = parsedLight.animations[animationIndex];
  18031. light.animations.push(parseAnimation(parsedAnimation));
  18032. }
  18033. }
  18034. if (parsedLight.autoAnimate) {
  18035. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18036. }
  18037. };
  18038. var parseCamera = function (parsedCamera, scene) {
  18039. var camera;
  18040. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18041. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18042. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18043. var alpha = parsedCamera.alpha;
  18044. var beta = parsedCamera.beta;
  18045. var radius = parsedCamera.radius;
  18046. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18047. var eye_space = parsedCamera.eye_space;
  18048. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18049. } else {
  18050. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18051. }
  18052. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18053. eye_space = parsedCamera.eye_space;
  18054. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18055. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  18056. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18057. } else if (parsedCamera.type === "FollowCamera") {
  18058. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18059. camera.heightOffset = parsedCamera.heightOffset;
  18060. camera.radius = parsedCamera.radius;
  18061. camera.rotationOffset = parsedCamera.rotationOffset;
  18062. if (lockedTargetMesh)
  18063. camera.target = lockedTargetMesh;
  18064. } else if (parsedCamera.type === "GamepadCamera") {
  18065. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18066. } else if (parsedCamera.type === "OculusCamera") {
  18067. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18068. } else if (parsedCamera.type === "OculusGamepadCamera") {
  18069. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18070. } else if (parsedCamera.type === "TouchCamera") {
  18071. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18072. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18073. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18074. } else if (parsedCamera.type === "WebVRCamera") {
  18075. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18076. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18077. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18078. } else {
  18079. // Free Camera is the default value
  18080. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18081. }
  18082. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18083. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18084. camera.lockedTarget = lockedTargetMesh;
  18085. }
  18086. camera.id = parsedCamera.id;
  18087. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18088. // Parent
  18089. if (parsedCamera.parentId) {
  18090. camera._waitingParentId = parsedCamera.parentId;
  18091. }
  18092. // Target
  18093. if (parsedCamera.target) {
  18094. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18095. } else {
  18096. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18097. }
  18098. camera.fov = parsedCamera.fov;
  18099. camera.minZ = parsedCamera.minZ;
  18100. camera.maxZ = parsedCamera.maxZ;
  18101. camera.speed = parsedCamera.speed;
  18102. camera.inertia = parsedCamera.inertia;
  18103. camera.checkCollisions = parsedCamera.checkCollisions;
  18104. camera.applyGravity = parsedCamera.applyGravity;
  18105. if (parsedCamera.ellipsoid) {
  18106. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18107. }
  18108. // Animations
  18109. if (parsedCamera.animations) {
  18110. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18111. var parsedAnimation = parsedCamera.animations[animationIndex];
  18112. camera.animations.push(parseAnimation(parsedAnimation));
  18113. }
  18114. }
  18115. if (parsedCamera.autoAnimate) {
  18116. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18117. }
  18118. // Layer Mask
  18119. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18120. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18121. } else {
  18122. camera.layerMask = 0xFFFFFFFF;
  18123. }
  18124. return camera;
  18125. };
  18126. var parseGeometry = function (parsedGeometry, scene) {
  18127. var id = parsedGeometry.id;
  18128. return scene.getGeometryByID(id);
  18129. };
  18130. var parseBox = function (parsedBox, scene) {
  18131. if (parseGeometry(parsedBox, scene)) {
  18132. return null;
  18133. }
  18134. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18135. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18136. scene.pushGeometry(box, true);
  18137. return box;
  18138. };
  18139. var parseSphere = function (parsedSphere, scene) {
  18140. if (parseGeometry(parsedSphere, scene)) {
  18141. return null;
  18142. }
  18143. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18144. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18145. scene.pushGeometry(sphere, true);
  18146. return sphere;
  18147. };
  18148. var parseCylinder = function (parsedCylinder, scene) {
  18149. if (parseGeometry(parsedCylinder, scene)) {
  18150. return null;
  18151. }
  18152. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18153. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18154. scene.pushGeometry(cylinder, true);
  18155. return cylinder;
  18156. };
  18157. var parseTorus = function (parsedTorus, scene) {
  18158. if (parseGeometry(parsedTorus, scene)) {
  18159. return null;
  18160. }
  18161. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18162. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18163. scene.pushGeometry(torus, true);
  18164. return torus;
  18165. };
  18166. var parseGround = function (parsedGround, scene) {
  18167. if (parseGeometry(parsedGround, scene)) {
  18168. return null;
  18169. }
  18170. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18171. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18172. scene.pushGeometry(ground, true);
  18173. return ground;
  18174. };
  18175. var parsePlane = function (parsedPlane, scene) {
  18176. if (parseGeometry(parsedPlane, scene)) {
  18177. return null;
  18178. }
  18179. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18180. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18181. scene.pushGeometry(plane, true);
  18182. return plane;
  18183. };
  18184. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18185. if (parseGeometry(parsedTorusKnot, scene)) {
  18186. return null;
  18187. }
  18188. 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);
  18189. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18190. scene.pushGeometry(torusKnot, true);
  18191. return torusKnot;
  18192. };
  18193. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18194. if (parseGeometry(parsedVertexData, scene)) {
  18195. return null;
  18196. }
  18197. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18198. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18199. if (parsedVertexData.delayLoadingFile) {
  18200. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18201. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18202. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18203. geometry._delayInfo = [];
  18204. if (parsedVertexData.hasUVs) {
  18205. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18206. }
  18207. if (parsedVertexData.hasUVs2) {
  18208. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18209. }
  18210. if (parsedVertexData.hasColors) {
  18211. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18212. }
  18213. if (parsedVertexData.hasMatricesIndices) {
  18214. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18215. }
  18216. if (parsedVertexData.hasMatricesWeights) {
  18217. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18218. }
  18219. geometry._delayLoadingFunction = importVertexData;
  18220. } else {
  18221. importVertexData(parsedVertexData, geometry);
  18222. }
  18223. scene.pushGeometry(geometry, true);
  18224. return geometry;
  18225. };
  18226. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18227. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18228. mesh.id = parsedMesh.id;
  18229. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18230. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18231. if (parsedMesh.rotationQuaternion) {
  18232. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18233. } else if (parsedMesh.rotation) {
  18234. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18235. }
  18236. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18237. if (parsedMesh.localMatrix) {
  18238. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18239. } else if (parsedMesh.pivotMatrix) {
  18240. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18241. }
  18242. mesh.setEnabled(parsedMesh.isEnabled);
  18243. mesh.isVisible = parsedMesh.isVisible;
  18244. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18245. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18246. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18247. if (parsedMesh.applyFog !== undefined) {
  18248. mesh.applyFog = parsedMesh.applyFog;
  18249. }
  18250. if (parsedMesh.pickable !== undefined) {
  18251. mesh.isPickable = parsedMesh.pickable;
  18252. }
  18253. if (parsedMesh.alphaIndex !== undefined) {
  18254. mesh.alphaIndex = parsedMesh.alphaIndex;
  18255. }
  18256. mesh.receiveShadows = parsedMesh.receiveShadows;
  18257. mesh.billboardMode = parsedMesh.billboardMode;
  18258. if (parsedMesh.visibility !== undefined) {
  18259. mesh.visibility = parsedMesh.visibility;
  18260. }
  18261. mesh.checkCollisions = parsedMesh.checkCollisions;
  18262. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18263. // Parent
  18264. if (parsedMesh.parentId) {
  18265. mesh._waitingParentId = parsedMesh.parentId;
  18266. }
  18267. // Actions
  18268. if (parsedMesh.actions !== undefined) {
  18269. mesh._waitingActions = parsedMesh.actions;
  18270. }
  18271. // Geometry
  18272. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18273. if (parsedMesh.delayLoadingFile) {
  18274. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18275. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18276. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18277. if (parsedMesh._binaryInfo) {
  18278. mesh._binaryInfo = parsedMesh._binaryInfo;
  18279. }
  18280. mesh._delayInfo = [];
  18281. if (parsedMesh.hasUVs) {
  18282. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18283. }
  18284. if (parsedMesh.hasUVs2) {
  18285. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18286. }
  18287. if (parsedMesh.hasColors) {
  18288. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18289. }
  18290. if (parsedMesh.hasMatricesIndices) {
  18291. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18292. }
  18293. if (parsedMesh.hasMatricesWeights) {
  18294. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18295. }
  18296. mesh._delayLoadingFunction = importGeometry;
  18297. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18298. mesh._checkDelayState();
  18299. }
  18300. } else {
  18301. importGeometry(parsedMesh, mesh);
  18302. }
  18303. // Material
  18304. if (parsedMesh.materialId) {
  18305. mesh.setMaterialByID(parsedMesh.materialId);
  18306. } else {
  18307. mesh.material = null;
  18308. }
  18309. // Skeleton
  18310. if (parsedMesh.skeletonId > -1) {
  18311. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18312. }
  18313. // Physics
  18314. if (parsedMesh.physicsImpostor) {
  18315. if (!scene.isPhysicsEnabled()) {
  18316. scene.enablePhysics();
  18317. }
  18318. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18319. }
  18320. // Animations
  18321. if (parsedMesh.animations) {
  18322. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18323. var parsedAnimation = parsedMesh.animations[animationIndex];
  18324. mesh.animations.push(parseAnimation(parsedAnimation));
  18325. }
  18326. }
  18327. if (parsedMesh.autoAnimate) {
  18328. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18329. }
  18330. // Layer Mask
  18331. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18332. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18333. } else {
  18334. mesh.layerMask = 0xFFFFFFFF;
  18335. }
  18336. // Instances
  18337. if (parsedMesh.instances) {
  18338. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18339. var parsedInstance = parsedMesh.instances[index];
  18340. var instance = mesh.createInstance(parsedInstance.name);
  18341. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18342. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18343. if (parsedInstance.rotationQuaternion) {
  18344. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18345. } else if (parsedInstance.rotation) {
  18346. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18347. }
  18348. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18349. instance.checkCollisions = mesh.checkCollisions;
  18350. if (parsedMesh.animations) {
  18351. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18352. parsedAnimation = parsedMesh.animations[animationIndex];
  18353. instance.animations.push(parseAnimation(parsedAnimation));
  18354. }
  18355. }
  18356. }
  18357. }
  18358. return mesh;
  18359. };
  18360. var parseActions = function (parsedActions, object, scene) {
  18361. var actionManager = new BABYLON.ActionManager(scene);
  18362. if (object === null)
  18363. scene.actionManager = actionManager;
  18364. else
  18365. object.actionManager = actionManager;
  18366. // instanciate a new object
  18367. var instanciate = function (name, params) {
  18368. var newInstance = Object.create(BABYLON[name].prototype);
  18369. newInstance.constructor.apply(newInstance, params);
  18370. return newInstance;
  18371. };
  18372. var parseParameter = function (name, value, target, propertyPath) {
  18373. if (propertyPath === null) {
  18374. // String, boolean or float
  18375. var floatValue = parseFloat(value);
  18376. if (value === "true" || value === "false")
  18377. return value === "true";
  18378. else
  18379. return isNaN(floatValue) ? value : floatValue;
  18380. }
  18381. var effectiveTarget = propertyPath.split(".");
  18382. var values = value.split(",");
  18383. for (var i = 0; i < effectiveTarget.length; i++) {
  18384. target = target[effectiveTarget[i]];
  18385. }
  18386. // Return appropriate value with its type
  18387. if (target instanceof Boolean)
  18388. return values[0] === "true";
  18389. if (target instanceof String)
  18390. return values[0];
  18391. // Parameters with multiple values such as Vector3 etc.
  18392. var split = new Array();
  18393. for (var i = 0; i < values.length; i++)
  18394. split.push(parseFloat(values[i]));
  18395. if (target instanceof BABYLON.Vector3)
  18396. return BABYLON.Vector3.FromArray(split);
  18397. if (target instanceof BABYLON.Vector4)
  18398. return BABYLON.Vector4.FromArray(split);
  18399. if (target instanceof BABYLON.Color3)
  18400. return BABYLON.Color3.FromArray(split);
  18401. if (target instanceof BABYLON.Color4)
  18402. return BABYLON.Color4.FromArray(split);
  18403. return parseFloat(values[0]);
  18404. };
  18405. // traverse graph per trigger
  18406. var traverse = function (parsedAction, trigger, condition, action) {
  18407. var parameters = new Array();
  18408. var target = null;
  18409. var propertyPath = null;
  18410. // Parameters
  18411. if (parsedAction.type === 2)
  18412. parameters.push(actionManager);
  18413. else
  18414. parameters.push(trigger);
  18415. for (var i = 0; i < parsedAction.properties.length; i++) {
  18416. var value = parsedAction.properties[i].value;
  18417. var name = parsedAction.properties[i].name;
  18418. if (name === "target")
  18419. value = target = scene.getNodeByName(value);
  18420. else if (name === "parent")
  18421. value = scene.getNodeByName(value);
  18422. else if (name !== "propertyPath") {
  18423. if (parsedAction.type === 2 && name === "operator")
  18424. value = BABYLON.ValueCondition[value];
  18425. else
  18426. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18427. } else {
  18428. propertyPath = value;
  18429. }
  18430. parameters.push(value);
  18431. }
  18432. parameters.push(condition);
  18433. // If interpolate value action
  18434. if (parsedAction.name === "InterpolateValueAction") {
  18435. var param = parameters[parameters.length - 2];
  18436. parameters[parameters.length - 1] = param;
  18437. parameters[parameters.length - 2] = condition;
  18438. }
  18439. // Action or condition(s)
  18440. var newAction = instanciate(parsedAction.name, parameters);
  18441. if (newAction instanceof BABYLON.Condition) {
  18442. condition = newAction;
  18443. newAction = action;
  18444. } else {
  18445. condition = null;
  18446. if (action)
  18447. action.then(newAction);
  18448. else
  18449. actionManager.registerAction(newAction);
  18450. }
  18451. for (var i = 0; i < parsedAction.children.length; i++)
  18452. traverse(parsedAction.children[i], trigger, condition, newAction);
  18453. };
  18454. for (var i = 0; i < parsedActions.children.length; i++) {
  18455. var triggerParams;
  18456. var trigger = parsedActions.children[i];
  18457. if (trigger.properties.length > 0) {
  18458. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18459. } else
  18460. triggerParams = BABYLON.ActionManager[trigger.name];
  18461. for (var j = 0; j < trigger.children.length; j++)
  18462. traverse(trigger.children[j], triggerParams, null, null);
  18463. }
  18464. };
  18465. var parseSound = function (parsedSound, scene, rootUrl) {
  18466. var soundName = parsedSound.name;
  18467. var soundUrl = rootUrl + soundName;
  18468. var options = {
  18469. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  18470. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  18471. rolloffFactor: parsedSound.rolloffFactor,
  18472. refDistance: parsedSound.refDistance,
  18473. distanceModel: parsedSound.distanceModel,
  18474. panningModel: parsedSound.panningModel
  18475. };
  18476. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18477. scene._removePendingData(newSound);
  18478. }, options);
  18479. scene._addPendingData(newSound);
  18480. if (parsedSound.position) {
  18481. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18482. newSound.setPosition(soundPosition);
  18483. }
  18484. if (parsedSound.isDirectional) {
  18485. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18486. if (parsedSound.localDirectionToMesh) {
  18487. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18488. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18489. }
  18490. }
  18491. if (parsedSound.connectedMeshId) {
  18492. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18493. if (connectedMesh) {
  18494. newSound.attachToMesh(connectedMesh);
  18495. }
  18496. }
  18497. };
  18498. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18499. names = (names instanceof Array) ? names : [names];
  18500. for (var i in names) {
  18501. if (mesh.name === names[i]) {
  18502. hierarchyIds.push(mesh.id);
  18503. return true;
  18504. }
  18505. }
  18506. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18507. hierarchyIds.push(mesh.id);
  18508. return true;
  18509. }
  18510. return false;
  18511. };
  18512. var importVertexData = function (parsedVertexData, geometry) {
  18513. var vertexData = new BABYLON.VertexData();
  18514. // positions
  18515. var positions = parsedVertexData.positions;
  18516. if (positions) {
  18517. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18518. }
  18519. // normals
  18520. var normals = parsedVertexData.normals;
  18521. if (normals) {
  18522. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18523. }
  18524. // uvs
  18525. var uvs = parsedVertexData.uvs;
  18526. if (uvs) {
  18527. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18528. }
  18529. // uv2s
  18530. var uv2s = parsedVertexData.uv2s;
  18531. if (uv2s) {
  18532. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18533. }
  18534. // colors
  18535. var colors = parsedVertexData.colors;
  18536. if (colors) {
  18537. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18538. }
  18539. // matricesIndices
  18540. var matricesIndices = parsedVertexData.matricesIndices;
  18541. if (matricesIndices) {
  18542. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18543. }
  18544. // matricesWeights
  18545. var matricesWeights = parsedVertexData.matricesWeights;
  18546. if (matricesWeights) {
  18547. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18548. }
  18549. // indices
  18550. var indices = parsedVertexData.indices;
  18551. if (indices) {
  18552. vertexData.indices = indices;
  18553. }
  18554. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18555. };
  18556. var importGeometry = function (parsedGeometry, mesh) {
  18557. var scene = mesh.getScene();
  18558. // Geometry
  18559. var geometryId = parsedGeometry.geometryId;
  18560. if (geometryId) {
  18561. var geometry = scene.getGeometryByID(geometryId);
  18562. if (geometry) {
  18563. geometry.applyToMesh(mesh);
  18564. }
  18565. } else if (parsedGeometry instanceof ArrayBuffer) {
  18566. var binaryInfo = mesh._binaryInfo;
  18567. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18568. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18569. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18570. }
  18571. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18572. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18573. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18574. }
  18575. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18576. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18577. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18578. }
  18579. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18580. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18581. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18582. }
  18583. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18584. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18585. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18586. }
  18587. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18588. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18589. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18590. }
  18591. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18592. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18593. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18594. }
  18595. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18596. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18597. mesh.setIndices(indicesData);
  18598. }
  18599. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18600. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18601. mesh.subMeshes = [];
  18602. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18603. var materialIndex = subMeshesData[(i * 5) + 0];
  18604. var verticesStart = subMeshesData[(i * 5) + 1];
  18605. var verticesCount = subMeshesData[(i * 5) + 2];
  18606. var indexStart = subMeshesData[(i * 5) + 3];
  18607. var indexCount = subMeshesData[(i * 5) + 4];
  18608. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18609. }
  18610. }
  18611. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18612. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18613. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18614. if (parsedGeometry.uvs) {
  18615. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18616. }
  18617. if (parsedGeometry.uvs2) {
  18618. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18619. }
  18620. if (parsedGeometry.colors) {
  18621. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18622. }
  18623. if (parsedGeometry.matricesIndices) {
  18624. if (!parsedGeometry.matricesIndices._isExpanded) {
  18625. var floatIndices = [];
  18626. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18627. var matricesIndex = parsedGeometry.matricesIndices[i];
  18628. floatIndices.push(matricesIndex & 0x000000FF);
  18629. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18630. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18631. floatIndices.push(matricesIndex >> 24);
  18632. }
  18633. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18634. } else {
  18635. delete parsedGeometry.matricesIndices._isExpanded;
  18636. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18637. }
  18638. }
  18639. if (parsedGeometry.matricesWeights) {
  18640. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18641. }
  18642. mesh.setIndices(parsedGeometry.indices);
  18643. // SubMeshes
  18644. if (parsedGeometry.subMeshes) {
  18645. mesh.subMeshes = [];
  18646. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18647. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18648. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18649. }
  18650. }
  18651. }
  18652. // Flat shading
  18653. if (mesh._shouldGenerateFlatShading) {
  18654. mesh.convertToFlatShadedMesh();
  18655. delete mesh._shouldGenerateFlatShading;
  18656. }
  18657. // Update
  18658. mesh.computeWorldMatrix(true);
  18659. // Octree
  18660. if (scene._selectionOctree) {
  18661. scene._selectionOctree.addMesh(mesh);
  18662. }
  18663. };
  18664. BABYLON.SceneLoader.RegisterPlugin({
  18665. extensions: ".babylon",
  18666. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18667. var parsedData = JSON.parse(data);
  18668. var loadedSkeletonsIds = [];
  18669. var loadedMaterialsIds = [];
  18670. var hierarchyIds = [];
  18671. for (var index = 0; index < parsedData.meshes.length; index++) {
  18672. var parsedMesh = parsedData.meshes[index];
  18673. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18674. if (meshesNames instanceof Array) {
  18675. // Remove found mesh name from list.
  18676. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18677. }
  18678. // Material ?
  18679. if (parsedMesh.materialId) {
  18680. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18681. if (!materialFound) {
  18682. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18683. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18684. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18685. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18686. var subMatId = parsedMultiMaterial.materials[matIndex];
  18687. loadedMaterialsIds.push(subMatId);
  18688. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18689. }
  18690. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18691. parseMultiMaterial(parsedMultiMaterial, scene);
  18692. materialFound = true;
  18693. break;
  18694. }
  18695. }
  18696. }
  18697. if (!materialFound) {
  18698. loadedMaterialsIds.push(parsedMesh.materialId);
  18699. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18700. }
  18701. }
  18702. // Skeleton ?
  18703. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18704. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18705. if (!skeletonAlreadyLoaded) {
  18706. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18707. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18708. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18709. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18710. loadedSkeletonsIds.push(parsedSkeleton.id);
  18711. }
  18712. }
  18713. }
  18714. }
  18715. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18716. meshes.push(mesh);
  18717. }
  18718. }
  18719. for (index = 0; index < scene.meshes.length; index++) {
  18720. var currentMesh = scene.meshes[index];
  18721. if (currentMesh._waitingParentId) {
  18722. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18723. currentMesh._waitingParentId = undefined;
  18724. }
  18725. }
  18726. // Particles
  18727. if (parsedData.particleSystems) {
  18728. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18729. var parsedParticleSystem = parsedData.particleSystems[index];
  18730. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18731. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18732. }
  18733. }
  18734. }
  18735. return true;
  18736. },
  18737. load: function (scene, data, rootUrl) {
  18738. var parsedData = JSON.parse(data);
  18739. // Scene
  18740. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18741. scene.autoClear = parsedData.autoClear;
  18742. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18743. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18744. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18745. // Fog
  18746. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18747. scene.fogMode = parsedData.fogMode;
  18748. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18749. scene.fogStart = parsedData.fogStart;
  18750. scene.fogEnd = parsedData.fogEnd;
  18751. scene.fogDensity = parsedData.fogDensity;
  18752. }
  18753. for (var index = 0; index < parsedData.lights.length; index++) {
  18754. var parsedLight = parsedData.lights[index];
  18755. parseLight(parsedLight, scene);
  18756. }
  18757. // Materials
  18758. if (parsedData.materials) {
  18759. for (index = 0; index < parsedData.materials.length; index++) {
  18760. var parsedMaterial = parsedData.materials[index];
  18761. parseMaterial(parsedMaterial, scene, rootUrl);
  18762. }
  18763. }
  18764. if (parsedData.multiMaterials) {
  18765. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18766. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18767. parseMultiMaterial(parsedMultiMaterial, scene);
  18768. }
  18769. }
  18770. // Skeletons
  18771. if (parsedData.skeletons) {
  18772. for (index = 0; index < parsedData.skeletons.length; index++) {
  18773. var parsedSkeleton = parsedData.skeletons[index];
  18774. parseSkeleton(parsedSkeleton, scene);
  18775. }
  18776. }
  18777. // Geometries
  18778. var geometries = parsedData.geometries;
  18779. if (geometries) {
  18780. // Boxes
  18781. var boxes = geometries.boxes;
  18782. if (boxes) {
  18783. for (index = 0; index < boxes.length; index++) {
  18784. var parsedBox = boxes[index];
  18785. parseBox(parsedBox, scene);
  18786. }
  18787. }
  18788. // Spheres
  18789. var spheres = geometries.spheres;
  18790. if (spheres) {
  18791. for (index = 0; index < spheres.length; index++) {
  18792. var parsedSphere = spheres[index];
  18793. parseSphere(parsedSphere, scene);
  18794. }
  18795. }
  18796. // Cylinders
  18797. var cylinders = geometries.cylinders;
  18798. if (cylinders) {
  18799. for (index = 0; index < cylinders.length; index++) {
  18800. var parsedCylinder = cylinders[index];
  18801. parseCylinder(parsedCylinder, scene);
  18802. }
  18803. }
  18804. // Toruses
  18805. var toruses = geometries.toruses;
  18806. if (toruses) {
  18807. for (index = 0; index < toruses.length; index++) {
  18808. var parsedTorus = toruses[index];
  18809. parseTorus(parsedTorus, scene);
  18810. }
  18811. }
  18812. // Grounds
  18813. var grounds = geometries.grounds;
  18814. if (grounds) {
  18815. for (index = 0; index < grounds.length; index++) {
  18816. var parsedGround = grounds[index];
  18817. parseGround(parsedGround, scene);
  18818. }
  18819. }
  18820. // Planes
  18821. var planes = geometries.planes;
  18822. if (planes) {
  18823. for (index = 0; index < planes.length; index++) {
  18824. var parsedPlane = planes[index];
  18825. parsePlane(parsedPlane, scene);
  18826. }
  18827. }
  18828. // TorusKnots
  18829. var torusKnots = geometries.torusKnots;
  18830. if (torusKnots) {
  18831. for (index = 0; index < torusKnots.length; index++) {
  18832. var parsedTorusKnot = torusKnots[index];
  18833. parseTorusKnot(parsedTorusKnot, scene);
  18834. }
  18835. }
  18836. // VertexData
  18837. var vertexData = geometries.vertexData;
  18838. if (vertexData) {
  18839. for (index = 0; index < vertexData.length; index++) {
  18840. var parsedVertexData = vertexData[index];
  18841. parseVertexData(parsedVertexData, scene, rootUrl);
  18842. }
  18843. }
  18844. }
  18845. for (index = 0; index < parsedData.meshes.length; index++) {
  18846. var parsedMesh = parsedData.meshes[index];
  18847. parseMesh(parsedMesh, scene, rootUrl);
  18848. }
  18849. for (index = 0; index < parsedData.cameras.length; index++) {
  18850. var parsedCamera = parsedData.cameras[index];
  18851. parseCamera(parsedCamera, scene);
  18852. }
  18853. if (parsedData.activeCameraID) {
  18854. scene.setActiveCameraByID(parsedData.activeCameraID);
  18855. }
  18856. for (index = 0; index < scene.cameras.length; index++) {
  18857. var camera = scene.cameras[index];
  18858. if (camera._waitingParentId) {
  18859. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18860. camera._waitingParentId = undefined;
  18861. }
  18862. }
  18863. for (index = 0; index < scene.lights.length; index++) {
  18864. var light = scene.lights[index];
  18865. if (light._waitingParentId) {
  18866. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18867. light._waitingParentId = undefined;
  18868. }
  18869. }
  18870. for (index = 0; index < scene.meshes.length; index++) {
  18871. var mesh = scene.meshes[index];
  18872. if (mesh._waitingParentId) {
  18873. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18874. mesh._waitingParentId = undefined;
  18875. }
  18876. if (mesh._waitingActions) {
  18877. parseActions(mesh._waitingActions, mesh, scene);
  18878. mesh._waitingActions = undefined;
  18879. }
  18880. }
  18881. // Particles Systems
  18882. if (parsedData.particleSystems) {
  18883. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18884. var parsedParticleSystem = parsedData.particleSystems[index];
  18885. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18886. }
  18887. }
  18888. // Lens flares
  18889. if (parsedData.lensFlareSystems) {
  18890. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18891. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18892. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18893. }
  18894. }
  18895. // Shadows
  18896. if (parsedData.shadowGenerators) {
  18897. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18898. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18899. parseShadowGenerator(parsedShadowGenerator, scene);
  18900. }
  18901. }
  18902. // Sounds
  18903. if (parsedData.sounds && scene.getEngine().getAudioEngine().canUseWebAudio) {
  18904. for (index = 0; index < parsedData.sounds.length; index++) {
  18905. var parsedSound = parsedData.sounds[index];
  18906. parseSound(parsedSound, scene, rootUrl);
  18907. }
  18908. }
  18909. // Actions (scene)
  18910. if (parsedData.actions) {
  18911. parseActions(parsedData.actions, null, scene);
  18912. }
  18913. // Finish
  18914. return true;
  18915. }
  18916. });
  18917. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18918. var Internals = BABYLON.Internals;
  18919. })(BABYLON || (BABYLON = {}));
  18920. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18921. var BABYLON;
  18922. (function (BABYLON) {
  18923. // Unique ID when we import meshes from Babylon to CSG
  18924. var currentCSGMeshId = 0;
  18925. // # class Vertex
  18926. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18927. // one to provide additional features like texture coordinates and vertex
  18928. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18929. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18930. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18931. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18932. // is not used anywhere else.
  18933. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18934. var Vertex = (function () {
  18935. function Vertex(pos, normal, uv) {
  18936. this.pos = pos;
  18937. this.normal = normal;
  18938. this.uv = uv;
  18939. }
  18940. Vertex.prototype.clone = function () {
  18941. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18942. };
  18943. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18944. // orientation of a polygon is flipped.
  18945. Vertex.prototype.flip = function () {
  18946. this.normal = this.normal.scale(-1);
  18947. };
  18948. // Create a new vertex between this vertex and `other` by linearly
  18949. // interpolating all properties using a parameter of `t`. Subclasses should
  18950. // override this to interpolate additional properties.
  18951. Vertex.prototype.interpolate = function (other, t) {
  18952. 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));
  18953. };
  18954. return Vertex;
  18955. })();
  18956. // # class Plane
  18957. // Represents a plane in 3D space.
  18958. var Plane = (function () {
  18959. function Plane(normal, w) {
  18960. this.normal = normal;
  18961. this.w = w;
  18962. }
  18963. Plane.FromPoints = function (a, b, c) {
  18964. var v0 = c.subtract(a);
  18965. var v1 = b.subtract(a);
  18966. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18967. return null;
  18968. }
  18969. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18970. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18971. };
  18972. Plane.prototype.clone = function () {
  18973. return new Plane(this.normal.clone(), this.w);
  18974. };
  18975. Plane.prototype.flip = function () {
  18976. this.normal.scaleInPlace(-1);
  18977. this.w = -this.w;
  18978. };
  18979. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18980. // fragments in the appropriate lists. Coplanar polygons go into either
  18981. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18982. // respect to this plane. Polygons in front or in back of this plane go into
  18983. // either `front` or `back`.
  18984. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18985. var COPLANAR = 0;
  18986. var FRONT = 1;
  18987. var BACK = 2;
  18988. var SPANNING = 3;
  18989. // Classify each point as well as the entire polygon into one of the above
  18990. // four classes.
  18991. var polygonType = 0;
  18992. var types = [];
  18993. for (var i = 0; i < polygon.vertices.length; i++) {
  18994. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18995. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18996. polygonType |= type;
  18997. types.push(type);
  18998. }
  18999. switch (polygonType) {
  19000. case COPLANAR:
  19001. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19002. break;
  19003. case FRONT:
  19004. front.push(polygon);
  19005. break;
  19006. case BACK:
  19007. back.push(polygon);
  19008. break;
  19009. case SPANNING:
  19010. var f = [], b = [];
  19011. for (i = 0; i < polygon.vertices.length; i++) {
  19012. var j = (i + 1) % polygon.vertices.length;
  19013. var ti = types[i], tj = types[j];
  19014. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19015. if (ti != BACK)
  19016. f.push(vi);
  19017. if (ti != FRONT)
  19018. b.push(ti != BACK ? vi.clone() : vi);
  19019. if ((ti | tj) == SPANNING) {
  19020. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19021. var v = vi.interpolate(vj, t);
  19022. f.push(v);
  19023. b.push(v.clone());
  19024. }
  19025. }
  19026. if (f.length >= 3) {
  19027. var poly = new Polygon(f, polygon.shared);
  19028. if (poly.plane)
  19029. front.push(poly);
  19030. }
  19031. if (b.length >= 3) {
  19032. poly = new Polygon(b, polygon.shared);
  19033. if (poly.plane)
  19034. back.push(poly);
  19035. }
  19036. break;
  19037. }
  19038. };
  19039. Plane.EPSILON = 1e-5;
  19040. return Plane;
  19041. })();
  19042. // # class Polygon
  19043. // Represents a convex polygon. The vertices used to initialize a polygon must
  19044. // be coplanar and form a convex loop.
  19045. //
  19046. // Each convex polygon has a `shared` property, which is shared between all
  19047. // polygons that are clones of each other or were split from the same polygon.
  19048. // This can be used to define per-polygon properties (such as surface color).
  19049. var Polygon = (function () {
  19050. function Polygon(vertices, shared) {
  19051. this.vertices = vertices;
  19052. this.shared = shared;
  19053. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19054. }
  19055. Polygon.prototype.clone = function () {
  19056. var vertices = this.vertices.map(function (v) {
  19057. return v.clone();
  19058. });
  19059. return new Polygon(vertices, this.shared);
  19060. };
  19061. Polygon.prototype.flip = function () {
  19062. this.vertices.reverse().map(function (v) {
  19063. v.flip();
  19064. });
  19065. this.plane.flip();
  19066. };
  19067. return Polygon;
  19068. })();
  19069. // # class Node
  19070. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19071. // by picking a polygon to split along. That polygon (and all other coplanar
  19072. // polygons) are added directly to that node and the other polygons are added to
  19073. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19074. // no distinction between internal and leaf nodes.
  19075. var Node = (function () {
  19076. function Node(polygons) {
  19077. this.plane = null;
  19078. this.front = null;
  19079. this.back = null;
  19080. this.polygons = [];
  19081. if (polygons) {
  19082. this.build(polygons);
  19083. }
  19084. }
  19085. Node.prototype.clone = function () {
  19086. var node = new Node();
  19087. node.plane = this.plane && this.plane.clone();
  19088. node.front = this.front && this.front.clone();
  19089. node.back = this.back && this.back.clone();
  19090. node.polygons = this.polygons.map(function (p) {
  19091. return p.clone();
  19092. });
  19093. return node;
  19094. };
  19095. // Convert solid space to empty space and empty space to solid space.
  19096. Node.prototype.invert = function () {
  19097. for (var i = 0; i < this.polygons.length; i++) {
  19098. this.polygons[i].flip();
  19099. }
  19100. if (this.plane) {
  19101. this.plane.flip();
  19102. }
  19103. if (this.front) {
  19104. this.front.invert();
  19105. }
  19106. if (this.back) {
  19107. this.back.invert();
  19108. }
  19109. var temp = this.front;
  19110. this.front = this.back;
  19111. this.back = temp;
  19112. };
  19113. // Recursively remove all polygons in `polygons` that are inside this BSP
  19114. // tree.
  19115. Node.prototype.clipPolygons = function (polygons) {
  19116. if (!this.plane)
  19117. return polygons.slice();
  19118. var front = [], back = [];
  19119. for (var i = 0; i < polygons.length; i++) {
  19120. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19121. }
  19122. if (this.front) {
  19123. front = this.front.clipPolygons(front);
  19124. }
  19125. if (this.back) {
  19126. back = this.back.clipPolygons(back);
  19127. } else {
  19128. back = [];
  19129. }
  19130. return front.concat(back);
  19131. };
  19132. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19133. // `bsp`.
  19134. Node.prototype.clipTo = function (bsp) {
  19135. this.polygons = bsp.clipPolygons(this.polygons);
  19136. if (this.front)
  19137. this.front.clipTo(bsp);
  19138. if (this.back)
  19139. this.back.clipTo(bsp);
  19140. };
  19141. // Return a list of all polygons in this BSP tree.
  19142. Node.prototype.allPolygons = function () {
  19143. var polygons = this.polygons.slice();
  19144. if (this.front)
  19145. polygons = polygons.concat(this.front.allPolygons());
  19146. if (this.back)
  19147. polygons = polygons.concat(this.back.allPolygons());
  19148. return polygons;
  19149. };
  19150. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19151. // new polygons are filtered down to the bottom of the tree and become new
  19152. // nodes there. Each set of polygons is partitioned using the first polygon
  19153. // (no heuristic is used to pick a good split).
  19154. Node.prototype.build = function (polygons) {
  19155. if (!polygons.length)
  19156. return;
  19157. if (!this.plane)
  19158. this.plane = polygons[0].plane.clone();
  19159. var front = [], back = [];
  19160. for (var i = 0; i < polygons.length; i++) {
  19161. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19162. }
  19163. if (front.length) {
  19164. if (!this.front)
  19165. this.front = new Node();
  19166. this.front.build(front);
  19167. }
  19168. if (back.length) {
  19169. if (!this.back)
  19170. this.back = new Node();
  19171. this.back.build(back);
  19172. }
  19173. };
  19174. return Node;
  19175. })();
  19176. var CSG = (function () {
  19177. function CSG() {
  19178. this.polygons = new Array();
  19179. }
  19180. // Convert BABYLON.Mesh to BABYLON.CSG
  19181. CSG.FromMesh = function (mesh) {
  19182. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19183. if (mesh instanceof BABYLON.Mesh) {
  19184. mesh.computeWorldMatrix(true);
  19185. var matrix = mesh.getWorldMatrix();
  19186. var meshPosition = mesh.position.clone();
  19187. var meshRotation = mesh.rotation.clone();
  19188. var meshScaling = mesh.scaling.clone();
  19189. } else {
  19190. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19191. }
  19192. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19193. var subMeshes = mesh.subMeshes;
  19194. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19195. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19196. vertices = [];
  19197. for (var j = 0; j < 3; j++) {
  19198. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19199. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19200. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19201. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19202. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19203. vertex = new Vertex(position, normal, uv);
  19204. vertices.push(vertex);
  19205. }
  19206. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19207. // To handle the case of degenerated triangle
  19208. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19209. if (polygon.plane)
  19210. polygons.push(polygon);
  19211. }
  19212. }
  19213. var csg = CSG.FromPolygons(polygons);
  19214. csg.matrix = matrix;
  19215. csg.position = meshPosition;
  19216. csg.rotation = meshRotation;
  19217. csg.scaling = meshScaling;
  19218. currentCSGMeshId++;
  19219. return csg;
  19220. };
  19221. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19222. CSG.FromPolygons = function (polygons) {
  19223. var csg = new BABYLON.CSG();
  19224. csg.polygons = polygons;
  19225. return csg;
  19226. };
  19227. CSG.prototype.clone = function () {
  19228. var csg = new BABYLON.CSG();
  19229. csg.polygons = this.polygons.map(function (p) {
  19230. return p.clone();
  19231. });
  19232. csg.copyTransformAttributes(this);
  19233. return csg;
  19234. };
  19235. CSG.prototype.toPolygons = function () {
  19236. return this.polygons;
  19237. };
  19238. CSG.prototype.union = function (csg) {
  19239. var a = new Node(this.clone().polygons);
  19240. var b = new Node(csg.clone().polygons);
  19241. a.clipTo(b);
  19242. b.clipTo(a);
  19243. b.invert();
  19244. b.clipTo(a);
  19245. b.invert();
  19246. a.build(b.allPolygons());
  19247. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19248. };
  19249. CSG.prototype.unionInPlace = function (csg) {
  19250. var a = new Node(this.polygons);
  19251. var b = new Node(csg.polygons);
  19252. a.clipTo(b);
  19253. b.clipTo(a);
  19254. b.invert();
  19255. b.clipTo(a);
  19256. b.invert();
  19257. a.build(b.allPolygons());
  19258. this.polygons = a.allPolygons();
  19259. };
  19260. CSG.prototype.subtract = function (csg) {
  19261. var a = new Node(this.clone().polygons);
  19262. var b = new Node(csg.clone().polygons);
  19263. a.invert();
  19264. a.clipTo(b);
  19265. b.clipTo(a);
  19266. b.invert();
  19267. b.clipTo(a);
  19268. b.invert();
  19269. a.build(b.allPolygons());
  19270. a.invert();
  19271. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19272. };
  19273. CSG.prototype.subtractInPlace = function (csg) {
  19274. var a = new Node(this.polygons);
  19275. var b = new Node(csg.polygons);
  19276. a.invert();
  19277. a.clipTo(b);
  19278. b.clipTo(a);
  19279. b.invert();
  19280. b.clipTo(a);
  19281. b.invert();
  19282. a.build(b.allPolygons());
  19283. a.invert();
  19284. this.polygons = a.allPolygons();
  19285. };
  19286. CSG.prototype.intersect = function (csg) {
  19287. var a = new Node(this.clone().polygons);
  19288. var b = new Node(csg.clone().polygons);
  19289. a.invert();
  19290. b.clipTo(a);
  19291. b.invert();
  19292. a.clipTo(b);
  19293. b.clipTo(a);
  19294. a.build(b.allPolygons());
  19295. a.invert();
  19296. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19297. };
  19298. CSG.prototype.intersectInPlace = function (csg) {
  19299. var a = new Node(this.polygons);
  19300. var b = new Node(csg.polygons);
  19301. a.invert();
  19302. b.clipTo(a);
  19303. b.invert();
  19304. a.clipTo(b);
  19305. b.clipTo(a);
  19306. a.build(b.allPolygons());
  19307. a.invert();
  19308. this.polygons = a.allPolygons();
  19309. };
  19310. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19311. // not modified.
  19312. CSG.prototype.inverse = function () {
  19313. var csg = this.clone();
  19314. csg.inverseInPlace();
  19315. return csg;
  19316. };
  19317. CSG.prototype.inverseInPlace = function () {
  19318. this.polygons.map(function (p) {
  19319. p.flip();
  19320. });
  19321. };
  19322. // This is used to keep meshes transformations so they can be restored
  19323. // when we build back a Babylon Mesh
  19324. // NB : All CSG operations are performed in world coordinates
  19325. CSG.prototype.copyTransformAttributes = function (csg) {
  19326. this.matrix = csg.matrix;
  19327. this.position = csg.position;
  19328. this.rotation = csg.rotation;
  19329. this.scaling = csg.scaling;
  19330. return this;
  19331. };
  19332. // Build Raw mesh from CSG
  19333. // Coordinates here are in world space
  19334. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19335. var matrix = this.matrix.clone();
  19336. matrix.invert();
  19337. 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;
  19338. if (keepSubMeshes) {
  19339. // Sort Polygons, since subMeshes are indices range
  19340. polygons.sort(function (a, b) {
  19341. if (a.shared.meshId === b.shared.meshId) {
  19342. return a.shared.subMeshId - b.shared.subMeshId;
  19343. } else {
  19344. return a.shared.meshId - b.shared.meshId;
  19345. }
  19346. });
  19347. }
  19348. for (var i = 0, il = polygons.length; i < il; i++) {
  19349. polygon = polygons[i];
  19350. // Building SubMeshes
  19351. if (!subMesh_dict[polygon.shared.meshId]) {
  19352. subMesh_dict[polygon.shared.meshId] = {};
  19353. }
  19354. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19355. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19356. indexStart: +Infinity,
  19357. indexEnd: -Infinity,
  19358. materialIndex: polygon.shared.materialIndex
  19359. };
  19360. }
  19361. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19362. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19363. polygonIndices[0] = 0;
  19364. polygonIndices[1] = j - 1;
  19365. polygonIndices[2] = j;
  19366. for (var k = 0; k < 3; k++) {
  19367. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19368. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19369. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19370. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19371. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19372. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19373. // Check if 2 points can be merged
  19374. 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)) {
  19375. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19376. uvs.push(uv.x, uv.y);
  19377. normals.push(normal.x, normal.y, normal.z);
  19378. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19379. }
  19380. indices.push(vertex_idx);
  19381. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19382. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19383. currentIndex++;
  19384. }
  19385. }
  19386. }
  19387. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19388. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19389. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19390. mesh.setIndices(indices);
  19391. if (keepSubMeshes) {
  19392. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19393. var materialIndexOffset = 0, materialMaxIndex;
  19394. mesh.subMeshes.length = 0;
  19395. for (var m in subMesh_dict) {
  19396. materialMaxIndex = -1;
  19397. for (var sm in subMesh_dict[m]) {
  19398. subMesh_obj = subMesh_dict[m][sm];
  19399. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19400. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19401. }
  19402. materialIndexOffset += ++materialMaxIndex;
  19403. }
  19404. }
  19405. return mesh;
  19406. };
  19407. // Build Mesh from CSG taking material and transforms into account
  19408. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19409. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19410. mesh.material = material;
  19411. mesh.position.copyFrom(this.position);
  19412. mesh.rotation.copyFrom(this.rotation);
  19413. mesh.scaling.copyFrom(this.scaling);
  19414. mesh.computeWorldMatrix(true);
  19415. return mesh;
  19416. };
  19417. return CSG;
  19418. })();
  19419. BABYLON.CSG = CSG;
  19420. })(BABYLON || (BABYLON = {}));
  19421. //# sourceMappingURL=babylon.csg.js.map
  19422. var BABYLON;
  19423. (function (BABYLON) {
  19424. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19425. __extends(OculusDistortionCorrectionPostProcess, _super);
  19426. //ANY
  19427. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19428. var _this = this;
  19429. _super.call(this, name, "oculusDistortionCorrection", [
  19430. 'LensCenter',
  19431. 'Scale',
  19432. 'ScaleIn',
  19433. 'HmdWarpParam'
  19434. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19435. this._isRightEye = isRightEye;
  19436. this._distortionFactors = cameraSettings.DistortionK;
  19437. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19438. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19439. this.onSizeChanged = function () {
  19440. _this.aspectRatio = _this.width * .5 / _this.height;
  19441. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19442. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19443. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19444. };
  19445. this.onApply = function (effect) {
  19446. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19447. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19448. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19449. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19450. };
  19451. }
  19452. return OculusDistortionCorrectionPostProcess;
  19453. })(BABYLON.PostProcess);
  19454. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19455. })(BABYLON || (BABYLON = {}));
  19456. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  19457. // Mainly based on these 2 articles :
  19458. // 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
  19459. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19460. var BABYLON;
  19461. (function (BABYLON) {
  19462. (function (JoystickAxis) {
  19463. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19464. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19465. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19466. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19467. var JoystickAxis = BABYLON.JoystickAxis;
  19468. var VirtualJoystick = (function () {
  19469. function VirtualJoystick(leftJoystick) {
  19470. var _this = this;
  19471. if (leftJoystick) {
  19472. this._leftJoystick = true;
  19473. } else {
  19474. this._leftJoystick = false;
  19475. }
  19476. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19477. VirtualJoystick._globalJoystickIndex++;
  19478. // By default left & right arrow keys are moving the X
  19479. // and up & down keys are moving the Y
  19480. this._axisTargetedByLeftAndRight = 0 /* X */;
  19481. this._axisTargetedByUpAndDown = 1 /* Y */;
  19482. this.reverseLeftRight = false;
  19483. this.reverseUpDown = false;
  19484. // collections of pointers
  19485. this._touches = new BABYLON.VirtualJoystick.Collection();
  19486. this.deltaPosition = BABYLON.Vector3.Zero();
  19487. this._joystickSensibility = 25;
  19488. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19489. this._rotationSpeed = 25;
  19490. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19491. this._rotateOnAxisRelativeToMesh = false;
  19492. // injecting a canvas element on top of the canvas 3D game
  19493. if (!VirtualJoystick.vjCanvas) {
  19494. window.addEventListener("resize", function () {
  19495. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19496. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19497. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19498. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19499. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19500. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19501. }, false);
  19502. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19503. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19504. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19505. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19506. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19507. VirtualJoystick.vjCanvas.style.width = "100%";
  19508. VirtualJoystick.vjCanvas.style.height = "100%";
  19509. VirtualJoystick.vjCanvas.style.position = "absolute";
  19510. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19511. VirtualJoystick.vjCanvas.style.top = "0px";
  19512. VirtualJoystick.vjCanvas.style.left = "0px";
  19513. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19514. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19515. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19516. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19517. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19518. document.body.appendChild(VirtualJoystick.vjCanvas);
  19519. }
  19520. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19521. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19522. this.pressed = false;
  19523. // default joystick color
  19524. this._joystickColor = "cyan";
  19525. this._joystickPointerID = -1;
  19526. // current joystick position
  19527. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19528. // origin joystick position
  19529. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19530. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19531. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19532. _this._onPointerDown(evt);
  19533. }, false);
  19534. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19535. _this._onPointerMove(evt);
  19536. }, false);
  19537. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19538. _this._onPointerUp(evt);
  19539. }, false);
  19540. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19541. _this._onPointerUp(evt);
  19542. }, false);
  19543. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19544. evt.preventDefault(); // Disables system menu
  19545. }, false);
  19546. requestAnimationFrame(function () {
  19547. _this._drawVirtualJoystick();
  19548. });
  19549. }
  19550. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19551. this._joystickSensibility = newJoystickSensibility;
  19552. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19553. };
  19554. VirtualJoystick.prototype._onPointerDown = function (e) {
  19555. var positionOnScreenCondition;
  19556. e.preventDefault();
  19557. if (this._leftJoystick === true) {
  19558. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19559. } else {
  19560. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19561. }
  19562. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19563. // First contact will be dedicated to the virtual joystick
  19564. this._joystickPointerID = e.pointerId;
  19565. this._joystickPointerStartPos.x = e.clientX;
  19566. this._joystickPointerStartPos.y = e.clientY;
  19567. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19568. this._deltaJoystickVector.x = 0;
  19569. this._deltaJoystickVector.y = 0;
  19570. this.pressed = true;
  19571. this._touches.add(e.pointerId.toString(), e);
  19572. } else {
  19573. // You can only trigger the action buttons with a joystick declared
  19574. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19575. this._action();
  19576. this._touches.add(e.pointerId.toString(), e);
  19577. }
  19578. }
  19579. };
  19580. VirtualJoystick.prototype._onPointerMove = function (e) {
  19581. // If the current pointer is the one associated to the joystick (first touch contact)
  19582. if (this._joystickPointerID == e.pointerId) {
  19583. this._joystickPointerPos.x = e.clientX;
  19584. this._joystickPointerPos.y = e.clientY;
  19585. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19586. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19587. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19588. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19589. switch (this._axisTargetedByLeftAndRight) {
  19590. case 0 /* X */:
  19591. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19592. break;
  19593. case 1 /* Y */:
  19594. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19595. break;
  19596. case 2 /* Z */:
  19597. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19598. break;
  19599. }
  19600. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19601. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19602. switch (this._axisTargetedByUpAndDown) {
  19603. case 0 /* X */:
  19604. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19605. break;
  19606. case 1 /* Y */:
  19607. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19608. break;
  19609. case 2 /* Z */:
  19610. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19611. break;
  19612. }
  19613. } else {
  19614. if (this._touches.item(e.pointerId.toString())) {
  19615. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19616. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19617. }
  19618. }
  19619. };
  19620. VirtualJoystick.prototype._onPointerUp = function (e) {
  19621. this._clearCanvas();
  19622. if (this._joystickPointerID == e.pointerId) {
  19623. this._joystickPointerID = -1;
  19624. this.pressed = false;
  19625. }
  19626. this._deltaJoystickVector.x = 0;
  19627. this._deltaJoystickVector.y = 0;
  19628. this._touches.remove(e.pointerId.toString());
  19629. };
  19630. /**
  19631. * Change the color of the virtual joystick
  19632. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19633. */
  19634. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19635. this._joystickColor = newColor;
  19636. };
  19637. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19638. this._action = action;
  19639. };
  19640. // Define which axis you'd like to control for left & right
  19641. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19642. switch (axis) {
  19643. case 0 /* X */:
  19644. case 1 /* Y */:
  19645. case 2 /* Z */:
  19646. this._axisTargetedByLeftAndRight = axis;
  19647. break;
  19648. default:
  19649. this._axisTargetedByLeftAndRight = 0 /* X */;
  19650. break;
  19651. }
  19652. };
  19653. // Define which axis you'd like to control for up & down
  19654. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19655. switch (axis) {
  19656. case 0 /* X */:
  19657. case 1 /* Y */:
  19658. case 2 /* Z */:
  19659. this._axisTargetedByUpAndDown = axis;
  19660. break;
  19661. default:
  19662. this._axisTargetedByUpAndDown = 1 /* Y */;
  19663. break;
  19664. }
  19665. };
  19666. VirtualJoystick.prototype._clearCanvas = function () {
  19667. if (this._leftJoystick) {
  19668. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19669. } else {
  19670. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19671. }
  19672. };
  19673. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19674. var _this = this;
  19675. if (this.pressed) {
  19676. this._clearCanvas();
  19677. this._touches.forEach(function (touch) {
  19678. if (touch.pointerId === _this._joystickPointerID) {
  19679. VirtualJoystick.vjCanvasContext.beginPath();
  19680. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19681. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19682. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19683. VirtualJoystick.vjCanvasContext.stroke();
  19684. VirtualJoystick.vjCanvasContext.beginPath();
  19685. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19686. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19687. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19688. VirtualJoystick.vjCanvasContext.stroke();
  19689. VirtualJoystick.vjCanvasContext.beginPath();
  19690. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19691. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19692. VirtualJoystick.vjCanvasContext.stroke();
  19693. } else {
  19694. VirtualJoystick.vjCanvasContext.beginPath();
  19695. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19696. VirtualJoystick.vjCanvasContext.beginPath();
  19697. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19698. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19699. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19700. VirtualJoystick.vjCanvasContext.stroke();
  19701. }
  19702. ;
  19703. });
  19704. }
  19705. requestAnimationFrame(function () {
  19706. _this._drawVirtualJoystick();
  19707. });
  19708. };
  19709. VirtualJoystick.prototype.releaseCanvas = function () {
  19710. if (VirtualJoystick.vjCanvas) {
  19711. document.body.removeChild(VirtualJoystick.vjCanvas);
  19712. VirtualJoystick.vjCanvas = null;
  19713. }
  19714. };
  19715. VirtualJoystick._globalJoystickIndex = 0;
  19716. return VirtualJoystick;
  19717. })();
  19718. BABYLON.VirtualJoystick = VirtualJoystick;
  19719. })(BABYLON || (BABYLON = {}));
  19720. var BABYLON;
  19721. (function (BABYLON) {
  19722. (function (VirtualJoystick) {
  19723. var Collection = (function () {
  19724. function Collection() {
  19725. this._count = 0;
  19726. this._collection = new Array();
  19727. }
  19728. Collection.prototype.Count = function () {
  19729. return this._count;
  19730. };
  19731. Collection.prototype.add = function (key, item) {
  19732. if (this._collection[key] != undefined) {
  19733. return undefined;
  19734. }
  19735. this._collection[key] = item;
  19736. return ++this._count;
  19737. };
  19738. Collection.prototype.remove = function (key) {
  19739. if (this._collection[key] == undefined) {
  19740. return undefined;
  19741. }
  19742. delete this._collection[key];
  19743. return --this._count;
  19744. };
  19745. Collection.prototype.item = function (key) {
  19746. return this._collection[key];
  19747. };
  19748. Collection.prototype.forEach = function (block) {
  19749. var key;
  19750. for (key in this._collection) {
  19751. if (this._collection.hasOwnProperty(key)) {
  19752. block(this._collection[key]);
  19753. }
  19754. }
  19755. };
  19756. return Collection;
  19757. })();
  19758. VirtualJoystick.Collection = Collection;
  19759. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  19760. var VirtualJoystick = BABYLON.VirtualJoystick;
  19761. })(BABYLON || (BABYLON = {}));
  19762. //# sourceMappingURL=babylon.virtualJoystick.js.map
  19763. var BABYLON;
  19764. (function (BABYLON) {
  19765. var OculusRiftDevKit2013_Metric = {
  19766. HResolution: 1280,
  19767. VResolution: 800,
  19768. HScreenSize: 0.149759993,
  19769. VScreenSize: 0.0935999975,
  19770. VScreenCenter: 0.0467999987,
  19771. EyeToScreenDistance: 0.0410000011,
  19772. LensSeparationDistance: 0.0635000020,
  19773. InterpupillaryDistance: 0.0640000030,
  19774. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19775. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19776. PostProcessScaleFactor: 1.714605507808412,
  19777. LensCenterOffset: 0.151976421
  19778. };
  19779. var _OculusInnerCamera = (function (_super) {
  19780. __extends(_OculusInnerCamera, _super);
  19781. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  19782. _super.call(this, name, position, scene);
  19783. this._workMatrix = new BABYLON.Matrix();
  19784. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19785. // Constants
  19786. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19787. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19788. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19789. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19790. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19791. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19792. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19793. // Postprocess
  19794. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19795. }
  19796. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  19797. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19798. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19799. return this._projectionMatrix;
  19800. };
  19801. _OculusInnerCamera.prototype._getViewMatrix = function () {
  19802. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19803. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19804. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19805. // Computing target and final matrix
  19806. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19807. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19808. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19809. return this._viewMatrix;
  19810. };
  19811. return _OculusInnerCamera;
  19812. })(BABYLON.FreeCamera);
  19813. var OculusCamera = (function (_super) {
  19814. __extends(OculusCamera, _super);
  19815. function OculusCamera(name, position, scene) {
  19816. _super.call(this, name, position, scene);
  19817. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  19818. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  19819. this.subCameras.push(this._leftCamera);
  19820. this.subCameras.push(this._rightCamera);
  19821. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19822. }
  19823. OculusCamera.prototype._update = function () {
  19824. this._leftCamera.position.copyFrom(this.position);
  19825. this._rightCamera.position.copyFrom(this.position);
  19826. this._updateCamera(this._leftCamera);
  19827. this._updateCamera(this._rightCamera);
  19828. _super.prototype._update.call(this);
  19829. };
  19830. OculusCamera.prototype._updateCamera = function (camera) {
  19831. camera.minZ = this.minZ;
  19832. camera.maxZ = this.maxZ;
  19833. camera.rotation.x = this.rotation.x;
  19834. camera.rotation.y = this.rotation.y;
  19835. camera.rotation.z = this.rotation.z;
  19836. };
  19837. // Oculus events
  19838. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19839. var yaw = evt.alpha / 180 * Math.PI;
  19840. var pitch = evt.beta / 180 * Math.PI;
  19841. var roll = evt.gamma / 180 * Math.PI;
  19842. if (!this._offsetOrientation) {
  19843. this._offsetOrientation = {
  19844. yaw: yaw,
  19845. pitch: pitch,
  19846. roll: roll
  19847. };
  19848. return;
  19849. } else {
  19850. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19851. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19852. this.rotation.z += this._offsetOrientation.roll - roll;
  19853. this._offsetOrientation.yaw = yaw;
  19854. this._offsetOrientation.pitch = pitch;
  19855. this._offsetOrientation.roll = roll;
  19856. }
  19857. };
  19858. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19859. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19860. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19861. };
  19862. OculusCamera.prototype.detachControl = function (element) {
  19863. _super.prototype.detachControl.call(this, element);
  19864. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19865. };
  19866. return OculusCamera;
  19867. })(BABYLON.FreeCamera);
  19868. BABYLON.OculusCamera = OculusCamera;
  19869. })(BABYLON || (BABYLON = {}));
  19870. //# sourceMappingURL=babylon.oculusCamera.js.map
  19871. var BABYLON;
  19872. (function (BABYLON) {
  19873. var OculusRiftDevKit2013_Metric = {
  19874. HResolution: 1280,
  19875. VResolution: 800,
  19876. HScreenSize: 0.149759993,
  19877. VScreenSize: 0.0935999975,
  19878. VScreenCenter: 0.0467999987,
  19879. EyeToScreenDistance: 0.0410000011,
  19880. LensSeparationDistance: 0.0635000020,
  19881. InterpupillaryDistance: 0.0640000030,
  19882. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19883. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19884. PostProcessScaleFactor: 1.714605507808412,
  19885. LensCenterOffset: 0.151976421
  19886. };
  19887. var _OculusInnerGamepadCamera = (function (_super) {
  19888. __extends(_OculusInnerGamepadCamera, _super);
  19889. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19890. _super.call(this, name, position, scene);
  19891. this._workMatrix = new BABYLON.Matrix();
  19892. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19893. // Constants
  19894. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19895. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19896. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19897. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19898. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19899. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19900. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19901. // Postprocess
  19902. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19903. }
  19904. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19905. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19906. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19907. return this._projectionMatrix;
  19908. };
  19909. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19910. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19911. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19912. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19913. // Computing target and final matrix
  19914. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19915. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19916. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19917. return this._viewMatrix;
  19918. };
  19919. return _OculusInnerGamepadCamera;
  19920. })(BABYLON.FreeCamera);
  19921. var OculusGamepadCamera = (function (_super) {
  19922. __extends(OculusGamepadCamera, _super);
  19923. function OculusGamepadCamera(name, position, scene) {
  19924. var _this = this;
  19925. _super.call(this, name, position, scene);
  19926. this.angularSensibility = 200;
  19927. this.moveSensibility = 75;
  19928. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19929. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19930. this.subCameras.push(this._leftCamera);
  19931. this.subCameras.push(this._rightCamera);
  19932. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19933. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19934. _this._onNewGameConnected(gamepad);
  19935. });
  19936. }
  19937. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19938. // Only the first gamepad can control the camera
  19939. if (gamepad.index === 0) {
  19940. this._gamepad = gamepad;
  19941. }
  19942. };
  19943. OculusGamepadCamera.prototype._update = function () {
  19944. this._leftCamera.position.copyFrom(this.position);
  19945. this._rightCamera.position.copyFrom(this.position);
  19946. this._updateCamera(this._leftCamera);
  19947. this._updateCamera(this._rightCamera);
  19948. _super.prototype._update.call(this);
  19949. };
  19950. OculusGamepadCamera.prototype._checkInputs = function () {
  19951. if (!this._gamepad) {
  19952. return;
  19953. }
  19954. var LSValues = this._gamepad.leftStick;
  19955. var normalizedLX = LSValues.x / this.moveSensibility;
  19956. var normalizedLY = LSValues.y / this.moveSensibility;
  19957. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19958. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19959. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19960. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19961. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19962. };
  19963. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19964. camera.minZ = this.minZ;
  19965. camera.maxZ = this.maxZ;
  19966. camera.rotation.x = this.rotation.x;
  19967. camera.rotation.y = this.rotation.y;
  19968. camera.rotation.z = this.rotation.z;
  19969. };
  19970. // Oculus events
  19971. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19972. var yaw = evt.alpha / 180 * Math.PI;
  19973. var pitch = evt.beta / 180 * Math.PI;
  19974. var roll = evt.gamma / 180 * Math.PI;
  19975. if (!this._offsetOrientation) {
  19976. this._offsetOrientation = {
  19977. yaw: yaw,
  19978. pitch: pitch,
  19979. roll: roll
  19980. };
  19981. return;
  19982. } else {
  19983. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19984. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19985. this.rotation.z += this._offsetOrientation.roll - roll;
  19986. this._offsetOrientation.yaw = yaw;
  19987. this._offsetOrientation.pitch = pitch;
  19988. this._offsetOrientation.roll = roll;
  19989. }
  19990. };
  19991. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19992. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19993. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19994. };
  19995. OculusGamepadCamera.prototype.detachControl = function (element) {
  19996. _super.prototype.detachControl.call(this, element);
  19997. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19998. };
  19999. OculusGamepadCamera.prototype.dispose = function () {
  20000. this._gamepads.dispose();
  20001. _super.prototype.dispose.call(this);
  20002. };
  20003. return OculusGamepadCamera;
  20004. })(BABYLON.FreeCamera);
  20005. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20006. })(BABYLON || (BABYLON = {}));
  20007. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20008. var BABYLON;
  20009. (function (BABYLON) {
  20010. // We're mainly based on the logic defined into the FreeCamera code
  20011. var VirtualJoysticksCamera = (function (_super) {
  20012. __extends(VirtualJoysticksCamera, _super);
  20013. function VirtualJoysticksCamera(name, position, scene) {
  20014. _super.call(this, name, position, scene);
  20015. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20016. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20017. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20018. this._leftjoystick.setJoystickSensibility(0.15);
  20019. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20020. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20021. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20022. this._rightjoystick.reverseUpDown = true;
  20023. this._rightjoystick.setJoystickSensibility(0.05);
  20024. this._rightjoystick.setJoystickColor("yellow");
  20025. }
  20026. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20027. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20028. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20029. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20030. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20031. if (!this._leftjoystick.pressed) {
  20032. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20033. }
  20034. if (!this._rightjoystick.pressed) {
  20035. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20036. }
  20037. };
  20038. VirtualJoysticksCamera.prototype.dispose = function () {
  20039. this._leftjoystick.releaseCanvas();
  20040. _super.prototype.dispose.call(this);
  20041. };
  20042. return VirtualJoysticksCamera;
  20043. })(BABYLON.FreeCamera);
  20044. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20045. })(BABYLON || (BABYLON = {}));
  20046. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20047. var BABYLON;
  20048. (function (BABYLON) {
  20049. var ShaderMaterial = (function (_super) {
  20050. __extends(ShaderMaterial, _super);
  20051. function ShaderMaterial(name, scene, shaderPath, options) {
  20052. _super.call(this, name, scene);
  20053. this._textures = new Array();
  20054. this._floats = new Array();
  20055. this._floatsArrays = {};
  20056. this._colors3 = new Array();
  20057. this._colors4 = new Array();
  20058. this._vectors2 = new Array();
  20059. this._vectors3 = new Array();
  20060. this._matrices = new Array();
  20061. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20062. this._shaderPath = shaderPath;
  20063. options.needAlphaBlending = options.needAlphaBlending || false;
  20064. options.needAlphaTesting = options.needAlphaTesting || false;
  20065. options.attributes = options.attributes || ["position", "normal", "uv"];
  20066. options.uniforms = options.uniforms || ["worldViewProjection"];
  20067. options.samplers = options.samplers || [];
  20068. this._options = options;
  20069. }
  20070. ShaderMaterial.prototype.needAlphaBlending = function () {
  20071. return this._options.needAlphaBlending;
  20072. };
  20073. ShaderMaterial.prototype.needAlphaTesting = function () {
  20074. return this._options.needAlphaTesting;
  20075. };
  20076. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20077. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20078. this._options.uniforms.push(uniformName);
  20079. }
  20080. };
  20081. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20082. if (this._options.samplers.indexOf(name) === -1) {
  20083. this._options.samplers.push(name);
  20084. }
  20085. this._textures[name] = texture;
  20086. return this;
  20087. };
  20088. ShaderMaterial.prototype.setFloat = function (name, value) {
  20089. this._checkUniform(name);
  20090. this._floats[name] = value;
  20091. return this;
  20092. };
  20093. ShaderMaterial.prototype.setFloats = function (name, value) {
  20094. this._checkUniform(name);
  20095. this._floatsArrays[name] = value;
  20096. return this;
  20097. };
  20098. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20099. this._checkUniform(name);
  20100. this._colors3[name] = value;
  20101. return this;
  20102. };
  20103. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20104. this._checkUniform(name);
  20105. this._colors4[name] = value;
  20106. return this;
  20107. };
  20108. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20109. this._checkUniform(name);
  20110. this._vectors2[name] = value;
  20111. return this;
  20112. };
  20113. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20114. this._checkUniform(name);
  20115. this._vectors3[name] = value;
  20116. return this;
  20117. };
  20118. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20119. this._checkUniform(name);
  20120. this._matrices[name] = value;
  20121. return this;
  20122. };
  20123. ShaderMaterial.prototype.isReady = function () {
  20124. var scene = this.getScene();
  20125. var engine = scene.getEngine();
  20126. if (!this.checkReadyOnEveryCall) {
  20127. if (this._renderId === scene.getRenderId()) {
  20128. return true;
  20129. }
  20130. }
  20131. var previousEffect = this._effect;
  20132. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20133. if (!this._effect.isReady()) {
  20134. return false;
  20135. }
  20136. if (previousEffect !== this._effect) {
  20137. scene.resetCachedMaterial();
  20138. }
  20139. this._renderId = scene.getRenderId();
  20140. return true;
  20141. };
  20142. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20143. var scene = this.getScene();
  20144. if (this._options.uniforms.indexOf("world") !== -1) {
  20145. this._effect.setMatrix("world", world);
  20146. }
  20147. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20148. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20149. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20150. }
  20151. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20152. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20153. }
  20154. };
  20155. ShaderMaterial.prototype.bind = function (world) {
  20156. // Std values
  20157. this.bindOnlyWorldMatrix(world);
  20158. if (this.getScene().getCachedMaterial() !== this) {
  20159. if (this._options.uniforms.indexOf("view") !== -1) {
  20160. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20161. }
  20162. if (this._options.uniforms.indexOf("projection") !== -1) {
  20163. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20164. }
  20165. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20166. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20167. }
  20168. for (var name in this._textures) {
  20169. this._effect.setTexture(name, this._textures[name]);
  20170. }
  20171. for (name in this._floats) {
  20172. this._effect.setFloat(name, this._floats[name]);
  20173. }
  20174. for (name in this._floatsArrays) {
  20175. this._effect.setArray(name, this._floatsArrays[name]);
  20176. }
  20177. for (name in this._colors3) {
  20178. this._effect.setColor3(name, this._colors3[name]);
  20179. }
  20180. for (name in this._colors4) {
  20181. var color = this._colors4[name];
  20182. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20183. }
  20184. for (name in this._vectors2) {
  20185. this._effect.setVector2(name, this._vectors2[name]);
  20186. }
  20187. for (name in this._vectors3) {
  20188. this._effect.setVector3(name, this._vectors3[name]);
  20189. }
  20190. for (name in this._matrices) {
  20191. this._effect.setMatrix(name, this._matrices[name]);
  20192. }
  20193. }
  20194. _super.prototype.bind.call(this, world, null);
  20195. };
  20196. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20197. for (var name in this._textures) {
  20198. this._textures[name].dispose();
  20199. }
  20200. this._textures = [];
  20201. _super.prototype.dispose.call(this, forceDisposeEffect);
  20202. };
  20203. return ShaderMaterial;
  20204. })(BABYLON.Material);
  20205. BABYLON.ShaderMaterial = ShaderMaterial;
  20206. })(BABYLON || (BABYLON = {}));
  20207. //# sourceMappingURL=babylon.shaderMaterial.js.map
  20208. var BABYLON;
  20209. (function (BABYLON) {
  20210. var VertexData = (function () {
  20211. function VertexData() {
  20212. }
  20213. VertexData.prototype.set = function (data, kind) {
  20214. switch (kind) {
  20215. case BABYLON.VertexBuffer.PositionKind:
  20216. this.positions = data;
  20217. break;
  20218. case BABYLON.VertexBuffer.NormalKind:
  20219. this.normals = data;
  20220. break;
  20221. case BABYLON.VertexBuffer.UVKind:
  20222. this.uvs = data;
  20223. break;
  20224. case BABYLON.VertexBuffer.UV2Kind:
  20225. this.uv2s = data;
  20226. break;
  20227. case BABYLON.VertexBuffer.ColorKind:
  20228. this.colors = data;
  20229. break;
  20230. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20231. this.matricesIndices = data;
  20232. break;
  20233. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20234. this.matricesWeights = data;
  20235. break;
  20236. }
  20237. };
  20238. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20239. this._applyTo(mesh, updatable);
  20240. };
  20241. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20242. this._applyTo(geometry, updatable);
  20243. };
  20244. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20245. this._update(mesh);
  20246. };
  20247. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20248. this._update(geometry);
  20249. };
  20250. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20251. if (this.positions) {
  20252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20253. }
  20254. if (this.normals) {
  20255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20256. }
  20257. if (this.uvs) {
  20258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20259. }
  20260. if (this.uv2s) {
  20261. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20262. }
  20263. if (this.colors) {
  20264. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20265. }
  20266. if (this.matricesIndices) {
  20267. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20268. }
  20269. if (this.matricesWeights) {
  20270. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20271. }
  20272. if (this.indices) {
  20273. meshOrGeometry.setIndices(this.indices);
  20274. }
  20275. };
  20276. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20277. if (this.positions) {
  20278. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20279. }
  20280. if (this.normals) {
  20281. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20282. }
  20283. if (this.uvs) {
  20284. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20285. }
  20286. if (this.uv2s) {
  20287. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20288. }
  20289. if (this.colors) {
  20290. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20291. }
  20292. if (this.matricesIndices) {
  20293. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20294. }
  20295. if (this.matricesWeights) {
  20296. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20297. }
  20298. if (this.indices) {
  20299. meshOrGeometry.setIndices(this.indices);
  20300. }
  20301. };
  20302. VertexData.prototype.transform = function (matrix) {
  20303. var transformed = BABYLON.Vector3.Zero();
  20304. if (this.positions) {
  20305. var position = BABYLON.Vector3.Zero();
  20306. for (var index = 0; index < this.positions.length; index += 3) {
  20307. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20308. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20309. this.positions[index] = transformed.x;
  20310. this.positions[index + 1] = transformed.y;
  20311. this.positions[index + 2] = transformed.z;
  20312. }
  20313. }
  20314. if (this.normals) {
  20315. var normal = BABYLON.Vector3.Zero();
  20316. for (index = 0; index < this.normals.length; index += 3) {
  20317. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20318. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20319. this.normals[index] = transformed.x;
  20320. this.normals[index + 1] = transformed.y;
  20321. this.normals[index + 2] = transformed.z;
  20322. }
  20323. }
  20324. };
  20325. VertexData.prototype.merge = function (other) {
  20326. if (other.indices) {
  20327. if (!this.indices) {
  20328. this.indices = [];
  20329. }
  20330. var offset = this.positions ? this.positions.length / 3 : 0;
  20331. for (var index = 0; index < other.indices.length; index++) {
  20332. this.indices.push(other.indices[index] + offset);
  20333. }
  20334. }
  20335. if (other.positions) {
  20336. if (!this.positions) {
  20337. this.positions = [];
  20338. }
  20339. for (index = 0; index < other.positions.length; index++) {
  20340. this.positions.push(other.positions[index]);
  20341. }
  20342. }
  20343. if (other.normals) {
  20344. if (!this.normals) {
  20345. this.normals = [];
  20346. }
  20347. for (index = 0; index < other.normals.length; index++) {
  20348. this.normals.push(other.normals[index]);
  20349. }
  20350. }
  20351. if (other.uvs) {
  20352. if (!this.uvs) {
  20353. this.uvs = [];
  20354. }
  20355. for (index = 0; index < other.uvs.length; index++) {
  20356. this.uvs.push(other.uvs[index]);
  20357. }
  20358. }
  20359. if (other.uv2s) {
  20360. if (!this.uv2s) {
  20361. this.uv2s = [];
  20362. }
  20363. for (index = 0; index < other.uv2s.length; index++) {
  20364. this.uv2s.push(other.uv2s[index]);
  20365. }
  20366. }
  20367. if (other.matricesIndices) {
  20368. if (!this.matricesIndices) {
  20369. this.matricesIndices = [];
  20370. }
  20371. for (index = 0; index < other.matricesIndices.length; index++) {
  20372. this.matricesIndices.push(other.matricesIndices[index]);
  20373. }
  20374. }
  20375. if (other.matricesWeights) {
  20376. if (!this.matricesWeights) {
  20377. this.matricesWeights = [];
  20378. }
  20379. for (index = 0; index < other.matricesWeights.length; index++) {
  20380. this.matricesWeights.push(other.matricesWeights[index]);
  20381. }
  20382. }
  20383. if (other.colors) {
  20384. if (!this.colors) {
  20385. this.colors = [];
  20386. }
  20387. for (index = 0; index < other.colors.length; index++) {
  20388. this.colors.push(other.colors[index]);
  20389. }
  20390. }
  20391. };
  20392. // Statics
  20393. VertexData.ExtractFromMesh = function (mesh) {
  20394. return VertexData._ExtractFrom(mesh);
  20395. };
  20396. VertexData.ExtractFromGeometry = function (geometry) {
  20397. return VertexData._ExtractFrom(geometry);
  20398. };
  20399. VertexData._ExtractFrom = function (meshOrGeometry) {
  20400. var result = new BABYLON.VertexData();
  20401. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20402. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20403. }
  20404. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20405. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20406. }
  20407. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20408. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20409. }
  20410. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20411. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20412. }
  20413. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20414. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20415. }
  20416. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20417. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20418. }
  20419. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20420. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20421. }
  20422. result.indices = meshOrGeometry.getIndices();
  20423. return result;
  20424. };
  20425. VertexData.CreateBox = function (size) {
  20426. var normalsSource = [
  20427. new BABYLON.Vector3(0, 0, 1),
  20428. new BABYLON.Vector3(0, 0, -1),
  20429. new BABYLON.Vector3(1, 0, 0),
  20430. new BABYLON.Vector3(-1, 0, 0),
  20431. new BABYLON.Vector3(0, 1, 0),
  20432. new BABYLON.Vector3(0, -1, 0)
  20433. ];
  20434. var indices = [];
  20435. var positions = [];
  20436. var normals = [];
  20437. var uvs = [];
  20438. size = size || 1;
  20439. for (var index = 0; index < normalsSource.length; index++) {
  20440. var normal = normalsSource[index];
  20441. // Get two vectors perpendicular to the face normal and to each other.
  20442. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20443. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20444. // Six indices (two triangles) per face.
  20445. var verticesLength = positions.length / 3;
  20446. indices.push(verticesLength);
  20447. indices.push(verticesLength + 1);
  20448. indices.push(verticesLength + 2);
  20449. indices.push(verticesLength);
  20450. indices.push(verticesLength + 2);
  20451. indices.push(verticesLength + 3);
  20452. // Four vertices per face.
  20453. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20454. positions.push(vertex.x, vertex.y, vertex.z);
  20455. normals.push(normal.x, normal.y, normal.z);
  20456. uvs.push(1.0, 1.0);
  20457. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20458. positions.push(vertex.x, vertex.y, vertex.z);
  20459. normals.push(normal.x, normal.y, normal.z);
  20460. uvs.push(0.0, 1.0);
  20461. vertex = normal.add(side1).add(side2).scale(size / 2);
  20462. positions.push(vertex.x, vertex.y, vertex.z);
  20463. normals.push(normal.x, normal.y, normal.z);
  20464. uvs.push(0.0, 0.0);
  20465. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20466. positions.push(vertex.x, vertex.y, vertex.z);
  20467. normals.push(normal.x, normal.y, normal.z);
  20468. uvs.push(1.0, 0.0);
  20469. }
  20470. // Result
  20471. var vertexData = new BABYLON.VertexData();
  20472. vertexData.indices = indices;
  20473. vertexData.positions = positions;
  20474. vertexData.normals = normals;
  20475. vertexData.uvs = uvs;
  20476. return vertexData;
  20477. };
  20478. VertexData.CreateSphere = function (segments, diameter) {
  20479. segments = segments || 32;
  20480. diameter = diameter || 1;
  20481. var radius = diameter / 2;
  20482. var totalZRotationSteps = 2 + segments;
  20483. var totalYRotationSteps = 2 * totalZRotationSteps;
  20484. var indices = [];
  20485. var positions = [];
  20486. var normals = [];
  20487. var uvs = [];
  20488. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20489. var normalizedZ = zRotationStep / totalZRotationSteps;
  20490. var angleZ = (normalizedZ * Math.PI);
  20491. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20492. var normalizedY = yRotationStep / totalYRotationSteps;
  20493. var angleY = normalizedY * Math.PI * 2;
  20494. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20495. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20496. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20497. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20498. var vertex = complete.scale(radius);
  20499. var normal = BABYLON.Vector3.Normalize(vertex);
  20500. positions.push(vertex.x, vertex.y, vertex.z);
  20501. normals.push(normal.x, normal.y, normal.z);
  20502. uvs.push(normalizedZ, normalizedY);
  20503. }
  20504. if (zRotationStep > 0) {
  20505. var verticesCount = positions.length / 3;
  20506. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20507. indices.push((firstIndex));
  20508. indices.push((firstIndex + 1));
  20509. indices.push(firstIndex + totalYRotationSteps + 1);
  20510. indices.push((firstIndex + totalYRotationSteps + 1));
  20511. indices.push((firstIndex + 1));
  20512. indices.push((firstIndex + totalYRotationSteps + 2));
  20513. }
  20514. }
  20515. }
  20516. // Result
  20517. var vertexData = new BABYLON.VertexData();
  20518. vertexData.indices = indices;
  20519. vertexData.positions = positions;
  20520. vertexData.normals = normals;
  20521. vertexData.uvs = uvs;
  20522. return vertexData;
  20523. };
  20524. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20525. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20526. var radiusTop = diameterTop / 2;
  20527. var radiusBottom = diameterBottom / 2;
  20528. var indices = [];
  20529. var positions = [];
  20530. var normals = [];
  20531. var uvs = [];
  20532. height = height || 1;
  20533. diameterTop = diameterTop || 0.5;
  20534. diameterBottom = diameterBottom || 1;
  20535. tessellation = tessellation || 16;
  20536. subdivisions = subdivisions || 1;
  20537. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20538. var getCircleVector = function (i) {
  20539. var angle = (i * 2.0 * Math.PI / tessellation);
  20540. var dx = Math.cos(angle);
  20541. var dz = Math.sin(angle);
  20542. return new BABYLON.Vector3(dx, 0, dz);
  20543. };
  20544. var createCylinderCap = function (isTop) {
  20545. var radius = isTop ? radiusTop : radiusBottom;
  20546. if (radius == 0) {
  20547. return;
  20548. }
  20549. var vbase = positions.length / 3;
  20550. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20551. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20552. if (!isTop) {
  20553. offset.scaleInPlace(-1);
  20554. textureScale.x = -textureScale.x;
  20555. }
  20556. for (i = 0; i < tessellation; i++) {
  20557. var circleVector = getCircleVector(i);
  20558. var position = circleVector.scale(radius).add(offset);
  20559. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20560. positions.push(position.x, position.y, position.z);
  20561. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20562. }
  20563. for (var i = 0; i < tessellation - 2; i++) {
  20564. if (!isTop) {
  20565. indices.push(vbase);
  20566. indices.push(vbase + (i + 2) % tessellation);
  20567. indices.push(vbase + (i + 1) % tessellation);
  20568. } else {
  20569. indices.push(vbase);
  20570. indices.push(vbase + (i + 1) % tessellation);
  20571. indices.push(vbase + (i + 2) % tessellation);
  20572. }
  20573. }
  20574. };
  20575. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20576. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20577. var stride = tessellation + 1;
  20578. for (var i = 0; i <= tessellation; i++) {
  20579. var circleVector = getCircleVector(i);
  20580. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20581. var position, radius = radiusBottom;
  20582. for (var s = 0; s <= subdivisions; s++) {
  20583. // Update variables
  20584. position = circleVector.scale(radius);
  20585. position.addInPlace(base.add(offset.scale(s)));
  20586. textureCoordinate.y += 1 / subdivisions;
  20587. radius += (radiusTop - radiusBottom) / subdivisions;
  20588. // Push in arrays
  20589. positions.push(position.x, position.y, position.z);
  20590. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20591. }
  20592. }
  20593. subdivisions += 1;
  20594. for (var s = 0; s < subdivisions - 1; s++) {
  20595. for (var i = 0; i <= tessellation; i++) {
  20596. indices.push(i * subdivisions + s);
  20597. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20598. indices.push(i * subdivisions + (s + 1));
  20599. indices.push(i * subdivisions + (s + 1));
  20600. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20601. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20602. }
  20603. }
  20604. // Create flat triangle fan caps to seal the top and bottom.
  20605. createCylinderCap(true);
  20606. createCylinderCap(false);
  20607. // Normals
  20608. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20609. // Result
  20610. var vertexData = new BABYLON.VertexData();
  20611. vertexData.indices = indices;
  20612. vertexData.positions = positions;
  20613. vertexData.normals = normals;
  20614. vertexData.uvs = uvs;
  20615. return vertexData;
  20616. };
  20617. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20618. var indices = [];
  20619. var positions = [];
  20620. var normals = [];
  20621. var uvs = [];
  20622. diameter = diameter || 1;
  20623. thickness = thickness || 0.5;
  20624. tessellation = tessellation || 16;
  20625. var stride = tessellation + 1;
  20626. for (var i = 0; i <= tessellation; i++) {
  20627. var u = i / tessellation;
  20628. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20629. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20630. for (var j = 0; j <= tessellation; j++) {
  20631. var v = 1 - j / tessellation;
  20632. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20633. var dx = Math.cos(innerAngle);
  20634. var dy = Math.sin(innerAngle);
  20635. // Create a vertex.
  20636. var normal = new BABYLON.Vector3(dx, dy, 0);
  20637. var position = normal.scale(thickness / 2);
  20638. var textureCoordinate = new BABYLON.Vector2(u, v);
  20639. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20640. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20641. positions.push(position.x, position.y, position.z);
  20642. normals.push(normal.x, normal.y, normal.z);
  20643. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20644. // And create indices for two triangles.
  20645. var nextI = (i + 1) % stride;
  20646. var nextJ = (j + 1) % stride;
  20647. indices.push(i * stride + j);
  20648. indices.push(i * stride + nextJ);
  20649. indices.push(nextI * stride + j);
  20650. indices.push(i * stride + nextJ);
  20651. indices.push(nextI * stride + nextJ);
  20652. indices.push(nextI * stride + j);
  20653. }
  20654. }
  20655. // Result
  20656. var vertexData = new BABYLON.VertexData();
  20657. vertexData.indices = indices;
  20658. vertexData.positions = positions;
  20659. vertexData.normals = normals;
  20660. vertexData.uvs = uvs;
  20661. return vertexData;
  20662. };
  20663. VertexData.CreateLines = function (points) {
  20664. var indices = [];
  20665. var positions = [];
  20666. for (var index = 0; index < points.length; index++) {
  20667. positions.push(points[index].x, points[index].y, points[index].z);
  20668. if (index > 0) {
  20669. indices.push(index - 1);
  20670. indices.push(index);
  20671. }
  20672. }
  20673. // Result
  20674. var vertexData = new BABYLON.VertexData();
  20675. vertexData.indices = indices;
  20676. vertexData.positions = positions;
  20677. return vertexData;
  20678. };
  20679. VertexData.CreateGround = function (width, height, subdivisions) {
  20680. var indices = [];
  20681. var positions = [];
  20682. var normals = [];
  20683. var uvs = [];
  20684. var row, col;
  20685. width = width || 1;
  20686. height = height || 1;
  20687. subdivisions = subdivisions || 1;
  20688. for (row = 0; row <= subdivisions; row++) {
  20689. for (col = 0; col <= subdivisions; col++) {
  20690. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20691. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20692. positions.push(position.x, position.y, position.z);
  20693. normals.push(normal.x, normal.y, normal.z);
  20694. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20695. }
  20696. }
  20697. for (row = 0; row < subdivisions; row++) {
  20698. for (col = 0; col < subdivisions; col++) {
  20699. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20700. indices.push(col + 1 + row * (subdivisions + 1));
  20701. indices.push(col + row * (subdivisions + 1));
  20702. indices.push(col + (row + 1) * (subdivisions + 1));
  20703. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20704. indices.push(col + row * (subdivisions + 1));
  20705. }
  20706. }
  20707. // Result
  20708. var vertexData = new BABYLON.VertexData();
  20709. vertexData.indices = indices;
  20710. vertexData.positions = positions;
  20711. vertexData.normals = normals;
  20712. vertexData.uvs = uvs;
  20713. return vertexData;
  20714. };
  20715. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  20716. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  20717. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  20718. var indices = [];
  20719. var positions = [];
  20720. var normals = [];
  20721. var uvs = [];
  20722. var row, col, tileRow, tileCol;
  20723. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  20724. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  20725. precision.w = (precision.w < 1) ? 1 : precision.w;
  20726. precision.h = (precision.h < 1) ? 1 : precision.h;
  20727. var tileSize = {
  20728. 'w': (xmax - xmin) / subdivisions.w,
  20729. 'h': (zmax - zmin) / subdivisions.h
  20730. };
  20731. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  20732. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  20733. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  20734. }
  20735. }
  20736. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  20737. // Indices
  20738. var base = positions.length / 3;
  20739. var rowLength = precision.w + 1;
  20740. for (row = 0; row < precision.h; row++) {
  20741. for (col = 0; col < precision.w; col++) {
  20742. var square = [
  20743. base + col + row * rowLength,
  20744. base + (col + 1) + row * rowLength,
  20745. base + (col + 1) + (row + 1) * rowLength,
  20746. base + col + (row + 1) * rowLength
  20747. ];
  20748. indices.push(square[1]);
  20749. indices.push(square[2]);
  20750. indices.push(square[3]);
  20751. indices.push(square[0]);
  20752. indices.push(square[1]);
  20753. indices.push(square[3]);
  20754. }
  20755. }
  20756. // Position, normals and uvs
  20757. var position = BABYLON.Vector3.Zero();
  20758. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20759. for (row = 0; row <= precision.h; row++) {
  20760. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  20761. for (col = 0; col <= precision.w; col++) {
  20762. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  20763. position.y = 0;
  20764. positions.push(position.x, position.y, position.z);
  20765. normals.push(normal.x, normal.y, normal.z);
  20766. uvs.push(col / precision.w, row / precision.h);
  20767. }
  20768. }
  20769. }
  20770. // Result
  20771. var vertexData = new BABYLON.VertexData();
  20772. vertexData.indices = indices;
  20773. vertexData.positions = positions;
  20774. vertexData.normals = normals;
  20775. vertexData.uvs = uvs;
  20776. return vertexData;
  20777. };
  20778. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  20779. var indices = [];
  20780. var positions = [];
  20781. var normals = [];
  20782. var uvs = [];
  20783. var row, col;
  20784. for (row = 0; row <= subdivisions; row++) {
  20785. for (col = 0; col <= subdivisions; col++) {
  20786. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20787. // Compute height
  20788. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  20789. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  20790. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  20791. var r = buffer[pos] / 255.0;
  20792. var g = buffer[pos + 1] / 255.0;
  20793. var b = buffer[pos + 2] / 255.0;
  20794. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20795. position.y = minHeight + (maxHeight - minHeight) * gradient;
  20796. // Add vertex
  20797. positions.push(position.x, position.y, position.z);
  20798. normals.push(0, 0, 0);
  20799. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20800. }
  20801. }
  20802. for (row = 0; row < subdivisions; row++) {
  20803. for (col = 0; col < subdivisions; col++) {
  20804. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20805. indices.push(col + 1 + row * (subdivisions + 1));
  20806. indices.push(col + row * (subdivisions + 1));
  20807. indices.push(col + (row + 1) * (subdivisions + 1));
  20808. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20809. indices.push(col + row * (subdivisions + 1));
  20810. }
  20811. }
  20812. // Normals
  20813. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20814. // Result
  20815. var vertexData = new BABYLON.VertexData();
  20816. vertexData.indices = indices;
  20817. vertexData.positions = positions;
  20818. vertexData.normals = normals;
  20819. vertexData.uvs = uvs;
  20820. return vertexData;
  20821. };
  20822. VertexData.CreatePlane = function (size) {
  20823. var indices = [];
  20824. var positions = [];
  20825. var normals = [];
  20826. var uvs = [];
  20827. size = size || 1;
  20828. // Vertices
  20829. var halfSize = size / 2.0;
  20830. positions.push(-halfSize, -halfSize, 0);
  20831. normals.push(0, 0, -1.0);
  20832. uvs.push(0.0, 0.0);
  20833. positions.push(halfSize, -halfSize, 0);
  20834. normals.push(0, 0, -1.0);
  20835. uvs.push(1.0, 0.0);
  20836. positions.push(halfSize, halfSize, 0);
  20837. normals.push(0, 0, -1.0);
  20838. uvs.push(1.0, 1.0);
  20839. positions.push(-halfSize, halfSize, 0);
  20840. normals.push(0, 0, -1.0);
  20841. uvs.push(0.0, 1.0);
  20842. // Indices
  20843. indices.push(0);
  20844. indices.push(1);
  20845. indices.push(2);
  20846. indices.push(0);
  20847. indices.push(2);
  20848. indices.push(3);
  20849. // Result
  20850. var vertexData = new BABYLON.VertexData();
  20851. vertexData.indices = indices;
  20852. vertexData.positions = positions;
  20853. vertexData.normals = normals;
  20854. vertexData.uvs = uvs;
  20855. return vertexData;
  20856. };
  20857. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20858. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20859. var indices = [];
  20860. var positions = [];
  20861. var normals = [];
  20862. var uvs = [];
  20863. radius = radius || 2;
  20864. tube = tube || 0.5;
  20865. radialSegments = radialSegments || 32;
  20866. tubularSegments = tubularSegments || 32;
  20867. p = p || 2;
  20868. q = q || 3;
  20869. // Helper
  20870. var getPos = function (angle) {
  20871. var cu = Math.cos(angle);
  20872. var su = Math.sin(angle);
  20873. var quOverP = q / p * angle;
  20874. var cs = Math.cos(quOverP);
  20875. var tx = radius * (2 + cs) * 0.5 * cu;
  20876. var ty = radius * (2 + cs) * su * 0.5;
  20877. var tz = radius * Math.sin(quOverP) * 0.5;
  20878. return new BABYLON.Vector3(tx, ty, tz);
  20879. };
  20880. for (var i = 0; i <= radialSegments; i++) {
  20881. var modI = i % radialSegments;
  20882. var u = modI / radialSegments * 2 * p * Math.PI;
  20883. var p1 = getPos(u);
  20884. var p2 = getPos(u + 0.01);
  20885. var tang = p2.subtract(p1);
  20886. var n = p2.add(p1);
  20887. var bitan = BABYLON.Vector3.Cross(tang, n);
  20888. n = BABYLON.Vector3.Cross(bitan, tang);
  20889. bitan.normalize();
  20890. n.normalize();
  20891. for (var j = 0; j < tubularSegments; j++) {
  20892. var modJ = j % tubularSegments;
  20893. var v = modJ / tubularSegments * 2 * Math.PI;
  20894. var cx = -tube * Math.cos(v);
  20895. var cy = tube * Math.sin(v);
  20896. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20897. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20898. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20899. uvs.push(i / radialSegments);
  20900. uvs.push(j / tubularSegments);
  20901. }
  20902. }
  20903. for (i = 0; i < radialSegments; i++) {
  20904. for (j = 0; j < tubularSegments; j++) {
  20905. var jNext = (j + 1) % tubularSegments;
  20906. var a = i * tubularSegments + j;
  20907. var b = (i + 1) * tubularSegments + j;
  20908. var c = (i + 1) * tubularSegments + jNext;
  20909. var d = i * tubularSegments + jNext;
  20910. indices.push(d);
  20911. indices.push(b);
  20912. indices.push(a);
  20913. indices.push(d);
  20914. indices.push(c);
  20915. indices.push(b);
  20916. }
  20917. }
  20918. // Normals
  20919. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20920. // Result
  20921. var vertexData = new BABYLON.VertexData();
  20922. vertexData.indices = indices;
  20923. vertexData.positions = positions;
  20924. vertexData.normals = normals;
  20925. vertexData.uvs = uvs;
  20926. return vertexData;
  20927. };
  20928. // Tools
  20929. VertexData.ComputeNormals = function (positions, indices, normals) {
  20930. var positionVectors = [];
  20931. var facesOfVertices = [];
  20932. var index;
  20933. for (index = 0; index < positions.length; index += 3) {
  20934. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20935. positionVectors.push(vector3);
  20936. facesOfVertices.push([]);
  20937. }
  20938. // Compute normals
  20939. var facesNormals = [];
  20940. for (index = 0; index < indices.length / 3; index++) {
  20941. var i1 = indices[index * 3];
  20942. var i2 = indices[index * 3 + 1];
  20943. var i3 = indices[index * 3 + 2];
  20944. var p1 = positionVectors[i1];
  20945. var p2 = positionVectors[i2];
  20946. var p3 = positionVectors[i3];
  20947. var p1p2 = p1.subtract(p2);
  20948. var p3p2 = p3.subtract(p2);
  20949. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20950. facesOfVertices[i1].push(index);
  20951. facesOfVertices[i2].push(index);
  20952. facesOfVertices[i3].push(index);
  20953. }
  20954. for (index = 0; index < positionVectors.length; index++) {
  20955. var faces = facesOfVertices[index];
  20956. var normal = BABYLON.Vector3.Zero();
  20957. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20958. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20959. }
  20960. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20961. normals[index * 3] = normal.x;
  20962. normals[index * 3 + 1] = normal.y;
  20963. normals[index * 3 + 2] = normal.z;
  20964. }
  20965. };
  20966. return VertexData;
  20967. })();
  20968. BABYLON.VertexData = VertexData;
  20969. })(BABYLON || (BABYLON = {}));
  20970. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20971. var BABYLON;
  20972. (function (BABYLON) {
  20973. var buildCamera = function (that, name) {
  20974. that._leftCamera.isIntermediate = true;
  20975. that.subCameras.push(that._leftCamera);
  20976. that.subCameras.push(that._rightCamera);
  20977. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20978. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20979. that._anaglyphPostProcess.onApply = function (effect) {
  20980. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20981. };
  20982. that._update();
  20983. };
  20984. var AnaglyphArcRotateCamera = (function (_super) {
  20985. __extends(AnaglyphArcRotateCamera, _super);
  20986. // ANY
  20987. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20988. _super.call(this, name, alpha, beta, radius, target, scene);
  20989. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20990. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20991. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20992. buildCamera(this, name);
  20993. }
  20994. AnaglyphArcRotateCamera.prototype._update = function () {
  20995. this._updateCamera(this._leftCamera);
  20996. this._updateCamera(this._rightCamera);
  20997. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20998. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20999. _super.prototype._update.call(this);
  21000. };
  21001. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21002. camera.beta = this.beta;
  21003. camera.radius = this.radius;
  21004. camera.minZ = this.minZ;
  21005. camera.maxZ = this.maxZ;
  21006. camera.fov = this.fov;
  21007. camera.target = this.target;
  21008. };
  21009. return AnaglyphArcRotateCamera;
  21010. })(BABYLON.ArcRotateCamera);
  21011. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21012. var AnaglyphFreeCamera = (function (_super) {
  21013. __extends(AnaglyphFreeCamera, _super);
  21014. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21015. _super.call(this, name, position, scene);
  21016. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21017. this._transformMatrix = new BABYLON.Matrix();
  21018. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21019. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21020. buildCamera(this, name);
  21021. }
  21022. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21023. var target = this.getTarget();
  21024. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21025. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21026. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21027. };
  21028. AnaglyphFreeCamera.prototype._update = function () {
  21029. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21030. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21031. this._updateCamera(this._leftCamera);
  21032. this._updateCamera(this._rightCamera);
  21033. _super.prototype._update.call(this);
  21034. };
  21035. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21036. camera.minZ = this.minZ;
  21037. camera.maxZ = this.maxZ;
  21038. camera.fov = this.fov;
  21039. camera.viewport = this.viewport;
  21040. camera.setTarget(this.getTarget());
  21041. };
  21042. return AnaglyphFreeCamera;
  21043. })(BABYLON.FreeCamera);
  21044. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21045. })(BABYLON || (BABYLON = {}));
  21046. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21047. var BABYLON;
  21048. (function (BABYLON) {
  21049. var AnaglyphPostProcess = (function (_super) {
  21050. __extends(AnaglyphPostProcess, _super);
  21051. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21052. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21053. }
  21054. return AnaglyphPostProcess;
  21055. })(BABYLON.PostProcess);
  21056. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21057. })(BABYLON || (BABYLON = {}));
  21058. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  21059. var BABYLON;
  21060. (function (BABYLON) {
  21061. var Tags = (function () {
  21062. function Tags() {
  21063. }
  21064. Tags.EnableFor = function (obj) {
  21065. obj._tags = obj._tags || {};
  21066. obj.hasTags = function () {
  21067. return Tags.HasTags(obj);
  21068. };
  21069. obj.addTags = function (tagsString) {
  21070. return Tags.AddTagsTo(obj, tagsString);
  21071. };
  21072. obj.removeTags = function (tagsString) {
  21073. return Tags.RemoveTagsFrom(obj, tagsString);
  21074. };
  21075. obj.matchesTagsQuery = function (tagsQuery) {
  21076. return Tags.MatchesQuery(obj, tagsQuery);
  21077. };
  21078. };
  21079. Tags.DisableFor = function (obj) {
  21080. delete obj._tags;
  21081. delete obj.hasTags;
  21082. delete obj.addTags;
  21083. delete obj.removeTags;
  21084. delete obj.matchesTagsQuery;
  21085. };
  21086. Tags.HasTags = function (obj) {
  21087. if (!obj._tags) {
  21088. return false;
  21089. }
  21090. return !BABYLON.Tools.IsEmpty(obj._tags);
  21091. };
  21092. Tags.GetTags = function (obj) {
  21093. if (!obj._tags) {
  21094. return null;
  21095. }
  21096. return obj._tags;
  21097. };
  21098. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21099. // a tag cannot start with '||', '&&', and '!'
  21100. // it cannot contain whitespaces
  21101. Tags.AddTagsTo = function (obj, tagsString) {
  21102. if (!tagsString) {
  21103. return;
  21104. }
  21105. var tags = tagsString.split(" ");
  21106. for (var t in tags) {
  21107. Tags._AddTagTo(obj, tags[t]);
  21108. }
  21109. };
  21110. Tags._AddTagTo = function (obj, tag) {
  21111. tag = tag.trim();
  21112. if (tag === "" || tag === "true" || tag === "false") {
  21113. return;
  21114. }
  21115. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21116. return;
  21117. }
  21118. Tags.EnableFor(obj);
  21119. obj._tags[tag] = true;
  21120. };
  21121. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21122. if (!Tags.HasTags(obj)) {
  21123. return;
  21124. }
  21125. var tags = tagsString.split(" ");
  21126. for (var t in tags) {
  21127. Tags._RemoveTagFrom(obj, tags[t]);
  21128. }
  21129. };
  21130. Tags._RemoveTagFrom = function (obj, tag) {
  21131. delete obj._tags[tag];
  21132. };
  21133. Tags.MatchesQuery = function (obj, tagsQuery) {
  21134. if (tagsQuery === undefined) {
  21135. return true;
  21136. }
  21137. if (tagsQuery === "") {
  21138. return Tags.HasTags(obj);
  21139. }
  21140. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  21141. return Tags.HasTags(obj) && obj._tags[r];
  21142. });
  21143. };
  21144. return Tags;
  21145. })();
  21146. BABYLON.Tags = Tags;
  21147. })(BABYLON || (BABYLON = {}));
  21148. //# sourceMappingURL=babylon.tags.js.map
  21149. var BABYLON;
  21150. (function (BABYLON) {
  21151. (function (Internals) {
  21152. var AndOrNotEvaluator = (function () {
  21153. function AndOrNotEvaluator() {
  21154. }
  21155. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21156. if (!query.match(/\([^\(\)]*\)/g)) {
  21157. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21158. } else {
  21159. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21160. // remove parenthesis
  21161. r = r.slice(1, r.length - 1);
  21162. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21163. });
  21164. }
  21165. if (query === "true") {
  21166. return true;
  21167. }
  21168. if (query === "false") {
  21169. return false;
  21170. }
  21171. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21172. };
  21173. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21174. evaluateCallback = evaluateCallback || (function (r) {
  21175. return r === "true" ? true : false;
  21176. });
  21177. var result;
  21178. var or = parenthesisContent.split("||");
  21179. for (var i in or) {
  21180. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21181. var and = ori.split("&&");
  21182. if (and.length > 1) {
  21183. for (var j = 0; j < and.length; ++j) {
  21184. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21185. if (andj !== "true" && andj !== "false") {
  21186. if (andj[0] === "!") {
  21187. result = !evaluateCallback(andj.substring(1));
  21188. } else {
  21189. result = evaluateCallback(andj);
  21190. }
  21191. } else {
  21192. result = andj === "true" ? true : false;
  21193. }
  21194. if (!result) {
  21195. ori = "false";
  21196. break;
  21197. }
  21198. }
  21199. }
  21200. if (result || ori === "true") {
  21201. result = true;
  21202. break;
  21203. }
  21204. // result equals false (or undefined)
  21205. if (ori !== "true" && ori !== "false") {
  21206. if (ori[0] === "!") {
  21207. result = !evaluateCallback(ori.substring(1));
  21208. } else {
  21209. result = evaluateCallback(ori);
  21210. }
  21211. } else {
  21212. result = ori === "true" ? true : false;
  21213. }
  21214. }
  21215. // the whole parenthesis scope is replaced by 'true' or 'false'
  21216. return result ? "true" : "false";
  21217. };
  21218. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21219. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21220. // remove whitespaces
  21221. r = r.replace(/[\s]/g, function () {
  21222. return "";
  21223. });
  21224. return r.length % 2 ? "!" : "";
  21225. });
  21226. booleanString = booleanString.trim();
  21227. if (booleanString === "!true") {
  21228. booleanString = "false";
  21229. } else if (booleanString === "!false") {
  21230. booleanString = "true";
  21231. }
  21232. return booleanString;
  21233. };
  21234. return AndOrNotEvaluator;
  21235. })();
  21236. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21237. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21238. var Internals = BABYLON.Internals;
  21239. })(BABYLON || (BABYLON = {}));
  21240. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  21241. var BABYLON;
  21242. (function (BABYLON) {
  21243. var PostProcessRenderPass = (function () {
  21244. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21245. this._enabled = true;
  21246. this._refCount = 0;
  21247. this._name = name;
  21248. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21249. this.setRenderList(renderList);
  21250. this._renderTexture.onBeforeRender = beforeRender;
  21251. this._renderTexture.onAfterRender = afterRender;
  21252. this._scene = scene;
  21253. this._renderList = renderList;
  21254. }
  21255. // private
  21256. PostProcessRenderPass.prototype._incRefCount = function () {
  21257. if (this._refCount === 0) {
  21258. this._scene.customRenderTargets.push(this._renderTexture);
  21259. }
  21260. return ++this._refCount;
  21261. };
  21262. PostProcessRenderPass.prototype._decRefCount = function () {
  21263. this._refCount--;
  21264. if (this._refCount <= 0) {
  21265. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21266. }
  21267. return this._refCount;
  21268. };
  21269. PostProcessRenderPass.prototype._update = function () {
  21270. this.setRenderList(this._renderList);
  21271. };
  21272. // public
  21273. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21274. this._renderTexture.renderList = renderList;
  21275. };
  21276. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21277. return this._renderTexture;
  21278. };
  21279. return PostProcessRenderPass;
  21280. })();
  21281. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21282. })(BABYLON || (BABYLON = {}));
  21283. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  21284. var BABYLON;
  21285. (function (BABYLON) {
  21286. var PostProcessRenderEffect = (function () {
  21287. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21288. this._engine = engine;
  21289. this._name = name;
  21290. this._singleInstance = singleInstance || true;
  21291. this._getPostProcess = getPostProcess;
  21292. this._cameras = [];
  21293. this._indicesForCamera = [];
  21294. this._postProcesses = {};
  21295. this._renderPasses = {};
  21296. this._renderEffectAsPasses = {};
  21297. }
  21298. PostProcessRenderEffect.prototype._update = function () {
  21299. for (var renderPassName in this._renderPasses) {
  21300. this._renderPasses[renderPassName]._update();
  21301. }
  21302. };
  21303. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21304. this._renderPasses[renderPass._name] = renderPass;
  21305. this._linkParameters();
  21306. };
  21307. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21308. delete this._renderPasses[renderPass._name];
  21309. this._linkParameters();
  21310. };
  21311. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21312. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21313. this._linkParameters();
  21314. };
  21315. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21316. for (var renderPassName in this._renderPasses) {
  21317. if (renderPassName === passName) {
  21318. return this._renderPasses[passName];
  21319. }
  21320. }
  21321. };
  21322. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21323. this._renderPasses = {};
  21324. this._linkParameters();
  21325. };
  21326. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21327. var cameraKey;
  21328. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21329. for (var i = 0; i < _cam.length; i++) {
  21330. var camera = _cam[i];
  21331. var cameraName = camera.name;
  21332. if (this._singleInstance) {
  21333. cameraKey = 0;
  21334. } else {
  21335. cameraKey = cameraName;
  21336. }
  21337. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21338. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21339. if (!this._indicesForCamera[cameraName]) {
  21340. this._indicesForCamera[cameraName] = [];
  21341. }
  21342. this._indicesForCamera[cameraName].push(index);
  21343. if (this._cameras.indexOf(camera) === -1) {
  21344. this._cameras[cameraName] = camera;
  21345. }
  21346. for (var passName in this._renderPasses) {
  21347. this._renderPasses[passName]._incRefCount();
  21348. }
  21349. }
  21350. this._linkParameters();
  21351. };
  21352. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21353. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21354. for (var i = 0; i < _cam.length; i++) {
  21355. var camera = _cam[i];
  21356. var cameraName = camera.name;
  21357. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21358. var index = this._cameras.indexOf(cameraName);
  21359. this._indicesForCamera.splice(index, 1);
  21360. this._cameras.splice(index, 1);
  21361. for (var passName in this._renderPasses) {
  21362. this._renderPasses[passName]._decRefCount();
  21363. }
  21364. }
  21365. };
  21366. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21367. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21368. for (var i = 0; i < _cam.length; i++) {
  21369. var camera = _cam[i];
  21370. var cameraName = camera.name;
  21371. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21372. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21373. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21374. }
  21375. }
  21376. for (var passName in this._renderPasses) {
  21377. this._renderPasses[passName]._incRefCount();
  21378. }
  21379. }
  21380. };
  21381. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21382. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21383. for (var i = 0; i < _cam.length; i++) {
  21384. var camera = _cam[i];
  21385. var cameraName = camera.Name;
  21386. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21387. for (var passName in this._renderPasses) {
  21388. this._renderPasses[passName]._decRefCount();
  21389. }
  21390. }
  21391. };
  21392. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21393. if (this._singleInstance) {
  21394. return this._postProcesses[0];
  21395. } else {
  21396. return this._postProcesses[camera.name];
  21397. }
  21398. };
  21399. PostProcessRenderEffect.prototype._linkParameters = function () {
  21400. var _this = this;
  21401. for (var index in this._postProcesses) {
  21402. if (this.applyParameters) {
  21403. this.applyParameters(this._postProcesses[index]);
  21404. }
  21405. this._postProcesses[index].onBeforeRender = function (effect) {
  21406. _this._linkTextures(effect);
  21407. };
  21408. }
  21409. };
  21410. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21411. for (var renderPassName in this._renderPasses) {
  21412. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21413. }
  21414. for (var renderEffectName in this._renderEffectAsPasses) {
  21415. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21416. }
  21417. };
  21418. return PostProcessRenderEffect;
  21419. })();
  21420. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21421. })(BABYLON || (BABYLON = {}));
  21422. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  21423. var BABYLON;
  21424. (function (BABYLON) {
  21425. var PostProcessRenderPipeline = (function () {
  21426. function PostProcessRenderPipeline(engine, name) {
  21427. this._engine = engine;
  21428. this._name = name;
  21429. this._renderEffects = {};
  21430. this._renderEffectsForIsolatedPass = {};
  21431. this._cameras = [];
  21432. }
  21433. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21434. this._renderEffects[renderEffect._name] = renderEffect;
  21435. };
  21436. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21437. var renderEffects = this._renderEffects[renderEffectName];
  21438. if (!renderEffects) {
  21439. return;
  21440. }
  21441. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21442. };
  21443. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21444. var renderEffects = this._renderEffects[renderEffectName];
  21445. if (!renderEffects) {
  21446. return;
  21447. }
  21448. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21449. };
  21450. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21451. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21452. var indicesToDelete = [];
  21453. for (var i = 0; i < _cam.length; i++) {
  21454. var camera = _cam[i];
  21455. var cameraName = camera.name;
  21456. if (this._cameras.indexOf(camera) === -1) {
  21457. this._cameras[cameraName] = camera;
  21458. } else if (unique) {
  21459. indicesToDelete.push(i);
  21460. }
  21461. }
  21462. for (var i = 0; i < indicesToDelete.length; i++) {
  21463. cameras.splice(indicesToDelete[i], 1);
  21464. }
  21465. for (var renderEffectName in this._renderEffects) {
  21466. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21467. }
  21468. };
  21469. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21470. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21471. for (var renderEffectName in this._renderEffects) {
  21472. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21473. }
  21474. for (var i = 0; i < _cam.length; i++) {
  21475. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21476. }
  21477. };
  21478. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21479. var _this = this;
  21480. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21481. var pass = null;
  21482. for (var renderEffectName in this._renderEffects) {
  21483. pass = this._renderEffects[renderEffectName].getPass(passName);
  21484. if (pass != null) {
  21485. break;
  21486. }
  21487. }
  21488. if (pass === null) {
  21489. return;
  21490. }
  21491. for (var renderEffectName in this._renderEffects) {
  21492. this._renderEffects[renderEffectName]._disable(_cam);
  21493. }
  21494. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21495. for (var i = 0; i < _cam.length; i++) {
  21496. var camera = _cam[i];
  21497. var cameraName = camera.name;
  21498. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21499. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21500. });
  21501. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21502. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21503. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21504. }
  21505. };
  21506. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21507. var _this = this;
  21508. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21509. for (var i = 0; i < _cam.length; i++) {
  21510. var camera = _cam[i];
  21511. var cameraName = camera.name;
  21512. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21513. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21514. });
  21515. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21516. }
  21517. for (var renderEffectName in this._renderEffects) {
  21518. this._renderEffects[renderEffectName]._enable(_cam);
  21519. }
  21520. };
  21521. PostProcessRenderPipeline.prototype._update = function () {
  21522. for (var renderEffectName in this._renderEffects) {
  21523. this._renderEffects[renderEffectName]._update();
  21524. }
  21525. for (var i = 0; i < this._cameras.length; i++) {
  21526. var cameraName = this._cameras[i].name;
  21527. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21528. this._renderEffectsForIsolatedPass[cameraName]._update();
  21529. }
  21530. }
  21531. };
  21532. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21533. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21534. return PostProcessRenderPipeline;
  21535. })();
  21536. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21537. })(BABYLON || (BABYLON = {}));
  21538. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  21539. var BABYLON;
  21540. (function (BABYLON) {
  21541. var PostProcessRenderPipelineManager = (function () {
  21542. function PostProcessRenderPipelineManager() {
  21543. this._renderPipelines = {};
  21544. }
  21545. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21546. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21547. };
  21548. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21549. var renderPipeline = this._renderPipelines[renderPipelineName];
  21550. if (!renderPipeline) {
  21551. return;
  21552. }
  21553. renderPipeline._attachCameras(cameras, unique);
  21554. };
  21555. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21556. var renderPipeline = this._renderPipelines[renderPipelineName];
  21557. if (!renderPipeline) {
  21558. return;
  21559. }
  21560. renderPipeline._detachCameras(cameras);
  21561. };
  21562. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21563. var renderPipeline = this._renderPipelines[renderPipelineName];
  21564. if (!renderPipeline) {
  21565. return;
  21566. }
  21567. renderPipeline._enableEffect(renderEffectName, cameras);
  21568. };
  21569. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21570. var renderPipeline = this._renderPipelines[renderPipelineName];
  21571. if (!renderPipeline) {
  21572. return;
  21573. }
  21574. renderPipeline._disableEffect(renderEffectName, cameras);
  21575. };
  21576. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21577. var renderPipeline = this._renderPipelines[renderPipelineName];
  21578. if (!renderPipeline) {
  21579. return;
  21580. }
  21581. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21582. };
  21583. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21584. var renderPipeline = this._renderPipelines[renderPipelineName];
  21585. if (!renderPipeline) {
  21586. return;
  21587. }
  21588. renderPipeline._disableDisplayOnlyPass(cameras);
  21589. };
  21590. PostProcessRenderPipelineManager.prototype.update = function () {
  21591. for (var renderPipelineName in this._renderPipelines) {
  21592. this._renderPipelines[renderPipelineName]._update();
  21593. }
  21594. };
  21595. return PostProcessRenderPipelineManager;
  21596. })();
  21597. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21598. })(BABYLON || (BABYLON = {}));
  21599. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21600. var BABYLON;
  21601. (function (BABYLON) {
  21602. var DisplayPassPostProcess = (function (_super) {
  21603. __extends(DisplayPassPostProcess, _super);
  21604. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21605. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21606. }
  21607. return DisplayPassPostProcess;
  21608. })(BABYLON.PostProcess);
  21609. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21610. })(BABYLON || (BABYLON = {}));
  21611. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  21612. var BABYLON;
  21613. (function (BABYLON) {
  21614. var BoundingBoxRenderer = (function () {
  21615. function BoundingBoxRenderer(scene) {
  21616. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21617. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21618. this.showBackLines = true;
  21619. this.renderList = new BABYLON.SmartArray(32);
  21620. this._scene = scene;
  21621. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21622. attributes: ["position"],
  21623. uniforms: ["worldViewProjection", "color"]
  21624. });
  21625. var engine = this._scene.getEngine();
  21626. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21627. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21628. 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]);
  21629. }
  21630. BoundingBoxRenderer.prototype.reset = function () {
  21631. this.renderList.reset();
  21632. };
  21633. BoundingBoxRenderer.prototype.render = function () {
  21634. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21635. return;
  21636. }
  21637. var engine = this._scene.getEngine();
  21638. engine.setDepthWrite(false);
  21639. this._colorShader._preBind();
  21640. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21641. var boundingBox = this.renderList.data[boundingBoxIndex];
  21642. var min = boundingBox.minimum;
  21643. var max = boundingBox.maximum;
  21644. var diff = max.subtract(min);
  21645. var median = min.add(diff.scale(0.5));
  21646. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21647. // VBOs
  21648. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21649. if (this.showBackLines) {
  21650. // Back
  21651. engine.setDepthFunctionToGreaterOrEqual();
  21652. this._scene.resetCachedMaterial();
  21653. this._colorShader.setColor4("color", this.backColor.toColor4());
  21654. this._colorShader.bind(worldMatrix);
  21655. // Draw order
  21656. engine.draw(false, 0, 24);
  21657. }
  21658. // Front
  21659. engine.setDepthFunctionToLess();
  21660. this._scene.resetCachedMaterial();
  21661. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21662. this._colorShader.bind(worldMatrix);
  21663. // Draw order
  21664. engine.draw(false, 0, 24);
  21665. }
  21666. this._colorShader.unbind();
  21667. engine.setDepthFunctionToLessOrEqual();
  21668. engine.setDepthWrite(true);
  21669. };
  21670. BoundingBoxRenderer.prototype.dispose = function () {
  21671. this._colorShader.dispose();
  21672. this._vb.dispose();
  21673. this._scene.getEngine()._releaseBuffer(this._ib);
  21674. };
  21675. return BoundingBoxRenderer;
  21676. })();
  21677. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21678. })(BABYLON || (BABYLON = {}));
  21679. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  21680. var BABYLON;
  21681. (function (BABYLON) {
  21682. (function (Internals) {
  21683. /*
  21684. * Based on jsTGALoader - Javascript loader for TGA file
  21685. * By Vincent Thibault
  21686. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21687. */
  21688. var TGATools = (function () {
  21689. function TGATools() {
  21690. }
  21691. TGATools.GetTGAHeader = function (data) {
  21692. var offset = 0;
  21693. var header = {
  21694. id_length: data[offset++],
  21695. colormap_type: data[offset++],
  21696. image_type: data[offset++],
  21697. colormap_index: data[offset++] | data[offset++] << 8,
  21698. colormap_length: data[offset++] | data[offset++] << 8,
  21699. colormap_size: data[offset++],
  21700. origin: [
  21701. data[offset++] | data[offset++] << 8,
  21702. data[offset++] | data[offset++] << 8
  21703. ],
  21704. width: data[offset++] | data[offset++] << 8,
  21705. height: data[offset++] | data[offset++] << 8,
  21706. pixel_size: data[offset++],
  21707. flags: data[offset++]
  21708. };
  21709. return header;
  21710. };
  21711. TGATools.UploadContent = function (gl, data) {
  21712. // Not enough data to contain header ?
  21713. if (data.length < 19) {
  21714. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  21715. return;
  21716. }
  21717. // Read Header
  21718. var offset = 18;
  21719. var header = TGATools.GetTGAHeader(data);
  21720. // Assume it's a valid Targa file.
  21721. if (header.id_length + offset > data.length) {
  21722. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  21723. return;
  21724. }
  21725. // Skip not needed data
  21726. offset += header.id_length;
  21727. var use_rle = false;
  21728. var use_pal = false;
  21729. var use_rgb = false;
  21730. var use_grey = false;
  21731. switch (header.image_type) {
  21732. case TGATools._TYPE_RLE_INDEXED:
  21733. use_rle = true;
  21734. case TGATools._TYPE_INDEXED:
  21735. use_pal = true;
  21736. break;
  21737. case TGATools._TYPE_RLE_RGB:
  21738. use_rle = true;
  21739. case TGATools._TYPE_RGB:
  21740. use_rgb = true;
  21741. break;
  21742. case TGATools._TYPE_RLE_GREY:
  21743. use_rle = true;
  21744. case TGATools._TYPE_GREY:
  21745. use_grey = true;
  21746. break;
  21747. }
  21748. var pixel_data;
  21749. var numAlphaBits = header.flags & 0xf;
  21750. var pixel_size = header.pixel_size >> 3;
  21751. var pixel_total = header.width * header.height * pixel_size;
  21752. // Read palettes
  21753. var palettes;
  21754. if (use_pal) {
  21755. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  21756. }
  21757. // Read LRE
  21758. if (use_rle) {
  21759. pixel_data = new Uint8Array(pixel_total);
  21760. var c, count, i;
  21761. var localOffset = 0;
  21762. var pixels = new Uint8Array(pixel_size);
  21763. while (offset < pixel_total && localOffset < pixel_total) {
  21764. c = data[offset++];
  21765. count = (c & 0x7f) + 1;
  21766. // RLE pixels
  21767. if (c & 0x80) {
  21768. for (i = 0; i < pixel_size; ++i) {
  21769. pixels[i] = data[offset++];
  21770. }
  21771. for (i = 0; i < count; ++i) {
  21772. pixel_data.set(pixels, localOffset + i * pixel_size);
  21773. }
  21774. localOffset += pixel_size * count;
  21775. } else {
  21776. count *= pixel_size;
  21777. for (i = 0; i < count; ++i) {
  21778. pixel_data[localOffset + i] = data[offset++];
  21779. }
  21780. localOffset += count;
  21781. }
  21782. }
  21783. } else {
  21784. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  21785. }
  21786. // Load to texture
  21787. var x_start, y_start, x_step, y_step, y_end, x_end;
  21788. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  21789. default:
  21790. case TGATools._ORIGIN_UL:
  21791. x_start = 0;
  21792. x_step = 1;
  21793. x_end = header.width;
  21794. y_start = 0;
  21795. y_step = 1;
  21796. y_end = header.height;
  21797. break;
  21798. case TGATools._ORIGIN_BL:
  21799. x_start = 0;
  21800. x_step = 1;
  21801. x_end = header.width;
  21802. y_start = header.height - 1;
  21803. y_step = -1;
  21804. y_end = -1;
  21805. break;
  21806. case TGATools._ORIGIN_UR:
  21807. x_start = header.width - 1;
  21808. x_step = -1;
  21809. x_end = -1;
  21810. y_start = 0;
  21811. y_step = 1;
  21812. y_end = header.height;
  21813. break;
  21814. case TGATools._ORIGIN_BR:
  21815. x_start = header.width - 1;
  21816. x_step = -1;
  21817. x_end = -1;
  21818. y_start = header.height - 1;
  21819. y_step = -1;
  21820. y_end = -1;
  21821. break;
  21822. }
  21823. // Load the specify method
  21824. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21825. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21826. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21827. };
  21828. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21829. var image = pixel_data, colormap = palettes;
  21830. var width = header.width, height = header.height;
  21831. var color, i = 0, x, y;
  21832. var imageData = new Uint8Array(width * height * 4);
  21833. for (y = y_start; y !== y_end; y += y_step) {
  21834. for (x = x_start; x !== x_end; x += x_step, i++) {
  21835. color = image[i];
  21836. imageData[(x + width * y) * 4 + 3] = 255;
  21837. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21838. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21839. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21840. }
  21841. }
  21842. return imageData;
  21843. };
  21844. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21845. var image = pixel_data;
  21846. var width = header.width, height = header.height;
  21847. var color, i = 0, x, y;
  21848. var imageData = new Uint8Array(width * height * 4);
  21849. for (y = y_start; y !== y_end; y += y_step) {
  21850. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21851. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21852. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21853. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21854. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21855. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21856. }
  21857. }
  21858. return imageData;
  21859. };
  21860. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21861. var image = pixel_data;
  21862. var width = header.width, height = header.height;
  21863. var i = 0, x, y;
  21864. var imageData = new Uint8Array(width * height * 4);
  21865. for (y = y_start; y !== y_end; y += y_step) {
  21866. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21867. imageData[(x + width * y) * 4 + 3] = 255;
  21868. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21869. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21870. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21871. }
  21872. }
  21873. return imageData;
  21874. };
  21875. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21876. var image = pixel_data;
  21877. var width = header.width, height = header.height;
  21878. var i = 0, x, y;
  21879. var imageData = new Uint8Array(width * height * 4);
  21880. for (y = y_start; y !== y_end; y += y_step) {
  21881. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21882. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21883. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21884. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21885. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21886. }
  21887. }
  21888. return imageData;
  21889. };
  21890. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21891. var image = pixel_data;
  21892. var width = header.width, height = header.height;
  21893. var color, i = 0, x, y;
  21894. var imageData = new Uint8Array(width * height * 4);
  21895. for (y = y_start; y !== y_end; y += y_step) {
  21896. for (x = x_start; x !== x_end; x += x_step, i++) {
  21897. color = image[i];
  21898. imageData[(x + width * y) * 4 + 0] = color;
  21899. imageData[(x + width * y) * 4 + 1] = color;
  21900. imageData[(x + width * y) * 4 + 2] = color;
  21901. imageData[(x + width * y) * 4 + 3] = 255;
  21902. }
  21903. }
  21904. return imageData;
  21905. };
  21906. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21907. var image = pixel_data;
  21908. var width = header.width, height = header.height;
  21909. var i = 0, x, y;
  21910. var imageData = new Uint8Array(width * height * 4);
  21911. for (y = y_start; y !== y_end; y += y_step) {
  21912. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21913. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21914. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21915. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21916. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21917. }
  21918. }
  21919. return imageData;
  21920. };
  21921. TGATools._TYPE_NO_DATA = 0;
  21922. TGATools._TYPE_INDEXED = 1;
  21923. TGATools._TYPE_RGB = 2;
  21924. TGATools._TYPE_GREY = 3;
  21925. TGATools._TYPE_RLE_INDEXED = 9;
  21926. TGATools._TYPE_RLE_RGB = 10;
  21927. TGATools._TYPE_RLE_GREY = 11;
  21928. TGATools._ORIGIN_MASK = 0x30;
  21929. TGATools._ORIGIN_SHIFT = 0x04;
  21930. TGATools._ORIGIN_BL = 0x00;
  21931. TGATools._ORIGIN_BR = 0x01;
  21932. TGATools._ORIGIN_UL = 0x02;
  21933. TGATools._ORIGIN_UR = 0x03;
  21934. return TGATools;
  21935. })();
  21936. Internals.TGATools = TGATools;
  21937. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21938. var Internals = BABYLON.Internals;
  21939. })(BABYLON || (BABYLON = {}));
  21940. //# sourceMappingURL=babylon.tools.tga.js.map
  21941. var BABYLON;
  21942. (function (BABYLON) {
  21943. (function (Internals) {
  21944. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21945. // All values and structures referenced from:
  21946. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21947. var DDS_MAGIC = 0x20534444;
  21948. 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;
  21949. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21950. 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;
  21951. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21952. function FourCCToInt32(value) {
  21953. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21954. }
  21955. function Int32ToFourCC(value) {
  21956. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21957. }
  21958. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21959. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21960. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21961. var headerLengthInt = 31;
  21962. // Offsets into the header array
  21963. var off_magic = 0;
  21964. var off_size = 1;
  21965. var off_flags = 2;
  21966. var off_height = 3;
  21967. var off_width = 4;
  21968. var off_mipmapCount = 7;
  21969. var off_pfFlags = 20;
  21970. var off_pfFourCC = 21;
  21971. var off_RGBbpp = 22;
  21972. var off_RMask = 23;
  21973. var off_GMask = 24;
  21974. var off_BMask = 25;
  21975. var off_AMask = 26;
  21976. var off_caps1 = 27;
  21977. var off_caps2 = 28;
  21978. ;
  21979. var DDSTools = (function () {
  21980. function DDSTools() {
  21981. }
  21982. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21983. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21984. var mipmapCount = 1;
  21985. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21986. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21987. }
  21988. return {
  21989. width: header[off_width],
  21990. height: header[off_height],
  21991. mipmapCount: mipmapCount,
  21992. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21993. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21994. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21995. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21996. };
  21997. };
  21998. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21999. var byteArray = new Uint8Array(dataLength);
  22000. var srcData = new Uint8Array(arrayBuffer);
  22001. var index = 0;
  22002. for (var y = height - 1; y >= 0; y--) {
  22003. for (var x = 0; x < width; x++) {
  22004. var srcPos = dataOffset + (x + y * width) * 4;
  22005. byteArray[index + 2] = srcData[srcPos];
  22006. byteArray[index + 1] = srcData[srcPos + 1];
  22007. byteArray[index] = srcData[srcPos + 2];
  22008. byteArray[index + 3] = srcData[srcPos + 3];
  22009. index += 4;
  22010. }
  22011. }
  22012. return byteArray;
  22013. };
  22014. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22015. var byteArray = new Uint8Array(dataLength);
  22016. var srcData = new Uint8Array(arrayBuffer);
  22017. var index = 0;
  22018. for (var y = height - 1; y >= 0; y--) {
  22019. for (var x = 0; x < width; x++) {
  22020. var srcPos = dataOffset + (x + y * width) * 3;
  22021. byteArray[index + 2] = srcData[srcPos];
  22022. byteArray[index + 1] = srcData[srcPos + 1];
  22023. byteArray[index] = srcData[srcPos + 2];
  22024. index += 3;
  22025. }
  22026. }
  22027. return byteArray;
  22028. };
  22029. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22030. var byteArray = new Uint8Array(dataLength);
  22031. var srcData = new Uint8Array(arrayBuffer);
  22032. var index = 0;
  22033. for (var y = height - 1; y >= 0; y--) {
  22034. for (var x = 0; x < width; x++) {
  22035. var srcPos = dataOffset + (x + y * width);
  22036. byteArray[index] = srcData[srcPos];
  22037. index++;
  22038. }
  22039. }
  22040. return byteArray;
  22041. };
  22042. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22043. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22044. if (header[off_magic] != DDS_MAGIC) {
  22045. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22046. return;
  22047. }
  22048. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22049. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22050. return;
  22051. }
  22052. if (info.isFourCC) {
  22053. fourCC = header[off_pfFourCC];
  22054. switch (fourCC) {
  22055. case FOURCC_DXT1:
  22056. blockBytes = 8;
  22057. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22058. break;
  22059. case FOURCC_DXT3:
  22060. blockBytes = 16;
  22061. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22062. break;
  22063. case FOURCC_DXT5:
  22064. blockBytes = 16;
  22065. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22066. break;
  22067. default:
  22068. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22069. return;
  22070. }
  22071. }
  22072. mipmapCount = 1;
  22073. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22074. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22075. }
  22076. var bpp = header[off_RGBbpp];
  22077. for (var face = 0; face < faces; face++) {
  22078. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22079. width = header[off_width];
  22080. height = header[off_height];
  22081. dataOffset = header[off_size] + 4;
  22082. for (i = 0; i < mipmapCount; ++i) {
  22083. if (info.isRGB) {
  22084. if (bpp == 24) {
  22085. dataLength = width * height * 3;
  22086. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22087. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22088. } else {
  22089. dataLength = width * height * 4;
  22090. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22091. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22092. }
  22093. } else if (info.isLuminance) {
  22094. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22095. var unpaddedRowSize = width;
  22096. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22097. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22098. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22099. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22100. } else {
  22101. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22102. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22103. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22104. }
  22105. dataOffset += dataLength;
  22106. width *= 0.5;
  22107. height *= 0.5;
  22108. width = Math.max(1.0, width);
  22109. height = Math.max(1.0, height);
  22110. }
  22111. }
  22112. };
  22113. return DDSTools;
  22114. })();
  22115. Internals.DDSTools = DDSTools;
  22116. })(BABYLON.Internals || (BABYLON.Internals = {}));
  22117. var Internals = BABYLON.Internals;
  22118. })(BABYLON || (BABYLON = {}));
  22119. //# sourceMappingURL=babylon.tools.dds.js.map
  22120. var BABYLON;
  22121. (function (BABYLON) {
  22122. var SmartArray = (function () {
  22123. function SmartArray(capacity) {
  22124. this.length = 0;
  22125. this._duplicateId = 0;
  22126. this.data = new Array(capacity);
  22127. this._id = SmartArray._GlobalId++;
  22128. }
  22129. SmartArray.prototype.push = function (value) {
  22130. this.data[this.length++] = value;
  22131. if (this.length > this.data.length) {
  22132. this.data.length *= 2;
  22133. }
  22134. if (!value.__smartArrayFlags) {
  22135. value.__smartArrayFlags = {};
  22136. }
  22137. value.__smartArrayFlags[this._id] = this._duplicateId;
  22138. };
  22139. SmartArray.prototype.pushNoDuplicate = function (value) {
  22140. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22141. return;
  22142. }
  22143. this.push(value);
  22144. };
  22145. SmartArray.prototype.sort = function (compareFn) {
  22146. this.data.sort(compareFn);
  22147. };
  22148. SmartArray.prototype.reset = function () {
  22149. this.length = 0;
  22150. this._duplicateId++;
  22151. };
  22152. SmartArray.prototype.concat = function (array) {
  22153. if (array.length === 0) {
  22154. return;
  22155. }
  22156. if (this.length + array.length > this.data.length) {
  22157. this.data.length = (this.length + array.length) * 2;
  22158. }
  22159. for (var index = 0; index < array.length; index++) {
  22160. this.data[this.length++] = (array.data || array)[index];
  22161. }
  22162. };
  22163. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22164. if (array.length === 0) {
  22165. return;
  22166. }
  22167. if (this.length + array.length > this.data.length) {
  22168. this.data.length = (this.length + array.length) * 2;
  22169. }
  22170. for (var index = 0; index < array.length; index++) {
  22171. var item = (array.data || array)[index];
  22172. this.pushNoDuplicate(item);
  22173. }
  22174. };
  22175. SmartArray.prototype.indexOf = function (value) {
  22176. var position = this.data.indexOf(value);
  22177. if (position >= this.length) {
  22178. return -1;
  22179. }
  22180. return position;
  22181. };
  22182. SmartArray._GlobalId = 0;
  22183. return SmartArray;
  22184. })();
  22185. BABYLON.SmartArray = SmartArray;
  22186. })(BABYLON || (BABYLON = {}));
  22187. //# sourceMappingURL=babylon.smartArray.js.map
  22188. var BABYLON;
  22189. (function (BABYLON) {
  22190. var CannonJSPlugin = (function () {
  22191. function CannonJSPlugin() {
  22192. this._registeredMeshes = [];
  22193. this._physicsMaterials = [];
  22194. this.updateBodyPosition = function (mesh) {
  22195. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22196. var registeredMesh = this._registeredMeshes[index];
  22197. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22198. var body = registeredMesh.body;
  22199. var center = mesh.getBoundingInfo().boundingBox.center;
  22200. body.position.set(center.x, center.z, center.y);
  22201. body.quaternion.x = mesh.rotationQuaternion.x;
  22202. body.quaternion.z = mesh.rotationQuaternion.y;
  22203. body.quaternion.y = mesh.rotationQuaternion.z;
  22204. body.quaternion.w = -mesh.rotationQuaternion.w;
  22205. return;
  22206. }
  22207. }
  22208. };
  22209. }
  22210. CannonJSPlugin.prototype.initialize = function (iterations) {
  22211. if (typeof iterations === "undefined") { iterations = 10; }
  22212. this._world = new CANNON.World();
  22213. this._world.broadphase = new CANNON.NaiveBroadphase();
  22214. this._world.solver.iterations = iterations;
  22215. };
  22216. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22217. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22218. };
  22219. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22220. this._world.step(delta);
  22221. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22222. var registeredMesh = this._registeredMeshes[index];
  22223. if (registeredMesh.isChild) {
  22224. continue;
  22225. }
  22226. // Body position
  22227. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22228. var deltaPos = registeredMesh.delta;
  22229. if (deltaPos) {
  22230. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22231. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22232. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22233. } else {
  22234. registeredMesh.mesh.position.x = bodyX;
  22235. registeredMesh.mesh.position.y = bodyZ;
  22236. registeredMesh.mesh.position.z = bodyY;
  22237. }
  22238. if (!registeredMesh.mesh.rotationQuaternion) {
  22239. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22240. }
  22241. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22242. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22243. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22244. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22245. }
  22246. };
  22247. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22248. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22249. };
  22250. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22251. this.unregisterMesh(mesh);
  22252. mesh.computeWorldMatrix(true);
  22253. switch (impostor) {
  22254. case BABYLON.PhysicsEngine.SphereImpostor:
  22255. var bbox = mesh.getBoundingInfo().boundingBox;
  22256. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22257. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22258. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22259. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22260. case BABYLON.PhysicsEngine.BoxImpostor:
  22261. bbox = mesh.getBoundingInfo().boundingBox;
  22262. var min = bbox.minimumWorld;
  22263. var max = bbox.maximumWorld;
  22264. var box = max.subtract(min).scale(0.5);
  22265. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22266. case BABYLON.PhysicsEngine.PlaneImpostor:
  22267. return this._createPlane(mesh, options);
  22268. case BABYLON.PhysicsEngine.MeshImpostor:
  22269. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22270. var rawFaces = mesh.getIndices();
  22271. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22272. }
  22273. return null;
  22274. };
  22275. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22276. var shape = new CANNON.Sphere(radius);
  22277. if (!options) {
  22278. return shape;
  22279. }
  22280. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22281. };
  22282. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22283. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22284. if (!options) {
  22285. return shape;
  22286. }
  22287. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22288. };
  22289. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22290. var shape = new CANNON.Plane();
  22291. if (!options) {
  22292. return shape;
  22293. }
  22294. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22295. };
  22296. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22297. var verts = [], faces = [];
  22298. mesh.computeWorldMatrix(true);
  22299. for (var i = 0; i < rawVerts.length; i += 3) {
  22300. var transformed = BABYLON.Vector3.Zero();
  22301. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22302. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22303. }
  22304. for (var j = 0; j < rawFaces.length; j += 3) {
  22305. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22306. }
  22307. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22308. if (!options) {
  22309. return shape;
  22310. }
  22311. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22312. };
  22313. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22314. var index;
  22315. var mat;
  22316. for (index = 0; index < this._physicsMaterials.length; index++) {
  22317. mat = this._physicsMaterials[index];
  22318. if (mat.friction === friction && mat.restitution === restitution) {
  22319. return mat;
  22320. }
  22321. }
  22322. var currentMat = new CANNON.Material();
  22323. currentMat.friction = friction;
  22324. currentMat.restitution = restitution;
  22325. this._physicsMaterials.push(currentMat);
  22326. for (index = 0; index < this._physicsMaterials.length; index++) {
  22327. mat = this._physicsMaterials[index];
  22328. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22329. contactMaterial.contactEquationStiffness = 1e10;
  22330. contactMaterial.contactEquationRegularizationTime = 10;
  22331. this._world.addContactMaterial(contactMaterial);
  22332. }
  22333. return currentMat;
  22334. };
  22335. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22336. var initialRotation = null;
  22337. if (mesh.rotationQuaternion) {
  22338. initialRotation = mesh.rotationQuaternion.clone();
  22339. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22340. }
  22341. // The delta between the mesh position and the mesh bounding box center
  22342. var bbox = mesh.getBoundingInfo().boundingBox;
  22343. var deltaPosition = mesh.position.subtract(bbox.center);
  22344. var material = this._addMaterial(friction, restitution);
  22345. var body = new CANNON.RigidBody(mass, shape, material);
  22346. if (initialRotation) {
  22347. body.quaternion.x = initialRotation.x;
  22348. body.quaternion.z = initialRotation.y;
  22349. body.quaternion.y = initialRotation.z;
  22350. body.quaternion.w = -initialRotation.w;
  22351. }
  22352. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22353. this._world.add(body);
  22354. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22355. return body;
  22356. };
  22357. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22358. var compoundShape = new CANNON.Compound();
  22359. for (var index = 0; index < parts.length; index++) {
  22360. var mesh = parts[index].mesh;
  22361. var shape = this.registerMesh(mesh, parts[index].impostor);
  22362. if (index == 0) {
  22363. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22364. } else {
  22365. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22366. }
  22367. }
  22368. var initialMesh = parts[0].mesh;
  22369. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22370. body.parts = parts;
  22371. return body;
  22372. };
  22373. CannonJSPlugin.prototype._unbindBody = function (body) {
  22374. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22375. var registeredMesh = this._registeredMeshes[index];
  22376. if (registeredMesh.body === body) {
  22377. registeredMesh.body = null;
  22378. registeredMesh.delta = 0;
  22379. }
  22380. }
  22381. };
  22382. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22383. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22384. var registeredMesh = this._registeredMeshes[index];
  22385. if (registeredMesh.mesh === mesh) {
  22386. // Remove body
  22387. if (registeredMesh.body) {
  22388. this._world.remove(registeredMesh.body);
  22389. this._unbindBody(registeredMesh.body);
  22390. }
  22391. this._registeredMeshes.splice(index, 1);
  22392. return;
  22393. }
  22394. }
  22395. };
  22396. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22397. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22398. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22399. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22400. var registeredMesh = this._registeredMeshes[index];
  22401. if (registeredMesh.mesh === mesh) {
  22402. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22403. return;
  22404. }
  22405. }
  22406. };
  22407. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22408. var body1 = null, body2 = null;
  22409. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22410. var registeredMesh = this._registeredMeshes[index];
  22411. if (registeredMesh.mesh === mesh1) {
  22412. body1 = registeredMesh.body;
  22413. } else if (registeredMesh.mesh === mesh2) {
  22414. body2 = registeredMesh.body;
  22415. }
  22416. }
  22417. if (!body1 || !body2) {
  22418. return false;
  22419. }
  22420. 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));
  22421. this._world.addConstraint(constraint);
  22422. return true;
  22423. };
  22424. CannonJSPlugin.prototype.dispose = function () {
  22425. while (this._registeredMeshes.length) {
  22426. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22427. }
  22428. };
  22429. CannonJSPlugin.prototype.isSupported = function () {
  22430. return window.CANNON !== undefined;
  22431. };
  22432. return CannonJSPlugin;
  22433. })();
  22434. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22435. })(BABYLON || (BABYLON = {}));
  22436. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22437. var BABYLON;
  22438. (function (BABYLON) {
  22439. var Condition = (function () {
  22440. function Condition(actionManager) {
  22441. this._actionManager = actionManager;
  22442. }
  22443. Condition.prototype.isValid = function () {
  22444. return true;
  22445. };
  22446. Condition.prototype._getProperty = function (propertyPath) {
  22447. return this._actionManager._getProperty(propertyPath);
  22448. };
  22449. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22450. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22451. };
  22452. return Condition;
  22453. })();
  22454. BABYLON.Condition = Condition;
  22455. var ValueCondition = (function (_super) {
  22456. __extends(ValueCondition, _super);
  22457. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22458. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  22459. _super.call(this, actionManager);
  22460. this.propertyPath = propertyPath;
  22461. this.value = value;
  22462. this.operator = operator;
  22463. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22464. this._property = this._getProperty(this.propertyPath);
  22465. }
  22466. Object.defineProperty(ValueCondition, "IsEqual", {
  22467. get: function () {
  22468. return ValueCondition._IsEqual;
  22469. },
  22470. enumerable: true,
  22471. configurable: true
  22472. });
  22473. Object.defineProperty(ValueCondition, "IsDifferent", {
  22474. get: function () {
  22475. return ValueCondition._IsDifferent;
  22476. },
  22477. enumerable: true,
  22478. configurable: true
  22479. });
  22480. Object.defineProperty(ValueCondition, "IsGreater", {
  22481. get: function () {
  22482. return ValueCondition._IsGreater;
  22483. },
  22484. enumerable: true,
  22485. configurable: true
  22486. });
  22487. Object.defineProperty(ValueCondition, "IsLesser", {
  22488. get: function () {
  22489. return ValueCondition._IsLesser;
  22490. },
  22491. enumerable: true,
  22492. configurable: true
  22493. });
  22494. // Methods
  22495. ValueCondition.prototype.isValid = function () {
  22496. switch (this.operator) {
  22497. case ValueCondition.IsGreater:
  22498. return this._target[this._property] > this.value;
  22499. case ValueCondition.IsLesser:
  22500. return this._target[this._property] < this.value;
  22501. case ValueCondition.IsEqual:
  22502. case ValueCondition.IsDifferent:
  22503. var check;
  22504. if (this.value.equals) {
  22505. check = this.value.equals(this._target[this._property]);
  22506. } else {
  22507. check = this.value === this._target[this._property];
  22508. }
  22509. return this.operator === ValueCondition.IsEqual ? check : !check;
  22510. }
  22511. return false;
  22512. };
  22513. ValueCondition._IsEqual = 0;
  22514. ValueCondition._IsDifferent = 1;
  22515. ValueCondition._IsGreater = 2;
  22516. ValueCondition._IsLesser = 3;
  22517. return ValueCondition;
  22518. })(Condition);
  22519. BABYLON.ValueCondition = ValueCondition;
  22520. var PredicateCondition = (function (_super) {
  22521. __extends(PredicateCondition, _super);
  22522. function PredicateCondition(actionManager, predicate) {
  22523. _super.call(this, actionManager);
  22524. this.predicate = predicate;
  22525. }
  22526. PredicateCondition.prototype.isValid = function () {
  22527. return this.predicate();
  22528. };
  22529. return PredicateCondition;
  22530. })(Condition);
  22531. BABYLON.PredicateCondition = PredicateCondition;
  22532. var StateCondition = (function (_super) {
  22533. __extends(StateCondition, _super);
  22534. function StateCondition(actionManager, target, value) {
  22535. _super.call(this, actionManager);
  22536. this.value = value;
  22537. this._target = target;
  22538. }
  22539. // Methods
  22540. StateCondition.prototype.isValid = function () {
  22541. return this._target.state === this.value;
  22542. };
  22543. return StateCondition;
  22544. })(Condition);
  22545. BABYLON.StateCondition = StateCondition;
  22546. })(BABYLON || (BABYLON = {}));
  22547. //# sourceMappingURL=babylon.condition.js.map
  22548. var BABYLON;
  22549. (function (BABYLON) {
  22550. var Action = (function () {
  22551. function Action(triggerOptions, condition) {
  22552. this.triggerOptions = triggerOptions;
  22553. if (triggerOptions.parameter) {
  22554. this.trigger = triggerOptions.trigger;
  22555. this._triggerParameter = triggerOptions.parameter;
  22556. } else {
  22557. this.trigger = triggerOptions;
  22558. }
  22559. this._nextActiveAction = this;
  22560. this._condition = condition;
  22561. }
  22562. // Methods
  22563. Action.prototype._prepare = function () {
  22564. };
  22565. Action.prototype.getTriggerParameter = function () {
  22566. return this._triggerParameter;
  22567. };
  22568. Action.prototype._executeCurrent = function (evt) {
  22569. if (this._condition) {
  22570. var currentRenderId = this._actionManager.getScene().getRenderId();
  22571. // We cache the current evaluation for the current frame
  22572. if (this._condition._evaluationId === currentRenderId) {
  22573. if (!this._condition._currentResult) {
  22574. return;
  22575. }
  22576. } else {
  22577. this._condition._evaluationId = currentRenderId;
  22578. if (!this._condition.isValid()) {
  22579. this._condition._currentResult = false;
  22580. return;
  22581. }
  22582. this._condition._currentResult = true;
  22583. }
  22584. }
  22585. this._nextActiveAction.execute(evt);
  22586. if (this._nextActiveAction._child) {
  22587. if (!this._nextActiveAction._child._actionManager) {
  22588. this._nextActiveAction._child._actionManager = this._actionManager;
  22589. }
  22590. this._nextActiveAction = this._nextActiveAction._child;
  22591. } else {
  22592. this._nextActiveAction = this;
  22593. }
  22594. };
  22595. Action.prototype.execute = function (evt) {
  22596. };
  22597. Action.prototype.then = function (action) {
  22598. this._child = action;
  22599. action._actionManager = this._actionManager;
  22600. action._prepare();
  22601. return action;
  22602. };
  22603. Action.prototype._getProperty = function (propertyPath) {
  22604. return this._actionManager._getProperty(propertyPath);
  22605. };
  22606. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22607. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22608. };
  22609. return Action;
  22610. })();
  22611. BABYLON.Action = Action;
  22612. })(BABYLON || (BABYLON = {}));
  22613. //# sourceMappingURL=babylon.action.js.map
  22614. var BABYLON;
  22615. (function (BABYLON) {
  22616. /**
  22617. * ActionEvent is the event beint sent when an action is triggered.
  22618. */
  22619. var ActionEvent = (function () {
  22620. /**
  22621. * @constructor
  22622. * @param source The mesh that triggered the action.
  22623. * @param pointerX the X mouse cursor position at the time of the event
  22624. * @param pointerY the Y mouse cursor position at the time of the event
  22625. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  22626. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  22627. */
  22628. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22629. this.source = source;
  22630. this.pointerX = pointerX;
  22631. this.pointerY = pointerY;
  22632. this.meshUnderPointer = meshUnderPointer;
  22633. this.sourceEvent = sourceEvent;
  22634. }
  22635. /**
  22636. * Helper function to auto-create an ActionEvent from a source mesh.
  22637. * @param source the source mesh that triggered the event
  22638. * @param evt {Event} The original (browser) event
  22639. */
  22640. ActionEvent.CreateNew = function (source, evt) {
  22641. var scene = source.getScene();
  22642. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22643. };
  22644. /**
  22645. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  22646. * @param scene the scene where the event occurred
  22647. * @param evt {Event} The original (browser) event
  22648. */
  22649. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22650. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22651. };
  22652. return ActionEvent;
  22653. })();
  22654. BABYLON.ActionEvent = ActionEvent;
  22655. /**
  22656. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  22657. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  22658. */
  22659. var ActionManager = (function () {
  22660. function ActionManager(scene) {
  22661. // Members
  22662. this.actions = new Array();
  22663. this._scene = scene;
  22664. scene._actionManagers.push(this);
  22665. }
  22666. Object.defineProperty(ActionManager, "NothingTrigger", {
  22667. get: function () {
  22668. return ActionManager._NothingTrigger;
  22669. },
  22670. enumerable: true,
  22671. configurable: true
  22672. });
  22673. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22674. get: function () {
  22675. return ActionManager._OnPickTrigger;
  22676. },
  22677. enumerable: true,
  22678. configurable: true
  22679. });
  22680. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22681. get: function () {
  22682. return ActionManager._OnLeftPickTrigger;
  22683. },
  22684. enumerable: true,
  22685. configurable: true
  22686. });
  22687. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22688. get: function () {
  22689. return ActionManager._OnRightPickTrigger;
  22690. },
  22691. enumerable: true,
  22692. configurable: true
  22693. });
  22694. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  22695. get: function () {
  22696. return ActionManager._OnCenterPickTrigger;
  22697. },
  22698. enumerable: true,
  22699. configurable: true
  22700. });
  22701. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  22702. get: function () {
  22703. return ActionManager._OnPointerOverTrigger;
  22704. },
  22705. enumerable: true,
  22706. configurable: true
  22707. });
  22708. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  22709. get: function () {
  22710. return ActionManager._OnPointerOutTrigger;
  22711. },
  22712. enumerable: true,
  22713. configurable: true
  22714. });
  22715. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  22716. get: function () {
  22717. return ActionManager._OnEveryFrameTrigger;
  22718. },
  22719. enumerable: true,
  22720. configurable: true
  22721. });
  22722. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  22723. get: function () {
  22724. return ActionManager._OnIntersectionEnterTrigger;
  22725. },
  22726. enumerable: true,
  22727. configurable: true
  22728. });
  22729. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  22730. get: function () {
  22731. return ActionManager._OnIntersectionExitTrigger;
  22732. },
  22733. enumerable: true,
  22734. configurable: true
  22735. });
  22736. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  22737. get: function () {
  22738. return ActionManager._OnKeyDownTrigger;
  22739. },
  22740. enumerable: true,
  22741. configurable: true
  22742. });
  22743. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  22744. get: function () {
  22745. return ActionManager._OnKeyUpTrigger;
  22746. },
  22747. enumerable: true,
  22748. configurable: true
  22749. });
  22750. // Methods
  22751. ActionManager.prototype.dispose = function () {
  22752. var index = this._scene._actionManagers.indexOf(this);
  22753. if (index > -1) {
  22754. this._scene._actionManagers.splice(index, 1);
  22755. }
  22756. };
  22757. ActionManager.prototype.getScene = function () {
  22758. return this._scene;
  22759. };
  22760. /**
  22761. * Does this action manager handles actions of any of the given triggers
  22762. * @param {number[]} triggers - the triggers to be tested
  22763. * @return {boolean} whether one (or more) of the triggers is handeled
  22764. */
  22765. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  22766. for (var index = 0; index < this.actions.length; index++) {
  22767. var action = this.actions[index];
  22768. if (triggers.indexOf(action.trigger) > -1) {
  22769. return true;
  22770. }
  22771. }
  22772. return false;
  22773. };
  22774. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  22775. /**
  22776. * Does this action manager has pointer triggers
  22777. * @return {boolean} whether or not it has pointer triggers
  22778. */
  22779. get: function () {
  22780. for (var index = 0; index < this.actions.length; index++) {
  22781. var action = this.actions[index];
  22782. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  22783. return true;
  22784. }
  22785. }
  22786. return false;
  22787. },
  22788. enumerable: true,
  22789. configurable: true
  22790. });
  22791. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  22792. /**
  22793. * Does this action manager has pick triggers
  22794. * @return {boolean} whether or not it has pick triggers
  22795. */
  22796. get: function () {
  22797. for (var index = 0; index < this.actions.length; index++) {
  22798. var action = this.actions[index];
  22799. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  22800. return true;
  22801. }
  22802. }
  22803. return false;
  22804. },
  22805. enumerable: true,
  22806. configurable: true
  22807. });
  22808. /**
  22809. * Registers an action to this action manager
  22810. * @param {BABYLON.Action} action - the action to be registered
  22811. * @return {BABYLON.Action} the action amended (prepared) after registration
  22812. */
  22813. ActionManager.prototype.registerAction = function (action) {
  22814. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  22815. if (this.getScene().actionManager !== this) {
  22816. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  22817. return null;
  22818. }
  22819. }
  22820. this.actions.push(action);
  22821. action._actionManager = this;
  22822. action._prepare();
  22823. return action;
  22824. };
  22825. /**
  22826. * Process a specific trigger
  22827. * @param {number} trigger - the trigger to process
  22828. * @param evt {BABYLON.ActionEvent} the event details to be processed
  22829. */
  22830. ActionManager.prototype.processTrigger = function (trigger, evt) {
  22831. for (var index = 0; index < this.actions.length; index++) {
  22832. var action = this.actions[index];
  22833. if (action.trigger === trigger) {
  22834. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  22835. var parameter = action.getTriggerParameter();
  22836. if (parameter) {
  22837. if (evt.sourceEvent.key !== parameter) {
  22838. continue;
  22839. }
  22840. }
  22841. }
  22842. action._executeCurrent(evt);
  22843. }
  22844. }
  22845. };
  22846. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  22847. var properties = propertyPath.split(".");
  22848. for (var index = 0; index < properties.length - 1; index++) {
  22849. target = target[properties[index]];
  22850. }
  22851. return target;
  22852. };
  22853. ActionManager.prototype._getProperty = function (propertyPath) {
  22854. var properties = propertyPath.split(".");
  22855. return properties[properties.length - 1];
  22856. };
  22857. ActionManager._NothingTrigger = 0;
  22858. ActionManager._OnPickTrigger = 1;
  22859. ActionManager._OnLeftPickTrigger = 2;
  22860. ActionManager._OnRightPickTrigger = 3;
  22861. ActionManager._OnCenterPickTrigger = 4;
  22862. ActionManager._OnPointerOverTrigger = 5;
  22863. ActionManager._OnPointerOutTrigger = 6;
  22864. ActionManager._OnEveryFrameTrigger = 7;
  22865. ActionManager._OnIntersectionEnterTrigger = 8;
  22866. ActionManager._OnIntersectionExitTrigger = 9;
  22867. ActionManager._OnKeyDownTrigger = 10;
  22868. ActionManager._OnKeyUpTrigger = 11;
  22869. return ActionManager;
  22870. })();
  22871. BABYLON.ActionManager = ActionManager;
  22872. })(BABYLON || (BABYLON = {}));
  22873. //# sourceMappingURL=babylon.actionManager.js.map
  22874. var BABYLON;
  22875. (function (BABYLON) {
  22876. var InterpolateValueAction = (function (_super) {
  22877. __extends(InterpolateValueAction, _super);
  22878. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22879. if (typeof duration === "undefined") { duration = 1000; }
  22880. _super.call(this, triggerOptions, condition);
  22881. this.propertyPath = propertyPath;
  22882. this.value = value;
  22883. this.duration = duration;
  22884. this.stopOtherAnimations = stopOtherAnimations;
  22885. this._target = target;
  22886. }
  22887. InterpolateValueAction.prototype._prepare = function () {
  22888. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22889. this._property = this._getProperty(this.propertyPath);
  22890. };
  22891. InterpolateValueAction.prototype.execute = function () {
  22892. var scene = this._actionManager.getScene();
  22893. var keys = [
  22894. {
  22895. frame: 0,
  22896. value: this._target[this._property]
  22897. }, {
  22898. frame: 100,
  22899. value: this.value
  22900. }
  22901. ];
  22902. var dataType;
  22903. if (typeof this.value === "number") {
  22904. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22905. } else if (this.value instanceof BABYLON.Color3) {
  22906. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22907. } else if (this.value instanceof BABYLON.Vector3) {
  22908. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22909. } else if (this.value instanceof BABYLON.Matrix) {
  22910. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22911. } else if (this.value instanceof BABYLON.Quaternion) {
  22912. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22913. } else {
  22914. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22915. return;
  22916. }
  22917. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22918. animation.setKeys(keys);
  22919. if (this.stopOtherAnimations) {
  22920. scene.stopAnimation(this._target);
  22921. }
  22922. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22923. };
  22924. return InterpolateValueAction;
  22925. })(BABYLON.Action);
  22926. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22927. })(BABYLON || (BABYLON = {}));
  22928. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22929. var BABYLON;
  22930. (function (BABYLON) {
  22931. var SwitchBooleanAction = (function (_super) {
  22932. __extends(SwitchBooleanAction, _super);
  22933. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22934. _super.call(this, triggerOptions, condition);
  22935. this.propertyPath = propertyPath;
  22936. this._target = target;
  22937. }
  22938. SwitchBooleanAction.prototype._prepare = function () {
  22939. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22940. this._property = this._getProperty(this.propertyPath);
  22941. };
  22942. SwitchBooleanAction.prototype.execute = function () {
  22943. this._target[this._property] = !this._target[this._property];
  22944. };
  22945. return SwitchBooleanAction;
  22946. })(BABYLON.Action);
  22947. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22948. var SetStateAction = (function (_super) {
  22949. __extends(SetStateAction, _super);
  22950. function SetStateAction(triggerOptions, target, value, condition) {
  22951. _super.call(this, triggerOptions, condition);
  22952. this.value = value;
  22953. this._target = target;
  22954. }
  22955. SetStateAction.prototype.execute = function () {
  22956. this._target.state = this.value;
  22957. };
  22958. return SetStateAction;
  22959. })(BABYLON.Action);
  22960. BABYLON.SetStateAction = SetStateAction;
  22961. var SetValueAction = (function (_super) {
  22962. __extends(SetValueAction, _super);
  22963. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22964. _super.call(this, triggerOptions, condition);
  22965. this.propertyPath = propertyPath;
  22966. this.value = value;
  22967. this._target = target;
  22968. }
  22969. SetValueAction.prototype._prepare = function () {
  22970. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22971. this._property = this._getProperty(this.propertyPath);
  22972. };
  22973. SetValueAction.prototype.execute = function () {
  22974. this._target[this._property] = this.value;
  22975. };
  22976. return SetValueAction;
  22977. })(BABYLON.Action);
  22978. BABYLON.SetValueAction = SetValueAction;
  22979. var IncrementValueAction = (function (_super) {
  22980. __extends(IncrementValueAction, _super);
  22981. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22982. _super.call(this, triggerOptions, condition);
  22983. this.propertyPath = propertyPath;
  22984. this.value = value;
  22985. this._target = target;
  22986. }
  22987. IncrementValueAction.prototype._prepare = function () {
  22988. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22989. this._property = this._getProperty(this.propertyPath);
  22990. if (typeof this._target[this._property] !== "number") {
  22991. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22992. }
  22993. };
  22994. IncrementValueAction.prototype.execute = function () {
  22995. this._target[this._property] += this.value;
  22996. };
  22997. return IncrementValueAction;
  22998. })(BABYLON.Action);
  22999. BABYLON.IncrementValueAction = IncrementValueAction;
  23000. var PlayAnimationAction = (function (_super) {
  23001. __extends(PlayAnimationAction, _super);
  23002. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23003. _super.call(this, triggerOptions, condition);
  23004. this.from = from;
  23005. this.to = to;
  23006. this.loop = loop;
  23007. this._target = target;
  23008. }
  23009. PlayAnimationAction.prototype._prepare = function () {
  23010. };
  23011. PlayAnimationAction.prototype.execute = function () {
  23012. var scene = this._actionManager.getScene();
  23013. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23014. };
  23015. return PlayAnimationAction;
  23016. })(BABYLON.Action);
  23017. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23018. var StopAnimationAction = (function (_super) {
  23019. __extends(StopAnimationAction, _super);
  23020. function StopAnimationAction(triggerOptions, target, condition) {
  23021. _super.call(this, triggerOptions, condition);
  23022. this._target = target;
  23023. }
  23024. StopAnimationAction.prototype._prepare = function () {
  23025. };
  23026. StopAnimationAction.prototype.execute = function () {
  23027. var scene = this._actionManager.getScene();
  23028. scene.stopAnimation(this._target);
  23029. };
  23030. return StopAnimationAction;
  23031. })(BABYLON.Action);
  23032. BABYLON.StopAnimationAction = StopAnimationAction;
  23033. var DoNothingAction = (function (_super) {
  23034. __extends(DoNothingAction, _super);
  23035. function DoNothingAction(triggerOptions, condition) {
  23036. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23037. _super.call(this, triggerOptions, condition);
  23038. }
  23039. DoNothingAction.prototype.execute = function () {
  23040. };
  23041. return DoNothingAction;
  23042. })(BABYLON.Action);
  23043. BABYLON.DoNothingAction = DoNothingAction;
  23044. var CombineAction = (function (_super) {
  23045. __extends(CombineAction, _super);
  23046. function CombineAction(triggerOptions, children, condition) {
  23047. _super.call(this, triggerOptions, condition);
  23048. this.children = children;
  23049. }
  23050. CombineAction.prototype._prepare = function () {
  23051. for (var index = 0; index < this.children.length; index++) {
  23052. this.children[index]._actionManager = this._actionManager;
  23053. this.children[index]._prepare();
  23054. }
  23055. };
  23056. CombineAction.prototype.execute = function (evt) {
  23057. for (var index = 0; index < this.children.length; index++) {
  23058. this.children[index].execute(evt);
  23059. }
  23060. };
  23061. return CombineAction;
  23062. })(BABYLON.Action);
  23063. BABYLON.CombineAction = CombineAction;
  23064. var ExecuteCodeAction = (function (_super) {
  23065. __extends(ExecuteCodeAction, _super);
  23066. function ExecuteCodeAction(triggerOptions, func, condition) {
  23067. _super.call(this, triggerOptions, condition);
  23068. this.func = func;
  23069. }
  23070. ExecuteCodeAction.prototype.execute = function (evt) {
  23071. this.func(evt);
  23072. };
  23073. return ExecuteCodeAction;
  23074. })(BABYLON.Action);
  23075. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23076. var SetParentAction = (function (_super) {
  23077. __extends(SetParentAction, _super);
  23078. function SetParentAction(triggerOptions, target, parent, condition) {
  23079. _super.call(this, triggerOptions, condition);
  23080. this._target = target;
  23081. this._parent = parent;
  23082. }
  23083. SetParentAction.prototype._prepare = function () {
  23084. };
  23085. SetParentAction.prototype.execute = function () {
  23086. if (this._target.parent === this._parent) {
  23087. return;
  23088. }
  23089. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23090. invertParentWorldMatrix.invert();
  23091. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23092. this._target.parent = this._parent;
  23093. };
  23094. return SetParentAction;
  23095. })(BABYLON.Action);
  23096. BABYLON.SetParentAction = SetParentAction;
  23097. })(BABYLON || (BABYLON = {}));
  23098. //# sourceMappingURL=babylon.directActions.js.map
  23099. var BABYLON;
  23100. (function (BABYLON) {
  23101. var Geometry = (function () {
  23102. function Geometry(id, scene, vertexData, updatable, mesh) {
  23103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23104. this._totalVertices = 0;
  23105. this._indices = [];
  23106. this.id = id;
  23107. this._engine = scene.getEngine();
  23108. this._meshes = [];
  23109. this._scene = scene;
  23110. // vertexData
  23111. if (vertexData) {
  23112. this.setAllVerticesData(vertexData, updatable);
  23113. } else {
  23114. this._totalVertices = 0;
  23115. this._indices = [];
  23116. }
  23117. // applyToMesh
  23118. if (mesh) {
  23119. this.applyToMesh(mesh);
  23120. }
  23121. }
  23122. Geometry.prototype.getScene = function () {
  23123. return this._scene;
  23124. };
  23125. Geometry.prototype.getEngine = function () {
  23126. return this._engine;
  23127. };
  23128. Geometry.prototype.isReady = function () {
  23129. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23130. };
  23131. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23132. vertexData.applyToGeometry(this, updatable);
  23133. };
  23134. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23135. this._vertexBuffers = this._vertexBuffers || {};
  23136. if (this._vertexBuffers[kind]) {
  23137. this._vertexBuffers[kind].dispose();
  23138. }
  23139. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23140. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23141. stride = this._vertexBuffers[kind].getStrideSize();
  23142. this._totalVertices = data.length / stride;
  23143. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23144. var meshes = this._meshes;
  23145. var numOfMeshes = meshes.length;
  23146. for (var index = 0; index < numOfMeshes; index++) {
  23147. var mesh = meshes[index];
  23148. mesh._resetPointsArrayCache();
  23149. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23150. mesh._createGlobalSubMesh();
  23151. mesh.computeWorldMatrix(true);
  23152. }
  23153. }
  23154. };
  23155. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23156. var vertexBuffer = this.getVertexBuffer(kind);
  23157. if (!vertexBuffer) {
  23158. return;
  23159. }
  23160. vertexBuffer.updateDirectly(data, offset);
  23161. };
  23162. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23163. var vertexBuffer = this.getVertexBuffer(kind);
  23164. if (!vertexBuffer) {
  23165. return;
  23166. }
  23167. vertexBuffer.update(data);
  23168. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23169. var extend;
  23170. var stride = vertexBuffer.getStrideSize();
  23171. this._totalVertices = data.length / stride;
  23172. if (updateExtends) {
  23173. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23174. }
  23175. var meshes = this._meshes;
  23176. var numOfMeshes = meshes.length;
  23177. for (var index = 0; index < numOfMeshes; index++) {
  23178. var mesh = meshes[index];
  23179. mesh._resetPointsArrayCache();
  23180. if (updateExtends) {
  23181. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23182. }
  23183. }
  23184. }
  23185. };
  23186. Geometry.prototype.getTotalVertices = function () {
  23187. if (!this.isReady()) {
  23188. return 0;
  23189. }
  23190. return this._totalVertices;
  23191. };
  23192. Geometry.prototype.getVerticesData = function (kind) {
  23193. var vertexBuffer = this.getVertexBuffer(kind);
  23194. if (!vertexBuffer) {
  23195. return null;
  23196. }
  23197. return vertexBuffer.getData();
  23198. };
  23199. Geometry.prototype.getVertexBuffer = function (kind) {
  23200. if (!this.isReady()) {
  23201. return null;
  23202. }
  23203. return this._vertexBuffers[kind];
  23204. };
  23205. Geometry.prototype.getVertexBuffers = function () {
  23206. if (!this.isReady()) {
  23207. return null;
  23208. }
  23209. return this._vertexBuffers;
  23210. };
  23211. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23212. if (!this._vertexBuffers) {
  23213. if (this._delayInfo) {
  23214. return this._delayInfo.indexOf(kind) !== -1;
  23215. }
  23216. return false;
  23217. }
  23218. return this._vertexBuffers[kind] !== undefined;
  23219. };
  23220. Geometry.prototype.getVerticesDataKinds = function () {
  23221. var result = [];
  23222. if (!this._vertexBuffers && this._delayInfo) {
  23223. for (var kind in this._delayInfo) {
  23224. result.push(kind);
  23225. }
  23226. } else {
  23227. for (kind in this._vertexBuffers) {
  23228. result.push(kind);
  23229. }
  23230. }
  23231. return result;
  23232. };
  23233. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23234. if (this._indexBuffer) {
  23235. this._engine._releaseBuffer(this._indexBuffer);
  23236. }
  23237. this._indices = indices;
  23238. if (this._meshes.length !== 0 && this._indices) {
  23239. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23240. }
  23241. if (totalVertices !== undefined) {
  23242. this._totalVertices = totalVertices;
  23243. }
  23244. var meshes = this._meshes;
  23245. var numOfMeshes = meshes.length;
  23246. for (var index = 0; index < numOfMeshes; index++) {
  23247. meshes[index]._createGlobalSubMesh();
  23248. }
  23249. };
  23250. Geometry.prototype.getTotalIndices = function () {
  23251. if (!this.isReady()) {
  23252. return 0;
  23253. }
  23254. return this._indices.length;
  23255. };
  23256. Geometry.prototype.getIndices = function () {
  23257. if (!this.isReady()) {
  23258. return null;
  23259. }
  23260. return this._indices;
  23261. };
  23262. Geometry.prototype.getIndexBuffer = function () {
  23263. if (!this.isReady()) {
  23264. return null;
  23265. }
  23266. return this._indexBuffer;
  23267. };
  23268. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23269. var meshes = this._meshes;
  23270. var index = meshes.indexOf(mesh);
  23271. if (index === -1) {
  23272. return;
  23273. }
  23274. for (var kind in this._vertexBuffers) {
  23275. this._vertexBuffers[kind].dispose();
  23276. }
  23277. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23278. this._indexBuffer = null;
  23279. }
  23280. meshes.splice(index, 1);
  23281. mesh._geometry = null;
  23282. if (meshes.length === 0 && shouldDispose) {
  23283. this.dispose();
  23284. }
  23285. };
  23286. Geometry.prototype.applyToMesh = function (mesh) {
  23287. if (mesh._geometry === this) {
  23288. return;
  23289. }
  23290. var previousGeometry = mesh._geometry;
  23291. if (previousGeometry) {
  23292. previousGeometry.releaseForMesh(mesh);
  23293. }
  23294. var meshes = this._meshes;
  23295. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23296. mesh._geometry = this;
  23297. this._scene.pushGeometry(this);
  23298. meshes.push(mesh);
  23299. if (this.isReady()) {
  23300. this._applyToMesh(mesh);
  23301. } else {
  23302. mesh._boundingInfo = this._boundingInfo;
  23303. }
  23304. };
  23305. Geometry.prototype._applyToMesh = function (mesh) {
  23306. var numOfMeshes = this._meshes.length;
  23307. for (var kind in this._vertexBuffers) {
  23308. if (numOfMeshes === 1) {
  23309. this._vertexBuffers[kind].create();
  23310. }
  23311. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23312. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23313. mesh._resetPointsArrayCache();
  23314. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23315. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23316. mesh._createGlobalSubMesh();
  23317. //bounding info was just created again, world matrix should be applied again.
  23318. mesh._updateBoundingInfo();
  23319. }
  23320. }
  23321. // indexBuffer
  23322. if (numOfMeshes === 1 && this._indices) {
  23323. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23324. }
  23325. if (this._indexBuffer) {
  23326. this._indexBuffer.references = numOfMeshes;
  23327. }
  23328. };
  23329. Geometry.prototype.load = function (scene, onLoaded) {
  23330. var _this = this;
  23331. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23332. return;
  23333. }
  23334. if (this.isReady()) {
  23335. if (onLoaded) {
  23336. onLoaded();
  23337. }
  23338. return;
  23339. }
  23340. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23341. scene._addPendingData(this);
  23342. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23343. _this._delayLoadingFunction(JSON.parse(data), _this);
  23344. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23345. _this._delayInfo = [];
  23346. scene._removePendingData(_this);
  23347. var meshes = _this._meshes;
  23348. var numOfMeshes = meshes.length;
  23349. for (var index = 0; index < numOfMeshes; index++) {
  23350. _this._applyToMesh(meshes[index]);
  23351. }
  23352. if (onLoaded) {
  23353. onLoaded();
  23354. }
  23355. }, function () {
  23356. }, scene.database);
  23357. };
  23358. Geometry.prototype.dispose = function () {
  23359. var meshes = this._meshes;
  23360. var numOfMeshes = meshes.length;
  23361. var index;
  23362. for (index = 0; index < numOfMeshes; index++) {
  23363. this.releaseForMesh(meshes[index]);
  23364. }
  23365. this._meshes = [];
  23366. for (var kind in this._vertexBuffers) {
  23367. this._vertexBuffers[kind].dispose();
  23368. }
  23369. this._vertexBuffers = [];
  23370. this._totalVertices = 0;
  23371. if (this._indexBuffer) {
  23372. this._engine._releaseBuffer(this._indexBuffer);
  23373. }
  23374. this._indexBuffer = null;
  23375. this._indices = [];
  23376. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23377. this.delayLoadingFile = null;
  23378. this._delayLoadingFunction = null;
  23379. this._delayInfo = [];
  23380. this._boundingInfo = null; // todo: .dispose()
  23381. var geometries = this._scene.getGeometries();
  23382. index = geometries.indexOf(this);
  23383. if (index > -1) {
  23384. geometries.splice(index, 1);
  23385. }
  23386. };
  23387. Geometry.prototype.copy = function (id) {
  23388. var vertexData = new BABYLON.VertexData();
  23389. vertexData.indices = [];
  23390. var indices = this.getIndices();
  23391. for (var index = 0; index < indices.length; index++) {
  23392. vertexData.indices.push(indices[index]);
  23393. }
  23394. var updatable = false;
  23395. var stopChecking = false;
  23396. for (var kind in this._vertexBuffers) {
  23397. vertexData.set(this.getVerticesData(kind), kind);
  23398. if (!stopChecking) {
  23399. updatable = this.getVertexBuffer(kind).isUpdatable();
  23400. stopChecking = !updatable;
  23401. }
  23402. }
  23403. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23404. geometry.delayLoadState = this.delayLoadState;
  23405. geometry.delayLoadingFile = this.delayLoadingFile;
  23406. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23407. for (kind in this._delayInfo) {
  23408. geometry._delayInfo = geometry._delayInfo || [];
  23409. geometry._delayInfo.push(kind);
  23410. }
  23411. // Bounding info
  23412. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23413. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23414. return geometry;
  23415. };
  23416. // Statics
  23417. Geometry.ExtractFromMesh = function (mesh, id) {
  23418. var geometry = mesh._geometry;
  23419. if (!geometry) {
  23420. return null;
  23421. }
  23422. return geometry.copy(id);
  23423. };
  23424. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23425. // be aware Math.random() could cause collisions
  23426. Geometry.RandomId = function () {
  23427. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23428. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23429. return v.toString(16);
  23430. });
  23431. };
  23432. return Geometry;
  23433. })();
  23434. BABYLON.Geometry = Geometry;
  23435. (function (Geometry) {
  23436. /////// Primitives //////////////////////////////////////////////
  23437. (function (Primitives) {
  23438. /// Abstract class
  23439. var _Primitive = (function (_super) {
  23440. __extends(_Primitive, _super);
  23441. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23442. this._beingRegenerated = true;
  23443. this._canBeRegenerated = canBeRegenerated;
  23444. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23445. this._beingRegenerated = false;
  23446. }
  23447. _Primitive.prototype.canBeRegenerated = function () {
  23448. return this._canBeRegenerated;
  23449. };
  23450. _Primitive.prototype.regenerate = function () {
  23451. if (!this._canBeRegenerated) {
  23452. return;
  23453. }
  23454. this._beingRegenerated = true;
  23455. this.setAllVerticesData(this._regenerateVertexData(), false);
  23456. this._beingRegenerated = false;
  23457. };
  23458. _Primitive.prototype.asNewGeometry = function (id) {
  23459. return _super.prototype.copy.call(this, id);
  23460. };
  23461. // overrides
  23462. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23463. if (!this._beingRegenerated) {
  23464. return;
  23465. }
  23466. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23467. };
  23468. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23469. if (!this._beingRegenerated) {
  23470. return;
  23471. }
  23472. _super.prototype.setVerticesData.call(this, kind, data, false);
  23473. };
  23474. // to override
  23475. // protected
  23476. _Primitive.prototype._regenerateVertexData = function () {
  23477. throw new Error("Abstract method");
  23478. };
  23479. _Primitive.prototype.copy = function (id) {
  23480. throw new Error("Must be overriden in sub-classes.");
  23481. };
  23482. return _Primitive;
  23483. })(Geometry);
  23484. Primitives._Primitive = _Primitive;
  23485. var Box = (function (_super) {
  23486. __extends(Box, _super);
  23487. function Box(id, scene, size, canBeRegenerated, mesh) {
  23488. this.size = size;
  23489. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23490. }
  23491. Box.prototype._regenerateVertexData = function () {
  23492. return BABYLON.VertexData.CreateBox(this.size);
  23493. };
  23494. Box.prototype.copy = function (id) {
  23495. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23496. };
  23497. return Box;
  23498. })(_Primitive);
  23499. Primitives.Box = Box;
  23500. var Sphere = (function (_super) {
  23501. __extends(Sphere, _super);
  23502. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23503. this.segments = segments;
  23504. this.diameter = diameter;
  23505. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23506. }
  23507. Sphere.prototype._regenerateVertexData = function () {
  23508. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23509. };
  23510. Sphere.prototype.copy = function (id) {
  23511. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23512. };
  23513. return Sphere;
  23514. })(_Primitive);
  23515. Primitives.Sphere = Sphere;
  23516. var Cylinder = (function (_super) {
  23517. __extends(Cylinder, _super);
  23518. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23519. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  23520. this.height = height;
  23521. this.diameterTop = diameterTop;
  23522. this.diameterBottom = diameterBottom;
  23523. this.tessellation = tessellation;
  23524. this.subdivisions = subdivisions;
  23525. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23526. }
  23527. Cylinder.prototype._regenerateVertexData = function () {
  23528. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23529. };
  23530. Cylinder.prototype.copy = function (id) {
  23531. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23532. };
  23533. return Cylinder;
  23534. })(_Primitive);
  23535. Primitives.Cylinder = Cylinder;
  23536. var Torus = (function (_super) {
  23537. __extends(Torus, _super);
  23538. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23539. this.diameter = diameter;
  23540. this.thickness = thickness;
  23541. this.tessellation = tessellation;
  23542. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23543. }
  23544. Torus.prototype._regenerateVertexData = function () {
  23545. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23546. };
  23547. Torus.prototype.copy = function (id) {
  23548. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23549. };
  23550. return Torus;
  23551. })(_Primitive);
  23552. Primitives.Torus = Torus;
  23553. var Ground = (function (_super) {
  23554. __extends(Ground, _super);
  23555. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23556. this.width = width;
  23557. this.height = height;
  23558. this.subdivisions = subdivisions;
  23559. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23560. }
  23561. Ground.prototype._regenerateVertexData = function () {
  23562. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23563. };
  23564. Ground.prototype.copy = function (id) {
  23565. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23566. };
  23567. return Ground;
  23568. })(_Primitive);
  23569. Primitives.Ground = Ground;
  23570. var TiledGround = (function (_super) {
  23571. __extends(TiledGround, _super);
  23572. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23573. this.xmin = xmin;
  23574. this.zmin = zmin;
  23575. this.xmax = xmax;
  23576. this.zmax = zmax;
  23577. this.subdivisions = subdivisions;
  23578. this.precision = precision;
  23579. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23580. }
  23581. TiledGround.prototype._regenerateVertexData = function () {
  23582. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23583. };
  23584. TiledGround.prototype.copy = function (id) {
  23585. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23586. };
  23587. return TiledGround;
  23588. })(_Primitive);
  23589. Primitives.TiledGround = TiledGround;
  23590. var Plane = (function (_super) {
  23591. __extends(Plane, _super);
  23592. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23593. this.size = size;
  23594. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23595. }
  23596. Plane.prototype._regenerateVertexData = function () {
  23597. return BABYLON.VertexData.CreatePlane(this.size);
  23598. };
  23599. Plane.prototype.copy = function (id) {
  23600. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23601. };
  23602. return Plane;
  23603. })(_Primitive);
  23604. Primitives.Plane = Plane;
  23605. var TorusKnot = (function (_super) {
  23606. __extends(TorusKnot, _super);
  23607. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23608. this.radius = radius;
  23609. this.tube = tube;
  23610. this.radialSegments = radialSegments;
  23611. this.tubularSegments = tubularSegments;
  23612. this.p = p;
  23613. this.q = q;
  23614. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23615. }
  23616. TorusKnot.prototype._regenerateVertexData = function () {
  23617. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23618. };
  23619. TorusKnot.prototype.copy = function (id) {
  23620. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23621. };
  23622. return TorusKnot;
  23623. })(_Primitive);
  23624. Primitives.TorusKnot = TorusKnot;
  23625. })(Geometry.Primitives || (Geometry.Primitives = {}));
  23626. var Primitives = Geometry.Primitives;
  23627. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  23628. var Geometry = BABYLON.Geometry;
  23629. })(BABYLON || (BABYLON = {}));
  23630. //# sourceMappingURL=babylon.geometry.js.map
  23631. var BABYLON;
  23632. (function (BABYLON) {
  23633. var Gamepads = (function () {
  23634. function Gamepads(ongamedpadconnected) {
  23635. var _this = this;
  23636. this.babylonGamepads = [];
  23637. this.oneGamepadConnected = false;
  23638. this.isMonitoring = false;
  23639. this.gamepadEventSupported = 'GamepadEvent' in window;
  23640. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23641. 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=";
  23642. this._callbackGamepadConnected = ongamedpadconnected;
  23643. if (this.gamepadSupportAvailable) {
  23644. // Checking if the gamepad connected event is supported (like in Firefox)
  23645. if (this.gamepadEventSupported) {
  23646. window.addEventListener('gamepadconnected', function (evt) {
  23647. _this._onGamepadConnected(evt);
  23648. }, false);
  23649. window.addEventListener('gamepaddisconnected', function (evt) {
  23650. _this._onGamepadDisconnected(evt);
  23651. }, false);
  23652. } else {
  23653. this._startMonitoringGamepads();
  23654. }
  23655. if (!this.oneGamepadConnected) {
  23656. this._insertGamepadDOMInstructions();
  23657. }
  23658. } else {
  23659. this._insertGamepadDOMNotSupported();
  23660. }
  23661. }
  23662. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23663. Gamepads.gamepadDOMInfo = document.createElement("div");
  23664. var buttonAImage = document.createElement("img");
  23665. buttonAImage.src = this.buttonADataURL;
  23666. var spanMessage = document.createElement("span");
  23667. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23668. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23669. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23670. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23671. Gamepads.gamepadDOMInfo.style.width = "100%";
  23672. Gamepads.gamepadDOMInfo.style.height = "48px";
  23673. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23674. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23675. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23676. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23677. buttonAImage.style.position = "relative";
  23678. buttonAImage.style.bottom = "8px";
  23679. spanMessage.style.position = "relative";
  23680. spanMessage.style.fontSize = "32px";
  23681. spanMessage.style.bottom = "32px";
  23682. spanMessage.style.color = "green";
  23683. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23684. };
  23685. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  23686. Gamepads.gamepadDOMInfo = document.createElement("div");
  23687. var spanMessage = document.createElement("span");
  23688. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  23689. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23690. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23691. Gamepads.gamepadDOMInfo.style.width = "100%";
  23692. Gamepads.gamepadDOMInfo.style.height = "40px";
  23693. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23694. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23695. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23696. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23697. spanMessage.style.position = "relative";
  23698. spanMessage.style.fontSize = "32px";
  23699. spanMessage.style.color = "red";
  23700. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23701. };
  23702. Gamepads.prototype.dispose = function () {
  23703. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23704. };
  23705. Gamepads.prototype._onGamepadConnected = function (evt) {
  23706. var newGamepad = this._addNewGamepad(evt.gamepad);
  23707. if (this._callbackGamepadConnected)
  23708. this._callbackGamepadConnected(newGamepad);
  23709. this._startMonitoringGamepads();
  23710. };
  23711. Gamepads.prototype._addNewGamepad = function (gamepad) {
  23712. if (!this.oneGamepadConnected) {
  23713. this.oneGamepadConnected = true;
  23714. if (Gamepads.gamepadDOMInfo) {
  23715. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23716. Gamepads.gamepadDOMInfo = null;
  23717. }
  23718. }
  23719. var newGamepad;
  23720. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  23721. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  23722. } else {
  23723. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  23724. }
  23725. this.babylonGamepads.push(newGamepad);
  23726. return newGamepad;
  23727. };
  23728. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  23729. for (var i in this.babylonGamepads) {
  23730. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  23731. this.babylonGamepads.splice(i, 1);
  23732. break;
  23733. }
  23734. }
  23735. // If no gamepads are left, stop the polling loop.
  23736. if (this.babylonGamepads.length == 0) {
  23737. this._stopMonitoringGamepads();
  23738. }
  23739. };
  23740. Gamepads.prototype._startMonitoringGamepads = function () {
  23741. if (!this.isMonitoring) {
  23742. this.isMonitoring = true;
  23743. this._checkGamepadsStatus();
  23744. }
  23745. };
  23746. Gamepads.prototype._stopMonitoringGamepads = function () {
  23747. this.isMonitoring = false;
  23748. };
  23749. Gamepads.prototype._checkGamepadsStatus = function () {
  23750. var _this = this;
  23751. // updating gamepad objects
  23752. this._updateGamepadObjects();
  23753. for (var i in this.babylonGamepads) {
  23754. this.babylonGamepads[i].update();
  23755. }
  23756. if (this.isMonitoring) {
  23757. if (window.requestAnimationFrame) {
  23758. window.requestAnimationFrame(function () {
  23759. _this._checkGamepadsStatus();
  23760. });
  23761. } else if (window.mozRequestAnimationFrame) {
  23762. window.mozRequestAnimationFrame(function () {
  23763. _this._checkGamepadsStatus();
  23764. });
  23765. } else if (window.webkitRequestAnimationFrame) {
  23766. window.webkitRequestAnimationFrame(function () {
  23767. _this._checkGamepadsStatus();
  23768. });
  23769. }
  23770. }
  23771. };
  23772. // This function is called only on Chrome, which does not yet support
  23773. // connection/disconnection events, but requires you to monitor
  23774. // an array for changes.
  23775. Gamepads.prototype._updateGamepadObjects = function () {
  23776. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  23777. for (var i = 0; i < gamepads.length; i++) {
  23778. if (gamepads[i]) {
  23779. if (!(gamepads[i].index in this.babylonGamepads)) {
  23780. var newGamepad = this._addNewGamepad(gamepads[i]);
  23781. if (this._callbackGamepadConnected) {
  23782. this._callbackGamepadConnected(newGamepad);
  23783. }
  23784. } else {
  23785. this.babylonGamepads[i].browserGamepad = gamepads[i];
  23786. }
  23787. }
  23788. }
  23789. };
  23790. return Gamepads;
  23791. })();
  23792. BABYLON.Gamepads = Gamepads;
  23793. var StickValues = (function () {
  23794. function StickValues(x, y) {
  23795. this.x = x;
  23796. this.y = y;
  23797. }
  23798. return StickValues;
  23799. })();
  23800. BABYLON.StickValues = StickValues;
  23801. var Gamepad = (function () {
  23802. function Gamepad(id, index, browserGamepad) {
  23803. this.id = id;
  23804. this.index = index;
  23805. this.browserGamepad = browserGamepad;
  23806. if (this.browserGamepad.axes.length >= 2) {
  23807. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23808. }
  23809. if (this.browserGamepad.axes.length >= 4) {
  23810. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23811. }
  23812. }
  23813. Gamepad.prototype.onleftstickchanged = function (callback) {
  23814. this._onleftstickchanged = callback;
  23815. };
  23816. Gamepad.prototype.onrightstickchanged = function (callback) {
  23817. this._onrightstickchanged = callback;
  23818. };
  23819. Object.defineProperty(Gamepad.prototype, "leftStick", {
  23820. get: function () {
  23821. return this._leftStick;
  23822. },
  23823. set: function (newValues) {
  23824. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  23825. this._onleftstickchanged(newValues);
  23826. }
  23827. this._leftStick = newValues;
  23828. },
  23829. enumerable: true,
  23830. configurable: true
  23831. });
  23832. Object.defineProperty(Gamepad.prototype, "rightStick", {
  23833. get: function () {
  23834. return this._rightStick;
  23835. },
  23836. set: function (newValues) {
  23837. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  23838. this._onrightstickchanged(newValues);
  23839. }
  23840. this._rightStick = newValues;
  23841. },
  23842. enumerable: true,
  23843. configurable: true
  23844. });
  23845. Gamepad.prototype.update = function () {
  23846. if (this._leftStick) {
  23847. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23848. }
  23849. if (this._rightStick) {
  23850. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23851. }
  23852. };
  23853. return Gamepad;
  23854. })();
  23855. BABYLON.Gamepad = Gamepad;
  23856. var GenericPad = (function (_super) {
  23857. __extends(GenericPad, _super);
  23858. function GenericPad(id, index, gamepad) {
  23859. _super.call(this, id, index, gamepad);
  23860. this.id = id;
  23861. this.index = index;
  23862. this.gamepad = gamepad;
  23863. this._buttons = new Array(gamepad.buttons.length);
  23864. }
  23865. GenericPad.prototype.onbuttondown = function (callback) {
  23866. this._onbuttondown = callback;
  23867. };
  23868. GenericPad.prototype.onbuttonup = function (callback) {
  23869. this._onbuttonup = callback;
  23870. };
  23871. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  23872. if (newValue !== currentValue) {
  23873. if (this._onbuttondown && newValue === 1) {
  23874. this._onbuttondown(buttonIndex);
  23875. }
  23876. if (this._onbuttonup && newValue === 0) {
  23877. this._onbuttonup(buttonIndex);
  23878. }
  23879. }
  23880. return newValue;
  23881. };
  23882. GenericPad.prototype.update = function () {
  23883. _super.prototype.update.call(this);
  23884. for (var index = 0; index < this._buttons.length; index++) {
  23885. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23886. }
  23887. };
  23888. return GenericPad;
  23889. })(Gamepad);
  23890. BABYLON.GenericPad = GenericPad;
  23891. (function (Xbox360Button) {
  23892. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23893. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23894. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23895. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23896. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23897. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23898. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23899. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23900. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23901. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23902. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23903. var Xbox360Button = BABYLON.Xbox360Button;
  23904. (function (Xbox360Dpad) {
  23905. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23906. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23907. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23908. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23909. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23910. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23911. var Xbox360Pad = (function (_super) {
  23912. __extends(Xbox360Pad, _super);
  23913. function Xbox360Pad() {
  23914. _super.apply(this, arguments);
  23915. this._leftTrigger = 0;
  23916. this._rightTrigger = 0;
  23917. this._buttonA = 0;
  23918. this._buttonB = 0;
  23919. this._buttonX = 0;
  23920. this._buttonY = 0;
  23921. this._buttonBack = 0;
  23922. this._buttonStart = 0;
  23923. this._buttonLB = 0;
  23924. this._buttonRB = 0;
  23925. this._buttonLeftStick = 0;
  23926. this._buttonRightStick = 0;
  23927. this._dPadUp = 0;
  23928. this._dPadDown = 0;
  23929. this._dPadLeft = 0;
  23930. this._dPadRight = 0;
  23931. }
  23932. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23933. this._onlefttriggerchanged = callback;
  23934. };
  23935. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23936. this._onrighttriggerchanged = callback;
  23937. };
  23938. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23939. get: function () {
  23940. return this._leftTrigger;
  23941. },
  23942. set: function (newValue) {
  23943. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23944. this._onlefttriggerchanged(newValue);
  23945. }
  23946. this._leftTrigger = newValue;
  23947. },
  23948. enumerable: true,
  23949. configurable: true
  23950. });
  23951. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23952. get: function () {
  23953. return this._rightTrigger;
  23954. },
  23955. set: function (newValue) {
  23956. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23957. this._onrighttriggerchanged(newValue);
  23958. }
  23959. this._rightTrigger = newValue;
  23960. },
  23961. enumerable: true,
  23962. configurable: true
  23963. });
  23964. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23965. this._onbuttondown = callback;
  23966. };
  23967. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23968. this._onbuttonup = callback;
  23969. };
  23970. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23971. this._ondpaddown = callback;
  23972. };
  23973. Xbox360Pad.prototype.ondpadup = function (callback) {
  23974. this._ondpadup = callback;
  23975. };
  23976. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23977. if (newValue !== currentValue) {
  23978. if (this._onbuttondown && newValue === 1) {
  23979. this._onbuttondown(buttonType);
  23980. }
  23981. if (this._onbuttonup && newValue === 0) {
  23982. this._onbuttonup(buttonType);
  23983. }
  23984. }
  23985. return newValue;
  23986. };
  23987. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23988. if (newValue !== currentValue) {
  23989. if (this._ondpaddown && newValue === 1) {
  23990. this._ondpaddown(buttonType);
  23991. }
  23992. if (this._ondpadup && newValue === 0) {
  23993. this._ondpadup(buttonType);
  23994. }
  23995. }
  23996. return newValue;
  23997. };
  23998. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23999. get: function () {
  24000. return this._buttonA;
  24001. },
  24002. set: function (value) {
  24003. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24004. },
  24005. enumerable: true,
  24006. configurable: true
  24007. });
  24008. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24009. get: function () {
  24010. return this._buttonB;
  24011. },
  24012. set: function (value) {
  24013. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24014. },
  24015. enumerable: true,
  24016. configurable: true
  24017. });
  24018. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24019. get: function () {
  24020. return this._buttonX;
  24021. },
  24022. set: function (value) {
  24023. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24024. },
  24025. enumerable: true,
  24026. configurable: true
  24027. });
  24028. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24029. get: function () {
  24030. return this._buttonY;
  24031. },
  24032. set: function (value) {
  24033. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24034. },
  24035. enumerable: true,
  24036. configurable: true
  24037. });
  24038. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24039. get: function () {
  24040. return this._buttonStart;
  24041. },
  24042. set: function (value) {
  24043. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24044. },
  24045. enumerable: true,
  24046. configurable: true
  24047. });
  24048. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24049. get: function () {
  24050. return this._buttonBack;
  24051. },
  24052. set: function (value) {
  24053. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24054. },
  24055. enumerable: true,
  24056. configurable: true
  24057. });
  24058. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24059. get: function () {
  24060. return this._buttonLB;
  24061. },
  24062. set: function (value) {
  24063. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24064. },
  24065. enumerable: true,
  24066. configurable: true
  24067. });
  24068. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24069. get: function () {
  24070. return this._buttonRB;
  24071. },
  24072. set: function (value) {
  24073. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24074. },
  24075. enumerable: true,
  24076. configurable: true
  24077. });
  24078. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24079. get: function () {
  24080. return this._buttonLeftStick;
  24081. },
  24082. set: function (value) {
  24083. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24084. },
  24085. enumerable: true,
  24086. configurable: true
  24087. });
  24088. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24089. get: function () {
  24090. return this._buttonRightStick;
  24091. },
  24092. set: function (value) {
  24093. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24094. },
  24095. enumerable: true,
  24096. configurable: true
  24097. });
  24098. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24099. get: function () {
  24100. return this._dPadUp;
  24101. },
  24102. set: function (value) {
  24103. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24104. },
  24105. enumerable: true,
  24106. configurable: true
  24107. });
  24108. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24109. get: function () {
  24110. return this._dPadDown;
  24111. },
  24112. set: function (value) {
  24113. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24114. },
  24115. enumerable: true,
  24116. configurable: true
  24117. });
  24118. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24119. get: function () {
  24120. return this._dPadLeft;
  24121. },
  24122. set: function (value) {
  24123. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24124. },
  24125. enumerable: true,
  24126. configurable: true
  24127. });
  24128. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24129. get: function () {
  24130. return this._dPadRight;
  24131. },
  24132. set: function (value) {
  24133. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24134. },
  24135. enumerable: true,
  24136. configurable: true
  24137. });
  24138. Xbox360Pad.prototype.update = function () {
  24139. _super.prototype.update.call(this);
  24140. this.buttonA = this.browserGamepad.buttons[0].value;
  24141. this.buttonB = this.browserGamepad.buttons[1].value;
  24142. this.buttonX = this.browserGamepad.buttons[2].value;
  24143. this.buttonY = this.browserGamepad.buttons[3].value;
  24144. this.buttonLB = this.browserGamepad.buttons[4].value;
  24145. this.buttonRB = this.browserGamepad.buttons[5].value;
  24146. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24147. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24148. this.buttonBack = this.browserGamepad.buttons[8].value;
  24149. this.buttonStart = this.browserGamepad.buttons[9].value;
  24150. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24151. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24152. this.dPadUp = this.browserGamepad.buttons[12].value;
  24153. this.dPadDown = this.browserGamepad.buttons[13].value;
  24154. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24155. this.dPadRight = this.browserGamepad.buttons[15].value;
  24156. };
  24157. return Xbox360Pad;
  24158. })(Gamepad);
  24159. BABYLON.Xbox360Pad = Xbox360Pad;
  24160. })(BABYLON || (BABYLON = {}));
  24161. //# sourceMappingURL=babylon.gamepads.js.map
  24162. var BABYLON;
  24163. (function (BABYLON) {
  24164. // We're mainly based on the logic defined into the FreeCamera code
  24165. var GamepadCamera = (function (_super) {
  24166. __extends(GamepadCamera, _super);
  24167. function GamepadCamera(name, position, scene) {
  24168. var _this = this;
  24169. _super.call(this, name, position, scene);
  24170. this.angularSensibility = 200;
  24171. this.moveSensibility = 75;
  24172. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24173. _this._onNewGameConnected(gamepad);
  24174. });
  24175. }
  24176. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24177. // Only the first gamepad can control the camera
  24178. if (gamepad.index === 0) {
  24179. this._gamepad = gamepad;
  24180. }
  24181. };
  24182. GamepadCamera.prototype._checkInputs = function () {
  24183. if (!this._gamepad) {
  24184. return;
  24185. }
  24186. var LSValues = this._gamepad.leftStick;
  24187. var normalizedLX = LSValues.x / this.moveSensibility;
  24188. var normalizedLY = LSValues.y / this.moveSensibility;
  24189. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24190. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24191. var RSValues = this._gamepad.rightStick;
  24192. var normalizedRX = RSValues.x / this.angularSensibility;
  24193. var normalizedRY = RSValues.y / this.angularSensibility;
  24194. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24195. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24196. ;
  24197. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24198. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  24199. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24200. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24201. };
  24202. GamepadCamera.prototype.dispose = function () {
  24203. this._gamepads.dispose();
  24204. _super.prototype.dispose.call(this);
  24205. };
  24206. return GamepadCamera;
  24207. })(BABYLON.FreeCamera);
  24208. BABYLON.GamepadCamera = GamepadCamera;
  24209. })(BABYLON || (BABYLON = {}));
  24210. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24211. var BABYLON;
  24212. (function (BABYLON) {
  24213. var LinesMesh = (function (_super) {
  24214. __extends(LinesMesh, _super);
  24215. function LinesMesh(name, scene, updatable) {
  24216. if (typeof updatable === "undefined") { updatable = false; }
  24217. _super.call(this, name, scene);
  24218. this.color = new BABYLON.Color3(1, 1, 1);
  24219. this.alpha = 1;
  24220. this._indices = new Array();
  24221. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24222. attributes: ["position"],
  24223. uniforms: ["worldViewProjection", "color"],
  24224. needAlphaBlending: true
  24225. });
  24226. }
  24227. Object.defineProperty(LinesMesh.prototype, "material", {
  24228. get: function () {
  24229. return this._colorShader;
  24230. },
  24231. enumerable: true,
  24232. configurable: true
  24233. });
  24234. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24235. get: function () {
  24236. return false;
  24237. },
  24238. enumerable: true,
  24239. configurable: true
  24240. });
  24241. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24242. get: function () {
  24243. return false;
  24244. },
  24245. enumerable: true,
  24246. configurable: true
  24247. });
  24248. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24249. var engine = this.getScene().getEngine();
  24250. var indexToBind = this._geometry.getIndexBuffer();
  24251. // VBOs
  24252. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24253. // Color
  24254. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24255. };
  24256. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24257. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24258. return;
  24259. }
  24260. var engine = this.getScene().getEngine();
  24261. // Draw order
  24262. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24263. };
  24264. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24265. return null;
  24266. };
  24267. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24268. this._colorShader.dispose();
  24269. _super.prototype.dispose.call(this, doNotRecurse);
  24270. };
  24271. return LinesMesh;
  24272. })(BABYLON.Mesh);
  24273. BABYLON.LinesMesh = LinesMesh;
  24274. })(BABYLON || (BABYLON = {}));
  24275. //# sourceMappingURL=babylon.linesMesh.js.map
  24276. var BABYLON;
  24277. (function (BABYLON) {
  24278. var OutlineRenderer = (function () {
  24279. function OutlineRenderer(scene) {
  24280. this._scene = scene;
  24281. }
  24282. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24283. if (typeof useOverlay === "undefined") { useOverlay = false; }
  24284. var scene = this._scene;
  24285. var engine = this._scene.getEngine();
  24286. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24287. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24288. return;
  24289. }
  24290. var mesh = subMesh.getRenderingMesh();
  24291. var material = subMesh.getMaterial();
  24292. engine.enableEffect(this._effect);
  24293. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24294. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24295. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24296. // Bones
  24297. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  24298. if (useBones) {
  24299. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24300. }
  24301. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24302. // Alpha test
  24303. if (material && material.needAlphaTesting()) {
  24304. var alphaTexture = material.getAlphaTestTexture();
  24305. this._effect.setTexture("diffuseSampler", alphaTexture);
  24306. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24307. }
  24308. if (hardwareInstancedRendering) {
  24309. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  24310. } else {
  24311. if (batch.renderSelf[subMesh._id]) {
  24312. this._effect.setMatrix("world", mesh.getWorldMatrix());
  24313. // Draw
  24314. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24315. }
  24316. if (batch.visibleInstances[subMesh._id]) {
  24317. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24318. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24319. this._effect.setMatrix("world", instance.getWorldMatrix());
  24320. // Draw
  24321. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24322. }
  24323. }
  24324. }
  24325. };
  24326. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24327. var defines = [];
  24328. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24329. var mesh = subMesh.getMesh();
  24330. var material = subMesh.getMaterial();
  24331. // Alpha test
  24332. if (material && material.needAlphaTesting()) {
  24333. defines.push("#define ALPHATEST");
  24334. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24335. attribs.push(BABYLON.VertexBuffer.UVKind);
  24336. defines.push("#define UV1");
  24337. }
  24338. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24339. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24340. defines.push("#define UV2");
  24341. }
  24342. }
  24343. // Bones
  24344. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24345. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24346. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24347. defines.push("#define BONES");
  24348. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24349. }
  24350. // Instances
  24351. if (useInstances) {
  24352. defines.push("#define INSTANCES");
  24353. attribs.push("world0");
  24354. attribs.push("world1");
  24355. attribs.push("world2");
  24356. attribs.push("world3");
  24357. }
  24358. // Get correct effect
  24359. var join = defines.join("\n");
  24360. if (this._cachedDefines != join) {
  24361. this._cachedDefines = join;
  24362. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24363. }
  24364. return this._effect.isReady();
  24365. };
  24366. return OutlineRenderer;
  24367. })();
  24368. BABYLON.OutlineRenderer = OutlineRenderer;
  24369. })(BABYLON || (BABYLON = {}));
  24370. //# sourceMappingURL=babylon.outlineRenderer.js.map
  24371. var BABYLON;
  24372. (function (BABYLON) {
  24373. var MeshAssetTask = (function () {
  24374. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24375. this.name = name;
  24376. this.meshesNames = meshesNames;
  24377. this.rootUrl = rootUrl;
  24378. this.sceneFilename = sceneFilename;
  24379. this.isCompleted = false;
  24380. }
  24381. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24382. var _this = this;
  24383. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24384. _this.loadedMeshes = meshes;
  24385. _this.loadedParticleSystems = particleSystems;
  24386. _this.loadedSkeletons = skeletons;
  24387. _this.isCompleted = true;
  24388. if (_this.onSuccess) {
  24389. _this.onSuccess(_this);
  24390. }
  24391. onSuccess();
  24392. }, null, function () {
  24393. if (_this.onError) {
  24394. _this.onError(_this);
  24395. }
  24396. onError();
  24397. });
  24398. };
  24399. return MeshAssetTask;
  24400. })();
  24401. BABYLON.MeshAssetTask = MeshAssetTask;
  24402. var TextFileAssetTask = (function () {
  24403. function TextFileAssetTask(name, url) {
  24404. this.name = name;
  24405. this.url = url;
  24406. this.isCompleted = false;
  24407. }
  24408. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24409. var _this = this;
  24410. BABYLON.Tools.LoadFile(this.url, function (data) {
  24411. _this.text = data;
  24412. _this.isCompleted = true;
  24413. if (_this.onSuccess) {
  24414. _this.onSuccess(_this);
  24415. }
  24416. onSuccess();
  24417. }, null, scene.database, false, function () {
  24418. if (_this.onError) {
  24419. _this.onError(_this);
  24420. }
  24421. onError();
  24422. });
  24423. };
  24424. return TextFileAssetTask;
  24425. })();
  24426. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24427. var BinaryFileAssetTask = (function () {
  24428. function BinaryFileAssetTask(name, url) {
  24429. this.name = name;
  24430. this.url = url;
  24431. this.isCompleted = false;
  24432. }
  24433. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24434. var _this = this;
  24435. BABYLON.Tools.LoadFile(this.url, function (data) {
  24436. _this.data = data;
  24437. _this.isCompleted = true;
  24438. if (_this.onSuccess) {
  24439. _this.onSuccess(_this);
  24440. }
  24441. onSuccess();
  24442. }, null, scene.database, true, function () {
  24443. if (_this.onError) {
  24444. _this.onError(_this);
  24445. }
  24446. onError();
  24447. });
  24448. };
  24449. return BinaryFileAssetTask;
  24450. })();
  24451. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24452. var ImageAssetTask = (function () {
  24453. function ImageAssetTask(name, url) {
  24454. this.name = name;
  24455. this.url = url;
  24456. this.isCompleted = false;
  24457. }
  24458. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24459. var _this = this;
  24460. var img = new Image();
  24461. img.onload = function () {
  24462. _this.image = img;
  24463. _this.isCompleted = true;
  24464. if (_this.onSuccess) {
  24465. _this.onSuccess(_this);
  24466. }
  24467. onSuccess();
  24468. };
  24469. img.onerror = function () {
  24470. if (_this.onError) {
  24471. _this.onError(_this);
  24472. }
  24473. onError();
  24474. };
  24475. img.src = this.url;
  24476. };
  24477. return ImageAssetTask;
  24478. })();
  24479. BABYLON.ImageAssetTask = ImageAssetTask;
  24480. var TextureAssetTask = (function () {
  24481. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24482. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24483. this.name = name;
  24484. this.url = url;
  24485. this.noMipmap = noMipmap;
  24486. this.invertY = invertY;
  24487. this.samplingMode = samplingMode;
  24488. this.isCompleted = false;
  24489. }
  24490. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24491. var _this = this;
  24492. var onload = function () {
  24493. _this.isCompleted = true;
  24494. if (_this.onSuccess) {
  24495. _this.onSuccess(_this);
  24496. }
  24497. onSuccess();
  24498. };
  24499. var onerror = function () {
  24500. if (_this.onError) {
  24501. _this.onError(_this);
  24502. }
  24503. onError();
  24504. };
  24505. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24506. };
  24507. return TextureAssetTask;
  24508. })();
  24509. BABYLON.TextureAssetTask = TextureAssetTask;
  24510. var AssetsManager = (function () {
  24511. function AssetsManager(scene) {
  24512. this._tasks = new Array();
  24513. this._waitingTasksCount = 0;
  24514. this.useDefaultLoadingScreen = true;
  24515. this._scene = scene;
  24516. }
  24517. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24518. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24519. this._tasks.push(task);
  24520. return task;
  24521. };
  24522. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24523. var task = new TextFileAssetTask(taskName, url);
  24524. this._tasks.push(task);
  24525. return task;
  24526. };
  24527. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24528. var task = new BinaryFileAssetTask(taskName, url);
  24529. this._tasks.push(task);
  24530. return task;
  24531. };
  24532. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24533. var task = new ImageAssetTask(taskName, url);
  24534. this._tasks.push(task);
  24535. return task;
  24536. };
  24537. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24538. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24539. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24540. this._tasks.push(task);
  24541. return task;
  24542. };
  24543. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24544. this._waitingTasksCount--;
  24545. if (this._waitingTasksCount === 0) {
  24546. if (this.onFinish) {
  24547. this.onFinish(this._tasks);
  24548. }
  24549. this._scene.getEngine().hideLoadingUI();
  24550. }
  24551. };
  24552. AssetsManager.prototype._runTask = function (task) {
  24553. var _this = this;
  24554. task.run(this._scene, function () {
  24555. if (_this.onTaskSuccess) {
  24556. _this.onTaskSuccess(task);
  24557. }
  24558. _this._decreaseWaitingTasksCount();
  24559. }, function () {
  24560. if (_this.onTaskError) {
  24561. _this.onTaskError(task);
  24562. }
  24563. _this._decreaseWaitingTasksCount();
  24564. });
  24565. };
  24566. AssetsManager.prototype.reset = function () {
  24567. this._tasks = new Array();
  24568. return this;
  24569. };
  24570. AssetsManager.prototype.load = function () {
  24571. this._waitingTasksCount = this._tasks.length;
  24572. if (this._waitingTasksCount === 0) {
  24573. if (this.onFinish) {
  24574. this.onFinish(this._tasks);
  24575. }
  24576. return this;
  24577. }
  24578. if (this.useDefaultLoadingScreen) {
  24579. this._scene.getEngine().displayLoadingUI();
  24580. }
  24581. for (var index = 0; index < this._tasks.length; index++) {
  24582. var task = this._tasks[index];
  24583. this._runTask(task);
  24584. }
  24585. return this;
  24586. };
  24587. return AssetsManager;
  24588. })();
  24589. BABYLON.AssetsManager = AssetsManager;
  24590. })(BABYLON || (BABYLON = {}));
  24591. //# sourceMappingURL=babylon.assetsManager.js.map
  24592. var BABYLON;
  24593. (function (BABYLON) {
  24594. var VRDeviceOrientationCamera = (function (_super) {
  24595. __extends(VRDeviceOrientationCamera, _super);
  24596. function VRDeviceOrientationCamera(name, position, scene) {
  24597. _super.call(this, name, position, scene);
  24598. this._alpha = 0;
  24599. this._beta = 0;
  24600. this._gamma = 0;
  24601. }
  24602. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24603. this._alpha = +evt.alpha | 0;
  24604. this._beta = +evt.beta | 0;
  24605. this._gamma = +evt.gamma | 0;
  24606. if (this._gamma < 0) {
  24607. this._gamma = 90 + this._gamma;
  24608. } else {
  24609. // Incline it in the correct angle.
  24610. this._gamma = 270 - this._gamma;
  24611. }
  24612. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24613. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24614. this.rotation.z = this._beta / 180.0 * Math.PI;
  24615. };
  24616. return VRDeviceOrientationCamera;
  24617. })(BABYLON.OculusCamera);
  24618. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24619. })(BABYLON || (BABYLON = {}));
  24620. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24621. var BABYLON;
  24622. (function (BABYLON) {
  24623. var WebVRCamera = (function (_super) {
  24624. __extends(WebVRCamera, _super);
  24625. function WebVRCamera(name, position, scene) {
  24626. _super.call(this, name, position, scene);
  24627. this._hmdDevice = null;
  24628. this._sensorDevice = null;
  24629. this._cacheState = null;
  24630. this._cacheQuaternion = new BABYLON.Quaternion();
  24631. this._cacheRotation = BABYLON.Vector3.Zero();
  24632. this._vrEnabled = false;
  24633. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24634. }
  24635. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24636. var size = devices.length;
  24637. var i = 0;
  24638. // Reset devices.
  24639. this._sensorDevice = null;
  24640. this._hmdDevice = null;
  24641. while (i < size && this._hmdDevice === null) {
  24642. if (devices[i] instanceof HMDVRDevice) {
  24643. this._hmdDevice = devices[i];
  24644. }
  24645. i++;
  24646. }
  24647. i = 0;
  24648. while (i < size && this._sensorDevice === null) {
  24649. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24650. this._sensorDevice = devices[i];
  24651. }
  24652. i++;
  24653. }
  24654. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24655. };
  24656. WebVRCamera.prototype._update = function () {
  24657. if (this._vrEnabled) {
  24658. this._cacheState = this._sensorDevice.getState();
  24659. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24660. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24661. this.rotation.x = -this._cacheRotation.z;
  24662. this.rotation.y = -this._cacheRotation.y;
  24663. this.rotation.z = this._cacheRotation.x;
  24664. }
  24665. _super.prototype._update.call(this);
  24666. };
  24667. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24668. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24669. if (navigator.getVRDevices) {
  24670. navigator.getVRDevices().then(this._getWebVRDevices);
  24671. } else if (navigator.mozGetVRDevices) {
  24672. navigator.mozGetVRDevices(this._getWebVRDevices);
  24673. }
  24674. };
  24675. WebVRCamera.prototype.detachControl = function (element) {
  24676. _super.prototype.detachControl.call(this, element);
  24677. this._vrEnabled = false;
  24678. };
  24679. return WebVRCamera;
  24680. })(BABYLON.OculusCamera);
  24681. BABYLON.WebVRCamera = WebVRCamera;
  24682. })(BABYLON || (BABYLON = {}));
  24683. //# sourceMappingURL=babylon.webVRCamera.js.map
  24684. var BABYLON;
  24685. (function (BABYLON) {
  24686. // Standard optimizations
  24687. var SceneOptimization = (function () {
  24688. function SceneOptimization(priority) {
  24689. if (typeof priority === "undefined") { priority = 0; }
  24690. this.priority = priority;
  24691. this.apply = function (scene) {
  24692. return true;
  24693. };
  24694. }
  24695. return SceneOptimization;
  24696. })();
  24697. BABYLON.SceneOptimization = SceneOptimization;
  24698. var TextureOptimization = (function (_super) {
  24699. __extends(TextureOptimization, _super);
  24700. function TextureOptimization(priority, maximumSize) {
  24701. if (typeof priority === "undefined") { priority = 0; }
  24702. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  24703. var _this = this;
  24704. _super.call(this, priority);
  24705. this.priority = priority;
  24706. this.maximumSize = maximumSize;
  24707. this.apply = function (scene) {
  24708. var allDone = true;
  24709. for (var index = 0; index < scene.textures.length; index++) {
  24710. var texture = scene.textures[index];
  24711. if (!texture.canRescale) {
  24712. continue;
  24713. }
  24714. var currentSize = texture.getSize();
  24715. var maxDimension = Math.max(currentSize.width, currentSize.height);
  24716. if (maxDimension > _this.maximumSize) {
  24717. texture.scale(0.5);
  24718. allDone = false;
  24719. }
  24720. }
  24721. return allDone;
  24722. };
  24723. }
  24724. return TextureOptimization;
  24725. })(SceneOptimization);
  24726. BABYLON.TextureOptimization = TextureOptimization;
  24727. var HardwareScalingOptimization = (function (_super) {
  24728. __extends(HardwareScalingOptimization, _super);
  24729. function HardwareScalingOptimization(priority, maximumScale) {
  24730. if (typeof priority === "undefined") { priority = 0; }
  24731. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  24732. var _this = this;
  24733. _super.call(this, priority);
  24734. this.priority = priority;
  24735. this.maximumScale = maximumScale;
  24736. this._currentScale = 1;
  24737. this.apply = function (scene) {
  24738. _this._currentScale++;
  24739. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  24740. return _this._currentScale >= _this.maximumScale;
  24741. };
  24742. }
  24743. return HardwareScalingOptimization;
  24744. })(SceneOptimization);
  24745. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  24746. var ShadowsOptimization = (function (_super) {
  24747. __extends(ShadowsOptimization, _super);
  24748. function ShadowsOptimization() {
  24749. _super.apply(this, arguments);
  24750. this.apply = function (scene) {
  24751. scene.shadowsEnabled = false;
  24752. return true;
  24753. };
  24754. }
  24755. return ShadowsOptimization;
  24756. })(SceneOptimization);
  24757. BABYLON.ShadowsOptimization = ShadowsOptimization;
  24758. var PostProcessesOptimization = (function (_super) {
  24759. __extends(PostProcessesOptimization, _super);
  24760. function PostProcessesOptimization() {
  24761. _super.apply(this, arguments);
  24762. this.apply = function (scene) {
  24763. scene.postProcessesEnabled = false;
  24764. return true;
  24765. };
  24766. }
  24767. return PostProcessesOptimization;
  24768. })(SceneOptimization);
  24769. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  24770. var LensFlaresOptimization = (function (_super) {
  24771. __extends(LensFlaresOptimization, _super);
  24772. function LensFlaresOptimization() {
  24773. _super.apply(this, arguments);
  24774. this.apply = function (scene) {
  24775. scene.lensFlaresEnabled = false;
  24776. return true;
  24777. };
  24778. }
  24779. return LensFlaresOptimization;
  24780. })(SceneOptimization);
  24781. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  24782. var ParticlesOptimization = (function (_super) {
  24783. __extends(ParticlesOptimization, _super);
  24784. function ParticlesOptimization() {
  24785. _super.apply(this, arguments);
  24786. this.apply = function (scene) {
  24787. scene.particlesEnabled = false;
  24788. return true;
  24789. };
  24790. }
  24791. return ParticlesOptimization;
  24792. })(SceneOptimization);
  24793. BABYLON.ParticlesOptimization = ParticlesOptimization;
  24794. var RenderTargetsOptimization = (function (_super) {
  24795. __extends(RenderTargetsOptimization, _super);
  24796. function RenderTargetsOptimization() {
  24797. _super.apply(this, arguments);
  24798. this.apply = function (scene) {
  24799. scene.renderTargetsEnabled = false;
  24800. return true;
  24801. };
  24802. }
  24803. return RenderTargetsOptimization;
  24804. })(SceneOptimization);
  24805. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  24806. var MergeMeshesOptimization = (function (_super) {
  24807. __extends(MergeMeshesOptimization, _super);
  24808. function MergeMeshesOptimization() {
  24809. _super.apply(this, arguments);
  24810. var _this = this;
  24811. this._canBeMerged = function (abstractMesh) {
  24812. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  24813. return false;
  24814. }
  24815. var mesh = abstractMesh;
  24816. if (!mesh.isVisible || !mesh.isEnabled()) {
  24817. return false;
  24818. }
  24819. if (mesh.instances.length > 0) {
  24820. return false;
  24821. }
  24822. if (mesh.skeleton || mesh.hasLODLevels) {
  24823. return false;
  24824. }
  24825. return true;
  24826. };
  24827. this.apply = function (scene) {
  24828. var globalPool = scene.meshes.slice(0);
  24829. var globalLength = globalPool.length;
  24830. for (var index = 0; index < globalLength; index++) {
  24831. var currentPool = new Array();
  24832. var current = globalPool[index];
  24833. // Checks
  24834. if (!_this._canBeMerged(current)) {
  24835. continue;
  24836. }
  24837. currentPool.push(current);
  24838. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  24839. var otherMesh = globalPool[subIndex];
  24840. if (!_this._canBeMerged(otherMesh)) {
  24841. continue;
  24842. }
  24843. if (otherMesh.material !== current.material) {
  24844. continue;
  24845. }
  24846. if (otherMesh.checkCollisions !== current.checkCollisions) {
  24847. continue;
  24848. }
  24849. currentPool.push(otherMesh);
  24850. globalLength--;
  24851. globalPool.splice(subIndex, 1);
  24852. subIndex--;
  24853. }
  24854. if (currentPool.length < 2) {
  24855. continue;
  24856. }
  24857. // Merge meshes
  24858. BABYLON.Mesh.MergeMeshes(currentPool);
  24859. }
  24860. return true;
  24861. };
  24862. }
  24863. return MergeMeshesOptimization;
  24864. })(SceneOptimization);
  24865. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  24866. // Options
  24867. var SceneOptimizerOptions = (function () {
  24868. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  24869. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  24870. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  24871. this.targetFrameRate = targetFrameRate;
  24872. this.trackerDuration = trackerDuration;
  24873. this.optimizations = new Array();
  24874. }
  24875. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24876. var result = new SceneOptimizerOptions(targetFrameRate);
  24877. var priority = 0;
  24878. result.optimizations.push(new MergeMeshesOptimization(priority));
  24879. result.optimizations.push(new ShadowsOptimization(priority));
  24880. result.optimizations.push(new LensFlaresOptimization(priority));
  24881. // Next priority
  24882. priority++;
  24883. result.optimizations.push(new PostProcessesOptimization(priority));
  24884. result.optimizations.push(new ParticlesOptimization(priority));
  24885. // Next priority
  24886. priority++;
  24887. result.optimizations.push(new TextureOptimization(priority, 1024));
  24888. return result;
  24889. };
  24890. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24891. var result = new SceneOptimizerOptions(targetFrameRate);
  24892. var priority = 0;
  24893. result.optimizations.push(new MergeMeshesOptimization(priority));
  24894. result.optimizations.push(new ShadowsOptimization(priority));
  24895. result.optimizations.push(new LensFlaresOptimization(priority));
  24896. // Next priority
  24897. priority++;
  24898. result.optimizations.push(new PostProcessesOptimization(priority));
  24899. result.optimizations.push(new ParticlesOptimization(priority));
  24900. // Next priority
  24901. priority++;
  24902. result.optimizations.push(new TextureOptimization(priority, 512));
  24903. // Next priority
  24904. priority++;
  24905. result.optimizations.push(new RenderTargetsOptimization(priority));
  24906. // Next priority
  24907. priority++;
  24908. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24909. return result;
  24910. };
  24911. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24912. var result = new SceneOptimizerOptions(targetFrameRate);
  24913. var priority = 0;
  24914. result.optimizations.push(new MergeMeshesOptimization(priority));
  24915. result.optimizations.push(new ShadowsOptimization(priority));
  24916. result.optimizations.push(new LensFlaresOptimization(priority));
  24917. // Next priority
  24918. priority++;
  24919. result.optimizations.push(new PostProcessesOptimization(priority));
  24920. result.optimizations.push(new ParticlesOptimization(priority));
  24921. // Next priority
  24922. priority++;
  24923. result.optimizations.push(new TextureOptimization(priority, 256));
  24924. // Next priority
  24925. priority++;
  24926. result.optimizations.push(new RenderTargetsOptimization(priority));
  24927. // Next priority
  24928. priority++;
  24929. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24930. return result;
  24931. };
  24932. return SceneOptimizerOptions;
  24933. })();
  24934. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24935. // Scene optimizer tool
  24936. var SceneOptimizer = (function () {
  24937. function SceneOptimizer() {
  24938. }
  24939. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24940. // TODO: add an epsilon
  24941. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24942. if (onSuccess) {
  24943. onSuccess();
  24944. }
  24945. return;
  24946. }
  24947. // Apply current level of optimizations
  24948. var allDone = true;
  24949. var noOptimizationApplied = true;
  24950. for (var index = 0; index < options.optimizations.length; index++) {
  24951. var optimization = options.optimizations[index];
  24952. if (optimization.priority === currentPriorityLevel) {
  24953. noOptimizationApplied = false;
  24954. allDone = allDone && optimization.apply(scene);
  24955. }
  24956. }
  24957. // If no optimization was applied, this is a failure :(
  24958. if (noOptimizationApplied) {
  24959. if (onFailure) {
  24960. onFailure();
  24961. }
  24962. return;
  24963. }
  24964. // If all optimizations were done, move to next level
  24965. if (allDone) {
  24966. currentPriorityLevel++;
  24967. }
  24968. // Let's the system running for a specific amount of time before checking FPS
  24969. scene.executeWhenReady(function () {
  24970. setTimeout(function () {
  24971. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24972. }, options.trackerDuration);
  24973. });
  24974. };
  24975. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24976. if (!options) {
  24977. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24978. }
  24979. // Let's the system running for a specific amount of time before checking FPS
  24980. scene.executeWhenReady(function () {
  24981. setTimeout(function () {
  24982. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24983. }, options.trackerDuration);
  24984. });
  24985. };
  24986. return SceneOptimizer;
  24987. })();
  24988. BABYLON.SceneOptimizer = SceneOptimizer;
  24989. })(BABYLON || (BABYLON = {}));
  24990. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24991. var BABYLON;
  24992. (function (BABYLON) {
  24993. (function (Internals) {
  24994. var MeshLODLevel = (function () {
  24995. function MeshLODLevel(distance, mesh) {
  24996. this.distance = distance;
  24997. this.mesh = mesh;
  24998. }
  24999. return MeshLODLevel;
  25000. })();
  25001. Internals.MeshLODLevel = MeshLODLevel;
  25002. })(BABYLON.Internals || (BABYLON.Internals = {}));
  25003. var Internals = BABYLON.Internals;
  25004. })(BABYLON || (BABYLON = {}));
  25005. //# sourceMappingURL=babylon.meshLODLevel.js.map
  25006. var BABYLON;
  25007. (function (BABYLON) {
  25008. var AudioEngine = (function () {
  25009. function AudioEngine() {
  25010. this.audioContext = null;
  25011. this.canUseWebAudio = false;
  25012. try {
  25013. if (typeof AudioContext !== 'undefined') {
  25014. this.audioContext = new AudioContext();
  25015. this.canUseWebAudio = true;
  25016. } else if (typeof webkitAudioContext !== 'undefined') {
  25017. this.audioContext = new webkitAudioContext();
  25018. this.canUseWebAudio = true;
  25019. }
  25020. } catch (e) {
  25021. this.canUseWebAudio = false;
  25022. BABYLON.Tools.Error("Your browser doesn't support Web Audio.");
  25023. }
  25024. // create a global volume gain node
  25025. if (this.canUseWebAudio) {
  25026. this.masterGain = this.audioContext.createGain();
  25027. this.masterGain.gain.value = 1;
  25028. this.masterGain.connect(this.audioContext.destination);
  25029. }
  25030. }
  25031. AudioEngine.prototype.dispose = function () {
  25032. if (this.canUseWebAudio) {
  25033. if (this._connectedAnalyser) {
  25034. this._connectedAnalyser.stopDebugCanvas();
  25035. }
  25036. this.canUseWebAudio = false;
  25037. this.masterGain.disconnect();
  25038. this.masterGain = null;
  25039. this.audioContext = null;
  25040. }
  25041. };
  25042. AudioEngine.prototype.getGlobalVolume = function () {
  25043. if (this.canUseWebAudio) {
  25044. return this.masterGain.gain.value;
  25045. } else {
  25046. return -1;
  25047. }
  25048. };
  25049. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25050. if (this.canUseWebAudio) {
  25051. this.masterGain.gain.value = newVolume;
  25052. }
  25053. };
  25054. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25055. if (this._connectedAnalyser) {
  25056. this._connectedAnalyser.stopDebugCanvas();
  25057. }
  25058. this._connectedAnalyser = analyser;
  25059. if (this.canUseWebAudio) {
  25060. this.masterGain.disconnect();
  25061. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25062. }
  25063. };
  25064. return AudioEngine;
  25065. })();
  25066. BABYLON.AudioEngine = AudioEngine;
  25067. })(BABYLON || (BABYLON = {}));
  25068. //# sourceMappingURL=babylon.audioengine.js.map
  25069. var BABYLON;
  25070. (function (BABYLON) {
  25071. var Sound = (function () {
  25072. /**
  25073. * Create a sound and attach it to a scene
  25074. * @param name Name of your sound
  25075. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25076. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25077. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25078. */
  25079. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25080. var _this = this;
  25081. this.autoplay = false;
  25082. this.loop = false;
  25083. this.useCustomAttenuation = false;
  25084. this.spatialSound = false;
  25085. this.refDistance = 1;
  25086. this.rolloffFactor = 1;
  25087. this.maxDistance = 100;
  25088. this.distanceModel = "linear";
  25089. this.panningModel = "HRTF";
  25090. this._startTime = 0;
  25091. this._startOffset = 0;
  25092. this._position = BABYLON.Vector3.Zero();
  25093. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25094. this._volume = 1;
  25095. this._isLoaded = false;
  25096. this._isReadyToPlay = false;
  25097. this._isPlaying = false;
  25098. this._isDirectional = false;
  25099. // Used if you'd like to create a directional sound.
  25100. // If not set, the sound will be omnidirectional
  25101. this._coneInnerAngle = 360;
  25102. this._coneOuterAngle = 360;
  25103. this._coneOuterGain = 0;
  25104. this.name = name;
  25105. this._scene = scene;
  25106. this._audioEngine = this._scene.getEngine().getAudioEngine();
  25107. this._readyToPlayCallback = readyToPlayCallback;
  25108. // Default custom attenuation function is a linear attenuation
  25109. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25110. if (currentDistance < maxDistance) {
  25111. return currentVolume * (1 - currentDistance / maxDistance);
  25112. } else {
  25113. return 0;
  25114. }
  25115. };
  25116. if (options) {
  25117. this.autoplay = options.autoplay || false;
  25118. this.loop = options.loop || false;
  25119. this._volume = options.volume || 1;
  25120. this.spatialSound = options.spatialSound || false;
  25121. this.maxDistance = options.maxDistance || 100;
  25122. this.useCustomAttenuation = options.useCustomAttenation || false;
  25123. this.rolloffFactor = options.rolloffFactor || 1;
  25124. this.refDistance = options.refDistance || 1;
  25125. this.distanceModel = options.distanceModel || "linear";
  25126. this.panningModel = options.panningModel || "HRTF";
  25127. }
  25128. if (this._audioEngine.canUseWebAudio) {
  25129. this._soundGain = this._audioEngine.audioContext.createGain();
  25130. this._soundGain.gain.value = this._volume;
  25131. if (this.spatialSound) {
  25132. this._createSpatialParameters();
  25133. } else {
  25134. this._audioNode = this._soundGain;
  25135. }
  25136. this._scene.mainSoundTrack.AddSound(this);
  25137. if (typeof (urlOrArrayBuffer) === "string") {
  25138. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25139. _this._soundLoaded(data);
  25140. }, null, null, true);
  25141. } else {
  25142. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25143. this._soundLoaded(urlOrArrayBuffer);
  25144. } else {
  25145. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25146. }
  25147. }
  25148. }
  25149. }
  25150. Sound.prototype.dispose = function () {
  25151. if (this._audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25152. if (this._isPlaying) {
  25153. this.stop();
  25154. }
  25155. this._isReadyToPlay = false;
  25156. if (this.soundTrackId === -1) {
  25157. this._scene.mainSoundTrack.RemoveSound(this);
  25158. } else {
  25159. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25160. }
  25161. this._soundGain.disconnect();
  25162. this._soundSource.disconnect();
  25163. this._audioBuffer = null;
  25164. this._soundGain = null;
  25165. this._soundSource = null;
  25166. if (this._soundPanner) {
  25167. this._soundPanner.disconnect();
  25168. this._soundPanner = null;
  25169. }
  25170. this._audioNode.disconnect();
  25171. if (this._connectedMesh) {
  25172. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25173. this._connectedMesh = null;
  25174. }
  25175. }
  25176. };
  25177. Sound.prototype._soundLoaded = function (audioData) {
  25178. var _this = this;
  25179. this._isLoaded = true;
  25180. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25181. _this._audioBuffer = buffer;
  25182. _this._isReadyToPlay = true;
  25183. if (_this.autoplay) {
  25184. _this.play();
  25185. }
  25186. if (_this._readyToPlayCallback) {
  25187. _this._readyToPlayCallback();
  25188. }
  25189. }, function (error) {
  25190. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25191. });
  25192. };
  25193. Sound.prototype.updateOptions = function (options) {
  25194. if (options) {
  25195. this.loop = options.loop || this.loop;
  25196. this.maxDistance = options.maxDistance || this.maxDistance;
  25197. this.useCustomAttenuation = options.useCustomAttenation || this.useCustomAttenuation;
  25198. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25199. this.refDistance = options.refDistance || this.refDistance;
  25200. this.distanceModel = options.distanceModel || this.distanceModel;
  25201. this.panningModel = options.panningModel || this.panningModel;
  25202. }
  25203. };
  25204. Sound.prototype._createSpatialParameters = function () {
  25205. if (this._audioEngine.canUseWebAudio) {
  25206. this._soundPanner = this._audioEngine.audioContext.createPanner();
  25207. if (this.useCustomAttenuation) {
  25208. // Tricks to disable in a way embedded Web Audio attenuation
  25209. this._soundPanner.distanceModel = "linear";
  25210. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25211. this._soundPanner.refDistance = 1;
  25212. this._soundPanner.rolloffFactor = 1;
  25213. this._soundPanner.panningModel = "HRTF";
  25214. } else {
  25215. this._soundPanner.distanceModel = this.distanceModel;
  25216. this._soundPanner.maxDistance = this.maxDistance;
  25217. this._soundPanner.refDistance = this.refDistance;
  25218. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25219. this._soundPanner.panningModel = this.panningModel;
  25220. }
  25221. this._soundPanner.connect(this._soundGain);
  25222. this._audioNode = this._soundPanner;
  25223. }
  25224. };
  25225. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25226. if (this._audioEngine.canUseWebAudio) {
  25227. this._audioNode.disconnect();
  25228. this._audioNode.connect(soundTrackAudioNode);
  25229. }
  25230. };
  25231. /**
  25232. * Transform this sound into a directional source
  25233. * @param coneInnerAngle Size of the inner cone in degree
  25234. * @param coneOuterAngle Size of the outer cone in degree
  25235. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25236. */
  25237. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25238. if (coneOuterAngle < coneInnerAngle) {
  25239. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25240. return;
  25241. }
  25242. this._coneInnerAngle = coneInnerAngle;
  25243. this._coneOuterAngle = coneOuterAngle;
  25244. this._coneOuterGain = coneOuterGain;
  25245. this._isDirectional = true;
  25246. if (this._isPlaying && this.loop) {
  25247. this.stop();
  25248. this.play();
  25249. }
  25250. };
  25251. Sound.prototype.setPosition = function (newPosition) {
  25252. this._position = newPosition;
  25253. if (this._isPlaying && this.spatialSound) {
  25254. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25255. }
  25256. };
  25257. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25258. this._localDirection = newLocalDirection;
  25259. if (this._connectedMesh && this._isPlaying) {
  25260. this._updateDirection();
  25261. }
  25262. };
  25263. Sound.prototype._updateDirection = function () {
  25264. var mat = this._connectedMesh.getWorldMatrix();
  25265. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25266. direction.normalize();
  25267. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25268. };
  25269. Sound.prototype.updateDistanceFromListener = function () {
  25270. if (this._connectedMesh && this.useCustomAttenuation) {
  25271. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25272. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25273. }
  25274. };
  25275. Sound.prototype.setAttenuationFunction = function (callback) {
  25276. this._customAttenuationFunction = callback;
  25277. };
  25278. /**
  25279. * Play the sound
  25280. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25281. */
  25282. Sound.prototype.play = function (time) {
  25283. if (this._isReadyToPlay) {
  25284. try {
  25285. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25286. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  25287. this._soundSource.buffer = this._audioBuffer;
  25288. if (this.spatialSound) {
  25289. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25290. if (this._isDirectional) {
  25291. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25292. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25293. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25294. if (this._connectedMesh) {
  25295. this._updateDirection();
  25296. } else {
  25297. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25298. }
  25299. }
  25300. }
  25301. this._soundSource.connect(this._audioNode);
  25302. this._soundSource.loop = this.loop;
  25303. this._startTime = startTime;
  25304. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25305. this._isPlaying = true;
  25306. } catch (ex) {
  25307. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25308. }
  25309. }
  25310. };
  25311. /**
  25312. * Stop the sound
  25313. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25314. */
  25315. Sound.prototype.stop = function (time) {
  25316. if (this._isPlaying) {
  25317. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25318. this._soundSource.stop(stopTime);
  25319. this._isPlaying = false;
  25320. }
  25321. };
  25322. Sound.prototype.pause = function () {
  25323. if (this._isPlaying) {
  25324. this._soundSource.stop(0);
  25325. this._startOffset += this._audioEngine.audioContext.currentTime - this._startTime;
  25326. }
  25327. };
  25328. Sound.prototype.setVolume = function (newVolume) {
  25329. this._volume = newVolume;
  25330. if (this._audioEngine.canUseWebAudio) {
  25331. this._soundGain.gain.value = newVolume;
  25332. }
  25333. };
  25334. Sound.prototype.getVolume = function () {
  25335. return this._volume;
  25336. };
  25337. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25338. var _this = this;
  25339. this._connectedMesh = meshToConnectTo;
  25340. if (!this.spatialSound) {
  25341. this._createSpatialParameters();
  25342. this.spatialSound = true;
  25343. if (this._isPlaying && this.loop) {
  25344. this.stop();
  25345. this.play();
  25346. }
  25347. }
  25348. this._registerFunc = function (connectedMesh) {
  25349. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  25350. };
  25351. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25352. };
  25353. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25354. this.setPosition(connectedMesh.position);
  25355. if (this._isDirectional && this._isPlaying) {
  25356. this._updateDirection();
  25357. }
  25358. };
  25359. return Sound;
  25360. })();
  25361. BABYLON.Sound = Sound;
  25362. })(BABYLON || (BABYLON = {}));
  25363. //# sourceMappingURL=babylon.sound.js.map
  25364. var BABYLON;
  25365. (function (BABYLON) {
  25366. var SoundTrack = (function () {
  25367. function SoundTrack(scene, options) {
  25368. this.id = -1;
  25369. this._isMainTrack = false;
  25370. this._scene = scene;
  25371. this._audioEngine = scene.getEngine().getAudioEngine();
  25372. this.soundCollection = new Array();
  25373. if (this._audioEngine.canUseWebAudio) {
  25374. this._trackGain = this._audioEngine.audioContext.createGain();
  25375. this._trackGain.connect(this._audioEngine.masterGain);
  25376. if (options) {
  25377. if (options.volume) {
  25378. this._trackGain.gain.value = options.volume;
  25379. }
  25380. if (options.mainTrack) {
  25381. this._isMainTrack = options.mainTrack;
  25382. }
  25383. }
  25384. }
  25385. if (!this._isMainTrack) {
  25386. this._scene.soundTracks.push(this);
  25387. this.id = this._scene.soundTracks.length - 1;
  25388. }
  25389. }
  25390. SoundTrack.prototype.dispose = function () {
  25391. if (this._audioEngine.canUseWebAudio) {
  25392. if (this._connectedAnalyser) {
  25393. this._connectedAnalyser.stopDebugCanvas();
  25394. }
  25395. while (this.soundCollection.length) {
  25396. this.soundCollection[0].dispose();
  25397. }
  25398. this._trackGain.disconnect();
  25399. this._trackGain = null;
  25400. }
  25401. };
  25402. SoundTrack.prototype.AddSound = function (sound) {
  25403. sound.connectToSoundTrackAudioNode(this._trackGain);
  25404. if (sound.soundTrackId) {
  25405. if (sound.soundTrackId === -1) {
  25406. this._scene.mainSoundTrack.RemoveSound(sound);
  25407. } else {
  25408. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25409. }
  25410. }
  25411. this.soundCollection.push(sound);
  25412. sound.soundTrackId = this.id;
  25413. };
  25414. SoundTrack.prototype.RemoveSound = function (sound) {
  25415. var index = this.soundCollection.indexOf(sound);
  25416. if (index !== -1) {
  25417. this.soundCollection.splice(index, 1);
  25418. }
  25419. };
  25420. SoundTrack.prototype.setVolume = function (newVolume) {
  25421. if (this._audioEngine.canUseWebAudio) {
  25422. this._trackGain.gain.value = newVolume;
  25423. }
  25424. };
  25425. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  25426. if (this._connectedAnalyser) {
  25427. this._connectedAnalyser.stopDebugCanvas();
  25428. }
  25429. this._connectedAnalyser = analyser;
  25430. if (this._audioEngine.canUseWebAudio) {
  25431. this._trackGain.disconnect();
  25432. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  25433. }
  25434. };
  25435. return SoundTrack;
  25436. })();
  25437. BABYLON.SoundTrack = SoundTrack;
  25438. })(BABYLON || (BABYLON = {}));
  25439. //# sourceMappingURL=babylon.soundtrack.js.map
  25440. var BABYLON;
  25441. (function (BABYLON) {
  25442. var DebugLayer = (function () {
  25443. function DebugLayer(scene) {
  25444. var _this = this;
  25445. this._enabled = false;
  25446. this._labelsEnabled = false;
  25447. this._displayStatistics = true;
  25448. this._displayTree = false;
  25449. this._displayLogs = false;
  25450. this._identityMatrix = BABYLON.Matrix.Identity();
  25451. this.axisRatio = 0.02;
  25452. this.accentColor = "orange";
  25453. this._scene = scene;
  25454. this._syncPositions = function () {
  25455. var engine = _this._scene.getEngine();
  25456. var canvasRect = engine.getRenderingCanvasClientRect();
  25457. if (_this._showUI) {
  25458. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  25459. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  25460. _this._statsDiv.style.width = "400px";
  25461. _this._statsDiv.style.height = "auto";
  25462. _this._statsSubsetDiv.style.maxHeight = "240px";
  25463. _this._optionsDiv.style.left = "0px";
  25464. _this._optionsDiv.style.top = "10px";
  25465. _this._optionsDiv.style.width = "200px";
  25466. _this._optionsDiv.style.height = "auto";
  25467. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  25468. _this._logDiv.style.left = "0px";
  25469. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  25470. _this._logDiv.style.width = "600px";
  25471. _this._logDiv.style.height = "160px";
  25472. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  25473. _this._treeDiv.style.top = "10px";
  25474. _this._treeDiv.style.width = "300px";
  25475. _this._treeDiv.style.height = "auto";
  25476. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  25477. }
  25478. _this._globalDiv.style.left = canvasRect.left + "px";
  25479. _this._globalDiv.style.top = canvasRect.top + "px";
  25480. _this._drawingCanvas.style.left = "0px";
  25481. _this._drawingCanvas.style.top = "0px";
  25482. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  25483. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  25484. var devicePixelRatio = window.devicePixelRatio || 1;
  25485. var context = _this._drawingContext;
  25486. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  25487. _this._ratio = devicePixelRatio / backingStoreRatio;
  25488. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  25489. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  25490. };
  25491. this._onCanvasClick = function (evt) {
  25492. _this._clickPosition = {
  25493. x: evt.clientX * _this._ratio,
  25494. y: evt.clientY * _this._ratio
  25495. };
  25496. };
  25497. this._syncData = function () {
  25498. if (_this._showUI) {
  25499. if (_this._displayStatistics) {
  25500. _this._displayStats();
  25501. _this._statsDiv.style.display = "";
  25502. } else {
  25503. _this._statsDiv.style.display = "none";
  25504. }
  25505. if (_this._displayLogs) {
  25506. _this._logDiv.style.display = "";
  25507. } else {
  25508. _this._logDiv.style.display = "none";
  25509. }
  25510. if (_this._displayTree) {
  25511. _this._treeDiv.style.display = "";
  25512. if (_this._needToRefreshMeshesTree) {
  25513. _this._needToRefreshMeshesTree = false;
  25514. _this._refreshMeshesTreeContent();
  25515. }
  25516. } else {
  25517. _this._treeDiv.style.display = "none";
  25518. }
  25519. }
  25520. if (_this._labelsEnabled || !_this._showUI) {
  25521. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  25522. var engine = _this._scene.getEngine();
  25523. var viewport = _this._scene.activeCamera.viewport;
  25524. var globalViewport = viewport.toGlobal(engine);
  25525. // Meshes
  25526. var meshes = _this._scene.getActiveMeshes();
  25527. for (var index = 0; index < meshes.length; index++) {
  25528. var mesh = meshes.data[index];
  25529. var position = mesh.getBoundingInfo().boundingSphere.center;
  25530. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25531. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25532. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25533. }
  25534. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25535. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25536. mesh.renderOverlay = !mesh.renderOverlay;
  25537. }, function () {
  25538. return mesh.renderOverlay ? 'red' : 'black';
  25539. });
  25540. }
  25541. }
  25542. // Cameras
  25543. var cameras = _this._scene.cameras;
  25544. for (index = 0; index < cameras.length; index++) {
  25545. var camera = cameras[index];
  25546. if (camera === _this._scene.activeCamera) {
  25547. continue;
  25548. }
  25549. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25550. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25551. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25552. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25553. _this._scene.activeCamera = camera;
  25554. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25555. }, function () {
  25556. return "purple";
  25557. });
  25558. }
  25559. }
  25560. // Lights
  25561. var lights = _this._scene.lights;
  25562. for (index = 0; index < lights.length; index++) {
  25563. var light = lights[index];
  25564. if (light.position) {
  25565. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25566. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25567. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25568. light.setEnabled(!light.isEnabled());
  25569. }, function () {
  25570. return light.isEnabled() ? "orange" : "gray";
  25571. });
  25572. }
  25573. }
  25574. }
  25575. }
  25576. _this._clickPosition = undefined;
  25577. };
  25578. }
  25579. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25580. while (this._treeSubsetDiv.hasChildNodes()) {
  25581. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25582. }
  25583. // Add meshes
  25584. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25585. sortedArray.sort(function (a, b) {
  25586. if (a.name === b.name) {
  25587. return 0;
  25588. }
  25589. return (a.name > b.name) ? 1 : -1;
  25590. });
  25591. for (var index = 0; index < sortedArray.length; index++) {
  25592. var mesh = sortedArray[index];
  25593. if (!mesh.isEnabled()) {
  25594. continue;
  25595. }
  25596. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25597. m.isVisible = element.checked;
  25598. }, mesh);
  25599. }
  25600. };
  25601. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25602. this._drawingContext.beginPath();
  25603. this._drawingContext.moveTo(zero.x, zero.y);
  25604. this._drawingContext.lineTo(unit.x, unit.y);
  25605. this._drawingContext.strokeStyle = color;
  25606. this._drawingContext.lineWidth = 4;
  25607. this._drawingContext.stroke();
  25608. this._drawingContext.font = "normal 14px Segoe UI";
  25609. this._drawingContext.fillStyle = color;
  25610. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25611. };
  25612. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25613. var position = mesh.getBoundingInfo().boundingSphere.center;
  25614. var worldMatrix = mesh.getWorldMatrix();
  25615. 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());
  25616. var unit = (unprojectedVector.subtract(position)).length();
  25617. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25618. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25619. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25620. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25621. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25622. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25623. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25624. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25625. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25626. };
  25627. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25628. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25629. this._drawingContext.font = "normal 12px Segoe UI";
  25630. var textMetrics = this._drawingContext.measureText(text);
  25631. var centerX = projectedPosition.x - textMetrics.width / 2;
  25632. var centerY = projectedPosition.y;
  25633. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  25634. onClick();
  25635. }
  25636. this._drawingContext.beginPath();
  25637. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  25638. this._drawingContext.fillStyle = getFillStyle();
  25639. this._drawingContext.globalAlpha = 0.5;
  25640. this._drawingContext.fill();
  25641. this._drawingContext.globalAlpha = 1.0;
  25642. this._drawingContext.strokeStyle = '#FFFFFF';
  25643. this._drawingContext.lineWidth = 1;
  25644. this._drawingContext.stroke();
  25645. this._drawingContext.fillStyle = "#FFFFFF";
  25646. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  25647. this._drawingContext.beginPath();
  25648. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  25649. this._drawingContext.fill();
  25650. }
  25651. };
  25652. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  25653. if (!this._clickPosition) {
  25654. return false;
  25655. }
  25656. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  25657. return false;
  25658. }
  25659. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  25660. return false;
  25661. }
  25662. return true;
  25663. };
  25664. DebugLayer.prototype.isVisible = function () {
  25665. return this._enabled;
  25666. };
  25667. DebugLayer.prototype.hide = function () {
  25668. if (!this._enabled) {
  25669. return;
  25670. }
  25671. this._enabled = false;
  25672. var engine = this._scene.getEngine();
  25673. this._scene.unregisterAfterRender(this._syncData);
  25674. document.body.removeChild(this._globalDiv);
  25675. window.removeEventListener("resize", this._syncPositions);
  25676. this._scene.forceShowBoundingBoxes = false;
  25677. this._scene.forceWireframe = false;
  25678. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  25679. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  25680. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  25681. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  25682. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  25683. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  25684. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  25685. this._scene.shadowsEnabled = true;
  25686. this._scene.particlesEnabled = true;
  25687. this._scene.postProcessesEnabled = true;
  25688. this._scene.collisionsEnabled = true;
  25689. this._scene.lightsEnabled = true;
  25690. this._scene.texturesEnabled = true;
  25691. this._scene.lensFlaresEnabled = true;
  25692. this._scene.proceduralTexturesEnabled = true;
  25693. this._scene.renderTargetsEnabled = true;
  25694. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  25695. };
  25696. DebugLayer.prototype.show = function (showUI) {
  25697. if (typeof showUI === "undefined") { showUI = true; }
  25698. if (this._enabled) {
  25699. return;
  25700. }
  25701. this._enabled = true;
  25702. this._showUI = showUI;
  25703. var engine = this._scene.getEngine();
  25704. this._globalDiv = document.createElement("div");
  25705. document.body.appendChild(this._globalDiv);
  25706. this._generateDOMelements();
  25707. window.addEventListener("resize", this._syncPositions);
  25708. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  25709. this._syncPositions();
  25710. this._scene.registerAfterRender(this._syncData);
  25711. };
  25712. DebugLayer.prototype._clearLabels = function () {
  25713. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  25714. for (var index = 0; index < this._scene.meshes.length; index++) {
  25715. var mesh = this._scene.meshes[index];
  25716. mesh.renderOverlay = false;
  25717. }
  25718. };
  25719. DebugLayer.prototype._generateheader = function (root, text) {
  25720. var header = document.createElement("div");
  25721. header.innerHTML = text + "&nbsp;";
  25722. header.style.textAlign = "right";
  25723. header.style.width = "100%";
  25724. header.style.color = "white";
  25725. header.style.backgroundColor = "Black";
  25726. header.style.padding = "5px 5px 4px 0px";
  25727. header.style.marginLeft = "-5px";
  25728. header.style.fontWeight = "bold";
  25729. root.appendChild(header);
  25730. };
  25731. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  25732. var label = document.createElement("label");
  25733. label.innerHTML = title;
  25734. label.style.color = color;
  25735. root.appendChild(label);
  25736. root.appendChild(document.createElement("br"));
  25737. };
  25738. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  25739. if (typeof tag === "undefined") { tag = null; }
  25740. var label = document.createElement("label");
  25741. var boundingBoxesCheckbox = document.createElement("input");
  25742. boundingBoxesCheckbox.type = "checkbox";
  25743. boundingBoxesCheckbox.checked = initialState;
  25744. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25745. task(evt.target, tag);
  25746. });
  25747. label.appendChild(boundingBoxesCheckbox);
  25748. var container = document.createElement("span");
  25749. var leftPart = document.createElement("span");
  25750. var rightPart = document.createElement("span");
  25751. rightPart.style.cssFloat = "right";
  25752. leftPart.innerHTML = leftTitle;
  25753. rightPart.innerHTML = rightTitle;
  25754. rightPart.style.fontSize = "12px";
  25755. rightPart.style.maxWidth = "200px";
  25756. container.appendChild(leftPart);
  25757. container.appendChild(rightPart);
  25758. label.appendChild(container);
  25759. root.appendChild(label);
  25760. root.appendChild(document.createElement("br"));
  25761. };
  25762. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  25763. if (typeof tag === "undefined") { tag = null; }
  25764. var label = document.createElement("label");
  25765. var boundingBoxesCheckbox = document.createElement("input");
  25766. boundingBoxesCheckbox.type = "checkbox";
  25767. boundingBoxesCheckbox.checked = initialState;
  25768. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25769. task(evt.target, tag);
  25770. });
  25771. label.appendChild(boundingBoxesCheckbox);
  25772. label.appendChild(document.createTextNode(title));
  25773. root.appendChild(label);
  25774. root.appendChild(document.createElement("br"));
  25775. };
  25776. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  25777. if (typeof tag === "undefined") { tag = null; }
  25778. var label = document.createElement("label");
  25779. var boundingBoxesRadio = document.createElement("input");
  25780. boundingBoxesRadio.type = "radio";
  25781. boundingBoxesRadio.name = name;
  25782. boundingBoxesRadio.checked = initialState;
  25783. boundingBoxesRadio.addEventListener("change", function (evt) {
  25784. task(evt.target, tag);
  25785. });
  25786. label.appendChild(boundingBoxesRadio);
  25787. label.appendChild(document.createTextNode(title));
  25788. root.appendChild(label);
  25789. root.appendChild(document.createElement("br"));
  25790. };
  25791. DebugLayer.prototype._generateDOMelements = function () {
  25792. var _this = this;
  25793. this._globalDiv.id = "DebugLayer";
  25794. this._globalDiv.style.position = "absolute";
  25795. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  25796. this._globalDiv.style.fontSize = "14px";
  25797. this._globalDiv.style.color = "white";
  25798. // Drawing canvas
  25799. this._drawingCanvas = document.createElement("canvas");
  25800. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  25801. this._drawingCanvas.style.position = "absolute";
  25802. this._drawingCanvas.style.pointerEvents = "none";
  25803. this._drawingContext = this._drawingCanvas.getContext("2d");
  25804. this._globalDiv.appendChild(this._drawingCanvas);
  25805. if (this._showUI) {
  25806. var background = "rgba(128, 128, 128, 0.4)";
  25807. var border = "rgb(180, 180, 180) solid 1px";
  25808. // Stats
  25809. this._statsDiv = document.createElement("div");
  25810. this._statsDiv.id = "DebugLayerStats";
  25811. this._statsDiv.style.border = border;
  25812. this._statsDiv.style.position = "absolute";
  25813. this._statsDiv.style.background = background;
  25814. this._statsDiv.style.padding = "0px 0px 0px 5px";
  25815. this._generateheader(this._statsDiv, "STATISTICS");
  25816. this._statsSubsetDiv = document.createElement("div");
  25817. this._statsSubsetDiv.style.paddingTop = "5px";
  25818. this._statsSubsetDiv.style.paddingBottom = "5px";
  25819. this._statsSubsetDiv.style.overflowY = "auto";
  25820. this._statsDiv.appendChild(this._statsSubsetDiv);
  25821. // Tree
  25822. this._treeDiv = document.createElement("div");
  25823. this._treeDiv.id = "DebugLayerTree";
  25824. this._treeDiv.style.border = border;
  25825. this._treeDiv.style.position = "absolute";
  25826. this._treeDiv.style.background = background;
  25827. this._treeDiv.style.padding = "0px 0px 0px 5px";
  25828. this._treeDiv.style.display = "none";
  25829. this._generateheader(this._treeDiv, "MESHES TREE");
  25830. this._treeSubsetDiv = document.createElement("div");
  25831. this._treeSubsetDiv.style.paddingTop = "5px";
  25832. this._treeSubsetDiv.style.paddingRight = "5px";
  25833. this._treeSubsetDiv.style.overflowY = "auto";
  25834. this._treeSubsetDiv.style.maxHeight = "300px";
  25835. this._treeDiv.appendChild(this._treeSubsetDiv);
  25836. this._needToRefreshMeshesTree = true;
  25837. // Logs
  25838. this._logDiv = document.createElement("div");
  25839. this._logDiv.style.border = border;
  25840. this._logDiv.id = "DebugLayerLogs";
  25841. this._logDiv.style.position = "absolute";
  25842. this._logDiv.style.background = background;
  25843. this._logDiv.style.padding = "0px 0px 0px 5px";
  25844. this._logDiv.style.display = "none";
  25845. this._generateheader(this._logDiv, "LOGS");
  25846. this._logSubsetDiv = document.createElement("div");
  25847. this._logSubsetDiv.style.height = "127px";
  25848. this._logSubsetDiv.style.paddingTop = "5px";
  25849. this._logSubsetDiv.style.overflowY = "auto";
  25850. this._logSubsetDiv.style.fontSize = "12px";
  25851. this._logSubsetDiv.style.fontFamily = "consolas";
  25852. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  25853. this._logDiv.appendChild(this._logSubsetDiv);
  25854. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  25855. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  25856. };
  25857. // Options
  25858. this._optionsDiv = document.createElement("div");
  25859. this._optionsDiv.id = "DebugLayerOptions";
  25860. this._optionsDiv.style.border = border;
  25861. this._optionsDiv.style.position = "absolute";
  25862. this._optionsDiv.style.background = background;
  25863. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  25864. this._optionsDiv.style.overflowY = "auto";
  25865. this._generateheader(this._optionsDiv, "OPTIONS");
  25866. this._optionsSubsetDiv = document.createElement("div");
  25867. this._optionsSubsetDiv.style.paddingTop = "5px";
  25868. this._optionsSubsetDiv.style.paddingBottom = "5px";
  25869. this._optionsSubsetDiv.style.overflowY = "auto";
  25870. this._optionsSubsetDiv.style.maxHeight = "200px";
  25871. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  25872. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  25873. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  25874. _this._displayStatistics = element.checked;
  25875. });
  25876. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  25877. _this._displayLogs = element.checked;
  25878. });
  25879. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  25880. _this._displayTree = element.checked;
  25881. _this._needToRefreshMeshesTree = true;
  25882. });
  25883. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25884. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  25885. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  25886. _this._scene.forceShowBoundingBoxes = element.checked;
  25887. });
  25888. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  25889. _this._labelsEnabled = element.checked;
  25890. if (!_this._labelsEnabled) {
  25891. _this._clearLabels();
  25892. }
  25893. });
  25894. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  25895. if (element.checked) {
  25896. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  25897. } else {
  25898. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  25899. }
  25900. });
  25901. ;
  25902. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25903. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  25904. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  25905. if (element.checked) {
  25906. _this._scene.forceWireframe = false;
  25907. _this._scene.forcePointsCloud = false;
  25908. }
  25909. });
  25910. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  25911. if (element.checked) {
  25912. _this._scene.forceWireframe = true;
  25913. _this._scene.forcePointsCloud = false;
  25914. }
  25915. });
  25916. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  25917. if (element.checked) {
  25918. _this._scene.forceWireframe = false;
  25919. _this._scene.forcePointsCloud = true;
  25920. }
  25921. });
  25922. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25923. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  25924. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  25925. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  25926. });
  25927. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  25928. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  25929. });
  25930. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  25931. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  25932. });
  25933. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  25934. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  25935. });
  25936. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  25937. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  25938. });
  25939. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  25940. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  25941. });
  25942. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  25943. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  25944. });
  25945. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  25946. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  25947. });
  25948. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25949. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  25950. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  25951. _this._scene.animationsEnabled = element.checked;
  25952. });
  25953. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  25954. _this._scene.collisionsEnabled = element.checked;
  25955. });
  25956. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  25957. _this._scene.fogEnabled = element.checked;
  25958. });
  25959. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  25960. _this._scene.lensFlaresEnabled = element.checked;
  25961. });
  25962. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  25963. _this._scene.lightsEnabled = element.checked;
  25964. });
  25965. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  25966. _this._scene.particlesEnabled = element.checked;
  25967. });
  25968. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  25969. _this._scene.postProcessesEnabled = element.checked;
  25970. });
  25971. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  25972. _this._scene.proceduralTexturesEnabled = element.checked;
  25973. });
  25974. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  25975. _this._scene.renderTargetsEnabled = element.checked;
  25976. });
  25977. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  25978. _this._scene.shadowsEnabled = element.checked;
  25979. });
  25980. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  25981. _this._scene.skeletonsEnabled = element.checked;
  25982. });
  25983. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  25984. _this._scene.texturesEnabled = element.checked;
  25985. });
  25986. this._globalDiv.appendChild(this._statsDiv);
  25987. this._globalDiv.appendChild(this._logDiv);
  25988. this._globalDiv.appendChild(this._optionsDiv);
  25989. this._globalDiv.appendChild(this._treeDiv);
  25990. }
  25991. };
  25992. DebugLayer.prototype._displayStats = function () {
  25993. var scene = this._scene;
  25994. var engine = scene.getEngine();
  25995. var glInfo = engine.getGlInfo();
  25996. 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>";
  25997. if (this.customStatsFunction) {
  25998. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  25999. }
  26000. };
  26001. return DebugLayer;
  26002. })();
  26003. BABYLON.DebugLayer = DebugLayer;
  26004. })(BABYLON || (BABYLON = {}));
  26005. //# sourceMappingURL=babylon.debugLayer.js.map
  26006. var BABYLON;
  26007. (function (BABYLON) {
  26008. var RawTexture = (function (_super) {
  26009. __extends(RawTexture, _super);
  26010. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26011. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  26012. if (typeof invertY === "undefined") { invertY = false; }
  26013. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26014. _super.call(this, null, scene, !generateMipMaps, invertY);
  26015. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26016. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26017. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26018. }
  26019. // Statics
  26020. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26021. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  26022. if (typeof invertY === "undefined") { invertY = false; }
  26023. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26024. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26025. };
  26026. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26027. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  26028. if (typeof invertY === "undefined") { invertY = false; }
  26029. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26030. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26031. };
  26032. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26033. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  26034. if (typeof invertY === "undefined") { invertY = false; }
  26035. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26036. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26037. };
  26038. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26039. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  26040. if (typeof invertY === "undefined") { invertY = false; }
  26041. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26042. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26043. };
  26044. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26045. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  26046. if (typeof invertY === "undefined") { invertY = false; }
  26047. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26048. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26049. };
  26050. return RawTexture;
  26051. })(BABYLON.Texture);
  26052. BABYLON.RawTexture = RawTexture;
  26053. })(BABYLON || (BABYLON = {}));
  26054. //# sourceMappingURL=babylon.rawTexture.js.map
  26055. var BABYLON;
  26056. (function (BABYLON) {
  26057. var IndexedVector2 = (function (_super) {
  26058. __extends(IndexedVector2, _super);
  26059. function IndexedVector2(original, index) {
  26060. _super.call(this, original.x, original.y);
  26061. this.index = index;
  26062. }
  26063. return IndexedVector2;
  26064. })(BABYLON.Vector2);
  26065. var PolygonPoints = (function () {
  26066. function PolygonPoints() {
  26067. this.elements = new Array();
  26068. }
  26069. PolygonPoints.prototype.add = function (originalPoints) {
  26070. var _this = this;
  26071. var result = new Array();
  26072. originalPoints.forEach(function (point) {
  26073. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26074. var newPoint = new IndexedVector2(point, _this.elements.length);
  26075. result.push(newPoint);
  26076. _this.elements.push(newPoint);
  26077. }
  26078. });
  26079. return result;
  26080. };
  26081. PolygonPoints.prototype.computeBounds = function () {
  26082. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26083. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26084. this.elements.forEach(function (point) {
  26085. // x
  26086. if (point.x < lmin.x) {
  26087. lmin.x = point.x;
  26088. } else if (point.x > lmax.x) {
  26089. lmax.x = point.x;
  26090. }
  26091. // y
  26092. if (point.y < lmin.y) {
  26093. lmin.y = point.y;
  26094. } else if (point.y > lmax.y) {
  26095. lmax.y = point.y;
  26096. }
  26097. });
  26098. return {
  26099. min: lmin,
  26100. max: lmax,
  26101. width: lmax.x - lmin.x,
  26102. height: lmax.y - lmin.y
  26103. };
  26104. };
  26105. return PolygonPoints;
  26106. })();
  26107. var Polygon = (function () {
  26108. function Polygon() {
  26109. }
  26110. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26111. return [
  26112. new BABYLON.Vector2(xmin, ymin),
  26113. new BABYLON.Vector2(xmax, ymin),
  26114. new BABYLON.Vector2(xmax, ymax),
  26115. new BABYLON.Vector2(xmin, ymax)
  26116. ];
  26117. };
  26118. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26119. if (typeof cx === "undefined") { cx = 0; }
  26120. if (typeof cy === "undefined") { cy = 0; }
  26121. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  26122. var result = new Array();
  26123. var angle = 0;
  26124. var increment = (Math.PI * 2) / numberOfSides;
  26125. for (var i = 0; i < numberOfSides; i++) {
  26126. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26127. angle -= increment;
  26128. }
  26129. return result;
  26130. };
  26131. Polygon.Parse = function (input) {
  26132. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  26133. return (!isNaN(val));
  26134. });
  26135. var i, result = [];
  26136. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26137. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26138. }
  26139. return result;
  26140. };
  26141. Polygon.StartingAt = function (x, y) {
  26142. return BABYLON.Path2.StartingAt(x, y);
  26143. };
  26144. return Polygon;
  26145. })();
  26146. BABYLON.Polygon = Polygon;
  26147. var PolygonMeshBuilder = (function () {
  26148. function PolygonMeshBuilder(name, contours, scene) {
  26149. this._points = new PolygonPoints();
  26150. if (!("poly2tri" in window)) {
  26151. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26152. }
  26153. this._name = name;
  26154. this._scene = scene;
  26155. var points;
  26156. if (contours instanceof BABYLON.Path2) {
  26157. points = contours.getPoints();
  26158. } else {
  26159. points = contours;
  26160. }
  26161. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26162. }
  26163. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26164. this._swctx.addHole(this._points.add(hole));
  26165. return this;
  26166. };
  26167. PolygonMeshBuilder.prototype.build = function (updatable) {
  26168. if (typeof updatable === "undefined") { updatable = false; }
  26169. var result = new BABYLON.Mesh(this._name, this._scene);
  26170. var normals = [];
  26171. var positions = [];
  26172. var uvs = [];
  26173. var bounds = this._points.computeBounds();
  26174. this._points.elements.forEach(function (p) {
  26175. normals.push(0, 1.0, 0);
  26176. positions.push(p.x, 0, p.y);
  26177. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26178. });
  26179. var indices = [];
  26180. this._swctx.triangulate();
  26181. this._swctx.getTriangles().forEach(function (triangle) {
  26182. triangle.getPoints().forEach(function (point) {
  26183. indices.push(point.index);
  26184. });
  26185. });
  26186. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26187. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26188. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26189. result.setIndices(indices);
  26190. return result;
  26191. };
  26192. return PolygonMeshBuilder;
  26193. })();
  26194. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26195. })(BABYLON || (BABYLON = {}));
  26196. //# sourceMappingURL=babylon.polygonMesh.js.map
  26197. var BABYLON;
  26198. (function (BABYLON) {
  26199. var SimplificationSettings = (function () {
  26200. function SimplificationSettings(quality, distance) {
  26201. this.quality = quality;
  26202. this.distance = distance;
  26203. }
  26204. return SimplificationSettings;
  26205. })();
  26206. BABYLON.SimplificationSettings = SimplificationSettings;
  26207. /**
  26208. * The implemented types of simplification.
  26209. * At the moment only Quadratic Error Decimation is implemented.
  26210. */
  26211. (function (SimplificationType) {
  26212. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26213. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26214. var SimplificationType = BABYLON.SimplificationType;
  26215. var DecimationTriangle = (function () {
  26216. function DecimationTriangle(vertices) {
  26217. this.vertices = vertices;
  26218. this.error = new Array(4);
  26219. this.deleted = false;
  26220. this.isDirty = false;
  26221. this.borderFactor = 0;
  26222. }
  26223. return DecimationTriangle;
  26224. })();
  26225. BABYLON.DecimationTriangle = DecimationTriangle;
  26226. var DecimationVertex = (function () {
  26227. function DecimationVertex(position, normal, uv, id) {
  26228. this.position = position;
  26229. this.normal = normal;
  26230. this.uv = uv;
  26231. this.id = id;
  26232. this.isBorder = true;
  26233. this.q = new QuadraticMatrix();
  26234. this.triangleCount = 0;
  26235. this.triangleStart = 0;
  26236. }
  26237. return DecimationVertex;
  26238. })();
  26239. BABYLON.DecimationVertex = DecimationVertex;
  26240. var QuadraticMatrix = (function () {
  26241. function QuadraticMatrix(data) {
  26242. this.data = new Array(10);
  26243. for (var i = 0; i < 10; ++i) {
  26244. if (data && data[i]) {
  26245. this.data[i] = data[i];
  26246. } else {
  26247. this.data[i] = 0;
  26248. }
  26249. }
  26250. }
  26251. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26252. 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];
  26253. return det;
  26254. };
  26255. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26256. for (var i = 0; i < 10; ++i) {
  26257. this.data[i] += matrix.data[i];
  26258. }
  26259. };
  26260. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26261. for (var i = 0; i < 10; ++i) {
  26262. this.data[i] += data[i];
  26263. }
  26264. };
  26265. QuadraticMatrix.prototype.add = function (matrix) {
  26266. var m = new QuadraticMatrix();
  26267. for (var i = 0; i < 10; ++i) {
  26268. m.data[i] = this.data[i] + matrix.data[i];
  26269. }
  26270. return m;
  26271. };
  26272. QuadraticMatrix.FromData = function (a, b, c, d) {
  26273. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26274. };
  26275. //returning an array to avoid garbage collection
  26276. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26277. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26278. };
  26279. return QuadraticMatrix;
  26280. })();
  26281. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26282. var Reference = (function () {
  26283. function Reference(vertexId, triangleId) {
  26284. this.vertexId = vertexId;
  26285. this.triangleId = triangleId;
  26286. }
  26287. return Reference;
  26288. })();
  26289. BABYLON.Reference = Reference;
  26290. /**
  26291. * An implementation of the Quadratic Error simplification algorithm.
  26292. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26293. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26294. * @author RaananW
  26295. */
  26296. var QuadraticErrorSimplification = (function () {
  26297. function QuadraticErrorSimplification(_mesh) {
  26298. this._mesh = _mesh;
  26299. this.initialised = false;
  26300. this.syncIterations = 5000;
  26301. this.aggressiveness = 7;
  26302. this.decimationIterations = 100;
  26303. }
  26304. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26305. var _this = this;
  26306. this.initWithMesh(this._mesh, function () {
  26307. _this.runDecimation(settings, successCallback);
  26308. });
  26309. };
  26310. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26311. var _this = this;
  26312. var targetCount = ~~(this.triangles.length * settings.quality);
  26313. var deletedTriangles = 0;
  26314. var triangleCount = this.triangles.length;
  26315. var iterationFunction = function (iteration, callback) {
  26316. setTimeout(function () {
  26317. if (iteration % 5 === 0) {
  26318. _this.updateMesh(iteration === 0);
  26319. }
  26320. for (var i = 0; i < _this.triangles.length; ++i) {
  26321. _this.triangles[i].isDirty = false;
  26322. }
  26323. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26324. var trianglesIterator = function (i) {
  26325. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26326. var t = _this.triangles[tIdx];
  26327. if (!t)
  26328. return;
  26329. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26330. return;
  26331. }
  26332. for (var j = 0; j < 3; ++j) {
  26333. if (t.error[j] < threshold) {
  26334. var deleted0 = [];
  26335. var deleted1 = [];
  26336. var i0 = t.vertices[j];
  26337. var i1 = t.vertices[(j + 1) % 3];
  26338. var v0 = _this.vertices[i0];
  26339. var v1 = _this.vertices[i1];
  26340. if (v0.isBorder !== v1.isBorder)
  26341. continue;
  26342. var p = BABYLON.Vector3.Zero();
  26343. var n = BABYLON.Vector3.Zero();
  26344. var uv = BABYLON.Vector2.Zero();
  26345. var color = new BABYLON.Color4(0, 0, 0, 1);
  26346. _this.calculateError(v0, v1, p, n, uv, color);
  26347. var delTr = [];
  26348. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26349. continue;
  26350. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26351. continue;
  26352. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26353. continue;
  26354. }
  26355. v0.normal = n;
  26356. if (v0.uv)
  26357. v0.uv = uv;
  26358. else if (v0.color)
  26359. v0.color = color;
  26360. v0.q = v1.q.add(v0.q);
  26361. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26362. continue;
  26363. if (p.equals(v0.position))
  26364. continue;
  26365. v0.position = p;
  26366. var tStart = _this.references.length;
  26367. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26368. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26369. var tCount = _this.references.length - tStart;
  26370. if (tCount <= v0.triangleCount) {
  26371. if (tCount) {
  26372. for (var c = 0; c < tCount; c++) {
  26373. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26374. }
  26375. }
  26376. } else {
  26377. v0.triangleStart = tStart;
  26378. }
  26379. v0.triangleCount = tCount;
  26380. break;
  26381. }
  26382. }
  26383. };
  26384. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26385. return (triangleCount - deletedTriangles <= targetCount);
  26386. });
  26387. }, 0);
  26388. };
  26389. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26390. if (triangleCount - deletedTriangles <= targetCount)
  26391. loop.breakLoop();
  26392. else {
  26393. iterationFunction(loop.index, function () {
  26394. loop.executeNext();
  26395. });
  26396. }
  26397. }, function () {
  26398. setTimeout(function () {
  26399. successCallback(_this.reconstructMesh());
  26400. }, 0);
  26401. });
  26402. };
  26403. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26404. var _this = this;
  26405. if (!mesh)
  26406. return;
  26407. this.vertices = [];
  26408. this.triangles = [];
  26409. this._mesh = mesh;
  26410. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26411. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26412. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26413. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26414. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26415. var indices = mesh.getIndices();
  26416. var vertexInit = function (i) {
  26417. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  26418. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26419. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26420. } else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26421. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  26422. }
  26423. _this.vertices.push(vertex);
  26424. };
  26425. var totalVertices = mesh.getTotalVertices();
  26426. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26427. var indicesInit = function (i) {
  26428. var pos = i * 3;
  26429. var i0 = indices[pos + 0];
  26430. var i1 = indices[pos + 1];
  26431. var i2 = indices[pos + 2];
  26432. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26433. _this.triangles.push(triangle);
  26434. };
  26435. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26436. _this.init(callback);
  26437. });
  26438. });
  26439. };
  26440. QuadraticErrorSimplification.prototype.init = function (callback) {
  26441. var _this = this;
  26442. var triangleInit1 = function (i) {
  26443. var t = _this.triangles[i];
  26444. 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();
  26445. for (var j = 0; j < 3; j++) {
  26446. _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))));
  26447. }
  26448. };
  26449. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  26450. var triangleInit2 = function (i) {
  26451. var t = _this.triangles[i];
  26452. for (var j = 0; j < 3; ++j) {
  26453. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  26454. }
  26455. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26456. };
  26457. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  26458. _this.initialised = true;
  26459. callback();
  26460. });
  26461. });
  26462. };
  26463. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  26464. var newTriangles = [];
  26465. var i;
  26466. for (i = 0; i < this.vertices.length; ++i) {
  26467. this.vertices[i].triangleCount = 0;
  26468. }
  26469. var t;
  26470. var j;
  26471. for (i = 0; i < this.triangles.length; ++i) {
  26472. if (!this.triangles[i].deleted) {
  26473. t = this.triangles[i];
  26474. for (j = 0; j < 3; ++j) {
  26475. this.vertices[t.vertices[j]].triangleCount = 1;
  26476. }
  26477. newTriangles.push(t);
  26478. }
  26479. }
  26480. var newVerticesOrder = [];
  26481. //compact vertices, get the IDs of the vertices used.
  26482. var dst = 0;
  26483. for (i = 0; i < this.vertices.length; ++i) {
  26484. if (this.vertices[i].triangleCount) {
  26485. this.vertices[i].triangleStart = dst;
  26486. this.vertices[dst].position = this.vertices[i].position;
  26487. this.vertices[dst].normal = this.vertices[i].normal;
  26488. this.vertices[dst].uv = this.vertices[i].uv;
  26489. this.vertices[dst].color = this.vertices[i].color;
  26490. newVerticesOrder.push(i);
  26491. dst++;
  26492. }
  26493. }
  26494. for (i = 0; i < newTriangles.length; ++i) {
  26495. t = newTriangles[i];
  26496. for (j = 0; j < 3; ++j) {
  26497. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  26498. }
  26499. }
  26500. this.vertices = this.vertices.slice(0, dst);
  26501. var newPositionData = [];
  26502. var newNormalData = [];
  26503. var newUVsData = [];
  26504. var newColorsData = [];
  26505. for (i = 0; i < newVerticesOrder.length; ++i) {
  26506. newPositionData.push(this.vertices[i].position.x);
  26507. newPositionData.push(this.vertices[i].position.y);
  26508. newPositionData.push(this.vertices[i].position.z);
  26509. newNormalData.push(this.vertices[i].normal.x);
  26510. newNormalData.push(this.vertices[i].normal.y);
  26511. newNormalData.push(this.vertices[i].normal.z);
  26512. if (this.vertices[i].uv) {
  26513. newUVsData.push(this.vertices[i].uv.x);
  26514. newUVsData.push(this.vertices[i].uv.y);
  26515. } else if (this.vertices[i].color) {
  26516. newColorsData.push(this.vertices[i].color.r);
  26517. newColorsData.push(this.vertices[i].color.g);
  26518. newColorsData.push(this.vertices[i].color.b);
  26519. newColorsData.push(this.vertices[i].color.a);
  26520. }
  26521. }
  26522. var newIndicesArray = [];
  26523. for (i = 0; i < newTriangles.length; ++i) {
  26524. newIndicesArray.push(newTriangles[i].vertices[0]);
  26525. newIndicesArray.push(newTriangles[i].vertices[1]);
  26526. newIndicesArray.push(newTriangles[i].vertices[2]);
  26527. }
  26528. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  26529. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  26530. newMesh.material = this._mesh.material;
  26531. newMesh.parent = this._mesh.parent;
  26532. newMesh.setIndices(newIndicesArray);
  26533. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  26534. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  26535. if (newUVsData.length > 0)
  26536. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  26537. if (newColorsData.length > 0)
  26538. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  26539. //preparing the skeleton support
  26540. if (this._mesh.skeleton) {
  26541. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  26542. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  26543. }
  26544. return newMesh;
  26545. };
  26546. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  26547. for (var i = 0; i < vertex1.triangleCount; ++i) {
  26548. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  26549. if (t.deleted)
  26550. continue;
  26551. var s = this.references[vertex1.triangleStart + i].vertexId;
  26552. var id1 = t.vertices[(s + 1) % 3];
  26553. var id2 = t.vertices[(s + 2) % 3];
  26554. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  26555. deletedArray[i] = true;
  26556. delTr.push(t);
  26557. continue;
  26558. }
  26559. var d1 = this.vertices[id1].position.subtract(point);
  26560. d1 = d1.normalize();
  26561. var d2 = this.vertices[id2].position.subtract(point);
  26562. d2 = d2.normalize();
  26563. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26564. return true;
  26565. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26566. deletedArray[i] = false;
  26567. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26568. return true;
  26569. }
  26570. return false;
  26571. };
  26572. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26573. var newDeleted = deletedTriangles;
  26574. for (var i = 0; i < vertex.triangleCount; ++i) {
  26575. var ref = this.references[vertex.triangleStart + i];
  26576. var t = this.triangles[ref.triangleId];
  26577. if (t.deleted)
  26578. continue;
  26579. if (deletedArray[i]) {
  26580. t.deleted = true;
  26581. newDeleted++;
  26582. continue;
  26583. }
  26584. t.vertices[ref.vertexId] = vertexId;
  26585. t.isDirty = true;
  26586. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26587. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26588. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26589. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26590. this.references.push(ref);
  26591. }
  26592. return newDeleted;
  26593. };
  26594. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26595. for (var i = 0; i < this.vertices.length; ++i) {
  26596. var vCount = [];
  26597. var vId = [];
  26598. var v = this.vertices[i];
  26599. var j;
  26600. for (j = 0; j < v.triangleCount; ++j) {
  26601. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26602. for (var ii = 0; ii < 3; ii++) {
  26603. var ofs = 0;
  26604. var id = triangle.vertices[ii];
  26605. while (ofs < vCount.length) {
  26606. if (vId[ofs] === id)
  26607. break;
  26608. ++ofs;
  26609. }
  26610. if (ofs === vCount.length) {
  26611. vCount.push(1);
  26612. vId.push(id);
  26613. } else {
  26614. vCount[ofs]++;
  26615. }
  26616. }
  26617. }
  26618. for (j = 0; j < vCount.length; ++j) {
  26619. if (vCount[j] === 1) {
  26620. this.vertices[vId[j]].isBorder = true;
  26621. } else {
  26622. this.vertices[vId[j]].isBorder = false;
  26623. }
  26624. }
  26625. }
  26626. };
  26627. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  26628. if (typeof identifyBorders === "undefined") { identifyBorders = false; }
  26629. var i;
  26630. if (!identifyBorders) {
  26631. var newTrianglesVector = [];
  26632. for (i = 0; i < this.triangles.length; ++i) {
  26633. if (!this.triangles[i].deleted) {
  26634. newTrianglesVector.push(this.triangles[i]);
  26635. }
  26636. }
  26637. this.triangles = newTrianglesVector;
  26638. }
  26639. for (i = 0; i < this.vertices.length; ++i) {
  26640. this.vertices[i].triangleCount = 0;
  26641. this.vertices[i].triangleStart = 0;
  26642. }
  26643. var t;
  26644. var j;
  26645. var v;
  26646. for (i = 0; i < this.triangles.length; ++i) {
  26647. t = this.triangles[i];
  26648. for (j = 0; j < 3; ++j) {
  26649. v = this.vertices[t.vertices[j]];
  26650. v.triangleCount++;
  26651. }
  26652. }
  26653. var tStart = 0;
  26654. for (i = 0; i < this.vertices.length; ++i) {
  26655. this.vertices[i].triangleStart = tStart;
  26656. tStart += this.vertices[i].triangleCount;
  26657. this.vertices[i].triangleCount = 0;
  26658. }
  26659. var newReferences = new Array(this.triangles.length * 3);
  26660. for (i = 0; i < this.triangles.length; ++i) {
  26661. t = this.triangles[i];
  26662. for (j = 0; j < 3; ++j) {
  26663. v = this.vertices[t.vertices[j]];
  26664. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  26665. v.triangleCount++;
  26666. }
  26667. }
  26668. this.references = newReferences;
  26669. if (identifyBorders) {
  26670. this.identifyBorder();
  26671. }
  26672. };
  26673. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  26674. var x = point.x;
  26675. var y = point.y;
  26676. var z = point.z;
  26677. 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];
  26678. };
  26679. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  26680. var q = vertex1.q.add(vertex2.q);
  26681. var border = vertex1.isBorder && vertex2.isBorder;
  26682. var error = 0;
  26683. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  26684. if (qDet !== 0 && !border) {
  26685. if (!pointResult) {
  26686. pointResult = BABYLON.Vector3.Zero();
  26687. }
  26688. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  26689. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  26690. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  26691. error = this.vertexError(q, pointResult);
  26692. //TODO this should be correctly calculated
  26693. if (normalResult) {
  26694. normalResult.copyFrom(vertex1.normal);
  26695. if (vertex1.uv)
  26696. uvResult.copyFrom(vertex1.uv);
  26697. else if (vertex1.color)
  26698. colorResult.copyFrom(vertex1.color);
  26699. }
  26700. } else {
  26701. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  26702. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  26703. var error1 = this.vertexError(q, vertex1.position);
  26704. var error2 = this.vertexError(q, vertex2.position);
  26705. var error3 = this.vertexError(q, p3);
  26706. error = Math.min(error1, error2, error3);
  26707. if (error === error1) {
  26708. if (pointResult) {
  26709. pointResult.copyFrom(vertex1.position);
  26710. normalResult.copyFrom(vertex1.normal);
  26711. if (vertex1.uv)
  26712. uvResult.copyFrom(vertex1.uv);
  26713. else if (vertex1.color)
  26714. colorResult.copyFrom(vertex1.color);
  26715. }
  26716. } else if (error === error2) {
  26717. if (pointResult) {
  26718. pointResult.copyFrom(vertex2.position);
  26719. normalResult.copyFrom(vertex2.normal);
  26720. if (vertex2.uv)
  26721. uvResult.copyFrom(vertex2.uv);
  26722. else if (vertex2.color)
  26723. colorResult.copyFrom(vertex2.color);
  26724. }
  26725. } else {
  26726. if (pointResult) {
  26727. pointResult.copyFrom(p3);
  26728. normalResult.copyFrom(vertex1.normal);
  26729. if (vertex1.uv)
  26730. uvResult.copyFrom(vertex1.uv);
  26731. else if (vertex1.color)
  26732. colorResult.copyFrom(vertex1.color);
  26733. }
  26734. }
  26735. }
  26736. return error;
  26737. };
  26738. return QuadraticErrorSimplification;
  26739. })();
  26740. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  26741. })(BABYLON || (BABYLON = {}));
  26742. //# sourceMappingURL=babylon.meshSimplification.js.map
  26743. var BABYLON;
  26744. (function (BABYLON) {
  26745. var Analyser = (function () {
  26746. function Analyser(scene) {
  26747. this.SMOOTHING = 0.75;
  26748. this.FFT_SIZE = 512;
  26749. this.BARGRAPHAMPLITUDE = 256;
  26750. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  26751. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  26752. this._scene = scene;
  26753. this._audioEngine = scene.getEngine().getAudioEngine();
  26754. if (this._audioEngine.canUseWebAudio) {
  26755. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  26756. this._webAudioAnalyser.minDecibels = -140;
  26757. this._webAudioAnalyser.maxDecibels = 0;
  26758. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  26759. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  26760. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  26761. }
  26762. }
  26763. Analyser.prototype.getFrequencyBinCount = function () {
  26764. return this._webAudioAnalyser.frequencyBinCount;
  26765. };
  26766. Analyser.prototype.getByteFrequencyData = function () {
  26767. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  26768. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  26769. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  26770. return this._byteFreqs;
  26771. };
  26772. Analyser.prototype.getByteTimeDomainData = function () {
  26773. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  26774. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  26775. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  26776. return this._byteTime;
  26777. };
  26778. Analyser.prototype.getFloatFrequencyData = function () {
  26779. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  26780. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  26781. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  26782. return this._floatFreqs;
  26783. };
  26784. Analyser.prototype.drawDebugCanvas = function () {
  26785. var _this = this;
  26786. if (this._audioEngine.canUseWebAudio) {
  26787. if (!this._debugCanvas) {
  26788. this._debugCanvas = document.createElement("canvas");
  26789. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  26790. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  26791. this._debugCanvas.style.position = "absolute";
  26792. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  26793. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  26794. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  26795. document.body.appendChild(this._debugCanvas);
  26796. this._registerFunc = function () {
  26797. _this.drawDebugCanvas();
  26798. };
  26799. this._scene.registerBeforeRender(this._registerFunc);
  26800. }
  26801. if (this._registerFunc) {
  26802. var workingArray = this.getByteFrequencyData();
  26803. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  26804. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  26805. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  26806. var value = workingArray[i];
  26807. var percent = value / this.BARGRAPHAMPLITUDE;
  26808. var height = this.DEBUGCANVASSIZE.height * percent;
  26809. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  26810. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  26811. var hue = i / this.getFrequencyBinCount() * 360;
  26812. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  26813. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  26814. }
  26815. }
  26816. }
  26817. };
  26818. Analyser.prototype.stopDebugCanvas = function () {
  26819. if (this._debugCanvas) {
  26820. this._scene.unregisterBeforeRender(this._registerFunc);
  26821. this._registerFunc = null;
  26822. document.body.removeChild(this._debugCanvas);
  26823. this._debugCanvas = null;
  26824. this._debugCanvasContext = null;
  26825. }
  26826. };
  26827. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  26828. if (this._audioEngine.canUseWebAudio) {
  26829. inputAudioNode.connect(this._webAudioAnalyser);
  26830. this._webAudioAnalyser.connect(outputAudioNode);
  26831. }
  26832. };
  26833. return Analyser;
  26834. })();
  26835. BABYLON.Analyser = Analyser;
  26836. })(BABYLON || (BABYLON = {}));
  26837. //# sourceMappingURL=babylon.analyser.js.map
  26838. var BABYLON;
  26839. (function (BABYLON) {
  26840. var DepthRenderer = (function () {
  26841. function DepthRenderer(scene, type) {
  26842. if (typeof type === "undefined") { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  26843. var _this = this;
  26844. this._viewMatrix = BABYLON.Matrix.Zero();
  26845. this._projectionMatrix = BABYLON.Matrix.Zero();
  26846. this._transformMatrix = BABYLON.Matrix.Zero();
  26847. this._worldViewProjection = BABYLON.Matrix.Zero();
  26848. this._scene = scene;
  26849. var engine = scene.getEngine();
  26850. // Render target
  26851. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  26852. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26853. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26854. this._depthMap.refreshRate = 1;
  26855. this._depthMap.renderParticles = false;
  26856. this._depthMap.renderList = null;
  26857. // Custom render function
  26858. var renderSubMesh = function (subMesh) {
  26859. var mesh = subMesh.getRenderingMesh();
  26860. var scene = _this._scene;
  26861. var engine = scene.getEngine();
  26862. // Culling
  26863. engine.setState(subMesh.getMaterial().backFaceCulling);
  26864. // Managing instances
  26865. var batch = mesh._getInstancesRenderList(subMesh._id);
  26866. if (batch.mustReturn) {
  26867. return;
  26868. }
  26869. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  26870. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  26871. engine.enableEffect(_this._effect);
  26872. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  26873. var material = subMesh.getMaterial();
  26874. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26875. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  26876. // Alpha test
  26877. if (material && material.needAlphaTesting()) {
  26878. var alphaTexture = material.getAlphaTestTexture();
  26879. _this._effect.setTexture("diffuseSampler", alphaTexture);
  26880. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26881. }
  26882. // Bones
  26883. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  26884. if (useBones) {
  26885. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26886. }
  26887. if (hardwareInstancedRendering) {
  26888. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  26889. } else {
  26890. if (batch.renderSelf[subMesh._id]) {
  26891. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  26892. // Draw
  26893. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  26894. }
  26895. if (batch.visibleInstances[subMesh._id]) {
  26896. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  26897. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  26898. _this._effect.setMatrix("world", instance.getWorldMatrix());
  26899. // Draw
  26900. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  26901. }
  26902. }
  26903. }
  26904. }
  26905. };
  26906. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  26907. var index;
  26908. for (index = 0; index < opaqueSubMeshes.length; index++) {
  26909. renderSubMesh(opaqueSubMeshes.data[index]);
  26910. }
  26911. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  26912. renderSubMesh(alphaTestSubMeshes.data[index]);
  26913. }
  26914. };
  26915. }
  26916. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  26917. var defines = [];
  26918. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26919. var mesh = subMesh.getMesh();
  26920. var scene = mesh.getScene();
  26921. var material = subMesh.getMaterial();
  26922. // Alpha test
  26923. if (material && material.needAlphaTesting()) {
  26924. defines.push("#define ALPHATEST");
  26925. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26926. attribs.push(BABYLON.VertexBuffer.UVKind);
  26927. defines.push("#define UV1");
  26928. }
  26929. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26930. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26931. defines.push("#define UV2");
  26932. }
  26933. }
  26934. // Bones
  26935. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26936. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26937. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26938. defines.push("#define BONES");
  26939. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26940. }
  26941. // Instances
  26942. if (useInstances) {
  26943. defines.push("#define INSTANCES");
  26944. attribs.push("world0");
  26945. attribs.push("world1");
  26946. attribs.push("world2");
  26947. attribs.push("world3");
  26948. }
  26949. // Get correct effect
  26950. var join = defines.join("\n");
  26951. if (this._cachedDefines !== join) {
  26952. this._cachedDefines = join;
  26953. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  26954. }
  26955. return this._effect.isReady();
  26956. };
  26957. DepthRenderer.prototype.getDepthMap = function () {
  26958. return this._depthMap;
  26959. };
  26960. // Methods
  26961. DepthRenderer.prototype.dispose = function () {
  26962. this._depthMap.dispose();
  26963. };
  26964. return DepthRenderer;
  26965. })();
  26966. BABYLON.DepthRenderer = DepthRenderer;
  26967. })(BABYLON || (BABYLON = {}));
  26968. //# sourceMappingURL=babylon.depthRenderer.js.map