babylon.2.0-beta.debug.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282
  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 (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { 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 (alpha === void 0) { 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 (offset === void 0) { 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 (offset === void 0) { 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 (offset === void 0) { 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 (x === void 0) { x = 0; }
  973. if (y === void 0) { y = 0; }
  974. if (z === void 0) { z = 0; }
  975. if (w === void 0) { 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. }
  1060. else {
  1061. if (determinant === 0.0) {
  1062. result.x = 0.0;
  1063. result.y = 0.0;
  1064. 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)
  1065. }
  1066. else {
  1067. 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)
  1068. result.y = Math.PI;
  1069. result.z = 0.0;
  1070. }
  1071. }
  1072. };
  1073. Quaternion.prototype.toRotationMatrix = function (result) {
  1074. var xx = this.x * this.x;
  1075. var yy = this.y * this.y;
  1076. var zz = this.z * this.z;
  1077. var xy = this.x * this.y;
  1078. var zw = this.z * this.w;
  1079. var zx = this.z * this.x;
  1080. var yw = this.y * this.w;
  1081. var yz = this.y * this.z;
  1082. var xw = this.x * this.w;
  1083. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1084. result.m[1] = 2.0 * (xy + zw);
  1085. result.m[2] = 2.0 * (zx - yw);
  1086. result.m[3] = 0;
  1087. result.m[4] = 2.0 * (xy - zw);
  1088. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1089. result.m[6] = 2.0 * (yz + xw);
  1090. result.m[7] = 0;
  1091. result.m[8] = 2.0 * (zx + yw);
  1092. result.m[9] = 2.0 * (yz - xw);
  1093. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1094. result.m[11] = 0;
  1095. result.m[12] = 0;
  1096. result.m[13] = 0;
  1097. result.m[14] = 0;
  1098. result.m[15] = 1.0;
  1099. };
  1100. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1101. var data = matrix.m;
  1102. var m11 = data[0], m12 = data[4], m13 = data[8];
  1103. var m21 = data[1], m22 = data[5], m23 = data[9];
  1104. var m31 = data[2], m32 = data[6], m33 = data[10];
  1105. var trace = m11 + m22 + m33;
  1106. var s;
  1107. if (trace > 0) {
  1108. s = 0.5 / Math.sqrt(trace + 1.0);
  1109. this.w = 0.25 / s;
  1110. this.x = (m32 - m23) * s;
  1111. this.y = (m13 - m31) * s;
  1112. this.z = (m21 - m12) * s;
  1113. return;
  1114. }
  1115. if (m11 > m22 && m11 > m33) {
  1116. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1117. this.w = (m32 - m23) / s;
  1118. this.x = 0.25 * s;
  1119. this.y = (m12 + m21) / s;
  1120. this.z = (m13 + m31) / s;
  1121. return;
  1122. }
  1123. if (m22 > m33) {
  1124. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1125. this.w = (m13 - m31) / s;
  1126. this.x = (m12 + m21) / s;
  1127. this.y = 0.25 * s;
  1128. this.z = (m23 + m32) / s;
  1129. return;
  1130. }
  1131. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1132. this.w = (m21 - m12) / s;
  1133. this.x = (m13 + m31) / s;
  1134. this.y = (m23 + m32) / s;
  1135. this.z = 0.25 * s;
  1136. };
  1137. // Statics
  1138. Quaternion.Inverse = function (q) {
  1139. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1140. };
  1141. Quaternion.Identity = function () {
  1142. return new Quaternion(0, 0, 0, 1);
  1143. };
  1144. Quaternion.RotationAxis = function (axis, angle) {
  1145. var result = new Quaternion();
  1146. var sin = Math.sin(angle / 2);
  1147. result.w = Math.cos(angle / 2);
  1148. result.x = axis.x * sin;
  1149. result.y = axis.y * sin;
  1150. result.z = axis.z * sin;
  1151. return result;
  1152. };
  1153. Quaternion.FromArray = function (array, offset) {
  1154. if (!offset) {
  1155. offset = 0;
  1156. }
  1157. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1158. };
  1159. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1160. var result = new Quaternion();
  1161. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1162. return result;
  1163. };
  1164. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1165. var halfRoll = roll * 0.5;
  1166. var halfPitch = pitch * 0.5;
  1167. var halfYaw = yaw * 0.5;
  1168. var sinRoll = Math.sin(halfRoll);
  1169. var cosRoll = Math.cos(halfRoll);
  1170. var sinPitch = Math.sin(halfPitch);
  1171. var cosPitch = Math.cos(halfPitch);
  1172. var sinYaw = Math.sin(halfYaw);
  1173. var cosYaw = Math.cos(halfYaw);
  1174. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1175. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1176. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1177. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1178. };
  1179. Quaternion.Slerp = function (left, right, amount) {
  1180. var num2;
  1181. var num3;
  1182. var num = amount;
  1183. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1184. var flag = false;
  1185. if (num4 < 0) {
  1186. flag = true;
  1187. num4 = -num4;
  1188. }
  1189. if (num4 > 0.999999) {
  1190. num3 = 1 - num;
  1191. num2 = flag ? -num : num;
  1192. }
  1193. else {
  1194. var num5 = Math.acos(num4);
  1195. var num6 = (1.0 / Math.sin(num5));
  1196. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1197. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1198. }
  1199. 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));
  1200. };
  1201. return Quaternion;
  1202. })();
  1203. BABYLON.Quaternion = Quaternion;
  1204. var Matrix = (function () {
  1205. function Matrix() {
  1206. this.m = new Float32Array(16);
  1207. }
  1208. // Properties
  1209. Matrix.prototype.isIdentity = function () {
  1210. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1211. return false;
  1212. 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)
  1213. return false;
  1214. return true;
  1215. };
  1216. Matrix.prototype.determinant = function () {
  1217. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1218. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1219. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1220. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1221. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1222. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1223. 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))));
  1224. };
  1225. // Methods
  1226. Matrix.prototype.toArray = function () {
  1227. return this.m;
  1228. };
  1229. Matrix.prototype.asArray = function () {
  1230. return this.toArray();
  1231. };
  1232. Matrix.prototype.invert = function () {
  1233. this.invertToRef(this);
  1234. };
  1235. Matrix.prototype.invertToRef = function (other) {
  1236. var l1 = this.m[0];
  1237. var l2 = this.m[1];
  1238. var l3 = this.m[2];
  1239. var l4 = this.m[3];
  1240. var l5 = this.m[4];
  1241. var l6 = this.m[5];
  1242. var l7 = this.m[6];
  1243. var l8 = this.m[7];
  1244. var l9 = this.m[8];
  1245. var l10 = this.m[9];
  1246. var l11 = this.m[10];
  1247. var l12 = this.m[11];
  1248. var l13 = this.m[12];
  1249. var l14 = this.m[13];
  1250. var l15 = this.m[14];
  1251. var l16 = this.m[15];
  1252. var l17 = (l11 * l16) - (l12 * l15);
  1253. var l18 = (l10 * l16) - (l12 * l14);
  1254. var l19 = (l10 * l15) - (l11 * l14);
  1255. var l20 = (l9 * l16) - (l12 * l13);
  1256. var l21 = (l9 * l15) - (l11 * l13);
  1257. var l22 = (l9 * l14) - (l10 * l13);
  1258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1263. var l28 = (l7 * l16) - (l8 * l15);
  1264. var l29 = (l6 * l16) - (l8 * l14);
  1265. var l30 = (l6 * l15) - (l7 * l14);
  1266. var l31 = (l5 * l16) - (l8 * l13);
  1267. var l32 = (l5 * l15) - (l7 * l13);
  1268. var l33 = (l5 * l14) - (l6 * l13);
  1269. var l34 = (l7 * l12) - (l8 * l11);
  1270. var l35 = (l6 * l12) - (l8 * l10);
  1271. var l36 = (l6 * l11) - (l7 * l10);
  1272. var l37 = (l5 * l12) - (l8 * l9);
  1273. var l38 = (l5 * l11) - (l7 * l9);
  1274. var l39 = (l5 * l10) - (l6 * l9);
  1275. other.m[0] = l23 * l27;
  1276. other.m[4] = l24 * l27;
  1277. other.m[8] = l25 * l27;
  1278. other.m[12] = l26 * l27;
  1279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1291. };
  1292. Matrix.prototype.setTranslation = function (vector3) {
  1293. this.m[12] = vector3.x;
  1294. this.m[13] = vector3.y;
  1295. this.m[14] = vector3.z;
  1296. };
  1297. Matrix.prototype.multiply = function (other) {
  1298. var result = new Matrix();
  1299. this.multiplyToRef(other, result);
  1300. return result;
  1301. };
  1302. Matrix.prototype.copyFrom = function (other) {
  1303. for (var index = 0; index < 16; index++) {
  1304. this.m[index] = other.m[index];
  1305. }
  1306. };
  1307. Matrix.prototype.copyToArray = function (array, offset) {
  1308. if (offset === void 0) { offset = 0; }
  1309. for (var index = 0; index < 16; index++) {
  1310. array[offset + index] = this.m[index];
  1311. }
  1312. };
  1313. Matrix.prototype.multiplyToRef = function (other, result) {
  1314. this.multiplyToArray(other, result.m, 0);
  1315. };
  1316. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1317. var tm0 = this.m[0];
  1318. var tm1 = this.m[1];
  1319. var tm2 = this.m[2];
  1320. var tm3 = this.m[3];
  1321. var tm4 = this.m[4];
  1322. var tm5 = this.m[5];
  1323. var tm6 = this.m[6];
  1324. var tm7 = this.m[7];
  1325. var tm8 = this.m[8];
  1326. var tm9 = this.m[9];
  1327. var tm10 = this.m[10];
  1328. var tm11 = this.m[11];
  1329. var tm12 = this.m[12];
  1330. var tm13 = this.m[13];
  1331. var tm14 = this.m[14];
  1332. var tm15 = this.m[15];
  1333. var om0 = other.m[0];
  1334. var om1 = other.m[1];
  1335. var om2 = other.m[2];
  1336. var om3 = other.m[3];
  1337. var om4 = other.m[4];
  1338. var om5 = other.m[5];
  1339. var om6 = other.m[6];
  1340. var om7 = other.m[7];
  1341. var om8 = other.m[8];
  1342. var om9 = other.m[9];
  1343. var om10 = other.m[10];
  1344. var om11 = other.m[11];
  1345. var om12 = other.m[12];
  1346. var om13 = other.m[13];
  1347. var om14 = other.m[14];
  1348. var om15 = other.m[15];
  1349. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1350. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1351. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1352. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1353. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1354. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1355. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1356. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1357. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1358. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1359. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1360. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1361. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1362. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1363. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1364. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1365. };
  1366. Matrix.prototype.equals = function (value) {
  1367. 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]);
  1368. };
  1369. Matrix.prototype.clone = function () {
  1370. 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]);
  1371. };
  1372. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1373. translation.x = this.m[12];
  1374. translation.y = this.m[13];
  1375. translation.z = this.m[14];
  1376. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1377. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1378. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1379. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1380. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1381. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1382. if (scale.x == 0 || scale.y == 0 || scale.z == 0) {
  1383. rotation.x = 0;
  1384. rotation.y = 0;
  1385. rotation.z = 0;
  1386. rotation.w = 1;
  1387. return false;
  1388. }
  1389. 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);
  1390. rotation.fromRotationMatrix(rotationMatrix);
  1391. return true;
  1392. };
  1393. // Statics
  1394. Matrix.FromArray = function (array, offset) {
  1395. var result = new Matrix();
  1396. if (!offset) {
  1397. offset = 0;
  1398. }
  1399. Matrix.FromArrayToRef(array, offset, result);
  1400. return result;
  1401. };
  1402. Matrix.FromArrayToRef = function (array, offset, result) {
  1403. for (var index = 0; index < 16; index++) {
  1404. result.m[index] = array[index + offset];
  1405. }
  1406. };
  1407. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1408. result.m[0] = initialM11;
  1409. result.m[1] = initialM12;
  1410. result.m[2] = initialM13;
  1411. result.m[3] = initialM14;
  1412. result.m[4] = initialM21;
  1413. result.m[5] = initialM22;
  1414. result.m[6] = initialM23;
  1415. result.m[7] = initialM24;
  1416. result.m[8] = initialM31;
  1417. result.m[9] = initialM32;
  1418. result.m[10] = initialM33;
  1419. result.m[11] = initialM34;
  1420. result.m[12] = initialM41;
  1421. result.m[13] = initialM42;
  1422. result.m[14] = initialM43;
  1423. result.m[15] = initialM44;
  1424. };
  1425. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1426. var result = new Matrix();
  1427. result.m[0] = initialM11;
  1428. result.m[1] = initialM12;
  1429. result.m[2] = initialM13;
  1430. result.m[3] = initialM14;
  1431. result.m[4] = initialM21;
  1432. result.m[5] = initialM22;
  1433. result.m[6] = initialM23;
  1434. result.m[7] = initialM24;
  1435. result.m[8] = initialM31;
  1436. result.m[9] = initialM32;
  1437. result.m[10] = initialM33;
  1438. result.m[11] = initialM34;
  1439. result.m[12] = initialM41;
  1440. result.m[13] = initialM42;
  1441. result.m[14] = initialM43;
  1442. result.m[15] = initialM44;
  1443. return result;
  1444. };
  1445. Matrix.Compose = function (scale, rotation, translation) {
  1446. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1447. var rotationMatrix = Matrix.Identity();
  1448. rotation.toRotationMatrix(rotationMatrix);
  1449. result = result.multiply(rotationMatrix);
  1450. result.setTranslation(translation);
  1451. return result;
  1452. };
  1453. Matrix.Identity = function () {
  1454. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1455. };
  1456. Matrix.IdentityToRef = function (result) {
  1457. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1458. };
  1459. Matrix.Zero = function () {
  1460. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1461. };
  1462. Matrix.RotationX = function (angle) {
  1463. var result = new Matrix();
  1464. Matrix.RotationXToRef(angle, result);
  1465. return result;
  1466. };
  1467. Matrix.Invert = function (source) {
  1468. var result = new Matrix();
  1469. source.invertToRef(result);
  1470. return result;
  1471. };
  1472. Matrix.RotationXToRef = function (angle, result) {
  1473. var s = Math.sin(angle);
  1474. var c = Math.cos(angle);
  1475. result.m[0] = 1.0;
  1476. result.m[15] = 1.0;
  1477. result.m[5] = c;
  1478. result.m[10] = c;
  1479. result.m[9] = -s;
  1480. result.m[6] = s;
  1481. result.m[1] = 0;
  1482. result.m[2] = 0;
  1483. result.m[3] = 0;
  1484. result.m[4] = 0;
  1485. result.m[7] = 0;
  1486. result.m[8] = 0;
  1487. result.m[11] = 0;
  1488. result.m[12] = 0;
  1489. result.m[13] = 0;
  1490. result.m[14] = 0;
  1491. };
  1492. Matrix.RotationY = function (angle) {
  1493. var result = new Matrix();
  1494. Matrix.RotationYToRef(angle, result);
  1495. return result;
  1496. };
  1497. Matrix.RotationYToRef = function (angle, result) {
  1498. var s = Math.sin(angle);
  1499. var c = Math.cos(angle);
  1500. result.m[5] = 1.0;
  1501. result.m[15] = 1.0;
  1502. result.m[0] = c;
  1503. result.m[2] = -s;
  1504. result.m[8] = s;
  1505. result.m[10] = c;
  1506. result.m[1] = 0;
  1507. result.m[3] = 0;
  1508. result.m[4] = 0;
  1509. result.m[6] = 0;
  1510. result.m[7] = 0;
  1511. result.m[9] = 0;
  1512. result.m[11] = 0;
  1513. result.m[12] = 0;
  1514. result.m[13] = 0;
  1515. result.m[14] = 0;
  1516. };
  1517. Matrix.RotationZ = function (angle) {
  1518. var result = new Matrix();
  1519. Matrix.RotationZToRef(angle, result);
  1520. return result;
  1521. };
  1522. Matrix.RotationZToRef = function (angle, result) {
  1523. var s = Math.sin(angle);
  1524. var c = Math.cos(angle);
  1525. result.m[10] = 1.0;
  1526. result.m[15] = 1.0;
  1527. result.m[0] = c;
  1528. result.m[1] = s;
  1529. result.m[4] = -s;
  1530. result.m[5] = c;
  1531. result.m[2] = 0;
  1532. result.m[3] = 0;
  1533. result.m[6] = 0;
  1534. result.m[7] = 0;
  1535. result.m[8] = 0;
  1536. result.m[9] = 0;
  1537. result.m[11] = 0;
  1538. result.m[12] = 0;
  1539. result.m[13] = 0;
  1540. result.m[14] = 0;
  1541. };
  1542. Matrix.RotationAxis = function (axis, angle) {
  1543. var s = Math.sin(-angle);
  1544. var c = Math.cos(-angle);
  1545. var c1 = 1 - c;
  1546. axis.normalize();
  1547. var result = Matrix.Zero();
  1548. result.m[0] = (axis.x * axis.x) * c1 + c;
  1549. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1550. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1551. result.m[3] = 0.0;
  1552. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1553. result.m[5] = (axis.y * axis.y) * c1 + c;
  1554. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1555. result.m[7] = 0.0;
  1556. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1557. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1558. result.m[10] = (axis.z * axis.z) * c1 + c;
  1559. result.m[11] = 0.0;
  1560. result.m[15] = 1.0;
  1561. return result;
  1562. };
  1563. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1564. var result = new Matrix();
  1565. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1566. return result;
  1567. };
  1568. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1569. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1570. this._tempQuaternion.toRotationMatrix(result);
  1571. };
  1572. Matrix.Scaling = function (x, y, z) {
  1573. var result = Matrix.Zero();
  1574. Matrix.ScalingToRef(x, y, z, result);
  1575. return result;
  1576. };
  1577. Matrix.ScalingToRef = function (x, y, z, result) {
  1578. result.m[0] = x;
  1579. result.m[1] = 0;
  1580. result.m[2] = 0;
  1581. result.m[3] = 0;
  1582. result.m[4] = 0;
  1583. result.m[5] = y;
  1584. result.m[6] = 0;
  1585. result.m[7] = 0;
  1586. result.m[8] = 0;
  1587. result.m[9] = 0;
  1588. result.m[10] = z;
  1589. result.m[11] = 0;
  1590. result.m[12] = 0;
  1591. result.m[13] = 0;
  1592. result.m[14] = 0;
  1593. result.m[15] = 1.0;
  1594. };
  1595. Matrix.Translation = function (x, y, z) {
  1596. var result = Matrix.Identity();
  1597. Matrix.TranslationToRef(x, y, z, result);
  1598. return result;
  1599. };
  1600. Matrix.TranslationToRef = function (x, y, z, result) {
  1601. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1602. };
  1603. Matrix.LookAtLH = function (eye, target, up) {
  1604. var result = Matrix.Zero();
  1605. Matrix.LookAtLHToRef(eye, target, up, result);
  1606. return result;
  1607. };
  1608. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1609. // Z axis
  1610. target.subtractToRef(eye, this._zAxis);
  1611. this._zAxis.normalize();
  1612. // X axis
  1613. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1614. this._xAxis.normalize();
  1615. // Y axis
  1616. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1617. this._yAxis.normalize();
  1618. // Eye angles
  1619. var ex = -Vector3.Dot(this._xAxis, eye);
  1620. var ey = -Vector3.Dot(this._yAxis, eye);
  1621. var ez = -Vector3.Dot(this._zAxis, eye);
  1622. 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);
  1623. };
  1624. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1625. var hw = 2.0 / width;
  1626. var hh = 2.0 / height;
  1627. var id = 1.0 / (zfar - znear);
  1628. var nid = znear / (znear - zfar);
  1629. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1630. };
  1631. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1632. var matrix = Matrix.Zero();
  1633. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1634. return matrix;
  1635. };
  1636. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1637. result.m[0] = 2.0 / (right - left);
  1638. result.m[1] = result.m[2] = result.m[3] = 0;
  1639. result.m[5] = 2.0 / (top - bottom);
  1640. result.m[4] = result.m[6] = result.m[7] = 0;
  1641. result.m[10] = -1.0 / (znear - zfar);
  1642. result.m[8] = result.m[9] = result.m[11] = 0;
  1643. result.m[12] = (left + right) / (left - right);
  1644. result.m[13] = (top + bottom) / (bottom - top);
  1645. result.m[14] = znear / (znear - zfar);
  1646. result.m[15] = 1.0;
  1647. };
  1648. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1649. var matrix = Matrix.Zero();
  1650. matrix.m[0] = (2.0 * znear) / width;
  1651. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1652. matrix.m[5] = (2.0 * znear) / height;
  1653. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1654. matrix.m[10] = -zfar / (znear - zfar);
  1655. matrix.m[8] = matrix.m[9] = 0.0;
  1656. matrix.m[11] = 1.0;
  1657. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1658. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1659. return matrix;
  1660. };
  1661. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1662. var matrix = Matrix.Zero();
  1663. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1664. return matrix;
  1665. };
  1666. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1667. var tan = 1.0 / (Math.tan(fov * 0.5));
  1668. result.m[0] = tan / aspect;
  1669. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1670. result.m[5] = tan;
  1671. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1672. result.m[8] = result.m[9] = 0.0;
  1673. result.m[10] = -zfar / (znear - zfar);
  1674. result.m[11] = 1.0;
  1675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1676. result.m[14] = (znear * zfar) / (znear - zfar);
  1677. };
  1678. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1679. var cw = viewport.width;
  1680. var ch = viewport.height;
  1681. var cx = viewport.x;
  1682. var cy = viewport.y;
  1683. 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);
  1684. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1685. };
  1686. Matrix.Transpose = function (matrix) {
  1687. var result = new Matrix();
  1688. result.m[0] = matrix.m[0];
  1689. result.m[1] = matrix.m[4];
  1690. result.m[2] = matrix.m[8];
  1691. result.m[3] = matrix.m[12];
  1692. result.m[4] = matrix.m[1];
  1693. result.m[5] = matrix.m[5];
  1694. result.m[6] = matrix.m[9];
  1695. result.m[7] = matrix.m[13];
  1696. result.m[8] = matrix.m[2];
  1697. result.m[9] = matrix.m[6];
  1698. result.m[10] = matrix.m[10];
  1699. result.m[11] = matrix.m[14];
  1700. result.m[12] = matrix.m[3];
  1701. result.m[13] = matrix.m[7];
  1702. result.m[14] = matrix.m[11];
  1703. result.m[15] = matrix.m[15];
  1704. return result;
  1705. };
  1706. Matrix.Reflection = function (plane) {
  1707. var matrix = new Matrix();
  1708. Matrix.ReflectionToRef(plane, matrix);
  1709. return matrix;
  1710. };
  1711. Matrix.ReflectionToRef = function (plane, result) {
  1712. plane.normalize();
  1713. var x = plane.normal.x;
  1714. var y = plane.normal.y;
  1715. var z = plane.normal.z;
  1716. var temp = -2 * x;
  1717. var temp2 = -2 * y;
  1718. var temp3 = -2 * z;
  1719. result.m[0] = (temp * x) + 1;
  1720. result.m[1] = temp2 * x;
  1721. result.m[2] = temp3 * x;
  1722. result.m[3] = 0.0;
  1723. result.m[4] = temp * y;
  1724. result.m[5] = (temp2 * y) + 1;
  1725. result.m[6] = temp3 * y;
  1726. result.m[7] = 0.0;
  1727. result.m[8] = temp * z;
  1728. result.m[9] = temp2 * z;
  1729. result.m[10] = (temp3 * z) + 1;
  1730. result.m[11] = 0.0;
  1731. result.m[12] = temp * plane.d;
  1732. result.m[13] = temp2 * plane.d;
  1733. result.m[14] = temp3 * plane.d;
  1734. result.m[15] = 1.0;
  1735. };
  1736. Matrix._tempQuaternion = new Quaternion();
  1737. Matrix._xAxis = Vector3.Zero();
  1738. Matrix._yAxis = Vector3.Zero();
  1739. Matrix._zAxis = Vector3.Zero();
  1740. return Matrix;
  1741. })();
  1742. BABYLON.Matrix = Matrix;
  1743. var Plane = (function () {
  1744. function Plane(a, b, c, d) {
  1745. this.normal = new Vector3(a, b, c);
  1746. this.d = d;
  1747. }
  1748. Plane.prototype.asArray = function () {
  1749. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1750. };
  1751. // Methods
  1752. Plane.prototype.clone = function () {
  1753. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1754. };
  1755. Plane.prototype.normalize = function () {
  1756. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1757. var magnitude = 0;
  1758. if (norm !== 0) {
  1759. magnitude = 1.0 / norm;
  1760. }
  1761. this.normal.x *= magnitude;
  1762. this.normal.y *= magnitude;
  1763. this.normal.z *= magnitude;
  1764. this.d *= magnitude;
  1765. };
  1766. Plane.prototype.transform = function (transformation) {
  1767. var transposedMatrix = Matrix.Transpose(transformation);
  1768. var x = this.normal.x;
  1769. var y = this.normal.y;
  1770. var z = this.normal.z;
  1771. var d = this.d;
  1772. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1773. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1774. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1775. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1776. return new Plane(normalX, normalY, normalZ, finalD);
  1777. };
  1778. Plane.prototype.dotCoordinate = function (point) {
  1779. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1780. };
  1781. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1782. var x1 = point2.x - point1.x;
  1783. var y1 = point2.y - point1.y;
  1784. var z1 = point2.z - point1.z;
  1785. var x2 = point3.x - point1.x;
  1786. var y2 = point3.y - point1.y;
  1787. var z2 = point3.z - point1.z;
  1788. var yz = (y1 * z2) - (z1 * y2);
  1789. var xz = (z1 * x2) - (x1 * z2);
  1790. var xy = (x1 * y2) - (y1 * x2);
  1791. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1792. var invPyth;
  1793. if (pyth !== 0) {
  1794. invPyth = 1.0 / pyth;
  1795. }
  1796. else {
  1797. invPyth = 0;
  1798. }
  1799. this.normal.x = yz * invPyth;
  1800. this.normal.y = xz * invPyth;
  1801. this.normal.z = xy * invPyth;
  1802. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1803. };
  1804. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1805. var dot = Vector3.Dot(this.normal, direction);
  1806. return (dot <= epsilon);
  1807. };
  1808. Plane.prototype.signedDistanceTo = function (point) {
  1809. return Vector3.Dot(point, this.normal) + this.d;
  1810. };
  1811. // Statics
  1812. Plane.FromArray = function (array) {
  1813. return new Plane(array[0], array[1], array[2], array[3]);
  1814. };
  1815. Plane.FromPoints = function (point1, point2, point3) {
  1816. var result = new Plane(0, 0, 0, 0);
  1817. result.copyFromPoints(point1, point2, point3);
  1818. return result;
  1819. };
  1820. Plane.FromPositionAndNormal = function (origin, normal) {
  1821. var result = new Plane(0, 0, 0, 0);
  1822. normal.normalize();
  1823. result.normal = normal;
  1824. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1825. return result;
  1826. };
  1827. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1828. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1829. return Vector3.Dot(point, normal) + d;
  1830. };
  1831. return Plane;
  1832. })();
  1833. BABYLON.Plane = Plane;
  1834. var Viewport = (function () {
  1835. function Viewport(x, y, width, height) {
  1836. this.x = x;
  1837. this.y = y;
  1838. this.width = width;
  1839. this.height = height;
  1840. }
  1841. Viewport.prototype.toGlobal = function (engine) {
  1842. var width = engine.getRenderWidth();
  1843. var height = engine.getRenderHeight();
  1844. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1845. };
  1846. return Viewport;
  1847. })();
  1848. BABYLON.Viewport = Viewport;
  1849. var Frustum = (function () {
  1850. function Frustum() {
  1851. }
  1852. Frustum.GetPlanes = function (transform) {
  1853. var frustumPlanes = [];
  1854. for (var index = 0; index < 6; index++) {
  1855. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1856. }
  1857. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1858. return frustumPlanes;
  1859. };
  1860. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1861. // Near
  1862. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1863. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1864. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1865. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1866. frustumPlanes[0].normalize();
  1867. // Far
  1868. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1869. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1870. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1871. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1872. frustumPlanes[1].normalize();
  1873. // Left
  1874. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1875. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1876. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1877. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1878. frustumPlanes[2].normalize();
  1879. // Right
  1880. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1881. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1882. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1883. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1884. frustumPlanes[3].normalize();
  1885. // Top
  1886. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1887. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1888. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1889. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1890. frustumPlanes[4].normalize();
  1891. // Bottom
  1892. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1893. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1894. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1895. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1896. frustumPlanes[5].normalize();
  1897. };
  1898. return Frustum;
  1899. })();
  1900. BABYLON.Frustum = Frustum;
  1901. var Ray = (function () {
  1902. function Ray(origin, direction, length) {
  1903. if (length === void 0) { length = Number.MAX_VALUE; }
  1904. this.origin = origin;
  1905. this.direction = direction;
  1906. this.length = length;
  1907. }
  1908. // Methods
  1909. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1910. var d = 0.0;
  1911. var maxValue = Number.MAX_VALUE;
  1912. if (Math.abs(this.direction.x) < 0.0000001) {
  1913. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1914. return false;
  1915. }
  1916. }
  1917. else {
  1918. var inv = 1.0 / this.direction.x;
  1919. var min = (minimum.x - this.origin.x) * inv;
  1920. var max = (maximum.x - this.origin.x) * inv;
  1921. if (max === -Infinity) {
  1922. max = Infinity;
  1923. }
  1924. if (min > max) {
  1925. var temp = min;
  1926. min = max;
  1927. max = temp;
  1928. }
  1929. d = Math.max(min, d);
  1930. maxValue = Math.min(max, maxValue);
  1931. if (d > maxValue) {
  1932. return false;
  1933. }
  1934. }
  1935. if (Math.abs(this.direction.y) < 0.0000001) {
  1936. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1937. return false;
  1938. }
  1939. }
  1940. else {
  1941. inv = 1.0 / this.direction.y;
  1942. min = (minimum.y - this.origin.y) * inv;
  1943. max = (maximum.y - this.origin.y) * inv;
  1944. if (max === -Infinity) {
  1945. max = Infinity;
  1946. }
  1947. if (min > max) {
  1948. temp = min;
  1949. min = max;
  1950. max = temp;
  1951. }
  1952. d = Math.max(min, d);
  1953. maxValue = Math.min(max, maxValue);
  1954. if (d > maxValue) {
  1955. return false;
  1956. }
  1957. }
  1958. if (Math.abs(this.direction.z) < 0.0000001) {
  1959. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1960. return false;
  1961. }
  1962. }
  1963. else {
  1964. inv = 1.0 / this.direction.z;
  1965. min = (minimum.z - this.origin.z) * inv;
  1966. max = (maximum.z - this.origin.z) * inv;
  1967. if (max === -Infinity) {
  1968. max = Infinity;
  1969. }
  1970. if (min > max) {
  1971. temp = min;
  1972. min = max;
  1973. max = temp;
  1974. }
  1975. d = Math.max(min, d);
  1976. maxValue = Math.min(max, maxValue);
  1977. if (d > maxValue) {
  1978. return false;
  1979. }
  1980. }
  1981. return true;
  1982. };
  1983. Ray.prototype.intersectsBox = function (box) {
  1984. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1985. };
  1986. Ray.prototype.intersectsSphere = function (sphere) {
  1987. var x = sphere.center.x - this.origin.x;
  1988. var y = sphere.center.y - this.origin.y;
  1989. var z = sphere.center.z - this.origin.z;
  1990. var pyth = (x * x) + (y * y) + (z * z);
  1991. var rr = sphere.radius * sphere.radius;
  1992. if (pyth <= rr) {
  1993. return true;
  1994. }
  1995. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1996. if (dot < 0.0) {
  1997. return false;
  1998. }
  1999. var temp = pyth - (dot * dot);
  2000. return temp <= rr;
  2001. };
  2002. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2003. if (!this._edge1) {
  2004. this._edge1 = Vector3.Zero();
  2005. this._edge2 = Vector3.Zero();
  2006. this._pvec = Vector3.Zero();
  2007. this._tvec = Vector3.Zero();
  2008. this._qvec = Vector3.Zero();
  2009. }
  2010. vertex1.subtractToRef(vertex0, this._edge1);
  2011. vertex2.subtractToRef(vertex0, this._edge2);
  2012. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2013. var det = Vector3.Dot(this._edge1, this._pvec);
  2014. if (det === 0) {
  2015. return null;
  2016. }
  2017. var invdet = 1 / det;
  2018. this.origin.subtractToRef(vertex0, this._tvec);
  2019. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2020. if (bu < 0 || bu > 1.0) {
  2021. return null;
  2022. }
  2023. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2024. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2025. if (bv < 0 || bu + bv > 1.0) {
  2026. return null;
  2027. }
  2028. //check if the distance is longer than the predefined length.
  2029. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2030. if (distance > this.length) {
  2031. return null;
  2032. }
  2033. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2034. };
  2035. // Statics
  2036. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2037. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2038. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2039. var direction = end.subtract(start);
  2040. direction.normalize();
  2041. return new Ray(start, direction);
  2042. };
  2043. /**
  2044. * 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
  2045. * transformed to the given world matrix.
  2046. * @param origin The origin point
  2047. * @param end The end point
  2048. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2049. */
  2050. Ray.CreateNewFromTo = function (origin, end, world) {
  2051. if (world === void 0) { world = Matrix.Identity(); }
  2052. var direction = end.subtract(origin);
  2053. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2054. direction.normalize();
  2055. return Ray.Transform(new Ray(origin, direction, length), world);
  2056. };
  2057. Ray.Transform = function (ray, matrix) {
  2058. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2059. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2060. return new Ray(newOrigin, newDirection, ray.length);
  2061. };
  2062. return Ray;
  2063. })();
  2064. BABYLON.Ray = Ray;
  2065. (function (Space) {
  2066. Space[Space["LOCAL"] = 0] = "LOCAL";
  2067. Space[Space["WORLD"] = 1] = "WORLD";
  2068. })(BABYLON.Space || (BABYLON.Space = {}));
  2069. var Space = BABYLON.Space;
  2070. var Axis = (function () {
  2071. function Axis() {
  2072. }
  2073. Axis.X = new Vector3(1, 0, 0);
  2074. Axis.Y = new Vector3(0, 1, 0);
  2075. Axis.Z = new Vector3(0, 0, 1);
  2076. return Axis;
  2077. })();
  2078. BABYLON.Axis = Axis;
  2079. ;
  2080. var BezierCurve = (function () {
  2081. function BezierCurve() {
  2082. }
  2083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2084. // Extract X (which is equal to time here)
  2085. var f0 = 1 - 3 * x2 + 3 * x1;
  2086. var f1 = 3 * x2 - 6 * x1;
  2087. var f2 = 3 * x1;
  2088. var refinedT = t;
  2089. for (var i = 0; i < 5; i++) {
  2090. var refinedT2 = refinedT * refinedT;
  2091. var refinedT3 = refinedT2 * refinedT;
  2092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2094. refinedT -= (x - t) * slope;
  2095. refinedT = Math.min(1, Math.max(0, refinedT));
  2096. }
  2097. // Resolve cubic bezier for the given x
  2098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2099. };
  2100. return BezierCurve;
  2101. })();
  2102. BABYLON.BezierCurve = BezierCurve;
  2103. (function (Orientation) {
  2104. Orientation[Orientation["CW"] = 0] = "CW";
  2105. Orientation[Orientation["CCW"] = 1] = "CCW";
  2106. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2107. var Orientation = BABYLON.Orientation;
  2108. var Angle = (function () {
  2109. function Angle(radians) {
  2110. var _this = this;
  2111. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2112. this.radians = function () { return _this._radians; };
  2113. this._radians = radians;
  2114. if (this._radians < 0)
  2115. this._radians += (2 * Math.PI);
  2116. }
  2117. Angle.BetweenTwoPoints = function (a, b) {
  2118. var delta = b.subtract(a);
  2119. var theta = Math.atan2(delta.y, delta.x);
  2120. return new Angle(theta);
  2121. };
  2122. Angle.FromRadians = function (radians) {
  2123. return new Angle(radians);
  2124. };
  2125. Angle.FromDegrees = function (degrees) {
  2126. return new Angle(degrees * Math.PI / 180);
  2127. };
  2128. return Angle;
  2129. })();
  2130. BABYLON.Angle = Angle;
  2131. var Arc2 = (function () {
  2132. function Arc2(startPoint, midPoint, endPoint) {
  2133. this.startPoint = startPoint;
  2134. this.midPoint = midPoint;
  2135. this.endPoint = endPoint;
  2136. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2137. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2138. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2139. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2140. 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);
  2141. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2142. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2143. var a1 = this.startAngle.degrees();
  2144. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2145. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2146. // angles correction
  2147. if (a2 - a1 > +180.0)
  2148. a2 -= 360.0;
  2149. if (a2 - a1 < -180.0)
  2150. a2 += 360.0;
  2151. if (a3 - a2 > +180.0)
  2152. a3 -= 360.0;
  2153. if (a3 - a2 < -180.0)
  2154. a3 += 360.0;
  2155. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2156. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2157. }
  2158. return Arc2;
  2159. })();
  2160. BABYLON.Arc2 = Arc2;
  2161. var PathCursor = (function () {
  2162. function PathCursor(path) {
  2163. this.path = path;
  2164. this._onchange = new Array();
  2165. this.value = 0;
  2166. this.animations = new Array();
  2167. }
  2168. PathCursor.prototype.getPoint = function () {
  2169. var point = this.path.getPointAtLengthPosition(this.value);
  2170. return new Vector3(point.x, 0, point.y);
  2171. };
  2172. PathCursor.prototype.moveAhead = function (step) {
  2173. if (step === void 0) { step = 0.002; }
  2174. this.move(step);
  2175. };
  2176. PathCursor.prototype.moveBack = function (step) {
  2177. if (step === void 0) { step = 0.002; }
  2178. this.move(-step);
  2179. };
  2180. PathCursor.prototype.move = function (step) {
  2181. if (Math.abs(step) > 1) {
  2182. throw "step size should be less than 1.";
  2183. }
  2184. this.value += step;
  2185. this.ensureLimits();
  2186. this.raiseOnChange();
  2187. };
  2188. PathCursor.prototype.ensureLimits = function () {
  2189. while (this.value > 1) {
  2190. this.value -= 1;
  2191. }
  2192. while (this.value < 0) {
  2193. this.value += 1;
  2194. }
  2195. };
  2196. // used by animation engine
  2197. PathCursor.prototype.markAsDirty = function (propertyName) {
  2198. this.ensureLimits();
  2199. this.raiseOnChange();
  2200. };
  2201. PathCursor.prototype.raiseOnChange = function () {
  2202. var _this = this;
  2203. this._onchange.forEach(function (f) { return f(_this); });
  2204. };
  2205. PathCursor.prototype.onchange = function (f) {
  2206. this._onchange.push(f);
  2207. };
  2208. return PathCursor;
  2209. })();
  2210. BABYLON.PathCursor = PathCursor;
  2211. var Path2 = (function () {
  2212. function Path2(x, y) {
  2213. this._points = [];
  2214. this._length = 0;
  2215. this.closed = false;
  2216. this._points.push(new Vector2(x, y));
  2217. }
  2218. Path2.prototype.addLineTo = function (x, y) {
  2219. if (closed) {
  2220. BABYLON.Tools.Error("cannot add lines to closed paths");
  2221. return this;
  2222. }
  2223. var newPoint = new Vector2(x, y);
  2224. var previousPoint = this._points[this._points.length - 1];
  2225. this._points.push(newPoint);
  2226. this._length += newPoint.subtract(previousPoint).length();
  2227. return this;
  2228. };
  2229. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2230. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2231. if (closed) {
  2232. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2233. return this;
  2234. }
  2235. var startPoint = this._points[this._points.length - 1];
  2236. var midPoint = new Vector2(midX, midY);
  2237. var endPoint = new Vector2(endX, endY);
  2238. var arc = new Arc2(startPoint, midPoint, endPoint);
  2239. var increment = arc.angle.radians() / numberOfSegments;
  2240. if (arc.orientation === 0 /* CW */)
  2241. increment *= -1;
  2242. var currentAngle = arc.startAngle.radians() + increment;
  2243. for (var i = 0; i < numberOfSegments; i++) {
  2244. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2245. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2246. this.addLineTo(x, y);
  2247. currentAngle += increment;
  2248. }
  2249. return this;
  2250. };
  2251. Path2.prototype.close = function () {
  2252. this.closed = true;
  2253. return this;
  2254. };
  2255. Path2.prototype.length = function () {
  2256. var result = this._length;
  2257. if (!this.closed) {
  2258. var lastPoint = this._points[this._points.length - 1];
  2259. var firstPoint = this._points[0];
  2260. result += (firstPoint.subtract(lastPoint).length());
  2261. }
  2262. return result;
  2263. };
  2264. Path2.prototype.getPoints = function () {
  2265. return this._points;
  2266. };
  2267. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2268. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2269. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2270. return;
  2271. }
  2272. var lengthPosition = normalizedLengthPosition * this.length();
  2273. var previousOffset = 0;
  2274. for (var i = 0; i < this._points.length; i++) {
  2275. var j = (i + 1) % this._points.length;
  2276. var a = this._points[i];
  2277. var b = this._points[j];
  2278. var bToA = b.subtract(a);
  2279. var nextOffset = (bToA.length() + previousOffset);
  2280. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2281. var dir = bToA.normalize();
  2282. var localOffset = lengthPosition - previousOffset;
  2283. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2284. }
  2285. previousOffset = nextOffset;
  2286. }
  2287. BABYLON.Tools.Error("internal error");
  2288. };
  2289. Path2.StartingAt = function (x, y) {
  2290. return new Path2(x, y);
  2291. };
  2292. return Path2;
  2293. })();
  2294. BABYLON.Path2 = Path2;
  2295. })(BABYLON || (BABYLON = {}));
  2296. //# sourceMappingURL=babylon.math.js.mapvar 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. }
  2309. else if (source.clone) {
  2310. return source.clone();
  2311. }
  2312. return null;
  2313. };
  2314. var Tools = (function () {
  2315. function Tools() {
  2316. }
  2317. Tools.GetFilename = function (path) {
  2318. var index = path.lastIndexOf("/");
  2319. if (index < 0)
  2320. return path;
  2321. return path.substring(index + 1);
  2322. };
  2323. Tools.GetDOMTextContent = function (element) {
  2324. var result = "";
  2325. var child = element.firstChild;
  2326. while (child) {
  2327. if (child.nodeType == 3) {
  2328. result += child.textContent;
  2329. }
  2330. child = child.nextSibling;
  2331. }
  2332. return result;
  2333. };
  2334. Tools.ToDegrees = function (angle) {
  2335. return angle * 180 / Math.PI;
  2336. };
  2337. Tools.ToRadians = function (angle) {
  2338. return angle * Math.PI / 180;
  2339. };
  2340. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2341. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2342. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2343. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2344. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2345. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2346. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2347. }
  2348. return {
  2349. minimum: minimum,
  2350. maximum: maximum
  2351. };
  2352. };
  2353. Tools.ExtractMinAndMax = function (positions, start, count) {
  2354. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2355. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2356. for (var index = start; index < start + count; index++) {
  2357. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2358. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2359. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2360. }
  2361. return {
  2362. minimum: minimum,
  2363. maximum: maximum
  2364. };
  2365. };
  2366. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2367. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2368. return undefined;
  2369. return Array.isArray(obj) ? obj : [obj];
  2370. };
  2371. // Misc.
  2372. Tools.GetPointerPrefix = function () {
  2373. var eventPrefix = "pointer";
  2374. // Check if hand.js is referenced or if the browser natively supports pointer events
  2375. if (!navigator.pointerEnabled) {
  2376. eventPrefix = "mouse";
  2377. }
  2378. return eventPrefix;
  2379. };
  2380. Tools.QueueNewFrame = function (func) {
  2381. if (window.requestAnimationFrame)
  2382. window.requestAnimationFrame(func);
  2383. else if (window.msRequestAnimationFrame)
  2384. window.msRequestAnimationFrame(func);
  2385. else if (window.webkitRequestAnimationFrame)
  2386. window.webkitRequestAnimationFrame(func);
  2387. else if (window.mozRequestAnimationFrame)
  2388. window.mozRequestAnimationFrame(func);
  2389. else if (window.oRequestAnimationFrame)
  2390. window.oRequestAnimationFrame(func);
  2391. else {
  2392. window.setTimeout(func, 16);
  2393. }
  2394. };
  2395. Tools.RequestFullscreen = function (element) {
  2396. if (element.requestFullscreen)
  2397. element.requestFullscreen();
  2398. else if (element.msRequestFullscreen)
  2399. element.msRequestFullscreen();
  2400. else if (element.webkitRequestFullscreen)
  2401. element.webkitRequestFullscreen();
  2402. else if (element.mozRequestFullScreen)
  2403. element.mozRequestFullScreen();
  2404. };
  2405. Tools.ExitFullscreen = function () {
  2406. if (document.exitFullscreen) {
  2407. document.exitFullscreen();
  2408. }
  2409. else if (document.mozCancelFullScreen) {
  2410. document.mozCancelFullScreen();
  2411. }
  2412. else if (document.webkitCancelFullScreen) {
  2413. document.webkitCancelFullScreen();
  2414. }
  2415. else if (document.msCancelFullScreen) {
  2416. document.msCancelFullScreen();
  2417. }
  2418. };
  2419. // External files
  2420. Tools.CleanUrl = function (url) {
  2421. url = url.replace(/#/mg, "%23");
  2422. return url;
  2423. };
  2424. Tools.LoadImage = function (url, onload, onerror, database) {
  2425. url = Tools.CleanUrl(url);
  2426. var img = new Image();
  2427. if (url.substr(0, 5) != "data:")
  2428. img.crossOrigin = 'anonymous';
  2429. img.onload = function () {
  2430. onload(img);
  2431. };
  2432. img.onerror = function (err) {
  2433. onerror(img, err);
  2434. };
  2435. var noIndexedDB = function () {
  2436. img.src = url;
  2437. };
  2438. var loadFromIndexedDB = function () {
  2439. database.loadImageFromDB(url, img);
  2440. };
  2441. //ANY database to do!
  2442. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2443. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2444. }
  2445. else {
  2446. if (url.indexOf("file:") === -1) {
  2447. noIndexedDB();
  2448. }
  2449. else {
  2450. try {
  2451. var textureName = url.substring(5);
  2452. var blobURL;
  2453. try {
  2454. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2455. }
  2456. catch (ex) {
  2457. // Chrome doesn't support oneTimeOnly parameter
  2458. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2459. }
  2460. img.src = blobURL;
  2461. }
  2462. catch (e) {
  2463. Tools.Log("Error while trying to load texture: " + textureName);
  2464. img.src = null;
  2465. }
  2466. }
  2467. }
  2468. return img;
  2469. };
  2470. //ANY
  2471. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2472. url = Tools.CleanUrl(url);
  2473. var noIndexedDB = function () {
  2474. var request = new XMLHttpRequest();
  2475. var loadUrl = Tools.BaseUrl + url;
  2476. request.open('GET', loadUrl, true);
  2477. if (useArrayBuffer) {
  2478. request.responseType = "arraybuffer";
  2479. }
  2480. request.onprogress = progressCallBack;
  2481. request.onreadystatechange = function () {
  2482. if (request.readyState == 4) {
  2483. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2484. callback(!useArrayBuffer ? request.responseText : request.response);
  2485. }
  2486. else {
  2487. if (onError) {
  2488. onError();
  2489. }
  2490. else {
  2491. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2492. }
  2493. }
  2494. }
  2495. };
  2496. request.send(null);
  2497. };
  2498. var loadFromIndexedDB = function () {
  2499. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2500. };
  2501. if (url.indexOf("file:") !== -1) {
  2502. var fileName = url.substring(5);
  2503. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2504. }
  2505. else {
  2506. // Caching all files
  2507. if (database && database.enableSceneOffline) {
  2508. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2509. }
  2510. else {
  2511. noIndexedDB();
  2512. }
  2513. }
  2514. };
  2515. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2516. var reader = new FileReader();
  2517. reader.onload = function (e) {
  2518. callback(e.target.result);
  2519. };
  2520. reader.onprogress = progressCallback;
  2521. reader.readAsDataURL(fileToLoad);
  2522. };
  2523. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2524. var reader = new FileReader();
  2525. reader.onload = function (e) {
  2526. callback(e.target.result);
  2527. };
  2528. reader.onprogress = progressCallBack;
  2529. if (!useArrayBuffer) {
  2530. // Asynchronous read
  2531. reader.readAsText(fileToLoad);
  2532. }
  2533. else {
  2534. reader.readAsArrayBuffer(fileToLoad);
  2535. }
  2536. };
  2537. // Misc.
  2538. Tools.Clamp = function (value, min, max) {
  2539. if (min === void 0) { min = 0; }
  2540. if (max === void 0) { max = 1; }
  2541. return Math.min(max, Math.max(min, value));
  2542. };
  2543. // Returns -1 when value is a negative number and
  2544. // +1 when value is a positive number.
  2545. Tools.Sign = function (value) {
  2546. value = +value; // convert to a number
  2547. if (value === 0 || isNaN(value))
  2548. return value;
  2549. return value > 0 ? 1 : -1;
  2550. };
  2551. Tools.Format = function (value, decimals) {
  2552. if (decimals === void 0) { decimals = 2; }
  2553. return value.toFixed(decimals);
  2554. };
  2555. Tools.CheckExtends = function (v, min, max) {
  2556. if (v.x < min.x)
  2557. min.x = v.x;
  2558. if (v.y < min.y)
  2559. min.y = v.y;
  2560. if (v.z < min.z)
  2561. min.z = v.z;
  2562. if (v.x > max.x)
  2563. max.x = v.x;
  2564. if (v.y > max.y)
  2565. max.y = v.y;
  2566. if (v.z > max.z)
  2567. max.z = v.z;
  2568. };
  2569. Tools.WithinEpsilon = function (a, b, epsilon) {
  2570. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2571. var num = a - b;
  2572. return -epsilon <= num && num <= epsilon;
  2573. };
  2574. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2575. for (var prop in source) {
  2576. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2577. continue;
  2578. }
  2579. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2580. continue;
  2581. }
  2582. var sourceValue = source[prop];
  2583. var typeOfSourceValue = typeof sourceValue;
  2584. if (typeOfSourceValue == "function") {
  2585. continue;
  2586. }
  2587. if (typeOfSourceValue == "object") {
  2588. if (sourceValue instanceof Array) {
  2589. destination[prop] = [];
  2590. if (sourceValue.length > 0) {
  2591. if (typeof sourceValue[0] == "object") {
  2592. for (var index = 0; index < sourceValue.length; index++) {
  2593. var clonedValue = cloneValue(sourceValue[index], destination);
  2594. if (destination[prop].indexOf(clonedValue) === -1) {
  2595. destination[prop].push(clonedValue);
  2596. }
  2597. }
  2598. }
  2599. else {
  2600. destination[prop] = sourceValue.slice(0);
  2601. }
  2602. }
  2603. }
  2604. else {
  2605. destination[prop] = cloneValue(sourceValue, destination);
  2606. }
  2607. }
  2608. else {
  2609. destination[prop] = sourceValue;
  2610. }
  2611. }
  2612. };
  2613. Tools.IsEmpty = function (obj) {
  2614. for (var i in obj) {
  2615. return false;
  2616. }
  2617. return true;
  2618. };
  2619. Tools.RegisterTopRootEvents = function (events) {
  2620. for (var index = 0; index < events.length; index++) {
  2621. var event = events[index];
  2622. window.addEventListener(event.name, event.handler, false);
  2623. try {
  2624. if (window.parent) {
  2625. window.parent.addEventListener(event.name, event.handler, false);
  2626. }
  2627. }
  2628. catch (e) {
  2629. }
  2630. }
  2631. };
  2632. Tools.UnregisterTopRootEvents = function (events) {
  2633. for (var index = 0; index < events.length; index++) {
  2634. var event = events[index];
  2635. window.removeEventListener(event.name, event.handler);
  2636. try {
  2637. if (window.parent) {
  2638. window.parent.removeEventListener(event.name, event.handler);
  2639. }
  2640. }
  2641. catch (e) {
  2642. }
  2643. }
  2644. };
  2645. Tools.CreateScreenshot = function (engine, camera, size) {
  2646. var width;
  2647. var height;
  2648. var scene = camera.getScene();
  2649. var previousCamera = null;
  2650. if (scene.activeCamera !== camera) {
  2651. previousCamera = scene.activeCamera;
  2652. scene.activeCamera = camera;
  2653. }
  2654. //If a precision value is specified
  2655. if (size.precision) {
  2656. width = Math.round(engine.getRenderWidth() * size.precision);
  2657. height = Math.round(width / engine.getAspectRatio(camera));
  2658. size = { width: width, height: height };
  2659. }
  2660. else if (size.width && size.height) {
  2661. width = size.width;
  2662. height = size.height;
  2663. }
  2664. else if (size.width && !size.height) {
  2665. width = size.width;
  2666. height = Math.round(width / engine.getAspectRatio(camera));
  2667. size = { width: width, height: height };
  2668. }
  2669. else if (size.height && !size.width) {
  2670. height = size.height;
  2671. width = Math.round(height * engine.getAspectRatio(camera));
  2672. size = { width: width, height: height };
  2673. }
  2674. else if (!isNaN(size)) {
  2675. height = size;
  2676. width = size;
  2677. }
  2678. else {
  2679. Tools.Error("Invalid 'size' parameter !");
  2680. return;
  2681. }
  2682. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2683. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2684. texture.renderList = scene.meshes;
  2685. texture.onAfterRender = function () {
  2686. // Read the contents of the framebuffer
  2687. var numberOfChannelsByLine = width * 4;
  2688. var halfHeight = height / 2;
  2689. //Reading datas from WebGL
  2690. var data = engine.readPixels(0, 0, width, height);
  2691. for (var i = 0; i < halfHeight; i++) {
  2692. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2693. var currentCell = j + i * numberOfChannelsByLine;
  2694. var targetLine = height - i - 1;
  2695. var targetCell = j + targetLine * numberOfChannelsByLine;
  2696. var temp = data[currentCell];
  2697. data[currentCell] = data[targetCell];
  2698. data[targetCell] = temp;
  2699. }
  2700. }
  2701. // Create a 2D canvas to store the result
  2702. if (!screenshotCanvas) {
  2703. screenshotCanvas = document.createElement('canvas');
  2704. }
  2705. screenshotCanvas.width = width;
  2706. screenshotCanvas.height = height;
  2707. var context = screenshotCanvas.getContext('2d');
  2708. // Copy the pixels to a 2D canvas
  2709. var imageData = context.createImageData(width, height);
  2710. imageData.data.set(data);
  2711. context.putImageData(imageData, 0, 0);
  2712. var base64Image = screenshotCanvas.toDataURL();
  2713. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2714. if (("download" in document.createElement("a"))) {
  2715. var a = window.document.createElement("a");
  2716. a.href = base64Image;
  2717. var date = new Date();
  2718. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2719. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2720. window.document.body.appendChild(a);
  2721. a.addEventListener("click", function () {
  2722. a.parentElement.removeChild(a);
  2723. });
  2724. a.click();
  2725. }
  2726. else {
  2727. var newWindow = window.open("");
  2728. var img = newWindow.document.createElement("img");
  2729. img.src = base64Image;
  2730. newWindow.document.body.appendChild(img);
  2731. }
  2732. };
  2733. texture.render(true);
  2734. texture.dispose();
  2735. if (previousCamera) {
  2736. scene.activeCamera = previousCamera;
  2737. }
  2738. };
  2739. // XHR response validator for local file scenario
  2740. Tools.ValidateXHRData = function (xhr, dataType) {
  2741. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2742. if (dataType === void 0) { dataType = 7; }
  2743. try {
  2744. if (dataType & 1) {
  2745. if (xhr.responseText && xhr.responseText.length > 0) {
  2746. return true;
  2747. }
  2748. else if (dataType === 1) {
  2749. return false;
  2750. }
  2751. }
  2752. if (dataType & 2) {
  2753. // Check header width and height since there is no "TGA" magic number
  2754. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2755. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2756. return true;
  2757. }
  2758. else if (dataType === 2) {
  2759. return false;
  2760. }
  2761. }
  2762. if (dataType & 4) {
  2763. // Check for the "DDS" magic number
  2764. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2765. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2766. return true;
  2767. }
  2768. else {
  2769. return false;
  2770. }
  2771. }
  2772. }
  2773. catch (e) {
  2774. }
  2775. return false;
  2776. };
  2777. Object.defineProperty(Tools, "NoneLogLevel", {
  2778. get: function () {
  2779. return Tools._NoneLogLevel;
  2780. },
  2781. enumerable: true,
  2782. configurable: true
  2783. });
  2784. Object.defineProperty(Tools, "MessageLogLevel", {
  2785. get: function () {
  2786. return Tools._MessageLogLevel;
  2787. },
  2788. enumerable: true,
  2789. configurable: true
  2790. });
  2791. Object.defineProperty(Tools, "WarningLogLevel", {
  2792. get: function () {
  2793. return Tools._WarningLogLevel;
  2794. },
  2795. enumerable: true,
  2796. configurable: true
  2797. });
  2798. Object.defineProperty(Tools, "ErrorLogLevel", {
  2799. get: function () {
  2800. return Tools._ErrorLogLevel;
  2801. },
  2802. enumerable: true,
  2803. configurable: true
  2804. });
  2805. Object.defineProperty(Tools, "AllLogLevel", {
  2806. get: function () {
  2807. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2808. },
  2809. enumerable: true,
  2810. configurable: true
  2811. });
  2812. Tools._AddLogEntry = function (entry) {
  2813. Tools._LogCache = entry + Tools._LogCache;
  2814. if (Tools.OnNewCacheEntry) {
  2815. Tools.OnNewCacheEntry(entry);
  2816. }
  2817. };
  2818. Tools._FormatMessage = function (message) {
  2819. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2820. var date = new Date();
  2821. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2822. };
  2823. Tools._LogDisabled = function (message) {
  2824. // nothing to do
  2825. };
  2826. Tools._LogEnabled = function (message) {
  2827. var formattedMessage = Tools._FormatMessage(message);
  2828. console.log("BJS - " + formattedMessage);
  2829. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2830. Tools._AddLogEntry(entry);
  2831. };
  2832. Tools._WarnDisabled = function (message) {
  2833. // nothing to do
  2834. };
  2835. Tools._WarnEnabled = function (message) {
  2836. var formattedMessage = Tools._FormatMessage(message);
  2837. console.warn("BJS - " + formattedMessage);
  2838. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2839. Tools._AddLogEntry(entry);
  2840. };
  2841. Tools._ErrorDisabled = function (message) {
  2842. // nothing to do
  2843. };
  2844. Tools._ErrorEnabled = function (message) {
  2845. var formattedMessage = Tools._FormatMessage(message);
  2846. console.error("BJS - " + formattedMessage);
  2847. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2848. Tools._AddLogEntry(entry);
  2849. };
  2850. Object.defineProperty(Tools, "LogCache", {
  2851. get: function () {
  2852. return Tools._LogCache;
  2853. },
  2854. enumerable: true,
  2855. configurable: true
  2856. });
  2857. Object.defineProperty(Tools, "LogLevels", {
  2858. set: function (level) {
  2859. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2860. Tools.Log = Tools._LogEnabled;
  2861. }
  2862. else {
  2863. Tools.Log = Tools._LogDisabled;
  2864. }
  2865. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2866. Tools.Warn = Tools._WarnEnabled;
  2867. }
  2868. else {
  2869. Tools.Warn = Tools._WarnDisabled;
  2870. }
  2871. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2872. Tools.Error = Tools._ErrorEnabled;
  2873. }
  2874. else {
  2875. Tools.Error = Tools._ErrorDisabled;
  2876. }
  2877. },
  2878. enumerable: true,
  2879. configurable: true
  2880. });
  2881. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2882. get: function () {
  2883. return Tools._PerformanceNoneLogLevel;
  2884. },
  2885. enumerable: true,
  2886. configurable: true
  2887. });
  2888. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2889. get: function () {
  2890. return Tools._PerformanceUserMarkLogLevel;
  2891. },
  2892. enumerable: true,
  2893. configurable: true
  2894. });
  2895. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2896. get: function () {
  2897. return Tools._PerformanceConsoleLogLevel;
  2898. },
  2899. enumerable: true,
  2900. configurable: true
  2901. });
  2902. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2903. set: function (level) {
  2904. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2905. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2906. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2907. return;
  2908. }
  2909. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2910. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2911. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2912. return;
  2913. }
  2914. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2915. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2916. },
  2917. enumerable: true,
  2918. configurable: true
  2919. });
  2920. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2921. };
  2922. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2923. };
  2924. Tools._StartUserMark = function (counterName, condition) {
  2925. if (condition === void 0) { condition = true; }
  2926. if (!condition || !Tools._performance.mark) {
  2927. return;
  2928. }
  2929. Tools._performance.mark(counterName + "-Begin");
  2930. };
  2931. Tools._EndUserMark = function (counterName, condition) {
  2932. if (condition === void 0) { condition = true; }
  2933. if (!condition || !Tools._performance.mark) {
  2934. return;
  2935. }
  2936. Tools._performance.mark(counterName + "-End");
  2937. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2938. };
  2939. Tools._StartPerformanceConsole = function (counterName, condition) {
  2940. if (condition === void 0) { condition = true; }
  2941. if (!condition) {
  2942. return;
  2943. }
  2944. Tools._StartUserMark(counterName, condition);
  2945. if (console.time) {
  2946. console.time(counterName);
  2947. }
  2948. };
  2949. Tools._EndPerformanceConsole = function (counterName, condition) {
  2950. if (condition === void 0) { condition = true; }
  2951. if (!condition) {
  2952. return;
  2953. }
  2954. Tools._EndUserMark(counterName, condition);
  2955. if (console.time) {
  2956. console.timeEnd(counterName);
  2957. }
  2958. };
  2959. Object.defineProperty(Tools, "Now", {
  2960. get: function () {
  2961. if (window.performance && window.performance.now) {
  2962. return window.performance.now();
  2963. }
  2964. return new Date().getTime();
  2965. },
  2966. enumerable: true,
  2967. configurable: true
  2968. });
  2969. // Deprecated
  2970. Tools.GetFps = function () {
  2971. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2972. return 0;
  2973. };
  2974. Tools.BaseUrl = "";
  2975. Tools.GetExponantOfTwo = function (value, max) {
  2976. var count = 1;
  2977. do {
  2978. count *= 2;
  2979. } while (count < value);
  2980. if (count > max)
  2981. count = max;
  2982. return count;
  2983. };
  2984. // Logs
  2985. Tools._NoneLogLevel = 0;
  2986. Tools._MessageLogLevel = 1;
  2987. Tools._WarningLogLevel = 2;
  2988. Tools._ErrorLogLevel = 4;
  2989. Tools._LogCache = "";
  2990. Tools.Log = Tools._LogEnabled;
  2991. Tools.Warn = Tools._WarnEnabled;
  2992. Tools.Error = Tools._ErrorEnabled;
  2993. // Performances
  2994. Tools._PerformanceNoneLogLevel = 0;
  2995. Tools._PerformanceUserMarkLogLevel = 1;
  2996. Tools._PerformanceConsoleLogLevel = 2;
  2997. Tools._performance = window.performance;
  2998. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2999. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3000. return Tools;
  3001. })();
  3002. BABYLON.Tools = Tools;
  3003. /**
  3004. * An implementation of a loop for asynchronous functions.
  3005. */
  3006. var AsyncLoop = (function () {
  3007. /**
  3008. * Constroctor.
  3009. * @param iterations the number of iterations.
  3010. * @param _fn the function to run each iteration
  3011. * @param _successCallback the callback that will be called upon succesful execution
  3012. * @param offset starting offset.
  3013. */
  3014. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3015. if (offset === void 0) { offset = 0; }
  3016. this.iterations = iterations;
  3017. this._fn = _fn;
  3018. this._successCallback = _successCallback;
  3019. this.index = offset - 1;
  3020. this._done = false;
  3021. }
  3022. /**
  3023. * Execute the next iteration. Must be called after the last iteration was finished.
  3024. */
  3025. AsyncLoop.prototype.executeNext = function () {
  3026. if (!this._done) {
  3027. if (this.index + 1 < this.iterations) {
  3028. ++this.index;
  3029. this._fn(this);
  3030. }
  3031. else {
  3032. this.breakLoop();
  3033. }
  3034. }
  3035. };
  3036. /**
  3037. * Break the loop and run the success callback.
  3038. */
  3039. AsyncLoop.prototype.breakLoop = function () {
  3040. this._done = true;
  3041. this._successCallback();
  3042. };
  3043. /**
  3044. * Helper function
  3045. */
  3046. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3047. if (offset === void 0) { offset = 0; }
  3048. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3049. loop.executeNext();
  3050. return loop;
  3051. };
  3052. /**
  3053. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3054. * @param iterations total number of iterations
  3055. * @param syncedIterations number of synchronous iterations in each async iteration.
  3056. * @param fn the function to call each iteration.
  3057. * @param callback a success call back that will be called when iterating stops.
  3058. * @param breakFunction a break condition (optional)
  3059. * @param timeout timeout settings for the setTimeout function. default - 0.
  3060. * @constructor
  3061. */
  3062. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3063. if (timeout === void 0) { timeout = 0; }
  3064. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3065. if (breakFunction && breakFunction())
  3066. loop.breakLoop();
  3067. else {
  3068. setTimeout(function () {
  3069. for (var i = 0; i < syncedIterations; ++i) {
  3070. var iteration = (loop.index * syncedIterations) + i;
  3071. if (iteration >= iterations)
  3072. break;
  3073. fn(iteration);
  3074. if (breakFunction && breakFunction()) {
  3075. loop.breakLoop();
  3076. break;
  3077. }
  3078. }
  3079. loop.executeNext();
  3080. }, timeout);
  3081. }
  3082. }, callback);
  3083. };
  3084. return AsyncLoop;
  3085. })();
  3086. BABYLON.AsyncLoop = AsyncLoop;
  3087. })(BABYLON || (BABYLON = {}));
  3088. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3089. (function (BABYLON) {
  3090. var _DepthCullingState = (function () {
  3091. function _DepthCullingState() {
  3092. this._isDepthTestDirty = false;
  3093. this._isDepthMaskDirty = false;
  3094. this._isDepthFuncDirty = false;
  3095. this._isCullFaceDirty = false;
  3096. this._isCullDirty = false;
  3097. }
  3098. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3099. get: function () {
  3100. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3101. },
  3102. enumerable: true,
  3103. configurable: true
  3104. });
  3105. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3106. get: function () {
  3107. return this._cullFace;
  3108. },
  3109. set: function (value) {
  3110. if (this._cullFace === value) {
  3111. return;
  3112. }
  3113. this._cullFace = value;
  3114. this._isCullFaceDirty = true;
  3115. },
  3116. enumerable: true,
  3117. configurable: true
  3118. });
  3119. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3120. get: function () {
  3121. return this._cull;
  3122. },
  3123. set: function (value) {
  3124. if (this._cull === value) {
  3125. return;
  3126. }
  3127. this._cull = value;
  3128. this._isCullDirty = true;
  3129. },
  3130. enumerable: true,
  3131. configurable: true
  3132. });
  3133. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3134. get: function () {
  3135. return this._depthFunc;
  3136. },
  3137. set: function (value) {
  3138. if (this._depthFunc === value) {
  3139. return;
  3140. }
  3141. this._depthFunc = value;
  3142. this._isDepthFuncDirty = true;
  3143. },
  3144. enumerable: true,
  3145. configurable: true
  3146. });
  3147. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3148. get: function () {
  3149. return this._depthMask;
  3150. },
  3151. set: function (value) {
  3152. if (this._depthMask === value) {
  3153. return;
  3154. }
  3155. this._depthMask = value;
  3156. this._isDepthMaskDirty = true;
  3157. },
  3158. enumerable: true,
  3159. configurable: true
  3160. });
  3161. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3162. get: function () {
  3163. return this._depthTest;
  3164. },
  3165. set: function (value) {
  3166. if (this._depthTest === value) {
  3167. return;
  3168. }
  3169. this._depthTest = value;
  3170. this._isDepthTestDirty = true;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. _DepthCullingState.prototype.reset = function () {
  3176. this._depthMask = true;
  3177. this._depthTest = true;
  3178. this._depthFunc = null;
  3179. this._cull = null;
  3180. this._cullFace = null;
  3181. this._isDepthTestDirty = true;
  3182. this._isDepthMaskDirty = true;
  3183. this._isDepthFuncDirty = false;
  3184. this._isCullFaceDirty = false;
  3185. this._isCullDirty = false;
  3186. };
  3187. _DepthCullingState.prototype.apply = function (gl) {
  3188. if (!this.isDirty) {
  3189. return;
  3190. }
  3191. // Cull
  3192. if (this._isCullDirty) {
  3193. if (this.cull) {
  3194. gl.enable(gl.CULL_FACE);
  3195. }
  3196. else {
  3197. gl.disable(gl.CULL_FACE);
  3198. }
  3199. this._isCullDirty = false;
  3200. }
  3201. // Cull face
  3202. if (this._isCullFaceDirty) {
  3203. gl.cullFace(this.cullFace);
  3204. this._isCullFaceDirty = false;
  3205. }
  3206. // Depth mask
  3207. if (this._isDepthMaskDirty) {
  3208. gl.depthMask(this.depthMask);
  3209. this._isDepthMaskDirty = false;
  3210. }
  3211. // Depth test
  3212. if (this._isDepthTestDirty) {
  3213. if (this.depthTest) {
  3214. gl.enable(gl.DEPTH_TEST);
  3215. }
  3216. else {
  3217. gl.disable(gl.DEPTH_TEST);
  3218. }
  3219. this._isDepthTestDirty = false;
  3220. }
  3221. // Depth func
  3222. if (this._isDepthFuncDirty) {
  3223. gl.depthFunc(this.depthFunc);
  3224. this._isDepthFuncDirty = false;
  3225. }
  3226. };
  3227. return _DepthCullingState;
  3228. })();
  3229. BABYLON._DepthCullingState = _DepthCullingState;
  3230. var _AlphaState = (function () {
  3231. function _AlphaState() {
  3232. this._isAlphaBlendDirty = false;
  3233. this._isBlendFunctionParametersDirty = false;
  3234. this._alphaBlend = false;
  3235. this._blendFunctionParameters = new Array(4);
  3236. }
  3237. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3238. get: function () {
  3239. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3240. },
  3241. enumerable: true,
  3242. configurable: true
  3243. });
  3244. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3245. get: function () {
  3246. return this._alphaBlend;
  3247. },
  3248. set: function (value) {
  3249. if (this._alphaBlend === value) {
  3250. return;
  3251. }
  3252. this._alphaBlend = value;
  3253. this._isAlphaBlendDirty = true;
  3254. },
  3255. enumerable: true,
  3256. configurable: true
  3257. });
  3258. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3259. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3260. return;
  3261. }
  3262. this._blendFunctionParameters[0] = value0;
  3263. this._blendFunctionParameters[1] = value1;
  3264. this._blendFunctionParameters[2] = value2;
  3265. this._blendFunctionParameters[3] = value3;
  3266. this._isBlendFunctionParametersDirty = true;
  3267. };
  3268. _AlphaState.prototype.reset = function () {
  3269. this._alphaBlend = false;
  3270. this._blendFunctionParameters[0] = null;
  3271. this._blendFunctionParameters[1] = null;
  3272. this._blendFunctionParameters[2] = null;
  3273. this._blendFunctionParameters[3] = null;
  3274. this._isAlphaBlendDirty = true;
  3275. this._isBlendFunctionParametersDirty = false;
  3276. };
  3277. _AlphaState.prototype.apply = function (gl) {
  3278. if (!this.isDirty) {
  3279. return;
  3280. }
  3281. // Alpha blend
  3282. if (this._isAlphaBlendDirty) {
  3283. if (this._alphaBlend) {
  3284. gl.enable(gl.BLEND);
  3285. }
  3286. else {
  3287. gl.disable(gl.BLEND);
  3288. }
  3289. this._isAlphaBlendDirty = false;
  3290. }
  3291. // Alpha function
  3292. if (this._isBlendFunctionParametersDirty) {
  3293. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3294. this._isBlendFunctionParametersDirty = false;
  3295. }
  3296. };
  3297. return _AlphaState;
  3298. })();
  3299. BABYLON._AlphaState = _AlphaState;
  3300. var compileShader = function (gl, source, type, defines) {
  3301. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3302. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3303. gl.compileShader(shader);
  3304. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3305. throw new Error(gl.getShaderInfoLog(shader));
  3306. }
  3307. return shader;
  3308. };
  3309. var getWebGLTextureType = function (gl, type) {
  3310. var textureType = gl.UNSIGNED_BYTE;
  3311. if (type === Engine.TEXTURETYPE_FLOAT)
  3312. textureType = gl.FLOAT;
  3313. return textureType;
  3314. };
  3315. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3316. var magFilter = gl.NEAREST;
  3317. var minFilter = gl.NEAREST;
  3318. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3319. magFilter = gl.LINEAR;
  3320. if (generateMipMaps) {
  3321. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3322. }
  3323. else {
  3324. minFilter = gl.LINEAR;
  3325. }
  3326. }
  3327. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3328. magFilter = gl.LINEAR;
  3329. if (generateMipMaps) {
  3330. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3331. }
  3332. else {
  3333. minFilter = gl.LINEAR;
  3334. }
  3335. }
  3336. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3337. magFilter = gl.NEAREST;
  3338. if (generateMipMaps) {
  3339. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3340. }
  3341. else {
  3342. minFilter = gl.NEAREST;
  3343. }
  3344. }
  3345. return {
  3346. min: minFilter,
  3347. mag: magFilter
  3348. };
  3349. };
  3350. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3351. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3352. var engine = scene.getEngine();
  3353. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3354. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3355. gl.bindTexture(gl.TEXTURE_2D, texture);
  3356. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3357. processFunction(potWidth, potHeight);
  3358. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3359. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3360. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3361. if (!noMipmap && !isCompressed) {
  3362. gl.generateMipmap(gl.TEXTURE_2D);
  3363. }
  3364. gl.bindTexture(gl.TEXTURE_2D, null);
  3365. engine._activeTexturesCache = [];
  3366. texture._baseWidth = width;
  3367. texture._baseHeight = height;
  3368. texture._width = potWidth;
  3369. texture._height = potHeight;
  3370. texture.isReady = true;
  3371. texture.samplingMode = samplingMode;
  3372. scene._removePendingData(texture);
  3373. };
  3374. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3375. var onload = function () {
  3376. loadedImages[index] = img;
  3377. loadedImages._internalCount++;
  3378. scene._removePendingData(img);
  3379. if (loadedImages._internalCount === 6) {
  3380. onfinish(loadedImages);
  3381. }
  3382. };
  3383. var onerror = function () {
  3384. scene._removePendingData(img);
  3385. };
  3386. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3387. scene._addPendingData(img);
  3388. };
  3389. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3390. var loadedImages = [];
  3391. loadedImages._internalCount = 0;
  3392. for (var index = 0; index < 6; index++) {
  3393. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3394. }
  3395. };
  3396. var EngineCapabilities = (function () {
  3397. function EngineCapabilities() {
  3398. }
  3399. return EngineCapabilities;
  3400. })();
  3401. BABYLON.EngineCapabilities = EngineCapabilities;
  3402. /**
  3403. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3404. */
  3405. var Engine = (function () {
  3406. /**
  3407. * @constructor
  3408. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3409. * @param {boolean} [antialias] - enable antialias
  3410. * @param options - further options to be sent to the getContext function
  3411. */
  3412. function Engine(canvas, antialias, options) {
  3413. var _this = this;
  3414. // Public members
  3415. this.isFullscreen = false;
  3416. this.isPointerLock = false;
  3417. this.cullBackFaces = true;
  3418. this.renderEvenInBackground = true;
  3419. this.scenes = new Array();
  3420. this._windowIsBackground = false;
  3421. this._loadingDivBackgroundColor = "black";
  3422. this._drawCalls = 0;
  3423. this._renderingQueueLaunched = false;
  3424. this._activeRenderLoops = [];
  3425. // FPS
  3426. this.fpsRange = 60;
  3427. this.previousFramesDuration = [];
  3428. this.fps = 60;
  3429. this.deltaTime = 0;
  3430. // States
  3431. this._depthCullingState = new _DepthCullingState();
  3432. this._alphaState = new _AlphaState();
  3433. this._alphaMode = Engine.ALPHA_DISABLE;
  3434. // Cache
  3435. this._loadedTexturesCache = new Array();
  3436. this._activeTexturesCache = new Array();
  3437. this._compiledEffects = {};
  3438. this._uintIndicesCurrentlySet = false;
  3439. this._renderingCanvas = canvas;
  3440. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3441. options = options || {};
  3442. options.antialias = antialias;
  3443. try {
  3444. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3445. }
  3446. catch (e) {
  3447. throw new Error("WebGL not supported");
  3448. }
  3449. if (!this._gl) {
  3450. throw new Error("WebGL not supported");
  3451. }
  3452. this._onBlur = function () {
  3453. _this._windowIsBackground = true;
  3454. };
  3455. this._onFocus = function () {
  3456. _this._windowIsBackground = false;
  3457. };
  3458. window.addEventListener("blur", this._onBlur);
  3459. window.addEventListener("focus", this._onFocus);
  3460. // Textures
  3461. this._workingCanvas = document.createElement("canvas");
  3462. this._workingContext = this._workingCanvas.getContext("2d");
  3463. // Viewport
  3464. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3465. this.resize();
  3466. // Caps
  3467. this._caps = new EngineCapabilities();
  3468. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3469. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3470. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3471. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3472. // Infos
  3473. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3474. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3475. if (rendererInfo != null) {
  3476. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3477. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3478. }
  3479. if (!this._glVendor) {
  3480. this._glVendor = "Unknown vendor";
  3481. }
  3482. if (!this._glRenderer) {
  3483. this._glRenderer = "Unknown renderer";
  3484. }
  3485. // Extensions
  3486. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3487. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3488. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3489. 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');
  3490. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3491. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3492. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3493. // Depth buffer
  3494. this.setDepthBuffer(true);
  3495. this.setDepthFunctionToLessOrEqual();
  3496. this.setDepthWrite(true);
  3497. // Fullscreen
  3498. this._onFullscreenChange = function () {
  3499. if (document.fullscreen !== undefined) {
  3500. _this.isFullscreen = document.fullscreen;
  3501. }
  3502. else if (document.mozFullScreen !== undefined) {
  3503. _this.isFullscreen = document.mozFullScreen;
  3504. }
  3505. else if (document.webkitIsFullScreen !== undefined) {
  3506. _this.isFullscreen = document.webkitIsFullScreen;
  3507. }
  3508. else if (document.msIsFullScreen !== undefined) {
  3509. _this.isFullscreen = document.msIsFullScreen;
  3510. }
  3511. // Pointer lock
  3512. if (_this.isFullscreen && _this._pointerLockRequested) {
  3513. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3514. if (canvas.requestPointerLock) {
  3515. canvas.requestPointerLock();
  3516. }
  3517. }
  3518. };
  3519. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3520. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3521. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3522. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3523. // Pointer lock
  3524. this._onPointerLockChange = function () {
  3525. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3526. };
  3527. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3528. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3529. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3530. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3531. if (!Engine.audioEngine) {
  3532. Engine.audioEngine = new BABYLON.AudioEngine();
  3533. }
  3534. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3535. }
  3536. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3537. get: function () {
  3538. return Engine._ALPHA_DISABLE;
  3539. },
  3540. enumerable: true,
  3541. configurable: true
  3542. });
  3543. Object.defineProperty(Engine, "ALPHA_ADD", {
  3544. get: function () {
  3545. return Engine._ALPHA_ADD;
  3546. },
  3547. enumerable: true,
  3548. configurable: true
  3549. });
  3550. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3551. get: function () {
  3552. return Engine._ALPHA_COMBINE;
  3553. },
  3554. enumerable: true,
  3555. configurable: true
  3556. });
  3557. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3558. get: function () {
  3559. return Engine._DELAYLOADSTATE_NONE;
  3560. },
  3561. enumerable: true,
  3562. configurable: true
  3563. });
  3564. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3565. get: function () {
  3566. return Engine._DELAYLOADSTATE_LOADED;
  3567. },
  3568. enumerable: true,
  3569. configurable: true
  3570. });
  3571. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3572. get: function () {
  3573. return Engine._DELAYLOADSTATE_LOADING;
  3574. },
  3575. enumerable: true,
  3576. configurable: true
  3577. });
  3578. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3579. get: function () {
  3580. return Engine._DELAYLOADSTATE_NOTLOADED;
  3581. },
  3582. enumerable: true,
  3583. configurable: true
  3584. });
  3585. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3586. get: function () {
  3587. return Engine._TEXTUREFORMAT_ALPHA;
  3588. },
  3589. enumerable: true,
  3590. configurable: true
  3591. });
  3592. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3593. get: function () {
  3594. return Engine._TEXTUREFORMAT_LUMINANCE;
  3595. },
  3596. enumerable: true,
  3597. configurable: true
  3598. });
  3599. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3600. get: function () {
  3601. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3602. },
  3603. enumerable: true,
  3604. configurable: true
  3605. });
  3606. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3607. get: function () {
  3608. return Engine._TEXTUREFORMAT_RGB;
  3609. },
  3610. enumerable: true,
  3611. configurable: true
  3612. });
  3613. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3614. get: function () {
  3615. return Engine._TEXTUREFORMAT_RGBA;
  3616. },
  3617. enumerable: true,
  3618. configurable: true
  3619. });
  3620. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3621. get: function () {
  3622. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3623. },
  3624. enumerable: true,
  3625. configurable: true
  3626. });
  3627. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3628. get: function () {
  3629. return Engine._TEXTURETYPE_FLOAT;
  3630. },
  3631. enumerable: true,
  3632. configurable: true
  3633. });
  3634. Object.defineProperty(Engine, "Version", {
  3635. get: function () {
  3636. return "2.0.0";
  3637. },
  3638. enumerable: true,
  3639. configurable: true
  3640. });
  3641. Engine.prototype.getGlInfo = function () {
  3642. return {
  3643. vendor: this._glVendor,
  3644. renderer: this._glRenderer,
  3645. version: this._glVersion
  3646. };
  3647. };
  3648. Engine.prototype.getAudioEngine = function () {
  3649. return Engine.audioEngine;
  3650. };
  3651. Engine.prototype.getAspectRatio = function (camera) {
  3652. var viewport = camera.viewport;
  3653. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3654. };
  3655. Engine.prototype.getRenderWidth = function () {
  3656. if (this._currentRenderTarget) {
  3657. return this._currentRenderTarget._width;
  3658. }
  3659. return this._renderingCanvas.width;
  3660. };
  3661. Engine.prototype.getRenderHeight = function () {
  3662. if (this._currentRenderTarget) {
  3663. return this._currentRenderTarget._height;
  3664. }
  3665. return this._renderingCanvas.height;
  3666. };
  3667. Engine.prototype.getRenderingCanvas = function () {
  3668. return this._renderingCanvas;
  3669. };
  3670. Engine.prototype.getRenderingCanvasClientRect = function () {
  3671. return this._renderingCanvas.getBoundingClientRect();
  3672. };
  3673. Engine.prototype.setHardwareScalingLevel = function (level) {
  3674. this._hardwareScalingLevel = level;
  3675. this.resize();
  3676. };
  3677. Engine.prototype.getHardwareScalingLevel = function () {
  3678. return this._hardwareScalingLevel;
  3679. };
  3680. Engine.prototype.getLoadedTexturesCache = function () {
  3681. return this._loadedTexturesCache;
  3682. };
  3683. Engine.prototype.getCaps = function () {
  3684. return this._caps;
  3685. };
  3686. Object.defineProperty(Engine.prototype, "drawCalls", {
  3687. get: function () {
  3688. return this._drawCalls;
  3689. },
  3690. enumerable: true,
  3691. configurable: true
  3692. });
  3693. // Methods
  3694. Engine.prototype.resetDrawCalls = function () {
  3695. this._drawCalls = 0;
  3696. };
  3697. Engine.prototype.setDepthFunctionToGreater = function () {
  3698. this._depthCullingState.depthFunc = this._gl.GREATER;
  3699. };
  3700. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3701. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3702. };
  3703. Engine.prototype.setDepthFunctionToLess = function () {
  3704. this._depthCullingState.depthFunc = this._gl.LESS;
  3705. };
  3706. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3707. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3708. };
  3709. /**
  3710. * stop executing a render loop function and remove it from the execution array
  3711. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3712. */
  3713. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3714. if (!renderFunction) {
  3715. this._activeRenderLoops = [];
  3716. return;
  3717. }
  3718. var index = this._activeRenderLoops.indexOf(renderFunction);
  3719. if (index >= 0) {
  3720. this._activeRenderLoops.splice(index, 1);
  3721. }
  3722. };
  3723. Engine.prototype._renderLoop = function () {
  3724. var _this = this;
  3725. var shouldRender = true;
  3726. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3727. shouldRender = false;
  3728. }
  3729. if (shouldRender) {
  3730. // Start new frame
  3731. this.beginFrame();
  3732. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3733. var renderFunction = this._activeRenderLoops[index];
  3734. renderFunction();
  3735. }
  3736. // Present
  3737. this.endFrame();
  3738. }
  3739. if (this._activeRenderLoops.length > 0) {
  3740. // Register new frame
  3741. BABYLON.Tools.QueueNewFrame(function () {
  3742. _this._renderLoop();
  3743. });
  3744. }
  3745. else {
  3746. this._renderingQueueLaunched = false;
  3747. }
  3748. };
  3749. /**
  3750. * Register and execute a render loop. The engine can have more than one render function.
  3751. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3752. * @example
  3753. * engine.runRenderLoop(function () {
  3754. * scene.render()
  3755. * })
  3756. */
  3757. Engine.prototype.runRenderLoop = function (renderFunction) {
  3758. var _this = this;
  3759. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3760. return;
  3761. }
  3762. this._activeRenderLoops.push(renderFunction);
  3763. if (!this._renderingQueueLaunched) {
  3764. this._renderingQueueLaunched = true;
  3765. BABYLON.Tools.QueueNewFrame(function () {
  3766. _this._renderLoop();
  3767. });
  3768. }
  3769. };
  3770. /**
  3771. * Toggle full screen mode.
  3772. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3773. */
  3774. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3775. if (this.isFullscreen) {
  3776. BABYLON.Tools.ExitFullscreen();
  3777. }
  3778. else {
  3779. this._pointerLockRequested = requestPointerLock;
  3780. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3781. }
  3782. };
  3783. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3784. this.applyStates();
  3785. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3786. if (this._depthCullingState.depthMask) {
  3787. this._gl.clearDepth(1.0);
  3788. }
  3789. var mode = 0;
  3790. if (backBuffer)
  3791. mode |= this._gl.COLOR_BUFFER_BIT;
  3792. if (depthStencil && this._depthCullingState.depthMask)
  3793. mode |= this._gl.DEPTH_BUFFER_BIT;
  3794. this._gl.clear(mode);
  3795. };
  3796. /**
  3797. * Set the WebGL's viewport
  3798. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  3799. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  3800. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  3801. */
  3802. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3803. var width = requiredWidth || this._renderingCanvas.width;
  3804. var height = requiredHeight || this._renderingCanvas.height;
  3805. var x = viewport.x || 0;
  3806. var y = viewport.y || 0;
  3807. this._cachedViewport = viewport;
  3808. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3809. };
  3810. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3811. this._cachedViewport = null;
  3812. this._gl.viewport(x, y, width, height);
  3813. };
  3814. Engine.prototype.beginFrame = function () {
  3815. this._measureFps();
  3816. };
  3817. Engine.prototype.endFrame = function () {
  3818. this.flushFramebuffer();
  3819. };
  3820. /**
  3821. * resize the view according to the canvas' size.
  3822. * @example
  3823. * window.addEventListener("resize", function () {
  3824. * engine.resize();
  3825. * });
  3826. */
  3827. Engine.prototype.resize = function () {
  3828. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3829. };
  3830. /**
  3831. * force a specific size of the canvas
  3832. * @param {number} width - the new canvas' width
  3833. * @param {number} height - the new canvas' height
  3834. */
  3835. Engine.prototype.setSize = function (width, height) {
  3836. this._renderingCanvas.width = width;
  3837. this._renderingCanvas.height = height;
  3838. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3839. };
  3840. Engine.prototype.bindFramebuffer = function (texture) {
  3841. this._currentRenderTarget = texture;
  3842. var gl = this._gl;
  3843. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3844. this._gl.viewport(0, 0, texture._width, texture._height);
  3845. this.wipeCaches();
  3846. };
  3847. Engine.prototype.unBindFramebuffer = function (texture) {
  3848. this._currentRenderTarget = null;
  3849. if (texture.generateMipMaps) {
  3850. var gl = this._gl;
  3851. gl.bindTexture(gl.TEXTURE_2D, texture);
  3852. gl.generateMipmap(gl.TEXTURE_2D);
  3853. gl.bindTexture(gl.TEXTURE_2D, null);
  3854. }
  3855. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3856. };
  3857. Engine.prototype.flushFramebuffer = function () {
  3858. // this._gl.flush();
  3859. };
  3860. Engine.prototype.restoreDefaultFramebuffer = function () {
  3861. this._currentRenderTarget = null;
  3862. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3863. this.setViewport(this._cachedViewport);
  3864. this.wipeCaches();
  3865. };
  3866. // VBOs
  3867. Engine.prototype._resetVertexBufferBinding = function () {
  3868. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3869. this._cachedVertexBuffers = null;
  3870. };
  3871. Engine.prototype.createVertexBuffer = function (vertices) {
  3872. var vbo = this._gl.createBuffer();
  3873. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3874. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3875. this._resetVertexBufferBinding();
  3876. vbo.references = 1;
  3877. return vbo;
  3878. };
  3879. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3880. var vbo = this._gl.createBuffer();
  3881. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3882. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3883. this._resetVertexBufferBinding();
  3884. vbo.references = 1;
  3885. return vbo;
  3886. };
  3887. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3888. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3889. if (offset === undefined) {
  3890. offset = 0;
  3891. }
  3892. if (vertices instanceof Float32Array) {
  3893. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3894. }
  3895. else {
  3896. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3897. }
  3898. this._resetVertexBufferBinding();
  3899. };
  3900. Engine.prototype._resetIndexBufferBinding = function () {
  3901. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3902. this._cachedIndexBuffer = null;
  3903. };
  3904. Engine.prototype.createIndexBuffer = function (indices) {
  3905. var vbo = this._gl.createBuffer();
  3906. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3907. // Check for 32 bits indices
  3908. var arrayBuffer;
  3909. var need32Bits = false;
  3910. if (this._caps.uintIndices) {
  3911. for (var index = 0; index < indices.length; index++) {
  3912. if (indices[index] > 65535) {
  3913. need32Bits = true;
  3914. break;
  3915. }
  3916. }
  3917. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3918. }
  3919. else {
  3920. arrayBuffer = new Uint16Array(indices);
  3921. }
  3922. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3923. this._resetIndexBufferBinding();
  3924. vbo.references = 1;
  3925. vbo.is32Bits = need32Bits;
  3926. return vbo;
  3927. };
  3928. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3929. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3930. this._cachedVertexBuffers = vertexBuffer;
  3931. this._cachedEffectForVertexBuffers = effect;
  3932. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3933. var offset = 0;
  3934. for (var index = 0; index < vertexDeclaration.length; index++) {
  3935. var order = effect.getAttributeLocation(index);
  3936. if (order >= 0) {
  3937. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3938. }
  3939. offset += vertexDeclaration[index] * 4;
  3940. }
  3941. }
  3942. if (this._cachedIndexBuffer !== indexBuffer) {
  3943. this._cachedIndexBuffer = indexBuffer;
  3944. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3945. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3946. }
  3947. };
  3948. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3949. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3950. this._cachedVertexBuffers = vertexBuffers;
  3951. this._cachedEffectForVertexBuffers = effect;
  3952. var attributes = effect.getAttributesNames();
  3953. for (var index = 0; index < attributes.length; index++) {
  3954. var order = effect.getAttributeLocation(index);
  3955. if (order >= 0) {
  3956. var vertexBuffer = vertexBuffers[attributes[index]];
  3957. if (!vertexBuffer) {
  3958. continue;
  3959. }
  3960. var stride = vertexBuffer.getStrideSize();
  3961. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3962. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3963. }
  3964. }
  3965. }
  3966. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3967. this._cachedIndexBuffer = indexBuffer;
  3968. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3969. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3970. }
  3971. };
  3972. Engine.prototype._releaseBuffer = function (buffer) {
  3973. buffer.references--;
  3974. if (buffer.references === 0) {
  3975. this._gl.deleteBuffer(buffer);
  3976. return true;
  3977. }
  3978. return false;
  3979. };
  3980. Engine.prototype.createInstancesBuffer = function (capacity) {
  3981. var buffer = this._gl.createBuffer();
  3982. buffer.capacity = capacity;
  3983. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3984. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3985. return buffer;
  3986. };
  3987. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3988. this._gl.deleteBuffer(buffer);
  3989. };
  3990. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3991. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3992. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3993. for (var index = 0; index < 4; index++) {
  3994. var offsetLocation = offsetLocations[index];
  3995. this._gl.enableVertexAttribArray(offsetLocation);
  3996. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3997. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3998. }
  3999. };
  4000. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4001. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4002. for (var index = 0; index < 4; index++) {
  4003. var offsetLocation = offsetLocations[index];
  4004. this._gl.disableVertexAttribArray(offsetLocation);
  4005. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4006. }
  4007. };
  4008. Engine.prototype.applyStates = function () {
  4009. this._depthCullingState.apply(this._gl);
  4010. this._alphaState.apply(this._gl);
  4011. };
  4012. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4013. // Apply states
  4014. this.applyStates();
  4015. this._drawCalls++;
  4016. // Render
  4017. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4018. if (instancesCount) {
  4019. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4020. return;
  4021. }
  4022. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4023. };
  4024. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4025. // Apply states
  4026. this.applyStates();
  4027. this._drawCalls++;
  4028. if (instancesCount) {
  4029. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4030. return;
  4031. }
  4032. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4033. };
  4034. // Shaders
  4035. Engine.prototype._releaseEffect = function (effect) {
  4036. if (this._compiledEffects[effect._key]) {
  4037. delete this._compiledEffects[effect._key];
  4038. if (effect.getProgram()) {
  4039. this._gl.deleteProgram(effect.getProgram());
  4040. }
  4041. }
  4042. };
  4043. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4044. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4045. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4046. var name = vertex + "+" + fragment + "@" + defines;
  4047. if (this._compiledEffects[name]) {
  4048. return this._compiledEffects[name];
  4049. }
  4050. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4051. effect._key = name;
  4052. this._compiledEffects[name] = effect;
  4053. return effect;
  4054. };
  4055. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4056. if (uniformsNames === void 0) { uniformsNames = []; }
  4057. if (samplers === void 0) { samplers = []; }
  4058. if (defines === void 0) { defines = ""; }
  4059. return this.createEffect({
  4060. vertex: "particles",
  4061. fragmentElement: fragmentName
  4062. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4063. };
  4064. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4065. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4066. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4067. var shaderProgram = this._gl.createProgram();
  4068. this._gl.attachShader(shaderProgram, vertexShader);
  4069. this._gl.attachShader(shaderProgram, fragmentShader);
  4070. this._gl.linkProgram(shaderProgram);
  4071. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4072. if (!linked) {
  4073. var error = this._gl.getProgramInfoLog(shaderProgram);
  4074. if (error) {
  4075. throw new Error(error);
  4076. }
  4077. }
  4078. this._gl.deleteShader(vertexShader);
  4079. this._gl.deleteShader(fragmentShader);
  4080. return shaderProgram;
  4081. };
  4082. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4083. var results = [];
  4084. for (var index = 0; index < uniformsNames.length; index++) {
  4085. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4086. }
  4087. return results;
  4088. };
  4089. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4090. var results = [];
  4091. for (var index = 0; index < attributesNames.length; index++) {
  4092. try {
  4093. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4094. }
  4095. catch (e) {
  4096. results.push(-1);
  4097. }
  4098. }
  4099. return results;
  4100. };
  4101. Engine.prototype.enableEffect = function (effect) {
  4102. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4103. if (effect && effect.onBind) {
  4104. effect.onBind(effect);
  4105. }
  4106. return;
  4107. }
  4108. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4109. // Use program
  4110. this._gl.useProgram(effect.getProgram());
  4111. for (var i in this._vertexAttribArrays) {
  4112. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4113. continue;
  4114. }
  4115. this._vertexAttribArrays[i] = false;
  4116. this._gl.disableVertexAttribArray(i);
  4117. }
  4118. var attributesCount = effect.getAttributesCount();
  4119. for (var index = 0; index < attributesCount; index++) {
  4120. // Attributes
  4121. var order = effect.getAttributeLocation(index);
  4122. if (order >= 0) {
  4123. this._vertexAttribArrays[order] = true;
  4124. this._gl.enableVertexAttribArray(order);
  4125. }
  4126. }
  4127. this._currentEffect = effect;
  4128. if (effect.onBind) {
  4129. effect.onBind(effect);
  4130. }
  4131. };
  4132. Engine.prototype.setArray = function (uniform, array) {
  4133. if (!uniform)
  4134. return;
  4135. this._gl.uniform1fv(uniform, array);
  4136. };
  4137. Engine.prototype.setMatrices = function (uniform, matrices) {
  4138. if (!uniform)
  4139. return;
  4140. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4141. };
  4142. Engine.prototype.setMatrix = function (uniform, matrix) {
  4143. if (!uniform)
  4144. return;
  4145. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4146. };
  4147. Engine.prototype.setFloat = function (uniform, value) {
  4148. if (!uniform)
  4149. return;
  4150. this._gl.uniform1f(uniform, value);
  4151. };
  4152. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4153. if (!uniform)
  4154. return;
  4155. this._gl.uniform2f(uniform, x, y);
  4156. };
  4157. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4158. if (!uniform)
  4159. return;
  4160. this._gl.uniform3f(uniform, x, y, z);
  4161. };
  4162. Engine.prototype.setBool = function (uniform, bool) {
  4163. if (!uniform)
  4164. return;
  4165. this._gl.uniform1i(uniform, bool);
  4166. };
  4167. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4168. if (!uniform)
  4169. return;
  4170. this._gl.uniform4f(uniform, x, y, z, w);
  4171. };
  4172. Engine.prototype.setColor3 = function (uniform, color3) {
  4173. if (!uniform)
  4174. return;
  4175. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4176. };
  4177. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4178. if (!uniform)
  4179. return;
  4180. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4181. };
  4182. // States
  4183. Engine.prototype.setState = function (culling, force) {
  4184. // Culling
  4185. if (this._depthCullingState.cull !== culling || force) {
  4186. if (culling) {
  4187. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4188. this._depthCullingState.cull = true;
  4189. }
  4190. else {
  4191. this._depthCullingState.cull = false;
  4192. }
  4193. }
  4194. };
  4195. Engine.prototype.setDepthBuffer = function (enable) {
  4196. this._depthCullingState.depthTest = enable;
  4197. };
  4198. Engine.prototype.getDepthWrite = function () {
  4199. return this._depthCullingState.depthMask;
  4200. };
  4201. Engine.prototype.setDepthWrite = function (enable) {
  4202. this._depthCullingState.depthMask = enable;
  4203. };
  4204. Engine.prototype.setColorWrite = function (enable) {
  4205. this._gl.colorMask(enable, enable, enable, enable);
  4206. };
  4207. Engine.prototype.setAlphaMode = function (mode) {
  4208. switch (mode) {
  4209. case Engine.ALPHA_DISABLE:
  4210. this.setDepthWrite(true);
  4211. this._alphaState.alphaBlend = false;
  4212. break;
  4213. case Engine.ALPHA_COMBINE:
  4214. this.setDepthWrite(false);
  4215. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4216. this._alphaState.alphaBlend = true;
  4217. break;
  4218. case Engine.ALPHA_ADD:
  4219. this.setDepthWrite(false);
  4220. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4221. this._alphaState.alphaBlend = true;
  4222. break;
  4223. }
  4224. this._alphaMode = mode;
  4225. };
  4226. Engine.prototype.getAlphaMode = function () {
  4227. return this._alphaMode;
  4228. };
  4229. Engine.prototype.setAlphaTesting = function (enable) {
  4230. this._alphaTest = enable;
  4231. };
  4232. Engine.prototype.getAlphaTesting = function () {
  4233. return this._alphaTest;
  4234. };
  4235. // Textures
  4236. Engine.prototype.wipeCaches = function () {
  4237. this._activeTexturesCache = [];
  4238. this._currentEffect = null;
  4239. this._depthCullingState.reset();
  4240. this._alphaState.reset();
  4241. this._cachedVertexBuffers = null;
  4242. this._cachedIndexBuffer = null;
  4243. this._cachedEffectForVertexBuffers = null;
  4244. };
  4245. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4246. var gl = this._gl;
  4247. gl.bindTexture(gl.TEXTURE_2D, texture);
  4248. var magFilter = gl.NEAREST;
  4249. var minFilter = gl.NEAREST;
  4250. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4251. magFilter = gl.LINEAR;
  4252. minFilter = gl.LINEAR;
  4253. }
  4254. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4255. magFilter = gl.LINEAR;
  4256. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4257. }
  4258. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4259. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4260. gl.bindTexture(gl.TEXTURE_2D, null);
  4261. texture.samplingMode = samplingMode;
  4262. };
  4263. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4264. var _this = this;
  4265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4266. if (onLoad === void 0) { onLoad = null; }
  4267. if (onError === void 0) { onError = null; }
  4268. if (buffer === void 0) { buffer = null; }
  4269. var texture = this._gl.createTexture();
  4270. var extension;
  4271. var fromData = false;
  4272. if (url.substr(0, 5) === "data:") {
  4273. fromData = true;
  4274. }
  4275. if (!fromData)
  4276. extension = url.substr(url.length - 4, 4).toLowerCase();
  4277. else {
  4278. var oldUrl = url;
  4279. fromData = oldUrl.split(':');
  4280. url = oldUrl;
  4281. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4282. }
  4283. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4284. var isTGA = (extension === ".tga");
  4285. scene._addPendingData(texture);
  4286. texture.url = url;
  4287. texture.noMipmap = noMipmap;
  4288. texture.references = 1;
  4289. this._loadedTexturesCache.push(texture);
  4290. var onerror = function () {
  4291. scene._removePendingData(texture);
  4292. if (onError) {
  4293. onError();
  4294. }
  4295. };
  4296. if (isTGA) {
  4297. var callback = function (arrayBuffer) {
  4298. var data = new Uint8Array(arrayBuffer);
  4299. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4300. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4301. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4302. if (onLoad) {
  4303. onLoad();
  4304. }
  4305. }, samplingMode);
  4306. };
  4307. if (!(fromData instanceof Array))
  4308. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4309. callback(arrayBuffer);
  4310. }, onerror, scene.database, true);
  4311. else
  4312. callback(buffer);
  4313. }
  4314. else if (isDDS) {
  4315. callback = function (data) {
  4316. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4317. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4318. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4319. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4320. if (onLoad) {
  4321. onLoad();
  4322. }
  4323. }, samplingMode);
  4324. };
  4325. if (!(fromData instanceof Array))
  4326. BABYLON.Tools.LoadFile(url, function (data) {
  4327. callback(data);
  4328. }, onerror, scene.database, true);
  4329. else
  4330. callback(buffer);
  4331. }
  4332. else {
  4333. var onload = function (img) {
  4334. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4335. var isPot = (img.width === potWidth && img.height === potHeight);
  4336. if (!isPot) {
  4337. _this._workingCanvas.width = potWidth;
  4338. _this._workingCanvas.height = potHeight;
  4339. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4340. _this._workingContext.imageSmoothingEnabled = false;
  4341. _this._workingContext.mozImageSmoothingEnabled = false;
  4342. _this._workingContext.oImageSmoothingEnabled = false;
  4343. _this._workingContext.webkitImageSmoothingEnabled = false;
  4344. _this._workingContext.msImageSmoothingEnabled = false;
  4345. }
  4346. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4347. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4348. _this._workingContext.imageSmoothingEnabled = true;
  4349. _this._workingContext.mozImageSmoothingEnabled = true;
  4350. _this._workingContext.oImageSmoothingEnabled = true;
  4351. _this._workingContext.webkitImageSmoothingEnabled = true;
  4352. _this._workingContext.msImageSmoothingEnabled = true;
  4353. }
  4354. }
  4355. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4356. if (onLoad) {
  4357. onLoad();
  4358. }
  4359. }, samplingMode);
  4360. };
  4361. if (!(fromData instanceof Array))
  4362. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4363. else
  4364. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4365. }
  4366. return texture;
  4367. };
  4368. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4369. var texture = this._gl.createTexture();
  4370. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4371. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4372. // Format
  4373. var internalFormat = this._gl.RGBA;
  4374. switch (format) {
  4375. case Engine.TEXTUREFORMAT_ALPHA:
  4376. internalFormat = this._gl.ALPHA;
  4377. break;
  4378. case Engine.TEXTUREFORMAT_LUMINANCE:
  4379. internalFormat = this._gl.LUMINANCE;
  4380. break;
  4381. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4382. internalFormat = this._gl.LUMINANCE_ALPHA;
  4383. break;
  4384. case Engine.TEXTUREFORMAT_RGB:
  4385. internalFormat = this._gl.RGB;
  4386. break;
  4387. case Engine.TEXTUREFORMAT_RGBA:
  4388. internalFormat = this._gl.RGBA;
  4389. break;
  4390. }
  4391. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4392. if (generateMipMaps) {
  4393. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4394. }
  4395. // Filters
  4396. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4397. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4399. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4400. this._activeTexturesCache = [];
  4401. texture._baseWidth = width;
  4402. texture._baseHeight = height;
  4403. texture._width = width;
  4404. texture._height = height;
  4405. texture.isReady = true;
  4406. texture.references = 1;
  4407. texture.samplingMode = samplingMode;
  4408. this._loadedTexturesCache.push(texture);
  4409. return texture;
  4410. };
  4411. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4412. var texture = this._gl.createTexture();
  4413. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4414. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4415. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4416. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4417. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4418. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4419. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4420. this._activeTexturesCache = [];
  4421. texture._baseWidth = width;
  4422. texture._baseHeight = height;
  4423. texture._width = width;
  4424. texture._height = height;
  4425. texture.isReady = false;
  4426. texture.generateMipMaps = generateMipMaps;
  4427. texture.references = 1;
  4428. texture.samplingMode = samplingMode;
  4429. this._loadedTexturesCache.push(texture);
  4430. return texture;
  4431. };
  4432. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4433. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4434. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4435. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4436. if (texture.generateMipMaps) {
  4437. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4438. }
  4439. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4440. this._activeTexturesCache = [];
  4441. texture.isReady = true;
  4442. };
  4443. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4444. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4445. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4446. // Scale the video if it is a NPOT using the current working canvas
  4447. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4448. if (!texture._workingCanvas) {
  4449. texture._workingCanvas = document.createElement("canvas");
  4450. texture._workingContext = texture._workingCanvas.getContext("2d");
  4451. texture._workingCanvas.width = texture._width;
  4452. texture._workingCanvas.height = texture._height;
  4453. }
  4454. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4455. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4456. }
  4457. else {
  4458. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4459. }
  4460. if (texture.generateMipMaps) {
  4461. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4462. }
  4463. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4464. this._activeTexturesCache = [];
  4465. texture.isReady = true;
  4466. };
  4467. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4468. // old version had a "generateMipMaps" arg instead of options.
  4469. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4470. // in the same way, generateDepthBuffer is defaulted to true
  4471. var generateMipMaps = false;
  4472. var generateDepthBuffer = true;
  4473. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4474. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4475. if (options !== undefined) {
  4476. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4477. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4478. type = options.type === undefined ? type : options.type;
  4479. if (options.samplingMode !== undefined) {
  4480. samplingMode = options.samplingMode;
  4481. }
  4482. if (type === Engine.TEXTURETYPE_FLOAT) {
  4483. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4484. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4485. }
  4486. }
  4487. var gl = this._gl;
  4488. var texture = gl.createTexture();
  4489. gl.bindTexture(gl.TEXTURE_2D, texture);
  4490. var width = size.width || size;
  4491. var height = size.height || size;
  4492. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4493. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4494. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4495. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4496. }
  4497. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4498. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4499. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4501. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4502. var depthBuffer;
  4503. // Create the depth buffer
  4504. if (generateDepthBuffer) {
  4505. depthBuffer = gl.createRenderbuffer();
  4506. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4507. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4508. }
  4509. // Create the framebuffer
  4510. var framebuffer = gl.createFramebuffer();
  4511. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4512. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4513. if (generateDepthBuffer) {
  4514. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4515. }
  4516. // Unbind
  4517. gl.bindTexture(gl.TEXTURE_2D, null);
  4518. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4519. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4520. texture._framebuffer = framebuffer;
  4521. if (generateDepthBuffer) {
  4522. texture._depthBuffer = depthBuffer;
  4523. }
  4524. texture._width = width;
  4525. texture._height = height;
  4526. texture.isReady = true;
  4527. texture.generateMipMaps = generateMipMaps;
  4528. texture.references = 1;
  4529. texture.samplingMode = samplingMode;
  4530. this._activeTexturesCache = [];
  4531. this._loadedTexturesCache.push(texture);
  4532. return texture;
  4533. };
  4534. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4535. var _this = this;
  4536. var gl = this._gl;
  4537. var texture = gl.createTexture();
  4538. texture.isCube = true;
  4539. texture.url = rootUrl;
  4540. texture.references = 1;
  4541. this._loadedTexturesCache.push(texture);
  4542. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4543. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4544. if (isDDS) {
  4545. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4546. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4547. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4548. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4549. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4550. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4551. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4552. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4553. }
  4554. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4555. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4556. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4557. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4558. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4559. _this._activeTexturesCache = [];
  4560. texture._width = info.width;
  4561. texture._height = info.height;
  4562. texture.isReady = true;
  4563. }, null, null, true);
  4564. }
  4565. else {
  4566. cascadeLoad(rootUrl, scene, function (imgs) {
  4567. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4568. var height = width;
  4569. _this._workingCanvas.width = width;
  4570. _this._workingCanvas.height = height;
  4571. var faces = [
  4572. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4573. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4574. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4575. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4576. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4577. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4578. ];
  4579. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4580. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4581. for (var index = 0; index < faces.length; index++) {
  4582. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4583. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4584. }
  4585. if (!noMipmap) {
  4586. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4587. }
  4588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4590. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4591. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4592. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4593. _this._activeTexturesCache = [];
  4594. texture._width = width;
  4595. texture._height = height;
  4596. texture.isReady = true;
  4597. }, extensions);
  4598. }
  4599. return texture;
  4600. };
  4601. Engine.prototype._releaseTexture = function (texture) {
  4602. var gl = this._gl;
  4603. if (texture._framebuffer) {
  4604. gl.deleteFramebuffer(texture._framebuffer);
  4605. }
  4606. if (texture._depthBuffer) {
  4607. gl.deleteRenderbuffer(texture._depthBuffer);
  4608. }
  4609. gl.deleteTexture(texture);
  4610. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4611. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4612. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4613. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4614. this._activeTexturesCache[channel] = null;
  4615. }
  4616. var index = this._loadedTexturesCache.indexOf(texture);
  4617. if (index !== -1) {
  4618. this._loadedTexturesCache.splice(index, 1);
  4619. }
  4620. };
  4621. Engine.prototype.bindSamplers = function (effect) {
  4622. this._gl.useProgram(effect.getProgram());
  4623. var samplers = effect.getSamplers();
  4624. for (var index = 0; index < samplers.length; index++) {
  4625. var uniform = effect.getUniform(samplers[index]);
  4626. this._gl.uniform1i(uniform, index);
  4627. }
  4628. this._currentEffect = null;
  4629. };
  4630. Engine.prototype._bindTexture = function (channel, texture) {
  4631. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4632. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4633. this._activeTexturesCache[channel] = null;
  4634. };
  4635. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4636. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4637. };
  4638. Engine.prototype.setTexture = function (channel, texture) {
  4639. if (channel < 0) {
  4640. return;
  4641. }
  4642. // Not ready?
  4643. if (!texture || !texture.isReady()) {
  4644. if (this._activeTexturesCache[channel] != null) {
  4645. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4646. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4647. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4648. this._activeTexturesCache[channel] = null;
  4649. }
  4650. return;
  4651. }
  4652. // Video
  4653. if (texture instanceof BABYLON.VideoTexture) {
  4654. if (texture.update()) {
  4655. this._activeTexturesCache[channel] = null;
  4656. }
  4657. }
  4658. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4659. texture.delayLoad();
  4660. return;
  4661. }
  4662. if (this._activeTexturesCache[channel] === texture) {
  4663. return;
  4664. }
  4665. this._activeTexturesCache[channel] = texture;
  4666. var internalTexture = texture.getInternalTexture();
  4667. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4668. if (internalTexture.isCube) {
  4669. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4670. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4671. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4672. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4673. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4674. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4675. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4676. }
  4677. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4678. }
  4679. else {
  4680. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4681. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4682. internalTexture._cachedWrapU = texture.wrapU;
  4683. switch (texture.wrapU) {
  4684. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4685. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4686. break;
  4687. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4688. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4689. break;
  4690. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4691. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4692. break;
  4693. }
  4694. }
  4695. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4696. internalTexture._cachedWrapV = texture.wrapV;
  4697. switch (texture.wrapV) {
  4698. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4699. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4700. break;
  4701. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4702. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4703. break;
  4704. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4705. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4706. break;
  4707. }
  4708. }
  4709. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4710. }
  4711. };
  4712. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4713. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4714. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4715. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4716. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4717. }
  4718. };
  4719. Engine.prototype.readPixels = function (x, y, width, height) {
  4720. var data = new Uint8Array(height * width * 4);
  4721. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4722. return data;
  4723. };
  4724. // Dispose
  4725. Engine.prototype.dispose = function () {
  4726. this.hideLoadingUI();
  4727. this.stopRenderLoop();
  4728. while (this.scenes.length) {
  4729. this.scenes[0].dispose();
  4730. }
  4731. // Release audio engine
  4732. Engine.audioEngine.dispose();
  4733. for (var name in this._compiledEffects) {
  4734. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4735. }
  4736. for (var i in this._vertexAttribArrays) {
  4737. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4738. continue;
  4739. }
  4740. this._gl.disableVertexAttribArray(i);
  4741. }
  4742. // Events
  4743. window.removeEventListener("blur", this._onBlur);
  4744. window.removeEventListener("focus", this._onFocus);
  4745. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4746. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4747. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4748. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4749. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4750. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4751. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4752. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4753. };
  4754. // Loading screen
  4755. Engine.prototype.displayLoadingUI = function () {
  4756. var _this = this;
  4757. this._loadingDiv = document.createElement("div");
  4758. this._loadingDiv.style.opacity = "0";
  4759. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4760. // Loading text
  4761. this._loadingTextDiv = document.createElement("div");
  4762. this._loadingTextDiv.style.position = "absolute";
  4763. this._loadingTextDiv.style.left = "0";
  4764. this._loadingTextDiv.style.top = "50%";
  4765. this._loadingTextDiv.style.marginTop = "80px";
  4766. this._loadingTextDiv.style.width = "100%";
  4767. this._loadingTextDiv.style.height = "20px";
  4768. this._loadingTextDiv.style.fontFamily = "Arial";
  4769. this._loadingTextDiv.style.fontSize = "14px";
  4770. this._loadingTextDiv.style.color = "white";
  4771. this._loadingTextDiv.style.textAlign = "center";
  4772. this._loadingTextDiv.innerHTML = "Loading";
  4773. this._loadingDiv.appendChild(this._loadingTextDiv);
  4774. // Loading img
  4775. var imgBack = new Image();
  4776. 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==";
  4777. imgBack.style.position = "absolute";
  4778. imgBack.style.left = "50%";
  4779. imgBack.style.top = "50%";
  4780. imgBack.style.marginLeft = "-50px";
  4781. imgBack.style.marginTop = "-50px";
  4782. imgBack.style.transition = "transform 1.0s ease";
  4783. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4784. var deg = 360;
  4785. var onTransitionEnd = function () {
  4786. deg += 360;
  4787. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4788. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4789. };
  4790. imgBack.addEventListener("transitionend", onTransitionEnd);
  4791. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4792. this._loadingDiv.appendChild(imgBack);
  4793. // front image
  4794. var imgFront = new Image();
  4795. 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=";
  4796. imgFront.style.position = "absolute";
  4797. imgFront.style.left = "50%";
  4798. imgFront.style.top = "50%";
  4799. imgFront.style.marginLeft = "-50px";
  4800. imgFront.style.marginTop = "-50px";
  4801. this._loadingDiv.appendChild(imgFront);
  4802. // Resize
  4803. this._resizeLoadingUI = function () {
  4804. var canvasRect = _this.getRenderingCanvasClientRect();
  4805. _this._loadingDiv.style.position = "absolute";
  4806. _this._loadingDiv.style.left = canvasRect.left + "px";
  4807. _this._loadingDiv.style.top = canvasRect.top + "px";
  4808. _this._loadingDiv.style.width = canvasRect.width + "px";
  4809. _this._loadingDiv.style.height = canvasRect.height + "px";
  4810. };
  4811. this._resizeLoadingUI();
  4812. window.addEventListener("resize", this._resizeLoadingUI);
  4813. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4814. document.body.appendChild(this._loadingDiv);
  4815. setTimeout(function () {
  4816. _this._loadingDiv.style.opacity = "1";
  4817. imgBack.style.transform = "rotateZ(360deg)";
  4818. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4819. }, 0);
  4820. };
  4821. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4822. set: function (text) {
  4823. if (!this._loadingDiv) {
  4824. return;
  4825. }
  4826. this._loadingTextDiv.innerHTML = text;
  4827. },
  4828. enumerable: true,
  4829. configurable: true
  4830. });
  4831. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4832. get: function () {
  4833. return this._loadingDivBackgroundColor;
  4834. },
  4835. set: function (color) {
  4836. this._loadingDivBackgroundColor = color;
  4837. if (!this._loadingDiv) {
  4838. return;
  4839. }
  4840. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4841. },
  4842. enumerable: true,
  4843. configurable: true
  4844. });
  4845. Engine.prototype.hideLoadingUI = function () {
  4846. var _this = this;
  4847. if (!this._loadingDiv) {
  4848. return;
  4849. }
  4850. var onTransitionEnd = function () {
  4851. if (!_this._loadingDiv) {
  4852. return;
  4853. }
  4854. document.body.removeChild(_this._loadingDiv);
  4855. window.removeEventListener("resize", _this._resizeLoadingUI);
  4856. _this._loadingDiv = null;
  4857. };
  4858. this._loadingDiv.style.opacity = "0";
  4859. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4860. };
  4861. // FPS
  4862. Engine.prototype.getFps = function () {
  4863. return this.fps;
  4864. };
  4865. Engine.prototype.getDeltaTime = function () {
  4866. return this.deltaTime;
  4867. };
  4868. Engine.prototype._measureFps = function () {
  4869. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4870. var length = this.previousFramesDuration.length;
  4871. if (length >= 2) {
  4872. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4873. }
  4874. if (length >= this.fpsRange) {
  4875. if (length > this.fpsRange) {
  4876. this.previousFramesDuration.splice(0, 1);
  4877. length = this.previousFramesDuration.length;
  4878. }
  4879. var sum = 0;
  4880. for (var id = 0; id < length - 1; id++) {
  4881. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4882. }
  4883. this.fps = 1000.0 / (sum / (length - 1));
  4884. }
  4885. };
  4886. // Statics
  4887. Engine.isSupported = function () {
  4888. try {
  4889. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4890. if (navigator.isCocoonJS) {
  4891. return true;
  4892. }
  4893. var tempcanvas = document.createElement("canvas");
  4894. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4895. return gl != null && !!window.WebGLRenderingContext;
  4896. }
  4897. catch (e) {
  4898. return false;
  4899. }
  4900. };
  4901. // Const statics
  4902. Engine._ALPHA_DISABLE = 0;
  4903. Engine._ALPHA_ADD = 1;
  4904. Engine._ALPHA_COMBINE = 2;
  4905. Engine._DELAYLOADSTATE_NONE = 0;
  4906. Engine._DELAYLOADSTATE_LOADED = 1;
  4907. Engine._DELAYLOADSTATE_LOADING = 2;
  4908. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4909. Engine._TEXTUREFORMAT_ALPHA = 0;
  4910. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4911. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4912. Engine._TEXTUREFORMAT_RGB = 4;
  4913. Engine._TEXTUREFORMAT_RGBA = 4;
  4914. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  4915. Engine._TEXTURETYPE_FLOAT = 1;
  4916. // Updatable statics so stick with vars here
  4917. Engine.Epsilon = 0.001;
  4918. Engine.CollisionsEpsilon = 0.001;
  4919. Engine.ShadersRepository = "Babylon/Shaders/";
  4920. return Engine;
  4921. })();
  4922. BABYLON.Engine = Engine;
  4923. })(BABYLON || (BABYLON = {}));
  4924. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  4925. (function (BABYLON) {
  4926. /**
  4927. * Node is the basic class for all scene objects (Mesh, Light Camera).
  4928. */
  4929. var Node = (function () {
  4930. /**
  4931. * @constructor
  4932. * @param {string} name - the name and id to be given to this node
  4933. * @param {BABYLON.Scene} the scene this node will be added to
  4934. */
  4935. function Node(name, scene) {
  4936. this.state = "";
  4937. this.animations = new Array();
  4938. this._childrenFlag = -1;
  4939. this._isEnabled = true;
  4940. this._isReady = true;
  4941. this._currentRenderId = -1;
  4942. this.name = name;
  4943. this.id = name;
  4944. this._scene = scene;
  4945. this._initCache();
  4946. }
  4947. Node.prototype.getScene = function () {
  4948. return this._scene;
  4949. };
  4950. Node.prototype.getEngine = function () {
  4951. return this._scene.getEngine();
  4952. };
  4953. // override it in derived class
  4954. Node.prototype.getWorldMatrix = function () {
  4955. return BABYLON.Matrix.Identity();
  4956. };
  4957. // override it in derived class if you add new variables to the cache
  4958. // and call the parent class method
  4959. Node.prototype._initCache = function () {
  4960. this._cache = {};
  4961. this._cache.parent = undefined;
  4962. };
  4963. Node.prototype.updateCache = function (force) {
  4964. if (!force && this.isSynchronized())
  4965. return;
  4966. this._cache.parent = this.parent;
  4967. this._updateCache();
  4968. };
  4969. // override it in derived class if you add new variables to the cache
  4970. // and call the parent class method if !ignoreParentClass
  4971. Node.prototype._updateCache = function (ignoreParentClass) {
  4972. };
  4973. // override it in derived class if you add new variables to the cache
  4974. Node.prototype._isSynchronized = function () {
  4975. return true;
  4976. };
  4977. Node.prototype.isSynchronizedWithParent = function () {
  4978. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4979. };
  4980. Node.prototype.isSynchronized = function (updateCache) {
  4981. var check = this.hasNewParent();
  4982. check = check || !this.isSynchronizedWithParent();
  4983. check = check || !this._isSynchronized();
  4984. if (updateCache)
  4985. this.updateCache(true);
  4986. return !check;
  4987. };
  4988. Node.prototype.hasNewParent = function (update) {
  4989. if (this._cache.parent === this.parent)
  4990. return false;
  4991. if (update)
  4992. this._cache.parent = this.parent;
  4993. return true;
  4994. };
  4995. /**
  4996. * Is this node ready to be used/rendered
  4997. * @return {boolean} is it ready
  4998. */
  4999. Node.prototype.isReady = function () {
  5000. return this._isReady;
  5001. };
  5002. /**
  5003. * Is this node enabled.
  5004. * If the node has a parent and is enabled, the parent will be inspected as well.
  5005. * @return {boolean} whether this node (and its parent) is enabled.
  5006. * @see setEnabled
  5007. */
  5008. Node.prototype.isEnabled = function () {
  5009. if (!this._isEnabled) {
  5010. return false;
  5011. }
  5012. if (this.parent) {
  5013. return this.parent.isEnabled();
  5014. }
  5015. return true;
  5016. };
  5017. /**
  5018. * Set the enabled state of this node.
  5019. * @param {boolean} value - the new enabled state
  5020. * @see isEnabled
  5021. */
  5022. Node.prototype.setEnabled = function (value) {
  5023. this._isEnabled = value;
  5024. };
  5025. /**
  5026. * Is this node a descendant of the given node.
  5027. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5028. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5029. * @see parent
  5030. */
  5031. Node.prototype.isDescendantOf = function (ancestor) {
  5032. if (this.parent) {
  5033. if (this.parent === ancestor) {
  5034. return true;
  5035. }
  5036. return this.parent.isDescendantOf(ancestor);
  5037. }
  5038. return false;
  5039. };
  5040. Node.prototype._getDescendants = function (list, results) {
  5041. for (var index = 0; index < list.length; index++) {
  5042. var item = list[index];
  5043. if (item.isDescendantOf(this)) {
  5044. results.push(item);
  5045. }
  5046. }
  5047. };
  5048. /**
  5049. * Will return all nodes that have this node as parent.
  5050. * @return {BABYLON.Node[]} all children nodes of all types.
  5051. */
  5052. Node.prototype.getDescendants = function () {
  5053. var results = [];
  5054. this._getDescendants(this._scene.meshes, results);
  5055. this._getDescendants(this._scene.lights, results);
  5056. this._getDescendants(this._scene.cameras, results);
  5057. return results;
  5058. };
  5059. Node.prototype._setReady = function (state) {
  5060. if (state == this._isReady) {
  5061. return;
  5062. }
  5063. if (!state) {
  5064. this._isReady = false;
  5065. return;
  5066. }
  5067. this._isReady = true;
  5068. if (this.onReady) {
  5069. this.onReady(this);
  5070. }
  5071. };
  5072. return Node;
  5073. })();
  5074. BABYLON.Node = Node;
  5075. })(BABYLON || (BABYLON = {}));
  5076. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5077. (function (BABYLON) {
  5078. var BoundingSphere = (function () {
  5079. function BoundingSphere(minimum, maximum) {
  5080. this.minimum = minimum;
  5081. this.maximum = maximum;
  5082. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5083. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5084. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5085. this.radius = distance * 0.5;
  5086. this.centerWorld = BABYLON.Vector3.Zero();
  5087. this._update(BABYLON.Matrix.Identity());
  5088. }
  5089. // Methods
  5090. BoundingSphere.prototype._update = function (world) {
  5091. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5092. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5093. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5094. };
  5095. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5096. for (var i = 0; i < 6; i++) {
  5097. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5098. return false;
  5099. }
  5100. return true;
  5101. };
  5102. BoundingSphere.prototype.intersectsPoint = function (point) {
  5103. var x = this.centerWorld.x - point.x;
  5104. var y = this.centerWorld.y - point.y;
  5105. var z = this.centerWorld.z - point.z;
  5106. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5107. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5108. return false;
  5109. return true;
  5110. };
  5111. // Statics
  5112. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5113. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5114. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5115. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5116. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5117. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5118. return false;
  5119. return true;
  5120. };
  5121. return BoundingSphere;
  5122. })();
  5123. BABYLON.BoundingSphere = BoundingSphere;
  5124. })(BABYLON || (BABYLON = {}));
  5125. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5126. (function (BABYLON) {
  5127. var BoundingBox = (function () {
  5128. function BoundingBox(minimum, maximum) {
  5129. this.minimum = minimum;
  5130. this.maximum = maximum;
  5131. this.vectors = new Array();
  5132. this.vectorsWorld = new Array();
  5133. // Bounding vectors
  5134. this.vectors.push(this.minimum.clone());
  5135. this.vectors.push(this.maximum.clone());
  5136. this.vectors.push(this.minimum.clone());
  5137. this.vectors[2].x = this.maximum.x;
  5138. this.vectors.push(this.minimum.clone());
  5139. this.vectors[3].y = this.maximum.y;
  5140. this.vectors.push(this.minimum.clone());
  5141. this.vectors[4].z = this.maximum.z;
  5142. this.vectors.push(this.maximum.clone());
  5143. this.vectors[5].z = this.minimum.z;
  5144. this.vectors.push(this.maximum.clone());
  5145. this.vectors[6].x = this.minimum.x;
  5146. this.vectors.push(this.maximum.clone());
  5147. this.vectors[7].y = this.minimum.y;
  5148. // OBB
  5149. this.center = this.maximum.add(this.minimum).scale(0.5);
  5150. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5151. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5152. for (var index = 0; index < this.vectors.length; index++) {
  5153. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5154. }
  5155. this.minimumWorld = BABYLON.Vector3.Zero();
  5156. this.maximumWorld = BABYLON.Vector3.Zero();
  5157. this._update(BABYLON.Matrix.Identity());
  5158. }
  5159. // Methods
  5160. BoundingBox.prototype.getWorldMatrix = function () {
  5161. return this._worldMatrix;
  5162. };
  5163. BoundingBox.prototype._update = function (world) {
  5164. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5165. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5166. for (var index = 0; index < this.vectors.length; index++) {
  5167. var v = this.vectorsWorld[index];
  5168. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5169. if (v.x < this.minimumWorld.x)
  5170. this.minimumWorld.x = v.x;
  5171. if (v.y < this.minimumWorld.y)
  5172. this.minimumWorld.y = v.y;
  5173. if (v.z < this.minimumWorld.z)
  5174. this.minimumWorld.z = v.z;
  5175. if (v.x > this.maximumWorld.x)
  5176. this.maximumWorld.x = v.x;
  5177. if (v.y > this.maximumWorld.y)
  5178. this.maximumWorld.y = v.y;
  5179. if (v.z > this.maximumWorld.z)
  5180. this.maximumWorld.z = v.z;
  5181. }
  5182. // OBB
  5183. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5184. this.center.scaleInPlace(0.5);
  5185. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5186. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5187. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5188. this._worldMatrix = world;
  5189. };
  5190. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5191. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5192. };
  5193. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5194. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5195. };
  5196. BoundingBox.prototype.intersectsPoint = function (point) {
  5197. var delta = BABYLON.Engine.Epsilon;
  5198. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5199. return false;
  5200. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5201. return false;
  5202. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5203. return false;
  5204. return true;
  5205. };
  5206. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5207. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5208. };
  5209. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5210. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5211. return false;
  5212. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5213. return false;
  5214. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5215. return false;
  5216. return true;
  5217. };
  5218. // Statics
  5219. BoundingBox.Intersects = function (box0, box1) {
  5220. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5221. return false;
  5222. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5223. return false;
  5224. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5225. return false;
  5226. return true;
  5227. };
  5228. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5229. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5230. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5231. return (num <= (sphereRadius * sphereRadius));
  5232. };
  5233. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5234. for (var p = 0; p < 6; p++) {
  5235. for (var i = 0; i < 8; i++) {
  5236. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5237. return false;
  5238. }
  5239. }
  5240. }
  5241. return true;
  5242. };
  5243. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5244. for (var p = 0; p < 6; p++) {
  5245. var inCount = 8;
  5246. for (var i = 0; i < 8; i++) {
  5247. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5248. --inCount;
  5249. }
  5250. else {
  5251. break;
  5252. }
  5253. }
  5254. if (inCount == 0)
  5255. return false;
  5256. }
  5257. return true;
  5258. };
  5259. return BoundingBox;
  5260. })();
  5261. BABYLON.BoundingBox = BoundingBox;
  5262. })(BABYLON || (BABYLON = {}));
  5263. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5264. (function (BABYLON) {
  5265. var computeBoxExtents = function (axis, box) {
  5266. var p = BABYLON.Vector3.Dot(box.center, axis);
  5267. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5268. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5269. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5270. var r = r0 + r1 + r2;
  5271. return {
  5272. min: p - r,
  5273. max: p + r
  5274. };
  5275. };
  5276. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5277. var axisOverlap = function (axis, box0, box1) {
  5278. var result0 = computeBoxExtents(axis, box0);
  5279. var result1 = computeBoxExtents(axis, box1);
  5280. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5281. };
  5282. var BoundingInfo = (function () {
  5283. function BoundingInfo(minimum, maximum) {
  5284. this.minimum = minimum;
  5285. this.maximum = maximum;
  5286. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5287. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5288. }
  5289. // Methods
  5290. BoundingInfo.prototype._update = function (world) {
  5291. this.boundingBox._update(world);
  5292. this.boundingSphere._update(world);
  5293. };
  5294. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5295. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5296. return false;
  5297. return this.boundingBox.isInFrustum(frustumPlanes);
  5298. };
  5299. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5300. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5301. };
  5302. BoundingInfo.prototype._checkCollision = function (collider) {
  5303. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5304. };
  5305. BoundingInfo.prototype.intersectsPoint = function (point) {
  5306. if (!this.boundingSphere.centerWorld) {
  5307. return false;
  5308. }
  5309. if (!this.boundingSphere.intersectsPoint(point)) {
  5310. return false;
  5311. }
  5312. if (!this.boundingBox.intersectsPoint(point)) {
  5313. return false;
  5314. }
  5315. return true;
  5316. };
  5317. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5318. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5319. return false;
  5320. }
  5321. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5322. return false;
  5323. }
  5324. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5325. return false;
  5326. }
  5327. if (!precise) {
  5328. return true;
  5329. }
  5330. var box0 = this.boundingBox;
  5331. var box1 = boundingInfo.boundingBox;
  5332. if (!axisOverlap(box0.directions[0], box0, box1))
  5333. return false;
  5334. if (!axisOverlap(box0.directions[1], box0, box1))
  5335. return false;
  5336. if (!axisOverlap(box0.directions[2], box0, box1))
  5337. return false;
  5338. if (!axisOverlap(box1.directions[0], box0, box1))
  5339. return false;
  5340. if (!axisOverlap(box1.directions[1], box0, box1))
  5341. return false;
  5342. if (!axisOverlap(box1.directions[2], box0, box1))
  5343. return false;
  5344. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5345. return false;
  5346. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5347. return false;
  5348. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5349. return false;
  5350. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5351. return false;
  5352. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5353. return false;
  5354. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5355. return false;
  5356. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5357. return false;
  5358. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5359. return false;
  5360. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5361. return false;
  5362. return true;
  5363. };
  5364. return BoundingInfo;
  5365. })();
  5366. BABYLON.BoundingInfo = BoundingInfo;
  5367. })(BABYLON || (BABYLON = {}));
  5368. //# sourceMappingURL=babylon.boundingInfo.js.map
  5369. var BABYLON;
  5370. (function (BABYLON) {
  5371. var Light = (function (_super) {
  5372. __extends(Light, _super);
  5373. function Light(name, scene) {
  5374. _super.call(this, name, scene);
  5375. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5376. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5377. this.intensity = 1.0;
  5378. this.range = Number.MAX_VALUE;
  5379. this.includedOnlyMeshes = new Array();
  5380. this.excludedMeshes = new Array();
  5381. this._excludedMeshesIds = new Array();
  5382. this._includedOnlyMeshesIds = new Array();
  5383. scene.lights.push(this);
  5384. }
  5385. Light.prototype.getShadowGenerator = function () {
  5386. return this._shadowGenerator;
  5387. };
  5388. Light.prototype.getAbsolutePosition = function () {
  5389. return BABYLON.Vector3.Zero();
  5390. };
  5391. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5392. };
  5393. Light.prototype._getWorldMatrix = function () {
  5394. return BABYLON.Matrix.Identity();
  5395. };
  5396. Light.prototype.canAffectMesh = function (mesh) {
  5397. if (!mesh) {
  5398. return true;
  5399. }
  5400. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5401. return false;
  5402. }
  5403. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5404. return false;
  5405. }
  5406. return true;
  5407. };
  5408. Light.prototype.getWorldMatrix = function () {
  5409. this._currentRenderId = this.getScene().getRenderId();
  5410. var worldMatrix = this._getWorldMatrix();
  5411. if (this.parent && this.parent.getWorldMatrix) {
  5412. if (!this._parentedWorldMatrix) {
  5413. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5414. }
  5415. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5416. return this._parentedWorldMatrix;
  5417. }
  5418. return worldMatrix;
  5419. };
  5420. Light.prototype.dispose = function () {
  5421. if (this._shadowGenerator) {
  5422. this._shadowGenerator.dispose();
  5423. this._shadowGenerator = null;
  5424. }
  5425. // Remove from scene
  5426. var index = this.getScene().lights.indexOf(this);
  5427. this.getScene().lights.splice(index, 1);
  5428. };
  5429. return Light;
  5430. })(BABYLON.Node);
  5431. BABYLON.Light = Light;
  5432. })(BABYLON || (BABYLON = {}));
  5433. //# sourceMappingURL=babylon.light.js.map
  5434. var BABYLON;
  5435. (function (BABYLON) {
  5436. var PointLight = (function (_super) {
  5437. __extends(PointLight, _super);
  5438. function PointLight(name, position, scene) {
  5439. _super.call(this, name, scene);
  5440. this.position = position;
  5441. }
  5442. PointLight.prototype.getAbsolutePosition = function () {
  5443. return this._transformedPosition ? this._transformedPosition : this.position;
  5444. };
  5445. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5446. if (this.parent && this.parent.getWorldMatrix) {
  5447. if (!this._transformedPosition) {
  5448. this._transformedPosition = BABYLON.Vector3.Zero();
  5449. }
  5450. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5451. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5452. return;
  5453. }
  5454. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5455. };
  5456. PointLight.prototype.getShadowGenerator = function () {
  5457. return null;
  5458. };
  5459. PointLight.prototype._getWorldMatrix = function () {
  5460. if (!this._worldMatrix) {
  5461. this._worldMatrix = BABYLON.Matrix.Identity();
  5462. }
  5463. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5464. return this._worldMatrix;
  5465. };
  5466. return PointLight;
  5467. })(BABYLON.Light);
  5468. BABYLON.PointLight = PointLight;
  5469. })(BABYLON || (BABYLON = {}));
  5470. //# sourceMappingURL=babylon.pointLight.js.map
  5471. var BABYLON;
  5472. (function (BABYLON) {
  5473. var SpotLight = (function (_super) {
  5474. __extends(SpotLight, _super);
  5475. function SpotLight(name, position, direction, angle, exponent, scene) {
  5476. _super.call(this, name, scene);
  5477. this.position = position;
  5478. this.direction = direction;
  5479. this.angle = angle;
  5480. this.exponent = exponent;
  5481. }
  5482. SpotLight.prototype.getAbsolutePosition = function () {
  5483. return this.transformedPosition ? this.transformedPosition : this.position;
  5484. };
  5485. SpotLight.prototype.setDirectionToTarget = function (target) {
  5486. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5487. return this.direction;
  5488. };
  5489. SpotLight.prototype.computeTransformedPosition = function () {
  5490. if (this.parent && this.parent.getWorldMatrix) {
  5491. if (!this.transformedPosition) {
  5492. this.transformedPosition = BABYLON.Vector3.Zero();
  5493. }
  5494. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5495. return true;
  5496. }
  5497. return false;
  5498. };
  5499. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5500. var normalizeDirection;
  5501. if (this.parent && this.parent.getWorldMatrix) {
  5502. if (!this._transformedDirection) {
  5503. this._transformedDirection = BABYLON.Vector3.Zero();
  5504. }
  5505. this.computeTransformedPosition();
  5506. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5507. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5508. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5509. }
  5510. else {
  5511. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5512. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5513. }
  5514. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5515. };
  5516. SpotLight.prototype._getWorldMatrix = function () {
  5517. if (!this._worldMatrix) {
  5518. this._worldMatrix = BABYLON.Matrix.Identity();
  5519. }
  5520. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5521. return this._worldMatrix;
  5522. };
  5523. return SpotLight;
  5524. })(BABYLON.Light);
  5525. BABYLON.SpotLight = SpotLight;
  5526. })(BABYLON || (BABYLON = {}));
  5527. //# sourceMappingURL=babylon.spotLight.js.map
  5528. var BABYLON;
  5529. (function (BABYLON) {
  5530. var DirectionalLight = (function (_super) {
  5531. __extends(DirectionalLight, _super);
  5532. function DirectionalLight(name, direction, scene) {
  5533. _super.call(this, name, scene);
  5534. this.direction = direction;
  5535. this.position = direction.scale(-1);
  5536. }
  5537. DirectionalLight.prototype.getAbsolutePosition = function () {
  5538. return this.transformedPosition ? this.transformedPosition : this.position;
  5539. };
  5540. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5541. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5542. return this.direction;
  5543. };
  5544. DirectionalLight.prototype.computeTransformedPosition = function () {
  5545. if (this.parent && this.parent.getWorldMatrix) {
  5546. if (!this.transformedPosition) {
  5547. this.transformedPosition = BABYLON.Vector3.Zero();
  5548. }
  5549. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5550. return true;
  5551. }
  5552. return false;
  5553. };
  5554. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5555. if (this.parent && this.parent.getWorldMatrix) {
  5556. if (!this._transformedDirection) {
  5557. this._transformedDirection = BABYLON.Vector3.Zero();
  5558. }
  5559. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5560. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5561. return;
  5562. }
  5563. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5564. };
  5565. DirectionalLight.prototype._getWorldMatrix = function () {
  5566. if (!this._worldMatrix) {
  5567. this._worldMatrix = BABYLON.Matrix.Identity();
  5568. }
  5569. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5570. return this._worldMatrix;
  5571. };
  5572. return DirectionalLight;
  5573. })(BABYLON.Light);
  5574. BABYLON.DirectionalLight = DirectionalLight;
  5575. })(BABYLON || (BABYLON = {}));
  5576. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5577. (function (BABYLON) {
  5578. var ShadowGenerator = (function () {
  5579. function ShadowGenerator(mapSize, light) {
  5580. var _this = this;
  5581. // Members
  5582. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5583. this._darkness = 0;
  5584. this._transparencyShadow = false;
  5585. this._viewMatrix = BABYLON.Matrix.Zero();
  5586. this._projectionMatrix = BABYLON.Matrix.Zero();
  5587. this._transformMatrix = BABYLON.Matrix.Zero();
  5588. this._worldViewProjection = BABYLON.Matrix.Zero();
  5589. this._light = light;
  5590. this._scene = light.getScene();
  5591. light._shadowGenerator = this;
  5592. // Render target
  5593. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5594. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5595. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5596. this._shadowMap.renderParticles = false;
  5597. // Custom render function
  5598. var renderSubMesh = function (subMesh) {
  5599. var mesh = subMesh.getRenderingMesh();
  5600. var scene = _this._scene;
  5601. var engine = scene.getEngine();
  5602. // Culling
  5603. engine.setState(subMesh.getMaterial().backFaceCulling);
  5604. // Managing instances
  5605. var batch = mesh._getInstancesRenderList(subMesh._id);
  5606. if (batch.mustReturn) {
  5607. return;
  5608. }
  5609. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5610. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5611. engine.enableEffect(_this._effect);
  5612. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5613. var material = subMesh.getMaterial();
  5614. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5615. // Alpha test
  5616. if (material && material.needAlphaTesting()) {
  5617. var alphaTexture = material.getAlphaTestTexture();
  5618. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5619. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5620. }
  5621. // Bones
  5622. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5623. if (useBones) {
  5624. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5625. }
  5626. if (hardwareInstancedRendering) {
  5627. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5628. }
  5629. else {
  5630. if (batch.renderSelf[subMesh._id]) {
  5631. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5632. // Draw
  5633. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5634. }
  5635. if (batch.visibleInstances[subMesh._id]) {
  5636. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5637. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5638. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5639. // Draw
  5640. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5641. }
  5642. }
  5643. }
  5644. }
  5645. else {
  5646. // Need to reset refresh rate of the shadowMap
  5647. _this._shadowMap.resetRefreshCounter();
  5648. }
  5649. };
  5650. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5651. var index;
  5652. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5653. renderSubMesh(opaqueSubMeshes.data[index]);
  5654. }
  5655. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5656. renderSubMesh(alphaTestSubMeshes.data[index]);
  5657. }
  5658. if (_this._transparencyShadow) {
  5659. for (index = 0; index < transparentSubMeshes.length; index++) {
  5660. renderSubMesh(transparentSubMeshes.data[index]);
  5661. }
  5662. }
  5663. };
  5664. }
  5665. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5666. // Static
  5667. get: function () {
  5668. return ShadowGenerator._FILTER_NONE;
  5669. },
  5670. enumerable: true,
  5671. configurable: true
  5672. });
  5673. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5674. get: function () {
  5675. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5676. },
  5677. enumerable: true,
  5678. configurable: true
  5679. });
  5680. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5681. get: function () {
  5682. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5683. },
  5684. enumerable: true,
  5685. configurable: true
  5686. });
  5687. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5688. get: function () {
  5689. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5690. },
  5691. set: function (value) {
  5692. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5693. },
  5694. enumerable: true,
  5695. configurable: true
  5696. });
  5697. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5698. get: function () {
  5699. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5700. },
  5701. set: function (value) {
  5702. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5703. },
  5704. enumerable: true,
  5705. configurable: true
  5706. });
  5707. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5708. var defines = [];
  5709. if (this.useVarianceShadowMap) {
  5710. defines.push("#define VSM");
  5711. }
  5712. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5713. var mesh = subMesh.getMesh();
  5714. var scene = mesh.getScene();
  5715. var material = subMesh.getMaterial();
  5716. // Alpha test
  5717. if (material && material.needAlphaTesting()) {
  5718. defines.push("#define ALPHATEST");
  5719. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5720. attribs.push(BABYLON.VertexBuffer.UVKind);
  5721. defines.push("#define UV1");
  5722. }
  5723. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5724. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5725. defines.push("#define UV2");
  5726. }
  5727. }
  5728. // Bones
  5729. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5730. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5731. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5732. defines.push("#define BONES");
  5733. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5734. }
  5735. // Instances
  5736. if (useInstances) {
  5737. defines.push("#define INSTANCES");
  5738. attribs.push("world0");
  5739. attribs.push("world1");
  5740. attribs.push("world2");
  5741. attribs.push("world3");
  5742. }
  5743. // Get correct effect
  5744. var join = defines.join("\n");
  5745. if (this._cachedDefines !== join) {
  5746. this._cachedDefines = join;
  5747. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5748. }
  5749. return this._effect.isReady();
  5750. };
  5751. ShadowGenerator.prototype.getShadowMap = function () {
  5752. return this._shadowMap;
  5753. };
  5754. ShadowGenerator.prototype.getLight = function () {
  5755. return this._light;
  5756. };
  5757. // Methods
  5758. ShadowGenerator.prototype.getTransformMatrix = function () {
  5759. var lightPosition = this._light.position;
  5760. var lightDirection = this._light.direction;
  5761. if (this._light.computeTransformedPosition()) {
  5762. lightPosition = this._light.transformedPosition;
  5763. }
  5764. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5765. this._cachedPosition = lightPosition.clone();
  5766. this._cachedDirection = lightDirection.clone();
  5767. var activeCamera = this._scene.activeCamera;
  5768. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5769. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5770. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5771. }
  5772. return this._transformMatrix;
  5773. };
  5774. ShadowGenerator.prototype.getDarkness = function () {
  5775. return this._darkness;
  5776. };
  5777. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5778. if (darkness >= 1.0)
  5779. this._darkness = 1.0;
  5780. else if (darkness <= 0.0)
  5781. this._darkness = 0.0;
  5782. else
  5783. this._darkness = darkness;
  5784. };
  5785. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5786. this._transparencyShadow = hasShadow;
  5787. };
  5788. ShadowGenerator.prototype.dispose = function () {
  5789. this._shadowMap.dispose();
  5790. };
  5791. ShadowGenerator._FILTER_NONE = 0;
  5792. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5793. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5794. return ShadowGenerator;
  5795. })();
  5796. BABYLON.ShadowGenerator = ShadowGenerator;
  5797. })(BABYLON || (BABYLON = {}));
  5798. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5799. var BABYLON;
  5800. (function (BABYLON) {
  5801. var HemisphericLight = (function (_super) {
  5802. __extends(HemisphericLight, _super);
  5803. function HemisphericLight(name, direction, scene) {
  5804. _super.call(this, name, scene);
  5805. this.direction = direction;
  5806. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5807. }
  5808. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5809. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5810. return this.direction;
  5811. };
  5812. HemisphericLight.prototype.getShadowGenerator = function () {
  5813. return null;
  5814. };
  5815. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5816. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5817. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5818. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5819. };
  5820. HemisphericLight.prototype._getWorldMatrix = function () {
  5821. if (!this._worldMatrix) {
  5822. this._worldMatrix = BABYLON.Matrix.Identity();
  5823. }
  5824. return this._worldMatrix;
  5825. };
  5826. return HemisphericLight;
  5827. })(BABYLON.Light);
  5828. BABYLON.HemisphericLight = HemisphericLight;
  5829. })(BABYLON || (BABYLON = {}));
  5830. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5831. (function (BABYLON) {
  5832. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5833. if (boxMin.x > sphereCenter.x + sphereRadius)
  5834. return false;
  5835. if (sphereCenter.x - sphereRadius > boxMax.x)
  5836. return false;
  5837. if (boxMin.y > sphereCenter.y + sphereRadius)
  5838. return false;
  5839. if (sphereCenter.y - sphereRadius > boxMax.y)
  5840. return false;
  5841. if (boxMin.z > sphereCenter.z + sphereRadius)
  5842. return false;
  5843. if (sphereCenter.z - sphereRadius > boxMax.z)
  5844. return false;
  5845. return true;
  5846. };
  5847. var getLowestRoot = function (a, b, c, maxR) {
  5848. var determinant = b * b - 4.0 * a * c;
  5849. var result = { root: 0, found: false };
  5850. if (determinant < 0)
  5851. return result;
  5852. var sqrtD = Math.sqrt(determinant);
  5853. var r1 = (-b - sqrtD) / (2.0 * a);
  5854. var r2 = (-b + sqrtD) / (2.0 * a);
  5855. if (r1 > r2) {
  5856. var temp = r2;
  5857. r2 = r1;
  5858. r1 = temp;
  5859. }
  5860. if (r1 > 0 && r1 < maxR) {
  5861. result.root = r1;
  5862. result.found = true;
  5863. return result;
  5864. }
  5865. if (r2 > 0 && r2 < maxR) {
  5866. result.root = r2;
  5867. result.found = true;
  5868. return result;
  5869. }
  5870. return result;
  5871. };
  5872. var Collider = (function () {
  5873. function Collider() {
  5874. this.radius = new BABYLON.Vector3(1, 1, 1);
  5875. this.retry = 0;
  5876. this.basePointWorld = BABYLON.Vector3.Zero();
  5877. this.velocityWorld = BABYLON.Vector3.Zero();
  5878. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5879. this._collisionPoint = BABYLON.Vector3.Zero();
  5880. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5881. this._tempVector = BABYLON.Vector3.Zero();
  5882. this._tempVector2 = BABYLON.Vector3.Zero();
  5883. this._tempVector3 = BABYLON.Vector3.Zero();
  5884. this._tempVector4 = BABYLON.Vector3.Zero();
  5885. this._edge = BABYLON.Vector3.Zero();
  5886. this._baseToVertex = BABYLON.Vector3.Zero();
  5887. this._destinationPoint = BABYLON.Vector3.Zero();
  5888. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5889. this._displacementVector = BABYLON.Vector3.Zero();
  5890. }
  5891. // Methods
  5892. Collider.prototype._initialize = function (source, dir, e) {
  5893. this.velocity = dir;
  5894. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5895. this.basePoint = source;
  5896. source.multiplyToRef(this.radius, this.basePointWorld);
  5897. dir.multiplyToRef(this.radius, this.velocityWorld);
  5898. this.velocityWorldLength = this.velocityWorld.length();
  5899. this.epsilon = e;
  5900. this.collisionFound = false;
  5901. };
  5902. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5903. pa.subtractToRef(point, this._tempVector);
  5904. pb.subtractToRef(point, this._tempVector2);
  5905. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5906. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5907. if (d < 0)
  5908. return false;
  5909. pc.subtractToRef(point, this._tempVector3);
  5910. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5911. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5912. if (d < 0)
  5913. return false;
  5914. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5915. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5916. return d >= 0;
  5917. };
  5918. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5919. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5920. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5921. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5922. return false;
  5923. }
  5924. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5925. return false;
  5926. return true;
  5927. };
  5928. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5929. var t0;
  5930. var embeddedInPlane = false;
  5931. if (!subMesh._trianglePlanes) {
  5932. subMesh._trianglePlanes = [];
  5933. }
  5934. if (!subMesh._trianglePlanes[faceIndex]) {
  5935. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5936. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5937. }
  5938. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5939. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5940. return;
  5941. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5942. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5943. if (normalDotVelocity == 0) {
  5944. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5945. return;
  5946. embeddedInPlane = true;
  5947. t0 = 0;
  5948. }
  5949. else {
  5950. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5951. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5952. if (t0 > t1) {
  5953. var temp = t1;
  5954. t1 = t0;
  5955. t0 = temp;
  5956. }
  5957. if (t0 > 1.0 || t1 < 0.0)
  5958. return;
  5959. if (t0 < 0)
  5960. t0 = 0;
  5961. if (t0 > 1.0)
  5962. t0 = 1.0;
  5963. }
  5964. this._collisionPoint.copyFromFloats(0, 0, 0);
  5965. var found = false;
  5966. var t = 1.0;
  5967. if (!embeddedInPlane) {
  5968. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5969. this.velocity.scaleToRef(t0, this._tempVector);
  5970. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5971. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5972. found = true;
  5973. t = t0;
  5974. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5975. }
  5976. }
  5977. if (!found) {
  5978. var velocitySquaredLength = this.velocity.lengthSquared();
  5979. var a = velocitySquaredLength;
  5980. this.basePoint.subtractToRef(p1, this._tempVector);
  5981. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5982. var c = this._tempVector.lengthSquared() - 1.0;
  5983. var lowestRoot = getLowestRoot(a, b, c, t);
  5984. if (lowestRoot.found) {
  5985. t = lowestRoot.root;
  5986. found = true;
  5987. this._collisionPoint.copyFrom(p1);
  5988. }
  5989. this.basePoint.subtractToRef(p2, this._tempVector);
  5990. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5991. c = this._tempVector.lengthSquared() - 1.0;
  5992. lowestRoot = getLowestRoot(a, b, c, t);
  5993. if (lowestRoot.found) {
  5994. t = lowestRoot.root;
  5995. found = true;
  5996. this._collisionPoint.copyFrom(p2);
  5997. }
  5998. this.basePoint.subtractToRef(p3, this._tempVector);
  5999. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6000. c = this._tempVector.lengthSquared() - 1.0;
  6001. lowestRoot = getLowestRoot(a, b, c, t);
  6002. if (lowestRoot.found) {
  6003. t = lowestRoot.root;
  6004. found = true;
  6005. this._collisionPoint.copyFrom(p3);
  6006. }
  6007. p2.subtractToRef(p1, this._edge);
  6008. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6009. var edgeSquaredLength = this._edge.lengthSquared();
  6010. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6011. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6012. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6013. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6014. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6015. lowestRoot = getLowestRoot(a, b, c, t);
  6016. if (lowestRoot.found) {
  6017. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6018. if (f >= 0.0 && f <= 1.0) {
  6019. t = lowestRoot.root;
  6020. found = true;
  6021. this._edge.scaleInPlace(f);
  6022. p1.addToRef(this._edge, this._collisionPoint);
  6023. }
  6024. }
  6025. p3.subtractToRef(p2, this._edge);
  6026. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6027. edgeSquaredLength = this._edge.lengthSquared();
  6028. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6029. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6030. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6031. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6032. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6033. lowestRoot = getLowestRoot(a, b, c, t);
  6034. if (lowestRoot.found) {
  6035. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6036. if (f >= 0.0 && f <= 1.0) {
  6037. t = lowestRoot.root;
  6038. found = true;
  6039. this._edge.scaleInPlace(f);
  6040. p2.addToRef(this._edge, this._collisionPoint);
  6041. }
  6042. }
  6043. p1.subtractToRef(p3, this._edge);
  6044. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6045. edgeSquaredLength = this._edge.lengthSquared();
  6046. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6047. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6048. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6049. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6050. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6051. lowestRoot = getLowestRoot(a, b, c, t);
  6052. if (lowestRoot.found) {
  6053. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6054. if (f >= 0.0 && f <= 1.0) {
  6055. t = lowestRoot.root;
  6056. found = true;
  6057. this._edge.scaleInPlace(f);
  6058. p3.addToRef(this._edge, this._collisionPoint);
  6059. }
  6060. }
  6061. }
  6062. if (found) {
  6063. var distToCollision = t * this.velocity.length();
  6064. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6065. if (!this.intersectionPoint) {
  6066. this.intersectionPoint = this._collisionPoint.clone();
  6067. }
  6068. else {
  6069. this.intersectionPoint.copyFrom(this._collisionPoint);
  6070. }
  6071. this.nearestDistance = distToCollision;
  6072. this.collisionFound = true;
  6073. this.collidedMesh = subMesh.getMesh();
  6074. }
  6075. }
  6076. };
  6077. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6078. for (var i = indexStart; i < indexEnd; i += 3) {
  6079. var p1 = pts[indices[i] - decal];
  6080. var p2 = pts[indices[i + 1] - decal];
  6081. var p3 = pts[indices[i + 2] - decal];
  6082. this._testTriangle(i, subMesh, p3, p2, p1);
  6083. }
  6084. };
  6085. Collider.prototype._getResponse = function (pos, vel) {
  6086. pos.addToRef(vel, this._destinationPoint);
  6087. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6088. this.basePoint.addToRef(vel, pos);
  6089. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6090. this._slidePlaneNormal.normalize();
  6091. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6092. pos.addInPlace(this._displacementVector);
  6093. this.intersectionPoint.addInPlace(this._displacementVector);
  6094. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6095. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6096. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6097. };
  6098. return Collider;
  6099. })();
  6100. BABYLON.Collider = Collider;
  6101. })(BABYLON || (BABYLON = {}));
  6102. //# sourceMappingURL=babylon.collider.js.map
  6103. var BABYLON;
  6104. (function (BABYLON) {
  6105. var Camera = (function (_super) {
  6106. __extends(Camera, _super);
  6107. function Camera(name, position, scene) {
  6108. _super.call(this, name, scene);
  6109. this.position = position;
  6110. // Members
  6111. this.upVector = BABYLON.Vector3.Up();
  6112. this.orthoLeft = null;
  6113. this.orthoRight = null;
  6114. this.orthoBottom = null;
  6115. this.orthoTop = null;
  6116. this.fov = 0.8;
  6117. this.minZ = 1.0;
  6118. this.maxZ = 10000.0;
  6119. this.inertia = 0.9;
  6120. this.mode = Camera.PERSPECTIVE_CAMERA;
  6121. this.isIntermediate = false;
  6122. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6123. this.subCameras = [];
  6124. this.layerMask = 0xFFFFFFFF;
  6125. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6126. this._projectionMatrix = new BABYLON.Matrix();
  6127. this._postProcesses = new Array();
  6128. this._postProcessesTakenIndices = [];
  6129. scene.cameras.push(this);
  6130. if (!scene.activeCamera) {
  6131. scene.activeCamera = this;
  6132. }
  6133. }
  6134. //Cache
  6135. Camera.prototype._initCache = function () {
  6136. _super.prototype._initCache.call(this);
  6137. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6138. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6139. this._cache.mode = undefined;
  6140. this._cache.minZ = undefined;
  6141. this._cache.maxZ = undefined;
  6142. this._cache.fov = undefined;
  6143. this._cache.aspectRatio = undefined;
  6144. this._cache.orthoLeft = undefined;
  6145. this._cache.orthoRight = undefined;
  6146. this._cache.orthoBottom = undefined;
  6147. this._cache.orthoTop = undefined;
  6148. this._cache.renderWidth = undefined;
  6149. this._cache.renderHeight = undefined;
  6150. };
  6151. Camera.prototype._updateCache = function (ignoreParentClass) {
  6152. if (!ignoreParentClass) {
  6153. _super.prototype._updateCache.call(this);
  6154. }
  6155. var engine = this.getEngine();
  6156. this._cache.position.copyFrom(this.position);
  6157. this._cache.upVector.copyFrom(this.upVector);
  6158. this._cache.mode = this.mode;
  6159. this._cache.minZ = this.minZ;
  6160. this._cache.maxZ = this.maxZ;
  6161. this._cache.fov = this.fov;
  6162. this._cache.aspectRatio = engine.getAspectRatio(this);
  6163. this._cache.orthoLeft = this.orthoLeft;
  6164. this._cache.orthoRight = this.orthoRight;
  6165. this._cache.orthoBottom = this.orthoBottom;
  6166. this._cache.orthoTop = this.orthoTop;
  6167. this._cache.renderWidth = engine.getRenderWidth();
  6168. this._cache.renderHeight = engine.getRenderHeight();
  6169. };
  6170. Camera.prototype._updateFromScene = function () {
  6171. this.updateCache();
  6172. this._update();
  6173. };
  6174. // Synchronized
  6175. Camera.prototype._isSynchronized = function () {
  6176. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6177. };
  6178. Camera.prototype._isSynchronizedViewMatrix = function () {
  6179. if (!_super.prototype._isSynchronized.call(this))
  6180. return false;
  6181. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6182. };
  6183. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6184. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6185. if (!check) {
  6186. return false;
  6187. }
  6188. var engine = this.getEngine();
  6189. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6190. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6191. }
  6192. else {
  6193. 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();
  6194. }
  6195. return check;
  6196. };
  6197. // Controls
  6198. Camera.prototype.attachControl = function (element) {
  6199. };
  6200. Camera.prototype.detachControl = function (element) {
  6201. };
  6202. Camera.prototype._update = function () {
  6203. };
  6204. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6205. if (insertAt === void 0) { insertAt = null; }
  6206. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6207. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6208. return 0;
  6209. }
  6210. if (insertAt == null || insertAt < 0) {
  6211. this._postProcesses.push(postProcess);
  6212. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6213. return this._postProcesses.length - 1;
  6214. }
  6215. var add = 0;
  6216. if (this._postProcesses[insertAt]) {
  6217. var start = this._postProcesses.length - 1;
  6218. for (var i = start; i >= insertAt + 1; --i) {
  6219. this._postProcesses[i + 1] = this._postProcesses[i];
  6220. }
  6221. add = 1;
  6222. }
  6223. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6224. if (this._postProcessesTakenIndices[i] < insertAt) {
  6225. continue;
  6226. }
  6227. start = this._postProcessesTakenIndices.length - 1;
  6228. for (var j = start; j >= i; --j) {
  6229. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6230. }
  6231. this._postProcessesTakenIndices[i] = insertAt;
  6232. break;
  6233. }
  6234. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6235. this._postProcessesTakenIndices.push(insertAt);
  6236. }
  6237. var result = insertAt + add;
  6238. this._postProcesses[result] = postProcess;
  6239. return result;
  6240. };
  6241. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6242. if (atIndices === void 0) { atIndices = null; }
  6243. var result = [];
  6244. if (!atIndices) {
  6245. var length = this._postProcesses.length;
  6246. for (var i = 0; i < length; i++) {
  6247. if (this._postProcesses[i] !== postProcess) {
  6248. continue;
  6249. }
  6250. delete this._postProcesses[i];
  6251. var index = this._postProcessesTakenIndices.indexOf(i);
  6252. this._postProcessesTakenIndices.splice(index, 1);
  6253. }
  6254. }
  6255. else {
  6256. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6257. for (i = 0; i < atIndices.length; i++) {
  6258. var foundPostProcess = this._postProcesses[atIndices[i]];
  6259. if (foundPostProcess !== postProcess) {
  6260. result.push(i);
  6261. continue;
  6262. }
  6263. delete this._postProcesses[atIndices[i]];
  6264. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6265. this._postProcessesTakenIndices.splice(index, 1);
  6266. }
  6267. }
  6268. return result;
  6269. };
  6270. Camera.prototype.getWorldMatrix = function () {
  6271. if (!this._worldMatrix) {
  6272. this._worldMatrix = BABYLON.Matrix.Identity();
  6273. }
  6274. var viewMatrix = this.getViewMatrix();
  6275. viewMatrix.invertToRef(this._worldMatrix);
  6276. return this._worldMatrix;
  6277. };
  6278. Camera.prototype._getViewMatrix = function () {
  6279. return BABYLON.Matrix.Identity();
  6280. };
  6281. Camera.prototype.getViewMatrix = function () {
  6282. this._computedViewMatrix = this._computeViewMatrix();
  6283. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6284. return this._computedViewMatrix;
  6285. }
  6286. if (!this._worldMatrix) {
  6287. this._worldMatrix = BABYLON.Matrix.Identity();
  6288. }
  6289. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6290. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6291. this._computedViewMatrix.invert();
  6292. this._currentRenderId = this.getScene().getRenderId();
  6293. return this._computedViewMatrix;
  6294. };
  6295. Camera.prototype._computeViewMatrix = function (force) {
  6296. if (!force && this._isSynchronizedViewMatrix()) {
  6297. return this._computedViewMatrix;
  6298. }
  6299. this._computedViewMatrix = this._getViewMatrix();
  6300. if (!this.parent || !this.parent.getWorldMatrix) {
  6301. this._currentRenderId = this.getScene().getRenderId();
  6302. }
  6303. return this._computedViewMatrix;
  6304. };
  6305. Camera.prototype.getProjectionMatrix = function (force) {
  6306. if (!force && this._isSynchronizedProjectionMatrix()) {
  6307. return this._projectionMatrix;
  6308. }
  6309. var engine = this.getEngine();
  6310. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6311. if (this.minZ <= 0) {
  6312. this.minZ = 0.1;
  6313. }
  6314. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6315. return this._projectionMatrix;
  6316. }
  6317. var halfWidth = engine.getRenderWidth() / 2.0;
  6318. var halfHeight = engine.getRenderHeight() / 2.0;
  6319. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6320. return this._projectionMatrix;
  6321. };
  6322. Camera.prototype.dispose = function () {
  6323. // Remove from scene
  6324. var index = this.getScene().cameras.indexOf(this);
  6325. this.getScene().cameras.splice(index, 1);
  6326. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6327. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6328. }
  6329. };
  6330. // Statics
  6331. Camera.PERSPECTIVE_CAMERA = 0;
  6332. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6333. return Camera;
  6334. })(BABYLON.Node);
  6335. BABYLON.Camera = Camera;
  6336. })(BABYLON || (BABYLON = {}));
  6337. //# sourceMappingURL=babylon.camera.js.map
  6338. var BABYLON;
  6339. (function (BABYLON) {
  6340. var TargetCamera = (function (_super) {
  6341. __extends(TargetCamera, _super);
  6342. function TargetCamera(name, position, scene) {
  6343. _super.call(this, name, position, scene);
  6344. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6345. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6346. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6347. this.speed = 2.0;
  6348. this.noRotationConstraint = false;
  6349. this.lockedTarget = null;
  6350. this._currentTarget = BABYLON.Vector3.Zero();
  6351. this._viewMatrix = BABYLON.Matrix.Zero();
  6352. this._camMatrix = BABYLON.Matrix.Zero();
  6353. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6354. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6355. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6356. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6357. this._lookAtTemp = BABYLON.Matrix.Zero();
  6358. this._tempMatrix = BABYLON.Matrix.Zero();
  6359. }
  6360. TargetCamera.prototype._getLockedTargetPosition = function () {
  6361. if (!this.lockedTarget) {
  6362. return null;
  6363. }
  6364. return this.lockedTarget.position || this.lockedTarget;
  6365. };
  6366. // Cache
  6367. TargetCamera.prototype._initCache = function () {
  6368. _super.prototype._initCache.call(this);
  6369. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6370. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6371. };
  6372. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6373. if (!ignoreParentClass) {
  6374. _super.prototype._updateCache.call(this);
  6375. }
  6376. var lockedTargetPosition = this._getLockedTargetPosition();
  6377. if (!lockedTargetPosition) {
  6378. this._cache.lockedTarget = null;
  6379. }
  6380. else {
  6381. if (!this._cache.lockedTarget) {
  6382. this._cache.lockedTarget = lockedTargetPosition.clone();
  6383. }
  6384. else {
  6385. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6386. }
  6387. }
  6388. this._cache.rotation.copyFrom(this.rotation);
  6389. };
  6390. // Synchronized
  6391. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6392. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6393. return false;
  6394. }
  6395. var lockedTargetPosition = this._getLockedTargetPosition();
  6396. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6397. };
  6398. // Methods
  6399. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6400. var engine = this.getEngine();
  6401. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6402. };
  6403. // Target
  6404. TargetCamera.prototype.setTarget = function (target) {
  6405. this.upVector.normalize();
  6406. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6407. this._camMatrix.invert();
  6408. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6409. var vDir = target.subtract(this.position);
  6410. if (vDir.x >= 0.0) {
  6411. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6412. }
  6413. else {
  6414. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6415. }
  6416. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6417. if (isNaN(this.rotation.x)) {
  6418. this.rotation.x = 0;
  6419. }
  6420. if (isNaN(this.rotation.y)) {
  6421. this.rotation.y = 0;
  6422. }
  6423. if (isNaN(this.rotation.z)) {
  6424. this.rotation.z = 0;
  6425. }
  6426. };
  6427. TargetCamera.prototype.getTarget = function () {
  6428. return this._currentTarget;
  6429. };
  6430. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6431. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6432. };
  6433. TargetCamera.prototype._updatePosition = function () {
  6434. this.position.addInPlace(this.cameraDirection);
  6435. };
  6436. TargetCamera.prototype._update = function () {
  6437. var needToMove = this._decideIfNeedsToMove();
  6438. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6439. // Move
  6440. if (needToMove) {
  6441. this._updatePosition();
  6442. }
  6443. // Rotate
  6444. if (needToRotate) {
  6445. this.rotation.x += this.cameraRotation.x;
  6446. this.rotation.y += this.cameraRotation.y;
  6447. if (!this.noRotationConstraint) {
  6448. var limit = (Math.PI / 2) * 0.95;
  6449. if (this.rotation.x > limit)
  6450. this.rotation.x = limit;
  6451. if (this.rotation.x < -limit)
  6452. this.rotation.x = -limit;
  6453. }
  6454. }
  6455. // Inertia
  6456. if (needToMove) {
  6457. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6458. this.cameraDirection.x = 0;
  6459. }
  6460. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6461. this.cameraDirection.y = 0;
  6462. }
  6463. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6464. this.cameraDirection.z = 0;
  6465. }
  6466. this.cameraDirection.scaleInPlace(this.inertia);
  6467. }
  6468. if (needToRotate) {
  6469. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6470. this.cameraRotation.x = 0;
  6471. }
  6472. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6473. this.cameraRotation.y = 0;
  6474. }
  6475. this.cameraRotation.scaleInPlace(this.inertia);
  6476. }
  6477. };
  6478. TargetCamera.prototype._getViewMatrix = function () {
  6479. if (!this.lockedTarget) {
  6480. // Compute
  6481. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6482. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6483. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6484. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6485. this._lookAtTemp.invert();
  6486. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6487. }
  6488. else {
  6489. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6490. }
  6491. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6492. // Computing target and final matrix
  6493. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6494. }
  6495. else {
  6496. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6497. }
  6498. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6499. return this._viewMatrix;
  6500. };
  6501. return TargetCamera;
  6502. })(BABYLON.Camera);
  6503. BABYLON.TargetCamera = TargetCamera;
  6504. })(BABYLON || (BABYLON = {}));
  6505. //# sourceMappingURL=babylon.targetCamera.js.map
  6506. var BABYLON;
  6507. (function (BABYLON) {
  6508. var FollowCamera = (function (_super) {
  6509. __extends(FollowCamera, _super);
  6510. function FollowCamera(name, position, scene) {
  6511. _super.call(this, name, position, scene);
  6512. this.radius = 12;
  6513. this.rotationOffset = 0;
  6514. this.heightOffset = 4;
  6515. this.cameraAcceleration = 0.05;
  6516. this.maxCameraSpeed = 20;
  6517. }
  6518. FollowCamera.prototype.getRadians = function (degrees) {
  6519. return degrees * Math.PI / 180;
  6520. };
  6521. FollowCamera.prototype.follow = function (cameraTarget) {
  6522. if (!cameraTarget)
  6523. return;
  6524. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6525. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6526. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6527. var dx = targetX - this.position.x;
  6528. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6529. var dz = (targetZ) - this.position.z;
  6530. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6531. var vy = dy * this.cameraAcceleration;
  6532. var vz = dz * this.cameraAcceleration * 2;
  6533. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6534. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6535. }
  6536. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6537. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6538. }
  6539. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6540. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6541. }
  6542. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6543. this.setTarget(cameraTarget.position);
  6544. };
  6545. FollowCamera.prototype._update = function () {
  6546. _super.prototype._update.call(this);
  6547. this.follow(this.target);
  6548. };
  6549. return FollowCamera;
  6550. })(BABYLON.TargetCamera);
  6551. BABYLON.FollowCamera = FollowCamera;
  6552. })(BABYLON || (BABYLON = {}));
  6553. //# sourceMappingURL=babylon.followCamera.js.map
  6554. var BABYLON;
  6555. (function (BABYLON) {
  6556. var FreeCamera = (function (_super) {
  6557. __extends(FreeCamera, _super);
  6558. function FreeCamera(name, position, scene) {
  6559. _super.call(this, name, position, scene);
  6560. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6561. this.keysUp = [38];
  6562. this.keysDown = [40];
  6563. this.keysLeft = [37];
  6564. this.keysRight = [39];
  6565. this.checkCollisions = false;
  6566. this.applyGravity = false;
  6567. this.angularSensibility = 2000.0;
  6568. this._keys = [];
  6569. this._collider = new BABYLON.Collider();
  6570. this._needMoveForGravity = true;
  6571. this._oldPosition = BABYLON.Vector3.Zero();
  6572. this._diffPosition = BABYLON.Vector3.Zero();
  6573. this._newPosition = BABYLON.Vector3.Zero();
  6574. }
  6575. // Controls
  6576. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6577. var _this = this;
  6578. var previousPosition;
  6579. var engine = this.getEngine();
  6580. if (this._attachedElement) {
  6581. return;
  6582. }
  6583. this._attachedElement = element;
  6584. if (this._onMouseDown === undefined) {
  6585. this._onMouseDown = function (evt) {
  6586. previousPosition = {
  6587. x: evt.clientX,
  6588. y: evt.clientY
  6589. };
  6590. if (!noPreventDefault) {
  6591. evt.preventDefault();
  6592. }
  6593. };
  6594. this._onMouseUp = function (evt) {
  6595. previousPosition = null;
  6596. if (!noPreventDefault) {
  6597. evt.preventDefault();
  6598. }
  6599. };
  6600. this._onMouseOut = function (evt) {
  6601. previousPosition = null;
  6602. _this._keys = [];
  6603. if (!noPreventDefault) {
  6604. evt.preventDefault();
  6605. }
  6606. };
  6607. this._onMouseMove = function (evt) {
  6608. if (!previousPosition && !engine.isPointerLock) {
  6609. return;
  6610. }
  6611. var offsetX;
  6612. var offsetY;
  6613. if (!engine.isPointerLock) {
  6614. offsetX = evt.clientX - previousPosition.x;
  6615. offsetY = evt.clientY - previousPosition.y;
  6616. }
  6617. else {
  6618. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6619. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6620. }
  6621. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6622. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6623. previousPosition = {
  6624. x: evt.clientX,
  6625. y: evt.clientY
  6626. };
  6627. if (!noPreventDefault) {
  6628. evt.preventDefault();
  6629. }
  6630. };
  6631. this._onKeyDown = function (evt) {
  6632. 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) {
  6633. var index = _this._keys.indexOf(evt.keyCode);
  6634. if (index === -1) {
  6635. _this._keys.push(evt.keyCode);
  6636. }
  6637. if (!noPreventDefault) {
  6638. evt.preventDefault();
  6639. }
  6640. }
  6641. };
  6642. this._onKeyUp = function (evt) {
  6643. 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) {
  6644. var index = _this._keys.indexOf(evt.keyCode);
  6645. if (index >= 0) {
  6646. _this._keys.splice(index, 1);
  6647. }
  6648. if (!noPreventDefault) {
  6649. evt.preventDefault();
  6650. }
  6651. }
  6652. };
  6653. this._onLostFocus = function () {
  6654. _this._keys = [];
  6655. };
  6656. this._reset = function () {
  6657. _this._keys = [];
  6658. previousPosition = null;
  6659. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6660. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6661. };
  6662. }
  6663. element.addEventListener("mousedown", this._onMouseDown, false);
  6664. element.addEventListener("mouseup", this._onMouseUp, false);
  6665. element.addEventListener("mouseout", this._onMouseOut, false);
  6666. element.addEventListener("mousemove", this._onMouseMove, false);
  6667. BABYLON.Tools.RegisterTopRootEvents([
  6668. { name: "keydown", handler: this._onKeyDown },
  6669. { name: "keyup", handler: this._onKeyUp },
  6670. { name: "blur", handler: this._onLostFocus }
  6671. ]);
  6672. };
  6673. FreeCamera.prototype.detachControl = function (element) {
  6674. if (this._attachedElement != element) {
  6675. return;
  6676. }
  6677. element.removeEventListener("mousedown", this._onMouseDown);
  6678. element.removeEventListener("mouseup", this._onMouseUp);
  6679. element.removeEventListener("mouseout", this._onMouseOut);
  6680. element.removeEventListener("mousemove", this._onMouseMove);
  6681. BABYLON.Tools.UnregisterTopRootEvents([
  6682. { name: "keydown", handler: this._onKeyDown },
  6683. { name: "keyup", handler: this._onKeyUp },
  6684. { name: "blur", handler: this._onLostFocus }
  6685. ]);
  6686. this._attachedElement = null;
  6687. if (this._reset) {
  6688. this._reset();
  6689. }
  6690. };
  6691. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6692. var globalPosition;
  6693. if (this.parent) {
  6694. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6695. }
  6696. else {
  6697. globalPosition = this.position;
  6698. }
  6699. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6700. this._collider.radius = this.ellipsoid;
  6701. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6702. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6703. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6704. this.position.addInPlace(this._diffPosition);
  6705. if (this.onCollide) {
  6706. this.onCollide(this._collider.collidedMesh);
  6707. }
  6708. }
  6709. };
  6710. FreeCamera.prototype._checkInputs = function () {
  6711. if (!this._localDirection) {
  6712. this._localDirection = BABYLON.Vector3.Zero();
  6713. this._transformedDirection = BABYLON.Vector3.Zero();
  6714. }
  6715. for (var index = 0; index < this._keys.length; index++) {
  6716. var keyCode = this._keys[index];
  6717. var speed = this._computeLocalCameraSpeed();
  6718. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6719. this._localDirection.copyFromFloats(-speed, 0, 0);
  6720. }
  6721. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6722. this._localDirection.copyFromFloats(0, 0, speed);
  6723. }
  6724. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6725. this._localDirection.copyFromFloats(speed, 0, 0);
  6726. }
  6727. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6728. this._localDirection.copyFromFloats(0, 0, -speed);
  6729. }
  6730. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6731. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6732. this.cameraDirection.addInPlace(this._transformedDirection);
  6733. }
  6734. };
  6735. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6736. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6737. };
  6738. FreeCamera.prototype._updatePosition = function () {
  6739. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6740. this._collideWithWorld(this.cameraDirection);
  6741. if (this.applyGravity) {
  6742. var oldPosition = this.position;
  6743. this._collideWithWorld(this.getScene().gravity);
  6744. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6745. }
  6746. }
  6747. else {
  6748. this.position.addInPlace(this.cameraDirection);
  6749. }
  6750. };
  6751. FreeCamera.prototype._update = function () {
  6752. this._checkInputs();
  6753. _super.prototype._update.call(this);
  6754. };
  6755. return FreeCamera;
  6756. })(BABYLON.TargetCamera);
  6757. BABYLON.FreeCamera = FreeCamera;
  6758. })(BABYLON || (BABYLON = {}));
  6759. //# sourceMappingURL=babylon.freeCamera.js.map
  6760. var BABYLON;
  6761. (function (BABYLON) {
  6762. // We're mainly based on the logic defined into the FreeCamera code
  6763. var TouchCamera = (function (_super) {
  6764. __extends(TouchCamera, _super);
  6765. function TouchCamera(name, position, scene) {
  6766. _super.call(this, name, position, scene);
  6767. this._offsetX = null;
  6768. this._offsetY = null;
  6769. this._pointerCount = 0;
  6770. this._pointerPressed = [];
  6771. this.angularSensibility = 200000.0;
  6772. this.moveSensibility = 500.0;
  6773. }
  6774. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6775. var _this = this;
  6776. var previousPosition;
  6777. if (this._attachedCanvas) {
  6778. return;
  6779. }
  6780. this._attachedCanvas = canvas;
  6781. if (this._onPointerDown === undefined) {
  6782. this._onPointerDown = function (evt) {
  6783. if (!noPreventDefault) {
  6784. evt.preventDefault();
  6785. }
  6786. _this._pointerPressed.push(evt.pointerId);
  6787. if (_this._pointerPressed.length !== 1) {
  6788. return;
  6789. }
  6790. previousPosition = {
  6791. x: evt.clientX,
  6792. y: evt.clientY
  6793. };
  6794. };
  6795. this._onPointerUp = function (evt) {
  6796. if (!noPreventDefault) {
  6797. evt.preventDefault();
  6798. }
  6799. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6800. if (index === -1) {
  6801. return;
  6802. }
  6803. _this._pointerPressed.splice(index, 1);
  6804. if (index != 0) {
  6805. return;
  6806. }
  6807. previousPosition = null;
  6808. _this._offsetX = null;
  6809. _this._offsetY = null;
  6810. };
  6811. this._onPointerMove = function (evt) {
  6812. if (!noPreventDefault) {
  6813. evt.preventDefault();
  6814. }
  6815. if (!previousPosition) {
  6816. return;
  6817. }
  6818. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6819. if (index != 0) {
  6820. return;
  6821. }
  6822. _this._offsetX = evt.clientX - previousPosition.x;
  6823. _this._offsetY = -(evt.clientY - previousPosition.y);
  6824. };
  6825. this._onLostFocus = function () {
  6826. _this._offsetX = null;
  6827. _this._offsetY = null;
  6828. };
  6829. }
  6830. canvas.addEventListener("pointerdown", this._onPointerDown);
  6831. canvas.addEventListener("pointerup", this._onPointerUp);
  6832. canvas.addEventListener("pointerout", this._onPointerUp);
  6833. canvas.addEventListener("pointermove", this._onPointerMove);
  6834. BABYLON.Tools.RegisterTopRootEvents([
  6835. { name: "blur", handler: this._onLostFocus }
  6836. ]);
  6837. };
  6838. TouchCamera.prototype.detachControl = function (canvas) {
  6839. if (this._attachedCanvas != canvas) {
  6840. return;
  6841. }
  6842. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6843. canvas.removeEventListener("pointerup", this._onPointerUp);
  6844. canvas.removeEventListener("pointerout", this._onPointerUp);
  6845. canvas.removeEventListener("pointermove", this._onPointerMove);
  6846. BABYLON.Tools.UnregisterTopRootEvents([
  6847. { name: "blur", handler: this._onLostFocus }
  6848. ]);
  6849. this._attachedCanvas = null;
  6850. };
  6851. TouchCamera.prototype._checkInputs = function () {
  6852. if (!this._offsetX) {
  6853. return;
  6854. }
  6855. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6856. if (this._pointerPressed.length > 1) {
  6857. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6858. }
  6859. else {
  6860. var speed = this._computeLocalCameraSpeed();
  6861. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6862. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6863. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6864. }
  6865. };
  6866. return TouchCamera;
  6867. })(BABYLON.FreeCamera);
  6868. BABYLON.TouchCamera = TouchCamera;
  6869. })(BABYLON || (BABYLON = {}));
  6870. //# sourceMappingURL=babylon.touchCamera.js.map
  6871. var BABYLON;
  6872. (function (BABYLON) {
  6873. // We're mainly based on the logic defined into the FreeCamera code
  6874. var DeviceOrientationCamera = (function (_super) {
  6875. __extends(DeviceOrientationCamera, _super);
  6876. function DeviceOrientationCamera(name, position, scene) {
  6877. var _this = this;
  6878. _super.call(this, name, position, scene);
  6879. this._offsetX = null;
  6880. this._offsetY = null;
  6881. this._orientationGamma = 0;
  6882. this._orientationBeta = 0;
  6883. this._initialOrientationGamma = 0;
  6884. this._initialOrientationBeta = 0;
  6885. this.angularSensibility = 10000.0;
  6886. this.moveSensibility = 50.0;
  6887. window.addEventListener("resize", function () {
  6888. _this._initialOrientationGamma = null;
  6889. }, false);
  6890. }
  6891. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6892. var _this = this;
  6893. if (this._attachedCanvas) {
  6894. return;
  6895. }
  6896. this._attachedCanvas = canvas;
  6897. if (!this._orientationChanged) {
  6898. this._orientationChanged = function (evt) {
  6899. if (!_this._initialOrientationGamma) {
  6900. _this._initialOrientationGamma = evt.gamma;
  6901. _this._initialOrientationBeta = evt.beta;
  6902. }
  6903. _this._orientationGamma = evt.gamma;
  6904. _this._orientationBeta = evt.beta;
  6905. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6906. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6907. };
  6908. }
  6909. window.addEventListener("deviceorientation", this._orientationChanged);
  6910. };
  6911. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6912. if (this._attachedCanvas != canvas) {
  6913. return;
  6914. }
  6915. window.removeEventListener("deviceorientation", this._orientationChanged);
  6916. this._attachedCanvas = null;
  6917. this._orientationGamma = 0;
  6918. this._orientationBeta = 0;
  6919. this._initialOrientationGamma = 0;
  6920. this._initialOrientationBeta = 0;
  6921. };
  6922. DeviceOrientationCamera.prototype._checkInputs = function () {
  6923. if (!this._offsetX) {
  6924. return;
  6925. }
  6926. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6927. var speed = this._computeLocalCameraSpeed();
  6928. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6929. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6930. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6931. };
  6932. return DeviceOrientationCamera;
  6933. })(BABYLON.FreeCamera);
  6934. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6935. })(BABYLON || (BABYLON = {}));
  6936. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6937. var BABYLON;
  6938. (function (BABYLON) {
  6939. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6940. var ArcRotateCamera = (function (_super) {
  6941. __extends(ArcRotateCamera, _super);
  6942. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6943. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6944. this.alpha = alpha;
  6945. this.beta = beta;
  6946. this.radius = radius;
  6947. this.target = target;
  6948. this.inertialAlphaOffset = 0;
  6949. this.inertialBetaOffset = 0;
  6950. this.inertialRadiusOffset = 0;
  6951. this.lowerAlphaLimit = null;
  6952. this.upperAlphaLimit = null;
  6953. this.lowerBetaLimit = 0.01;
  6954. this.upperBetaLimit = Math.PI;
  6955. this.lowerRadiusLimit = null;
  6956. this.upperRadiusLimit = null;
  6957. this.angularSensibility = 1000.0;
  6958. this.wheelPrecision = 3.0;
  6959. this.keysUp = [38];
  6960. this.keysDown = [40];
  6961. this.keysLeft = [37];
  6962. this.keysRight = [39];
  6963. this.zoomOnFactor = 1;
  6964. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6965. this._keys = [];
  6966. this._viewMatrix = new BABYLON.Matrix();
  6967. this.checkCollisions = false;
  6968. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6969. this._collider = new BABYLON.Collider();
  6970. this._previousPosition = BABYLON.Vector3.Zero();
  6971. this._collisionVelocity = BABYLON.Vector3.Zero();
  6972. this._newPosition = BABYLON.Vector3.Zero();
  6973. // Pinch
  6974. // value for pinch step scaling
  6975. // set to 20 by default
  6976. this.pinchPrecision = 20;
  6977. this.getViewMatrix();
  6978. }
  6979. ArcRotateCamera.prototype._getTargetPosition = function () {
  6980. return this.target.position || this.target;
  6981. };
  6982. // Cache
  6983. ArcRotateCamera.prototype._initCache = function () {
  6984. _super.prototype._initCache.call(this);
  6985. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6986. this._cache.alpha = undefined;
  6987. this._cache.beta = undefined;
  6988. this._cache.radius = undefined;
  6989. this._cache.targetScreenOffset = undefined;
  6990. };
  6991. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6992. if (!ignoreParentClass) {
  6993. _super.prototype._updateCache.call(this);
  6994. }
  6995. this._cache.target.copyFrom(this._getTargetPosition());
  6996. this._cache.alpha = this.alpha;
  6997. this._cache.beta = this.beta;
  6998. this._cache.radius = this.radius;
  6999. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7000. };
  7001. // Synchronized
  7002. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7003. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7004. return false;
  7005. 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);
  7006. };
  7007. // Methods
  7008. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7009. var _this = this;
  7010. var previousPosition;
  7011. var pointerId;
  7012. // to know if pinch started
  7013. var pinchStarted = false;
  7014. // two pinch point on X
  7015. // that will use for find if user action is pinch open or pinch close
  7016. var pinchPointX1, pinchPointX2;
  7017. if (this._attachedElement) {
  7018. return;
  7019. }
  7020. this._attachedElement = element;
  7021. var engine = this.getEngine();
  7022. if (this._onPointerDown === undefined) {
  7023. this._onPointerDown = function (evt) {
  7024. if (pointerId) {
  7025. return;
  7026. }
  7027. pointerId = evt.pointerId;
  7028. previousPosition = {
  7029. x: evt.clientX,
  7030. y: evt.clientY
  7031. };
  7032. if (!noPreventDefault) {
  7033. evt.preventDefault();
  7034. }
  7035. };
  7036. this._onPointerUp = function (evt) {
  7037. previousPosition = null;
  7038. pointerId = null;
  7039. if (!noPreventDefault) {
  7040. evt.preventDefault();
  7041. }
  7042. };
  7043. this._onPointerMove = function (evt) {
  7044. if (!previousPosition) {
  7045. return;
  7046. }
  7047. if (pointerId !== evt.pointerId) {
  7048. return;
  7049. }
  7050. // return pinch is started
  7051. if (pinchStarted) {
  7052. return;
  7053. }
  7054. var offsetX = evt.clientX - previousPosition.x;
  7055. var offsetY = evt.clientY - previousPosition.y;
  7056. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7057. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7058. previousPosition = {
  7059. x: evt.clientX,
  7060. y: evt.clientY
  7061. };
  7062. if (!noPreventDefault) {
  7063. evt.preventDefault();
  7064. }
  7065. };
  7066. this._onMouseMove = function (evt) {
  7067. if (!engine.isPointerLock) {
  7068. return;
  7069. }
  7070. // return pinch is started
  7071. if (pinchStarted) {
  7072. return;
  7073. }
  7074. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7075. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7076. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7077. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7078. if (!noPreventDefault) {
  7079. evt.preventDefault();
  7080. }
  7081. };
  7082. this._wheel = function (event) {
  7083. var delta = 0;
  7084. if (event.wheelDelta) {
  7085. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7086. }
  7087. else if (event.detail) {
  7088. delta = -event.detail / _this.wheelPrecision;
  7089. }
  7090. if (delta)
  7091. _this.inertialRadiusOffset += delta;
  7092. if (event.preventDefault) {
  7093. if (!noPreventDefault) {
  7094. event.preventDefault();
  7095. }
  7096. }
  7097. };
  7098. this._onKeyDown = function (evt) {
  7099. 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) {
  7100. var index = _this._keys.indexOf(evt.keyCode);
  7101. if (index === -1) {
  7102. _this._keys.push(evt.keyCode);
  7103. }
  7104. if (evt.preventDefault) {
  7105. if (!noPreventDefault) {
  7106. evt.preventDefault();
  7107. }
  7108. }
  7109. }
  7110. };
  7111. this._onKeyUp = function (evt) {
  7112. 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) {
  7113. var index = _this._keys.indexOf(evt.keyCode);
  7114. if (index >= 0) {
  7115. _this._keys.splice(index, 1);
  7116. }
  7117. if (evt.preventDefault) {
  7118. if (!noPreventDefault) {
  7119. evt.preventDefault();
  7120. }
  7121. }
  7122. }
  7123. };
  7124. this._onLostFocus = function () {
  7125. _this._keys = [];
  7126. pointerId = null;
  7127. };
  7128. this._onGestureStart = function (e) {
  7129. if (window.MSGesture === undefined) {
  7130. return;
  7131. }
  7132. if (!_this._MSGestureHandler) {
  7133. _this._MSGestureHandler = new MSGesture();
  7134. _this._MSGestureHandler.target = element;
  7135. }
  7136. _this._MSGestureHandler.addPointer(e.pointerId);
  7137. };
  7138. this._onGesture = function (e) {
  7139. _this.radius *= e.scale;
  7140. if (e.preventDefault) {
  7141. if (!noPreventDefault) {
  7142. e.stopPropagation();
  7143. e.preventDefault();
  7144. }
  7145. }
  7146. };
  7147. this._reset = function () {
  7148. _this._keys = [];
  7149. _this.inertialAlphaOffset = 0;
  7150. _this.inertialBetaOffset = 0;
  7151. _this.inertialRadiusOffset = 0;
  7152. previousPosition = null;
  7153. pointerId = null;
  7154. };
  7155. this._touchStart = function (event) {
  7156. if (event.touches.length === 2) {
  7157. //-- start pinch if two fingers on the screen
  7158. pinchStarted = true;
  7159. _this._pinchStart(event);
  7160. }
  7161. };
  7162. this._touchMove = function (event) {
  7163. if (pinchStarted) {
  7164. //-- make scaling
  7165. _this._pinchMove(event);
  7166. }
  7167. };
  7168. this._touchEnd = function (event) {
  7169. if (pinchStarted) {
  7170. //-- end of pinch
  7171. _this._pinchEnd(event);
  7172. }
  7173. };
  7174. this._pinchStart = function (event) {
  7175. // save origin touch point
  7176. pinchPointX1 = event.touches[0].clientX;
  7177. pinchPointX2 = event.touches[1].clientX;
  7178. // block the camera
  7179. // if not it rotate around target during pinch
  7180. pinchStarted = true;
  7181. };
  7182. this._pinchMove = function (event) {
  7183. // variable for new camera's radius
  7184. var delta = 0;
  7185. // variables to know if pinch open or pinch close
  7186. var direction = 1;
  7187. var distanceXOrigine, distanceXNow;
  7188. if (event.touches.length !== 2)
  7189. return;
  7190. // calculate absolute distances of the two fingers
  7191. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7192. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7193. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7194. if (distanceXNow < distanceXOrigine) {
  7195. direction = -1;
  7196. }
  7197. // calculate new radius
  7198. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7199. // set new radius
  7200. _this.inertialRadiusOffset -= delta;
  7201. // save origin touch point
  7202. pinchPointX1 = event.touches[0].clientX;
  7203. pinchPointX2 = event.touches[1].clientX;
  7204. };
  7205. this._pinchEnd = function (event) {
  7206. // cancel pinch and deblock camera rotation
  7207. pinchStarted = false;
  7208. };
  7209. }
  7210. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7211. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7212. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7213. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7214. element.addEventListener("mousemove", this._onMouseMove, false);
  7215. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7216. element.addEventListener("MSGestureChange", this._onGesture, false);
  7217. element.addEventListener('mousewheel', this._wheel, false);
  7218. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7219. // pinch
  7220. element.addEventListener('touchstart', this._touchStart, false);
  7221. element.addEventListener('touchmove', this._touchMove, false);
  7222. element.addEventListener('touchend', this._touchEnd, false);
  7223. BABYLON.Tools.RegisterTopRootEvents([
  7224. { name: "keydown", handler: this._onKeyDown },
  7225. { name: "keyup", handler: this._onKeyUp },
  7226. { name: "blur", handler: this._onLostFocus }
  7227. ]);
  7228. };
  7229. ArcRotateCamera.prototype.detachControl = function (element) {
  7230. if (this._attachedElement != element) {
  7231. return;
  7232. }
  7233. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7234. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7235. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7236. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7237. element.removeEventListener("mousemove", this._onMouseMove);
  7238. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7239. element.removeEventListener("MSGestureChange", this._onGesture);
  7240. element.removeEventListener('mousewheel', this._wheel);
  7241. element.removeEventListener('DOMMouseScroll', this._wheel);
  7242. // pinch
  7243. element.removeEventListener('touchstart', this._touchStart);
  7244. element.removeEventListener('touchmove', this._touchMove);
  7245. element.removeEventListener('touchend', this._touchEnd);
  7246. BABYLON.Tools.UnregisterTopRootEvents([
  7247. { name: "keydown", handler: this._onKeyDown },
  7248. { name: "keyup", handler: this._onKeyUp },
  7249. { name: "blur", handler: this._onLostFocus }
  7250. ]);
  7251. this._MSGestureHandler = null;
  7252. this._attachedElement = null;
  7253. if (this._reset) {
  7254. this._reset();
  7255. }
  7256. };
  7257. ArcRotateCamera.prototype._update = function () {
  7258. for (var index = 0; index < this._keys.length; index++) {
  7259. var keyCode = this._keys[index];
  7260. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7261. this.inertialAlphaOffset -= 0.01;
  7262. }
  7263. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7264. this.inertialBetaOffset -= 0.01;
  7265. }
  7266. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7267. this.inertialAlphaOffset += 0.01;
  7268. }
  7269. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7270. this.inertialBetaOffset += 0.01;
  7271. }
  7272. }
  7273. // Inertia
  7274. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7275. this.alpha += this.inertialAlphaOffset;
  7276. this.beta += this.inertialBetaOffset;
  7277. this.radius -= this.inertialRadiusOffset;
  7278. this.inertialAlphaOffset *= this.inertia;
  7279. this.inertialBetaOffset *= this.inertia;
  7280. this.inertialRadiusOffset *= this.inertia;
  7281. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7282. this.inertialAlphaOffset = 0;
  7283. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7284. this.inertialBetaOffset = 0;
  7285. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7286. this.inertialRadiusOffset = 0;
  7287. }
  7288. // Limits
  7289. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7290. this.alpha = this.lowerAlphaLimit;
  7291. }
  7292. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7293. this.alpha = this.upperAlphaLimit;
  7294. }
  7295. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7296. this.beta = this.lowerBetaLimit;
  7297. }
  7298. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7299. this.beta = this.upperBetaLimit;
  7300. }
  7301. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7302. this.radius = this.lowerRadiusLimit;
  7303. }
  7304. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7305. this.radius = this.upperRadiusLimit;
  7306. }
  7307. };
  7308. ArcRotateCamera.prototype.setPosition = function (position) {
  7309. var radiusv3 = position.subtract(this._getTargetPosition());
  7310. this.radius = radiusv3.length();
  7311. // Alpha
  7312. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7313. if (radiusv3.z < 0) {
  7314. this.alpha = 2 * Math.PI - this.alpha;
  7315. }
  7316. // Beta
  7317. this.beta = Math.acos(radiusv3.y / this.radius);
  7318. };
  7319. ArcRotateCamera.prototype._getViewMatrix = function () {
  7320. // Compute
  7321. var cosa = Math.cos(this.alpha);
  7322. var sina = Math.sin(this.alpha);
  7323. var cosb = Math.cos(this.beta);
  7324. var sinb = Math.sin(this.beta);
  7325. var target = this._getTargetPosition();
  7326. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7327. if (this.checkCollisions) {
  7328. this._collider.radius = this.collisionRadius;
  7329. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7330. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7331. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7332. this.position.copyFrom(this._previousPosition);
  7333. this.alpha = this._previousAlpha;
  7334. this.beta = this._previousBeta;
  7335. this.radius = this._previousRadius;
  7336. if (this.onCollide) {
  7337. this.onCollide(this._collider.collidedMesh);
  7338. }
  7339. }
  7340. }
  7341. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7342. this._previousAlpha = this.alpha;
  7343. this._previousBeta = this.beta;
  7344. this._previousRadius = this.radius;
  7345. this._previousPosition.copyFrom(this.position);
  7346. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7347. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7348. return this._viewMatrix;
  7349. };
  7350. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7351. meshes = meshes || this.getScene().meshes;
  7352. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7353. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7354. this.radius = distance * this.zoomOnFactor;
  7355. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7356. };
  7357. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7358. var meshesOrMinMaxVector;
  7359. var distance;
  7360. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7361. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7362. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7363. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7364. }
  7365. else {
  7366. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7367. distance = meshesOrMinMaxVectorAndDistance.distance;
  7368. }
  7369. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7370. this.maxZ = distance * 2;
  7371. };
  7372. return ArcRotateCamera;
  7373. })(BABYLON.Camera);
  7374. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7375. })(BABYLON || (BABYLON = {}));
  7376. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7377. (function (BABYLON) {
  7378. /**
  7379. * Represents a scene to be rendered by the engine.
  7380. * @see http://doc.babylonjs.com/page.php?p=21911
  7381. */
  7382. var Scene = (function () {
  7383. /**
  7384. * @constructor
  7385. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7386. */
  7387. function Scene(engine) {
  7388. // Members
  7389. this.autoClear = true;
  7390. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7391. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7392. this.forceWireframe = false;
  7393. this.forcePointsCloud = false;
  7394. this.forceShowBoundingBoxes = false;
  7395. this.animationsEnabled = true;
  7396. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  7397. // Fog
  7398. /**
  7399. * is fog enabled on this scene.
  7400. * @type {boolean}
  7401. */
  7402. this.fogEnabled = true;
  7403. this.fogMode = Scene.FOGMODE_NONE;
  7404. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7405. this.fogDensity = 0.1;
  7406. this.fogStart = 0;
  7407. this.fogEnd = 1000.0;
  7408. // Lights
  7409. /**
  7410. * is shadow enabled on this scene.
  7411. * @type {boolean}
  7412. */
  7413. this.shadowsEnabled = true;
  7414. /**
  7415. * is light enabled on this scene.
  7416. * @type {boolean}
  7417. */
  7418. this.lightsEnabled = true;
  7419. /**
  7420. * All of the lights added to this scene.
  7421. * @see BABYLON.Light
  7422. * @type {BABYLON.Light[]}
  7423. */
  7424. this.lights = new Array();
  7425. // Cameras
  7426. /**
  7427. * All of the cameras added to this scene.
  7428. * @see BABYLON.Camera
  7429. * @type {BABYLON.Camera[]}
  7430. */
  7431. this.cameras = new Array();
  7432. this.activeCameras = new Array();
  7433. // Meshes
  7434. /**
  7435. * All of the (abstract) meshes added to this scene.
  7436. * @see BABYLON.AbstractMesh
  7437. * @type {BABYLON.AbstractMesh[]}
  7438. */
  7439. this.meshes = new Array();
  7440. // Geometries
  7441. this._geometries = new Array();
  7442. this.materials = new Array();
  7443. this.multiMaterials = new Array();
  7444. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7445. // Textures
  7446. this.texturesEnabled = true;
  7447. this.textures = new Array();
  7448. // Particles
  7449. this.particlesEnabled = true;
  7450. this.particleSystems = new Array();
  7451. // Sprites
  7452. this.spriteManagers = new Array();
  7453. // Layers
  7454. this.layers = new Array();
  7455. // Skeletons
  7456. this.skeletonsEnabled = true;
  7457. this.skeletons = new Array();
  7458. // Lens flares
  7459. this.lensFlaresEnabled = true;
  7460. this.lensFlareSystems = new Array();
  7461. // Collisions
  7462. this.collisionsEnabled = true;
  7463. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7464. // Postprocesses
  7465. this.postProcessesEnabled = true;
  7466. // Customs render targets
  7467. this.renderTargetsEnabled = true;
  7468. this.customRenderTargets = new Array();
  7469. // Imported meshes
  7470. this.importedMeshesFiles = new Array();
  7471. this._actionManagers = new Array();
  7472. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7473. // Procedural textures
  7474. this.proceduralTexturesEnabled = true;
  7475. this._proceduralTextures = new Array();
  7476. this.soundTracks = new Array();
  7477. this._totalVertices = 0;
  7478. this._activeVertices = 0;
  7479. this._activeParticles = 0;
  7480. this._lastFrameDuration = 0;
  7481. this._evaluateActiveMeshesDuration = 0;
  7482. this._renderTargetsDuration = 0;
  7483. this._particlesDuration = 0;
  7484. this._renderDuration = 0;
  7485. this._spritesDuration = 0;
  7486. this._animationRatio = 0;
  7487. this._renderId = 0;
  7488. this._executeWhenReadyTimeoutId = -1;
  7489. this._toBeDisposed = new BABYLON.SmartArray(256);
  7490. this._onReadyCallbacks = new Array();
  7491. this._pendingData = []; //ANY
  7492. this._onBeforeRenderCallbacks = new Array();
  7493. this._onAfterRenderCallbacks = new Array();
  7494. this._activeMeshes = new BABYLON.SmartArray(256);
  7495. this._processedMaterials = new BABYLON.SmartArray(256);
  7496. this._renderTargets = new BABYLON.SmartArray(256);
  7497. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7498. this._activeSkeletons = new BABYLON.SmartArray(32);
  7499. this._activeBones = 0;
  7500. this._activeAnimatables = new Array();
  7501. this._transformMatrix = BABYLON.Matrix.Zero();
  7502. this._scaledPosition = BABYLON.Vector3.Zero();
  7503. this._scaledVelocity = BABYLON.Vector3.Zero();
  7504. this._engine = engine;
  7505. engine.scenes.push(this);
  7506. this._renderingManager = new BABYLON.RenderingManager(this);
  7507. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7508. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7509. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7510. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7511. this.attachControl();
  7512. this._debugLayer = new BABYLON.DebugLayer(this);
  7513. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7514. }
  7515. Object.defineProperty(Scene.prototype, "debugLayer", {
  7516. // Properties
  7517. get: function () {
  7518. return this._debugLayer;
  7519. },
  7520. enumerable: true,
  7521. configurable: true
  7522. });
  7523. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7524. /**
  7525. * The mesh that is currently under the pointer.
  7526. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7527. */
  7528. get: function () {
  7529. return this._meshUnderPointer;
  7530. },
  7531. enumerable: true,
  7532. configurable: true
  7533. });
  7534. Object.defineProperty(Scene.prototype, "pointerX", {
  7535. /**
  7536. * Current on-screen X position of the pointer
  7537. * @return {number} X position of the pointer
  7538. */
  7539. get: function () {
  7540. return this._pointerX;
  7541. },
  7542. enumerable: true,
  7543. configurable: true
  7544. });
  7545. Object.defineProperty(Scene.prototype, "pointerY", {
  7546. /**
  7547. * Current on-screen Y position of the pointer
  7548. * @return {number} Y position of the pointer
  7549. */
  7550. get: function () {
  7551. return this._pointerY;
  7552. },
  7553. enumerable: true,
  7554. configurable: true
  7555. });
  7556. Scene.prototype.getCachedMaterial = function () {
  7557. return this._cachedMaterial;
  7558. };
  7559. Scene.prototype.getBoundingBoxRenderer = function () {
  7560. return this._boundingBoxRenderer;
  7561. };
  7562. Scene.prototype.getOutlineRenderer = function () {
  7563. return this._outlineRenderer;
  7564. };
  7565. Scene.prototype.getEngine = function () {
  7566. return this._engine;
  7567. };
  7568. Scene.prototype.getTotalVertices = function () {
  7569. return this._totalVertices;
  7570. };
  7571. Scene.prototype.getActiveVertices = function () {
  7572. return this._activeVertices;
  7573. };
  7574. Scene.prototype.getActiveParticles = function () {
  7575. return this._activeParticles;
  7576. };
  7577. Scene.prototype.getActiveBones = function () {
  7578. return this._activeBones;
  7579. };
  7580. // Stats
  7581. Scene.prototype.getLastFrameDuration = function () {
  7582. return this._lastFrameDuration;
  7583. };
  7584. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7585. return this._evaluateActiveMeshesDuration;
  7586. };
  7587. Scene.prototype.getActiveMeshes = function () {
  7588. return this._activeMeshes;
  7589. };
  7590. Scene.prototype.getRenderTargetsDuration = function () {
  7591. return this._renderTargetsDuration;
  7592. };
  7593. Scene.prototype.getRenderDuration = function () {
  7594. return this._renderDuration;
  7595. };
  7596. Scene.prototype.getParticlesDuration = function () {
  7597. return this._particlesDuration;
  7598. };
  7599. Scene.prototype.getSpritesDuration = function () {
  7600. return this._spritesDuration;
  7601. };
  7602. Scene.prototype.getAnimationRatio = function () {
  7603. return this._animationRatio;
  7604. };
  7605. Scene.prototype.getRenderId = function () {
  7606. return this._renderId;
  7607. };
  7608. Scene.prototype._updatePointerPosition = function (evt) {
  7609. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7610. this._pointerX = evt.clientX - canvasRect.left;
  7611. this._pointerY = evt.clientY - canvasRect.top;
  7612. if (this.cameraToUseForPointers) {
  7613. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7614. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7615. }
  7616. };
  7617. // Pointers handling
  7618. Scene.prototype.attachControl = function () {
  7619. var _this = this;
  7620. this._onPointerMove = function (evt) {
  7621. var canvas = _this._engine.getRenderingCanvas();
  7622. _this._updatePointerPosition(evt);
  7623. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  7624. if (pickResult.hit) {
  7625. _this._meshUnderPointer = pickResult.pickedMesh;
  7626. _this.setPointerOverMesh(pickResult.pickedMesh);
  7627. canvas.style.cursor = "pointer";
  7628. }
  7629. else {
  7630. _this.setPointerOverMesh(null);
  7631. canvas.style.cursor = "";
  7632. _this._meshUnderPointer = null;
  7633. }
  7634. };
  7635. this._onPointerDown = function (evt) {
  7636. var predicate = null;
  7637. if (!_this.onPointerDown) {
  7638. predicate = function (mesh) {
  7639. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7640. };
  7641. }
  7642. _this._updatePointerPosition(evt);
  7643. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7644. if (pickResult.hit) {
  7645. if (pickResult.pickedMesh.actionManager) {
  7646. switch (evt.button) {
  7647. case 0:
  7648. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7649. break;
  7650. case 1:
  7651. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7652. break;
  7653. case 2:
  7654. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7655. break;
  7656. }
  7657. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7658. }
  7659. }
  7660. if (_this.onPointerDown) {
  7661. _this.onPointerDown(evt, pickResult);
  7662. }
  7663. };
  7664. this._onKeyDown = function (evt) {
  7665. if (_this.actionManager) {
  7666. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7667. }
  7668. };
  7669. this._onKeyUp = function (evt) {
  7670. if (_this.actionManager) {
  7671. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7672. }
  7673. };
  7674. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7675. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7676. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7677. window.addEventListener("keydown", this._onKeyDown, false);
  7678. window.addEventListener("keyup", this._onKeyUp, false);
  7679. };
  7680. Scene.prototype.detachControl = function () {
  7681. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7682. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7683. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7684. window.removeEventListener("keydown", this._onKeyDown);
  7685. window.removeEventListener("keyup", this._onKeyUp);
  7686. };
  7687. // Ready
  7688. Scene.prototype.isReady = function () {
  7689. if (this._pendingData.length > 0) {
  7690. return false;
  7691. }
  7692. for (var index = 0; index < this._geometries.length; index++) {
  7693. var geometry = this._geometries[index];
  7694. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7695. return false;
  7696. }
  7697. }
  7698. for (index = 0; index < this.meshes.length; index++) {
  7699. var mesh = this.meshes[index];
  7700. if (!mesh.isReady()) {
  7701. return false;
  7702. }
  7703. var mat = mesh.material;
  7704. if (mat) {
  7705. if (!mat.isReady(mesh)) {
  7706. return false;
  7707. }
  7708. }
  7709. }
  7710. return true;
  7711. };
  7712. Scene.prototype.resetCachedMaterial = function () {
  7713. this._cachedMaterial = null;
  7714. };
  7715. Scene.prototype.registerBeforeRender = function (func) {
  7716. this._onBeforeRenderCallbacks.push(func);
  7717. };
  7718. Scene.prototype.unregisterBeforeRender = function (func) {
  7719. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7720. if (index > -1) {
  7721. this._onBeforeRenderCallbacks.splice(index, 1);
  7722. }
  7723. };
  7724. Scene.prototype.registerAfterRender = function (func) {
  7725. this._onAfterRenderCallbacks.push(func);
  7726. };
  7727. Scene.prototype.unregisterAfterRender = function (func) {
  7728. var index = this._onAfterRenderCallbacks.indexOf(func);
  7729. if (index > -1) {
  7730. this._onAfterRenderCallbacks.splice(index, 1);
  7731. }
  7732. };
  7733. Scene.prototype._addPendingData = function (data) {
  7734. this._pendingData.push(data);
  7735. };
  7736. Scene.prototype._removePendingData = function (data) {
  7737. var index = this._pendingData.indexOf(data);
  7738. if (index !== -1) {
  7739. this._pendingData.splice(index, 1);
  7740. }
  7741. };
  7742. Scene.prototype.getWaitingItemsCount = function () {
  7743. return this._pendingData.length;
  7744. };
  7745. /**
  7746. * Registers a function to be executed when the scene is ready.
  7747. * @param {Function} func - the function to be executed.
  7748. */
  7749. Scene.prototype.executeWhenReady = function (func) {
  7750. var _this = this;
  7751. this._onReadyCallbacks.push(func);
  7752. if (this._executeWhenReadyTimeoutId !== -1) {
  7753. return;
  7754. }
  7755. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7756. _this._checkIsReady();
  7757. }, 150);
  7758. };
  7759. Scene.prototype._checkIsReady = function () {
  7760. var _this = this;
  7761. if (this.isReady()) {
  7762. this._onReadyCallbacks.forEach(function (func) {
  7763. func();
  7764. });
  7765. this._onReadyCallbacks = [];
  7766. this._executeWhenReadyTimeoutId = -1;
  7767. return;
  7768. }
  7769. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7770. _this._checkIsReady();
  7771. }, 150);
  7772. };
  7773. // Animations
  7774. /**
  7775. * Will start the animation sequence of a given target
  7776. * @param target - the target
  7777. * @param {number} from - from which frame should animation start
  7778. * @param {number} to - till which frame should animation run.
  7779. * @param {boolean} [loop] - should the animation loop
  7780. * @param {number} [speedRatio] - the speed in which to run the animation
  7781. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  7782. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  7783. * @return {BABYLON.Animatable} the animatable object created for this animation
  7784. * @see BABYLON.Animatable
  7785. * @see http://doc.babylonjs.com/page.php?p=22081
  7786. */
  7787. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7788. if (speedRatio === undefined) {
  7789. speedRatio = 1.0;
  7790. }
  7791. this.stopAnimation(target);
  7792. if (!animatable) {
  7793. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7794. }
  7795. // Local animations
  7796. if (target.animations) {
  7797. animatable.appendAnimations(target, target.animations);
  7798. }
  7799. // Children animations
  7800. if (target.getAnimatables) {
  7801. var animatables = target.getAnimatables();
  7802. for (var index = 0; index < animatables.length; index++) {
  7803. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7804. }
  7805. }
  7806. return animatable;
  7807. };
  7808. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7809. if (speedRatio === undefined) {
  7810. speedRatio = 1.0;
  7811. }
  7812. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7813. return animatable;
  7814. };
  7815. Scene.prototype.getAnimatableByTarget = function (target) {
  7816. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7817. if (this._activeAnimatables[index].target === target) {
  7818. return this._activeAnimatables[index];
  7819. }
  7820. }
  7821. return null;
  7822. };
  7823. /**
  7824. * Will stop the animation of the given target
  7825. * @param target - the target
  7826. * @see beginAnimation
  7827. */
  7828. Scene.prototype.stopAnimation = function (target) {
  7829. var animatable = this.getAnimatableByTarget(target);
  7830. if (animatable) {
  7831. animatable.stop();
  7832. }
  7833. };
  7834. Scene.prototype._animate = function () {
  7835. if (!this.animationsEnabled) {
  7836. return;
  7837. }
  7838. if (!this._animationStartDate) {
  7839. this._animationStartDate = BABYLON.Tools.Now;
  7840. }
  7841. // Getting time
  7842. var now = BABYLON.Tools.Now;
  7843. var delay = now - this._animationStartDate;
  7844. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7845. if (!this._activeAnimatables[index]._animate(delay)) {
  7846. this._activeAnimatables.splice(index, 1);
  7847. index--;
  7848. }
  7849. }
  7850. };
  7851. // Matrix
  7852. Scene.prototype.getViewMatrix = function () {
  7853. return this._viewMatrix;
  7854. };
  7855. Scene.prototype.getProjectionMatrix = function () {
  7856. return this._projectionMatrix;
  7857. };
  7858. Scene.prototype.getTransformMatrix = function () {
  7859. return this._transformMatrix;
  7860. };
  7861. Scene.prototype.setTransformMatrix = function (view, projection) {
  7862. this._viewMatrix = view;
  7863. this._projectionMatrix = projection;
  7864. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7865. };
  7866. // Methods
  7867. /**
  7868. * sets the active camera of the scene using its ID
  7869. * @param {string} id - the camera's ID
  7870. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7871. * @see activeCamera
  7872. */
  7873. Scene.prototype.setActiveCameraByID = function (id) {
  7874. var camera = this.getCameraByID(id);
  7875. if (camera) {
  7876. this.activeCamera = camera;
  7877. return camera;
  7878. }
  7879. return null;
  7880. };
  7881. /**
  7882. * sets the active camera of the scene using its name
  7883. * @param {string} name - the camera's name
  7884. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  7885. * @see activeCamera
  7886. */
  7887. Scene.prototype.setActiveCameraByName = function (name) {
  7888. var camera = this.getCameraByName(name);
  7889. if (camera) {
  7890. this.activeCamera = camera;
  7891. return camera;
  7892. }
  7893. return null;
  7894. };
  7895. /**
  7896. * get a material using its id
  7897. * @param {string} the material's ID
  7898. * @return {BABYLON.Material|null} the material or null if none found.
  7899. */
  7900. Scene.prototype.getMaterialByID = function (id) {
  7901. for (var index = 0; index < this.materials.length; index++) {
  7902. if (this.materials[index].id === id) {
  7903. return this.materials[index];
  7904. }
  7905. }
  7906. return null;
  7907. };
  7908. /**
  7909. * get a material using its name
  7910. * @param {string} the material's name
  7911. * @return {BABYLON.Material|null} the material or null if none found.
  7912. */
  7913. Scene.prototype.getMaterialByName = function (name) {
  7914. for (var index = 0; index < this.materials.length; index++) {
  7915. if (this.materials[index].name === name) {
  7916. return this.materials[index];
  7917. }
  7918. }
  7919. return null;
  7920. };
  7921. Scene.prototype.getCameraByID = function (id) {
  7922. for (var index = 0; index < this.cameras.length; index++) {
  7923. if (this.cameras[index].id === id) {
  7924. return this.cameras[index];
  7925. }
  7926. }
  7927. return null;
  7928. };
  7929. /**
  7930. * get a camera using its name
  7931. * @param {string} the camera's name
  7932. * @return {BABYLON.Camera|null} the camera or null if none found.
  7933. */
  7934. Scene.prototype.getCameraByName = function (name) {
  7935. for (var index = 0; index < this.cameras.length; index++) {
  7936. if (this.cameras[index].name === name) {
  7937. return this.cameras[index];
  7938. }
  7939. }
  7940. return null;
  7941. };
  7942. /**
  7943. * get a light node using its name
  7944. * @param {string} the light's name
  7945. * @return {BABYLON.Light|null} the light or null if none found.
  7946. */
  7947. Scene.prototype.getLightByName = function (name) {
  7948. for (var index = 0; index < this.lights.length; index++) {
  7949. if (this.lights[index].name === name) {
  7950. return this.lights[index];
  7951. }
  7952. }
  7953. return null;
  7954. };
  7955. /**
  7956. * get a light node using its ID
  7957. * @param {string} the light's id
  7958. * @return {BABYLON.Light|null} the light or null if none found.
  7959. */
  7960. Scene.prototype.getLightByID = function (id) {
  7961. for (var index = 0; index < this.lights.length; index++) {
  7962. if (this.lights[index].id === id) {
  7963. return this.lights[index];
  7964. }
  7965. }
  7966. return null;
  7967. };
  7968. /**
  7969. * get a geometry using its ID
  7970. * @param {string} the geometry's id
  7971. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  7972. */
  7973. Scene.prototype.getGeometryByID = function (id) {
  7974. for (var index = 0; index < this._geometries.length; index++) {
  7975. if (this._geometries[index].id === id) {
  7976. return this._geometries[index];
  7977. }
  7978. }
  7979. return null;
  7980. };
  7981. /**
  7982. * add a new geometry to this scene.
  7983. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  7984. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  7985. * @return {boolean} was the geometry added or not
  7986. */
  7987. Scene.prototype.pushGeometry = function (geometry, force) {
  7988. if (!force && this.getGeometryByID(geometry.id)) {
  7989. return false;
  7990. }
  7991. this._geometries.push(geometry);
  7992. return true;
  7993. };
  7994. Scene.prototype.getGeometries = function () {
  7995. return this._geometries;
  7996. };
  7997. /**
  7998. * Get a the first added mesh found of a given ID
  7999. * @param {string} id - the id to search for
  8000. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8001. */
  8002. Scene.prototype.getMeshByID = function (id) {
  8003. for (var index = 0; index < this.meshes.length; index++) {
  8004. if (this.meshes[index].id === id) {
  8005. return this.meshes[index];
  8006. }
  8007. }
  8008. return null;
  8009. };
  8010. /**
  8011. * Get a the last added mesh found of a given ID
  8012. * @param {string} id - the id to search for
  8013. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8014. */
  8015. Scene.prototype.getLastMeshByID = function (id) {
  8016. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8017. if (this.meshes[index].id === id) {
  8018. return this.meshes[index];
  8019. }
  8020. }
  8021. return null;
  8022. };
  8023. /**
  8024. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8025. * @param {string} id - the id to search for
  8026. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8027. */
  8028. Scene.prototype.getLastEntryByID = function (id) {
  8029. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8030. if (this.meshes[index].id === id) {
  8031. return this.meshes[index];
  8032. }
  8033. }
  8034. for (index = this.cameras.length - 1; index >= 0; index--) {
  8035. if (this.cameras[index].id === id) {
  8036. return this.cameras[index];
  8037. }
  8038. }
  8039. for (index = this.lights.length - 1; index >= 0; index--) {
  8040. if (this.lights[index].id === id) {
  8041. return this.lights[index];
  8042. }
  8043. }
  8044. return null;
  8045. };
  8046. Scene.prototype.getNodeByName = function (name) {
  8047. var mesh = this.getMeshByName(name);
  8048. if (mesh) {
  8049. return mesh;
  8050. }
  8051. var light = this.getLightByName(name);
  8052. if (light) {
  8053. return light;
  8054. }
  8055. return this.getCameraByName(name);
  8056. };
  8057. Scene.prototype.getMeshByName = function (name) {
  8058. for (var index = 0; index < this.meshes.length; index++) {
  8059. if (this.meshes[index].name === name) {
  8060. return this.meshes[index];
  8061. }
  8062. }
  8063. return null;
  8064. };
  8065. Scene.prototype.getSoundByName = function (name) {
  8066. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8067. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8068. return this.mainSoundTrack.soundCollection[index];
  8069. }
  8070. }
  8071. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8072. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8073. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8074. return this.soundTracks[sdIndex].soundCollection[index];
  8075. }
  8076. }
  8077. }
  8078. return null;
  8079. };
  8080. Scene.prototype.getLastSkeletonByID = function (id) {
  8081. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8082. if (this.skeletons[index].id === id) {
  8083. return this.skeletons[index];
  8084. }
  8085. }
  8086. return null;
  8087. };
  8088. Scene.prototype.getSkeletonById = function (id) {
  8089. for (var index = 0; index < this.skeletons.length; index++) {
  8090. if (this.skeletons[index].id === id) {
  8091. return this.skeletons[index];
  8092. }
  8093. }
  8094. return null;
  8095. };
  8096. Scene.prototype.getSkeletonByName = function (name) {
  8097. for (var index = 0; index < this.skeletons.length; index++) {
  8098. if (this.skeletons[index].name === name) {
  8099. return this.skeletons[index];
  8100. }
  8101. }
  8102. return null;
  8103. };
  8104. Scene.prototype.isActiveMesh = function (mesh) {
  8105. return (this._activeMeshes.indexOf(mesh) !== -1);
  8106. };
  8107. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8108. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8109. var material = subMesh.getMaterial();
  8110. if (mesh.showSubMeshesBoundingBox) {
  8111. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8112. }
  8113. if (material) {
  8114. // Render targets
  8115. if (material.getRenderTargetTextures) {
  8116. if (this._processedMaterials.indexOf(material) === -1) {
  8117. this._processedMaterials.push(material);
  8118. this._renderTargets.concat(material.getRenderTargetTextures());
  8119. }
  8120. }
  8121. // Dispatch
  8122. this._activeVertices += subMesh.indexCount;
  8123. this._renderingManager.dispatch(subMesh);
  8124. }
  8125. }
  8126. };
  8127. Scene.prototype._evaluateActiveMeshes = function () {
  8128. this._activeMeshes.reset();
  8129. this._renderingManager.reset();
  8130. this._processedMaterials.reset();
  8131. this._activeParticleSystems.reset();
  8132. this._activeSkeletons.reset();
  8133. this._boundingBoxRenderer.reset();
  8134. if (!this._frustumPlanes) {
  8135. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8136. }
  8137. else {
  8138. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8139. }
  8140. // Meshes
  8141. var meshes;
  8142. var len;
  8143. if (this._selectionOctree) {
  8144. var selection = this._selectionOctree.select(this._frustumPlanes);
  8145. meshes = selection.data;
  8146. len = selection.length;
  8147. }
  8148. else {
  8149. len = this.meshes.length;
  8150. meshes = this.meshes;
  8151. }
  8152. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8153. var mesh = meshes[meshIndex];
  8154. if (mesh.isBlocked) {
  8155. continue;
  8156. }
  8157. this._totalVertices += mesh.getTotalVertices();
  8158. if (!mesh.isReady()) {
  8159. continue;
  8160. }
  8161. mesh.computeWorldMatrix();
  8162. // Intersections
  8163. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8164. this._meshesForIntersections.pushNoDuplicate(mesh);
  8165. }
  8166. // Switch to current LOD
  8167. var meshLOD = mesh.getLOD(this.activeCamera);
  8168. if (!meshLOD) {
  8169. continue;
  8170. }
  8171. mesh._preActivate();
  8172. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8173. this._activeMeshes.push(mesh);
  8174. mesh._activate(this._renderId);
  8175. this._activeMesh(meshLOD);
  8176. }
  8177. }
  8178. // Particle systems
  8179. var beforeParticlesDate = BABYLON.Tools.Now;
  8180. if (this.particlesEnabled) {
  8181. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8182. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8183. var particleSystem = this.particleSystems[particleIndex];
  8184. if (!particleSystem.isStarted()) {
  8185. continue;
  8186. }
  8187. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8188. this._activeParticleSystems.push(particleSystem);
  8189. particleSystem.animate();
  8190. }
  8191. }
  8192. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8193. }
  8194. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8195. };
  8196. Scene.prototype._activeMesh = function (mesh) {
  8197. if (mesh.skeleton && this.skeletonsEnabled) {
  8198. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8199. }
  8200. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8201. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8202. }
  8203. if (mesh && mesh.subMeshes) {
  8204. // Submeshes Octrees
  8205. var len;
  8206. var subMeshes;
  8207. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8208. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8209. len = intersections.length;
  8210. subMeshes = intersections.data;
  8211. }
  8212. else {
  8213. subMeshes = mesh.subMeshes;
  8214. len = subMeshes.length;
  8215. }
  8216. for (var subIndex = 0; subIndex < len; subIndex++) {
  8217. var subMesh = subMeshes[subIndex];
  8218. this._evaluateSubMesh(subMesh, mesh);
  8219. }
  8220. }
  8221. };
  8222. Scene.prototype.updateTransformMatrix = function (force) {
  8223. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8224. };
  8225. Scene.prototype._renderForCamera = function (camera) {
  8226. var engine = this._engine;
  8227. this.activeCamera = camera;
  8228. if (!this.activeCamera)
  8229. throw new Error("Active camera not set");
  8230. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8231. // Viewport
  8232. engine.setViewport(this.activeCamera.viewport);
  8233. // Camera
  8234. this._renderId++;
  8235. this.updateTransformMatrix();
  8236. if (this.beforeCameraRender) {
  8237. this.beforeCameraRender(this.activeCamera);
  8238. }
  8239. // Meshes
  8240. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8241. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8242. this._evaluateActiveMeshes();
  8243. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8244. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8245. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8246. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8247. skeleton.prepare();
  8248. this._activeBones += skeleton.bones.length;
  8249. }
  8250. // Render targets
  8251. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8252. if (this.renderTargetsEnabled) {
  8253. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8254. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8255. var renderTarget = this._renderTargets.data[renderIndex];
  8256. if (renderTarget._shouldRender()) {
  8257. this._renderId++;
  8258. renderTarget.render();
  8259. }
  8260. }
  8261. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8262. this._renderId++;
  8263. }
  8264. if (this._renderTargets.length > 0) {
  8265. engine.restoreDefaultFramebuffer();
  8266. }
  8267. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8268. // Prepare Frame
  8269. this.postProcessManager._prepareFrame();
  8270. var beforeRenderDate = BABYLON.Tools.Now;
  8271. // Backgrounds
  8272. if (this.layers.length) {
  8273. engine.setDepthBuffer(false);
  8274. var layerIndex;
  8275. var layer;
  8276. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8277. layer = this.layers[layerIndex];
  8278. if (layer.isBackground) {
  8279. layer.render();
  8280. }
  8281. }
  8282. engine.setDepthBuffer(true);
  8283. }
  8284. // Render
  8285. BABYLON.Tools.StartPerformanceCounter("Main render");
  8286. this._renderingManager.render(null, null, true, true);
  8287. BABYLON.Tools.EndPerformanceCounter("Main render");
  8288. // Bounding boxes
  8289. this._boundingBoxRenderer.render();
  8290. // Lens flares
  8291. if (this.lensFlaresEnabled) {
  8292. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8293. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8294. this.lensFlareSystems[lensFlareSystemIndex].render();
  8295. }
  8296. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8297. }
  8298. // Foregrounds
  8299. if (this.layers.length) {
  8300. engine.setDepthBuffer(false);
  8301. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8302. layer = this.layers[layerIndex];
  8303. if (!layer.isBackground) {
  8304. layer.render();
  8305. }
  8306. }
  8307. engine.setDepthBuffer(true);
  8308. }
  8309. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8310. // Finalize frame
  8311. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8312. // Update camera
  8313. this.activeCamera._updateFromScene();
  8314. // Reset some special arrays
  8315. this._renderTargets.reset();
  8316. if (this.afterCameraRender) {
  8317. this.afterCameraRender(this.activeCamera);
  8318. }
  8319. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8320. };
  8321. Scene.prototype._processSubCameras = function (camera) {
  8322. if (camera.subCameras.length === 0) {
  8323. this._renderForCamera(camera);
  8324. return;
  8325. }
  8326. for (var index = 0; index < camera.subCameras.length; index++) {
  8327. this._renderForCamera(camera.subCameras[index]);
  8328. }
  8329. this.activeCamera = camera;
  8330. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8331. // Update camera
  8332. this.activeCamera._updateFromScene();
  8333. };
  8334. Scene.prototype._checkIntersections = function () {
  8335. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8336. var sourceMesh = this._meshesForIntersections.data[index];
  8337. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8338. var action = sourceMesh.actionManager.actions[actionIndex];
  8339. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8340. var otherMesh = action.getTriggerParameter();
  8341. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  8342. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8343. if (areIntersecting && currentIntersectionInProgress === -1) {
  8344. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8345. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8346. sourceMesh._intersectionsInProgress.push(otherMesh);
  8347. }
  8348. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8349. sourceMesh._intersectionsInProgress.push(otherMesh);
  8350. }
  8351. }
  8352. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8353. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8354. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8355. if (indexOfOther > -1) {
  8356. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8357. }
  8358. }
  8359. }
  8360. }
  8361. }
  8362. };
  8363. Scene.prototype.render = function () {
  8364. var startDate = BABYLON.Tools.Now;
  8365. this._particlesDuration = 0;
  8366. this._spritesDuration = 0;
  8367. this._activeParticles = 0;
  8368. this._renderDuration = 0;
  8369. this._renderTargetsDuration = 0;
  8370. this._evaluateActiveMeshesDuration = 0;
  8371. this._totalVertices = 0;
  8372. this._activeVertices = 0;
  8373. this._activeBones = 0;
  8374. this.getEngine().resetDrawCalls();
  8375. this._meshesForIntersections.reset();
  8376. this.resetCachedMaterial();
  8377. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8378. // Actions
  8379. if (this.actionManager) {
  8380. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8381. }
  8382. // Before render
  8383. if (this.beforeRender) {
  8384. this.beforeRender();
  8385. }
  8386. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8387. this._onBeforeRenderCallbacks[callbackIndex]();
  8388. }
  8389. // Animations
  8390. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8391. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8392. this._animate();
  8393. // Physics
  8394. if (this._physicsEngine) {
  8395. BABYLON.Tools.StartPerformanceCounter("Physics");
  8396. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8397. BABYLON.Tools.EndPerformanceCounter("Physics");
  8398. }
  8399. // Customs render targets
  8400. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8401. var engine = this.getEngine();
  8402. if (this.renderTargetsEnabled) {
  8403. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8404. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8405. var renderTarget = this.customRenderTargets[customIndex];
  8406. if (renderTarget._shouldRender()) {
  8407. this._renderId++;
  8408. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8409. if (!this.activeCamera)
  8410. throw new Error("Active camera not set");
  8411. // Viewport
  8412. engine.setViewport(this.activeCamera.viewport);
  8413. // Camera
  8414. this.updateTransformMatrix();
  8415. renderTarget.render();
  8416. }
  8417. }
  8418. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8419. this._renderId++;
  8420. }
  8421. if (this.customRenderTargets.length > 0) {
  8422. engine.restoreDefaultFramebuffer();
  8423. }
  8424. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8425. // Procedural textures
  8426. if (this.proceduralTexturesEnabled) {
  8427. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8428. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8429. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8430. if (proceduralTexture._shouldRender()) {
  8431. proceduralTexture.render();
  8432. }
  8433. }
  8434. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8435. }
  8436. // Clear
  8437. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8438. // Shadows
  8439. if (this.shadowsEnabled) {
  8440. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8441. var light = this.lights[lightIndex];
  8442. var shadowGenerator = light.getShadowGenerator();
  8443. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8444. this._renderTargets.push(shadowGenerator.getShadowMap());
  8445. }
  8446. }
  8447. }
  8448. // Depth renderer
  8449. if (this._depthRenderer) {
  8450. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8451. }
  8452. // RenderPipeline
  8453. this.postProcessRenderPipelineManager.update();
  8454. // Multi-cameras?
  8455. if (this.activeCameras.length > 0) {
  8456. var currentRenderId = this._renderId;
  8457. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8458. this._renderId = currentRenderId;
  8459. this._processSubCameras(this.activeCameras[cameraIndex]);
  8460. }
  8461. }
  8462. else {
  8463. if (!this.activeCamera) {
  8464. throw new Error("No camera defined");
  8465. }
  8466. this._processSubCameras(this.activeCamera);
  8467. }
  8468. // Intersection checks
  8469. this._checkIntersections();
  8470. // Update the audio listener attached to the camera
  8471. this._updateAudioParameters();
  8472. // After render
  8473. if (this.afterRender) {
  8474. this.afterRender();
  8475. }
  8476. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8477. this._onAfterRenderCallbacks[callbackIndex]();
  8478. }
  8479. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8480. this._toBeDisposed.data[index].dispose();
  8481. this._toBeDisposed[index] = null;
  8482. }
  8483. this._toBeDisposed.reset();
  8484. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8485. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8486. };
  8487. Scene.prototype._updateAudioParameters = function () {
  8488. var listeningCamera;
  8489. var audioEngine = this._engine.getAudioEngine();
  8490. if (this.activeCameras.length > 0) {
  8491. listeningCamera = this.activeCameras[0];
  8492. }
  8493. else {
  8494. listeningCamera = this.activeCamera;
  8495. }
  8496. if (listeningCamera && audioEngine.canUseWebAudio) {
  8497. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8498. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8499. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8500. cameraDirection.normalize();
  8501. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8502. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8503. var sound = this.mainSoundTrack.soundCollection[i];
  8504. if (sound.useCustomAttenuation) {
  8505. sound.updateDistanceFromListener();
  8506. }
  8507. }
  8508. for (i = 0; i < this.soundTracks.length; i++) {
  8509. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8510. sound = this.soundTracks[i].soundCollection[j];
  8511. if (sound.useCustomAttenuation) {
  8512. sound.updateDistanceFromListener();
  8513. }
  8514. }
  8515. }
  8516. }
  8517. };
  8518. Scene.prototype.enableDepthRenderer = function () {
  8519. if (this._depthRenderer) {
  8520. return this._depthRenderer;
  8521. }
  8522. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8523. return this._depthRenderer;
  8524. };
  8525. Scene.prototype.disableDepthRenderer = function () {
  8526. if (!this._depthRenderer) {
  8527. return;
  8528. }
  8529. this._depthRenderer.dispose();
  8530. this._depthRenderer = null;
  8531. };
  8532. Scene.prototype.dispose = function () {
  8533. this.beforeRender = null;
  8534. this.afterRender = null;
  8535. this.skeletons = [];
  8536. this._boundingBoxRenderer.dispose();
  8537. if (this._depthRenderer) {
  8538. this._depthRenderer.dispose();
  8539. }
  8540. // Debug layer
  8541. this.debugLayer.hide();
  8542. // Events
  8543. if (this.onDispose) {
  8544. this.onDispose();
  8545. }
  8546. this._onBeforeRenderCallbacks = [];
  8547. this._onAfterRenderCallbacks = [];
  8548. this.detachControl();
  8549. // Release sounds & sounds tracks
  8550. this.mainSoundTrack.dispose();
  8551. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8552. this.soundTracks[scIndex].dispose();
  8553. }
  8554. // Detach cameras
  8555. var canvas = this._engine.getRenderingCanvas();
  8556. var index;
  8557. for (index = 0; index < this.cameras.length; index++) {
  8558. this.cameras[index].detachControl(canvas);
  8559. }
  8560. while (this.lights.length) {
  8561. this.lights[0].dispose();
  8562. }
  8563. while (this.meshes.length) {
  8564. this.meshes[0].dispose(true);
  8565. }
  8566. while (this.cameras.length) {
  8567. this.cameras[0].dispose();
  8568. }
  8569. while (this.materials.length) {
  8570. this.materials[0].dispose();
  8571. }
  8572. while (this.particleSystems.length) {
  8573. this.particleSystems[0].dispose();
  8574. }
  8575. while (this.spriteManagers.length) {
  8576. this.spriteManagers[0].dispose();
  8577. }
  8578. while (this.layers.length) {
  8579. this.layers[0].dispose();
  8580. }
  8581. while (this.textures.length) {
  8582. this.textures[0].dispose();
  8583. }
  8584. // Post-processes
  8585. this.postProcessManager.dispose();
  8586. // Physics
  8587. if (this._physicsEngine) {
  8588. this.disablePhysicsEngine();
  8589. }
  8590. // Remove from engine
  8591. index = this._engine.scenes.indexOf(this);
  8592. if (index > -1) {
  8593. this._engine.scenes.splice(index, 1);
  8594. }
  8595. this._engine.wipeCaches();
  8596. };
  8597. // Collisions
  8598. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8599. if (excludedMesh === void 0) { excludedMesh = null; }
  8600. position.divideToRef(collider.radius, this._scaledPosition);
  8601. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8602. collider.retry = 0;
  8603. collider.initialVelocity = this._scaledVelocity;
  8604. collider.initialPosition = this._scaledPosition;
  8605. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8606. finalPosition.multiplyInPlace(collider.radius);
  8607. };
  8608. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8609. if (excludedMesh === void 0) { excludedMesh = null; }
  8610. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8611. if (collider.retry >= maximumRetry) {
  8612. finalPosition.copyFrom(position);
  8613. return;
  8614. }
  8615. collider._initialize(position, velocity, closeDistance);
  8616. for (var index = 0; index < this.meshes.length; index++) {
  8617. var mesh = this.meshes[index];
  8618. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8619. mesh._checkCollision(collider);
  8620. }
  8621. }
  8622. if (!collider.collisionFound) {
  8623. position.addToRef(velocity, finalPosition);
  8624. return;
  8625. }
  8626. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8627. collider._getResponse(position, velocity);
  8628. }
  8629. if (velocity.length() <= closeDistance) {
  8630. finalPosition.copyFrom(position);
  8631. return;
  8632. }
  8633. collider.retry++;
  8634. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8635. };
  8636. // Octrees
  8637. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8638. if (maxCapacity === void 0) { maxCapacity = 64; }
  8639. if (maxDepth === void 0) { maxDepth = 2; }
  8640. if (!this._selectionOctree) {
  8641. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8642. }
  8643. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8644. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8645. for (var index = 0; index < this.meshes.length; index++) {
  8646. var mesh = this.meshes[index];
  8647. mesh.computeWorldMatrix(true);
  8648. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8649. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8650. BABYLON.Tools.CheckExtends(minBox, min, max);
  8651. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8652. }
  8653. // Update octree
  8654. this._selectionOctree.update(min, max, this.meshes);
  8655. return this._selectionOctree;
  8656. };
  8657. // Picking
  8658. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8659. var engine = this._engine;
  8660. if (!camera) {
  8661. if (!this.activeCamera)
  8662. throw new Error("Active camera not set");
  8663. camera = this.activeCamera;
  8664. }
  8665. var cameraViewport = camera.viewport;
  8666. var viewport = cameraViewport.toGlobal(engine);
  8667. // Moving coordinates to local viewport world
  8668. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8669. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8670. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8671. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8672. };
  8673. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8674. var pickingInfo = null;
  8675. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8676. var mesh = this.meshes[meshIndex];
  8677. if (predicate) {
  8678. if (!predicate(mesh)) {
  8679. continue;
  8680. }
  8681. }
  8682. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8683. continue;
  8684. }
  8685. var world = mesh.getWorldMatrix();
  8686. var ray = rayFunction(world);
  8687. var result = mesh.intersects(ray, fastCheck);
  8688. if (!result || !result.hit)
  8689. continue;
  8690. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8691. continue;
  8692. pickingInfo = result;
  8693. if (fastCheck) {
  8694. break;
  8695. }
  8696. }
  8697. return pickingInfo || new BABYLON.PickingInfo();
  8698. };
  8699. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8700. var _this = this;
  8701. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8702. /// <param name="x">X position on screen</param>
  8703. /// <param name="y">Y position on screen</param>
  8704. /// <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>
  8705. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8706. /// <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>
  8707. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8708. };
  8709. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8710. var _this = this;
  8711. return this._internalPick(function (world) {
  8712. if (!_this._pickWithRayInverseMatrix) {
  8713. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8714. }
  8715. world.invertToRef(_this._pickWithRayInverseMatrix);
  8716. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8717. }, predicate, fastCheck);
  8718. };
  8719. Scene.prototype.setPointerOverMesh = function (mesh) {
  8720. if (this._pointerOverMesh === mesh) {
  8721. return;
  8722. }
  8723. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8724. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8725. }
  8726. this._pointerOverMesh = mesh;
  8727. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8728. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8729. }
  8730. };
  8731. Scene.prototype.getPointerOverMesh = function () {
  8732. return this._pointerOverMesh;
  8733. };
  8734. // Physics
  8735. Scene.prototype.getPhysicsEngine = function () {
  8736. return this._physicsEngine;
  8737. };
  8738. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8739. if (this._physicsEngine) {
  8740. return true;
  8741. }
  8742. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8743. if (!this._physicsEngine.isSupported()) {
  8744. this._physicsEngine = null;
  8745. return false;
  8746. }
  8747. this._physicsEngine._initialize(gravity);
  8748. return true;
  8749. };
  8750. Scene.prototype.disablePhysicsEngine = function () {
  8751. if (!this._physicsEngine) {
  8752. return;
  8753. }
  8754. this._physicsEngine.dispose();
  8755. this._physicsEngine = undefined;
  8756. };
  8757. Scene.prototype.isPhysicsEnabled = function () {
  8758. return this._physicsEngine !== undefined;
  8759. };
  8760. Scene.prototype.setGravity = function (gravity) {
  8761. if (!this._physicsEngine) {
  8762. return;
  8763. }
  8764. this._physicsEngine._setGravity(gravity);
  8765. };
  8766. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8767. if (parts.parts) {
  8768. options = parts;
  8769. parts = parts.parts;
  8770. }
  8771. if (!this._physicsEngine) {
  8772. return null;
  8773. }
  8774. for (var index = 0; index < parts.length; index++) {
  8775. var mesh = parts[index].mesh;
  8776. mesh._physicImpostor = parts[index].impostor;
  8777. mesh._physicsMass = options.mass / parts.length;
  8778. mesh._physicsFriction = options.friction;
  8779. mesh._physicRestitution = options.restitution;
  8780. }
  8781. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8782. };
  8783. //ANY
  8784. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8785. for (var index = 0; index < compound.parts.length; index++) {
  8786. var mesh = compound.parts[index].mesh;
  8787. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8788. this._physicsEngine._unregisterMesh(mesh);
  8789. }
  8790. };
  8791. // Tags
  8792. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  8793. if (tagsQuery === undefined) {
  8794. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8795. return list;
  8796. }
  8797. var listByTags = [];
  8798. forEach = forEach || (function (item) {
  8799. return;
  8800. });
  8801. for (var i in list) {
  8802. var item = list[i];
  8803. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8804. listByTags.push(item);
  8805. forEach(item);
  8806. }
  8807. }
  8808. return listByTags;
  8809. };
  8810. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  8811. return this._getByTags(this.meshes, tagsQuery, forEach);
  8812. };
  8813. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  8814. return this._getByTags(this.cameras, tagsQuery, forEach);
  8815. };
  8816. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  8817. return this._getByTags(this.lights, tagsQuery, forEach);
  8818. };
  8819. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  8820. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  8821. };
  8822. // Statics
  8823. Scene.FOGMODE_NONE = 0;
  8824. Scene.FOGMODE_EXP = 1;
  8825. Scene.FOGMODE_EXP2 = 2;
  8826. Scene.FOGMODE_LINEAR = 3;
  8827. Scene.MinDeltaTime = 1.0;
  8828. Scene.MaxDeltaTime = 1000.0;
  8829. return Scene;
  8830. })();
  8831. BABYLON.Scene = Scene;
  8832. })(BABYLON || (BABYLON = {}));
  8833. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  8834. (function (BABYLON) {
  8835. var VertexBuffer = (function () {
  8836. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8837. if (engine instanceof BABYLON.Mesh) {
  8838. this._engine = engine.getScene().getEngine();
  8839. }
  8840. else {
  8841. this._engine = engine;
  8842. }
  8843. this._updatable = updatable;
  8844. this._data = data;
  8845. if (!postponeInternalCreation) {
  8846. this.create();
  8847. }
  8848. this._kind = kind;
  8849. if (stride) {
  8850. this._strideSize = stride;
  8851. return;
  8852. }
  8853. switch (kind) {
  8854. case VertexBuffer.PositionKind:
  8855. this._strideSize = 3;
  8856. break;
  8857. case VertexBuffer.NormalKind:
  8858. this._strideSize = 3;
  8859. break;
  8860. case VertexBuffer.UVKind:
  8861. this._strideSize = 2;
  8862. break;
  8863. case VertexBuffer.UV2Kind:
  8864. this._strideSize = 2;
  8865. break;
  8866. case VertexBuffer.ColorKind:
  8867. this._strideSize = 4;
  8868. break;
  8869. case VertexBuffer.MatricesIndicesKind:
  8870. this._strideSize = 4;
  8871. break;
  8872. case VertexBuffer.MatricesWeightsKind:
  8873. this._strideSize = 4;
  8874. break;
  8875. }
  8876. }
  8877. // Properties
  8878. VertexBuffer.prototype.isUpdatable = function () {
  8879. return this._updatable;
  8880. };
  8881. VertexBuffer.prototype.getData = function () {
  8882. return this._data;
  8883. };
  8884. VertexBuffer.prototype.getBuffer = function () {
  8885. return this._buffer;
  8886. };
  8887. VertexBuffer.prototype.getStrideSize = function () {
  8888. return this._strideSize;
  8889. };
  8890. // Methods
  8891. VertexBuffer.prototype.create = function (data) {
  8892. if (!data && this._buffer) {
  8893. return; // nothing to do
  8894. }
  8895. data = data || this._data;
  8896. if (!this._buffer) {
  8897. if (this._updatable) {
  8898. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8899. }
  8900. else {
  8901. this._buffer = this._engine.createVertexBuffer(data);
  8902. }
  8903. }
  8904. if (this._updatable) {
  8905. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8906. this._data = data;
  8907. }
  8908. };
  8909. VertexBuffer.prototype.update = function (data) {
  8910. this.create(data);
  8911. };
  8912. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8913. if (!this._buffer) {
  8914. return;
  8915. }
  8916. if (this._updatable) {
  8917. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8918. this._data = null;
  8919. }
  8920. };
  8921. VertexBuffer.prototype.dispose = function () {
  8922. if (!this._buffer) {
  8923. return;
  8924. }
  8925. if (this._engine._releaseBuffer(this._buffer)) {
  8926. this._buffer = null;
  8927. }
  8928. };
  8929. Object.defineProperty(VertexBuffer, "PositionKind", {
  8930. get: function () {
  8931. return VertexBuffer._PositionKind;
  8932. },
  8933. enumerable: true,
  8934. configurable: true
  8935. });
  8936. Object.defineProperty(VertexBuffer, "NormalKind", {
  8937. get: function () {
  8938. return VertexBuffer._NormalKind;
  8939. },
  8940. enumerable: true,
  8941. configurable: true
  8942. });
  8943. Object.defineProperty(VertexBuffer, "UVKind", {
  8944. get: function () {
  8945. return VertexBuffer._UVKind;
  8946. },
  8947. enumerable: true,
  8948. configurable: true
  8949. });
  8950. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8951. get: function () {
  8952. return VertexBuffer._UV2Kind;
  8953. },
  8954. enumerable: true,
  8955. configurable: true
  8956. });
  8957. Object.defineProperty(VertexBuffer, "ColorKind", {
  8958. get: function () {
  8959. return VertexBuffer._ColorKind;
  8960. },
  8961. enumerable: true,
  8962. configurable: true
  8963. });
  8964. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8965. get: function () {
  8966. return VertexBuffer._MatricesIndicesKind;
  8967. },
  8968. enumerable: true,
  8969. configurable: true
  8970. });
  8971. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8972. get: function () {
  8973. return VertexBuffer._MatricesWeightsKind;
  8974. },
  8975. enumerable: true,
  8976. configurable: true
  8977. });
  8978. // Enums
  8979. VertexBuffer._PositionKind = "position";
  8980. VertexBuffer._NormalKind = "normal";
  8981. VertexBuffer._UVKind = "uv";
  8982. VertexBuffer._UV2Kind = "uv2";
  8983. VertexBuffer._ColorKind = "color";
  8984. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8985. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8986. return VertexBuffer;
  8987. })();
  8988. BABYLON.VertexBuffer = VertexBuffer;
  8989. })(BABYLON || (BABYLON = {}));
  8990. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8991. var BABYLON;
  8992. (function (BABYLON) {
  8993. var AbstractMesh = (function (_super) {
  8994. __extends(AbstractMesh, _super);
  8995. function AbstractMesh(name, scene) {
  8996. _super.call(this, name, scene);
  8997. // Properties
  8998. this.definedFacingForward = true; // orientation for POV movement & rotation
  8999. this.position = new BABYLON.Vector3(0, 0, 0);
  9000. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9001. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9002. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9003. this.visibility = 1.0;
  9004. this.alphaIndex = Number.MAX_VALUE;
  9005. this.infiniteDistance = false;
  9006. this.isVisible = true;
  9007. this.isPickable = true;
  9008. this.showBoundingBox = false;
  9009. this.showSubMeshesBoundingBox = false;
  9010. this.onDispose = null;
  9011. this.checkCollisions = false;
  9012. this.isBlocker = false;
  9013. this.renderingGroupId = 0;
  9014. this.receiveShadows = false;
  9015. this.renderOutline = false;
  9016. this.outlineColor = BABYLON.Color3.Red();
  9017. this.outlineWidth = 0.02;
  9018. this.renderOverlay = false;
  9019. this.overlayColor = BABYLON.Color3.Red();
  9020. this.overlayAlpha = 0.5;
  9021. this.hasVertexAlpha = false;
  9022. this.useVertexColors = true;
  9023. this.applyFog = true;
  9024. this.useOctreeForRenderingSelection = true;
  9025. this.useOctreeForPicking = true;
  9026. this.useOctreeForCollisions = true;
  9027. this.layerMask = 0xFFFFFFFF;
  9028. // Physics
  9029. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9030. // Collisions
  9031. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9032. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9033. this._collider = new BABYLON.Collider();
  9034. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9035. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9036. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9037. // Cache
  9038. this._localScaling = BABYLON.Matrix.Zero();
  9039. this._localRotation = BABYLON.Matrix.Zero();
  9040. this._localTranslation = BABYLON.Matrix.Zero();
  9041. this._localBillboard = BABYLON.Matrix.Zero();
  9042. this._localPivotScaling = BABYLON.Matrix.Zero();
  9043. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9044. this._localWorld = BABYLON.Matrix.Zero();
  9045. this._worldMatrix = BABYLON.Matrix.Zero();
  9046. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9047. this._absolutePosition = BABYLON.Vector3.Zero();
  9048. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9049. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9050. this._isDirty = false;
  9051. this._pivotMatrix = BABYLON.Matrix.Identity();
  9052. this._isDisposed = false;
  9053. this._renderId = 0;
  9054. this._intersectionsInProgress = new Array();
  9055. this._onAfterWorldMatrixUpdate = new Array();
  9056. scene.meshes.push(this);
  9057. }
  9058. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9059. get: function () {
  9060. return AbstractMesh._BILLBOARDMODE_NONE;
  9061. },
  9062. enumerable: true,
  9063. configurable: true
  9064. });
  9065. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9066. get: function () {
  9067. return AbstractMesh._BILLBOARDMODE_X;
  9068. },
  9069. enumerable: true,
  9070. configurable: true
  9071. });
  9072. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9073. get: function () {
  9074. return AbstractMesh._BILLBOARDMODE_Y;
  9075. },
  9076. enumerable: true,
  9077. configurable: true
  9078. });
  9079. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9080. get: function () {
  9081. return AbstractMesh._BILLBOARDMODE_Z;
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9087. get: function () {
  9088. return AbstractMesh._BILLBOARDMODE_ALL;
  9089. },
  9090. enumerable: true,
  9091. configurable: true
  9092. });
  9093. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9094. // Methods
  9095. get: function () {
  9096. return false;
  9097. },
  9098. enumerable: true,
  9099. configurable: true
  9100. });
  9101. AbstractMesh.prototype.getLOD = function (camera) {
  9102. return this;
  9103. };
  9104. AbstractMesh.prototype.getTotalVertices = function () {
  9105. return 0;
  9106. };
  9107. AbstractMesh.prototype.getIndices = function () {
  9108. return null;
  9109. };
  9110. AbstractMesh.prototype.getVerticesData = function (kind) {
  9111. return null;
  9112. };
  9113. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9114. return false;
  9115. };
  9116. AbstractMesh.prototype.getBoundingInfo = function () {
  9117. if (this._masterMesh) {
  9118. return this._masterMesh.getBoundingInfo();
  9119. }
  9120. if (!this._boundingInfo) {
  9121. this._updateBoundingInfo();
  9122. }
  9123. return this._boundingInfo;
  9124. };
  9125. AbstractMesh.prototype._preActivate = function () {
  9126. };
  9127. AbstractMesh.prototype._activate = function (renderId) {
  9128. this._renderId = renderId;
  9129. };
  9130. AbstractMesh.prototype.getWorldMatrix = function () {
  9131. if (this._masterMesh) {
  9132. return this._masterMesh.getWorldMatrix();
  9133. }
  9134. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9135. this.computeWorldMatrix();
  9136. }
  9137. return this._worldMatrix;
  9138. };
  9139. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9140. get: function () {
  9141. return this._worldMatrix;
  9142. },
  9143. enumerable: true,
  9144. configurable: true
  9145. });
  9146. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9147. get: function () {
  9148. return this._absolutePosition;
  9149. },
  9150. enumerable: true,
  9151. configurable: true
  9152. });
  9153. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9154. if (!this.rotationQuaternion) {
  9155. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9156. this.rotation = BABYLON.Vector3.Zero();
  9157. }
  9158. if (!space || space == 0 /* LOCAL */) {
  9159. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9160. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9161. }
  9162. else {
  9163. if (this.parent) {
  9164. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9165. invertParentWorldMatrix.invert();
  9166. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9167. }
  9168. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9169. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9170. }
  9171. };
  9172. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9173. var displacementVector = axis.scale(distance);
  9174. if (!space || space == 0 /* LOCAL */) {
  9175. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9176. this.setPositionWithLocalVector(tempV3);
  9177. }
  9178. else {
  9179. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9180. }
  9181. };
  9182. AbstractMesh.prototype.getAbsolutePosition = function () {
  9183. this.computeWorldMatrix();
  9184. return this._absolutePosition;
  9185. };
  9186. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9187. if (!absolutePosition) {
  9188. return;
  9189. }
  9190. var absolutePositionX;
  9191. var absolutePositionY;
  9192. var absolutePositionZ;
  9193. if (absolutePosition.x === undefined) {
  9194. if (arguments.length < 3) {
  9195. return;
  9196. }
  9197. absolutePositionX = arguments[0];
  9198. absolutePositionY = arguments[1];
  9199. absolutePositionZ = arguments[2];
  9200. }
  9201. else {
  9202. absolutePositionX = absolutePosition.x;
  9203. absolutePositionY = absolutePosition.y;
  9204. absolutePositionZ = absolutePosition.z;
  9205. }
  9206. if (this.parent) {
  9207. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9208. invertParentWorldMatrix.invert();
  9209. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9210. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9211. }
  9212. else {
  9213. this.position.x = absolutePositionX;
  9214. this.position.y = absolutePositionY;
  9215. this.position.z = absolutePositionZ;
  9216. }
  9217. };
  9218. // ================================== Point of View Movement =================================
  9219. /**
  9220. * Perform relative position change from the point of view of behind the front of the mesh.
  9221. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9222. * Supports definition of mesh facing forward or backward.
  9223. * @param {number} amountRight
  9224. * @param {number} amountUp
  9225. * @param {number} amountForward
  9226. */
  9227. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9228. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9229. };
  9230. /**
  9231. * Calculate relative position change from the point of view of behind the front of the mesh.
  9232. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9233. * Supports definition of mesh facing forward or backward.
  9234. * @param {number} amountRight
  9235. * @param {number} amountUp
  9236. * @param {number} amountForward
  9237. */
  9238. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9239. var rotMatrix = new BABYLON.Matrix();
  9240. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9241. rotQuaternion.toRotationMatrix(rotMatrix);
  9242. var translationDelta = BABYLON.Vector3.Zero();
  9243. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9244. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9245. return translationDelta;
  9246. };
  9247. // ================================== Point of View Rotation =================================
  9248. /**
  9249. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9250. * Supports definition of mesh facing forward or backward.
  9251. * @param {number} flipBack
  9252. * @param {number} twirlClockwise
  9253. * @param {number} tiltRight
  9254. */
  9255. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9256. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9257. };
  9258. /**
  9259. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9260. * Supports definition of mesh facing forward or backward.
  9261. * @param {number} flipBack
  9262. * @param {number} twirlClockwise
  9263. * @param {number} tiltRight
  9264. */
  9265. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9266. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9267. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9268. };
  9269. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9270. this._pivotMatrix = matrix;
  9271. this._cache.pivotMatrixUpdated = true;
  9272. };
  9273. AbstractMesh.prototype.getPivotMatrix = function () {
  9274. return this._pivotMatrix;
  9275. };
  9276. AbstractMesh.prototype._isSynchronized = function () {
  9277. if (this._isDirty) {
  9278. return false;
  9279. }
  9280. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9281. return false;
  9282. if (this._cache.pivotMatrixUpdated) {
  9283. return false;
  9284. }
  9285. if (this.infiniteDistance) {
  9286. return false;
  9287. }
  9288. if (!this._cache.position.equals(this.position))
  9289. return false;
  9290. if (this.rotationQuaternion) {
  9291. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9292. return false;
  9293. }
  9294. else {
  9295. if (!this._cache.rotation.equals(this.rotation))
  9296. return false;
  9297. }
  9298. if (!this._cache.scaling.equals(this.scaling))
  9299. return false;
  9300. return true;
  9301. };
  9302. AbstractMesh.prototype._initCache = function () {
  9303. _super.prototype._initCache.call(this);
  9304. this._cache.localMatrixUpdated = false;
  9305. this._cache.position = BABYLON.Vector3.Zero();
  9306. this._cache.scaling = BABYLON.Vector3.Zero();
  9307. this._cache.rotation = BABYLON.Vector3.Zero();
  9308. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9309. };
  9310. AbstractMesh.prototype.markAsDirty = function (property) {
  9311. if (property === "rotation") {
  9312. this.rotationQuaternion = null;
  9313. }
  9314. this._currentRenderId = Number.MAX_VALUE;
  9315. this._isDirty = true;
  9316. };
  9317. AbstractMesh.prototype._updateBoundingInfo = function () {
  9318. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9319. this._boundingInfo._update(this.worldMatrixFromCache);
  9320. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9321. };
  9322. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9323. if (!this.subMeshes) {
  9324. return;
  9325. }
  9326. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9327. var subMesh = this.subMeshes[subIndex];
  9328. subMesh.updateBoundingInfo(matrix);
  9329. }
  9330. };
  9331. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9332. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9333. return this._worldMatrix;
  9334. }
  9335. this._cache.position.copyFrom(this.position);
  9336. this._cache.scaling.copyFrom(this.scaling);
  9337. this._cache.pivotMatrixUpdated = false;
  9338. this._currentRenderId = this.getScene().getRenderId();
  9339. this._isDirty = false;
  9340. // Scaling
  9341. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9342. // Rotation
  9343. if (this.rotationQuaternion) {
  9344. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9345. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9346. }
  9347. else {
  9348. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9349. this._cache.rotation.copyFrom(this.rotation);
  9350. }
  9351. // Translation
  9352. if (this.infiniteDistance && !this.parent) {
  9353. var camera = this.getScene().activeCamera;
  9354. var cameraWorldMatrix = camera.getWorldMatrix();
  9355. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9356. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9357. }
  9358. else {
  9359. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9360. }
  9361. // Composing transformations
  9362. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9363. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9364. // Billboarding
  9365. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9366. var localPosition = this.position.clone();
  9367. var zero = this.getScene().activeCamera.position.clone();
  9368. if (this.parent && this.parent.position) {
  9369. localPosition.addInPlace(this.parent.position);
  9370. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9371. }
  9372. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9373. zero = this.getScene().activeCamera.position;
  9374. }
  9375. else {
  9376. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9377. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9378. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9379. zero.y = localPosition.y + 0.001;
  9380. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9381. zero.z = localPosition.z + 0.001;
  9382. }
  9383. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9384. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9385. this._localBillboard.invert();
  9386. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9387. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9388. }
  9389. // Local world
  9390. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9391. // Parent
  9392. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9393. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9394. }
  9395. else {
  9396. this._worldMatrix.copyFrom(this._localWorld);
  9397. }
  9398. // Bounding info
  9399. this._updateBoundingInfo();
  9400. // Absolute position
  9401. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9402. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9403. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9404. }
  9405. return this._worldMatrix;
  9406. };
  9407. /**
  9408. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9409. * @param func: callback function to add
  9410. */
  9411. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9412. this._onAfterWorldMatrixUpdate.push(func);
  9413. };
  9414. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9415. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9416. if (index > -1) {
  9417. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9418. }
  9419. };
  9420. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9421. this.computeWorldMatrix();
  9422. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9423. };
  9424. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9425. this.computeWorldMatrix();
  9426. var invLocalWorldMatrix = this._localWorld.clone();
  9427. invLocalWorldMatrix.invert();
  9428. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9429. };
  9430. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9431. this.computeWorldMatrix();
  9432. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9433. };
  9434. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9435. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9436. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9437. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9438. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9439. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9440. /// <returns>Mesh oriented towards targetMesh</returns>
  9441. yawCor = yawCor || 0; // default to zero if undefined
  9442. pitchCor = pitchCor || 0;
  9443. rollCor = rollCor || 0;
  9444. var dv = targetPoint.subtract(this.position);
  9445. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9446. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9447. var pitch = Math.atan2(dv.y, len);
  9448. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9449. };
  9450. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9451. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9452. return false;
  9453. }
  9454. return true;
  9455. };
  9456. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9457. if (!camera) {
  9458. camera = this.getScene().activeCamera;
  9459. }
  9460. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9461. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9462. return false;
  9463. }
  9464. return true;
  9465. };
  9466. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9467. if (!this._boundingInfo || !mesh._boundingInfo) {
  9468. return false;
  9469. }
  9470. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9471. };
  9472. AbstractMesh.prototype.intersectsPoint = function (point) {
  9473. if (!this._boundingInfo) {
  9474. return false;
  9475. }
  9476. return this._boundingInfo.intersectsPoint(point);
  9477. };
  9478. // Physics
  9479. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9480. var physicsEngine = this.getScene().getPhysicsEngine();
  9481. if (!physicsEngine) {
  9482. return;
  9483. }
  9484. if (impostor.impostor) {
  9485. // Old API
  9486. options = impostor;
  9487. impostor = impostor.impostor;
  9488. }
  9489. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9490. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9491. physicsEngine._unregisterMesh(this);
  9492. return;
  9493. }
  9494. options.mass = options.mass || 0;
  9495. options.friction = options.friction || 0.2;
  9496. options.restitution = options.restitution || 0.2;
  9497. this._physicImpostor = impostor;
  9498. this._physicsMass = options.mass;
  9499. this._physicsFriction = options.friction;
  9500. this._physicRestitution = options.restitution;
  9501. return physicsEngine._registerMesh(this, impostor, options);
  9502. };
  9503. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9504. if (!this._physicImpostor) {
  9505. return BABYLON.PhysicsEngine.NoImpostor;
  9506. }
  9507. return this._physicImpostor;
  9508. };
  9509. AbstractMesh.prototype.getPhysicsMass = function () {
  9510. if (!this._physicsMass) {
  9511. return 0;
  9512. }
  9513. return this._physicsMass;
  9514. };
  9515. AbstractMesh.prototype.getPhysicsFriction = function () {
  9516. if (!this._physicsFriction) {
  9517. return 0;
  9518. }
  9519. return this._physicsFriction;
  9520. };
  9521. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9522. if (!this._physicRestitution) {
  9523. return 0;
  9524. }
  9525. return this._physicRestitution;
  9526. };
  9527. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9528. if (!camera) {
  9529. camera = this.getScene().activeCamera;
  9530. }
  9531. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9532. };
  9533. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9534. if (!camera) {
  9535. camera = this.getScene().activeCamera;
  9536. }
  9537. return this.absolutePosition.subtract(camera.position).length();
  9538. };
  9539. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9540. if (!this._physicImpostor) {
  9541. return;
  9542. }
  9543. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9544. };
  9545. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9546. if (!this._physicImpostor) {
  9547. return;
  9548. }
  9549. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9550. };
  9551. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9552. if (!this._physicImpostor) {
  9553. return;
  9554. }
  9555. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9556. };
  9557. // Collisions
  9558. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9559. var globalPosition = this.getAbsolutePosition();
  9560. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9561. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9562. this._collider.radius = this.ellipsoid;
  9563. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9564. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9565. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9566. this.position.addInPlace(this._diffPositionForCollisions);
  9567. }
  9568. };
  9569. // Submeshes octree
  9570. /**
  9571. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9572. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9573. */
  9574. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9575. if (maxCapacity === void 0) { maxCapacity = 64; }
  9576. if (maxDepth === void 0) { maxDepth = 2; }
  9577. if (!this._submeshesOctree) {
  9578. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9579. }
  9580. this.computeWorldMatrix(true);
  9581. // Update octree
  9582. var bbox = this.getBoundingInfo().boundingBox;
  9583. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9584. return this._submeshesOctree;
  9585. };
  9586. // Collisions
  9587. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9588. this._generatePointsArray();
  9589. // Transformation
  9590. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9591. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9592. subMesh._lastColliderWorldVertices = [];
  9593. subMesh._trianglePlanes = [];
  9594. var start = subMesh.verticesStart;
  9595. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9596. for (var i = start; i < end; i++) {
  9597. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9598. }
  9599. }
  9600. // Collide
  9601. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9602. };
  9603. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9604. var subMeshes;
  9605. var len;
  9606. // Octrees
  9607. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9608. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9609. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9610. len = intersections.length;
  9611. subMeshes = intersections.data;
  9612. }
  9613. else {
  9614. subMeshes = this.subMeshes;
  9615. len = subMeshes.length;
  9616. }
  9617. for (var index = 0; index < len; index++) {
  9618. var subMesh = subMeshes[index];
  9619. // Bounding test
  9620. if (len > 1 && !subMesh._checkCollision(collider))
  9621. continue;
  9622. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9623. }
  9624. };
  9625. AbstractMesh.prototype._checkCollision = function (collider) {
  9626. // Bounding box test
  9627. if (!this._boundingInfo._checkCollision(collider))
  9628. return;
  9629. // Transformation matrix
  9630. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9631. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9632. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9633. };
  9634. // Picking
  9635. AbstractMesh.prototype._generatePointsArray = function () {
  9636. return false;
  9637. };
  9638. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9639. var pickingInfo = new BABYLON.PickingInfo();
  9640. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9641. return pickingInfo;
  9642. }
  9643. if (!this._generatePointsArray()) {
  9644. return pickingInfo;
  9645. }
  9646. var intersectInfo = null;
  9647. // Octrees
  9648. var subMeshes;
  9649. var len;
  9650. if (this._submeshesOctree && this.useOctreeForPicking) {
  9651. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9652. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9653. len = intersections.length;
  9654. subMeshes = intersections.data;
  9655. }
  9656. else {
  9657. subMeshes = this.subMeshes;
  9658. len = subMeshes.length;
  9659. }
  9660. for (var index = 0; index < len; index++) {
  9661. var subMesh = subMeshes[index];
  9662. // Bounding test
  9663. if (len > 1 && !subMesh.canIntersects(ray))
  9664. continue;
  9665. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9666. if (currentIntersectInfo) {
  9667. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9668. intersectInfo = currentIntersectInfo;
  9669. if (fastCheck) {
  9670. break;
  9671. }
  9672. }
  9673. }
  9674. }
  9675. if (intersectInfo) {
  9676. // Get picked point
  9677. var world = this.getWorldMatrix();
  9678. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9679. var direction = ray.direction.clone();
  9680. direction.normalize();
  9681. direction = direction.scale(intersectInfo.distance);
  9682. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9683. var pickedPoint = worldOrigin.add(worldDirection);
  9684. // Return result
  9685. pickingInfo.hit = true;
  9686. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9687. pickingInfo.pickedPoint = pickedPoint;
  9688. pickingInfo.pickedMesh = this;
  9689. pickingInfo.bu = intersectInfo.bu;
  9690. pickingInfo.bv = intersectInfo.bv;
  9691. pickingInfo.faceId = intersectInfo.faceId;
  9692. return pickingInfo;
  9693. }
  9694. return pickingInfo;
  9695. };
  9696. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9697. return null;
  9698. };
  9699. AbstractMesh.prototype.releaseSubMeshes = function () {
  9700. if (this.subMeshes) {
  9701. while (this.subMeshes.length) {
  9702. this.subMeshes[0].dispose();
  9703. }
  9704. }
  9705. else {
  9706. this.subMeshes = new Array();
  9707. }
  9708. };
  9709. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9710. // Physics
  9711. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9712. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9713. }
  9714. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9715. var other = this._intersectionsInProgress[index];
  9716. var pos = other._intersectionsInProgress.indexOf(this);
  9717. other._intersectionsInProgress.splice(pos, 1);
  9718. }
  9719. this._intersectionsInProgress = [];
  9720. // SubMeshes
  9721. this.releaseSubMeshes();
  9722. // Remove from scene
  9723. var index = this.getScene().meshes.indexOf(this);
  9724. if (index != -1) {
  9725. // Remove from the scene if mesh found
  9726. this.getScene().meshes.splice(index, 1);
  9727. }
  9728. if (!doNotRecurse) {
  9729. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9730. if (this.getScene().particleSystems[index].emitter == this) {
  9731. this.getScene().particleSystems[index].dispose();
  9732. index--;
  9733. }
  9734. }
  9735. // Children
  9736. var objects = this.getScene().meshes.slice(0);
  9737. for (index = 0; index < objects.length; index++) {
  9738. if (objects[index].parent == this) {
  9739. objects[index].dispose();
  9740. }
  9741. }
  9742. }
  9743. else {
  9744. for (index = 0; index < this.getScene().meshes.length; index++) {
  9745. var obj = this.getScene().meshes[index];
  9746. if (obj.parent === this) {
  9747. obj.parent = null;
  9748. obj.computeWorldMatrix(true);
  9749. }
  9750. }
  9751. }
  9752. this._onAfterWorldMatrixUpdate = [];
  9753. this._isDisposed = true;
  9754. // Callback
  9755. if (this.onDispose) {
  9756. this.onDispose();
  9757. }
  9758. };
  9759. // Statics
  9760. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9761. AbstractMesh._BILLBOARDMODE_X = 1;
  9762. AbstractMesh._BILLBOARDMODE_Y = 2;
  9763. AbstractMesh._BILLBOARDMODE_Z = 4;
  9764. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9765. return AbstractMesh;
  9766. })(BABYLON.Node);
  9767. BABYLON.AbstractMesh = AbstractMesh;
  9768. })(BABYLON || (BABYLON = {}));
  9769. //# sourceMappingURL=babylon.abstractMesh.js.map
  9770. var BABYLON;
  9771. (function (BABYLON) {
  9772. var _InstancesBatch = (function () {
  9773. function _InstancesBatch() {
  9774. this.mustReturn = false;
  9775. this.visibleInstances = new Array();
  9776. this.renderSelf = new Array();
  9777. }
  9778. return _InstancesBatch;
  9779. })();
  9780. BABYLON._InstancesBatch = _InstancesBatch;
  9781. var Mesh = (function (_super) {
  9782. __extends(Mesh, _super);
  9783. /**
  9784. * @constructor
  9785. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9786. * @param {Scene} scene - The scene to add this mesh to.
  9787. * @param {Node} parent - The parent of this mesh, if it has one
  9788. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9789. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9790. * When false, achieved by calling a clone(), also passing False.
  9791. * This will make creation of children, recursive.
  9792. */
  9793. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9794. if (parent === void 0) { parent = null; }
  9795. _super.call(this, name, scene);
  9796. // Members
  9797. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9798. this.instances = new Array();
  9799. this._LODLevels = new Array();
  9800. this._onBeforeRenderCallbacks = new Array();
  9801. this._onAfterRenderCallbacks = new Array();
  9802. this._visibleInstances = {};
  9803. this._renderIdForInstances = new Array();
  9804. this._batchCache = new _InstancesBatch();
  9805. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  9806. if (source) {
  9807. // Geometry
  9808. if (source._geometry) {
  9809. source._geometry.applyToMesh(this);
  9810. }
  9811. // Deep copy
  9812. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9813. // Material
  9814. this.material = source.material;
  9815. if (!doNotCloneChildren) {
  9816. for (var index = 0; index < scene.meshes.length; index++) {
  9817. var mesh = scene.meshes[index];
  9818. if (mesh.parent === source) {
  9819. // doNotCloneChildren is always going to be False
  9820. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9821. }
  9822. }
  9823. }
  9824. for (index = 0; index < scene.particleSystems.length; index++) {
  9825. var system = scene.particleSystems[index];
  9826. if (system.emitter === source) {
  9827. system.clone(system.name, this);
  9828. }
  9829. }
  9830. this.computeWorldMatrix(true);
  9831. }
  9832. // Parent
  9833. if (parent !== null) {
  9834. this.parent = parent;
  9835. }
  9836. }
  9837. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9838. // Methods
  9839. get: function () {
  9840. return this._LODLevels.length > 0;
  9841. },
  9842. enumerable: true,
  9843. configurable: true
  9844. });
  9845. Mesh.prototype._sortLODLevels = function () {
  9846. this._LODLevels.sort(function (a, b) {
  9847. if (a.distance < b.distance) {
  9848. return 1;
  9849. }
  9850. if (a.distance > b.distance) {
  9851. return -1;
  9852. }
  9853. return 0;
  9854. });
  9855. };
  9856. /**
  9857. * Add a mesh as LOD level triggered at the given distance.
  9858. * @param {number} distance - the distance from the center of the object to show this level
  9859. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  9860. * @return {BABYLON.Mesh} this mesh (for chaining)
  9861. */
  9862. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9863. if (mesh && mesh._masterMesh) {
  9864. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9865. return this;
  9866. }
  9867. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9868. this._LODLevels.push(level);
  9869. if (mesh) {
  9870. mesh._masterMesh = this;
  9871. }
  9872. this._sortLODLevels();
  9873. return this;
  9874. };
  9875. /**
  9876. * Remove a mesh from the LOD array
  9877. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  9878. * @return {BABYLON.Mesh} this mesh (for chaining)
  9879. */
  9880. Mesh.prototype.removeLODLevel = function (mesh) {
  9881. for (var index = 0; index < this._LODLevels.length; index++) {
  9882. if (this._LODLevels[index].mesh === mesh) {
  9883. this._LODLevels.splice(index, 1);
  9884. if (mesh) {
  9885. mesh._masterMesh = null;
  9886. }
  9887. }
  9888. }
  9889. this._sortLODLevels();
  9890. return this;
  9891. };
  9892. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9893. if (!this._LODLevels || this._LODLevels.length === 0) {
  9894. return this;
  9895. }
  9896. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9897. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9898. return this;
  9899. }
  9900. for (var index = 0; index < this._LODLevels.length; index++) {
  9901. var level = this._LODLevels[index];
  9902. if (level.distance < distanceToCamera) {
  9903. if (level.mesh) {
  9904. level.mesh._preActivate();
  9905. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9906. }
  9907. return level.mesh;
  9908. }
  9909. }
  9910. return this;
  9911. };
  9912. Object.defineProperty(Mesh.prototype, "geometry", {
  9913. get: function () {
  9914. return this._geometry;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Mesh.prototype.getTotalVertices = function () {
  9920. if (!this._geometry) {
  9921. return 0;
  9922. }
  9923. return this._geometry.getTotalVertices();
  9924. };
  9925. Mesh.prototype.getVerticesData = function (kind) {
  9926. if (!this._geometry) {
  9927. return null;
  9928. }
  9929. return this._geometry.getVerticesData(kind);
  9930. };
  9931. Mesh.prototype.getVertexBuffer = function (kind) {
  9932. if (!this._geometry) {
  9933. return undefined;
  9934. }
  9935. return this._geometry.getVertexBuffer(kind);
  9936. };
  9937. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9938. if (!this._geometry) {
  9939. if (this._delayInfo) {
  9940. return this._delayInfo.indexOf(kind) !== -1;
  9941. }
  9942. return false;
  9943. }
  9944. return this._geometry.isVerticesDataPresent(kind);
  9945. };
  9946. Mesh.prototype.getVerticesDataKinds = function () {
  9947. if (!this._geometry) {
  9948. var result = [];
  9949. if (this._delayInfo) {
  9950. for (var kind in this._delayInfo) {
  9951. result.push(kind);
  9952. }
  9953. }
  9954. return result;
  9955. }
  9956. return this._geometry.getVerticesDataKinds();
  9957. };
  9958. Mesh.prototype.getTotalIndices = function () {
  9959. if (!this._geometry) {
  9960. return 0;
  9961. }
  9962. return this._geometry.getTotalIndices();
  9963. };
  9964. Mesh.prototype.getIndices = function () {
  9965. if (!this._geometry) {
  9966. return [];
  9967. }
  9968. return this._geometry.getIndices();
  9969. };
  9970. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9971. get: function () {
  9972. return this._masterMesh !== null && this._masterMesh !== undefined;
  9973. },
  9974. enumerable: true,
  9975. configurable: true
  9976. });
  9977. Mesh.prototype.isReady = function () {
  9978. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9979. return false;
  9980. }
  9981. return _super.prototype.isReady.call(this);
  9982. };
  9983. Mesh.prototype.isDisposed = function () {
  9984. return this._isDisposed;
  9985. };
  9986. // Methods
  9987. Mesh.prototype._preActivate = function () {
  9988. var sceneRenderId = this.getScene().getRenderId();
  9989. if (this._preActivateId == sceneRenderId) {
  9990. return;
  9991. }
  9992. this._preActivateId = sceneRenderId;
  9993. this._visibleInstances = null;
  9994. };
  9995. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9996. if (!this._visibleInstances) {
  9997. this._visibleInstances = {};
  9998. this._visibleInstances.defaultRenderId = renderId;
  9999. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10000. }
  10001. if (!this._visibleInstances[renderId]) {
  10002. this._visibleInstances[renderId] = new Array();
  10003. }
  10004. this._visibleInstances[renderId].push(instance);
  10005. };
  10006. Mesh.prototype.refreshBoundingInfo = function () {
  10007. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10008. if (data) {
  10009. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10010. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10011. }
  10012. if (this.subMeshes) {
  10013. for (var index = 0; index < this.subMeshes.length; index++) {
  10014. this.subMeshes[index].refreshBoundingInfo();
  10015. }
  10016. }
  10017. this._updateBoundingInfo();
  10018. };
  10019. Mesh.prototype._createGlobalSubMesh = function () {
  10020. var totalVertices = this.getTotalVertices();
  10021. if (!totalVertices || !this.getIndices()) {
  10022. return null;
  10023. }
  10024. this.releaseSubMeshes();
  10025. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10026. };
  10027. Mesh.prototype.subdivide = function (count) {
  10028. if (count < 1) {
  10029. return;
  10030. }
  10031. var totalIndices = this.getTotalIndices();
  10032. var subdivisionSize = (totalIndices / count) | 0;
  10033. var offset = 0;
  10034. while (subdivisionSize % 3 != 0) {
  10035. subdivisionSize++;
  10036. }
  10037. this.releaseSubMeshes();
  10038. for (var index = 0; index < count; index++) {
  10039. if (offset >= totalIndices) {
  10040. break;
  10041. }
  10042. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10043. offset += subdivisionSize;
  10044. }
  10045. this.synchronizeInstances();
  10046. };
  10047. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10048. if (kind instanceof Array) {
  10049. var temp = data;
  10050. data = kind;
  10051. kind = temp;
  10052. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10053. }
  10054. if (!this._geometry) {
  10055. var vertexData = new BABYLON.VertexData();
  10056. vertexData.set(data, kind);
  10057. var scene = this.getScene();
  10058. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10059. }
  10060. else {
  10061. this._geometry.setVerticesData(kind, data, updatable, stride);
  10062. }
  10063. };
  10064. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10065. if (!this._geometry) {
  10066. return;
  10067. }
  10068. if (!makeItUnique) {
  10069. this._geometry.updateVerticesData(kind, data, updateExtends);
  10070. }
  10071. else {
  10072. this.makeGeometryUnique();
  10073. this.updateVerticesData(kind, data, updateExtends, false);
  10074. }
  10075. };
  10076. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10077. if (!this._geometry) {
  10078. return;
  10079. }
  10080. if (!makeItUnique) {
  10081. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10082. }
  10083. else {
  10084. this.makeGeometryUnique();
  10085. this.updateVerticesDataDirectly(kind, data, offset, false);
  10086. }
  10087. };
  10088. Mesh.prototype.makeGeometryUnique = function () {
  10089. if (!this._geometry) {
  10090. return;
  10091. }
  10092. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10093. geometry.applyToMesh(this);
  10094. };
  10095. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10096. if (!this._geometry) {
  10097. var vertexData = new BABYLON.VertexData();
  10098. vertexData.indices = indices;
  10099. var scene = this.getScene();
  10100. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10101. }
  10102. else {
  10103. this._geometry.setIndices(indices, totalVertices);
  10104. }
  10105. };
  10106. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10107. var engine = this.getScene().getEngine();
  10108. // Wireframe
  10109. var indexToBind;
  10110. switch (fillMode) {
  10111. case BABYLON.Material.PointFillMode:
  10112. indexToBind = null;
  10113. break;
  10114. case BABYLON.Material.WireFrameFillMode:
  10115. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10116. break;
  10117. default:
  10118. case BABYLON.Material.TriangleFillMode:
  10119. indexToBind = this._geometry.getIndexBuffer();
  10120. break;
  10121. }
  10122. // VBOs
  10123. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10124. };
  10125. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10126. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10127. return;
  10128. }
  10129. var engine = this.getScene().getEngine();
  10130. switch (fillMode) {
  10131. case BABYLON.Material.PointFillMode:
  10132. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10133. break;
  10134. case BABYLON.Material.WireFrameFillMode:
  10135. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10136. break;
  10137. default:
  10138. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10139. }
  10140. };
  10141. Mesh.prototype.registerBeforeRender = function (func) {
  10142. this._onBeforeRenderCallbacks.push(func);
  10143. };
  10144. Mesh.prototype.unregisterBeforeRender = function (func) {
  10145. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10146. if (index > -1) {
  10147. this._onBeforeRenderCallbacks.splice(index, 1);
  10148. }
  10149. };
  10150. Mesh.prototype.registerAfterRender = function (func) {
  10151. this._onAfterRenderCallbacks.push(func);
  10152. };
  10153. Mesh.prototype.unregisterAfterRender = function (func) {
  10154. var index = this._onAfterRenderCallbacks.indexOf(func);
  10155. if (index > -1) {
  10156. this._onAfterRenderCallbacks.splice(index, 1);
  10157. }
  10158. };
  10159. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10160. var scene = this.getScene();
  10161. this._batchCache.mustReturn = false;
  10162. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10163. this._batchCache.visibleInstances[subMeshId] = null;
  10164. if (this._visibleInstances) {
  10165. var currentRenderId = scene.getRenderId();
  10166. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10167. var selfRenderId = this._renderId;
  10168. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10169. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10170. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10171. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10172. }
  10173. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10174. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10175. this._batchCache.mustReturn = true;
  10176. return this._batchCache;
  10177. }
  10178. if (currentRenderId !== selfRenderId) {
  10179. this._batchCache.renderSelf[subMeshId] = false;
  10180. }
  10181. }
  10182. this._renderIdForInstances[subMeshId] = currentRenderId;
  10183. }
  10184. return this._batchCache;
  10185. };
  10186. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10187. var visibleInstances = batch.visibleInstances[subMesh._id];
  10188. var matricesCount = visibleInstances.length + 1;
  10189. var bufferSize = matricesCount * 16 * 4;
  10190. while (this._instancesBufferSize < bufferSize) {
  10191. this._instancesBufferSize *= 2;
  10192. }
  10193. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10194. if (this._worldMatricesInstancesBuffer) {
  10195. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10196. }
  10197. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10198. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10199. }
  10200. var offset = 0;
  10201. var instancesCount = 0;
  10202. var world = this.getWorldMatrix();
  10203. if (batch.renderSelf[subMesh._id]) {
  10204. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10205. offset += 16;
  10206. instancesCount++;
  10207. }
  10208. if (visibleInstances) {
  10209. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10210. var instance = visibleInstances[instanceIndex];
  10211. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10212. offset += 16;
  10213. instancesCount++;
  10214. }
  10215. }
  10216. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10217. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10218. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10219. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10220. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10221. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10222. this._draw(subMesh, fillMode, instancesCount);
  10223. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10224. };
  10225. Mesh.prototype.render = function (subMesh) {
  10226. var scene = this.getScene();
  10227. // Managing instances
  10228. var batch = this._getInstancesRenderList(subMesh._id);
  10229. if (batch.mustReturn) {
  10230. return;
  10231. }
  10232. // Checking geometry state
  10233. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10234. return;
  10235. }
  10236. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10237. this._onBeforeRenderCallbacks[callbackIndex]();
  10238. }
  10239. var engine = scene.getEngine();
  10240. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10241. // Material
  10242. var effectiveMaterial = subMesh.getMaterial();
  10243. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10244. return;
  10245. }
  10246. // Outline - step 1
  10247. var savedDepthWrite = engine.getDepthWrite();
  10248. if (this.renderOutline) {
  10249. engine.setDepthWrite(false);
  10250. scene.getOutlineRenderer().render(subMesh, batch);
  10251. engine.setDepthWrite(savedDepthWrite);
  10252. }
  10253. effectiveMaterial._preBind();
  10254. var effect = effectiveMaterial.getEffect();
  10255. // Bind
  10256. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10257. this._bind(subMesh, effect, fillMode);
  10258. var world = this.getWorldMatrix();
  10259. effectiveMaterial.bind(world, this);
  10260. // Instances rendering
  10261. if (hardwareInstancedRendering) {
  10262. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10263. }
  10264. else {
  10265. if (batch.renderSelf[subMesh._id]) {
  10266. // Draw
  10267. this._draw(subMesh, fillMode);
  10268. }
  10269. if (batch.visibleInstances[subMesh._id]) {
  10270. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10271. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10272. // World
  10273. world = instance.getWorldMatrix();
  10274. effectiveMaterial.bindOnlyWorldMatrix(world);
  10275. // Draw
  10276. this._draw(subMesh, fillMode);
  10277. }
  10278. }
  10279. }
  10280. // Unbind
  10281. effectiveMaterial.unbind();
  10282. // Outline - step 2
  10283. if (this.renderOutline && savedDepthWrite) {
  10284. engine.setDepthWrite(true);
  10285. engine.setColorWrite(false);
  10286. scene.getOutlineRenderer().render(subMesh, batch);
  10287. engine.setColorWrite(true);
  10288. }
  10289. // Overlay
  10290. if (this.renderOverlay) {
  10291. var currentMode = engine.getAlphaMode();
  10292. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10293. scene.getOutlineRenderer().render(subMesh, batch, true);
  10294. engine.setAlphaMode(currentMode);
  10295. }
  10296. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10297. this._onAfterRenderCallbacks[callbackIndex]();
  10298. }
  10299. };
  10300. Mesh.prototype.getEmittedParticleSystems = function () {
  10301. var results = new Array();
  10302. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10303. var particleSystem = this.getScene().particleSystems[index];
  10304. if (particleSystem.emitter === this) {
  10305. results.push(particleSystem);
  10306. }
  10307. }
  10308. return results;
  10309. };
  10310. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10311. var results = new Array();
  10312. var descendants = this.getDescendants();
  10313. descendants.push(this);
  10314. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10315. var particleSystem = this.getScene().particleSystems[index];
  10316. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10317. results.push(particleSystem);
  10318. }
  10319. }
  10320. return results;
  10321. };
  10322. Mesh.prototype.getChildren = function () {
  10323. var results = [];
  10324. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10325. var mesh = this.getScene().meshes[index];
  10326. if (mesh.parent == this) {
  10327. results.push(mesh);
  10328. }
  10329. }
  10330. return results;
  10331. };
  10332. Mesh.prototype._checkDelayState = function () {
  10333. var _this = this;
  10334. var that = this;
  10335. var scene = this.getScene();
  10336. if (this._geometry) {
  10337. this._geometry.load(scene);
  10338. }
  10339. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10340. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10341. scene._addPendingData(that);
  10342. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  10343. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10344. if (data instanceof ArrayBuffer) {
  10345. _this._delayLoadingFunction(data, _this);
  10346. }
  10347. else {
  10348. _this._delayLoadingFunction(JSON.parse(data), _this);
  10349. }
  10350. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10351. scene._removePendingData(_this);
  10352. }, function () {
  10353. }, scene.database, getBinaryData);
  10354. }
  10355. };
  10356. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10357. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10358. return false;
  10359. }
  10360. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10361. return false;
  10362. }
  10363. this._checkDelayState();
  10364. return true;
  10365. };
  10366. Mesh.prototype.setMaterialByID = function (id) {
  10367. var materials = this.getScene().materials;
  10368. for (var index = 0; index < materials.length; index++) {
  10369. if (materials[index].id == id) {
  10370. this.material = materials[index];
  10371. return;
  10372. }
  10373. }
  10374. // Multi
  10375. var multiMaterials = this.getScene().multiMaterials;
  10376. for (index = 0; index < multiMaterials.length; index++) {
  10377. if (multiMaterials[index].id == id) {
  10378. this.material = multiMaterials[index];
  10379. return;
  10380. }
  10381. }
  10382. };
  10383. Mesh.prototype.getAnimatables = function () {
  10384. var results = [];
  10385. if (this.material) {
  10386. results.push(this.material);
  10387. }
  10388. if (this.skeleton) {
  10389. results.push(this.skeleton);
  10390. }
  10391. return results;
  10392. };
  10393. // Geometry
  10394. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10395. // Position
  10396. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10397. return;
  10398. }
  10399. this._resetPointsArrayCache();
  10400. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10401. var temp = [];
  10402. for (var index = 0; index < data.length; index += 3) {
  10403. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10404. }
  10405. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10406. // Normals
  10407. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10408. return;
  10409. }
  10410. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10411. for (index = 0; index < data.length; index += 3) {
  10412. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10413. }
  10414. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10415. };
  10416. // Cache
  10417. Mesh.prototype._resetPointsArrayCache = function () {
  10418. this._positions = null;
  10419. };
  10420. Mesh.prototype._generatePointsArray = function () {
  10421. if (this._positions)
  10422. return true;
  10423. this._positions = [];
  10424. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10425. if (!data) {
  10426. return false;
  10427. }
  10428. for (var index = 0; index < data.length; index += 3) {
  10429. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10430. }
  10431. return true;
  10432. };
  10433. // Clone
  10434. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10435. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10436. };
  10437. // Dispose
  10438. Mesh.prototype.dispose = function (doNotRecurse) {
  10439. if (this._geometry) {
  10440. this._geometry.releaseForMesh(this, true);
  10441. }
  10442. // Instances
  10443. if (this._worldMatricesInstancesBuffer) {
  10444. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10445. this._worldMatricesInstancesBuffer = null;
  10446. }
  10447. while (this.instances.length) {
  10448. this.instances[0].dispose();
  10449. }
  10450. _super.prototype.dispose.call(this, doNotRecurse);
  10451. };
  10452. // Geometric tools
  10453. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10454. var _this = this;
  10455. var scene = this.getScene();
  10456. var onload = function (img) {
  10457. // Getting height map data
  10458. var canvas = document.createElement("canvas");
  10459. var context = canvas.getContext("2d");
  10460. var heightMapWidth = img.width;
  10461. var heightMapHeight = img.height;
  10462. canvas.width = heightMapWidth;
  10463. canvas.height = heightMapHeight;
  10464. context.drawImage(img, 0, 0);
  10465. // Create VertexData from map data
  10466. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10467. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10468. //execute success callback, if set
  10469. if (onSuccess) {
  10470. onSuccess(_this);
  10471. }
  10472. };
  10473. BABYLON.Tools.LoadImage(url, onload, function () {
  10474. }, scene.database);
  10475. };
  10476. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10477. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10478. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10479. return;
  10480. }
  10481. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10482. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10483. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10484. var position = BABYLON.Vector3.Zero();
  10485. var normal = BABYLON.Vector3.Zero();
  10486. var uv = BABYLON.Vector2.Zero();
  10487. for (var index = 0; index < positions.length; index += 3) {
  10488. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10489. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10490. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10491. // Compute height
  10492. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10493. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10494. var pos = (u + v * heightMapWidth) * 4;
  10495. var r = buffer[pos] / 255.0;
  10496. var g = buffer[pos + 1] / 255.0;
  10497. var b = buffer[pos + 2] / 255.0;
  10498. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10499. normal.normalize();
  10500. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10501. position = position.add(normal);
  10502. position.toArray(positions, index);
  10503. }
  10504. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10505. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10506. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10507. };
  10508. Mesh.prototype.convertToFlatShadedMesh = function () {
  10509. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10510. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10511. var kinds = this.getVerticesDataKinds();
  10512. var vbs = [];
  10513. var data = [];
  10514. var newdata = [];
  10515. var updatableNormals = false;
  10516. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10517. var kind = kinds[kindIndex];
  10518. var vertexBuffer = this.getVertexBuffer(kind);
  10519. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10520. updatableNormals = vertexBuffer.isUpdatable();
  10521. kinds.splice(kindIndex, 1);
  10522. kindIndex--;
  10523. continue;
  10524. }
  10525. vbs[kind] = vertexBuffer;
  10526. data[kind] = vbs[kind].getData();
  10527. newdata[kind] = [];
  10528. }
  10529. // Save previous submeshes
  10530. var previousSubmeshes = this.subMeshes.slice(0);
  10531. var indices = this.getIndices();
  10532. var totalIndices = this.getTotalIndices();
  10533. for (var index = 0; index < totalIndices; index++) {
  10534. var vertexIndex = indices[index];
  10535. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10536. kind = kinds[kindIndex];
  10537. var stride = vbs[kind].getStrideSize();
  10538. for (var offset = 0; offset < stride; offset++) {
  10539. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10540. }
  10541. }
  10542. }
  10543. // Updating faces & normal
  10544. var normals = [];
  10545. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10546. for (index = 0; index < totalIndices; index += 3) {
  10547. indices[index] = index;
  10548. indices[index + 1] = index + 1;
  10549. indices[index + 2] = index + 2;
  10550. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10551. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10552. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10553. var p1p2 = p1.subtract(p2);
  10554. var p3p2 = p3.subtract(p2);
  10555. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10556. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10557. normals.push(normal.x);
  10558. normals.push(normal.y);
  10559. normals.push(normal.z);
  10560. }
  10561. }
  10562. this.setIndices(indices);
  10563. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10564. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10565. kind = kinds[kindIndex];
  10566. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10567. }
  10568. // Updating submeshes
  10569. this.releaseSubMeshes();
  10570. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10571. var previousOne = previousSubmeshes[submeshIndex];
  10572. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10573. }
  10574. this.synchronizeInstances();
  10575. };
  10576. // Instances
  10577. Mesh.prototype.createInstance = function (name) {
  10578. return new BABYLON.InstancedMesh(name, this);
  10579. };
  10580. Mesh.prototype.synchronizeInstances = function () {
  10581. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10582. var instance = this.instances[instanceIndex];
  10583. instance._syncSubMeshes();
  10584. }
  10585. };
  10586. /**
  10587. * Simplify the mesh according to the given array of settings.
  10588. * Function will return immediately and will simplify async.
  10589. * @param settings a collection of simplification settings.
  10590. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10591. * @param type the type of simplification to run.
  10592. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10593. */
  10594. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10595. var _this = this;
  10596. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10597. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10598. var getSimplifier = function () {
  10599. switch (type) {
  10600. case 0 /* QUADRATIC */:
  10601. default:
  10602. return new BABYLON.QuadraticErrorSimplification(_this);
  10603. }
  10604. };
  10605. if (parallelProcessing) {
  10606. //parallel simplifier
  10607. settings.forEach(function (setting) {
  10608. var simplifier = getSimplifier();
  10609. simplifier.simplify(setting, function (newMesh) {
  10610. _this.addLODLevel(setting.distance, newMesh);
  10611. //check if it is the last
  10612. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10613. //all done, run the success callback.
  10614. successCallback();
  10615. }
  10616. });
  10617. });
  10618. }
  10619. else {
  10620. //single simplifier.
  10621. var simplifier = getSimplifier();
  10622. var runDecimation = function (setting, callback) {
  10623. simplifier.simplify(setting, function (newMesh) {
  10624. _this.addLODLevel(setting.distance, newMesh);
  10625. //run the next quality level
  10626. callback();
  10627. });
  10628. };
  10629. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10630. runDecimation(settings[loop.index], function () {
  10631. loop.executeNext();
  10632. });
  10633. }, function () {
  10634. //execution ended, run the success callback.
  10635. if (successCallback) {
  10636. successCallback();
  10637. }
  10638. });
  10639. }
  10640. };
  10641. // Statics
  10642. Mesh.CreateBox = function (name, size, scene, updatable) {
  10643. var box = new Mesh(name, scene);
  10644. var vertexData = BABYLON.VertexData.CreateBox(size);
  10645. vertexData.applyToMesh(box, updatable);
  10646. return box;
  10647. };
  10648. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10649. var sphere = new Mesh(name, scene);
  10650. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10651. vertexData.applyToMesh(sphere, updatable);
  10652. return sphere;
  10653. };
  10654. // Cylinder and cone (Code inspired by SharpDX.org)
  10655. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10656. // subdivisions is a new parameter, we need to support old signature
  10657. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10658. if (scene !== undefined) {
  10659. updatable = scene;
  10660. }
  10661. scene = subdivisions;
  10662. subdivisions = 1;
  10663. }
  10664. var cylinder = new Mesh(name, scene);
  10665. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10666. vertexData.applyToMesh(cylinder, updatable);
  10667. return cylinder;
  10668. };
  10669. // Torus (Code from SharpDX.org)
  10670. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10671. var torus = new Mesh(name, scene);
  10672. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10673. vertexData.applyToMesh(torus, updatable);
  10674. return torus;
  10675. };
  10676. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10677. var torusKnot = new Mesh(name, scene);
  10678. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10679. vertexData.applyToMesh(torusKnot, updatable);
  10680. return torusKnot;
  10681. };
  10682. // Lines
  10683. Mesh.CreateLines = function (name, points, scene, updatable) {
  10684. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10685. var vertexData = BABYLON.VertexData.CreateLines(points);
  10686. vertexData.applyToMesh(lines, updatable);
  10687. return lines;
  10688. };
  10689. // Plane & ground
  10690. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10691. var plane = new Mesh(name, scene);
  10692. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10693. vertexData.applyToMesh(plane, updatable);
  10694. return plane;
  10695. };
  10696. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10697. var ground = new BABYLON.GroundMesh(name, scene);
  10698. ground._setReady(false);
  10699. ground._subdivisions = subdivisions;
  10700. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10701. vertexData.applyToMesh(ground, updatable);
  10702. ground._setReady(true);
  10703. return ground;
  10704. };
  10705. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10706. var tiledGround = new Mesh(name, scene);
  10707. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10708. vertexData.applyToMesh(tiledGround, updatable);
  10709. return tiledGround;
  10710. };
  10711. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  10712. var ground = new BABYLON.GroundMesh(name, scene);
  10713. ground._subdivisions = subdivisions;
  10714. ground._setReady(false);
  10715. var onload = function (img) {
  10716. // Getting height map data
  10717. var canvas = document.createElement("canvas");
  10718. var context = canvas.getContext("2d");
  10719. var heightMapWidth = img.width;
  10720. var heightMapHeight = img.height;
  10721. canvas.width = heightMapWidth;
  10722. canvas.height = heightMapHeight;
  10723. context.drawImage(img, 0, 0);
  10724. // Create VertexData from map data
  10725. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10726. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10727. vertexData.applyToMesh(ground, updatable);
  10728. ground._setReady(true);
  10729. //execute ready callback, if set
  10730. if (onReady) {
  10731. onReady(ground);
  10732. }
  10733. };
  10734. BABYLON.Tools.LoadImage(url, onload, function () {
  10735. }, scene.database);
  10736. return ground;
  10737. };
  10738. // Tools
  10739. Mesh.MinMax = function (meshes) {
  10740. var minVector = null;
  10741. var maxVector = null;
  10742. for (var i in meshes) {
  10743. var mesh = meshes[i];
  10744. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10745. if (!minVector) {
  10746. minVector = boundingBox.minimumWorld;
  10747. maxVector = boundingBox.maximumWorld;
  10748. continue;
  10749. }
  10750. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10751. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10752. }
  10753. return {
  10754. min: minVector,
  10755. max: maxVector
  10756. };
  10757. };
  10758. Mesh.Center = function (meshesOrMinMaxVector) {
  10759. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10760. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10761. };
  10762. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10763. if (disposeSource === void 0) { disposeSource = true; }
  10764. var source = meshes[0];
  10765. var material = source.material;
  10766. var scene = source.getScene();
  10767. if (!allow32BitsIndices) {
  10768. var totalVertices = 0;
  10769. for (var index = 0; index < meshes.length; index++) {
  10770. totalVertices += meshes[index].getTotalVertices();
  10771. if (totalVertices > 65536) {
  10772. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10773. return null;
  10774. }
  10775. }
  10776. }
  10777. // Merge
  10778. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10779. vertexData.transform(source.getWorldMatrix());
  10780. for (index = 1; index < meshes.length; index++) {
  10781. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10782. otherVertexData.transform(meshes[index].getWorldMatrix());
  10783. vertexData.merge(otherVertexData);
  10784. }
  10785. var newMesh = new Mesh(source.name + "_merged", scene);
  10786. vertexData.applyToMesh(newMesh);
  10787. // Setting properties
  10788. newMesh.material = material;
  10789. newMesh.checkCollisions = source.checkCollisions;
  10790. // Cleaning
  10791. if (disposeSource) {
  10792. for (index = 0; index < meshes.length; index++) {
  10793. meshes[index].dispose();
  10794. }
  10795. }
  10796. return newMesh;
  10797. };
  10798. return Mesh;
  10799. })(BABYLON.AbstractMesh);
  10800. BABYLON.Mesh = Mesh;
  10801. })(BABYLON || (BABYLON = {}));
  10802. //# sourceMappingURL=babylon.mesh.js.map
  10803. var BABYLON;
  10804. (function (BABYLON) {
  10805. var GroundMesh = (function (_super) {
  10806. __extends(GroundMesh, _super);
  10807. function GroundMesh(name, scene) {
  10808. _super.call(this, name, scene);
  10809. this.generateOctree = false;
  10810. this._worldInverse = new BABYLON.Matrix();
  10811. }
  10812. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10813. get: function () {
  10814. return this._subdivisions;
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. GroundMesh.prototype.optimize = function (chunksCount) {
  10820. this.subdivide(this._subdivisions);
  10821. this.createOrUpdateSubmeshesOctree(32);
  10822. };
  10823. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10824. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10825. this.getWorldMatrix().invertToRef(this._worldInverse);
  10826. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10827. var pickInfo = this.intersects(ray);
  10828. if (pickInfo.hit) {
  10829. return pickInfo.pickedPoint.y;
  10830. }
  10831. return 0;
  10832. };
  10833. return GroundMesh;
  10834. })(BABYLON.Mesh);
  10835. BABYLON.GroundMesh = GroundMesh;
  10836. })(BABYLON || (BABYLON = {}));
  10837. //# sourceMappingURL=babylon.groundMesh.js.map
  10838. var BABYLON;
  10839. (function (BABYLON) {
  10840. /**
  10841. * Creates an instance based on a source mesh.
  10842. */
  10843. var InstancedMesh = (function (_super) {
  10844. __extends(InstancedMesh, _super);
  10845. function InstancedMesh(name, source) {
  10846. _super.call(this, name, source.getScene());
  10847. source.instances.push(this);
  10848. this._sourceMesh = source;
  10849. this.position.copyFrom(source.position);
  10850. this.rotation.copyFrom(source.rotation);
  10851. this.scaling.copyFrom(source.scaling);
  10852. if (source.rotationQuaternion) {
  10853. this.rotationQuaternion = source.rotationQuaternion.clone();
  10854. }
  10855. this.infiniteDistance = source.infiniteDistance;
  10856. this.setPivotMatrix(source.getPivotMatrix());
  10857. this.refreshBoundingInfo();
  10858. this._syncSubMeshes();
  10859. }
  10860. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10861. // Methods
  10862. get: function () {
  10863. return this._sourceMesh.receiveShadows;
  10864. },
  10865. enumerable: true,
  10866. configurable: true
  10867. });
  10868. Object.defineProperty(InstancedMesh.prototype, "material", {
  10869. get: function () {
  10870. return this._sourceMesh.material;
  10871. },
  10872. enumerable: true,
  10873. configurable: true
  10874. });
  10875. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10876. get: function () {
  10877. return this._sourceMesh.visibility;
  10878. },
  10879. enumerable: true,
  10880. configurable: true
  10881. });
  10882. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10883. get: function () {
  10884. return this._sourceMesh.skeleton;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. InstancedMesh.prototype.getTotalVertices = function () {
  10890. return this._sourceMesh.getTotalVertices();
  10891. };
  10892. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10893. get: function () {
  10894. return this._sourceMesh;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. InstancedMesh.prototype.getVerticesData = function (kind) {
  10900. return this._sourceMesh.getVerticesData(kind);
  10901. };
  10902. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10903. return this._sourceMesh.isVerticesDataPresent(kind);
  10904. };
  10905. InstancedMesh.prototype.getIndices = function () {
  10906. return this._sourceMesh.getIndices();
  10907. };
  10908. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10909. get: function () {
  10910. return this._sourceMesh._positions;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10916. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10917. if (data) {
  10918. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10919. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10920. }
  10921. this._updateBoundingInfo();
  10922. };
  10923. InstancedMesh.prototype._preActivate = function () {
  10924. if (this._currentLOD) {
  10925. this._currentLOD._preActivate();
  10926. }
  10927. };
  10928. InstancedMesh.prototype._activate = function (renderId) {
  10929. if (this._currentLOD) {
  10930. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10931. }
  10932. };
  10933. InstancedMesh.prototype.getLOD = function (camera) {
  10934. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10935. if (this._currentLOD === this.sourceMesh) {
  10936. return this;
  10937. }
  10938. return this._currentLOD;
  10939. };
  10940. InstancedMesh.prototype._syncSubMeshes = function () {
  10941. this.releaseSubMeshes();
  10942. if (this._sourceMesh.subMeshes) {
  10943. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10944. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10945. }
  10946. }
  10947. };
  10948. InstancedMesh.prototype._generatePointsArray = function () {
  10949. return this._sourceMesh._generatePointsArray();
  10950. };
  10951. // Clone
  10952. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10953. var result = this._sourceMesh.createInstance(name);
  10954. // Deep copy
  10955. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10956. // Bounding info
  10957. this.refreshBoundingInfo();
  10958. // Parent
  10959. if (newParent) {
  10960. result.parent = newParent;
  10961. }
  10962. if (!doNotCloneChildren) {
  10963. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10964. var mesh = this.getScene().meshes[index];
  10965. if (mesh.parent === this) {
  10966. mesh.clone(mesh.name, result);
  10967. }
  10968. }
  10969. }
  10970. result.computeWorldMatrix(true);
  10971. return result;
  10972. };
  10973. // Dispoe
  10974. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10975. // Remove from mesh
  10976. var index = this._sourceMesh.instances.indexOf(this);
  10977. this._sourceMesh.instances.splice(index, 1);
  10978. _super.prototype.dispose.call(this, doNotRecurse);
  10979. };
  10980. return InstancedMesh;
  10981. })(BABYLON.AbstractMesh);
  10982. BABYLON.InstancedMesh = InstancedMesh;
  10983. })(BABYLON || (BABYLON = {}));
  10984. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  10985. (function (BABYLON) {
  10986. var SubMesh = (function () {
  10987. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10988. if (createBoundingBox === void 0) { createBoundingBox = true; }
  10989. this.materialIndex = materialIndex;
  10990. this.verticesStart = verticesStart;
  10991. this.verticesCount = verticesCount;
  10992. this.indexStart = indexStart;
  10993. this.indexCount = indexCount;
  10994. this._renderId = 0;
  10995. this._mesh = mesh;
  10996. this._renderingMesh = renderingMesh || mesh;
  10997. mesh.subMeshes.push(this);
  10998. this._id = mesh.subMeshes.length - 1;
  10999. if (createBoundingBox) {
  11000. this.refreshBoundingInfo();
  11001. }
  11002. }
  11003. SubMesh.prototype.getBoundingInfo = function () {
  11004. return this._boundingInfo;
  11005. };
  11006. SubMesh.prototype.getMesh = function () {
  11007. return this._mesh;
  11008. };
  11009. SubMesh.prototype.getRenderingMesh = function () {
  11010. return this._renderingMesh;
  11011. };
  11012. SubMesh.prototype.getMaterial = function () {
  11013. var rootMaterial = this._renderingMesh.material;
  11014. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11015. var multiMaterial = rootMaterial;
  11016. return multiMaterial.getSubMaterial(this.materialIndex);
  11017. }
  11018. if (!rootMaterial) {
  11019. return this._mesh.getScene().defaultMaterial;
  11020. }
  11021. return rootMaterial;
  11022. };
  11023. // Methods
  11024. SubMesh.prototype.refreshBoundingInfo = function () {
  11025. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11026. if (!data) {
  11027. this._boundingInfo = this._mesh._boundingInfo;
  11028. return;
  11029. }
  11030. var indices = this._renderingMesh.getIndices();
  11031. var extend;
  11032. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11033. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11034. }
  11035. else {
  11036. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11037. }
  11038. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11039. };
  11040. SubMesh.prototype._checkCollision = function (collider) {
  11041. return this._boundingInfo._checkCollision(collider);
  11042. };
  11043. SubMesh.prototype.updateBoundingInfo = function (world) {
  11044. if (!this._boundingInfo) {
  11045. this.refreshBoundingInfo();
  11046. }
  11047. this._boundingInfo._update(world);
  11048. };
  11049. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11050. return this._boundingInfo.isInFrustum(frustumPlanes);
  11051. };
  11052. SubMesh.prototype.render = function () {
  11053. this._renderingMesh.render(this);
  11054. };
  11055. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11056. if (!this._linesIndexBuffer) {
  11057. var linesIndices = [];
  11058. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11059. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11060. }
  11061. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11062. this.linesIndexCount = linesIndices.length;
  11063. }
  11064. return this._linesIndexBuffer;
  11065. };
  11066. SubMesh.prototype.canIntersects = function (ray) {
  11067. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11068. };
  11069. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11070. var intersectInfo = null;
  11071. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11072. var p0 = positions[indices[index]];
  11073. var p1 = positions[indices[index + 1]];
  11074. var p2 = positions[indices[index + 2]];
  11075. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11076. if (currentIntersectInfo) {
  11077. if (currentIntersectInfo.distance < 0) {
  11078. continue;
  11079. }
  11080. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11081. intersectInfo = currentIntersectInfo;
  11082. intersectInfo.faceId = index / 3;
  11083. if (fastCheck) {
  11084. break;
  11085. }
  11086. }
  11087. }
  11088. }
  11089. return intersectInfo;
  11090. };
  11091. // Clone
  11092. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11093. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11094. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11095. return result;
  11096. };
  11097. // Dispose
  11098. SubMesh.prototype.dispose = function () {
  11099. if (this._linesIndexBuffer) {
  11100. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11101. this._linesIndexBuffer = null;
  11102. }
  11103. // Remove from mesh
  11104. var index = this._mesh.subMeshes.indexOf(this);
  11105. this._mesh.subMeshes.splice(index, 1);
  11106. };
  11107. // Statics
  11108. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11109. var minVertexIndex = Number.MAX_VALUE;
  11110. var maxVertexIndex = -Number.MAX_VALUE;
  11111. renderingMesh = renderingMesh || mesh;
  11112. var indices = renderingMesh.getIndices();
  11113. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11114. var vertexIndex = indices[index];
  11115. if (vertexIndex < minVertexIndex)
  11116. minVertexIndex = vertexIndex;
  11117. if (vertexIndex > maxVertexIndex)
  11118. maxVertexIndex = vertexIndex;
  11119. }
  11120. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11121. };
  11122. return SubMesh;
  11123. })();
  11124. BABYLON.SubMesh = SubMesh;
  11125. })(BABYLON || (BABYLON = {}));
  11126. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11127. (function (BABYLON) {
  11128. var BaseTexture = (function () {
  11129. function BaseTexture(scene) {
  11130. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11131. this.hasAlpha = false;
  11132. this.getAlphaFromRGB = false;
  11133. this.level = 1;
  11134. this.isCube = false;
  11135. this.isRenderTarget = false;
  11136. this.animations = new Array();
  11137. this.coordinatesIndex = 0;
  11138. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11139. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11140. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11141. this.anisotropicFilteringLevel = 4;
  11142. this._scene = scene;
  11143. this._scene.textures.push(this);
  11144. }
  11145. BaseTexture.prototype.getScene = function () {
  11146. return this._scene;
  11147. };
  11148. BaseTexture.prototype.getTextureMatrix = function () {
  11149. return null;
  11150. };
  11151. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11152. return null;
  11153. };
  11154. BaseTexture.prototype.getInternalTexture = function () {
  11155. return this._texture;
  11156. };
  11157. BaseTexture.prototype.isReady = function () {
  11158. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11159. return true;
  11160. }
  11161. if (this._texture) {
  11162. return this._texture.isReady;
  11163. }
  11164. return false;
  11165. };
  11166. BaseTexture.prototype.getSize = function () {
  11167. if (this._texture._width) {
  11168. return { width: this._texture._width, height: this._texture._height };
  11169. }
  11170. if (this._texture._size) {
  11171. return { width: this._texture._size, height: this._texture._size };
  11172. }
  11173. return { width: 0, height: 0 };
  11174. };
  11175. BaseTexture.prototype.getBaseSize = function () {
  11176. if (!this.isReady())
  11177. return { width: 0, height: 0 };
  11178. if (this._texture._size) {
  11179. return { width: this._texture._size, height: this._texture._size };
  11180. }
  11181. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11182. };
  11183. BaseTexture.prototype.scale = function (ratio) {
  11184. };
  11185. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11186. get: function () {
  11187. return false;
  11188. },
  11189. enumerable: true,
  11190. configurable: true
  11191. });
  11192. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11193. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11194. for (var index = 0; index < texturesCache.length; index++) {
  11195. var texturesCacheEntry = texturesCache[index];
  11196. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11197. texturesCache.splice(index, 1);
  11198. return;
  11199. }
  11200. }
  11201. };
  11202. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11203. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11204. for (var index = 0; index < texturesCache.length; index++) {
  11205. var texturesCacheEntry = texturesCache[index];
  11206. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11207. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11208. texturesCacheEntry.references++;
  11209. return texturesCacheEntry;
  11210. }
  11211. }
  11212. }
  11213. return null;
  11214. };
  11215. BaseTexture.prototype.delayLoad = function () {
  11216. };
  11217. BaseTexture.prototype.releaseInternalTexture = function () {
  11218. if (!this._texture) {
  11219. return;
  11220. }
  11221. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11222. this._texture.references--;
  11223. // Final reference ?
  11224. if (this._texture.references === 0) {
  11225. var index = texturesCache.indexOf(this._texture);
  11226. texturesCache.splice(index, 1);
  11227. this._scene.getEngine()._releaseTexture(this._texture);
  11228. delete this._texture;
  11229. }
  11230. };
  11231. BaseTexture.prototype.clone = function () {
  11232. return null;
  11233. };
  11234. BaseTexture.prototype.dispose = function () {
  11235. // Remove from scene
  11236. var index = this._scene.textures.indexOf(this);
  11237. if (index >= 0) {
  11238. this._scene.textures.splice(index, 1);
  11239. }
  11240. if (this._texture === undefined) {
  11241. return;
  11242. }
  11243. this.releaseInternalTexture();
  11244. // Callback
  11245. if (this.onDispose) {
  11246. this.onDispose();
  11247. }
  11248. };
  11249. return BaseTexture;
  11250. })();
  11251. BABYLON.BaseTexture = BaseTexture;
  11252. })(BABYLON || (BABYLON = {}));
  11253. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11254. (function (BABYLON) {
  11255. var RenderingGroup = (function () {
  11256. function RenderingGroup(index, scene) {
  11257. this.index = index;
  11258. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11259. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11260. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11261. this._scene = scene;
  11262. }
  11263. RenderingGroup.prototype.render = function (customRenderFunction) {
  11264. if (customRenderFunction) {
  11265. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11266. return true;
  11267. }
  11268. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11269. return false;
  11270. }
  11271. var engine = this._scene.getEngine();
  11272. // Opaque
  11273. var subIndex;
  11274. var submesh;
  11275. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11276. submesh = this._opaqueSubMeshes.data[subIndex];
  11277. submesh.render();
  11278. }
  11279. // Alpha test
  11280. engine.setAlphaTesting(true);
  11281. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11282. submesh = this._alphaTestSubMeshes.data[subIndex];
  11283. submesh.render();
  11284. }
  11285. engine.setAlphaTesting(false);
  11286. // Transparent
  11287. if (this._transparentSubMeshes.length) {
  11288. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11289. submesh = this._transparentSubMeshes.data[subIndex];
  11290. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11291. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11292. }
  11293. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11294. sortedArray.sort(function (a, b) {
  11295. // Alpha index first
  11296. if (a._alphaIndex > b._alphaIndex) {
  11297. return 1;
  11298. }
  11299. if (a._alphaIndex < b._alphaIndex) {
  11300. return -1;
  11301. }
  11302. // Then distance to camera
  11303. if (a._distanceToCamera < b._distanceToCamera) {
  11304. return 1;
  11305. }
  11306. if (a._distanceToCamera > b._distanceToCamera) {
  11307. return -1;
  11308. }
  11309. return 0;
  11310. });
  11311. // Rendering
  11312. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11313. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11314. submesh = sortedArray[subIndex];
  11315. submesh.render();
  11316. }
  11317. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11318. }
  11319. return true;
  11320. };
  11321. RenderingGroup.prototype.prepare = function () {
  11322. this._opaqueSubMeshes.reset();
  11323. this._transparentSubMeshes.reset();
  11324. this._alphaTestSubMeshes.reset();
  11325. };
  11326. RenderingGroup.prototype.dispatch = function (subMesh) {
  11327. var material = subMesh.getMaterial();
  11328. var mesh = subMesh.getMesh();
  11329. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11330. this._transparentSubMeshes.push(subMesh);
  11331. }
  11332. else if (material.needAlphaTesting()) {
  11333. this._alphaTestSubMeshes.push(subMesh);
  11334. }
  11335. else {
  11336. this._opaqueSubMeshes.push(subMesh); // Opaque
  11337. }
  11338. };
  11339. return RenderingGroup;
  11340. })();
  11341. BABYLON.RenderingGroup = RenderingGroup;
  11342. })(BABYLON || (BABYLON = {}));
  11343. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11344. (function (BABYLON) {
  11345. var RenderingManager = (function () {
  11346. function RenderingManager(scene) {
  11347. this._renderingGroups = new Array();
  11348. this._scene = scene;
  11349. }
  11350. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11351. if (this._scene._activeParticleSystems.length === 0) {
  11352. return;
  11353. }
  11354. // Particles
  11355. var beforeParticlesDate = BABYLON.Tools.Now;
  11356. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11357. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11358. if (particleSystem.renderingGroupId !== index) {
  11359. continue;
  11360. }
  11361. this._clearDepthBuffer();
  11362. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11363. this._scene._activeParticles += particleSystem.render();
  11364. }
  11365. }
  11366. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11367. };
  11368. RenderingManager.prototype._renderSprites = function (index) {
  11369. if (this._scene.spriteManagers.length === 0) {
  11370. return;
  11371. }
  11372. // Sprites
  11373. var beforeSpritessDate = BABYLON.Tools.Now;
  11374. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11375. var spriteManager = this._scene.spriteManagers[id];
  11376. if (spriteManager.renderingGroupId === index) {
  11377. this._clearDepthBuffer();
  11378. spriteManager.render();
  11379. }
  11380. }
  11381. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11382. };
  11383. RenderingManager.prototype._clearDepthBuffer = function () {
  11384. if (this._depthBufferAlreadyCleaned) {
  11385. return;
  11386. }
  11387. this._scene.getEngine().clear(0, false, true);
  11388. this._depthBufferAlreadyCleaned = true;
  11389. };
  11390. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11391. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11392. this._depthBufferAlreadyCleaned = false;
  11393. var renderingGroup = this._renderingGroups[index];
  11394. if (renderingGroup) {
  11395. this._clearDepthBuffer();
  11396. if (!renderingGroup.render(customRenderFunction)) {
  11397. this._renderingGroups.splice(index, 1);
  11398. }
  11399. }
  11400. if (renderSprites) {
  11401. this._renderSprites(index);
  11402. }
  11403. if (renderParticles) {
  11404. this._renderParticles(index, activeMeshes);
  11405. }
  11406. }
  11407. };
  11408. RenderingManager.prototype.reset = function () {
  11409. for (var index in this._renderingGroups) {
  11410. var renderingGroup = this._renderingGroups[index];
  11411. renderingGroup.prepare();
  11412. }
  11413. };
  11414. RenderingManager.prototype.dispatch = function (subMesh) {
  11415. var mesh = subMesh.getMesh();
  11416. var renderingGroupId = mesh.renderingGroupId || 0;
  11417. if (!this._renderingGroups[renderingGroupId]) {
  11418. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11419. }
  11420. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11421. };
  11422. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11423. return RenderingManager;
  11424. })();
  11425. BABYLON.RenderingManager = RenderingManager;
  11426. })(BABYLON || (BABYLON = {}));
  11427. //# sourceMappingURL=babylon.renderingManager.js.map
  11428. var BABYLON;
  11429. (function (BABYLON) {
  11430. var Texture = (function (_super) {
  11431. __extends(Texture, _super);
  11432. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11433. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11434. if (onLoad === void 0) { onLoad = null; }
  11435. if (onError === void 0) { onError = null; }
  11436. if (buffer === void 0) { buffer = null; }
  11437. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11438. _super.call(this, scene);
  11439. this.uOffset = 0;
  11440. this.vOffset = 0;
  11441. this.uScale = 1.0;
  11442. this.vScale = 1.0;
  11443. this.uAng = 0;
  11444. this.vAng = 0;
  11445. this.wAng = 0;
  11446. this.name = url;
  11447. this.url = url;
  11448. this._noMipmap = noMipmap;
  11449. this._invertY = invertY;
  11450. this._samplingMode = samplingMode;
  11451. this._buffer = buffer;
  11452. this._deleteBuffer = deleteBuffer;
  11453. if (!url) {
  11454. return;
  11455. }
  11456. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11457. if (!this._texture) {
  11458. if (!scene.useDelayedTextureLoading) {
  11459. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11460. if (deleteBuffer) {
  11461. delete this._buffer;
  11462. }
  11463. }
  11464. else {
  11465. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11466. }
  11467. }
  11468. }
  11469. Texture.prototype.delayLoad = function () {
  11470. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11471. return;
  11472. }
  11473. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11474. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11475. if (!this._texture) {
  11476. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11477. if (this._deleteBuffer) {
  11478. delete this._buffer;
  11479. }
  11480. }
  11481. };
  11482. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11483. x -= this.uOffset + 0.5;
  11484. y -= this.vOffset + 0.5;
  11485. z -= 0.5;
  11486. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11487. t.x *= this.uScale;
  11488. t.y *= this.vScale;
  11489. t.x += 0.5;
  11490. t.y += 0.5;
  11491. t.z += 0.5;
  11492. };
  11493. Texture.prototype.getTextureMatrix = function () {
  11494. 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) {
  11495. return this._cachedTextureMatrix;
  11496. }
  11497. this._cachedUOffset = this.uOffset;
  11498. this._cachedVOffset = this.vOffset;
  11499. this._cachedUScale = this.uScale;
  11500. this._cachedVScale = this.vScale;
  11501. this._cachedUAng = this.uAng;
  11502. this._cachedVAng = this.vAng;
  11503. this._cachedWAng = this.wAng;
  11504. if (!this._cachedTextureMatrix) {
  11505. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11506. this._rowGenerationMatrix = new BABYLON.Matrix();
  11507. this._t0 = BABYLON.Vector3.Zero();
  11508. this._t1 = BABYLON.Vector3.Zero();
  11509. this._t2 = BABYLON.Vector3.Zero();
  11510. }
  11511. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11512. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11513. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11514. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11515. this._t1.subtractInPlace(this._t0);
  11516. this._t2.subtractInPlace(this._t0);
  11517. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11518. this._cachedTextureMatrix.m[0] = this._t1.x;
  11519. this._cachedTextureMatrix.m[1] = this._t1.y;
  11520. this._cachedTextureMatrix.m[2] = this._t1.z;
  11521. this._cachedTextureMatrix.m[4] = this._t2.x;
  11522. this._cachedTextureMatrix.m[5] = this._t2.y;
  11523. this._cachedTextureMatrix.m[6] = this._t2.z;
  11524. this._cachedTextureMatrix.m[8] = this._t0.x;
  11525. this._cachedTextureMatrix.m[9] = this._t0.y;
  11526. this._cachedTextureMatrix.m[10] = this._t0.z;
  11527. return this._cachedTextureMatrix;
  11528. };
  11529. Texture.prototype.getReflectionTextureMatrix = function () {
  11530. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11531. return this._cachedTextureMatrix;
  11532. }
  11533. if (!this._cachedTextureMatrix) {
  11534. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11535. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11536. }
  11537. this._cachedCoordinatesMode = this.coordinatesMode;
  11538. switch (this.coordinatesMode) {
  11539. case BABYLON.Texture.SPHERICAL_MODE:
  11540. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11541. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11542. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11543. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11544. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11545. break;
  11546. case BABYLON.Texture.PLANAR_MODE:
  11547. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11548. this._cachedTextureMatrix[0] = this.uScale;
  11549. this._cachedTextureMatrix[5] = this.vScale;
  11550. this._cachedTextureMatrix[12] = this.uOffset;
  11551. this._cachedTextureMatrix[13] = this.vOffset;
  11552. break;
  11553. case BABYLON.Texture.PROJECTION_MODE:
  11554. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11555. this._projectionModeMatrix.m[0] = 0.5;
  11556. this._projectionModeMatrix.m[5] = -0.5;
  11557. this._projectionModeMatrix.m[10] = 0.0;
  11558. this._projectionModeMatrix.m[12] = 0.5;
  11559. this._projectionModeMatrix.m[13] = 0.5;
  11560. this._projectionModeMatrix.m[14] = 1.0;
  11561. this._projectionModeMatrix.m[15] = 1.0;
  11562. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11563. break;
  11564. default:
  11565. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11566. break;
  11567. }
  11568. return this._cachedTextureMatrix;
  11569. };
  11570. Texture.prototype.clone = function () {
  11571. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  11572. // Base texture
  11573. newTexture.hasAlpha = this.hasAlpha;
  11574. newTexture.level = this.level;
  11575. newTexture.wrapU = this.wrapU;
  11576. newTexture.wrapV = this.wrapV;
  11577. newTexture.coordinatesIndex = this.coordinatesIndex;
  11578. newTexture.coordinatesMode = this.coordinatesMode;
  11579. // Texture
  11580. newTexture.uOffset = this.uOffset;
  11581. newTexture.vOffset = this.vOffset;
  11582. newTexture.uScale = this.uScale;
  11583. newTexture.vScale = this.vScale;
  11584. newTexture.uAng = this.uAng;
  11585. newTexture.vAng = this.vAng;
  11586. newTexture.wAng = this.wAng;
  11587. return newTexture;
  11588. };
  11589. // Statics
  11590. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11591. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11592. if (onLoad === void 0) { onLoad = null; }
  11593. if (onError === void 0) { onError = null; }
  11594. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11595. };
  11596. // Constants
  11597. Texture.NEAREST_SAMPLINGMODE = 1;
  11598. Texture.BILINEAR_SAMPLINGMODE = 2;
  11599. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11600. Texture.EXPLICIT_MODE = 0;
  11601. Texture.SPHERICAL_MODE = 1;
  11602. Texture.PLANAR_MODE = 2;
  11603. Texture.CUBIC_MODE = 3;
  11604. Texture.PROJECTION_MODE = 4;
  11605. Texture.SKYBOX_MODE = 5;
  11606. Texture.CLAMP_ADDRESSMODE = 0;
  11607. Texture.WRAP_ADDRESSMODE = 1;
  11608. Texture.MIRROR_ADDRESSMODE = 2;
  11609. return Texture;
  11610. })(BABYLON.BaseTexture);
  11611. BABYLON.Texture = Texture;
  11612. })(BABYLON || (BABYLON = {}));
  11613. //# sourceMappingURL=babylon.texture.js.map
  11614. var BABYLON;
  11615. (function (BABYLON) {
  11616. var CubeTexture = (function (_super) {
  11617. __extends(CubeTexture, _super);
  11618. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11619. _super.call(this, scene);
  11620. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11621. this.name = rootUrl;
  11622. this.url = rootUrl;
  11623. this._noMipmap = noMipmap;
  11624. this.hasAlpha = false;
  11625. this._texture = this._getFromCache(rootUrl, noMipmap);
  11626. if (!extensions) {
  11627. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11628. }
  11629. this._extensions = extensions;
  11630. if (!this._texture) {
  11631. if (!scene.useDelayedTextureLoading) {
  11632. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11633. }
  11634. else {
  11635. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11636. }
  11637. }
  11638. this.isCube = true;
  11639. this._textureMatrix = BABYLON.Matrix.Identity();
  11640. }
  11641. CubeTexture.prototype.clone = function () {
  11642. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11643. // Base texture
  11644. newTexture.level = this.level;
  11645. newTexture.wrapU = this.wrapU;
  11646. newTexture.wrapV = this.wrapV;
  11647. newTexture.coordinatesIndex = this.coordinatesIndex;
  11648. newTexture.coordinatesMode = this.coordinatesMode;
  11649. return newTexture;
  11650. };
  11651. // Methods
  11652. CubeTexture.prototype.delayLoad = function () {
  11653. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11654. return;
  11655. }
  11656. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11657. this._texture = this._getFromCache(this.url, this._noMipmap);
  11658. if (!this._texture) {
  11659. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11660. }
  11661. };
  11662. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11663. return this._textureMatrix;
  11664. };
  11665. return CubeTexture;
  11666. })(BABYLON.BaseTexture);
  11667. BABYLON.CubeTexture = CubeTexture;
  11668. })(BABYLON || (BABYLON = {}));
  11669. //# sourceMappingURL=babylon.cubeTexture.js.map
  11670. var BABYLON;
  11671. (function (BABYLON) {
  11672. var RenderTargetTexture = (function (_super) {
  11673. __extends(RenderTargetTexture, _super);
  11674. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  11675. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11676. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  11677. _super.call(this, null, scene, !generateMipMaps);
  11678. this.renderList = new Array();
  11679. this.renderParticles = true;
  11680. this.renderSprites = false;
  11681. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11682. this._currentRefreshId = -1;
  11683. this._refreshRate = 1;
  11684. this.name = name;
  11685. this.isRenderTarget = true;
  11686. this._size = size;
  11687. this._generateMipMaps = generateMipMaps;
  11688. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11689. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  11690. // Rendering groups
  11691. this._renderingManager = new BABYLON.RenderingManager(scene);
  11692. }
  11693. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11694. this._currentRefreshId = -1;
  11695. };
  11696. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11697. get: function () {
  11698. return this._refreshRate;
  11699. },
  11700. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11701. set: function (value) {
  11702. this._refreshRate = value;
  11703. this.resetRefreshCounter();
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. RenderTargetTexture.prototype._shouldRender = function () {
  11709. if (this._currentRefreshId === -1) {
  11710. this._currentRefreshId = 1;
  11711. return true;
  11712. }
  11713. if (this.refreshRate === this._currentRefreshId) {
  11714. this._currentRefreshId = 1;
  11715. return true;
  11716. }
  11717. this._currentRefreshId++;
  11718. return false;
  11719. };
  11720. RenderTargetTexture.prototype.isReady = function () {
  11721. if (!this.getScene().renderTargetsEnabled) {
  11722. return false;
  11723. }
  11724. return _super.prototype.isReady.call(this);
  11725. };
  11726. RenderTargetTexture.prototype.getRenderSize = function () {
  11727. return this._size;
  11728. };
  11729. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11730. get: function () {
  11731. return true;
  11732. },
  11733. enumerable: true,
  11734. configurable: true
  11735. });
  11736. RenderTargetTexture.prototype.scale = function (ratio) {
  11737. var newSize = this._size * ratio;
  11738. this.resize(newSize, this._generateMipMaps);
  11739. };
  11740. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11741. this.releaseInternalTexture();
  11742. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11743. };
  11744. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11745. var scene = this.getScene();
  11746. var engine = scene.getEngine();
  11747. if (this._waitingRenderList) {
  11748. this.renderList = [];
  11749. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11750. var id = this._waitingRenderList[index];
  11751. this.renderList.push(scene.getMeshByID(id));
  11752. }
  11753. delete this._waitingRenderList;
  11754. }
  11755. if (this.renderList && this.renderList.length === 0) {
  11756. return;
  11757. }
  11758. // Bind
  11759. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11760. engine.bindFramebuffer(this._texture);
  11761. }
  11762. // Clear
  11763. engine.clear(scene.clearColor, true, true);
  11764. this._renderingManager.reset();
  11765. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  11766. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  11767. var mesh = currentRenderList[meshIndex];
  11768. if (mesh) {
  11769. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11770. // Reset _currentRefreshId
  11771. this.resetRefreshCounter();
  11772. continue;
  11773. }
  11774. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  11775. mesh._activate(scene.getRenderId());
  11776. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11777. var subMesh = mesh.subMeshes[subIndex];
  11778. scene._activeVertices += subMesh.indexCount;
  11779. this._renderingManager.dispatch(subMesh);
  11780. }
  11781. }
  11782. }
  11783. }
  11784. if (!this._doNotChangeAspectRatio) {
  11785. scene.updateTransformMatrix(true);
  11786. }
  11787. if (this.onBeforeRender) {
  11788. this.onBeforeRender();
  11789. }
  11790. // Render
  11791. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  11792. if (useCameraPostProcess) {
  11793. scene.postProcessManager._finalizeFrame(false, this._texture);
  11794. }
  11795. if (this.onAfterRender) {
  11796. this.onAfterRender();
  11797. }
  11798. // Unbind
  11799. engine.unBindFramebuffer(this._texture);
  11800. if (!this._doNotChangeAspectRatio) {
  11801. scene.updateTransformMatrix(true);
  11802. }
  11803. };
  11804. RenderTargetTexture.prototype.clone = function () {
  11805. var textureSize = this.getSize();
  11806. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11807. // Base texture
  11808. newTexture.hasAlpha = this.hasAlpha;
  11809. newTexture.level = this.level;
  11810. // RenderTarget Texture
  11811. newTexture.coordinatesMode = this.coordinatesMode;
  11812. newTexture.renderList = this.renderList.slice(0);
  11813. return newTexture;
  11814. };
  11815. return RenderTargetTexture;
  11816. })(BABYLON.Texture);
  11817. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11818. })(BABYLON || (BABYLON = {}));
  11819. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11820. var BABYLON;
  11821. (function (BABYLON) {
  11822. var ProceduralTexture = (function (_super) {
  11823. __extends(ProceduralTexture, _super);
  11824. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11825. if (generateMipMaps === void 0) { generateMipMaps = true; }
  11826. _super.call(this, null, scene, !generateMipMaps);
  11827. this._currentRefreshId = -1;
  11828. this._refreshRate = 1;
  11829. this._vertexDeclaration = [2];
  11830. this._vertexStrideSize = 2 * 4;
  11831. this._uniforms = new Array();
  11832. this._samplers = new Array();
  11833. this._textures = new Array();
  11834. this._floats = new Array();
  11835. this._floatsArrays = {};
  11836. this._colors3 = new Array();
  11837. this._colors4 = new Array();
  11838. this._vectors2 = new Array();
  11839. this._vectors3 = new Array();
  11840. this._matrices = new Array();
  11841. this._fallbackTextureUsed = false;
  11842. scene._proceduralTextures.push(this);
  11843. this.name = name;
  11844. this.isRenderTarget = true;
  11845. this._size = size;
  11846. this._generateMipMaps = generateMipMaps;
  11847. this.setFragment(fragment);
  11848. this._fallbackTexture = fallbackTexture;
  11849. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11850. // VBO
  11851. var vertices = [];
  11852. vertices.push(1, 1);
  11853. vertices.push(-1, 1);
  11854. vertices.push(-1, -1);
  11855. vertices.push(1, -1);
  11856. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11857. // Indices
  11858. var indices = [];
  11859. indices.push(0);
  11860. indices.push(1);
  11861. indices.push(2);
  11862. indices.push(0);
  11863. indices.push(2);
  11864. indices.push(3);
  11865. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11866. }
  11867. ProceduralTexture.prototype.reset = function () {
  11868. if (this._effect === undefined) {
  11869. return;
  11870. }
  11871. var engine = this.getScene().getEngine();
  11872. engine._releaseEffect(this._effect);
  11873. };
  11874. ProceduralTexture.prototype.isReady = function () {
  11875. var _this = this;
  11876. var engine = this.getScene().getEngine();
  11877. var shaders;
  11878. if (!this._fragment) {
  11879. return false;
  11880. }
  11881. if (this._fallbackTextureUsed) {
  11882. return true;
  11883. }
  11884. if (this._fragment.fragmentElement !== undefined) {
  11885. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11886. }
  11887. else {
  11888. shaders = { vertex: "procedural", fragment: this._fragment };
  11889. }
  11890. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11891. _this.releaseInternalTexture();
  11892. if (_this._fallbackTexture) {
  11893. _this._texture = _this._fallbackTexture._texture;
  11894. _this._texture.references++;
  11895. }
  11896. _this._fallbackTextureUsed = true;
  11897. });
  11898. return this._effect.isReady();
  11899. };
  11900. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11901. this._currentRefreshId = -1;
  11902. };
  11903. ProceduralTexture.prototype.setFragment = function (fragment) {
  11904. this._fragment = fragment;
  11905. };
  11906. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11907. get: function () {
  11908. return this._refreshRate;
  11909. },
  11910. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11911. set: function (value) {
  11912. this._refreshRate = value;
  11913. this.resetRefreshCounter();
  11914. },
  11915. enumerable: true,
  11916. configurable: true
  11917. });
  11918. ProceduralTexture.prototype._shouldRender = function () {
  11919. if (!this.isReady() || !this._texture) {
  11920. return false;
  11921. }
  11922. if (this._fallbackTextureUsed) {
  11923. return false;
  11924. }
  11925. if (this._currentRefreshId === -1) {
  11926. this._currentRefreshId = 1;
  11927. return true;
  11928. }
  11929. if (this.refreshRate === this._currentRefreshId) {
  11930. this._currentRefreshId = 1;
  11931. return true;
  11932. }
  11933. this._currentRefreshId++;
  11934. return false;
  11935. };
  11936. ProceduralTexture.prototype.getRenderSize = function () {
  11937. return this._size;
  11938. };
  11939. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11940. if (this._fallbackTextureUsed) {
  11941. return;
  11942. }
  11943. this.releaseInternalTexture();
  11944. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11945. };
  11946. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11947. if (this._uniforms.indexOf(uniformName) === -1) {
  11948. this._uniforms.push(uniformName);
  11949. }
  11950. };
  11951. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11952. if (this._samplers.indexOf(name) === -1) {
  11953. this._samplers.push(name);
  11954. }
  11955. this._textures[name] = texture;
  11956. return this;
  11957. };
  11958. ProceduralTexture.prototype.setFloat = function (name, value) {
  11959. this._checkUniform(name);
  11960. this._floats[name] = value;
  11961. return this;
  11962. };
  11963. ProceduralTexture.prototype.setFloats = function (name, value) {
  11964. this._checkUniform(name);
  11965. this._floatsArrays[name] = value;
  11966. return this;
  11967. };
  11968. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11969. this._checkUniform(name);
  11970. this._colors3[name] = value;
  11971. return this;
  11972. };
  11973. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11974. this._checkUniform(name);
  11975. this._colors4[name] = value;
  11976. return this;
  11977. };
  11978. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11979. this._checkUniform(name);
  11980. this._vectors2[name] = value;
  11981. return this;
  11982. };
  11983. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11984. this._checkUniform(name);
  11985. this._vectors3[name] = value;
  11986. return this;
  11987. };
  11988. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11989. this._checkUniform(name);
  11990. this._matrices[name] = value;
  11991. return this;
  11992. };
  11993. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11994. var scene = this.getScene();
  11995. var engine = scene.getEngine();
  11996. engine.bindFramebuffer(this._texture);
  11997. // Clear
  11998. engine.clear(scene.clearColor, true, true);
  11999. // Render
  12000. engine.enableEffect(this._effect);
  12001. engine.setState(false);
  12002. for (var name in this._textures) {
  12003. this._effect.setTexture(name, this._textures[name]);
  12004. }
  12005. for (name in this._floats) {
  12006. this._effect.setFloat(name, this._floats[name]);
  12007. }
  12008. for (name in this._floatsArrays) {
  12009. this._effect.setArray(name, this._floatsArrays[name]);
  12010. }
  12011. for (name in this._colors3) {
  12012. this._effect.setColor3(name, this._colors3[name]);
  12013. }
  12014. for (name in this._colors4) {
  12015. var color = this._colors4[name];
  12016. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12017. }
  12018. for (name in this._vectors2) {
  12019. this._effect.setVector2(name, this._vectors2[name]);
  12020. }
  12021. for (name in this._vectors3) {
  12022. this._effect.setVector3(name, this._vectors3[name]);
  12023. }
  12024. for (name in this._matrices) {
  12025. this._effect.setMatrix(name, this._matrices[name]);
  12026. }
  12027. // VBOs
  12028. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12029. // Draw order
  12030. engine.draw(true, 0, 6);
  12031. // Unbind
  12032. engine.unBindFramebuffer(this._texture);
  12033. };
  12034. ProceduralTexture.prototype.clone = function () {
  12035. var textureSize = this.getSize();
  12036. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12037. // Base texture
  12038. newTexture.hasAlpha = this.hasAlpha;
  12039. newTexture.level = this.level;
  12040. // RenderTarget Texture
  12041. newTexture.coordinatesMode = this.coordinatesMode;
  12042. return newTexture;
  12043. };
  12044. ProceduralTexture.prototype.dispose = function () {
  12045. var index = this.getScene()._proceduralTextures.indexOf(this);
  12046. if (index >= 0) {
  12047. this.getScene()._proceduralTextures.splice(index, 1);
  12048. }
  12049. _super.prototype.dispose.call(this);
  12050. };
  12051. return ProceduralTexture;
  12052. })(BABYLON.Texture);
  12053. BABYLON.ProceduralTexture = ProceduralTexture;
  12054. })(BABYLON || (BABYLON = {}));
  12055. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12056. var BABYLON;
  12057. (function (BABYLON) {
  12058. var WoodProceduralTexture = (function (_super) {
  12059. __extends(WoodProceduralTexture, _super);
  12060. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12061. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12062. this._ampScale = 100.0;
  12063. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12064. this.updateShaderUniforms();
  12065. this.refreshRate = 0;
  12066. }
  12067. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12068. this.setFloat("ampScale", this._ampScale);
  12069. this.setColor3("woodColor", this._woodColor);
  12070. };
  12071. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12072. get: function () {
  12073. return this._ampScale;
  12074. },
  12075. set: function (value) {
  12076. this._ampScale = value;
  12077. this.updateShaderUniforms();
  12078. },
  12079. enumerable: true,
  12080. configurable: true
  12081. });
  12082. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12083. get: function () {
  12084. return this._woodColor;
  12085. },
  12086. set: function (value) {
  12087. this._woodColor = value;
  12088. this.updateShaderUniforms();
  12089. },
  12090. enumerable: true,
  12091. configurable: true
  12092. });
  12093. return WoodProceduralTexture;
  12094. })(BABYLON.ProceduralTexture);
  12095. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12096. var FireProceduralTexture = (function (_super) {
  12097. __extends(FireProceduralTexture, _super);
  12098. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12099. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12100. this._time = 0.0;
  12101. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12102. this._shift = 1.6;
  12103. this._autoGenerateTime = true;
  12104. this._alphaThreshold = 0.5;
  12105. this._fireColors = FireProceduralTexture.RedFireColors;
  12106. this.updateShaderUniforms();
  12107. this.refreshRate = 1;
  12108. }
  12109. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12110. this.setFloat("time", this._time);
  12111. this.setVector2("speed", this._speed);
  12112. this.setFloat("shift", this._shift);
  12113. this.setColor3("c1", this._fireColors[0]);
  12114. this.setColor3("c2", this._fireColors[1]);
  12115. this.setColor3("c3", this._fireColors[2]);
  12116. this.setColor3("c4", this._fireColors[3]);
  12117. this.setColor3("c5", this._fireColors[4]);
  12118. this.setColor3("c6", this._fireColors[5]);
  12119. this.setFloat("alphaThreshold", this._alphaThreshold);
  12120. };
  12121. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12122. if (this._autoGenerateTime) {
  12123. this._time += this.getScene().getAnimationRatio() * 0.03;
  12124. this.updateShaderUniforms();
  12125. }
  12126. _super.prototype.render.call(this, useCameraPostProcess);
  12127. };
  12128. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12129. get: function () {
  12130. return [
  12131. new BABYLON.Color3(0.5, 0.0, 1.0),
  12132. new BABYLON.Color3(0.9, 0.0, 1.0),
  12133. new BABYLON.Color3(0.2, 0.0, 1.0),
  12134. new BABYLON.Color3(1.0, 0.9, 1.0),
  12135. new BABYLON.Color3(0.1, 0.1, 1.0),
  12136. new BABYLON.Color3(0.9, 0.9, 1.0)
  12137. ];
  12138. },
  12139. enumerable: true,
  12140. configurable: true
  12141. });
  12142. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12143. get: function () {
  12144. return [
  12145. new BABYLON.Color3(0.5, 1.0, 0.0),
  12146. new BABYLON.Color3(0.5, 1.0, 0.0),
  12147. new BABYLON.Color3(0.3, 0.4, 0.0),
  12148. new BABYLON.Color3(0.5, 1.0, 0.0),
  12149. new BABYLON.Color3(0.2, 0.0, 0.0),
  12150. new BABYLON.Color3(0.5, 1.0, 0.0)
  12151. ];
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12157. get: function () {
  12158. return [
  12159. new BABYLON.Color3(0.5, 0.0, 0.1),
  12160. new BABYLON.Color3(0.9, 0.0, 0.0),
  12161. new BABYLON.Color3(0.2, 0.0, 0.0),
  12162. new BABYLON.Color3(1.0, 0.9, 0.0),
  12163. new BABYLON.Color3(0.1, 0.1, 0.1),
  12164. new BABYLON.Color3(0.9, 0.9, 0.9)
  12165. ];
  12166. },
  12167. enumerable: true,
  12168. configurable: true
  12169. });
  12170. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12171. get: function () {
  12172. return [
  12173. new BABYLON.Color3(0.1, 0.0, 0.5),
  12174. new BABYLON.Color3(0.0, 0.0, 0.5),
  12175. new BABYLON.Color3(0.1, 0.0, 0.2),
  12176. new BABYLON.Color3(0.0, 0.0, 1.0),
  12177. new BABYLON.Color3(0.1, 0.2, 0.3),
  12178. new BABYLON.Color3(0.0, 0.2, 0.9)
  12179. ];
  12180. },
  12181. enumerable: true,
  12182. configurable: true
  12183. });
  12184. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12185. get: function () {
  12186. return this._fireColors;
  12187. },
  12188. set: function (value) {
  12189. this._fireColors = value;
  12190. this.updateShaderUniforms();
  12191. },
  12192. enumerable: true,
  12193. configurable: true
  12194. });
  12195. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12196. get: function () {
  12197. return this._time;
  12198. },
  12199. set: function (value) {
  12200. this._time = value;
  12201. this.updateShaderUniforms();
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12207. get: function () {
  12208. return this._speed;
  12209. },
  12210. set: function (value) {
  12211. this._speed = value;
  12212. this.updateShaderUniforms();
  12213. },
  12214. enumerable: true,
  12215. configurable: true
  12216. });
  12217. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12218. get: function () {
  12219. return this._shift;
  12220. },
  12221. set: function (value) {
  12222. this._shift = value;
  12223. this.updateShaderUniforms();
  12224. },
  12225. enumerable: true,
  12226. configurable: true
  12227. });
  12228. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12229. get: function () {
  12230. return this._alphaThreshold;
  12231. },
  12232. set: function (value) {
  12233. this._alphaThreshold = value;
  12234. this.updateShaderUniforms();
  12235. },
  12236. enumerable: true,
  12237. configurable: true
  12238. });
  12239. return FireProceduralTexture;
  12240. })(BABYLON.ProceduralTexture);
  12241. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12242. var CloudProceduralTexture = (function (_super) {
  12243. __extends(CloudProceduralTexture, _super);
  12244. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12245. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12246. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12247. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12248. this.updateShaderUniforms();
  12249. this.refreshRate = 0;
  12250. }
  12251. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12252. this.setColor3("skyColor", this._skyColor);
  12253. this.setColor3("cloudColor", this._cloudColor);
  12254. };
  12255. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12256. get: function () {
  12257. return this._skyColor;
  12258. },
  12259. set: function (value) {
  12260. this._skyColor = value;
  12261. this.updateShaderUniforms();
  12262. },
  12263. enumerable: true,
  12264. configurable: true
  12265. });
  12266. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12267. get: function () {
  12268. return this._cloudColor;
  12269. },
  12270. set: function (value) {
  12271. this._cloudColor = value;
  12272. this.updateShaderUniforms();
  12273. },
  12274. enumerable: true,
  12275. configurable: true
  12276. });
  12277. return CloudProceduralTexture;
  12278. })(BABYLON.ProceduralTexture);
  12279. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12280. var GrassProceduralTexture = (function (_super) {
  12281. __extends(GrassProceduralTexture, _super);
  12282. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12283. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12284. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12285. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12286. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12287. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12288. this._grassColors = [
  12289. new BABYLON.Color3(0.29, 0.38, 0.02),
  12290. new BABYLON.Color3(0.36, 0.49, 0.09),
  12291. new BABYLON.Color3(0.51, 0.6, 0.28)
  12292. ];
  12293. this.updateShaderUniforms();
  12294. this.refreshRate = 0;
  12295. }
  12296. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12297. this.setColor3("herb1Color", this._grassColors[0]);
  12298. this.setColor3("herb2Color", this._grassColors[1]);
  12299. this.setColor3("herb3Color", this._grassColors[2]);
  12300. this.setColor3("groundColor", this._groundColor);
  12301. };
  12302. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12303. get: function () {
  12304. return this._grassColors;
  12305. },
  12306. set: function (value) {
  12307. this._grassColors = value;
  12308. this.updateShaderUniforms();
  12309. },
  12310. enumerable: true,
  12311. configurable: true
  12312. });
  12313. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12314. get: function () {
  12315. return this._groundColor;
  12316. },
  12317. set: function (value) {
  12318. this.groundColor = value;
  12319. this.updateShaderUniforms();
  12320. },
  12321. enumerable: true,
  12322. configurable: true
  12323. });
  12324. return GrassProceduralTexture;
  12325. })(BABYLON.ProceduralTexture);
  12326. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12327. var RoadProceduralTexture = (function (_super) {
  12328. __extends(RoadProceduralTexture, _super);
  12329. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12330. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12331. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12332. this.updateShaderUniforms();
  12333. this.refreshRate = 0;
  12334. }
  12335. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12336. this.setColor3("roadColor", this._roadColor);
  12337. };
  12338. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12339. get: function () {
  12340. return this._roadColor;
  12341. },
  12342. set: function (value) {
  12343. this._roadColor = value;
  12344. this.updateShaderUniforms();
  12345. },
  12346. enumerable: true,
  12347. configurable: true
  12348. });
  12349. return RoadProceduralTexture;
  12350. })(BABYLON.ProceduralTexture);
  12351. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12352. var BrickProceduralTexture = (function (_super) {
  12353. __extends(BrickProceduralTexture, _super);
  12354. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12355. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12356. this._numberOfBricksHeight = 15;
  12357. this._numberOfBricksWidth = 5;
  12358. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12359. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12360. this.updateShaderUniforms();
  12361. this.refreshRate = 0;
  12362. }
  12363. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12364. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12365. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12366. this.setColor3("brickColor", this._brickColor);
  12367. this.setColor3("jointColor", this._jointColor);
  12368. };
  12369. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12370. get: function () {
  12371. return this._numberOfBricksHeight;
  12372. },
  12373. enumerable: true,
  12374. configurable: true
  12375. });
  12376. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12377. set: function (value) {
  12378. this._numberOfBricksHeight = value;
  12379. this.updateShaderUniforms();
  12380. },
  12381. enumerable: true,
  12382. configurable: true
  12383. });
  12384. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12385. get: function () {
  12386. return this._numberOfBricksWidth;
  12387. },
  12388. set: function (value) {
  12389. this._numberOfBricksHeight = value;
  12390. this.updateShaderUniforms();
  12391. },
  12392. enumerable: true,
  12393. configurable: true
  12394. });
  12395. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12396. get: function () {
  12397. return this._jointColor;
  12398. },
  12399. set: function (value) {
  12400. this._jointColor = value;
  12401. this.updateShaderUniforms();
  12402. },
  12403. enumerable: true,
  12404. configurable: true
  12405. });
  12406. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12407. get: function () {
  12408. return this._brickColor;
  12409. },
  12410. set: function (value) {
  12411. this._brickColor = value;
  12412. this.updateShaderUniforms();
  12413. },
  12414. enumerable: true,
  12415. configurable: true
  12416. });
  12417. return BrickProceduralTexture;
  12418. })(BABYLON.ProceduralTexture);
  12419. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12420. var MarbleProceduralTexture = (function (_super) {
  12421. __extends(MarbleProceduralTexture, _super);
  12422. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12423. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12424. this._numberOfTilesHeight = 3;
  12425. this._numberOfTilesWidth = 3;
  12426. this._amplitude = 9.0;
  12427. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12428. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12429. this.updateShaderUniforms();
  12430. this.refreshRate = 0;
  12431. }
  12432. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12433. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12434. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12435. this.setFloat("amplitude", this._amplitude);
  12436. this.setColor3("marbleColor", this._marbleColor);
  12437. this.setColor3("jointColor", this._jointColor);
  12438. };
  12439. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12440. get: function () {
  12441. return this._numberOfTilesHeight;
  12442. },
  12443. set: function (value) {
  12444. this._numberOfTilesHeight = value;
  12445. this.updateShaderUniforms();
  12446. },
  12447. enumerable: true,
  12448. configurable: true
  12449. });
  12450. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12451. get: function () {
  12452. return this._numberOfTilesWidth;
  12453. },
  12454. set: function (value) {
  12455. this._numberOfTilesWidth = value;
  12456. this.updateShaderUniforms();
  12457. },
  12458. enumerable: true,
  12459. configurable: true
  12460. });
  12461. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12462. get: function () {
  12463. return this._jointColor;
  12464. },
  12465. set: function (value) {
  12466. this._jointColor = value;
  12467. this.updateShaderUniforms();
  12468. },
  12469. enumerable: true,
  12470. configurable: true
  12471. });
  12472. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12473. get: function () {
  12474. return this._marbleColor;
  12475. },
  12476. set: function (value) {
  12477. this._marbleColor = value;
  12478. this.updateShaderUniforms();
  12479. },
  12480. enumerable: true,
  12481. configurable: true
  12482. });
  12483. return MarbleProceduralTexture;
  12484. })(BABYLON.ProceduralTexture);
  12485. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12486. })(BABYLON || (BABYLON = {}));
  12487. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12488. var BABYLON;
  12489. (function (BABYLON) {
  12490. var CustomProceduralTexture = (function (_super) {
  12491. __extends(CustomProceduralTexture, _super);
  12492. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12493. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12494. this._animate = true;
  12495. this._time = 0;
  12496. this._texturePath = texturePath;
  12497. //Try to load json
  12498. this.loadJson(texturePath);
  12499. this.refreshRate = 1;
  12500. }
  12501. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12502. var _this = this;
  12503. var that = this;
  12504. function noConfigFile() {
  12505. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12506. try {
  12507. that.setFragment(that._texturePath);
  12508. }
  12509. catch (ex) {
  12510. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12511. }
  12512. }
  12513. var configFileUrl = jsonUrl + "/config.json";
  12514. var xhr = new XMLHttpRequest();
  12515. xhr.open("GET", configFileUrl, true);
  12516. xhr.addEventListener("load", function () {
  12517. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12518. try {
  12519. _this._config = JSON.parse(xhr.response);
  12520. _this.updateShaderUniforms();
  12521. _this.updateTextures();
  12522. _this.setFragment(_this._texturePath + "/custom");
  12523. _this._animate = _this._config.animate;
  12524. _this.refreshRate = _this._config.refreshrate;
  12525. }
  12526. catch (ex) {
  12527. noConfigFile();
  12528. }
  12529. }
  12530. else {
  12531. noConfigFile();
  12532. }
  12533. }, false);
  12534. xhr.addEventListener("error", function (event) {
  12535. noConfigFile();
  12536. }, false);
  12537. try {
  12538. xhr.send();
  12539. }
  12540. catch (ex) {
  12541. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12542. }
  12543. };
  12544. CustomProceduralTexture.prototype.isReady = function () {
  12545. if (!_super.prototype.isReady.call(this)) {
  12546. return false;
  12547. }
  12548. for (var name in this._textures) {
  12549. var texture = this._textures[name];
  12550. if (!texture.isReady()) {
  12551. return false;
  12552. }
  12553. }
  12554. return true;
  12555. };
  12556. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12557. if (this._animate) {
  12558. this._time += this.getScene().getAnimationRatio() * 0.03;
  12559. this.updateShaderUniforms();
  12560. }
  12561. _super.prototype.render.call(this, useCameraPostProcess);
  12562. };
  12563. CustomProceduralTexture.prototype.updateTextures = function () {
  12564. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12565. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12566. }
  12567. };
  12568. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12569. if (this._config) {
  12570. for (var j = 0; j < this._config.uniforms.length; j++) {
  12571. var uniform = this._config.uniforms[j];
  12572. switch (uniform.type) {
  12573. case "float":
  12574. this.setFloat(uniform.name, uniform.value);
  12575. break;
  12576. case "color3":
  12577. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12578. break;
  12579. case "color4":
  12580. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12581. break;
  12582. case "vector2":
  12583. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12584. break;
  12585. case "vector3":
  12586. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12587. break;
  12588. }
  12589. }
  12590. }
  12591. this.setFloat("time", this._time);
  12592. };
  12593. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12594. get: function () {
  12595. return this._animate;
  12596. },
  12597. set: function (value) {
  12598. this._animate = value;
  12599. },
  12600. enumerable: true,
  12601. configurable: true
  12602. });
  12603. return CustomProceduralTexture;
  12604. })(BABYLON.ProceduralTexture);
  12605. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12606. })(BABYLON || (BABYLON = {}));
  12607. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12608. var BABYLON;
  12609. (function (BABYLON) {
  12610. var MirrorTexture = (function (_super) {
  12611. __extends(MirrorTexture, _super);
  12612. function MirrorTexture(name, size, scene, generateMipMaps) {
  12613. var _this = this;
  12614. _super.call(this, name, size, scene, generateMipMaps, true);
  12615. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12616. this._transformMatrix = BABYLON.Matrix.Zero();
  12617. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12618. this.onBeforeRender = function () {
  12619. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12620. _this._savedViewMatrix = scene.getViewMatrix();
  12621. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12622. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12623. scene.clipPlane = _this.mirrorPlane;
  12624. scene.getEngine().cullBackFaces = false;
  12625. };
  12626. this.onAfterRender = function () {
  12627. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12628. scene.getEngine().cullBackFaces = true;
  12629. delete scene.clipPlane;
  12630. };
  12631. }
  12632. MirrorTexture.prototype.clone = function () {
  12633. var textureSize = this.getSize();
  12634. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12635. // Base texture
  12636. newTexture.hasAlpha = this.hasAlpha;
  12637. newTexture.level = this.level;
  12638. // Mirror Texture
  12639. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12640. newTexture.renderList = this.renderList.slice(0);
  12641. return newTexture;
  12642. };
  12643. return MirrorTexture;
  12644. })(BABYLON.RenderTargetTexture);
  12645. BABYLON.MirrorTexture = MirrorTexture;
  12646. })(BABYLON || (BABYLON = {}));
  12647. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12648. var BABYLON;
  12649. (function (BABYLON) {
  12650. var DynamicTexture = (function (_super) {
  12651. __extends(DynamicTexture, _super);
  12652. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12653. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12654. _super.call(this, null, scene, !generateMipMaps);
  12655. this.name = name;
  12656. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12657. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12658. this._generateMipMaps = generateMipMaps;
  12659. if (options.getContext) {
  12660. this._canvas = options;
  12661. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12662. }
  12663. else {
  12664. this._canvas = document.createElement("canvas");
  12665. if (options.width) {
  12666. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12667. }
  12668. else {
  12669. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12670. }
  12671. }
  12672. var textureSize = this.getSize();
  12673. this._canvas.width = textureSize.width;
  12674. this._canvas.height = textureSize.height;
  12675. this._context = this._canvas.getContext("2d");
  12676. }
  12677. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12678. get: function () {
  12679. return true;
  12680. },
  12681. enumerable: true,
  12682. configurable: true
  12683. });
  12684. DynamicTexture.prototype.scale = function (ratio) {
  12685. var textureSize = this.getSize();
  12686. textureSize.width *= ratio;
  12687. textureSize.height *= ratio;
  12688. this._canvas.width = textureSize.width;
  12689. this._canvas.height = textureSize.height;
  12690. this.releaseInternalTexture();
  12691. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12692. };
  12693. DynamicTexture.prototype.getContext = function () {
  12694. return this._context;
  12695. };
  12696. DynamicTexture.prototype.clear = function () {
  12697. var size = this.getSize();
  12698. this._context.fillRect(0, 0, size.width, size.height);
  12699. };
  12700. DynamicTexture.prototype.update = function (invertY) {
  12701. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12702. };
  12703. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12704. if (update === void 0) { update = true; }
  12705. var size = this.getSize();
  12706. if (clearColor) {
  12707. this._context.fillStyle = clearColor;
  12708. this._context.fillRect(0, 0, size.width, size.height);
  12709. }
  12710. this._context.font = font;
  12711. if (x === null) {
  12712. var textSize = this._context.measureText(text);
  12713. x = (size.width - textSize.width) / 2;
  12714. }
  12715. this._context.fillStyle = color;
  12716. this._context.fillText(text, x, y);
  12717. if (update) {
  12718. this.update(invertY);
  12719. }
  12720. };
  12721. DynamicTexture.prototype.clone = function () {
  12722. var textureSize = this.getSize();
  12723. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12724. // Base texture
  12725. newTexture.hasAlpha = this.hasAlpha;
  12726. newTexture.level = this.level;
  12727. // Dynamic Texture
  12728. newTexture.wrapU = this.wrapU;
  12729. newTexture.wrapV = this.wrapV;
  12730. return newTexture;
  12731. };
  12732. return DynamicTexture;
  12733. })(BABYLON.Texture);
  12734. BABYLON.DynamicTexture = DynamicTexture;
  12735. })(BABYLON || (BABYLON = {}));
  12736. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12737. var BABYLON;
  12738. (function (BABYLON) {
  12739. var VideoTexture = (function (_super) {
  12740. __extends(VideoTexture, _super);
  12741. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12742. var _this = this;
  12743. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12744. _super.call(this, null, scene, !generateMipMaps, invertY);
  12745. this._autoLaunch = true;
  12746. this.name = name;
  12747. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12748. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12749. var requiredWidth = size.width || size;
  12750. var requiredHeight = size.height || size;
  12751. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12752. var textureSize = this.getSize();
  12753. this.video = document.createElement("video");
  12754. this.video.width = textureSize.width;
  12755. this.video.height = textureSize.height;
  12756. this.video.autoplay = false;
  12757. this.video.loop = true;
  12758. this.video.addEventListener("canplaythrough", function () {
  12759. if (_this._texture) {
  12760. _this._texture.isReady = true;
  12761. }
  12762. });
  12763. urls.forEach(function (url) {
  12764. var source = document.createElement("source");
  12765. source.src = url;
  12766. _this.video.appendChild(source);
  12767. });
  12768. this._lastUpdate = BABYLON.Tools.Now;
  12769. }
  12770. VideoTexture.prototype.update = function () {
  12771. if (this._autoLaunch) {
  12772. this._autoLaunch = false;
  12773. this.video.play();
  12774. }
  12775. var now = BABYLON.Tools.Now;
  12776. if (now - this._lastUpdate < 15) {
  12777. return false;
  12778. }
  12779. this._lastUpdate = now;
  12780. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12781. return true;
  12782. };
  12783. return VideoTexture;
  12784. })(BABYLON.Texture);
  12785. BABYLON.VideoTexture = VideoTexture;
  12786. })(BABYLON || (BABYLON = {}));
  12787. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  12788. (function (BABYLON) {
  12789. var EffectFallbacks = (function () {
  12790. function EffectFallbacks() {
  12791. this._defines = {};
  12792. this._currentRank = 32;
  12793. this._maxRank = -1;
  12794. }
  12795. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12796. if (!this._defines[rank]) {
  12797. if (rank < this._currentRank) {
  12798. this._currentRank = rank;
  12799. }
  12800. if (rank > this._maxRank) {
  12801. this._maxRank = rank;
  12802. }
  12803. this._defines[rank] = new Array();
  12804. }
  12805. this._defines[rank].push(define);
  12806. };
  12807. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12808. get: function () {
  12809. return this._currentRank <= this._maxRank;
  12810. },
  12811. enumerable: true,
  12812. configurable: true
  12813. });
  12814. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12815. var currentFallbacks = this._defines[this._currentRank];
  12816. for (var index = 0; index < currentFallbacks.length; index++) {
  12817. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12818. }
  12819. this._currentRank++;
  12820. return currentDefines;
  12821. };
  12822. return EffectFallbacks;
  12823. })();
  12824. BABYLON.EffectFallbacks = EffectFallbacks;
  12825. var Effect = (function () {
  12826. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12827. var _this = this;
  12828. this._isReady = false;
  12829. this._compilationError = "";
  12830. this._valueCache = [];
  12831. this._engine = engine;
  12832. this.name = baseName;
  12833. this.defines = defines;
  12834. this._uniformsNames = uniformsNames.concat(samplers);
  12835. this._samplers = samplers;
  12836. this._attributesNames = attributesNames;
  12837. this.onError = onError;
  12838. this.onCompiled = onCompiled;
  12839. var vertexSource;
  12840. var fragmentSource;
  12841. if (baseName.vertexElement) {
  12842. vertexSource = document.getElementById(baseName.vertexElement);
  12843. if (!vertexSource) {
  12844. vertexSource = baseName.vertexElement;
  12845. }
  12846. }
  12847. else {
  12848. vertexSource = baseName.vertex || baseName;
  12849. }
  12850. if (baseName.fragmentElement) {
  12851. fragmentSource = document.getElementById(baseName.fragmentElement);
  12852. if (!fragmentSource) {
  12853. fragmentSource = baseName.fragmentElement;
  12854. }
  12855. }
  12856. else {
  12857. fragmentSource = baseName.fragment || baseName;
  12858. }
  12859. this._loadVertexShader(vertexSource, function (vertexCode) {
  12860. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12861. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12862. });
  12863. });
  12864. }
  12865. // Properties
  12866. Effect.prototype.isReady = function () {
  12867. return this._isReady;
  12868. };
  12869. Effect.prototype.getProgram = function () {
  12870. return this._program;
  12871. };
  12872. Effect.prototype.getAttributesNames = function () {
  12873. return this._attributesNames;
  12874. };
  12875. Effect.prototype.getAttributeLocation = function (index) {
  12876. return this._attributes[index];
  12877. };
  12878. Effect.prototype.getAttributeLocationByName = function (name) {
  12879. var index = this._attributesNames.indexOf(name);
  12880. return this._attributes[index];
  12881. };
  12882. Effect.prototype.getAttributesCount = function () {
  12883. return this._attributes.length;
  12884. };
  12885. Effect.prototype.getUniformIndex = function (uniformName) {
  12886. return this._uniformsNames.indexOf(uniformName);
  12887. };
  12888. Effect.prototype.getUniform = function (uniformName) {
  12889. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12890. };
  12891. Effect.prototype.getSamplers = function () {
  12892. return this._samplers;
  12893. };
  12894. Effect.prototype.getCompilationError = function () {
  12895. return this._compilationError;
  12896. };
  12897. // Methods
  12898. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12899. // DOM element ?
  12900. if (vertex instanceof HTMLElement) {
  12901. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12902. callback(vertexCode);
  12903. return;
  12904. }
  12905. // Is in local store ?
  12906. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12907. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12908. return;
  12909. }
  12910. var vertexShaderUrl;
  12911. if (vertex[0] === ".") {
  12912. vertexShaderUrl = vertex;
  12913. }
  12914. else {
  12915. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12916. }
  12917. // Vertex shader
  12918. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12919. };
  12920. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12921. // DOM element ?
  12922. if (fragment instanceof HTMLElement) {
  12923. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12924. callback(fragmentCode);
  12925. return;
  12926. }
  12927. // Is in local store ?
  12928. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12929. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12930. return;
  12931. }
  12932. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12933. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12934. return;
  12935. }
  12936. var fragmentShaderUrl;
  12937. if (fragment[0] === ".") {
  12938. fragmentShaderUrl = fragment;
  12939. }
  12940. else {
  12941. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12942. }
  12943. // Fragment shader
  12944. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12945. };
  12946. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12947. try {
  12948. var engine = this._engine;
  12949. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12950. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12951. this._attributes = engine.getAttributes(this._program, attributesNames);
  12952. for (var index = 0; index < this._samplers.length; index++) {
  12953. var sampler = this.getUniform(this._samplers[index]);
  12954. if (sampler == null) {
  12955. this._samplers.splice(index, 1);
  12956. index--;
  12957. }
  12958. }
  12959. engine.bindSamplers(this);
  12960. this._isReady = true;
  12961. if (this.onCompiled) {
  12962. this.onCompiled(this);
  12963. }
  12964. }
  12965. catch (e) {
  12966. // Is it a problem with precision?
  12967. if (e.message.indexOf("highp") !== -1) {
  12968. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12969. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12970. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12971. return;
  12972. }
  12973. // Let's go through fallbacks then
  12974. if (fallbacks && fallbacks.isMoreFallbacks) {
  12975. defines = fallbacks.reduce(defines);
  12976. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12977. }
  12978. else {
  12979. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12980. BABYLON.Tools.Error("Defines: " + defines);
  12981. BABYLON.Tools.Error("Error: " + e.message);
  12982. this._compilationError = e.message;
  12983. if (this.onError) {
  12984. this.onError(this, this._compilationError);
  12985. }
  12986. }
  12987. }
  12988. };
  12989. Effect.prototype._bindTexture = function (channel, texture) {
  12990. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12991. };
  12992. Effect.prototype.setTexture = function (channel, texture) {
  12993. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12994. };
  12995. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12996. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12997. };
  12998. //public _cacheMatrix(uniformName, matrix) {
  12999. // if (!this._valueCache[uniformName]) {
  13000. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13001. // }
  13002. // for (var index = 0; index < 16; index++) {
  13003. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13004. // }
  13005. //};
  13006. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13007. if (!this._valueCache[uniformName]) {
  13008. this._valueCache[uniformName] = [x, y];
  13009. return;
  13010. }
  13011. this._valueCache[uniformName][0] = x;
  13012. this._valueCache[uniformName][1] = y;
  13013. };
  13014. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13015. if (!this._valueCache[uniformName]) {
  13016. this._valueCache[uniformName] = [x, y, z];
  13017. return;
  13018. }
  13019. this._valueCache[uniformName][0] = x;
  13020. this._valueCache[uniformName][1] = y;
  13021. this._valueCache[uniformName][2] = z;
  13022. };
  13023. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13024. if (!this._valueCache[uniformName]) {
  13025. this._valueCache[uniformName] = [x, y, z, w];
  13026. return;
  13027. }
  13028. this._valueCache[uniformName][0] = x;
  13029. this._valueCache[uniformName][1] = y;
  13030. this._valueCache[uniformName][2] = z;
  13031. this._valueCache[uniformName][3] = w;
  13032. };
  13033. Effect.prototype.setArray = function (uniformName, array) {
  13034. this._engine.setArray(this.getUniform(uniformName), array);
  13035. return this;
  13036. };
  13037. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13038. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13039. return this;
  13040. };
  13041. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13042. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13043. // return;
  13044. //this._cacheMatrix(uniformName, matrix);
  13045. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13046. return this;
  13047. };
  13048. Effect.prototype.setFloat = function (uniformName, value) {
  13049. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13050. return this;
  13051. this._valueCache[uniformName] = value;
  13052. this._engine.setFloat(this.getUniform(uniformName), value);
  13053. return this;
  13054. };
  13055. Effect.prototype.setBool = function (uniformName, bool) {
  13056. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13057. return this;
  13058. this._valueCache[uniformName] = bool;
  13059. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13060. return this;
  13061. };
  13062. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13063. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13064. return this;
  13065. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13066. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13067. return this;
  13068. };
  13069. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13070. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13071. return this;
  13072. this._cacheFloat2(uniformName, x, y);
  13073. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13074. return this;
  13075. };
  13076. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13077. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13078. return this;
  13079. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13080. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13081. return this;
  13082. };
  13083. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13084. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13085. return this;
  13086. this._cacheFloat3(uniformName, x, y, z);
  13087. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13088. return this;
  13089. };
  13090. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13091. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13092. return this;
  13093. this._cacheFloat4(uniformName, x, y, z, w);
  13094. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13095. return this;
  13096. };
  13097. Effect.prototype.setColor3 = function (uniformName, color3) {
  13098. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13099. return this;
  13100. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13101. this._engine.setColor3(this.getUniform(uniformName), color3);
  13102. return this;
  13103. };
  13104. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13105. 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)
  13106. return this;
  13107. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13108. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13109. return this;
  13110. };
  13111. // Statics
  13112. 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}",
  13113. 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}",
  13114. 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}",
  13115. 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}",
  13116. 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}",
  13117. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13118. 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}",
  13119. 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}",
  13120. 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}",
  13121. 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}",
  13122. 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}",
  13123. 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}",
  13124. 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}",
  13125. 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}",
  13126. 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}",
  13127. 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}",
  13128. 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}",
  13129. 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}",
  13130. 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}",
  13131. 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}",
  13132. 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}",
  13133. 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}",
  13134. 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}",
  13135. 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}",
  13136. 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}",
  13137. 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}",
  13138. 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}",
  13139. 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}",
  13140. 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}",
  13141. 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}",
  13142. 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}",
  13143. 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}",
  13144. 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}",
  13145. 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}",
  13146. 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}",
  13147. 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}",
  13148. 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}",
  13149. 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}",
  13150. 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}",
  13151. };
  13152. return Effect;
  13153. })();
  13154. BABYLON.Effect = Effect;
  13155. })(BABYLON || (BABYLON = {}));
  13156. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13157. (function (BABYLON) {
  13158. var Material = (function () {
  13159. function Material(name, scene, doNotAdd) {
  13160. this.name = name;
  13161. this.checkReadyOnEveryCall = true;
  13162. this.checkReadyOnlyOnce = false;
  13163. this.state = "";
  13164. this.alpha = 1.0;
  13165. this.backFaceCulling = true;
  13166. this._wasPreviouslyReady = false;
  13167. this._fillMode = Material.TriangleFillMode;
  13168. this.pointSize = 1.0;
  13169. this.id = name;
  13170. this._scene = scene;
  13171. if (!doNotAdd) {
  13172. scene.materials.push(this);
  13173. }
  13174. }
  13175. Object.defineProperty(Material, "TriangleFillMode", {
  13176. get: function () {
  13177. return Material._TriangleFillMode;
  13178. },
  13179. enumerable: true,
  13180. configurable: true
  13181. });
  13182. Object.defineProperty(Material, "WireFrameFillMode", {
  13183. get: function () {
  13184. return Material._WireFrameFillMode;
  13185. },
  13186. enumerable: true,
  13187. configurable: true
  13188. });
  13189. Object.defineProperty(Material, "PointFillMode", {
  13190. get: function () {
  13191. return Material._PointFillMode;
  13192. },
  13193. enumerable: true,
  13194. configurable: true
  13195. });
  13196. Object.defineProperty(Material.prototype, "wireframe", {
  13197. get: function () {
  13198. return this._fillMode === Material.WireFrameFillMode;
  13199. },
  13200. set: function (value) {
  13201. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13202. },
  13203. enumerable: true,
  13204. configurable: true
  13205. });
  13206. Object.defineProperty(Material.prototype, "pointsCloud", {
  13207. get: function () {
  13208. return this._fillMode === Material.PointFillMode;
  13209. },
  13210. set: function (value) {
  13211. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13212. },
  13213. enumerable: true,
  13214. configurable: true
  13215. });
  13216. Object.defineProperty(Material.prototype, "fillMode", {
  13217. get: function () {
  13218. return this._fillMode;
  13219. },
  13220. set: function (value) {
  13221. this._fillMode = value;
  13222. },
  13223. enumerable: true,
  13224. configurable: true
  13225. });
  13226. Material.prototype.isReady = function (mesh, useInstances) {
  13227. return true;
  13228. };
  13229. Material.prototype.getEffect = function () {
  13230. return this._effect;
  13231. };
  13232. Material.prototype.getScene = function () {
  13233. return this._scene;
  13234. };
  13235. Material.prototype.needAlphaBlending = function () {
  13236. return (this.alpha < 1.0);
  13237. };
  13238. Material.prototype.needAlphaTesting = function () {
  13239. return false;
  13240. };
  13241. Material.prototype.getAlphaTestTexture = function () {
  13242. return null;
  13243. };
  13244. Material.prototype.trackCreation = function (onCompiled, onError) {
  13245. };
  13246. Material.prototype._preBind = function () {
  13247. var engine = this._scene.getEngine();
  13248. engine.enableEffect(this._effect);
  13249. engine.setState(this.backFaceCulling);
  13250. };
  13251. Material.prototype.bind = function (world, mesh) {
  13252. this._scene._cachedMaterial = this;
  13253. if (this.onBind) {
  13254. this.onBind(this);
  13255. }
  13256. };
  13257. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13258. };
  13259. Material.prototype.unbind = function () {
  13260. };
  13261. Material.prototype.dispose = function (forceDisposeEffect) {
  13262. // Remove from scene
  13263. var index = this._scene.materials.indexOf(this);
  13264. this._scene.materials.splice(index, 1);
  13265. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13266. if (forceDisposeEffect && this._effect) {
  13267. this._scene.getEngine()._releaseEffect(this._effect);
  13268. this._effect = null;
  13269. }
  13270. // Callback
  13271. if (this.onDispose) {
  13272. this.onDispose();
  13273. }
  13274. };
  13275. Material._TriangleFillMode = 0;
  13276. Material._WireFrameFillMode = 1;
  13277. Material._PointFillMode = 2;
  13278. return Material;
  13279. })();
  13280. BABYLON.Material = Material;
  13281. })(BABYLON || (BABYLON = {}));
  13282. //# sourceMappingURL=babylon.material.js.map
  13283. var BABYLON;
  13284. (function (BABYLON) {
  13285. var maxSimultaneousLights = 4;
  13286. var FresnelParameters = (function () {
  13287. function FresnelParameters() {
  13288. this.isEnabled = true;
  13289. this.leftColor = BABYLON.Color3.White();
  13290. this.rightColor = BABYLON.Color3.Black();
  13291. this.bias = 0;
  13292. this.power = 1;
  13293. }
  13294. return FresnelParameters;
  13295. })();
  13296. BABYLON.FresnelParameters = FresnelParameters;
  13297. var StandardMaterial = (function (_super) {
  13298. __extends(StandardMaterial, _super);
  13299. function StandardMaterial(name, scene) {
  13300. var _this = this;
  13301. _super.call(this, name, scene);
  13302. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13303. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13304. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13305. this.specularPower = 64;
  13306. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13307. this.useAlphaFromDiffuseTexture = false;
  13308. this.useSpecularOverAlpha = true;
  13309. this.fogEnabled = true;
  13310. this._cachedDefines = null;
  13311. this._renderTargets = new BABYLON.SmartArray(16);
  13312. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13313. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13314. this._scaledDiffuse = new BABYLON.Color3();
  13315. this._scaledSpecular = new BABYLON.Color3();
  13316. this.getRenderTargetTextures = function () {
  13317. _this._renderTargets.reset();
  13318. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13319. _this._renderTargets.push(_this.reflectionTexture);
  13320. }
  13321. return _this._renderTargets;
  13322. };
  13323. }
  13324. StandardMaterial.prototype.needAlphaBlending = function () {
  13325. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13326. };
  13327. StandardMaterial.prototype.needAlphaTesting = function () {
  13328. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13329. };
  13330. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13331. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13332. };
  13333. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13334. return this.diffuseTexture;
  13335. };
  13336. // Methods
  13337. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13338. if (this.checkReadyOnlyOnce) {
  13339. if (this._wasPreviouslyReady) {
  13340. return true;
  13341. }
  13342. }
  13343. var scene = this.getScene();
  13344. if (!this.checkReadyOnEveryCall) {
  13345. if (this._renderId === scene.getRenderId()) {
  13346. return true;
  13347. }
  13348. }
  13349. var engine = scene.getEngine();
  13350. var defines = [];
  13351. var fallbacks = new BABYLON.EffectFallbacks();
  13352. // Textures
  13353. if (scene.texturesEnabled) {
  13354. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13355. if (!this.diffuseTexture.isReady()) {
  13356. return false;
  13357. }
  13358. else {
  13359. defines.push("#define DIFFUSE");
  13360. }
  13361. }
  13362. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13363. if (!this.ambientTexture.isReady()) {
  13364. return false;
  13365. }
  13366. else {
  13367. defines.push("#define AMBIENT");
  13368. }
  13369. }
  13370. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13371. if (!this.opacityTexture.isReady()) {
  13372. return false;
  13373. }
  13374. else {
  13375. defines.push("#define OPACITY");
  13376. if (this.opacityTexture.getAlphaFromRGB) {
  13377. defines.push("#define OPACITYRGB");
  13378. }
  13379. }
  13380. }
  13381. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13382. if (!this.reflectionTexture.isReady()) {
  13383. return false;
  13384. }
  13385. else {
  13386. defines.push("#define REFLECTION");
  13387. fallbacks.addFallback(0, "REFLECTION");
  13388. }
  13389. }
  13390. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13391. if (!this.emissiveTexture.isReady()) {
  13392. return false;
  13393. }
  13394. else {
  13395. defines.push("#define EMISSIVE");
  13396. }
  13397. }
  13398. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13399. if (!this.specularTexture.isReady()) {
  13400. return false;
  13401. }
  13402. else {
  13403. defines.push("#define SPECULAR");
  13404. fallbacks.addFallback(0, "SPECULAR");
  13405. }
  13406. }
  13407. }
  13408. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13409. if (!this.bumpTexture.isReady()) {
  13410. return false;
  13411. }
  13412. else {
  13413. defines.push("#define BUMP");
  13414. fallbacks.addFallback(0, "BUMP");
  13415. }
  13416. }
  13417. // Effect
  13418. if (this.useSpecularOverAlpha) {
  13419. defines.push("#define SPECULAROVERALPHA");
  13420. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13421. }
  13422. if (scene.clipPlane) {
  13423. defines.push("#define CLIPPLANE");
  13424. }
  13425. if (engine.getAlphaTesting()) {
  13426. defines.push("#define ALPHATEST");
  13427. }
  13428. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13429. defines.push("#define ALPHAFROMDIFFUSE");
  13430. }
  13431. // Point size
  13432. if (this.pointsCloud || scene.forcePointsCloud) {
  13433. defines.push("#define POINTSIZE");
  13434. }
  13435. // Fog
  13436. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13437. defines.push("#define FOG");
  13438. fallbacks.addFallback(1, "FOG");
  13439. }
  13440. var shadowsActivated = false;
  13441. var lightIndex = 0;
  13442. if (scene.lightsEnabled) {
  13443. for (var index = 0; index < scene.lights.length; index++) {
  13444. var light = scene.lights[index];
  13445. if (!light.isEnabled()) {
  13446. continue;
  13447. }
  13448. // Excluded check
  13449. if (light._excludedMeshesIds.length > 0) {
  13450. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13451. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13452. if (excludedMesh) {
  13453. light.excludedMeshes.push(excludedMesh);
  13454. }
  13455. }
  13456. light._excludedMeshesIds = [];
  13457. }
  13458. // Included check
  13459. if (light._includedOnlyMeshesIds.length > 0) {
  13460. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13461. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13462. if (includedOnlyMesh) {
  13463. light.includedOnlyMeshes.push(includedOnlyMesh);
  13464. }
  13465. }
  13466. light._includedOnlyMeshesIds = [];
  13467. }
  13468. if (!light.canAffectMesh(mesh)) {
  13469. continue;
  13470. }
  13471. defines.push("#define LIGHT" + lightIndex);
  13472. if (lightIndex > 0) {
  13473. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13474. }
  13475. var type;
  13476. if (light instanceof BABYLON.SpotLight) {
  13477. type = "#define SPOTLIGHT" + lightIndex;
  13478. }
  13479. else if (light instanceof BABYLON.HemisphericLight) {
  13480. type = "#define HEMILIGHT" + lightIndex;
  13481. }
  13482. else {
  13483. type = "#define POINTDIRLIGHT" + lightIndex;
  13484. }
  13485. defines.push(type);
  13486. if (lightIndex > 0) {
  13487. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13488. }
  13489. // Shadows
  13490. if (scene.shadowsEnabled) {
  13491. var shadowGenerator = light.getShadowGenerator();
  13492. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13493. defines.push("#define SHADOW" + lightIndex);
  13494. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13495. if (!shadowsActivated) {
  13496. defines.push("#define SHADOWS");
  13497. shadowsActivated = true;
  13498. }
  13499. if (shadowGenerator.useVarianceShadowMap) {
  13500. defines.push("#define SHADOWVSM" + lightIndex);
  13501. if (lightIndex > 0) {
  13502. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13503. }
  13504. }
  13505. if (shadowGenerator.usePoissonSampling) {
  13506. defines.push("#define SHADOWPCF" + lightIndex);
  13507. if (lightIndex > 0) {
  13508. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13509. }
  13510. }
  13511. }
  13512. }
  13513. lightIndex++;
  13514. if (lightIndex === maxSimultaneousLights)
  13515. break;
  13516. }
  13517. }
  13518. if (StandardMaterial.FresnelEnabled) {
  13519. // Fresnel
  13520. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13521. var fresnelRank = 1;
  13522. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13523. defines.push("#define DIFFUSEFRESNEL");
  13524. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13525. fresnelRank++;
  13526. }
  13527. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13528. defines.push("#define OPACITYFRESNEL");
  13529. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13530. fresnelRank++;
  13531. }
  13532. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13533. defines.push("#define REFLECTIONFRESNEL");
  13534. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13535. fresnelRank++;
  13536. }
  13537. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13538. defines.push("#define EMISSIVEFRESNEL");
  13539. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13540. fresnelRank++;
  13541. }
  13542. defines.push("#define FRESNEL");
  13543. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13544. }
  13545. }
  13546. // Attribs
  13547. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13548. if (mesh) {
  13549. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13550. attribs.push(BABYLON.VertexBuffer.UVKind);
  13551. defines.push("#define UV1");
  13552. }
  13553. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13554. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13555. defines.push("#define UV2");
  13556. }
  13557. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13558. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13559. defines.push("#define VERTEXCOLOR");
  13560. if (mesh.hasVertexAlpha) {
  13561. defines.push("#define VERTEXALPHA");
  13562. }
  13563. }
  13564. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13565. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13566. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13567. defines.push("#define BONES");
  13568. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13569. defines.push("#define BONES4");
  13570. fallbacks.addFallback(0, "BONES4");
  13571. }
  13572. // Instances
  13573. if (useInstances) {
  13574. defines.push("#define INSTANCES");
  13575. attribs.push("world0");
  13576. attribs.push("world1");
  13577. attribs.push("world2");
  13578. attribs.push("world3");
  13579. }
  13580. }
  13581. // Get correct effect
  13582. var join = defines.join("\n");
  13583. if (this._cachedDefines !== join) {
  13584. this._cachedDefines = join;
  13585. scene.resetCachedMaterial();
  13586. // Legacy browser patch
  13587. var shaderName = "default";
  13588. if (!scene.getEngine().getCaps().standardDerivatives) {
  13589. shaderName = "legacydefault";
  13590. }
  13591. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "darkness0", "darkness1", "darkness2", "darkness3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  13592. }
  13593. if (!this._effect.isReady()) {
  13594. return false;
  13595. }
  13596. this._renderId = scene.getRenderId();
  13597. this._wasPreviouslyReady = true;
  13598. return true;
  13599. };
  13600. StandardMaterial.prototype.unbind = function () {
  13601. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13602. this._effect.setTexture("reflection2DSampler", null);
  13603. }
  13604. };
  13605. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13606. this._effect.setMatrix("world", world);
  13607. };
  13608. StandardMaterial.prototype.bind = function (world, mesh) {
  13609. var scene = this.getScene();
  13610. // Matrices
  13611. this.bindOnlyWorldMatrix(world);
  13612. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13613. // Bones
  13614. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13615. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13616. }
  13617. if (scene.getCachedMaterial() !== this) {
  13618. if (StandardMaterial.FresnelEnabled) {
  13619. // Fresnel
  13620. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13621. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13622. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13623. }
  13624. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13625. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13626. }
  13627. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13628. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13629. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13630. }
  13631. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13632. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13633. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13634. }
  13635. }
  13636. // Textures
  13637. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13638. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13639. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13640. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13641. }
  13642. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13643. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13644. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13645. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13646. }
  13647. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13648. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13649. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13650. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13651. }
  13652. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13653. if (this.reflectionTexture.isCube) {
  13654. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13655. }
  13656. else {
  13657. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13658. }
  13659. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13660. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13661. }
  13662. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13663. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13664. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13665. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13666. }
  13667. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13668. this._effect.setTexture("specularSampler", this.specularTexture);
  13669. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13670. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13671. }
  13672. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13673. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13674. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13675. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13676. }
  13677. // Clip plane
  13678. if (scene.clipPlane) {
  13679. var clipPlane = scene.clipPlane;
  13680. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13681. }
  13682. // Point size
  13683. if (this.pointsCloud) {
  13684. this._effect.setFloat("pointSize", this.pointSize);
  13685. }
  13686. // Colors
  13687. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13688. // Scaling down color according to emissive
  13689. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13690. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13691. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13692. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13693. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13694. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13695. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13696. }
  13697. // Scaling down color according to emissive
  13698. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13699. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13700. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13701. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13702. if (scene.lightsEnabled) {
  13703. var lightIndex = 0;
  13704. for (var index = 0; index < scene.lights.length; index++) {
  13705. var light = scene.lights[index];
  13706. if (!light.isEnabled()) {
  13707. continue;
  13708. }
  13709. if (!light.canAffectMesh(mesh)) {
  13710. continue;
  13711. }
  13712. if (light instanceof BABYLON.PointLight) {
  13713. // Point Light
  13714. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13715. }
  13716. else if (light instanceof BABYLON.DirectionalLight) {
  13717. // Directional Light
  13718. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13719. }
  13720. else if (light instanceof BABYLON.SpotLight) {
  13721. // Spot Light
  13722. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13723. }
  13724. else if (light instanceof BABYLON.HemisphericLight) {
  13725. // Hemispheric Light
  13726. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13727. }
  13728. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13729. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13730. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13731. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13732. // Shadows
  13733. if (scene.shadowsEnabled) {
  13734. var shadowGenerator = light.getShadowGenerator();
  13735. if (mesh.receiveShadows && shadowGenerator) {
  13736. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13737. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13738. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13739. }
  13740. }
  13741. lightIndex++;
  13742. if (lightIndex === maxSimultaneousLights)
  13743. break;
  13744. }
  13745. }
  13746. // View
  13747. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13748. this._effect.setMatrix("view", scene.getViewMatrix());
  13749. }
  13750. // Fog
  13751. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13752. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13753. this._effect.setColor3("vFogColor", scene.fogColor);
  13754. }
  13755. _super.prototype.bind.call(this, world, mesh);
  13756. };
  13757. StandardMaterial.prototype.getAnimatables = function () {
  13758. var results = [];
  13759. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13760. results.push(this.diffuseTexture);
  13761. }
  13762. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13763. results.push(this.ambientTexture);
  13764. }
  13765. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13766. results.push(this.opacityTexture);
  13767. }
  13768. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13769. results.push(this.reflectionTexture);
  13770. }
  13771. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13772. results.push(this.emissiveTexture);
  13773. }
  13774. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13775. results.push(this.specularTexture);
  13776. }
  13777. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13778. results.push(this.bumpTexture);
  13779. }
  13780. return results;
  13781. };
  13782. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13783. if (this.diffuseTexture) {
  13784. this.diffuseTexture.dispose();
  13785. }
  13786. if (this.ambientTexture) {
  13787. this.ambientTexture.dispose();
  13788. }
  13789. if (this.opacityTexture) {
  13790. this.opacityTexture.dispose();
  13791. }
  13792. if (this.reflectionTexture) {
  13793. this.reflectionTexture.dispose();
  13794. }
  13795. if (this.emissiveTexture) {
  13796. this.emissiveTexture.dispose();
  13797. }
  13798. if (this.specularTexture) {
  13799. this.specularTexture.dispose();
  13800. }
  13801. if (this.bumpTexture) {
  13802. this.bumpTexture.dispose();
  13803. }
  13804. _super.prototype.dispose.call(this, forceDisposeEffect);
  13805. };
  13806. StandardMaterial.prototype.clone = function (name) {
  13807. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13808. // Base material
  13809. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13810. newStandardMaterial.alpha = this.alpha;
  13811. newStandardMaterial.fillMode = this.fillMode;
  13812. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13813. // Standard material
  13814. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13815. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13816. }
  13817. if (this.ambientTexture && this.ambientTexture.clone) {
  13818. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13819. }
  13820. if (this.opacityTexture && this.opacityTexture.clone) {
  13821. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13822. }
  13823. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13824. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13825. }
  13826. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13827. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13828. }
  13829. if (this.specularTexture && this.specularTexture.clone) {
  13830. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13831. }
  13832. if (this.bumpTexture && this.bumpTexture.clone) {
  13833. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13834. }
  13835. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13836. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13837. newStandardMaterial.specularColor = this.specularColor.clone();
  13838. newStandardMaterial.specularPower = this.specularPower;
  13839. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13840. return newStandardMaterial;
  13841. };
  13842. // Statics
  13843. // Flags used to enable or disable a type of texture for all Standard Materials
  13844. StandardMaterial.DiffuseTextureEnabled = true;
  13845. StandardMaterial.AmbientTextureEnabled = true;
  13846. StandardMaterial.OpacityTextureEnabled = true;
  13847. StandardMaterial.ReflectionTextureEnabled = true;
  13848. StandardMaterial.EmissiveTextureEnabled = true;
  13849. StandardMaterial.SpecularTextureEnabled = true;
  13850. StandardMaterial.BumpTextureEnabled = true;
  13851. StandardMaterial.FresnelEnabled = true;
  13852. return StandardMaterial;
  13853. })(BABYLON.Material);
  13854. BABYLON.StandardMaterial = StandardMaterial;
  13855. })(BABYLON || (BABYLON = {}));
  13856. //# sourceMappingURL=babylon.standardMaterial.js.map
  13857. var BABYLON;
  13858. (function (BABYLON) {
  13859. var MultiMaterial = (function (_super) {
  13860. __extends(MultiMaterial, _super);
  13861. function MultiMaterial(name, scene) {
  13862. _super.call(this, name, scene, true);
  13863. this.subMaterials = new Array();
  13864. scene.multiMaterials.push(this);
  13865. }
  13866. // Properties
  13867. MultiMaterial.prototype.getSubMaterial = function (index) {
  13868. if (index < 0 || index >= this.subMaterials.length) {
  13869. return this.getScene().defaultMaterial;
  13870. }
  13871. return this.subMaterials[index];
  13872. };
  13873. // Methods
  13874. MultiMaterial.prototype.isReady = function (mesh) {
  13875. for (var index = 0; index < this.subMaterials.length; index++) {
  13876. var subMaterial = this.subMaterials[index];
  13877. if (subMaterial) {
  13878. if (!this.subMaterials[index].isReady(mesh)) {
  13879. return false;
  13880. }
  13881. }
  13882. }
  13883. return true;
  13884. };
  13885. return MultiMaterial;
  13886. })(BABYLON.Material);
  13887. BABYLON.MultiMaterial = MultiMaterial;
  13888. })(BABYLON || (BABYLON = {}));
  13889. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  13890. (function (BABYLON) {
  13891. var Database = (function () {
  13892. function Database(urlToScene, callbackManifestChecked) {
  13893. // Handling various flavors of prefixed version of IndexedDB
  13894. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13895. this.callbackManifestChecked = callbackManifestChecked;
  13896. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13897. this.db = null;
  13898. this.enableSceneOffline = false;
  13899. this.enableTexturesOffline = false;
  13900. this.manifestVersionFound = 0;
  13901. this.mustUpdateRessources = false;
  13902. this.hasReachedQuota = false;
  13903. this.checkManifestFile();
  13904. }
  13905. Database.prototype.checkManifestFile = function () {
  13906. var _this = this;
  13907. function noManifestFile() {
  13908. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13909. that.enableSceneOffline = false;
  13910. that.enableTexturesOffline = false;
  13911. that.callbackManifestChecked(false);
  13912. }
  13913. var that = this;
  13914. var manifestURL = this.currentSceneUrl + ".manifest";
  13915. var xhr = new XMLHttpRequest();
  13916. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13917. xhr.open("GET", manifestURLTimeStamped, true);
  13918. xhr.addEventListener("load", function () {
  13919. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13920. try {
  13921. var manifestFile = JSON.parse(xhr.response);
  13922. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13923. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13924. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13925. _this.manifestVersionFound = manifestFile.version;
  13926. }
  13927. if (_this.callbackManifestChecked) {
  13928. _this.callbackManifestChecked(true);
  13929. }
  13930. }
  13931. catch (ex) {
  13932. noManifestFile();
  13933. }
  13934. }
  13935. else {
  13936. noManifestFile();
  13937. }
  13938. }, false);
  13939. xhr.addEventListener("error", function (event) {
  13940. noManifestFile();
  13941. }, false);
  13942. try {
  13943. xhr.send();
  13944. }
  13945. catch (ex) {
  13946. BABYLON.Tools.Error("Error on XHR send request.");
  13947. that.callbackManifestChecked(false);
  13948. }
  13949. };
  13950. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13951. var _this = this;
  13952. function handleError() {
  13953. that.isSupported = false;
  13954. if (errorCallback)
  13955. errorCallback();
  13956. }
  13957. var that = this;
  13958. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13959. // Your browser doesn't support IndexedDB
  13960. this.isSupported = false;
  13961. if (errorCallback)
  13962. errorCallback();
  13963. }
  13964. else {
  13965. // If the DB hasn't been opened or created yet
  13966. if (!this.db) {
  13967. this.hasReachedQuota = false;
  13968. this.isSupported = true;
  13969. var request = this.idbFactory.open("babylonjs", 1);
  13970. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13971. request.onerror = function (event) {
  13972. handleError();
  13973. };
  13974. // executes when a version change transaction cannot complete due to other active transactions
  13975. request.onblocked = function (event) {
  13976. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13977. handleError();
  13978. };
  13979. // DB has been opened successfully
  13980. request.onsuccess = function (event) {
  13981. _this.db = request.result;
  13982. successCallback();
  13983. };
  13984. // Initialization of the DB. Creating Scenes & Textures stores
  13985. request.onupgradeneeded = function (event) {
  13986. _this.db = (event.target).result;
  13987. try {
  13988. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13989. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13990. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13991. }
  13992. catch (ex) {
  13993. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13994. handleError();
  13995. }
  13996. };
  13997. }
  13998. else {
  13999. if (successCallback)
  14000. successCallback();
  14001. }
  14002. }
  14003. };
  14004. Database.prototype.loadImageFromDB = function (url, image) {
  14005. var _this = this;
  14006. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  14007. var saveAndLoadImage = function () {
  14008. if (!_this.hasReachedQuota && _this.db !== null) {
  14009. // the texture is not yet in the DB, let's try to save it
  14010. _this._saveImageIntoDBAsync(completeURL, image);
  14011. }
  14012. else {
  14013. image.src = url;
  14014. }
  14015. };
  14016. if (!this.mustUpdateRessources) {
  14017. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14018. }
  14019. else {
  14020. saveAndLoadImage();
  14021. }
  14022. };
  14023. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14024. if (this.isSupported && this.db !== null) {
  14025. var texture;
  14026. var transaction = this.db.transaction(["textures"]);
  14027. transaction.onabort = function (event) {
  14028. image.src = url;
  14029. };
  14030. transaction.oncomplete = function (event) {
  14031. var blobTextureURL;
  14032. if (texture) {
  14033. var URL = window.URL || window.webkitURL;
  14034. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14035. image.onerror = function () {
  14036. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14037. image.src = url;
  14038. };
  14039. image.src = blobTextureURL;
  14040. }
  14041. else {
  14042. notInDBCallback();
  14043. }
  14044. };
  14045. var getRequest = transaction.objectStore("textures").get(url);
  14046. getRequest.onsuccess = function (event) {
  14047. texture = (event.target).result;
  14048. };
  14049. getRequest.onerror = function (event) {
  14050. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14051. image.src = url;
  14052. };
  14053. }
  14054. else {
  14055. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14056. image.src = url;
  14057. }
  14058. };
  14059. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14060. var _this = this;
  14061. if (this.isSupported) {
  14062. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14063. var generateBlobUrl = function () {
  14064. var blobTextureURL;
  14065. if (blob) {
  14066. var URL = window.URL || window.webkitURL;
  14067. try {
  14068. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14069. }
  14070. catch (ex) {
  14071. blobTextureURL = URL.createObjectURL(blob);
  14072. }
  14073. }
  14074. image.src = blobTextureURL;
  14075. };
  14076. if (BABYLON.Database.isUASupportingBlobStorage) {
  14077. var xhr = new XMLHttpRequest(), blob;
  14078. xhr.open("GET", url, true);
  14079. xhr.responseType = "blob";
  14080. xhr.addEventListener("load", function () {
  14081. if (xhr.status === 200) {
  14082. // Blob as response (XHR2)
  14083. blob = xhr.response;
  14084. var transaction = _this.db.transaction(["textures"], "readwrite");
  14085. // the transaction could abort because of a QuotaExceededError error
  14086. transaction.onabort = function (event) {
  14087. try {
  14088. if (event.srcElement.error.name === "QuotaExceededError") {
  14089. this.hasReachedQuota = true;
  14090. }
  14091. }
  14092. catch (ex) {
  14093. }
  14094. generateBlobUrl();
  14095. };
  14096. transaction.oncomplete = function (event) {
  14097. generateBlobUrl();
  14098. };
  14099. var newTexture = { textureUrl: url, data: blob };
  14100. try {
  14101. // Put the blob into the dabase
  14102. var addRequest = transaction.objectStore("textures").put(newTexture);
  14103. addRequest.onsuccess = function (event) {
  14104. };
  14105. addRequest.onerror = function (event) {
  14106. generateBlobUrl();
  14107. };
  14108. }
  14109. catch (ex) {
  14110. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14111. if (ex.code === 25) {
  14112. BABYLON.Database.isUASupportingBlobStorage = false;
  14113. }
  14114. image.src = url;
  14115. }
  14116. }
  14117. else {
  14118. image.src = url;
  14119. }
  14120. }, false);
  14121. xhr.addEventListener("error", function (event) {
  14122. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14123. image.src = url;
  14124. }, false);
  14125. xhr.send();
  14126. }
  14127. else {
  14128. image.src = url;
  14129. }
  14130. }
  14131. else {
  14132. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14133. image.src = url;
  14134. }
  14135. };
  14136. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14137. var _this = this;
  14138. var updateVersion = function (event) {
  14139. // the version is not yet in the DB or we need to update it
  14140. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14141. };
  14142. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14143. };
  14144. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14145. var _this = this;
  14146. if (this.isSupported) {
  14147. var version;
  14148. try {
  14149. var transaction = this.db.transaction(["versions"]);
  14150. transaction.oncomplete = function (event) {
  14151. if (version) {
  14152. // If the version in the JSON file is > than the version in DB
  14153. if (_this.manifestVersionFound > version.data) {
  14154. _this.mustUpdateRessources = true;
  14155. updateInDBCallback();
  14156. }
  14157. else {
  14158. callback(version.data);
  14159. }
  14160. }
  14161. else {
  14162. _this.mustUpdateRessources = true;
  14163. updateInDBCallback();
  14164. }
  14165. };
  14166. transaction.onabort = function (event) {
  14167. callback(-1);
  14168. };
  14169. var getRequest = transaction.objectStore("versions").get(url);
  14170. getRequest.onsuccess = function (event) {
  14171. version = (event.target).result;
  14172. };
  14173. getRequest.onerror = function (event) {
  14174. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14175. callback(-1);
  14176. };
  14177. }
  14178. catch (ex) {
  14179. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14180. callback(-1);
  14181. }
  14182. }
  14183. else {
  14184. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14185. callback(-1);
  14186. }
  14187. };
  14188. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14189. var _this = this;
  14190. if (this.isSupported && !this.hasReachedQuota) {
  14191. try {
  14192. // Open a transaction to the database
  14193. var transaction = this.db.transaction(["versions"], "readwrite");
  14194. // the transaction could abort because of a QuotaExceededError error
  14195. transaction.onabort = function (event) {
  14196. try {
  14197. if (event.srcElement.error.name === "QuotaExceededError") {
  14198. _this.hasReachedQuota = true;
  14199. }
  14200. }
  14201. catch (ex) {
  14202. }
  14203. callback(-1);
  14204. };
  14205. transaction.oncomplete = function (event) {
  14206. callback(_this.manifestVersionFound);
  14207. };
  14208. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14209. // Put the scene into the database
  14210. var addRequest = transaction.objectStore("versions").put(newVersion);
  14211. addRequest.onsuccess = function (event) {
  14212. };
  14213. addRequest.onerror = function (event) {
  14214. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14215. };
  14216. }
  14217. catch (ex) {
  14218. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14219. callback(-1);
  14220. }
  14221. }
  14222. else {
  14223. callback(-1);
  14224. }
  14225. };
  14226. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14227. var _this = this;
  14228. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  14229. var saveAndLoadFile = function (event) {
  14230. // the scene is not yet in the DB, let's try to save it
  14231. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14232. };
  14233. this._checkVersionFromDB(completeUrl, function (version) {
  14234. if (version !== -1) {
  14235. if (!_this.mustUpdateRessources) {
  14236. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14237. }
  14238. else {
  14239. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14240. }
  14241. }
  14242. else {
  14243. errorCallback();
  14244. }
  14245. });
  14246. };
  14247. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14248. if (this.isSupported) {
  14249. var targetStore;
  14250. if (url.indexOf(".babylon") !== -1) {
  14251. targetStore = "scenes";
  14252. }
  14253. else {
  14254. targetStore = "textures";
  14255. }
  14256. var file;
  14257. var transaction = this.db.transaction([targetStore]);
  14258. transaction.oncomplete = function (event) {
  14259. if (file) {
  14260. callback(file.data);
  14261. }
  14262. else {
  14263. notInDBCallback();
  14264. }
  14265. };
  14266. transaction.onabort = function (event) {
  14267. notInDBCallback();
  14268. };
  14269. var getRequest = transaction.objectStore(targetStore).get(url);
  14270. getRequest.onsuccess = function (event) {
  14271. file = (event.target).result;
  14272. };
  14273. getRequest.onerror = function (event) {
  14274. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14275. notInDBCallback();
  14276. };
  14277. }
  14278. else {
  14279. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14280. callback();
  14281. }
  14282. };
  14283. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14284. var _this = this;
  14285. if (this.isSupported) {
  14286. var targetStore;
  14287. if (url.indexOf(".babylon") !== -1) {
  14288. targetStore = "scenes";
  14289. }
  14290. else {
  14291. targetStore = "textures";
  14292. }
  14293. // Create XHR
  14294. var xhr = new XMLHttpRequest(), fileData;
  14295. xhr.open("GET", url, true);
  14296. if (useArrayBuffer) {
  14297. xhr.responseType = "arraybuffer";
  14298. }
  14299. xhr.onprogress = progressCallback;
  14300. xhr.addEventListener("load", function () {
  14301. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14302. // Blob as response (XHR2)
  14303. //fileData = xhr.responseText;
  14304. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14305. if (!_this.hasReachedQuota) {
  14306. // Open a transaction to the database
  14307. var transaction = _this.db.transaction([targetStore], "readwrite");
  14308. // the transaction could abort because of a QuotaExceededError error
  14309. transaction.onabort = function (event) {
  14310. try {
  14311. if (event.srcElement.error.name === "QuotaExceededError") {
  14312. this.hasReachedQuota = true;
  14313. }
  14314. }
  14315. catch (ex) {
  14316. }
  14317. callback(fileData);
  14318. };
  14319. transaction.oncomplete = function (event) {
  14320. callback(fileData);
  14321. };
  14322. var newFile;
  14323. if (targetStore === "scenes") {
  14324. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14325. }
  14326. else {
  14327. newFile = { textureUrl: url, data: fileData };
  14328. }
  14329. try {
  14330. // Put the scene into the database
  14331. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14332. addRequest.onsuccess = function (event) {
  14333. };
  14334. addRequest.onerror = function (event) {
  14335. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14336. };
  14337. }
  14338. catch (ex) {
  14339. callback(fileData);
  14340. }
  14341. }
  14342. else {
  14343. callback(fileData);
  14344. }
  14345. }
  14346. else {
  14347. callback();
  14348. }
  14349. }, false);
  14350. xhr.addEventListener("error", function (event) {
  14351. BABYLON.Tools.Error("error on XHR request.");
  14352. callback();
  14353. }, false);
  14354. xhr.send();
  14355. }
  14356. else {
  14357. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14358. callback();
  14359. }
  14360. };
  14361. Database.isUASupportingBlobStorage = true;
  14362. Database.parseURL = function (url) {
  14363. var a = document.createElement('a');
  14364. a.href = url;
  14365. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14366. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14367. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14368. return absLocation;
  14369. };
  14370. Database.ReturnFullUrlLocation = function (url) {
  14371. if (url.indexOf("http:/") === -1) {
  14372. return (BABYLON.Database.parseURL(window.location.href) + url);
  14373. }
  14374. else {
  14375. return url;
  14376. }
  14377. };
  14378. return Database;
  14379. })();
  14380. BABYLON.Database = Database;
  14381. })(BABYLON || (BABYLON = {}));
  14382. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14383. (function (BABYLON) {
  14384. var SpriteManager = (function () {
  14385. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14386. this.name = name;
  14387. this.cellSize = cellSize;
  14388. this.sprites = new Array();
  14389. this.renderingGroupId = 0;
  14390. this.fogEnabled = true;
  14391. this._vertexDeclaration = [3, 4, 4, 4];
  14392. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14393. this._capacity = capacity;
  14394. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14395. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14396. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14397. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14398. this._scene = scene;
  14399. this._scene.spriteManagers.push(this);
  14400. // VBO
  14401. this._vertexDeclaration = [3, 4, 4, 4];
  14402. this._vertexStrideSize = 15 * 4;
  14403. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14404. var indices = [];
  14405. var index = 0;
  14406. for (var count = 0; count < capacity; count++) {
  14407. indices.push(index);
  14408. indices.push(index + 1);
  14409. indices.push(index + 2);
  14410. indices.push(index);
  14411. indices.push(index + 2);
  14412. indices.push(index + 3);
  14413. index += 4;
  14414. }
  14415. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14416. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14417. // Effects
  14418. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14419. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14420. }
  14421. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14422. var arrayOffset = index * 15;
  14423. if (offsetX == 0)
  14424. offsetX = this._epsilon;
  14425. else if (offsetX == 1)
  14426. offsetX = 1 - this._epsilon;
  14427. if (offsetY == 0)
  14428. offsetY = this._epsilon;
  14429. else if (offsetY == 1)
  14430. offsetY = 1 - this._epsilon;
  14431. this._vertices[arrayOffset] = sprite.position.x;
  14432. this._vertices[arrayOffset + 1] = sprite.position.y;
  14433. this._vertices[arrayOffset + 2] = sprite.position.z;
  14434. this._vertices[arrayOffset + 3] = sprite.angle;
  14435. this._vertices[arrayOffset + 4] = sprite.size;
  14436. this._vertices[arrayOffset + 5] = offsetX;
  14437. this._vertices[arrayOffset + 6] = offsetY;
  14438. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14439. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14440. var offset = (sprite.cellIndex / rowSize) >> 0;
  14441. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14442. this._vertices[arrayOffset + 10] = offset;
  14443. // Color
  14444. this._vertices[arrayOffset + 11] = sprite.color.r;
  14445. this._vertices[arrayOffset + 12] = sprite.color.g;
  14446. this._vertices[arrayOffset + 13] = sprite.color.b;
  14447. this._vertices[arrayOffset + 14] = sprite.color.a;
  14448. };
  14449. SpriteManager.prototype.render = function () {
  14450. // Check
  14451. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14452. return;
  14453. var engine = this._scene.getEngine();
  14454. var baseSize = this._spriteTexture.getBaseSize();
  14455. // Sprites
  14456. var deltaTime = engine.getDeltaTime();
  14457. var max = Math.min(this._capacity, this.sprites.length);
  14458. var rowSize = baseSize.width / this.cellSize;
  14459. var offset = 0;
  14460. for (var index = 0; index < max; index++) {
  14461. var sprite = this.sprites[index];
  14462. if (!sprite) {
  14463. continue;
  14464. }
  14465. sprite._animate(deltaTime);
  14466. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14467. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14468. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14469. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14470. }
  14471. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14472. // Render
  14473. var effect = this._effectBase;
  14474. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14475. effect = this._effectFog;
  14476. }
  14477. engine.enableEffect(effect);
  14478. var viewMatrix = this._scene.getViewMatrix();
  14479. effect.setTexture("diffuseSampler", this._spriteTexture);
  14480. effect.setMatrix("view", viewMatrix);
  14481. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14482. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14483. // Fog
  14484. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14485. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14486. effect.setColor3("vFogColor", this._scene.fogColor);
  14487. }
  14488. // VBOs
  14489. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14490. // Draw order
  14491. effect.setBool("alphaTest", true);
  14492. engine.setColorWrite(false);
  14493. engine.draw(true, 0, max * 6);
  14494. engine.setColorWrite(true);
  14495. effect.setBool("alphaTest", false);
  14496. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14497. engine.draw(true, 0, max * 6);
  14498. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14499. };
  14500. SpriteManager.prototype.dispose = function () {
  14501. if (this._vertexBuffer) {
  14502. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14503. this._vertexBuffer = null;
  14504. }
  14505. if (this._indexBuffer) {
  14506. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14507. this._indexBuffer = null;
  14508. }
  14509. if (this._spriteTexture) {
  14510. this._spriteTexture.dispose();
  14511. this._spriteTexture = null;
  14512. }
  14513. // Remove from scene
  14514. var index = this._scene.spriteManagers.indexOf(this);
  14515. this._scene.spriteManagers.splice(index, 1);
  14516. // Callback
  14517. if (this.onDispose) {
  14518. this.onDispose();
  14519. }
  14520. };
  14521. return SpriteManager;
  14522. })();
  14523. BABYLON.SpriteManager = SpriteManager;
  14524. })(BABYLON || (BABYLON = {}));
  14525. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14526. (function (BABYLON) {
  14527. var Sprite = (function () {
  14528. function Sprite(name, manager) {
  14529. this.name = name;
  14530. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14531. this.size = 1.0;
  14532. this.angle = 0;
  14533. this.cellIndex = 0;
  14534. this.invertU = 0;
  14535. this.invertV = 0;
  14536. this.animations = new Array();
  14537. this._animationStarted = false;
  14538. this._loopAnimation = false;
  14539. this._fromIndex = 0;
  14540. this._toIndex = 0;
  14541. this._delay = 0;
  14542. this._direction = 1;
  14543. this._frameCount = 0;
  14544. this._time = 0;
  14545. this._manager = manager;
  14546. this._manager.sprites.push(this);
  14547. this.position = BABYLON.Vector3.Zero();
  14548. }
  14549. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14550. this._fromIndex = from;
  14551. this._toIndex = to;
  14552. this._loopAnimation = loop;
  14553. this._delay = delay;
  14554. this._animationStarted = true;
  14555. this._direction = from < to ? 1 : -1;
  14556. this.cellIndex = from;
  14557. this._time = 0;
  14558. };
  14559. Sprite.prototype.stopAnimation = function () {
  14560. this._animationStarted = false;
  14561. };
  14562. Sprite.prototype._animate = function (deltaTime) {
  14563. if (!this._animationStarted)
  14564. return;
  14565. this._time += deltaTime;
  14566. if (this._time > this._delay) {
  14567. this._time = this._time % this._delay;
  14568. this.cellIndex += this._direction;
  14569. if (this.cellIndex == this._toIndex) {
  14570. if (this._loopAnimation) {
  14571. this.cellIndex = this._fromIndex;
  14572. }
  14573. else {
  14574. this._animationStarted = false;
  14575. if (this.disposeWhenFinishedAnimating) {
  14576. this.dispose();
  14577. }
  14578. }
  14579. }
  14580. }
  14581. };
  14582. Sprite.prototype.dispose = function () {
  14583. for (var i = 0; i < this._manager.sprites.length; i++) {
  14584. if (this._manager.sprites[i] == this) {
  14585. this._manager.sprites.splice(i, 1);
  14586. }
  14587. }
  14588. };
  14589. return Sprite;
  14590. })();
  14591. BABYLON.Sprite = Sprite;
  14592. })(BABYLON || (BABYLON = {}));
  14593. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14594. (function (BABYLON) {
  14595. var Layer = (function () {
  14596. function Layer(name, imgUrl, scene, isBackground, color) {
  14597. this.name = name;
  14598. this._vertexDeclaration = [2];
  14599. this._vertexStrideSize = 2 * 4;
  14600. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14601. this.isBackground = isBackground === undefined ? true : isBackground;
  14602. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14603. this._scene = scene;
  14604. this._scene.layers.push(this);
  14605. // VBO
  14606. var vertices = [];
  14607. vertices.push(1, 1);
  14608. vertices.push(-1, 1);
  14609. vertices.push(-1, -1);
  14610. vertices.push(1, -1);
  14611. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14612. // Indices
  14613. var indices = [];
  14614. indices.push(0);
  14615. indices.push(1);
  14616. indices.push(2);
  14617. indices.push(0);
  14618. indices.push(2);
  14619. indices.push(3);
  14620. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14621. // Effects
  14622. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14623. }
  14624. Layer.prototype.render = function () {
  14625. // Check
  14626. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14627. return;
  14628. var engine = this._scene.getEngine();
  14629. // Render
  14630. engine.enableEffect(this._effect);
  14631. engine.setState(false);
  14632. // Texture
  14633. this._effect.setTexture("textureSampler", this.texture);
  14634. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14635. // Color
  14636. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14637. // VBOs
  14638. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14639. // Draw order
  14640. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14641. engine.draw(true, 0, 6);
  14642. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14643. };
  14644. Layer.prototype.dispose = function () {
  14645. if (this._vertexBuffer) {
  14646. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14647. this._vertexBuffer = null;
  14648. }
  14649. if (this._indexBuffer) {
  14650. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14651. this._indexBuffer = null;
  14652. }
  14653. if (this.texture) {
  14654. this.texture.dispose();
  14655. this.texture = null;
  14656. }
  14657. // Remove from scene
  14658. var index = this._scene.layers.indexOf(this);
  14659. this._scene.layers.splice(index, 1);
  14660. // Callback
  14661. if (this.onDispose) {
  14662. this.onDispose();
  14663. }
  14664. };
  14665. return Layer;
  14666. })();
  14667. BABYLON.Layer = Layer;
  14668. })(BABYLON || (BABYLON = {}));
  14669. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14670. (function (BABYLON) {
  14671. var Particle = (function () {
  14672. function Particle() {
  14673. this.position = BABYLON.Vector3.Zero();
  14674. this.direction = BABYLON.Vector3.Zero();
  14675. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14676. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14677. this.lifeTime = 1.0;
  14678. this.age = 0;
  14679. this.size = 0;
  14680. this.angle = 0;
  14681. this.angularSpeed = 0;
  14682. }
  14683. Particle.prototype.copyTo = function (other) {
  14684. other.position.copyFrom(this.position);
  14685. other.direction.copyFrom(this.direction);
  14686. other.color.copyFrom(this.color);
  14687. other.colorStep.copyFrom(this.colorStep);
  14688. other.lifeTime = this.lifeTime;
  14689. other.age = this.age;
  14690. other.size = this.size;
  14691. other.angle = this.angle;
  14692. other.angularSpeed = this.angularSpeed;
  14693. };
  14694. return Particle;
  14695. })();
  14696. BABYLON.Particle = Particle;
  14697. })(BABYLON || (BABYLON = {}));
  14698. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14699. (function (BABYLON) {
  14700. var randomNumber = function (min, max) {
  14701. if (min === max) {
  14702. return (min);
  14703. }
  14704. var random = Math.random();
  14705. return ((random * (max - min)) + min);
  14706. };
  14707. var ParticleSystem = (function () {
  14708. function ParticleSystem(name, capacity, scene, customEffect) {
  14709. var _this = this;
  14710. this.name = name;
  14711. this.renderingGroupId = 0;
  14712. this.emitter = null;
  14713. this.emitRate = 10;
  14714. this.manualEmitCount = -1;
  14715. this.updateSpeed = 0.01;
  14716. this.targetStopDuration = 0;
  14717. this.disposeOnStop = false;
  14718. this.minEmitPower = 1;
  14719. this.maxEmitPower = 1;
  14720. this.minLifeTime = 1;
  14721. this.maxLifeTime = 1;
  14722. this.minSize = 1;
  14723. this.maxSize = 1;
  14724. this.minAngularSpeed = 0;
  14725. this.maxAngularSpeed = 0;
  14726. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14727. this.forceDepthWrite = false;
  14728. this.gravity = BABYLON.Vector3.Zero();
  14729. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14730. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14731. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14732. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14733. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14734. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14735. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14736. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14737. this.particles = new Array();
  14738. this._vertexDeclaration = [3, 4, 4];
  14739. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14740. this._stockParticles = new Array();
  14741. this._newPartsExcess = 0;
  14742. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14743. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14744. this._scaledDirection = BABYLON.Vector3.Zero();
  14745. this._scaledGravity = BABYLON.Vector3.Zero();
  14746. this._currentRenderId = -1;
  14747. this._started = false;
  14748. this._stopped = false;
  14749. this._actualFrame = 0;
  14750. this.id = name;
  14751. this._capacity = capacity;
  14752. this._scene = scene;
  14753. this._customEffect = customEffect;
  14754. scene.particleSystems.push(this);
  14755. // VBO
  14756. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14757. var indices = [];
  14758. var index = 0;
  14759. for (var count = 0; count < capacity; count++) {
  14760. indices.push(index);
  14761. indices.push(index + 1);
  14762. indices.push(index + 2);
  14763. indices.push(index);
  14764. indices.push(index + 2);
  14765. indices.push(index + 3);
  14766. index += 4;
  14767. }
  14768. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14769. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14770. // Default behaviors
  14771. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14772. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14773. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14774. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14775. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14776. };
  14777. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14778. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14779. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14780. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14781. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14782. };
  14783. this.updateFunction = function (particles) {
  14784. for (var index = 0; index < particles.length; index++) {
  14785. var particle = particles[index];
  14786. particle.age += _this._scaledUpdateSpeed;
  14787. if (particle.age >= particle.lifeTime) {
  14788. _this.recycleParticle(particle);
  14789. index--;
  14790. continue;
  14791. }
  14792. else {
  14793. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14794. particle.color.addInPlace(_this._scaledColorStep);
  14795. if (particle.color.a < 0)
  14796. particle.color.a = 0;
  14797. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14798. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14799. particle.position.addInPlace(_this._scaledDirection);
  14800. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14801. particle.direction.addInPlace(_this._scaledGravity);
  14802. }
  14803. }
  14804. };
  14805. }
  14806. ParticleSystem.prototype.recycleParticle = function (particle) {
  14807. var lastParticle = this.particles.pop();
  14808. if (lastParticle !== particle) {
  14809. lastParticle.copyTo(particle);
  14810. this._stockParticles.push(lastParticle);
  14811. }
  14812. };
  14813. ParticleSystem.prototype.getCapacity = function () {
  14814. return this._capacity;
  14815. };
  14816. ParticleSystem.prototype.isAlive = function () {
  14817. return this._alive;
  14818. };
  14819. ParticleSystem.prototype.isStarted = function () {
  14820. return this._started;
  14821. };
  14822. ParticleSystem.prototype.start = function () {
  14823. this._started = true;
  14824. this._stopped = false;
  14825. this._actualFrame = 0;
  14826. };
  14827. ParticleSystem.prototype.stop = function () {
  14828. this._stopped = true;
  14829. };
  14830. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14831. var offset = index * 11;
  14832. this._vertices[offset] = particle.position.x;
  14833. this._vertices[offset + 1] = particle.position.y;
  14834. this._vertices[offset + 2] = particle.position.z;
  14835. this._vertices[offset + 3] = particle.color.r;
  14836. this._vertices[offset + 4] = particle.color.g;
  14837. this._vertices[offset + 5] = particle.color.b;
  14838. this._vertices[offset + 6] = particle.color.a;
  14839. this._vertices[offset + 7] = particle.angle;
  14840. this._vertices[offset + 8] = particle.size;
  14841. this._vertices[offset + 9] = offsetX;
  14842. this._vertices[offset + 10] = offsetY;
  14843. };
  14844. ParticleSystem.prototype._update = function (newParticles) {
  14845. // Update current
  14846. this._alive = this.particles.length > 0;
  14847. this.updateFunction(this.particles);
  14848. // Add new ones
  14849. var worldMatrix;
  14850. if (this.emitter.position) {
  14851. worldMatrix = this.emitter.getWorldMatrix();
  14852. }
  14853. else {
  14854. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14855. }
  14856. for (var index = 0; index < newParticles; index++) {
  14857. if (this.particles.length === this._capacity) {
  14858. break;
  14859. }
  14860. if (this._stockParticles.length !== 0) {
  14861. var particle = this._stockParticles.pop();
  14862. particle.age = 0;
  14863. }
  14864. else {
  14865. particle = new BABYLON.Particle();
  14866. }
  14867. this.particles.push(particle);
  14868. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14869. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14870. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14871. particle.size = randomNumber(this.minSize, this.maxSize);
  14872. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14873. this.startPositionFunction(worldMatrix, particle.position);
  14874. var step = randomNumber(0, 1.0);
  14875. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14876. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14877. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14878. }
  14879. };
  14880. ParticleSystem.prototype._getEffect = function () {
  14881. if (this._customEffect) {
  14882. return this._customEffect;
  14883. }
  14884. ;
  14885. var defines = [];
  14886. if (this._scene.clipPlane) {
  14887. defines.push("#define CLIPPLANE");
  14888. }
  14889. // Effect
  14890. var join = defines.join("\n");
  14891. if (this._cachedDefines !== join) {
  14892. this._cachedDefines = join;
  14893. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14894. }
  14895. return this._effect;
  14896. };
  14897. ParticleSystem.prototype.animate = function () {
  14898. if (!this._started)
  14899. return;
  14900. var effect = this._getEffect();
  14901. // Check
  14902. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14903. return;
  14904. if (this._currentRenderId === this._scene.getRenderId()) {
  14905. return;
  14906. }
  14907. this._currentRenderId = this._scene.getRenderId();
  14908. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14909. // determine the number of particles we need to create
  14910. var emitCout;
  14911. if (this.manualEmitCount > -1) {
  14912. emitCout = this.manualEmitCount;
  14913. this.manualEmitCount = 0;
  14914. }
  14915. else {
  14916. emitCout = this.emitRate;
  14917. }
  14918. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14919. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14920. if (this._newPartsExcess > 1.0) {
  14921. newParticles += this._newPartsExcess >> 0;
  14922. this._newPartsExcess -= this._newPartsExcess >> 0;
  14923. }
  14924. this._alive = false;
  14925. if (!this._stopped) {
  14926. this._actualFrame += this._scaledUpdateSpeed;
  14927. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14928. this.stop();
  14929. }
  14930. else {
  14931. newParticles = 0;
  14932. }
  14933. this._update(newParticles);
  14934. // Stopped?
  14935. if (this._stopped) {
  14936. if (!this._alive) {
  14937. this._started = false;
  14938. if (this.disposeOnStop) {
  14939. this._scene._toBeDisposed.push(this);
  14940. }
  14941. }
  14942. }
  14943. // Update VBO
  14944. var offset = 0;
  14945. for (var index = 0; index < this.particles.length; index++) {
  14946. var particle = this.particles[index];
  14947. this._appendParticleVertex(offset++, particle, 0, 0);
  14948. this._appendParticleVertex(offset++, particle, 1, 0);
  14949. this._appendParticleVertex(offset++, particle, 1, 1);
  14950. this._appendParticleVertex(offset++, particle, 0, 1);
  14951. }
  14952. var engine = this._scene.getEngine();
  14953. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14954. };
  14955. ParticleSystem.prototype.render = function () {
  14956. var effect = this._getEffect();
  14957. // Check
  14958. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14959. return 0;
  14960. var engine = this._scene.getEngine();
  14961. // Render
  14962. engine.enableEffect(effect);
  14963. engine.setState(false);
  14964. var viewMatrix = this._scene.getViewMatrix();
  14965. effect.setTexture("diffuseSampler", this.particleTexture);
  14966. effect.setMatrix("view", viewMatrix);
  14967. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14968. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14969. if (this._scene.clipPlane) {
  14970. var clipPlane = this._scene.clipPlane;
  14971. var invView = viewMatrix.clone();
  14972. invView.invert();
  14973. effect.setMatrix("invView", invView);
  14974. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14975. }
  14976. // VBOs
  14977. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14978. // Draw order
  14979. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14980. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14981. }
  14982. else {
  14983. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14984. }
  14985. if (this.forceDepthWrite) {
  14986. engine.setDepthWrite(true);
  14987. }
  14988. engine.draw(true, 0, this.particles.length * 6);
  14989. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14990. return this.particles.length;
  14991. };
  14992. ParticleSystem.prototype.dispose = function () {
  14993. if (this._vertexBuffer) {
  14994. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14995. this._vertexBuffer = null;
  14996. }
  14997. if (this._indexBuffer) {
  14998. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14999. this._indexBuffer = null;
  15000. }
  15001. if (this.particleTexture) {
  15002. this.particleTexture.dispose();
  15003. this.particleTexture = null;
  15004. }
  15005. // Remove from scene
  15006. var index = this._scene.particleSystems.indexOf(this);
  15007. this._scene.particleSystems.splice(index, 1);
  15008. // Callback
  15009. if (this.onDispose) {
  15010. this.onDispose();
  15011. }
  15012. };
  15013. // Clone
  15014. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15015. var result = new ParticleSystem(name, this._capacity, this._scene);
  15016. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15017. if (newEmitter === undefined) {
  15018. newEmitter = this.emitter;
  15019. }
  15020. result.emitter = newEmitter;
  15021. if (this.particleTexture) {
  15022. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15023. }
  15024. result.start();
  15025. return result;
  15026. };
  15027. // Statics
  15028. ParticleSystem.BLENDMODE_ONEONE = 0;
  15029. ParticleSystem.BLENDMODE_STANDARD = 1;
  15030. return ParticleSystem;
  15031. })();
  15032. BABYLON.ParticleSystem = ParticleSystem;
  15033. })(BABYLON || (BABYLON = {}));
  15034. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15035. (function (BABYLON) {
  15036. var Animation = (function () {
  15037. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15038. this.name = name;
  15039. this.targetProperty = targetProperty;
  15040. this.framePerSecond = framePerSecond;
  15041. this.dataType = dataType;
  15042. this.loopMode = loopMode;
  15043. this._offsetsCache = {};
  15044. this._highLimitsCache = {};
  15045. this._stopped = false;
  15046. this.targetPropertyPath = targetProperty.split(".");
  15047. this.dataType = dataType;
  15048. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15049. }
  15050. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15051. var dataType = undefined;
  15052. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15053. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15054. }
  15055. else if (from instanceof BABYLON.Quaternion) {
  15056. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15057. }
  15058. else if (from instanceof BABYLON.Vector3) {
  15059. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15060. }
  15061. else if (from instanceof BABYLON.Vector2) {
  15062. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15063. }
  15064. else if (from instanceof BABYLON.Color3) {
  15065. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15066. }
  15067. if (dataType == undefined) {
  15068. return;
  15069. }
  15070. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15071. var keys = [];
  15072. keys.push({ frame: 0, value: from });
  15073. keys.push({ frame: totalFrame, value: to });
  15074. animation.setKeys(keys);
  15075. mesh.animations.push(animation);
  15076. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15077. };
  15078. // Methods
  15079. Animation.prototype.isStopped = function () {
  15080. return this._stopped;
  15081. };
  15082. Animation.prototype.getKeys = function () {
  15083. return this._keys;
  15084. };
  15085. Animation.prototype.getEasingFunction = function () {
  15086. return this._easingFunction;
  15087. };
  15088. Animation.prototype.setEasingFunction = function (easingFunction) {
  15089. this._easingFunction = easingFunction;
  15090. };
  15091. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15092. return startValue + (endValue - startValue) * gradient;
  15093. };
  15094. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15095. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15096. };
  15097. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15098. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15099. };
  15100. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15101. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15102. };
  15103. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15104. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15105. };
  15106. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15107. var startScale = new BABYLON.Vector3(0, 0, 0);
  15108. var startRotation = new BABYLON.Quaternion();
  15109. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15110. startValue.decompose(startScale, startRotation, startTranslation);
  15111. var endScale = new BABYLON.Vector3(0, 0, 0);
  15112. var endRotation = new BABYLON.Quaternion();
  15113. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15114. endValue.decompose(endScale, endRotation, endTranslation);
  15115. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15116. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15117. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15118. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15119. return result;
  15120. };
  15121. Animation.prototype.clone = function () {
  15122. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15123. clone.setKeys(this._keys);
  15124. return clone;
  15125. };
  15126. Animation.prototype.setKeys = function (values) {
  15127. this._keys = values.slice(0);
  15128. this._offsetsCache = {};
  15129. this._highLimitsCache = {};
  15130. };
  15131. Animation.prototype._getKeyValue = function (value) {
  15132. if (typeof value === "function") {
  15133. return value();
  15134. }
  15135. return value;
  15136. };
  15137. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15138. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15139. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15140. }
  15141. this.currentFrame = currentFrame;
  15142. for (var key = 0; key < this._keys.length; key++) {
  15143. // for each frame, we need the key just before the frame superior
  15144. if (this._keys[key + 1].frame >= currentFrame) {
  15145. var startValue = this._getKeyValue(this._keys[key].value);
  15146. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15147. // gradient : percent of currentFrame between the frame inf and the frame sup
  15148. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15149. // check for easingFunction and correction of gradient
  15150. if (this._easingFunction != null) {
  15151. gradient = this._easingFunction.ease(gradient);
  15152. }
  15153. switch (this.dataType) {
  15154. case Animation.ANIMATIONTYPE_FLOAT:
  15155. switch (loopMode) {
  15156. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15157. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15158. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15159. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15160. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15161. }
  15162. break;
  15163. case Animation.ANIMATIONTYPE_QUATERNION:
  15164. var quaternion = null;
  15165. switch (loopMode) {
  15166. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15167. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15168. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15169. break;
  15170. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15171. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15172. break;
  15173. }
  15174. return quaternion;
  15175. case Animation.ANIMATIONTYPE_VECTOR3:
  15176. switch (loopMode) {
  15177. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15178. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15179. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15180. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15181. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15182. }
  15183. case Animation.ANIMATIONTYPE_VECTOR2:
  15184. switch (loopMode) {
  15185. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15186. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15187. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15188. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15189. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15190. }
  15191. case Animation.ANIMATIONTYPE_COLOR3:
  15192. switch (loopMode) {
  15193. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15194. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15195. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15196. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15197. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15198. }
  15199. case Animation.ANIMATIONTYPE_MATRIX:
  15200. switch (loopMode) {
  15201. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15202. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15203. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  15204. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15205. return startValue;
  15206. }
  15207. default:
  15208. break;
  15209. }
  15210. break;
  15211. }
  15212. }
  15213. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15214. };
  15215. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15216. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15217. this._stopped = true;
  15218. return false;
  15219. }
  15220. var returnValue = true;
  15221. // Adding a start key at frame 0 if missing
  15222. if (this._keys[0].frame !== 0) {
  15223. var newKey = { frame: 0, value: this._keys[0].value };
  15224. this._keys.splice(0, 0, newKey);
  15225. }
  15226. // Check limits
  15227. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15228. from = this._keys[0].frame;
  15229. }
  15230. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15231. to = this._keys[this._keys.length - 1].frame;
  15232. }
  15233. // Compute ratio
  15234. var range = to - from;
  15235. var offsetValue;
  15236. // ratio represents the frame delta between from and to
  15237. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15238. var highLimitValue = 0;
  15239. if (ratio > range && !loop) {
  15240. returnValue = false;
  15241. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15242. }
  15243. else {
  15244. // Get max value if required
  15245. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15246. var keyOffset = to.toString() + from.toString();
  15247. if (!this._offsetsCache[keyOffset]) {
  15248. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15249. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15250. switch (this.dataType) {
  15251. case Animation.ANIMATIONTYPE_FLOAT:
  15252. this._offsetsCache[keyOffset] = toValue - fromValue;
  15253. break;
  15254. case Animation.ANIMATIONTYPE_QUATERNION:
  15255. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15256. break;
  15257. case Animation.ANIMATIONTYPE_VECTOR3:
  15258. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15259. case Animation.ANIMATIONTYPE_VECTOR2:
  15260. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15261. case Animation.ANIMATIONTYPE_COLOR3:
  15262. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15263. default:
  15264. break;
  15265. }
  15266. this._highLimitsCache[keyOffset] = toValue;
  15267. }
  15268. highLimitValue = this._highLimitsCache[keyOffset];
  15269. offsetValue = this._offsetsCache[keyOffset];
  15270. }
  15271. }
  15272. if (offsetValue === undefined) {
  15273. switch (this.dataType) {
  15274. case Animation.ANIMATIONTYPE_FLOAT:
  15275. offsetValue = 0;
  15276. break;
  15277. case Animation.ANIMATIONTYPE_QUATERNION:
  15278. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15279. break;
  15280. case Animation.ANIMATIONTYPE_VECTOR3:
  15281. offsetValue = BABYLON.Vector3.Zero();
  15282. break;
  15283. case Animation.ANIMATIONTYPE_VECTOR2:
  15284. offsetValue = BABYLON.Vector2.Zero();
  15285. break;
  15286. case Animation.ANIMATIONTYPE_COLOR3:
  15287. offsetValue = BABYLON.Color3.Black();
  15288. }
  15289. }
  15290. // Compute value
  15291. var repeatCount = (ratio / range) >> 0;
  15292. var currentFrame = returnValue ? from + ratio % range : to;
  15293. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15294. // Set value
  15295. if (this.targetPropertyPath.length > 1) {
  15296. var property = this._target[this.targetPropertyPath[0]];
  15297. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15298. property = property[this.targetPropertyPath[index]];
  15299. }
  15300. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15301. }
  15302. else {
  15303. this._target[this.targetPropertyPath[0]] = currentValue;
  15304. }
  15305. if (this._target.markAsDirty) {
  15306. this._target.markAsDirty(this.targetProperty);
  15307. }
  15308. if (!returnValue) {
  15309. this._stopped = true;
  15310. }
  15311. return returnValue;
  15312. };
  15313. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15314. get: function () {
  15315. return Animation._ANIMATIONTYPE_FLOAT;
  15316. },
  15317. enumerable: true,
  15318. configurable: true
  15319. });
  15320. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15321. get: function () {
  15322. return Animation._ANIMATIONTYPE_VECTOR3;
  15323. },
  15324. enumerable: true,
  15325. configurable: true
  15326. });
  15327. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15328. get: function () {
  15329. return Animation._ANIMATIONTYPE_VECTOR2;
  15330. },
  15331. enumerable: true,
  15332. configurable: true
  15333. });
  15334. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15335. get: function () {
  15336. return Animation._ANIMATIONTYPE_QUATERNION;
  15337. },
  15338. enumerable: true,
  15339. configurable: true
  15340. });
  15341. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15342. get: function () {
  15343. return Animation._ANIMATIONTYPE_MATRIX;
  15344. },
  15345. enumerable: true,
  15346. configurable: true
  15347. });
  15348. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15349. get: function () {
  15350. return Animation._ANIMATIONTYPE_COLOR3;
  15351. },
  15352. enumerable: true,
  15353. configurable: true
  15354. });
  15355. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15356. get: function () {
  15357. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15358. },
  15359. enumerable: true,
  15360. configurable: true
  15361. });
  15362. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15363. get: function () {
  15364. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15365. },
  15366. enumerable: true,
  15367. configurable: true
  15368. });
  15369. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15370. get: function () {
  15371. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15372. },
  15373. enumerable: true,
  15374. configurable: true
  15375. });
  15376. // Statics
  15377. Animation._ANIMATIONTYPE_FLOAT = 0;
  15378. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15379. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15380. Animation._ANIMATIONTYPE_MATRIX = 3;
  15381. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15382. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15383. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15384. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15385. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15386. return Animation;
  15387. })();
  15388. BABYLON.Animation = Animation;
  15389. })(BABYLON || (BABYLON = {}));
  15390. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15391. (function (BABYLON) {
  15392. var Animatable = (function () {
  15393. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15394. if (fromFrame === void 0) { fromFrame = 0; }
  15395. if (toFrame === void 0) { toFrame = 100; }
  15396. if (loopAnimation === void 0) { loopAnimation = false; }
  15397. if (speedRatio === void 0) { speedRatio = 1.0; }
  15398. this.target = target;
  15399. this.fromFrame = fromFrame;
  15400. this.toFrame = toFrame;
  15401. this.loopAnimation = loopAnimation;
  15402. this.speedRatio = speedRatio;
  15403. this.onAnimationEnd = onAnimationEnd;
  15404. this._animations = new Array();
  15405. this._paused = false;
  15406. this.animationStarted = false;
  15407. if (animations) {
  15408. this.appendAnimations(target, animations);
  15409. }
  15410. this._scene = scene;
  15411. scene._activeAnimatables.push(this);
  15412. }
  15413. // Methods
  15414. Animatable.prototype.appendAnimations = function (target, animations) {
  15415. for (var index = 0; index < animations.length; index++) {
  15416. var animation = animations[index];
  15417. animation._target = target;
  15418. this._animations.push(animation);
  15419. }
  15420. };
  15421. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15422. var animations = this._animations;
  15423. for (var index = 0; index < animations.length; index++) {
  15424. if (animations[index].targetProperty === property) {
  15425. return animations[index];
  15426. }
  15427. }
  15428. return null;
  15429. };
  15430. Animatable.prototype.pause = function () {
  15431. if (this._paused) {
  15432. return;
  15433. }
  15434. this._paused = true;
  15435. };
  15436. Animatable.prototype.restart = function () {
  15437. this._paused = false;
  15438. };
  15439. Animatable.prototype.stop = function () {
  15440. var index = this._scene._activeAnimatables.indexOf(this);
  15441. if (index > -1) {
  15442. this._scene._activeAnimatables.splice(index, 1);
  15443. }
  15444. if (this.onAnimationEnd) {
  15445. this.onAnimationEnd();
  15446. }
  15447. };
  15448. Animatable.prototype._animate = function (delay) {
  15449. if (this._paused) {
  15450. if (!this._pausedDelay) {
  15451. this._pausedDelay = delay;
  15452. }
  15453. return true;
  15454. }
  15455. if (!this._localDelayOffset) {
  15456. this._localDelayOffset = delay;
  15457. }
  15458. else if (this._pausedDelay) {
  15459. this._localDelayOffset += delay - this._pausedDelay;
  15460. this._pausedDelay = null;
  15461. }
  15462. // Animating
  15463. var running = false;
  15464. var animations = this._animations;
  15465. for (var index = 0; index < animations.length; index++) {
  15466. var animation = animations[index];
  15467. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15468. running = running || isRunning;
  15469. }
  15470. if (!running && this.onAnimationEnd) {
  15471. this.onAnimationEnd();
  15472. }
  15473. return running;
  15474. };
  15475. return Animatable;
  15476. })();
  15477. BABYLON.Animatable = Animatable;
  15478. })(BABYLON || (BABYLON = {}));
  15479. //# sourceMappingURL=babylon.animatable.js.map
  15480. var BABYLON;
  15481. (function (BABYLON) {
  15482. var EasingFunction = (function () {
  15483. function EasingFunction() {
  15484. // Properties
  15485. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15486. }
  15487. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15488. get: function () {
  15489. return EasingFunction._EASINGMODE_EASEIN;
  15490. },
  15491. enumerable: true,
  15492. configurable: true
  15493. });
  15494. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15495. get: function () {
  15496. return EasingFunction._EASINGMODE_EASEOUT;
  15497. },
  15498. enumerable: true,
  15499. configurable: true
  15500. });
  15501. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15502. get: function () {
  15503. return EasingFunction._EASINGMODE_EASEINOUT;
  15504. },
  15505. enumerable: true,
  15506. configurable: true
  15507. });
  15508. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15509. var n = Math.min(Math.max(easingMode, 0), 2);
  15510. this._easingMode = n;
  15511. };
  15512. EasingFunction.prototype.getEasingMode = function () {
  15513. return this._easingMode;
  15514. };
  15515. EasingFunction.prototype.easeInCore = function (gradient) {
  15516. throw new Error('You must implement this method');
  15517. };
  15518. EasingFunction.prototype.ease = function (gradient) {
  15519. switch (this._easingMode) {
  15520. case EasingFunction.EASINGMODE_EASEIN:
  15521. return this.easeInCore(gradient);
  15522. case EasingFunction.EASINGMODE_EASEOUT:
  15523. return (1 - this.easeInCore(1 - gradient));
  15524. }
  15525. if (gradient >= 0.5) {
  15526. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15527. }
  15528. return (this.easeInCore(gradient * 2) * 0.5);
  15529. };
  15530. //Statics
  15531. EasingFunction._EASINGMODE_EASEIN = 0;
  15532. EasingFunction._EASINGMODE_EASEOUT = 1;
  15533. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15534. return EasingFunction;
  15535. })();
  15536. BABYLON.EasingFunction = EasingFunction;
  15537. var CircleEase = (function (_super) {
  15538. __extends(CircleEase, _super);
  15539. function CircleEase() {
  15540. _super.apply(this, arguments);
  15541. }
  15542. CircleEase.prototype.easeInCore = function (gradient) {
  15543. gradient = Math.max(0, Math.min(1, gradient));
  15544. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15545. };
  15546. return CircleEase;
  15547. })(EasingFunction);
  15548. BABYLON.CircleEase = CircleEase;
  15549. var BackEase = (function (_super) {
  15550. __extends(BackEase, _super);
  15551. function BackEase(amplitude) {
  15552. if (amplitude === void 0) { amplitude = 1; }
  15553. _super.call(this);
  15554. this.amplitude = amplitude;
  15555. }
  15556. BackEase.prototype.easeInCore = function (gradient) {
  15557. var num = Math.max(0, this.amplitude);
  15558. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15559. };
  15560. return BackEase;
  15561. })(EasingFunction);
  15562. BABYLON.BackEase = BackEase;
  15563. var BounceEase = (function (_super) {
  15564. __extends(BounceEase, _super);
  15565. function BounceEase(bounces, bounciness) {
  15566. if (bounces === void 0) { bounces = 3; }
  15567. if (bounciness === void 0) { bounciness = 2; }
  15568. _super.call(this);
  15569. this.bounces = bounces;
  15570. this.bounciness = bounciness;
  15571. }
  15572. BounceEase.prototype.easeInCore = function (gradient) {
  15573. var y = Math.max(0.0, this.bounces);
  15574. var bounciness = this.bounciness;
  15575. if (bounciness <= 1.0) {
  15576. bounciness = 1.001;
  15577. }
  15578. var num9 = Math.pow(bounciness, y);
  15579. var num5 = 1.0 - bounciness;
  15580. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15581. var num15 = gradient * num4;
  15582. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15583. var num3 = Math.floor(num65);
  15584. var num13 = num3 + 1.0;
  15585. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15586. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15587. var num7 = (num8 + num12) * 0.5;
  15588. var num6 = gradient - num7;
  15589. var num2 = num7 - num8;
  15590. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15591. };
  15592. return BounceEase;
  15593. })(EasingFunction);
  15594. BABYLON.BounceEase = BounceEase;
  15595. var CubicEase = (function (_super) {
  15596. __extends(CubicEase, _super);
  15597. function CubicEase() {
  15598. _super.apply(this, arguments);
  15599. }
  15600. CubicEase.prototype.easeInCore = function (gradient) {
  15601. return (gradient * gradient * gradient);
  15602. };
  15603. return CubicEase;
  15604. })(EasingFunction);
  15605. BABYLON.CubicEase = CubicEase;
  15606. var ElasticEase = (function (_super) {
  15607. __extends(ElasticEase, _super);
  15608. function ElasticEase(oscillations, springiness) {
  15609. if (oscillations === void 0) { oscillations = 3; }
  15610. if (springiness === void 0) { springiness = 3; }
  15611. _super.call(this);
  15612. this.oscillations = oscillations;
  15613. this.springiness = springiness;
  15614. }
  15615. ElasticEase.prototype.easeInCore = function (gradient) {
  15616. var num2;
  15617. var num3 = Math.max(0.0, this.oscillations);
  15618. var num = Math.max(0.0, this.springiness);
  15619. if (num == 0) {
  15620. num2 = gradient;
  15621. }
  15622. else {
  15623. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15624. }
  15625. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15626. };
  15627. return ElasticEase;
  15628. })(EasingFunction);
  15629. BABYLON.ElasticEase = ElasticEase;
  15630. var ExponentialEase = (function (_super) {
  15631. __extends(ExponentialEase, _super);
  15632. function ExponentialEase(exponent) {
  15633. if (exponent === void 0) { exponent = 2; }
  15634. _super.call(this);
  15635. this.exponent = exponent;
  15636. }
  15637. ExponentialEase.prototype.easeInCore = function (gradient) {
  15638. if (this.exponent <= 0) {
  15639. return gradient;
  15640. }
  15641. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15642. };
  15643. return ExponentialEase;
  15644. })(EasingFunction);
  15645. BABYLON.ExponentialEase = ExponentialEase;
  15646. var PowerEase = (function (_super) {
  15647. __extends(PowerEase, _super);
  15648. function PowerEase(power) {
  15649. if (power === void 0) { power = 2; }
  15650. _super.call(this);
  15651. this.power = power;
  15652. }
  15653. PowerEase.prototype.easeInCore = function (gradient) {
  15654. var y = Math.max(0.0, this.power);
  15655. return Math.pow(gradient, y);
  15656. };
  15657. return PowerEase;
  15658. })(EasingFunction);
  15659. BABYLON.PowerEase = PowerEase;
  15660. var QuadraticEase = (function (_super) {
  15661. __extends(QuadraticEase, _super);
  15662. function QuadraticEase() {
  15663. _super.apply(this, arguments);
  15664. }
  15665. QuadraticEase.prototype.easeInCore = function (gradient) {
  15666. return (gradient * gradient);
  15667. };
  15668. return QuadraticEase;
  15669. })(EasingFunction);
  15670. BABYLON.QuadraticEase = QuadraticEase;
  15671. var QuarticEase = (function (_super) {
  15672. __extends(QuarticEase, _super);
  15673. function QuarticEase() {
  15674. _super.apply(this, arguments);
  15675. }
  15676. QuarticEase.prototype.easeInCore = function (gradient) {
  15677. return (gradient * gradient * gradient * gradient);
  15678. };
  15679. return QuarticEase;
  15680. })(EasingFunction);
  15681. BABYLON.QuarticEase = QuarticEase;
  15682. var QuinticEase = (function (_super) {
  15683. __extends(QuinticEase, _super);
  15684. function QuinticEase() {
  15685. _super.apply(this, arguments);
  15686. }
  15687. QuinticEase.prototype.easeInCore = function (gradient) {
  15688. return (gradient * gradient * gradient * gradient * gradient);
  15689. };
  15690. return QuinticEase;
  15691. })(EasingFunction);
  15692. BABYLON.QuinticEase = QuinticEase;
  15693. var SineEase = (function (_super) {
  15694. __extends(SineEase, _super);
  15695. function SineEase() {
  15696. _super.apply(this, arguments);
  15697. }
  15698. SineEase.prototype.easeInCore = function (gradient) {
  15699. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15700. };
  15701. return SineEase;
  15702. })(EasingFunction);
  15703. BABYLON.SineEase = SineEase;
  15704. var BezierCurveEase = (function (_super) {
  15705. __extends(BezierCurveEase, _super);
  15706. function BezierCurveEase(x1, y1, x2, y2) {
  15707. if (x1 === void 0) { x1 = 0; }
  15708. if (y1 === void 0) { y1 = 0; }
  15709. if (x2 === void 0) { x2 = 1; }
  15710. if (y2 === void 0) { y2 = 1; }
  15711. _super.call(this);
  15712. this.x1 = x1;
  15713. this.y1 = y1;
  15714. this.x2 = x2;
  15715. this.y2 = y2;
  15716. }
  15717. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15718. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15719. };
  15720. return BezierCurveEase;
  15721. })(EasingFunction);
  15722. BABYLON.BezierCurveEase = BezierCurveEase;
  15723. })(BABYLON || (BABYLON = {}));
  15724. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15725. (function (BABYLON) {
  15726. var Octree = (function () {
  15727. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15728. if (maxDepth === void 0) { maxDepth = 2; }
  15729. this.maxDepth = maxDepth;
  15730. this.dynamicContent = new Array();
  15731. this._maxBlockCapacity = maxBlockCapacity || 64;
  15732. this._selectionContent = new BABYLON.SmartArray(1024);
  15733. this._creationFunc = creationFunc;
  15734. }
  15735. // Methods
  15736. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15737. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15738. };
  15739. Octree.prototype.addMesh = function (entry) {
  15740. for (var index = 0; index < this.blocks.length; index++) {
  15741. var block = this.blocks[index];
  15742. block.addEntry(entry);
  15743. }
  15744. };
  15745. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15746. this._selectionContent.reset();
  15747. for (var index = 0; index < this.blocks.length; index++) {
  15748. var block = this.blocks[index];
  15749. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15750. }
  15751. if (allowDuplicate) {
  15752. this._selectionContent.concat(this.dynamicContent);
  15753. }
  15754. else {
  15755. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15756. }
  15757. return this._selectionContent;
  15758. };
  15759. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15760. this._selectionContent.reset();
  15761. for (var index = 0; index < this.blocks.length; index++) {
  15762. var block = this.blocks[index];
  15763. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15764. }
  15765. if (allowDuplicate) {
  15766. this._selectionContent.concat(this.dynamicContent);
  15767. }
  15768. else {
  15769. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15770. }
  15771. return this._selectionContent;
  15772. };
  15773. Octree.prototype.intersectsRay = function (ray) {
  15774. this._selectionContent.reset();
  15775. for (var index = 0; index < this.blocks.length; index++) {
  15776. var block = this.blocks[index];
  15777. block.intersectsRay(ray, this._selectionContent);
  15778. }
  15779. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15780. return this._selectionContent;
  15781. };
  15782. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15783. target.blocks = new Array();
  15784. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15785. for (var x = 0; x < 2; x++) {
  15786. for (var y = 0; y < 2; y++) {
  15787. for (var z = 0; z < 2; z++) {
  15788. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15789. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15790. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15791. block.addEntries(entries);
  15792. target.blocks.push(block);
  15793. }
  15794. }
  15795. }
  15796. };
  15797. Octree.CreationFuncForMeshes = function (entry, block) {
  15798. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15799. block.entries.push(entry);
  15800. }
  15801. };
  15802. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15803. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15804. block.entries.push(entry);
  15805. }
  15806. };
  15807. return Octree;
  15808. })();
  15809. BABYLON.Octree = Octree;
  15810. })(BABYLON || (BABYLON = {}));
  15811. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  15812. (function (BABYLON) {
  15813. var OctreeBlock = (function () {
  15814. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15815. this.entries = new Array();
  15816. this._boundingVectors = new Array();
  15817. this._capacity = capacity;
  15818. this._depth = depth;
  15819. this._maxDepth = maxDepth;
  15820. this._creationFunc = creationFunc;
  15821. this._minPoint = minPoint;
  15822. this._maxPoint = maxPoint;
  15823. this._boundingVectors.push(minPoint.clone());
  15824. this._boundingVectors.push(maxPoint.clone());
  15825. this._boundingVectors.push(minPoint.clone());
  15826. this._boundingVectors[2].x = maxPoint.x;
  15827. this._boundingVectors.push(minPoint.clone());
  15828. this._boundingVectors[3].y = maxPoint.y;
  15829. this._boundingVectors.push(minPoint.clone());
  15830. this._boundingVectors[4].z = maxPoint.z;
  15831. this._boundingVectors.push(maxPoint.clone());
  15832. this._boundingVectors[5].z = minPoint.z;
  15833. this._boundingVectors.push(maxPoint.clone());
  15834. this._boundingVectors[6].x = minPoint.x;
  15835. this._boundingVectors.push(maxPoint.clone());
  15836. this._boundingVectors[7].y = minPoint.y;
  15837. }
  15838. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15839. // Property
  15840. get: function () {
  15841. return this._capacity;
  15842. },
  15843. enumerable: true,
  15844. configurable: true
  15845. });
  15846. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15847. get: function () {
  15848. return this._minPoint;
  15849. },
  15850. enumerable: true,
  15851. configurable: true
  15852. });
  15853. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15854. get: function () {
  15855. return this._maxPoint;
  15856. },
  15857. enumerable: true,
  15858. configurable: true
  15859. });
  15860. // Methods
  15861. OctreeBlock.prototype.addEntry = function (entry) {
  15862. if (this.blocks) {
  15863. for (var index = 0; index < this.blocks.length; index++) {
  15864. var block = this.blocks[index];
  15865. block.addEntry(entry);
  15866. }
  15867. return;
  15868. }
  15869. this._creationFunc(entry, this);
  15870. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15871. this.createInnerBlocks();
  15872. }
  15873. };
  15874. OctreeBlock.prototype.addEntries = function (entries) {
  15875. for (var index = 0; index < entries.length; index++) {
  15876. var mesh = entries[index];
  15877. this.addEntry(mesh);
  15878. }
  15879. };
  15880. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15881. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15882. if (this.blocks) {
  15883. for (var index = 0; index < this.blocks.length; index++) {
  15884. var block = this.blocks[index];
  15885. block.select(frustumPlanes, selection, allowDuplicate);
  15886. }
  15887. return;
  15888. }
  15889. if (allowDuplicate) {
  15890. selection.concat(this.entries);
  15891. }
  15892. else {
  15893. selection.concatWithNoDuplicate(this.entries);
  15894. }
  15895. }
  15896. };
  15897. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15898. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15899. if (this.blocks) {
  15900. for (var index = 0; index < this.blocks.length; index++) {
  15901. var block = this.blocks[index];
  15902. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15903. }
  15904. return;
  15905. }
  15906. if (allowDuplicate) {
  15907. selection.concat(this.entries);
  15908. }
  15909. else {
  15910. selection.concatWithNoDuplicate(this.entries);
  15911. }
  15912. }
  15913. };
  15914. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15915. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15916. if (this.blocks) {
  15917. for (var index = 0; index < this.blocks.length; index++) {
  15918. var block = this.blocks[index];
  15919. block.intersectsRay(ray, selection);
  15920. }
  15921. return;
  15922. }
  15923. selection.concatWithNoDuplicate(this.entries);
  15924. }
  15925. };
  15926. OctreeBlock.prototype.createInnerBlocks = function () {
  15927. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15928. };
  15929. return OctreeBlock;
  15930. })();
  15931. BABYLON.OctreeBlock = OctreeBlock;
  15932. })(BABYLON || (BABYLON = {}));
  15933. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  15934. (function (BABYLON) {
  15935. var Bone = (function () {
  15936. function Bone(name, skeleton, parentBone, matrix) {
  15937. this.name = name;
  15938. this.children = new Array();
  15939. this.animations = new Array();
  15940. this._worldTransform = new BABYLON.Matrix();
  15941. this._absoluteTransform = new BABYLON.Matrix();
  15942. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15943. this._skeleton = skeleton;
  15944. this._matrix = matrix;
  15945. this._baseMatrix = matrix;
  15946. skeleton.bones.push(this);
  15947. if (parentBone) {
  15948. this._parent = parentBone;
  15949. parentBone.children.push(this);
  15950. }
  15951. else {
  15952. this._parent = null;
  15953. }
  15954. this._updateDifferenceMatrix();
  15955. }
  15956. // Members
  15957. Bone.prototype.getParent = function () {
  15958. return this._parent;
  15959. };
  15960. Bone.prototype.getLocalMatrix = function () {
  15961. return this._matrix;
  15962. };
  15963. Bone.prototype.getBaseMatrix = function () {
  15964. return this._baseMatrix;
  15965. };
  15966. Bone.prototype.getWorldMatrix = function () {
  15967. return this._worldTransform;
  15968. };
  15969. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15970. return this._invertedAbsoluteTransform;
  15971. };
  15972. Bone.prototype.getAbsoluteMatrix = function () {
  15973. var matrix = this._matrix.clone();
  15974. var parent = this._parent;
  15975. while (parent) {
  15976. matrix = matrix.multiply(parent.getLocalMatrix());
  15977. parent = parent.getParent();
  15978. }
  15979. return matrix;
  15980. };
  15981. // Methods
  15982. Bone.prototype.updateMatrix = function (matrix) {
  15983. this._matrix = matrix;
  15984. this._skeleton._markAsDirty();
  15985. this._updateDifferenceMatrix();
  15986. };
  15987. Bone.prototype._updateDifferenceMatrix = function () {
  15988. if (this._parent) {
  15989. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15990. }
  15991. else {
  15992. this._absoluteTransform.copyFrom(this._matrix);
  15993. }
  15994. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15995. for (var index = 0; index < this.children.length; index++) {
  15996. this.children[index]._updateDifferenceMatrix();
  15997. }
  15998. };
  15999. Bone.prototype.markAsDirty = function () {
  16000. this._skeleton._markAsDirty();
  16001. };
  16002. return Bone;
  16003. })();
  16004. BABYLON.Bone = Bone;
  16005. })(BABYLON || (BABYLON = {}));
  16006. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16007. (function (BABYLON) {
  16008. var Skeleton = (function () {
  16009. function Skeleton(name, id, scene) {
  16010. this.name = name;
  16011. this.id = id;
  16012. this.bones = new Array();
  16013. this._isDirty = true;
  16014. this._identity = BABYLON.Matrix.Identity();
  16015. this.bones = [];
  16016. this._scene = scene;
  16017. scene.skeletons.push(this);
  16018. }
  16019. // Members
  16020. Skeleton.prototype.getTransformMatrices = function () {
  16021. return this._transformMatrices;
  16022. };
  16023. // Methods
  16024. Skeleton.prototype._markAsDirty = function () {
  16025. this._isDirty = true;
  16026. };
  16027. Skeleton.prototype.prepare = function () {
  16028. if (!this._isDirty) {
  16029. return;
  16030. }
  16031. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16032. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16033. }
  16034. for (var index = 0; index < this.bones.length; index++) {
  16035. var bone = this.bones[index];
  16036. var parentBone = bone.getParent();
  16037. if (parentBone) {
  16038. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16039. }
  16040. else {
  16041. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16042. }
  16043. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16044. }
  16045. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16046. this._isDirty = false;
  16047. };
  16048. Skeleton.prototype.getAnimatables = function () {
  16049. if (!this._animatables || this._animatables.length != this.bones.length) {
  16050. this._animatables = [];
  16051. for (var index = 0; index < this.bones.length; index++) {
  16052. this._animatables.push(this.bones[index]);
  16053. }
  16054. }
  16055. return this._animatables;
  16056. };
  16057. Skeleton.prototype.clone = function (name, id) {
  16058. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  16059. for (var index = 0; index < this.bones.length; index++) {
  16060. var source = this.bones[index];
  16061. var parentBone = null;
  16062. if (source.getParent()) {
  16063. var parentIndex = this.bones.indexOf(source.getParent());
  16064. parentBone = result.bones[parentIndex];
  16065. }
  16066. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16067. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16068. }
  16069. return result;
  16070. };
  16071. return Skeleton;
  16072. })();
  16073. BABYLON.Skeleton = Skeleton;
  16074. })(BABYLON || (BABYLON = {}));
  16075. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16076. (function (BABYLON) {
  16077. var PostProcess = (function () {
  16078. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  16079. this.name = name;
  16080. this.width = -1;
  16081. this.height = -1;
  16082. this._reusable = false;
  16083. this._textures = new BABYLON.SmartArray(2);
  16084. this._currentRenderTextureInd = 0;
  16085. if (camera != null) {
  16086. this._camera = camera;
  16087. this._scene = camera.getScene();
  16088. camera.attachPostProcess(this);
  16089. this._engine = this._scene.getEngine();
  16090. }
  16091. else {
  16092. this._engine = engine;
  16093. }
  16094. this._renderRatio = ratio;
  16095. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16096. this._reusable = reusable || false;
  16097. samplers = samplers || [];
  16098. samplers.push("textureSampler");
  16099. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  16100. }
  16101. PostProcess.prototype.isReusable = function () {
  16102. return this._reusable;
  16103. };
  16104. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16105. camera = camera || this._camera;
  16106. var scene = camera.getScene();
  16107. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16108. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16109. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16110. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16111. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16112. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16113. if (this._textures.length > 0) {
  16114. for (var i = 0; i < this._textures.length; i++) {
  16115. this._engine._releaseTexture(this._textures.data[i]);
  16116. }
  16117. this._textures.reset();
  16118. }
  16119. this.width = desiredWidth;
  16120. this.height = desiredHeight;
  16121. 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 }));
  16122. if (this._reusable) {
  16123. 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 }));
  16124. }
  16125. if (this.onSizeChanged) {
  16126. this.onSizeChanged();
  16127. }
  16128. }
  16129. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16130. if (this.onActivate) {
  16131. this.onActivate(camera);
  16132. }
  16133. // Clear
  16134. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16135. if (this._reusable) {
  16136. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16137. }
  16138. };
  16139. PostProcess.prototype.apply = function () {
  16140. // Check
  16141. if (!this._effect.isReady())
  16142. return null;
  16143. // States
  16144. this._engine.enableEffect(this._effect);
  16145. this._engine.setState(false);
  16146. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16147. this._engine.setDepthBuffer(false);
  16148. this._engine.setDepthWrite(false);
  16149. // Texture
  16150. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16151. // Parameters
  16152. if (this.onApply) {
  16153. this.onApply(this._effect);
  16154. }
  16155. return this._effect;
  16156. };
  16157. PostProcess.prototype.dispose = function (camera) {
  16158. camera = camera || this._camera;
  16159. if (this._textures.length > 0) {
  16160. for (var i = 0; i < this._textures.length; i++) {
  16161. this._engine._releaseTexture(this._textures.data[i]);
  16162. }
  16163. this._textures.reset();
  16164. }
  16165. camera.detachPostProcess(this);
  16166. var index = camera._postProcesses.indexOf(this);
  16167. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16168. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16169. }
  16170. };
  16171. return PostProcess;
  16172. })();
  16173. BABYLON.PostProcess = PostProcess;
  16174. })(BABYLON || (BABYLON = {}));
  16175. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16176. (function (BABYLON) {
  16177. var PostProcessManager = (function () {
  16178. function PostProcessManager(scene) {
  16179. this._vertexDeclaration = [2];
  16180. this._vertexStrideSize = 2 * 4;
  16181. this._scene = scene;
  16182. // VBO
  16183. var vertices = [];
  16184. vertices.push(1, 1);
  16185. vertices.push(-1, 1);
  16186. vertices.push(-1, -1);
  16187. vertices.push(1, -1);
  16188. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16189. // Indices
  16190. var indices = [];
  16191. indices.push(0);
  16192. indices.push(1);
  16193. indices.push(2);
  16194. indices.push(0);
  16195. indices.push(2);
  16196. indices.push(3);
  16197. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16198. }
  16199. // Methods
  16200. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16201. var postProcesses = this._scene.activeCamera._postProcesses;
  16202. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16203. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16204. return false;
  16205. }
  16206. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16207. return true;
  16208. };
  16209. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16210. var postProcesses = this._scene.activeCamera._postProcesses;
  16211. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16212. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16213. return;
  16214. }
  16215. var engine = this._scene.getEngine();
  16216. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16217. if (index < postProcessesTakenIndices.length - 1) {
  16218. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16219. }
  16220. else {
  16221. if (targetTexture) {
  16222. engine.bindFramebuffer(targetTexture);
  16223. }
  16224. else {
  16225. engine.restoreDefaultFramebuffer();
  16226. }
  16227. }
  16228. if (doNotPresent) {
  16229. break;
  16230. }
  16231. var pp = postProcesses[postProcessesTakenIndices[index]];
  16232. var effect = pp.apply();
  16233. if (effect) {
  16234. if (pp.onBeforeRender) {
  16235. pp.onBeforeRender(effect);
  16236. }
  16237. // VBOs
  16238. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16239. // Draw order
  16240. engine.draw(true, 0, 6);
  16241. }
  16242. }
  16243. // Restore depth buffer
  16244. engine.setDepthBuffer(true);
  16245. engine.setDepthWrite(true);
  16246. };
  16247. PostProcessManager.prototype.dispose = function () {
  16248. if (this._vertexBuffer) {
  16249. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16250. this._vertexBuffer = null;
  16251. }
  16252. if (this._indexBuffer) {
  16253. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16254. this._indexBuffer = null;
  16255. }
  16256. };
  16257. return PostProcessManager;
  16258. })();
  16259. BABYLON.PostProcessManager = PostProcessManager;
  16260. })(BABYLON || (BABYLON = {}));
  16261. //# sourceMappingURL=babylon.postProcessManager.js.map
  16262. var BABYLON;
  16263. (function (BABYLON) {
  16264. var PassPostProcess = (function (_super) {
  16265. __extends(PassPostProcess, _super);
  16266. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16267. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16268. }
  16269. return PassPostProcess;
  16270. })(BABYLON.PostProcess);
  16271. BABYLON.PassPostProcess = PassPostProcess;
  16272. })(BABYLON || (BABYLON = {}));
  16273. //# sourceMappingURL=babylon.passPostProcess.js.map
  16274. var BABYLON;
  16275. (function (BABYLON) {
  16276. var BlurPostProcess = (function (_super) {
  16277. __extends(BlurPostProcess, _super);
  16278. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16279. var _this = this;
  16280. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16281. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16282. this.direction = direction;
  16283. this.blurWidth = blurWidth;
  16284. this.onApply = function (effect) {
  16285. effect.setFloat2("screenSize", _this.width, _this.height);
  16286. effect.setVector2("direction", _this.direction);
  16287. effect.setFloat("blurWidth", _this.blurWidth);
  16288. };
  16289. }
  16290. return BlurPostProcess;
  16291. })(BABYLON.PostProcess);
  16292. BABYLON.BlurPostProcess = BlurPostProcess;
  16293. })(BABYLON || (BABYLON = {}));
  16294. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16295. var BABYLON;
  16296. (function (BABYLON) {
  16297. var FilterPostProcess = (function (_super) {
  16298. __extends(FilterPostProcess, _super);
  16299. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16300. var _this = this;
  16301. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16302. this.kernelMatrix = kernelMatrix;
  16303. this.onApply = function (effect) {
  16304. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16305. };
  16306. }
  16307. return FilterPostProcess;
  16308. })(BABYLON.PostProcess);
  16309. BABYLON.FilterPostProcess = FilterPostProcess;
  16310. })(BABYLON || (BABYLON = {}));
  16311. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16312. var BABYLON;
  16313. (function (BABYLON) {
  16314. var RefractionPostProcess = (function (_super) {
  16315. __extends(RefractionPostProcess, _super);
  16316. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16317. var _this = this;
  16318. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16319. this.color = color;
  16320. this.depth = depth;
  16321. this.colorLevel = colorLevel;
  16322. this.onActivate = function (cam) {
  16323. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16324. };
  16325. this.onApply = function (effect) {
  16326. effect.setColor3("baseColor", _this.color);
  16327. effect.setFloat("depth", _this.depth);
  16328. effect.setFloat("colorLevel", _this.colorLevel);
  16329. effect.setTexture("refractionSampler", _this._refRexture);
  16330. };
  16331. }
  16332. // Methods
  16333. RefractionPostProcess.prototype.dispose = function (camera) {
  16334. if (this._refRexture) {
  16335. this._refRexture.dispose();
  16336. }
  16337. _super.prototype.dispose.call(this, camera);
  16338. };
  16339. return RefractionPostProcess;
  16340. })(BABYLON.PostProcess);
  16341. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16342. })(BABYLON || (BABYLON = {}));
  16343. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16344. var BABYLON;
  16345. (function (BABYLON) {
  16346. var BlackAndWhitePostProcess = (function (_super) {
  16347. __extends(BlackAndWhitePostProcess, _super);
  16348. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16349. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16350. }
  16351. return BlackAndWhitePostProcess;
  16352. })(BABYLON.PostProcess);
  16353. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16354. })(BABYLON || (BABYLON = {}));
  16355. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16356. var BABYLON;
  16357. (function (BABYLON) {
  16358. var ConvolutionPostProcess = (function (_super) {
  16359. __extends(ConvolutionPostProcess, _super);
  16360. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16361. var _this = this;
  16362. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16363. this.kernel = kernel;
  16364. this.onApply = function (effect) {
  16365. effect.setFloat2("screenSize", _this.width, _this.height);
  16366. effect.setArray("kernel", _this.kernel);
  16367. };
  16368. }
  16369. // Statics
  16370. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16371. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16372. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16373. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16374. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16375. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16376. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16377. return ConvolutionPostProcess;
  16378. })(BABYLON.PostProcess);
  16379. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16380. })(BABYLON || (BABYLON = {}));
  16381. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16382. var BABYLON;
  16383. (function (BABYLON) {
  16384. var FxaaPostProcess = (function (_super) {
  16385. __extends(FxaaPostProcess, _super);
  16386. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16387. var _this = this;
  16388. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16389. this.onSizeChanged = function () {
  16390. _this.texelWidth = 1.0 / _this.width;
  16391. _this.texelHeight = 1.0 / _this.height;
  16392. };
  16393. this.onApply = function (effect) {
  16394. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16395. };
  16396. }
  16397. return FxaaPostProcess;
  16398. })(BABYLON.PostProcess);
  16399. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16400. })(BABYLON || (BABYLON = {}));
  16401. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16402. (function (BABYLON) {
  16403. var LensFlare = (function () {
  16404. function LensFlare(size, position, color, imgUrl, system) {
  16405. this.size = size;
  16406. this.position = position;
  16407. this.dispose = function () {
  16408. if (this.texture) {
  16409. this.texture.dispose();
  16410. }
  16411. // Remove from scene
  16412. var index = this._system.lensFlares.indexOf(this);
  16413. this._system.lensFlares.splice(index, 1);
  16414. };
  16415. this.color = color || new BABYLON.Color3(1, 1, 1);
  16416. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16417. this._system = system;
  16418. system.lensFlares.push(this);
  16419. }
  16420. return LensFlare;
  16421. })();
  16422. BABYLON.LensFlare = LensFlare;
  16423. })(BABYLON || (BABYLON = {}));
  16424. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16425. (function (BABYLON) {
  16426. var LensFlareSystem = (function () {
  16427. function LensFlareSystem(name, emitter, scene) {
  16428. this.name = name;
  16429. this.lensFlares = new Array();
  16430. this.borderLimit = 300;
  16431. this._vertexDeclaration = [2];
  16432. this._vertexStrideSize = 2 * 4;
  16433. this._isEnabled = true;
  16434. this._scene = scene;
  16435. this._emitter = emitter;
  16436. scene.lensFlareSystems.push(this);
  16437. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16438. // VBO
  16439. var vertices = [];
  16440. vertices.push(1, 1);
  16441. vertices.push(-1, 1);
  16442. vertices.push(-1, -1);
  16443. vertices.push(1, -1);
  16444. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16445. // Indices
  16446. var indices = [];
  16447. indices.push(0);
  16448. indices.push(1);
  16449. indices.push(2);
  16450. indices.push(0);
  16451. indices.push(2);
  16452. indices.push(3);
  16453. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16454. // Effects
  16455. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16456. }
  16457. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16458. get: function () {
  16459. return this._isEnabled;
  16460. },
  16461. set: function (value) {
  16462. this._isEnabled = value;
  16463. },
  16464. enumerable: true,
  16465. configurable: true
  16466. });
  16467. LensFlareSystem.prototype.getScene = function () {
  16468. return this._scene;
  16469. };
  16470. LensFlareSystem.prototype.getEmitter = function () {
  16471. return this._emitter;
  16472. };
  16473. LensFlareSystem.prototype.getEmitterPosition = function () {
  16474. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16475. };
  16476. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16477. var position = this.getEmitterPosition();
  16478. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16479. this._positionX = position.x;
  16480. this._positionY = position.y;
  16481. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16482. if (position.z > 0) {
  16483. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16484. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16485. return true;
  16486. }
  16487. }
  16488. return false;
  16489. };
  16490. LensFlareSystem.prototype._isVisible = function () {
  16491. if (!this._isEnabled) {
  16492. return false;
  16493. }
  16494. var emitterPosition = this.getEmitterPosition();
  16495. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16496. var distance = direction.length();
  16497. direction.normalize();
  16498. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16499. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16500. return !pickInfo.hit || pickInfo.distance > distance;
  16501. };
  16502. LensFlareSystem.prototype.render = function () {
  16503. if (!this._effect.isReady())
  16504. return false;
  16505. var engine = this._scene.getEngine();
  16506. var viewport = this._scene.activeCamera.viewport;
  16507. var globalViewport = viewport.toGlobal(engine);
  16508. // Position
  16509. if (!this.computeEffectivePosition(globalViewport)) {
  16510. return false;
  16511. }
  16512. // Visibility
  16513. if (!this._isVisible()) {
  16514. return false;
  16515. }
  16516. // Intensity
  16517. var awayX;
  16518. var awayY;
  16519. if (this._positionX < this.borderLimit + globalViewport.x) {
  16520. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16521. }
  16522. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16523. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16524. }
  16525. else {
  16526. awayX = 0;
  16527. }
  16528. if (this._positionY < this.borderLimit + globalViewport.y) {
  16529. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16530. }
  16531. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16532. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16533. }
  16534. else {
  16535. awayY = 0;
  16536. }
  16537. var away = (awayX > awayY) ? awayX : awayY;
  16538. if (away > this.borderLimit) {
  16539. away = this.borderLimit;
  16540. }
  16541. var intensity = 1.0 - (away / this.borderLimit);
  16542. if (intensity < 0) {
  16543. return false;
  16544. }
  16545. if (intensity > 1.0) {
  16546. intensity = 1.0;
  16547. }
  16548. // Position
  16549. var centerX = globalViewport.x + globalViewport.width / 2;
  16550. var centerY = globalViewport.y + globalViewport.height / 2;
  16551. var distX = centerX - this._positionX;
  16552. var distY = centerY - this._positionY;
  16553. // Effects
  16554. engine.enableEffect(this._effect);
  16555. engine.setState(false);
  16556. engine.setDepthBuffer(false);
  16557. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16558. // VBOs
  16559. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16560. for (var index = 0; index < this.lensFlares.length; index++) {
  16561. var flare = this.lensFlares[index];
  16562. var x = centerX - (distX * flare.position);
  16563. var y = centerY - (distY * flare.position);
  16564. var cw = flare.size;
  16565. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16566. var cx = 2 * (x / globalViewport.width) - 1.0;
  16567. var cy = 1.0 - 2 * (y / globalViewport.height);
  16568. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16569. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16570. // Texture
  16571. this._effect.setTexture("textureSampler", flare.texture);
  16572. // Color
  16573. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16574. // Draw order
  16575. engine.draw(true, 0, 6);
  16576. }
  16577. engine.setDepthBuffer(true);
  16578. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16579. return true;
  16580. };
  16581. LensFlareSystem.prototype.dispose = function () {
  16582. if (this._vertexBuffer) {
  16583. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16584. this._vertexBuffer = null;
  16585. }
  16586. if (this._indexBuffer) {
  16587. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16588. this._indexBuffer = null;
  16589. }
  16590. while (this.lensFlares.length) {
  16591. this.lensFlares[0].dispose();
  16592. }
  16593. // Remove from scene
  16594. var index = this._scene.lensFlareSystems.indexOf(this);
  16595. this._scene.lensFlareSystems.splice(index, 1);
  16596. };
  16597. return LensFlareSystem;
  16598. })();
  16599. BABYLON.LensFlareSystem = LensFlareSystem;
  16600. })(BABYLON || (BABYLON = {}));
  16601. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16602. (function (BABYLON) {
  16603. var IntersectionInfo = (function () {
  16604. function IntersectionInfo(bu, bv, distance) {
  16605. this.bu = bu;
  16606. this.bv = bv;
  16607. this.distance = distance;
  16608. this.faceId = 0;
  16609. }
  16610. return IntersectionInfo;
  16611. })();
  16612. BABYLON.IntersectionInfo = IntersectionInfo;
  16613. var PickingInfo = (function () {
  16614. function PickingInfo() {
  16615. this.hit = false;
  16616. this.distance = 0;
  16617. this.pickedPoint = null;
  16618. this.pickedMesh = null;
  16619. this.bu = 0;
  16620. this.bv = 0;
  16621. this.faceId = -1;
  16622. }
  16623. // Methods
  16624. PickingInfo.prototype.getNormal = function () {
  16625. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16626. return null;
  16627. }
  16628. var indices = this.pickedMesh.getIndices();
  16629. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16630. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16631. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16632. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16633. normal0 = normal0.scale(this.bu);
  16634. normal1 = normal1.scale(this.bv);
  16635. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16636. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16637. };
  16638. PickingInfo.prototype.getTextureCoordinates = function () {
  16639. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16640. return null;
  16641. }
  16642. var indices = this.pickedMesh.getIndices();
  16643. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16644. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16645. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16646. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16647. uv0 = uv0.scale(this.bu);
  16648. uv1 = uv1.scale(this.bv);
  16649. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16650. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16651. };
  16652. return PickingInfo;
  16653. })();
  16654. BABYLON.PickingInfo = PickingInfo;
  16655. })(BABYLON || (BABYLON = {}));
  16656. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16657. (function (BABYLON) {
  16658. var FilesInput = (function () {
  16659. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16660. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16661. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16662. this.engine = p_engine;
  16663. this.canvas = p_canvas;
  16664. this.currentScene = p_scene;
  16665. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16666. this.progressCallback = p_progressCallback;
  16667. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16668. this.textureLoadingCallback = p_textureLoadingCallback;
  16669. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16670. }
  16671. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16672. var _this = this;
  16673. if (p_elementToMonitor) {
  16674. this.elementToMonitor = p_elementToMonitor;
  16675. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16676. _this.drag(e);
  16677. }, false);
  16678. this.elementToMonitor.addEventListener("dragover", function (e) {
  16679. _this.drag(e);
  16680. }, false);
  16681. this.elementToMonitor.addEventListener("drop", function (e) {
  16682. _this.drop(e);
  16683. }, false);
  16684. }
  16685. };
  16686. FilesInput.prototype.renderFunction = function () {
  16687. if (this.additionnalRenderLoopLogicCallback) {
  16688. this.additionnalRenderLoopLogicCallback();
  16689. }
  16690. if (this.currentScene) {
  16691. if (this.textureLoadingCallback) {
  16692. var remaining = this.currentScene.getWaitingItemsCount();
  16693. if (remaining > 0) {
  16694. this.textureLoadingCallback(remaining);
  16695. }
  16696. }
  16697. this.currentScene.render();
  16698. }
  16699. };
  16700. FilesInput.prototype.drag = function (e) {
  16701. e.stopPropagation();
  16702. e.preventDefault();
  16703. };
  16704. FilesInput.prototype.drop = function (eventDrop) {
  16705. eventDrop.stopPropagation();
  16706. eventDrop.preventDefault();
  16707. this.loadFiles(eventDrop);
  16708. };
  16709. FilesInput.prototype.loadFiles = function (event) {
  16710. var _this = this;
  16711. var that = this;
  16712. if (this.startingProcessingFilesCallback)
  16713. this.startingProcessingFilesCallback();
  16714. var sceneFileToLoad;
  16715. var filesToLoad;
  16716. // Handling data transfer via drag'n'drop
  16717. if (event && event.dataTransfer && event.dataTransfer.files) {
  16718. filesToLoad = event.dataTransfer.files;
  16719. }
  16720. // Handling files from input files
  16721. if (event && event.target && event.target.files) {
  16722. filesToLoad = event.target.files;
  16723. }
  16724. if (filesToLoad && filesToLoad.length > 0) {
  16725. for (var i = 0; i < filesToLoad.length; i++) {
  16726. switch (filesToLoad[i].type) {
  16727. case "image/jpeg":
  16728. case "image/png":
  16729. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16730. break;
  16731. case "image/targa":
  16732. case "image/vnd.ms-dds":
  16733. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16734. break;
  16735. default:
  16736. 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) {
  16737. sceneFileToLoad = filesToLoad[i];
  16738. }
  16739. break;
  16740. }
  16741. }
  16742. // If a ".babylon" file has been provided
  16743. if (sceneFileToLoad) {
  16744. if (this.currentScene) {
  16745. this.engine.stopRenderLoop();
  16746. this.currentScene.dispose();
  16747. }
  16748. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16749. that.currentScene = newScene;
  16750. // Wait for textures and shaders to be ready
  16751. that.currentScene.executeWhenReady(function () {
  16752. // Attach camera to canvas inputs
  16753. if (that.currentScene.activeCamera) {
  16754. that.currentScene.activeCamera.attachControl(that.canvas);
  16755. }
  16756. if (that.sceneLoadedCallback) {
  16757. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16758. }
  16759. that.engine.runRenderLoop(function () {
  16760. that.renderFunction();
  16761. });
  16762. });
  16763. }, function (progress) {
  16764. if (_this.progressCallback) {
  16765. _this.progressCallback(progress);
  16766. }
  16767. });
  16768. }
  16769. else {
  16770. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16771. }
  16772. }
  16773. };
  16774. FilesInput.FilesTextures = new Array();
  16775. FilesInput.FilesToLoad = new Array();
  16776. return FilesInput;
  16777. })();
  16778. BABYLON.FilesInput = FilesInput;
  16779. })(BABYLON || (BABYLON = {}));
  16780. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  16781. (function (BABYLON) {
  16782. var OimoJSPlugin = (function () {
  16783. function OimoJSPlugin() {
  16784. this._registeredMeshes = [];
  16785. /**
  16786. * Update the body position according to the mesh position
  16787. * @param mesh
  16788. */
  16789. this.updateBodyPosition = function (mesh) {
  16790. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16791. var registeredMesh = this._registeredMeshes[index];
  16792. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16793. var body = registeredMesh.body.body;
  16794. mesh.computeWorldMatrix(true);
  16795. var center = mesh.getBoundingInfo().boundingBox.center;
  16796. body.setPosition(center.x, center.y, center.z);
  16797. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16798. return;
  16799. }
  16800. // Case where the parent has been updated
  16801. if (registeredMesh.mesh.parent === mesh) {
  16802. mesh.computeWorldMatrix(true);
  16803. registeredMesh.mesh.computeWorldMatrix(true);
  16804. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16805. var absoluteRotation = mesh.rotation;
  16806. body = registeredMesh.body.body;
  16807. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16808. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16809. return;
  16810. }
  16811. }
  16812. };
  16813. }
  16814. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16815. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16816. };
  16817. OimoJSPlugin.prototype.initialize = function (iterations) {
  16818. this._world = new OIMO.World();
  16819. this._world.clear();
  16820. };
  16821. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16822. this._world.gravity = gravity;
  16823. };
  16824. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16825. var body = null;
  16826. this.unregisterMesh(mesh);
  16827. mesh.computeWorldMatrix(true);
  16828. switch (impostor) {
  16829. case BABYLON.PhysicsEngine.SphereImpostor:
  16830. var initialRotation = null;
  16831. if (mesh.rotationQuaternion) {
  16832. initialRotation = mesh.rotationQuaternion.clone();
  16833. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16834. mesh.computeWorldMatrix(true);
  16835. }
  16836. var bbox = mesh.getBoundingInfo().boundingBox;
  16837. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16838. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16839. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16840. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16841. // The delta between the mesh position and the mesh bounding box center
  16842. var deltaPosition = mesh.position.subtract(bbox.center);
  16843. // Transform delta position with the rotation
  16844. if (initialRotation) {
  16845. var m = new BABYLON.Matrix();
  16846. initialRotation.toRotationMatrix(m);
  16847. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16848. }
  16849. body = new OIMO.Body({
  16850. type: 'sphere',
  16851. size: [size],
  16852. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16853. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16854. move: options.mass != 0,
  16855. config: [options.mass, options.friction, options.restitution],
  16856. world: this._world
  16857. });
  16858. // Restore rotation
  16859. if (initialRotation) {
  16860. body.setQuaternion(initialRotation);
  16861. }
  16862. this._registeredMeshes.push({
  16863. mesh: mesh,
  16864. body: body,
  16865. delta: deltaPosition
  16866. });
  16867. break;
  16868. case BABYLON.PhysicsEngine.PlaneImpostor:
  16869. case BABYLON.PhysicsEngine.BoxImpostor:
  16870. initialRotation = null;
  16871. if (mesh.rotationQuaternion) {
  16872. initialRotation = mesh.rotationQuaternion.clone();
  16873. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16874. mesh.computeWorldMatrix(true);
  16875. }
  16876. bbox = mesh.getBoundingInfo().boundingBox;
  16877. var min = bbox.minimumWorld;
  16878. var max = bbox.maximumWorld;
  16879. var box = max.subtract(min);
  16880. var sizeX = this._checkWithEpsilon(box.x);
  16881. var sizeY = this._checkWithEpsilon(box.y);
  16882. var sizeZ = this._checkWithEpsilon(box.z);
  16883. // The delta between the mesh position and the mesh boudning box center
  16884. deltaPosition = mesh.position.subtract(bbox.center);
  16885. // Transform delta position with the rotation
  16886. if (initialRotation) {
  16887. m = new BABYLON.Matrix();
  16888. initialRotation.toRotationMatrix(m);
  16889. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16890. }
  16891. body = new OIMO.Body({
  16892. type: 'box',
  16893. size: [sizeX, sizeY, sizeZ],
  16894. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16895. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16896. move: options.mass != 0,
  16897. config: [options.mass, options.friction, options.restitution],
  16898. world: this._world
  16899. });
  16900. if (initialRotation) {
  16901. body.setQuaternion(initialRotation);
  16902. }
  16903. this._registeredMeshes.push({
  16904. mesh: mesh,
  16905. body: body,
  16906. delta: deltaPosition
  16907. });
  16908. break;
  16909. }
  16910. return body;
  16911. };
  16912. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16913. var types = [], sizes = [], positions = [], rotations = [];
  16914. var initialMesh = parts[0].mesh;
  16915. for (var index = 0; index < parts.length; index++) {
  16916. var part = parts[index];
  16917. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16918. types.push(bodyParameters.type);
  16919. sizes.push.apply(sizes, bodyParameters.size);
  16920. positions.push.apply(positions, bodyParameters.pos);
  16921. rotations.push.apply(rotations, bodyParameters.rot);
  16922. }
  16923. var body = new OIMO.Body({
  16924. type: types,
  16925. size: sizes,
  16926. pos: positions,
  16927. rot: rotations,
  16928. move: options.mass != 0,
  16929. config: [options.mass, options.friction, options.restitution],
  16930. world: this._world
  16931. });
  16932. this._registeredMeshes.push({
  16933. mesh: initialMesh,
  16934. body: body
  16935. });
  16936. return body;
  16937. };
  16938. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16939. var bodyParameters = null;
  16940. var mesh = part.mesh;
  16941. // We need the bounding box/sphere info to compute the physics body
  16942. mesh.computeWorldMatrix();
  16943. switch (part.impostor) {
  16944. case BABYLON.PhysicsEngine.SphereImpostor:
  16945. var bbox = mesh.getBoundingInfo().boundingBox;
  16946. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16947. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16948. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16949. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16950. bodyParameters = {
  16951. type: 'sphere',
  16952. /* bug with oimo : sphere needs 3 sizes in this case */
  16953. size: [size, -1, -1],
  16954. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16955. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16956. };
  16957. break;
  16958. case BABYLON.PhysicsEngine.PlaneImpostor:
  16959. case BABYLON.PhysicsEngine.BoxImpostor:
  16960. bbox = mesh.getBoundingInfo().boundingBox;
  16961. var min = bbox.minimumWorld;
  16962. var max = bbox.maximumWorld;
  16963. var box = max.subtract(min);
  16964. var sizeX = this._checkWithEpsilon(box.x);
  16965. var sizeY = this._checkWithEpsilon(box.y);
  16966. var sizeZ = this._checkWithEpsilon(box.z);
  16967. var relativePosition = mesh.position;
  16968. bodyParameters = {
  16969. type: 'box',
  16970. size: [sizeX, sizeY, sizeZ],
  16971. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16972. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16973. };
  16974. break;
  16975. }
  16976. return bodyParameters;
  16977. };
  16978. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16979. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16980. var registeredMesh = this._registeredMeshes[index];
  16981. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16982. if (registeredMesh.body) {
  16983. this._world.removeRigidBody(registeredMesh.body.body);
  16984. this._unbindBody(registeredMesh.body);
  16985. }
  16986. this._registeredMeshes.splice(index, 1);
  16987. return;
  16988. }
  16989. }
  16990. };
  16991. OimoJSPlugin.prototype._unbindBody = function (body) {
  16992. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16993. var registeredMesh = this._registeredMeshes[index];
  16994. if (registeredMesh.body === body) {
  16995. registeredMesh.body = null;
  16996. }
  16997. }
  16998. };
  16999. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17000. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17001. var registeredMesh = this._registeredMeshes[index];
  17002. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17003. // Get object mass to have a behaviour similar to cannon.js
  17004. var mass = registeredMesh.body.body.massInfo.mass;
  17005. // The force is scaled with the mass of object
  17006. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17007. return;
  17008. }
  17009. }
  17010. };
  17011. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17012. var body1 = null, body2 = null;
  17013. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17014. var registeredMesh = this._registeredMeshes[index];
  17015. if (registeredMesh.mesh === mesh1) {
  17016. body1 = registeredMesh.body.body;
  17017. }
  17018. else if (registeredMesh.mesh === mesh2) {
  17019. body2 = registeredMesh.body.body;
  17020. }
  17021. }
  17022. if (!body1 || !body2) {
  17023. return false;
  17024. }
  17025. if (!options) {
  17026. options = {};
  17027. }
  17028. new OIMO.Link({
  17029. type: options.type,
  17030. body1: body1,
  17031. body2: body2,
  17032. min: options.min,
  17033. max: options.max,
  17034. axe1: options.axe1,
  17035. axe2: options.axe2,
  17036. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17037. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17038. collision: options.collision,
  17039. spring: options.spring,
  17040. world: this._world
  17041. });
  17042. return true;
  17043. };
  17044. OimoJSPlugin.prototype.dispose = function () {
  17045. this._world.clear();
  17046. while (this._registeredMeshes.length) {
  17047. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17048. }
  17049. };
  17050. OimoJSPlugin.prototype.isSupported = function () {
  17051. return OIMO !== undefined;
  17052. };
  17053. OimoJSPlugin.prototype._getLastShape = function (body) {
  17054. var lastShape = body.shapes;
  17055. while (lastShape.next) {
  17056. lastShape = lastShape.next;
  17057. }
  17058. return lastShape;
  17059. };
  17060. OimoJSPlugin.prototype.runOneStep = function (time) {
  17061. this._world.step();
  17062. // Update the position of all registered meshes
  17063. var i = this._registeredMeshes.length;
  17064. var m;
  17065. while (i--) {
  17066. var body = this._registeredMeshes[i].body.body;
  17067. var mesh = this._registeredMeshes[i].mesh;
  17068. var delta = this._registeredMeshes[i].delta;
  17069. if (!body.sleeping) {
  17070. if (body.shapes.next) {
  17071. var parentShape = this._getLastShape(body);
  17072. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17073. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17074. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17075. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17076. if (!mesh.rotationQuaternion) {
  17077. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17078. }
  17079. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17080. mesh.computeWorldMatrix();
  17081. }
  17082. else {
  17083. m = body.getMatrix();
  17084. mtx = BABYLON.Matrix.FromArray(m);
  17085. // Body position
  17086. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17087. if (!delta) {
  17088. mesh.position.x = bodyX;
  17089. mesh.position.y = bodyY;
  17090. mesh.position.z = bodyZ;
  17091. }
  17092. else {
  17093. mesh.position.x = bodyX + delta.x;
  17094. mesh.position.y = bodyY + delta.y;
  17095. mesh.position.z = bodyZ + delta.z;
  17096. }
  17097. if (!mesh.rotationQuaternion) {
  17098. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17099. }
  17100. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17101. mesh.computeWorldMatrix();
  17102. }
  17103. }
  17104. }
  17105. };
  17106. return OimoJSPlugin;
  17107. })();
  17108. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17109. })(BABYLON || (BABYLON = {}));
  17110. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17111. (function (BABYLON) {
  17112. var PhysicsEngine = (function () {
  17113. function PhysicsEngine(plugin) {
  17114. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17115. }
  17116. PhysicsEngine.prototype._initialize = function (gravity) {
  17117. this._currentPlugin.initialize();
  17118. this._setGravity(gravity);
  17119. };
  17120. PhysicsEngine.prototype._runOneStep = function (delta) {
  17121. if (delta > 0.1) {
  17122. delta = 0.1;
  17123. }
  17124. else if (delta <= 0) {
  17125. delta = 1.0 / 60.0;
  17126. }
  17127. this._currentPlugin.runOneStep(delta);
  17128. };
  17129. PhysicsEngine.prototype._setGravity = function (gravity) {
  17130. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17131. this._currentPlugin.setGravity(this.gravity);
  17132. };
  17133. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17134. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17135. };
  17136. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17137. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17138. };
  17139. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17140. this._currentPlugin.unregisterMesh(mesh);
  17141. };
  17142. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17143. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17144. };
  17145. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17146. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17147. };
  17148. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17149. this._currentPlugin.updateBodyPosition(mesh);
  17150. };
  17151. PhysicsEngine.prototype.dispose = function () {
  17152. this._currentPlugin.dispose();
  17153. };
  17154. PhysicsEngine.prototype.isSupported = function () {
  17155. return this._currentPlugin.isSupported();
  17156. };
  17157. // Statics
  17158. PhysicsEngine.NoImpostor = 0;
  17159. PhysicsEngine.SphereImpostor = 1;
  17160. PhysicsEngine.BoxImpostor = 2;
  17161. PhysicsEngine.PlaneImpostor = 3;
  17162. PhysicsEngine.MeshImpostor = 4;
  17163. PhysicsEngine.CapsuleImpostor = 5;
  17164. PhysicsEngine.ConeImpostor = 6;
  17165. PhysicsEngine.CylinderImpostor = 7;
  17166. PhysicsEngine.ConvexHullImpostor = 8;
  17167. PhysicsEngine.Epsilon = 0.001;
  17168. return PhysicsEngine;
  17169. })();
  17170. BABYLON.PhysicsEngine = PhysicsEngine;
  17171. })(BABYLON || (BABYLON = {}));
  17172. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17173. (function (BABYLON) {
  17174. var serializeLight = function (light) {
  17175. var serializationObject = {};
  17176. serializationObject.name = light.name;
  17177. serializationObject.id = light.id;
  17178. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17179. if (light instanceof BABYLON.PointLight) {
  17180. serializationObject.type = 0;
  17181. serializationObject.position = light.position.asArray();
  17182. }
  17183. else if (light instanceof BABYLON.DirectionalLight) {
  17184. serializationObject.type = 1;
  17185. var directionalLight = light;
  17186. serializationObject.position = directionalLight.position.asArray();
  17187. serializationObject.direction = directionalLight.direction.asArray();
  17188. }
  17189. else if (light instanceof BABYLON.SpotLight) {
  17190. serializationObject.type = 2;
  17191. var spotLight = light;
  17192. serializationObject.position = spotLight.position.asArray();
  17193. serializationObject.direction = spotLight.position.asArray();
  17194. serializationObject.angle = spotLight.angle;
  17195. serializationObject.exponent = spotLight.exponent;
  17196. }
  17197. else if (light instanceof BABYLON.HemisphericLight) {
  17198. serializationObject.type = 3;
  17199. var hemisphericLight = light;
  17200. serializationObject.direction = hemisphericLight.direction.asArray();
  17201. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17202. }
  17203. if (light.intensity) {
  17204. serializationObject.intensity = light.intensity;
  17205. }
  17206. serializationObject.range = light.range;
  17207. serializationObject.diffuse = light.diffuse.asArray();
  17208. serializationObject.specular = light.specular.asArray();
  17209. return serializationObject;
  17210. };
  17211. var serializeFresnelParameter = function (fresnelParameter) {
  17212. var serializationObject = {};
  17213. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17214. serializationObject.leftColor = fresnelParameter.leftColor;
  17215. serializationObject.rightColor = fresnelParameter.rightColor;
  17216. serializationObject.bias = fresnelParameter.bias;
  17217. serializationObject.power = fresnelParameter.power;
  17218. return serializationObject;
  17219. };
  17220. var serializeCamera = function (camera) {
  17221. var serializationObject = {};
  17222. serializationObject.name = camera.name;
  17223. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17224. serializationObject.id = camera.id;
  17225. serializationObject.position = camera.position.asArray();
  17226. // Parent
  17227. if (camera.parent) {
  17228. serializationObject.parentId = camera.parent.id;
  17229. }
  17230. // Target
  17231. serializationObject.rotation = camera.rotation.asArray();
  17232. // Locked target
  17233. if (camera.lockedTarget && camera.lockedTarget.id) {
  17234. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17235. }
  17236. serializationObject.fov = camera.fov;
  17237. serializationObject.minZ = camera.minZ;
  17238. serializationObject.maxZ = camera.maxZ;
  17239. serializationObject.speed = camera.speed;
  17240. serializationObject.inertia = camera.inertia;
  17241. serializationObject.checkCollisions = camera.checkCollisions;
  17242. serializationObject.applyGravity = camera.applyGravity;
  17243. if (camera.ellipsoid) {
  17244. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17245. }
  17246. // Animations
  17247. appendAnimations(camera, serializationObject);
  17248. // Layer mask
  17249. serializationObject.layerMask = camera.layerMask;
  17250. return serializationObject;
  17251. };
  17252. var appendAnimations = function (source, destination) {
  17253. if (source.animations) {
  17254. destination.animations = [];
  17255. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17256. var animation = source.animations[animationIndex];
  17257. destination.animations.push(serializeAnimation(animation));
  17258. }
  17259. }
  17260. };
  17261. var serializeAnimation = function (animation) {
  17262. var serializationObject = {};
  17263. serializationObject.name = animation.name;
  17264. serializationObject.property = animation.targetProperty;
  17265. serializationObject.framePerSecond = animation.framePerSecond;
  17266. serializationObject.dataType = animation.dataType;
  17267. serializationObject.loopBehavior = animation.loopMode;
  17268. var dataType = animation.dataType;
  17269. serializationObject.keys = [];
  17270. var keys = animation.getKeys();
  17271. for (var index = 0; index < keys.length; index++) {
  17272. var animationKey = keys[index];
  17273. var key = {};
  17274. key.frame = animationKey.frame;
  17275. switch (dataType) {
  17276. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17277. key.values = [animationKey.value];
  17278. break;
  17279. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17280. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17281. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17282. key.values = animationKey.value.asArray();
  17283. break;
  17284. }
  17285. serializationObject.keys.push(key);
  17286. }
  17287. return serializationObject;
  17288. };
  17289. var serializeMultiMaterial = function (material) {
  17290. var serializationObject = {};
  17291. serializationObject.name = material.name;
  17292. serializationObject.id = material.id;
  17293. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17294. serializationObject.materials = [];
  17295. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17296. var subMat = material.subMaterials[matIndex];
  17297. if (subMat) {
  17298. serializationObject.materials.push(subMat.id);
  17299. }
  17300. else {
  17301. serializationObject.materials.push(null);
  17302. }
  17303. }
  17304. return serializationObject;
  17305. };
  17306. var serializeMaterial = function (material) {
  17307. var serializationObject = {};
  17308. serializationObject.name = material.name;
  17309. serializationObject.ambient = material.ambientColor.asArray();
  17310. serializationObject.diffuse = material.diffuseColor.asArray();
  17311. serializationObject.specular = material.specularColor.asArray();
  17312. serializationObject.specularPower = material.specularPower;
  17313. serializationObject.emissive = material.emissiveColor.asArray();
  17314. serializationObject.alpha = material.alpha;
  17315. serializationObject.id = material.id;
  17316. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17317. serializationObject.backFaceCulling = material.backFaceCulling;
  17318. if (material.diffuseTexture) {
  17319. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17320. }
  17321. if (material.diffuseFresnelParameters) {
  17322. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17323. }
  17324. if (material.ambientTexture) {
  17325. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17326. }
  17327. if (material.opacityTexture) {
  17328. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17329. }
  17330. if (material.opacityFresnelParameters) {
  17331. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17332. }
  17333. if (material.reflectionTexture) {
  17334. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17335. }
  17336. if (material.reflectionFresnelParameters) {
  17337. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17338. }
  17339. if (material.emissiveTexture) {
  17340. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17341. }
  17342. if (material.emissiveFresnelParameters) {
  17343. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17344. }
  17345. if (material.specularTexture) {
  17346. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17347. }
  17348. if (material.bumpTexture) {
  17349. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17350. }
  17351. return serializationObject;
  17352. };
  17353. var serializeTexture = function (texture) {
  17354. var serializationObject = {};
  17355. if (!texture.name) {
  17356. return null;
  17357. }
  17358. if (texture instanceof BABYLON.CubeTexture) {
  17359. serializationObject.name = texture.name;
  17360. serializationObject.hasAlpha = texture.hasAlpha;
  17361. serializationObject.level = texture.level;
  17362. serializationObject.coordinatesMode = texture.coordinatesMode;
  17363. return serializationObject;
  17364. }
  17365. if (texture instanceof BABYLON.MirrorTexture) {
  17366. var mirrorTexture = texture;
  17367. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17368. serializationObject.renderList = [];
  17369. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17370. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17371. }
  17372. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17373. }
  17374. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17375. var renderTargetTexture = texture;
  17376. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17377. serializationObject.renderList = [];
  17378. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17379. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17380. }
  17381. }
  17382. var regularTexture = texture;
  17383. serializationObject.name = texture.name;
  17384. serializationObject.hasAlpha = texture.hasAlpha;
  17385. serializationObject.level = texture.level;
  17386. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17387. serializationObject.coordinatesMode = texture.coordinatesMode;
  17388. serializationObject.uOffset = regularTexture.uOffset;
  17389. serializationObject.vOffset = regularTexture.vOffset;
  17390. serializationObject.uScale = regularTexture.uScale;
  17391. serializationObject.vScale = regularTexture.vScale;
  17392. serializationObject.uAng = regularTexture.uAng;
  17393. serializationObject.vAng = regularTexture.vAng;
  17394. serializationObject.wAng = regularTexture.wAng;
  17395. serializationObject.wrapU = texture.wrapU;
  17396. serializationObject.wrapV = texture.wrapV;
  17397. // Animations
  17398. appendAnimations(texture, serializationObject);
  17399. return serializationObject;
  17400. };
  17401. var serializeSkeleton = function (skeleton) {
  17402. var serializationObject = {};
  17403. serializationObject.name = skeleton.name;
  17404. serializationObject.id = skeleton.id;
  17405. serializationObject.bones = [];
  17406. for (var index = 0; index < skeleton.bones.length; index++) {
  17407. var bone = skeleton.bones[index];
  17408. var serializedBone = {
  17409. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17410. name: bone.name,
  17411. matrix: bone.getLocalMatrix().toArray()
  17412. };
  17413. serializationObject.bones.push(serializedBone);
  17414. if (bone.animations && bone.animations.length > 0) {
  17415. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17416. }
  17417. }
  17418. return serializationObject;
  17419. };
  17420. var serializeParticleSystem = function (particleSystem) {
  17421. var serializationObject = {};
  17422. serializationObject.emitterId = particleSystem.emitter.id;
  17423. serializationObject.capacity = particleSystem.getCapacity();
  17424. if (particleSystem.particleTexture) {
  17425. serializationObject.textureName = particleSystem.particleTexture.name;
  17426. }
  17427. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17428. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17429. serializationObject.minSize = particleSystem.minSize;
  17430. serializationObject.maxSize = particleSystem.maxSize;
  17431. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17432. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17433. serializationObject.emitRate = particleSystem.emitRate;
  17434. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17435. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17436. serializationObject.gravity = particleSystem.gravity.asArray();
  17437. serializationObject.direction1 = particleSystem.direction1.asArray();
  17438. serializationObject.direction2 = particleSystem.direction2.asArray();
  17439. serializationObject.color1 = particleSystem.color1.asArray();
  17440. serializationObject.color2 = particleSystem.color2.asArray();
  17441. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17442. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17443. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17444. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17445. serializationObject.blendMode = particleSystem.blendMode;
  17446. return serializationObject;
  17447. };
  17448. var serializeLensFlareSystem = function (lensFlareSystem) {
  17449. var serializationObject = {};
  17450. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17451. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17452. serializationObject.flares = [];
  17453. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17454. var flare = lensFlareSystem.lensFlares[index];
  17455. serializationObject.flares.push({
  17456. size: flare.size,
  17457. position: flare.position,
  17458. color: flare.color.asArray(),
  17459. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17460. });
  17461. }
  17462. return serializationObject;
  17463. };
  17464. var serializeShadowGenerator = function (light) {
  17465. var serializationObject = {};
  17466. var shadowGenerator = light.getShadowGenerator();
  17467. serializationObject.lightId = light.id;
  17468. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17469. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17470. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17471. serializationObject.renderList = [];
  17472. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17473. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17474. serializationObject.renderList.push(mesh.id);
  17475. }
  17476. return serializationObject;
  17477. };
  17478. var serializedGeometries = [];
  17479. var serializeGeometry = function (geometry, serializationGeometries) {
  17480. if (serializedGeometries[geometry.id]) {
  17481. return;
  17482. }
  17483. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17484. serializationGeometries.boxes.push(serializeBox(geometry));
  17485. }
  17486. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17487. serializationGeometries.spheres.push(serializeSphere(geometry));
  17488. }
  17489. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17490. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17491. }
  17492. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17493. serializationGeometries.toruses.push(serializeTorus(geometry));
  17494. }
  17495. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17496. serializationGeometries.grounds.push(serializeGround(geometry));
  17497. }
  17498. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17499. serializationGeometries.planes.push(serializePlane(geometry));
  17500. }
  17501. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17502. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17503. }
  17504. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17505. throw new Error("Unknow primitive type");
  17506. }
  17507. else {
  17508. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17509. }
  17510. serializedGeometries[geometry.id] = true;
  17511. };
  17512. var serializeGeometryBase = function (geometry) {
  17513. var serializationObject = {};
  17514. serializationObject.id = geometry.id;
  17515. if (BABYLON.Tags.HasTags(geometry)) {
  17516. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17517. }
  17518. return serializationObject;
  17519. };
  17520. var serializeVertexData = function (vertexData) {
  17521. var serializationObject = serializeGeometryBase(vertexData);
  17522. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17523. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17524. }
  17525. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17526. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17527. }
  17528. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17529. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17530. }
  17531. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17532. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17533. }
  17534. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17535. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17536. }
  17537. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17538. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17539. serializationObject.matricesIndices._isExpanded = true;
  17540. }
  17541. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17542. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17543. }
  17544. serializationObject.indices = vertexData.getIndices();
  17545. return serializationObject;
  17546. };
  17547. var serializePrimitive = function (primitive) {
  17548. var serializationObject = serializeGeometryBase(primitive);
  17549. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17550. return serializationObject;
  17551. };
  17552. var serializeBox = function (box) {
  17553. var serializationObject = serializePrimitive(box);
  17554. serializationObject.size = box.size;
  17555. return serializationObject;
  17556. };
  17557. var serializeSphere = function (sphere) {
  17558. var serializationObject = serializePrimitive(sphere);
  17559. serializationObject.segments = sphere.segments;
  17560. serializationObject.diameter = sphere.diameter;
  17561. return serializationObject;
  17562. };
  17563. var serializeCylinder = function (cylinder) {
  17564. var serializationObject = serializePrimitive(cylinder);
  17565. serializationObject.height = cylinder.height;
  17566. serializationObject.diameterTop = cylinder.diameterTop;
  17567. serializationObject.diameterBottom = cylinder.diameterBottom;
  17568. serializationObject.tessellation = cylinder.tessellation;
  17569. return serializationObject;
  17570. };
  17571. var serializeTorus = function (torus) {
  17572. var serializationObject = serializePrimitive(torus);
  17573. serializationObject.diameter = torus.diameter;
  17574. serializationObject.thickness = torus.thickness;
  17575. serializationObject.tessellation = torus.tessellation;
  17576. return serializationObject;
  17577. };
  17578. var serializeGround = function (ground) {
  17579. var serializationObject = serializePrimitive(ground);
  17580. serializationObject.width = ground.width;
  17581. serializationObject.height = ground.height;
  17582. serializationObject.subdivisions = ground.subdivisions;
  17583. return serializationObject;
  17584. };
  17585. var serializePlane = function (plane) {
  17586. var serializationObject = serializePrimitive(plane);
  17587. serializationObject.size = plane.size;
  17588. return serializationObject;
  17589. };
  17590. var serializeTorusKnot = function (torusKnot) {
  17591. var serializationObject = serializePrimitive(torusKnot);
  17592. serializationObject.radius = torusKnot.radius;
  17593. serializationObject.tube = torusKnot.tube;
  17594. serializationObject.radialSegments = torusKnot.radialSegments;
  17595. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17596. serializationObject.p = torusKnot.p;
  17597. serializationObject.q = torusKnot.q;
  17598. return serializationObject;
  17599. };
  17600. var serializeMesh = function (mesh, serializationScene) {
  17601. var serializationObject = {};
  17602. serializationObject.name = mesh.name;
  17603. serializationObject.id = mesh.id;
  17604. if (BABYLON.Tags.HasTags(mesh)) {
  17605. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17606. }
  17607. serializationObject.position = mesh.position.asArray();
  17608. if (mesh.rotationQuaternion) {
  17609. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17610. }
  17611. else if (mesh.rotation) {
  17612. serializationObject.rotation = mesh.rotation.asArray();
  17613. }
  17614. serializationObject.scaling = mesh.scaling.asArray();
  17615. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17616. serializationObject.isEnabled = mesh.isEnabled();
  17617. serializationObject.isVisible = mesh.isVisible;
  17618. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17619. serializationObject.pickable = mesh.isPickable;
  17620. serializationObject.receiveShadows = mesh.receiveShadows;
  17621. serializationObject.billboardMode = mesh.billboardMode;
  17622. serializationObject.visibility = mesh.visibility;
  17623. serializationObject.checkCollisions = mesh.checkCollisions;
  17624. // Parent
  17625. if (mesh.parent) {
  17626. serializationObject.parentId = mesh.parent.id;
  17627. }
  17628. // Geometry
  17629. var geometry = mesh._geometry;
  17630. if (geometry) {
  17631. var geometryId = geometry.id;
  17632. serializationObject.geometryId = geometryId;
  17633. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17634. // 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
  17635. serializeGeometry(geometry, serializationScene.geometries);
  17636. }
  17637. // SubMeshes
  17638. serializationObject.subMeshes = [];
  17639. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17640. var subMesh = mesh.subMeshes[subIndex];
  17641. serializationObject.subMeshes.push({
  17642. materialIndex: subMesh.materialIndex,
  17643. verticesStart: subMesh.verticesStart,
  17644. verticesCount: subMesh.verticesCount,
  17645. indexStart: subMesh.indexStart,
  17646. indexCount: subMesh.indexCount
  17647. });
  17648. }
  17649. }
  17650. // Material
  17651. if (mesh.material) {
  17652. serializationObject.materialId = mesh.material.id;
  17653. }
  17654. else {
  17655. mesh.material = null;
  17656. }
  17657. // Skeleton
  17658. if (mesh.skeleton) {
  17659. serializationObject.skeletonId = mesh.skeleton.id;
  17660. }
  17661. // Physics
  17662. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17663. serializationObject.physicsMass = mesh.getPhysicsMass();
  17664. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17665. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17666. switch (mesh.getPhysicsImpostor()) {
  17667. case BABYLON.PhysicsEngine.BoxImpostor:
  17668. serializationObject.physicsImpostor = 1;
  17669. break;
  17670. case BABYLON.PhysicsEngine.SphereImpostor:
  17671. serializationObject.physicsImpostor = 2;
  17672. break;
  17673. }
  17674. }
  17675. // Instances
  17676. serializationObject.instances = [];
  17677. for (var index = 0; index < mesh.instances.length; index++) {
  17678. var instance = mesh.instances[index];
  17679. var serializationInstance = {
  17680. name: instance.name,
  17681. position: instance.position,
  17682. rotation: instance.rotation,
  17683. rotationQuaternion: instance.rotationQuaternion,
  17684. scaling: instance.scaling
  17685. };
  17686. serializationObject.instances.push(serializationInstance);
  17687. // Animations
  17688. appendAnimations(instance, serializationInstance);
  17689. }
  17690. // Animations
  17691. appendAnimations(mesh, serializationObject);
  17692. // Layer mask
  17693. serializationObject.layerMask = mesh.layerMask;
  17694. return serializationObject;
  17695. };
  17696. var SceneSerializer = (function () {
  17697. function SceneSerializer() {
  17698. }
  17699. SceneSerializer.Serialize = function (scene) {
  17700. var serializationObject = {};
  17701. // Scene
  17702. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17703. serializationObject.autoClear = scene.autoClear;
  17704. serializationObject.clearColor = scene.clearColor.asArray();
  17705. serializationObject.ambientColor = scene.ambientColor.asArray();
  17706. serializationObject.gravity = scene.gravity.asArray();
  17707. // Fog
  17708. if (scene.fogMode && scene.fogMode !== 0) {
  17709. serializationObject.fogMode = scene.fogMode;
  17710. serializationObject.fogColor = scene.fogColor.asArray();
  17711. serializationObject.fogStart = scene.fogStart;
  17712. serializationObject.fogEnd = scene.fogEnd;
  17713. serializationObject.fogDensity = scene.fogDensity;
  17714. }
  17715. // Lights
  17716. serializationObject.lights = [];
  17717. for (var index = 0; index < scene.lights.length; index++) {
  17718. var light = scene.lights[index];
  17719. serializationObject.lights.push(serializeLight(light));
  17720. }
  17721. // Cameras
  17722. serializationObject.cameras = [];
  17723. for (index = 0; index < scene.cameras.length; index++) {
  17724. var camera = scene.cameras[index];
  17725. if (camera instanceof BABYLON.FreeCamera) {
  17726. serializationObject.cameras.push(serializeCamera(camera));
  17727. }
  17728. }
  17729. if (scene.activeCamera) {
  17730. serializationObject.activeCameraID = scene.activeCamera.id;
  17731. }
  17732. // Materials
  17733. serializationObject.materials = [];
  17734. serializationObject.multiMaterials = [];
  17735. for (index = 0; index < scene.materials.length; index++) {
  17736. var material = scene.materials[index];
  17737. if (material instanceof BABYLON.StandardMaterial) {
  17738. serializationObject.materials.push(serializeMaterial(material));
  17739. }
  17740. else if (material instanceof BABYLON.MultiMaterial) {
  17741. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17742. }
  17743. }
  17744. // Skeletons
  17745. serializationObject.skeletons = [];
  17746. for (index = 0; index < scene.skeletons.length; index++) {
  17747. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17748. }
  17749. // Geometries
  17750. serializationObject.geometries = {};
  17751. serializationObject.geometries.boxes = [];
  17752. serializationObject.geometries.spheres = [];
  17753. serializationObject.geometries.cylinders = [];
  17754. serializationObject.geometries.toruses = [];
  17755. serializationObject.geometries.grounds = [];
  17756. serializationObject.geometries.planes = [];
  17757. serializationObject.geometries.torusKnots = [];
  17758. serializationObject.geometries.vertexData = [];
  17759. serializedGeometries = [];
  17760. var geometries = scene.getGeometries();
  17761. for (var index = 0; index < geometries.length; index++) {
  17762. var geometry = geometries[index];
  17763. if (geometry.isReady()) {
  17764. serializeGeometry(geometry, serializationObject.geometries);
  17765. }
  17766. }
  17767. // Meshes
  17768. serializationObject.meshes = [];
  17769. for (index = 0; index < scene.meshes.length; index++) {
  17770. var abstractMesh = scene.meshes[index];
  17771. if (abstractMesh instanceof BABYLON.Mesh) {
  17772. var mesh = abstractMesh;
  17773. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17774. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17775. }
  17776. }
  17777. }
  17778. // Particles Systems
  17779. serializationObject.particleSystems = [];
  17780. for (index = 0; index < scene.particleSystems.length; index++) {
  17781. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17782. }
  17783. // Lens flares
  17784. serializationObject.lensFlareSystems = [];
  17785. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17786. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17787. }
  17788. // Shadows
  17789. serializationObject.shadowGenerators = [];
  17790. for (index = 0; index < scene.lights.length; index++) {
  17791. light = scene.lights[index];
  17792. if (light.getShadowGenerator()) {
  17793. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17794. }
  17795. }
  17796. return serializationObject;
  17797. };
  17798. return SceneSerializer;
  17799. })();
  17800. BABYLON.SceneSerializer = SceneSerializer;
  17801. })(BABYLON || (BABYLON = {}));
  17802. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  17803. (function (BABYLON) {
  17804. var SceneLoader = (function () {
  17805. function SceneLoader() {
  17806. }
  17807. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17808. get: function () {
  17809. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17810. },
  17811. set: function (value) {
  17812. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17813. },
  17814. enumerable: true,
  17815. configurable: true
  17816. });
  17817. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17818. get: function () {
  17819. return SceneLoader._ShowLoadingScreen;
  17820. },
  17821. set: function (value) {
  17822. SceneLoader._ShowLoadingScreen = value;
  17823. },
  17824. enumerable: true,
  17825. configurable: true
  17826. });
  17827. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17828. var dotPosition = sceneFilename.lastIndexOf(".");
  17829. var queryStringPosition = sceneFilename.indexOf("?");
  17830. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17831. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17832. var plugin = this._registeredPlugins[index];
  17833. if (plugin.extensions.indexOf(extension) !== -1) {
  17834. return plugin;
  17835. }
  17836. }
  17837. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17838. };
  17839. // Public functions
  17840. SceneLoader.RegisterPlugin = function (plugin) {
  17841. plugin.extensions = plugin.extensions.toLowerCase();
  17842. SceneLoader._registeredPlugins.push(plugin);
  17843. };
  17844. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17845. var manifestChecked = function (success) {
  17846. scene.database = database;
  17847. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17848. var importMeshFromData = function (data) {
  17849. var meshes = [];
  17850. var particleSystems = [];
  17851. var skeletons = [];
  17852. try {
  17853. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17854. if (onerror) {
  17855. onerror(scene, 'unable to load the scene');
  17856. }
  17857. return;
  17858. }
  17859. }
  17860. catch (e) {
  17861. if (onerror) {
  17862. onerror(scene, e);
  17863. }
  17864. return;
  17865. }
  17866. if (onsuccess) {
  17867. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17868. onsuccess(meshes, particleSystems, skeletons);
  17869. }
  17870. };
  17871. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17872. // Direct load
  17873. importMeshFromData(sceneFilename.substr(5));
  17874. return;
  17875. }
  17876. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17877. importMeshFromData(data);
  17878. }, progressCallBack, database);
  17879. };
  17880. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17881. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17882. };
  17883. /**
  17884. * Load a scene
  17885. * @param rootUrl a string that defines the root url for scene and resources
  17886. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17887. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17888. */
  17889. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17890. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17891. };
  17892. /**
  17893. * Append a scene
  17894. * @param rootUrl a string that defines the root url for scene and resources
  17895. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17896. * @param scene is the instance of BABYLON.Scene to append to
  17897. */
  17898. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17899. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17900. var database;
  17901. if (SceneLoader.ShowLoadingScreen) {
  17902. scene.getEngine().displayLoadingUI();
  17903. }
  17904. var loadSceneFromData = function (data) {
  17905. scene.database = database;
  17906. if (!plugin.load(scene, data, rootUrl)) {
  17907. if (onerror) {
  17908. onerror(scene);
  17909. }
  17910. scene.getEngine().hideLoadingUI();
  17911. return;
  17912. }
  17913. if (onsuccess) {
  17914. onsuccess(scene);
  17915. }
  17916. if (SceneLoader.ShowLoadingScreen) {
  17917. scene.executeWhenReady(function () {
  17918. scene.getEngine().hideLoadingUI();
  17919. });
  17920. }
  17921. };
  17922. var manifestChecked = function (success) {
  17923. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17924. };
  17925. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17926. // Direct load
  17927. loadSceneFromData(sceneFilename.substr(5));
  17928. return;
  17929. }
  17930. if (rootUrl.indexOf("file:") === -1) {
  17931. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17932. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17933. }
  17934. else {
  17935. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17936. }
  17937. };
  17938. // Flags
  17939. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17940. SceneLoader._ShowLoadingScreen = true;
  17941. // Members
  17942. SceneLoader._registeredPlugins = new Array();
  17943. return SceneLoader;
  17944. })();
  17945. BABYLON.SceneLoader = SceneLoader;
  17946. ;
  17947. })(BABYLON || (BABYLON = {}));
  17948. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  17949. (function (BABYLON) {
  17950. var Internals;
  17951. (function (Internals) {
  17952. var checkColors4 = function (colors, count) {
  17953. // Check if color3 was used
  17954. if (colors.length === count * 3) {
  17955. var colors4 = [];
  17956. for (var index = 0; index < colors.length; index += 3) {
  17957. var newIndex = (index / 3) * 4;
  17958. colors4[newIndex] = colors[index];
  17959. colors4[newIndex + 1] = colors[index + 1];
  17960. colors4[newIndex + 2] = colors[index + 2];
  17961. colors4[newIndex + 3] = 1.0;
  17962. }
  17963. return colors4;
  17964. }
  17965. return colors;
  17966. };
  17967. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17968. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17969. texture.name = parsedTexture.name;
  17970. texture.hasAlpha = parsedTexture.hasAlpha;
  17971. texture.level = parsedTexture.level;
  17972. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17973. return texture;
  17974. };
  17975. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17976. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17977. return null;
  17978. }
  17979. if (parsedTexture.isCube) {
  17980. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17981. }
  17982. var texture;
  17983. if (parsedTexture.mirrorPlane) {
  17984. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17985. texture._waitingRenderList = parsedTexture.renderList;
  17986. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17987. }
  17988. else if (parsedTexture.isRenderTarget) {
  17989. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17990. texture._waitingRenderList = parsedTexture.renderList;
  17991. }
  17992. else {
  17993. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17994. }
  17995. texture.name = parsedTexture.name;
  17996. texture.hasAlpha = parsedTexture.hasAlpha;
  17997. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17998. texture.level = parsedTexture.level;
  17999. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18000. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18001. texture.uOffset = parsedTexture.uOffset;
  18002. texture.vOffset = parsedTexture.vOffset;
  18003. texture.uScale = parsedTexture.uScale;
  18004. texture.vScale = parsedTexture.vScale;
  18005. texture.uAng = parsedTexture.uAng;
  18006. texture.vAng = parsedTexture.vAng;
  18007. texture.wAng = parsedTexture.wAng;
  18008. texture.wrapU = parsedTexture.wrapU;
  18009. texture.wrapV = parsedTexture.wrapV;
  18010. // Animations
  18011. if (parsedTexture.animations) {
  18012. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18013. var parsedAnimation = parsedTexture.animations[animationIndex];
  18014. texture.animations.push(parseAnimation(parsedAnimation));
  18015. }
  18016. }
  18017. return texture;
  18018. };
  18019. var parseSkeleton = function (parsedSkeleton, scene) {
  18020. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18021. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18022. var parsedBone = parsedSkeleton.bones[index];
  18023. var parentBone = null;
  18024. if (parsedBone.parentBoneIndex > -1) {
  18025. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18026. }
  18027. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18028. if (parsedBone.animation) {
  18029. bone.animations.push(parseAnimation(parsedBone.animation));
  18030. }
  18031. }
  18032. return skeleton;
  18033. };
  18034. var parseFresnelParameters = function (parsedFresnelParameters) {
  18035. var fresnelParameters = new BABYLON.FresnelParameters();
  18036. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18037. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18038. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18039. fresnelParameters.bias = parsedFresnelParameters.bias;
  18040. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18041. return fresnelParameters;
  18042. };
  18043. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18044. var material;
  18045. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18046. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18047. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18048. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18049. material.specularPower = parsedMaterial.specularPower;
  18050. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18051. material.alpha = parsedMaterial.alpha;
  18052. material.id = parsedMaterial.id;
  18053. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18054. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18055. material.wireframe = parsedMaterial.wireframe;
  18056. if (parsedMaterial.diffuseTexture) {
  18057. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18058. }
  18059. if (parsedMaterial.diffuseFresnelParameters) {
  18060. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18061. }
  18062. if (parsedMaterial.ambientTexture) {
  18063. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18064. }
  18065. if (parsedMaterial.opacityTexture) {
  18066. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18067. }
  18068. if (parsedMaterial.opacityFresnelParameters) {
  18069. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18070. }
  18071. if (parsedMaterial.reflectionTexture) {
  18072. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18073. }
  18074. if (parsedMaterial.reflectionFresnelParameters) {
  18075. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18076. }
  18077. if (parsedMaterial.emissiveTexture) {
  18078. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18079. }
  18080. if (parsedMaterial.emissiveFresnelParameters) {
  18081. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18082. }
  18083. if (parsedMaterial.specularTexture) {
  18084. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18085. }
  18086. if (parsedMaterial.bumpTexture) {
  18087. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18088. }
  18089. return material;
  18090. };
  18091. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18092. for (var index = 0; index < parsedData.materials.length; index++) {
  18093. var parsedMaterial = parsedData.materials[index];
  18094. if (parsedMaterial.id === id) {
  18095. return parseMaterial(parsedMaterial, scene, rootUrl);
  18096. }
  18097. }
  18098. return null;
  18099. };
  18100. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18101. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18102. multiMaterial.id = parsedMultiMaterial.id;
  18103. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18104. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18105. var subMatId = parsedMultiMaterial.materials[matIndex];
  18106. if (subMatId) {
  18107. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18108. }
  18109. else {
  18110. multiMaterial.subMaterials.push(null);
  18111. }
  18112. }
  18113. return multiMaterial;
  18114. };
  18115. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18116. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18117. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18118. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18119. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18120. var parsedFlare = parsedLensFlareSystem.flares[index];
  18121. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18122. }
  18123. return lensFlareSystem;
  18124. };
  18125. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18126. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18127. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18128. if (parsedParticleSystem.textureName) {
  18129. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18130. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18131. }
  18132. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18133. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18134. particleSystem.minSize = parsedParticleSystem.minSize;
  18135. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18136. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18137. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18138. particleSystem.emitter = emitter;
  18139. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18140. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18141. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18142. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18143. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18144. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18145. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18146. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18147. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18148. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18149. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18150. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18151. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18152. particleSystem.start();
  18153. return particleSystem;
  18154. };
  18155. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18156. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18157. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18158. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18159. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18160. shadowGenerator.getShadowMap().renderList.push(mesh);
  18161. }
  18162. if (parsedShadowGenerator.usePoissonSampling) {
  18163. shadowGenerator.usePoissonSampling = true;
  18164. }
  18165. else {
  18166. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18167. }
  18168. return shadowGenerator;
  18169. };
  18170. var parseAnimation = function (parsedAnimation) {
  18171. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18172. var dataType = parsedAnimation.dataType;
  18173. var keys = [];
  18174. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18175. var key = parsedAnimation.keys[index];
  18176. var data;
  18177. switch (dataType) {
  18178. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18179. data = key.values[0];
  18180. break;
  18181. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18182. data = BABYLON.Quaternion.FromArray(key.values);
  18183. break;
  18184. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18185. data = BABYLON.Matrix.FromArray(key.values);
  18186. break;
  18187. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18188. default:
  18189. data = BABYLON.Vector3.FromArray(key.values);
  18190. break;
  18191. }
  18192. keys.push({
  18193. frame: key.frame,
  18194. value: data
  18195. });
  18196. }
  18197. animation.setKeys(keys);
  18198. return animation;
  18199. };
  18200. var parseLight = function (parsedLight, scene) {
  18201. var light;
  18202. switch (parsedLight.type) {
  18203. case 0:
  18204. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18205. break;
  18206. case 1:
  18207. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18208. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18209. break;
  18210. case 2:
  18211. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18212. break;
  18213. case 3:
  18214. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18215. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18216. break;
  18217. }
  18218. light.id = parsedLight.id;
  18219. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18220. if (parsedLight.intensity !== undefined) {
  18221. light.intensity = parsedLight.intensity;
  18222. }
  18223. if (parsedLight.range) {
  18224. light.range = parsedLight.range;
  18225. }
  18226. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18227. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18228. if (parsedLight.excludedMeshesIds) {
  18229. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18230. }
  18231. // Parent
  18232. if (parsedLight.parentId) {
  18233. light._waitingParentId = parsedLight.parentId;
  18234. }
  18235. if (parsedLight.includedOnlyMeshesIds) {
  18236. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18237. }
  18238. // Animations
  18239. if (parsedLight.animations) {
  18240. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18241. var parsedAnimation = parsedLight.animations[animationIndex];
  18242. light.animations.push(parseAnimation(parsedAnimation));
  18243. }
  18244. }
  18245. if (parsedLight.autoAnimate) {
  18246. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18247. }
  18248. };
  18249. var parseCamera = function (parsedCamera, scene) {
  18250. var camera;
  18251. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18252. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18253. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18254. var alpha = parsedCamera.alpha;
  18255. var beta = parsedCamera.beta;
  18256. var radius = parsedCamera.radius;
  18257. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18258. var eye_space = parsedCamera.eye_space;
  18259. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18260. }
  18261. else {
  18262. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18263. }
  18264. }
  18265. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18266. eye_space = parsedCamera.eye_space;
  18267. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18268. }
  18269. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18270. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18271. }
  18272. else if (parsedCamera.type === "FollowCamera") {
  18273. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18274. camera.heightOffset = parsedCamera.heightOffset;
  18275. camera.radius = parsedCamera.radius;
  18276. camera.rotationOffset = parsedCamera.rotationOffset;
  18277. if (lockedTargetMesh)
  18278. camera.target = lockedTargetMesh;
  18279. }
  18280. else if (parsedCamera.type === "GamepadCamera") {
  18281. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18282. }
  18283. else if (parsedCamera.type === "OculusCamera") {
  18284. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18285. }
  18286. else if (parsedCamera.type === "OculusGamepadCamera") {
  18287. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18288. }
  18289. else if (parsedCamera.type === "TouchCamera") {
  18290. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18291. }
  18292. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18293. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18294. }
  18295. else if (parsedCamera.type === "WebVRCamera") {
  18296. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18297. }
  18298. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18299. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18300. }
  18301. else {
  18302. // Free Camera is the default value
  18303. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18304. }
  18305. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18306. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18307. camera.lockedTarget = lockedTargetMesh;
  18308. }
  18309. camera.id = parsedCamera.id;
  18310. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18311. // Parent
  18312. if (parsedCamera.parentId) {
  18313. camera._waitingParentId = parsedCamera.parentId;
  18314. }
  18315. // Target
  18316. if (parsedCamera.target) {
  18317. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18318. }
  18319. else {
  18320. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18321. }
  18322. camera.fov = parsedCamera.fov;
  18323. camera.minZ = parsedCamera.minZ;
  18324. camera.maxZ = parsedCamera.maxZ;
  18325. camera.speed = parsedCamera.speed;
  18326. camera.inertia = parsedCamera.inertia;
  18327. camera.checkCollisions = parsedCamera.checkCollisions;
  18328. camera.applyGravity = parsedCamera.applyGravity;
  18329. if (parsedCamera.ellipsoid) {
  18330. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18331. }
  18332. // Animations
  18333. if (parsedCamera.animations) {
  18334. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18335. var parsedAnimation = parsedCamera.animations[animationIndex];
  18336. camera.animations.push(parseAnimation(parsedAnimation));
  18337. }
  18338. }
  18339. if (parsedCamera.autoAnimate) {
  18340. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18341. }
  18342. // Layer Mask
  18343. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18344. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18345. }
  18346. else {
  18347. camera.layerMask = 0xFFFFFFFF;
  18348. }
  18349. return camera;
  18350. };
  18351. var parseGeometry = function (parsedGeometry, scene) {
  18352. var id = parsedGeometry.id;
  18353. return scene.getGeometryByID(id);
  18354. };
  18355. var parseBox = function (parsedBox, scene) {
  18356. if (parseGeometry(parsedBox, scene)) {
  18357. return null; // null since geometry could be something else than a box...
  18358. }
  18359. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18360. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18361. scene.pushGeometry(box, true);
  18362. return box;
  18363. };
  18364. var parseSphere = function (parsedSphere, scene) {
  18365. if (parseGeometry(parsedSphere, scene)) {
  18366. return null; // null since geometry could be something else than a sphere...
  18367. }
  18368. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18369. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18370. scene.pushGeometry(sphere, true);
  18371. return sphere;
  18372. };
  18373. var parseCylinder = function (parsedCylinder, scene) {
  18374. if (parseGeometry(parsedCylinder, scene)) {
  18375. return null; // null since geometry could be something else than a cylinder...
  18376. }
  18377. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18378. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18379. scene.pushGeometry(cylinder, true);
  18380. return cylinder;
  18381. };
  18382. var parseTorus = function (parsedTorus, scene) {
  18383. if (parseGeometry(parsedTorus, scene)) {
  18384. return null; // null since geometry could be something else than a torus...
  18385. }
  18386. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18387. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18388. scene.pushGeometry(torus, true);
  18389. return torus;
  18390. };
  18391. var parseGround = function (parsedGround, scene) {
  18392. if (parseGeometry(parsedGround, scene)) {
  18393. return null; // null since geometry could be something else than a ground...
  18394. }
  18395. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18396. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18397. scene.pushGeometry(ground, true);
  18398. return ground;
  18399. };
  18400. var parsePlane = function (parsedPlane, scene) {
  18401. if (parseGeometry(parsedPlane, scene)) {
  18402. return null; // null since geometry could be something else than a plane...
  18403. }
  18404. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18405. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18406. scene.pushGeometry(plane, true);
  18407. return plane;
  18408. };
  18409. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18410. if (parseGeometry(parsedTorusKnot, scene)) {
  18411. return null; // null since geometry could be something else than a torusKnot...
  18412. }
  18413. 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);
  18414. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18415. scene.pushGeometry(torusKnot, true);
  18416. return torusKnot;
  18417. };
  18418. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18419. if (parseGeometry(parsedVertexData, scene)) {
  18420. return null; // null since geometry could be a primitive
  18421. }
  18422. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18423. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18424. if (parsedVertexData.delayLoadingFile) {
  18425. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18426. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18427. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18428. geometry._delayInfo = [];
  18429. if (parsedVertexData.hasUVs) {
  18430. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18431. }
  18432. if (parsedVertexData.hasUVs2) {
  18433. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18434. }
  18435. if (parsedVertexData.hasColors) {
  18436. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18437. }
  18438. if (parsedVertexData.hasMatricesIndices) {
  18439. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18440. }
  18441. if (parsedVertexData.hasMatricesWeights) {
  18442. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18443. }
  18444. geometry._delayLoadingFunction = importVertexData;
  18445. }
  18446. else {
  18447. importVertexData(parsedVertexData, geometry);
  18448. }
  18449. scene.pushGeometry(geometry, true);
  18450. return geometry;
  18451. };
  18452. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18453. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18454. mesh.id = parsedMesh.id;
  18455. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18456. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18457. if (parsedMesh.rotationQuaternion) {
  18458. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18459. }
  18460. else if (parsedMesh.rotation) {
  18461. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18462. }
  18463. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18464. if (parsedMesh.localMatrix) {
  18465. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18466. }
  18467. else if (parsedMesh.pivotMatrix) {
  18468. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18469. }
  18470. mesh.setEnabled(parsedMesh.isEnabled);
  18471. mesh.isVisible = parsedMesh.isVisible;
  18472. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18473. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18474. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18475. if (parsedMesh.applyFog !== undefined) {
  18476. mesh.applyFog = parsedMesh.applyFog;
  18477. }
  18478. if (parsedMesh.pickable !== undefined) {
  18479. mesh.isPickable = parsedMesh.pickable;
  18480. }
  18481. if (parsedMesh.alphaIndex !== undefined) {
  18482. mesh.alphaIndex = parsedMesh.alphaIndex;
  18483. }
  18484. mesh.receiveShadows = parsedMesh.receiveShadows;
  18485. mesh.billboardMode = parsedMesh.billboardMode;
  18486. if (parsedMesh.visibility !== undefined) {
  18487. mesh.visibility = parsedMesh.visibility;
  18488. }
  18489. mesh.checkCollisions = parsedMesh.checkCollisions;
  18490. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18491. // Parent
  18492. if (parsedMesh.parentId) {
  18493. mesh._waitingParentId = parsedMesh.parentId;
  18494. }
  18495. // Actions
  18496. if (parsedMesh.actions !== undefined) {
  18497. mesh._waitingActions = parsedMesh.actions;
  18498. }
  18499. // Geometry
  18500. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18501. if (parsedMesh.delayLoadingFile) {
  18502. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18503. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18504. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18505. if (parsedMesh._binaryInfo) {
  18506. mesh._binaryInfo = parsedMesh._binaryInfo;
  18507. }
  18508. mesh._delayInfo = [];
  18509. if (parsedMesh.hasUVs) {
  18510. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18511. }
  18512. if (parsedMesh.hasUVs2) {
  18513. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18514. }
  18515. if (parsedMesh.hasColors) {
  18516. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18517. }
  18518. if (parsedMesh.hasMatricesIndices) {
  18519. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18520. }
  18521. if (parsedMesh.hasMatricesWeights) {
  18522. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18523. }
  18524. mesh._delayLoadingFunction = importGeometry;
  18525. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18526. mesh._checkDelayState();
  18527. }
  18528. }
  18529. else {
  18530. importGeometry(parsedMesh, mesh);
  18531. }
  18532. // Material
  18533. if (parsedMesh.materialId) {
  18534. mesh.setMaterialByID(parsedMesh.materialId);
  18535. }
  18536. else {
  18537. mesh.material = null;
  18538. }
  18539. // Skeleton
  18540. if (parsedMesh.skeletonId > -1) {
  18541. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18542. }
  18543. // Physics
  18544. if (parsedMesh.physicsImpostor) {
  18545. if (!scene.isPhysicsEnabled()) {
  18546. scene.enablePhysics();
  18547. }
  18548. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18549. }
  18550. // Animations
  18551. if (parsedMesh.animations) {
  18552. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18553. var parsedAnimation = parsedMesh.animations[animationIndex];
  18554. mesh.animations.push(parseAnimation(parsedAnimation));
  18555. }
  18556. }
  18557. if (parsedMesh.autoAnimate) {
  18558. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18559. }
  18560. // Layer Mask
  18561. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18562. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18563. }
  18564. else {
  18565. mesh.layerMask = 0xFFFFFFFF;
  18566. }
  18567. // Instances
  18568. if (parsedMesh.instances) {
  18569. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18570. var parsedInstance = parsedMesh.instances[index];
  18571. var instance = mesh.createInstance(parsedInstance.name);
  18572. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18573. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18574. if (parsedInstance.rotationQuaternion) {
  18575. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18576. }
  18577. else if (parsedInstance.rotation) {
  18578. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18579. }
  18580. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18581. instance.checkCollisions = mesh.checkCollisions;
  18582. if (parsedMesh.animations) {
  18583. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18584. parsedAnimation = parsedMesh.animations[animationIndex];
  18585. instance.animations.push(parseAnimation(parsedAnimation));
  18586. }
  18587. }
  18588. }
  18589. }
  18590. return mesh;
  18591. };
  18592. var parseActions = function (parsedActions, object, scene) {
  18593. var actionManager = new BABYLON.ActionManager(scene);
  18594. if (object === null)
  18595. scene.actionManager = actionManager;
  18596. else
  18597. object.actionManager = actionManager;
  18598. // instanciate a new object
  18599. var instanciate = function (name, params) {
  18600. var newInstance = Object.create(BABYLON[name].prototype);
  18601. newInstance.constructor.apply(newInstance, params);
  18602. return newInstance;
  18603. };
  18604. var parseParameter = function (name, value, target, propertyPath) {
  18605. if (propertyPath === null) {
  18606. // String, boolean or float
  18607. var floatValue = parseFloat(value);
  18608. if (value === "true" || value === "false")
  18609. return value === "true";
  18610. else
  18611. return isNaN(floatValue) ? value : floatValue;
  18612. }
  18613. var effectiveTarget = propertyPath.split(".");
  18614. var values = value.split(",");
  18615. for (var i = 0; i < effectiveTarget.length; i++) {
  18616. target = target[effectiveTarget[i]];
  18617. }
  18618. // Return appropriate value with its type
  18619. if (target instanceof Boolean)
  18620. return values[0] === "true";
  18621. if (target instanceof String)
  18622. return values[0];
  18623. // Parameters with multiple values such as Vector3 etc.
  18624. var split = new Array();
  18625. for (var i = 0; i < values.length; i++)
  18626. split.push(parseFloat(values[i]));
  18627. if (target instanceof BABYLON.Vector3)
  18628. return BABYLON.Vector3.FromArray(split);
  18629. if (target instanceof BABYLON.Vector4)
  18630. return BABYLON.Vector4.FromArray(split);
  18631. if (target instanceof BABYLON.Color3)
  18632. return BABYLON.Color3.FromArray(split);
  18633. if (target instanceof BABYLON.Color4)
  18634. return BABYLON.Color4.FromArray(split);
  18635. return parseFloat(values[0]);
  18636. };
  18637. // traverse graph per trigger
  18638. var traverse = function (parsedAction, trigger, condition, action) {
  18639. var parameters = new Array();
  18640. var target = null;
  18641. var propertyPath = null;
  18642. // Parameters
  18643. if (parsedAction.type === 2)
  18644. parameters.push(actionManager);
  18645. else
  18646. parameters.push(trigger);
  18647. for (var i = 0; i < parsedAction.properties.length; i++) {
  18648. var value = parsedAction.properties[i].value;
  18649. var name = parsedAction.properties[i].name;
  18650. if (name === "target")
  18651. value = target = scene.getNodeByName(value);
  18652. else if (name === "parent")
  18653. value = scene.getNodeByName(value);
  18654. else if (name !== "propertyPath") {
  18655. if (parsedAction.type === 2 && name === "operator")
  18656. value = BABYLON.ValueCondition[value];
  18657. else
  18658. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  18659. }
  18660. else {
  18661. propertyPath = value;
  18662. }
  18663. parameters.push(value);
  18664. }
  18665. parameters.push(condition);
  18666. // If interpolate value action
  18667. if (parsedAction.name === "InterpolateValueAction") {
  18668. var param = parameters[parameters.length - 2];
  18669. parameters[parameters.length - 1] = param;
  18670. parameters[parameters.length - 2] = condition;
  18671. }
  18672. // Action or condition(s)
  18673. var newAction = instanciate(parsedAction.name, parameters);
  18674. if (newAction instanceof BABYLON.Condition) {
  18675. condition = newAction;
  18676. newAction = action;
  18677. }
  18678. else {
  18679. condition = null;
  18680. if (action)
  18681. action.then(newAction);
  18682. else
  18683. actionManager.registerAction(newAction);
  18684. }
  18685. for (var i = 0; i < parsedAction.children.length; i++)
  18686. traverse(parsedAction.children[i], trigger, condition, newAction);
  18687. };
  18688. for (var i = 0; i < parsedActions.children.length; i++) {
  18689. var triggerParams;
  18690. var trigger = parsedActions.children[i];
  18691. if (trigger.properties.length > 0) {
  18692. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18693. }
  18694. else
  18695. triggerParams = BABYLON.ActionManager[trigger.name];
  18696. for (var j = 0; j < trigger.children.length; j++)
  18697. traverse(trigger.children[j], triggerParams, null, null);
  18698. }
  18699. };
  18700. var parseSound = function (parsedSound, scene, rootUrl) {
  18701. var soundName = parsedSound.name;
  18702. var soundUrl = rootUrl + soundName;
  18703. var options = {
  18704. autoplay: parsedSound.autoplay,
  18705. loop: parsedSound.loop,
  18706. volume: parsedSound.volume,
  18707. spatialSound: parsedSound.spatialSound,
  18708. maxDistance: parsedSound.maxDistance,
  18709. rolloffFactor: parsedSound.rolloffFactor,
  18710. refDistance: parsedSound.refDistance,
  18711. distanceModel: parsedSound.distanceModel,
  18712. panningModel: parsedSound.panningModel
  18713. };
  18714. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  18715. scene._removePendingData(newSound);
  18716. }, options);
  18717. scene._addPendingData(newSound);
  18718. if (parsedSound.position) {
  18719. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  18720. newSound.setPosition(soundPosition);
  18721. }
  18722. if (parsedSound.isDirectional) {
  18723. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  18724. if (parsedSound.localDirectionToMesh) {
  18725. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  18726. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  18727. }
  18728. }
  18729. if (parsedSound.connectedMeshId) {
  18730. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  18731. if (connectedMesh) {
  18732. newSound.attachToMesh(connectedMesh);
  18733. }
  18734. }
  18735. };
  18736. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18737. names = (names instanceof Array) ? names : [names];
  18738. for (var i in names) {
  18739. if (mesh.name === names[i]) {
  18740. hierarchyIds.push(mesh.id);
  18741. return true;
  18742. }
  18743. }
  18744. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18745. hierarchyIds.push(mesh.id);
  18746. return true;
  18747. }
  18748. return false;
  18749. };
  18750. var importVertexData = function (parsedVertexData, geometry) {
  18751. var vertexData = new BABYLON.VertexData();
  18752. // positions
  18753. var positions = parsedVertexData.positions;
  18754. if (positions) {
  18755. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18756. }
  18757. // normals
  18758. var normals = parsedVertexData.normals;
  18759. if (normals) {
  18760. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18761. }
  18762. // uvs
  18763. var uvs = parsedVertexData.uvs;
  18764. if (uvs) {
  18765. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18766. }
  18767. // uv2s
  18768. var uv2s = parsedVertexData.uv2s;
  18769. if (uv2s) {
  18770. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18771. }
  18772. // colors
  18773. var colors = parsedVertexData.colors;
  18774. if (colors) {
  18775. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18776. }
  18777. // matricesIndices
  18778. var matricesIndices = parsedVertexData.matricesIndices;
  18779. if (matricesIndices) {
  18780. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18781. }
  18782. // matricesWeights
  18783. var matricesWeights = parsedVertexData.matricesWeights;
  18784. if (matricesWeights) {
  18785. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18786. }
  18787. // indices
  18788. var indices = parsedVertexData.indices;
  18789. if (indices) {
  18790. vertexData.indices = indices;
  18791. }
  18792. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18793. };
  18794. var importGeometry = function (parsedGeometry, mesh) {
  18795. var scene = mesh.getScene();
  18796. // Geometry
  18797. var geometryId = parsedGeometry.geometryId;
  18798. if (geometryId) {
  18799. var geometry = scene.getGeometryByID(geometryId);
  18800. if (geometry) {
  18801. geometry.applyToMesh(mesh);
  18802. }
  18803. }
  18804. else if (parsedGeometry instanceof ArrayBuffer) {
  18805. var binaryInfo = mesh._binaryInfo;
  18806. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18807. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18808. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18809. }
  18810. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18811. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18812. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18813. }
  18814. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18815. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18816. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18817. }
  18818. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18819. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18820. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18821. }
  18822. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18823. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18824. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18825. }
  18826. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18827. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18828. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18829. }
  18830. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18831. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18832. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18833. }
  18834. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18835. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18836. mesh.setIndices(indicesData);
  18837. }
  18838. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18839. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18840. mesh.subMeshes = [];
  18841. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18842. var materialIndex = subMeshesData[(i * 5) + 0];
  18843. var verticesStart = subMeshesData[(i * 5) + 1];
  18844. var verticesCount = subMeshesData[(i * 5) + 2];
  18845. var indexStart = subMeshesData[(i * 5) + 3];
  18846. var indexCount = subMeshesData[(i * 5) + 4];
  18847. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18848. }
  18849. }
  18850. }
  18851. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18852. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18853. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18854. if (parsedGeometry.uvs) {
  18855. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18856. }
  18857. if (parsedGeometry.uvs2) {
  18858. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18859. }
  18860. if (parsedGeometry.colors) {
  18861. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18862. }
  18863. if (parsedGeometry.matricesIndices) {
  18864. if (!parsedGeometry.matricesIndices._isExpanded) {
  18865. var floatIndices = [];
  18866. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18867. var matricesIndex = parsedGeometry.matricesIndices[i];
  18868. floatIndices.push(matricesIndex & 0x000000FF);
  18869. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18870. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18871. floatIndices.push(matricesIndex >> 24);
  18872. }
  18873. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18874. }
  18875. else {
  18876. delete parsedGeometry.matricesIndices._isExpanded;
  18877. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18878. }
  18879. }
  18880. if (parsedGeometry.matricesWeights) {
  18881. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18882. }
  18883. mesh.setIndices(parsedGeometry.indices);
  18884. // SubMeshes
  18885. if (parsedGeometry.subMeshes) {
  18886. mesh.subMeshes = [];
  18887. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18888. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18889. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18890. }
  18891. }
  18892. }
  18893. // Flat shading
  18894. if (mesh._shouldGenerateFlatShading) {
  18895. mesh.convertToFlatShadedMesh();
  18896. delete mesh._shouldGenerateFlatShading;
  18897. }
  18898. // Update
  18899. mesh.computeWorldMatrix(true);
  18900. // Octree
  18901. if (scene._selectionOctree) {
  18902. scene._selectionOctree.addMesh(mesh);
  18903. }
  18904. };
  18905. BABYLON.SceneLoader.RegisterPlugin({
  18906. extensions: ".babylon",
  18907. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18908. var parsedData = JSON.parse(data);
  18909. var loadedSkeletonsIds = [];
  18910. var loadedMaterialsIds = [];
  18911. var hierarchyIds = [];
  18912. for (var index = 0; index < parsedData.meshes.length; index++) {
  18913. var parsedMesh = parsedData.meshes[index];
  18914. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18915. if (meshesNames instanceof Array) {
  18916. // Remove found mesh name from list.
  18917. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18918. }
  18919. // Material ?
  18920. if (parsedMesh.materialId) {
  18921. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18922. if (!materialFound) {
  18923. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18924. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18925. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18926. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18927. var subMatId = parsedMultiMaterial.materials[matIndex];
  18928. loadedMaterialsIds.push(subMatId);
  18929. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18930. }
  18931. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18932. parseMultiMaterial(parsedMultiMaterial, scene);
  18933. materialFound = true;
  18934. break;
  18935. }
  18936. }
  18937. }
  18938. if (!materialFound) {
  18939. loadedMaterialsIds.push(parsedMesh.materialId);
  18940. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18941. }
  18942. }
  18943. // Skeleton ?
  18944. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18945. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18946. if (!skeletonAlreadyLoaded) {
  18947. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18948. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18949. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18950. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18951. loadedSkeletonsIds.push(parsedSkeleton.id);
  18952. }
  18953. }
  18954. }
  18955. }
  18956. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18957. meshes.push(mesh);
  18958. }
  18959. }
  18960. for (index = 0; index < scene.meshes.length; index++) {
  18961. var currentMesh = scene.meshes[index];
  18962. if (currentMesh._waitingParentId) {
  18963. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18964. currentMesh._waitingParentId = undefined;
  18965. }
  18966. }
  18967. // Particles
  18968. if (parsedData.particleSystems) {
  18969. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18970. var parsedParticleSystem = parsedData.particleSystems[index];
  18971. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18972. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18973. }
  18974. }
  18975. }
  18976. return true;
  18977. },
  18978. load: function (scene, data, rootUrl) {
  18979. var parsedData = JSON.parse(data);
  18980. // Scene
  18981. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18982. scene.autoClear = parsedData.autoClear;
  18983. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18984. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18985. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18986. // Fog
  18987. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18988. scene.fogMode = parsedData.fogMode;
  18989. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18990. scene.fogStart = parsedData.fogStart;
  18991. scene.fogEnd = parsedData.fogEnd;
  18992. scene.fogDensity = parsedData.fogDensity;
  18993. }
  18994. for (var index = 0; index < parsedData.lights.length; index++) {
  18995. var parsedLight = parsedData.lights[index];
  18996. parseLight(parsedLight, scene);
  18997. }
  18998. // Materials
  18999. if (parsedData.materials) {
  19000. for (index = 0; index < parsedData.materials.length; index++) {
  19001. var parsedMaterial = parsedData.materials[index];
  19002. parseMaterial(parsedMaterial, scene, rootUrl);
  19003. }
  19004. }
  19005. if (parsedData.multiMaterials) {
  19006. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19007. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19008. parseMultiMaterial(parsedMultiMaterial, scene);
  19009. }
  19010. }
  19011. // Skeletons
  19012. if (parsedData.skeletons) {
  19013. for (index = 0; index < parsedData.skeletons.length; index++) {
  19014. var parsedSkeleton = parsedData.skeletons[index];
  19015. parseSkeleton(parsedSkeleton, scene);
  19016. }
  19017. }
  19018. // Geometries
  19019. var geometries = parsedData.geometries;
  19020. if (geometries) {
  19021. // Boxes
  19022. var boxes = geometries.boxes;
  19023. if (boxes) {
  19024. for (index = 0; index < boxes.length; index++) {
  19025. var parsedBox = boxes[index];
  19026. parseBox(parsedBox, scene);
  19027. }
  19028. }
  19029. // Spheres
  19030. var spheres = geometries.spheres;
  19031. if (spheres) {
  19032. for (index = 0; index < spheres.length; index++) {
  19033. var parsedSphere = spheres[index];
  19034. parseSphere(parsedSphere, scene);
  19035. }
  19036. }
  19037. // Cylinders
  19038. var cylinders = geometries.cylinders;
  19039. if (cylinders) {
  19040. for (index = 0; index < cylinders.length; index++) {
  19041. var parsedCylinder = cylinders[index];
  19042. parseCylinder(parsedCylinder, scene);
  19043. }
  19044. }
  19045. // Toruses
  19046. var toruses = geometries.toruses;
  19047. if (toruses) {
  19048. for (index = 0; index < toruses.length; index++) {
  19049. var parsedTorus = toruses[index];
  19050. parseTorus(parsedTorus, scene);
  19051. }
  19052. }
  19053. // Grounds
  19054. var grounds = geometries.grounds;
  19055. if (grounds) {
  19056. for (index = 0; index < grounds.length; index++) {
  19057. var parsedGround = grounds[index];
  19058. parseGround(parsedGround, scene);
  19059. }
  19060. }
  19061. // Planes
  19062. var planes = geometries.planes;
  19063. if (planes) {
  19064. for (index = 0; index < planes.length; index++) {
  19065. var parsedPlane = planes[index];
  19066. parsePlane(parsedPlane, scene);
  19067. }
  19068. }
  19069. // TorusKnots
  19070. var torusKnots = geometries.torusKnots;
  19071. if (torusKnots) {
  19072. for (index = 0; index < torusKnots.length; index++) {
  19073. var parsedTorusKnot = torusKnots[index];
  19074. parseTorusKnot(parsedTorusKnot, scene);
  19075. }
  19076. }
  19077. // VertexData
  19078. var vertexData = geometries.vertexData;
  19079. if (vertexData) {
  19080. for (index = 0; index < vertexData.length; index++) {
  19081. var parsedVertexData = vertexData[index];
  19082. parseVertexData(parsedVertexData, scene, rootUrl);
  19083. }
  19084. }
  19085. }
  19086. for (index = 0; index < parsedData.meshes.length; index++) {
  19087. var parsedMesh = parsedData.meshes[index];
  19088. parseMesh(parsedMesh, scene, rootUrl);
  19089. }
  19090. for (index = 0; index < parsedData.cameras.length; index++) {
  19091. var parsedCamera = parsedData.cameras[index];
  19092. parseCamera(parsedCamera, scene);
  19093. }
  19094. if (parsedData.activeCameraID) {
  19095. scene.setActiveCameraByID(parsedData.activeCameraID);
  19096. }
  19097. for (index = 0; index < scene.cameras.length; index++) {
  19098. var camera = scene.cameras[index];
  19099. if (camera._waitingParentId) {
  19100. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19101. camera._waitingParentId = undefined;
  19102. }
  19103. }
  19104. for (index = 0; index < scene.lights.length; index++) {
  19105. var light = scene.lights[index];
  19106. if (light._waitingParentId) {
  19107. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19108. light._waitingParentId = undefined;
  19109. }
  19110. }
  19111. for (index = 0; index < scene.meshes.length; index++) {
  19112. var mesh = scene.meshes[index];
  19113. if (mesh._waitingParentId) {
  19114. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19115. mesh._waitingParentId = undefined;
  19116. }
  19117. if (mesh._waitingActions) {
  19118. parseActions(mesh._waitingActions, mesh, scene);
  19119. mesh._waitingActions = undefined;
  19120. }
  19121. }
  19122. // Particles Systems
  19123. if (parsedData.particleSystems) {
  19124. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19125. var parsedParticleSystem = parsedData.particleSystems[index];
  19126. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19127. }
  19128. }
  19129. // Lens flares
  19130. if (parsedData.lensFlareSystems) {
  19131. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19132. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19133. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19134. }
  19135. }
  19136. // Shadows
  19137. if (parsedData.shadowGenerators) {
  19138. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19139. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19140. parseShadowGenerator(parsedShadowGenerator, scene);
  19141. }
  19142. }
  19143. // Sounds
  19144. if (parsedData.sounds && scene.getEngine().getAudioEngine().canUseWebAudio) {
  19145. for (index = 0; index < parsedData.sounds.length; index++) {
  19146. var parsedSound = parsedData.sounds[index];
  19147. parseSound(parsedSound, scene, rootUrl);
  19148. }
  19149. }
  19150. // Actions (scene)
  19151. if (parsedData.actions) {
  19152. parseActions(parsedData.actions, null, scene);
  19153. }
  19154. // Finish
  19155. return true;
  19156. }
  19157. });
  19158. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19159. })(BABYLON || (BABYLON = {}));
  19160. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19161. (function (BABYLON) {
  19162. // Unique ID when we import meshes from Babylon to CSG
  19163. var currentCSGMeshId = 0;
  19164. // # class Vertex
  19165. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19166. // one to provide additional features like texture coordinates and vertex
  19167. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19168. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19169. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19170. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19171. // is not used anywhere else.
  19172. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19173. var Vertex = (function () {
  19174. function Vertex(pos, normal, uv) {
  19175. this.pos = pos;
  19176. this.normal = normal;
  19177. this.uv = uv;
  19178. }
  19179. Vertex.prototype.clone = function () {
  19180. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19181. };
  19182. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19183. // orientation of a polygon is flipped.
  19184. Vertex.prototype.flip = function () {
  19185. this.normal = this.normal.scale(-1);
  19186. };
  19187. // Create a new vertex between this vertex and `other` by linearly
  19188. // interpolating all properties using a parameter of `t`. Subclasses should
  19189. // override this to interpolate additional properties.
  19190. Vertex.prototype.interpolate = function (other, t) {
  19191. 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));
  19192. };
  19193. return Vertex;
  19194. })();
  19195. // # class Plane
  19196. // Represents a plane in 3D space.
  19197. var Plane = (function () {
  19198. function Plane(normal, w) {
  19199. this.normal = normal;
  19200. this.w = w;
  19201. }
  19202. Plane.FromPoints = function (a, b, c) {
  19203. var v0 = c.subtract(a);
  19204. var v1 = b.subtract(a);
  19205. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19206. return null;
  19207. }
  19208. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19209. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19210. };
  19211. Plane.prototype.clone = function () {
  19212. return new Plane(this.normal.clone(), this.w);
  19213. };
  19214. Plane.prototype.flip = function () {
  19215. this.normal.scaleInPlace(-1);
  19216. this.w = -this.w;
  19217. };
  19218. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19219. // fragments in the appropriate lists. Coplanar polygons go into either
  19220. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19221. // respect to this plane. Polygons in front or in back of this plane go into
  19222. // either `front` or `back`.
  19223. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19224. var COPLANAR = 0;
  19225. var FRONT = 1;
  19226. var BACK = 2;
  19227. var SPANNING = 3;
  19228. // Classify each point as well as the entire polygon into one of the above
  19229. // four classes.
  19230. var polygonType = 0;
  19231. var types = [];
  19232. for (var i = 0; i < polygon.vertices.length; i++) {
  19233. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19234. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19235. polygonType |= type;
  19236. types.push(type);
  19237. }
  19238. switch (polygonType) {
  19239. case COPLANAR:
  19240. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19241. break;
  19242. case FRONT:
  19243. front.push(polygon);
  19244. break;
  19245. case BACK:
  19246. back.push(polygon);
  19247. break;
  19248. case SPANNING:
  19249. var f = [], b = [];
  19250. for (i = 0; i < polygon.vertices.length; i++) {
  19251. var j = (i + 1) % polygon.vertices.length;
  19252. var ti = types[i], tj = types[j];
  19253. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19254. if (ti != BACK)
  19255. f.push(vi);
  19256. if (ti != FRONT)
  19257. b.push(ti != BACK ? vi.clone() : vi);
  19258. if ((ti | tj) == SPANNING) {
  19259. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19260. var v = vi.interpolate(vj, t);
  19261. f.push(v);
  19262. b.push(v.clone());
  19263. }
  19264. }
  19265. if (f.length >= 3) {
  19266. var poly = new Polygon(f, polygon.shared);
  19267. if (poly.plane)
  19268. front.push(poly);
  19269. }
  19270. if (b.length >= 3) {
  19271. poly = new Polygon(b, polygon.shared);
  19272. if (poly.plane)
  19273. back.push(poly);
  19274. }
  19275. break;
  19276. }
  19277. };
  19278. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19279. // point is on the plane.
  19280. Plane.EPSILON = 1e-5;
  19281. return Plane;
  19282. })();
  19283. // # class Polygon
  19284. // Represents a convex polygon. The vertices used to initialize a polygon must
  19285. // be coplanar and form a convex loop.
  19286. //
  19287. // Each convex polygon has a `shared` property, which is shared between all
  19288. // polygons that are clones of each other or were split from the same polygon.
  19289. // This can be used to define per-polygon properties (such as surface color).
  19290. var Polygon = (function () {
  19291. function Polygon(vertices, shared) {
  19292. this.vertices = vertices;
  19293. this.shared = shared;
  19294. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19295. }
  19296. Polygon.prototype.clone = function () {
  19297. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19298. return new Polygon(vertices, this.shared);
  19299. };
  19300. Polygon.prototype.flip = function () {
  19301. this.vertices.reverse().map(function (v) {
  19302. v.flip();
  19303. });
  19304. this.plane.flip();
  19305. };
  19306. return Polygon;
  19307. })();
  19308. // # class Node
  19309. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19310. // by picking a polygon to split along. That polygon (and all other coplanar
  19311. // polygons) are added directly to that node and the other polygons are added to
  19312. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19313. // no distinction between internal and leaf nodes.
  19314. var Node = (function () {
  19315. function Node(polygons) {
  19316. this.plane = null;
  19317. this.front = null;
  19318. this.back = null;
  19319. this.polygons = [];
  19320. if (polygons) {
  19321. this.build(polygons);
  19322. }
  19323. }
  19324. Node.prototype.clone = function () {
  19325. var node = new Node();
  19326. node.plane = this.plane && this.plane.clone();
  19327. node.front = this.front && this.front.clone();
  19328. node.back = this.back && this.back.clone();
  19329. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19330. return node;
  19331. };
  19332. // Convert solid space to empty space and empty space to solid space.
  19333. Node.prototype.invert = function () {
  19334. for (var i = 0; i < this.polygons.length; i++) {
  19335. this.polygons[i].flip();
  19336. }
  19337. if (this.plane) {
  19338. this.plane.flip();
  19339. }
  19340. if (this.front) {
  19341. this.front.invert();
  19342. }
  19343. if (this.back) {
  19344. this.back.invert();
  19345. }
  19346. var temp = this.front;
  19347. this.front = this.back;
  19348. this.back = temp;
  19349. };
  19350. // Recursively remove all polygons in `polygons` that are inside this BSP
  19351. // tree.
  19352. Node.prototype.clipPolygons = function (polygons) {
  19353. if (!this.plane)
  19354. return polygons.slice();
  19355. var front = [], back = [];
  19356. for (var i = 0; i < polygons.length; i++) {
  19357. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19358. }
  19359. if (this.front) {
  19360. front = this.front.clipPolygons(front);
  19361. }
  19362. if (this.back) {
  19363. back = this.back.clipPolygons(back);
  19364. }
  19365. else {
  19366. back = [];
  19367. }
  19368. return front.concat(back);
  19369. };
  19370. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19371. // `bsp`.
  19372. Node.prototype.clipTo = function (bsp) {
  19373. this.polygons = bsp.clipPolygons(this.polygons);
  19374. if (this.front)
  19375. this.front.clipTo(bsp);
  19376. if (this.back)
  19377. this.back.clipTo(bsp);
  19378. };
  19379. // Return a list of all polygons in this BSP tree.
  19380. Node.prototype.allPolygons = function () {
  19381. var polygons = this.polygons.slice();
  19382. if (this.front)
  19383. polygons = polygons.concat(this.front.allPolygons());
  19384. if (this.back)
  19385. polygons = polygons.concat(this.back.allPolygons());
  19386. return polygons;
  19387. };
  19388. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  19389. // new polygons are filtered down to the bottom of the tree and become new
  19390. // nodes there. Each set of polygons is partitioned using the first polygon
  19391. // (no heuristic is used to pick a good split).
  19392. Node.prototype.build = function (polygons) {
  19393. if (!polygons.length)
  19394. return;
  19395. if (!this.plane)
  19396. this.plane = polygons[0].plane.clone();
  19397. var front = [], back = [];
  19398. for (var i = 0; i < polygons.length; i++) {
  19399. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  19400. }
  19401. if (front.length) {
  19402. if (!this.front)
  19403. this.front = new Node();
  19404. this.front.build(front);
  19405. }
  19406. if (back.length) {
  19407. if (!this.back)
  19408. this.back = new Node();
  19409. this.back.build(back);
  19410. }
  19411. };
  19412. return Node;
  19413. })();
  19414. var CSG = (function () {
  19415. function CSG() {
  19416. this.polygons = new Array();
  19417. }
  19418. // Convert BABYLON.Mesh to BABYLON.CSG
  19419. CSG.FromMesh = function (mesh) {
  19420. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19421. if (mesh instanceof BABYLON.Mesh) {
  19422. mesh.computeWorldMatrix(true);
  19423. var matrix = mesh.getWorldMatrix();
  19424. var meshPosition = mesh.position.clone();
  19425. var meshRotation = mesh.rotation.clone();
  19426. var meshScaling = mesh.scaling.clone();
  19427. }
  19428. else {
  19429. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19430. }
  19431. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19432. var subMeshes = mesh.subMeshes;
  19433. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19434. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19435. vertices = [];
  19436. for (var j = 0; j < 3; j++) {
  19437. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19438. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19439. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19440. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19441. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19442. vertex = new Vertex(position, normal, uv);
  19443. vertices.push(vertex);
  19444. }
  19445. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19446. // To handle the case of degenerated triangle
  19447. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19448. if (polygon.plane)
  19449. polygons.push(polygon);
  19450. }
  19451. }
  19452. var csg = CSG.FromPolygons(polygons);
  19453. csg.matrix = matrix;
  19454. csg.position = meshPosition;
  19455. csg.rotation = meshRotation;
  19456. csg.scaling = meshScaling;
  19457. currentCSGMeshId++;
  19458. return csg;
  19459. };
  19460. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19461. CSG.FromPolygons = function (polygons) {
  19462. var csg = new BABYLON.CSG();
  19463. csg.polygons = polygons;
  19464. return csg;
  19465. };
  19466. CSG.prototype.clone = function () {
  19467. var csg = new BABYLON.CSG();
  19468. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19469. csg.copyTransformAttributes(this);
  19470. return csg;
  19471. };
  19472. CSG.prototype.toPolygons = function () {
  19473. return this.polygons;
  19474. };
  19475. CSG.prototype.union = function (csg) {
  19476. var a = new Node(this.clone().polygons);
  19477. var b = new Node(csg.clone().polygons);
  19478. a.clipTo(b);
  19479. b.clipTo(a);
  19480. b.invert();
  19481. b.clipTo(a);
  19482. b.invert();
  19483. a.build(b.allPolygons());
  19484. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19485. };
  19486. CSG.prototype.unionInPlace = function (csg) {
  19487. var a = new Node(this.polygons);
  19488. var b = new Node(csg.polygons);
  19489. a.clipTo(b);
  19490. b.clipTo(a);
  19491. b.invert();
  19492. b.clipTo(a);
  19493. b.invert();
  19494. a.build(b.allPolygons());
  19495. this.polygons = a.allPolygons();
  19496. };
  19497. CSG.prototype.subtract = function (csg) {
  19498. var a = new Node(this.clone().polygons);
  19499. var b = new Node(csg.clone().polygons);
  19500. a.invert();
  19501. a.clipTo(b);
  19502. b.clipTo(a);
  19503. b.invert();
  19504. b.clipTo(a);
  19505. b.invert();
  19506. a.build(b.allPolygons());
  19507. a.invert();
  19508. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19509. };
  19510. CSG.prototype.subtractInPlace = function (csg) {
  19511. var a = new Node(this.polygons);
  19512. var b = new Node(csg.polygons);
  19513. a.invert();
  19514. a.clipTo(b);
  19515. b.clipTo(a);
  19516. b.invert();
  19517. b.clipTo(a);
  19518. b.invert();
  19519. a.build(b.allPolygons());
  19520. a.invert();
  19521. this.polygons = a.allPolygons();
  19522. };
  19523. CSG.prototype.intersect = function (csg) {
  19524. var a = new Node(this.clone().polygons);
  19525. var b = new Node(csg.clone().polygons);
  19526. a.invert();
  19527. b.clipTo(a);
  19528. b.invert();
  19529. a.clipTo(b);
  19530. b.clipTo(a);
  19531. a.build(b.allPolygons());
  19532. a.invert();
  19533. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19534. };
  19535. CSG.prototype.intersectInPlace = function (csg) {
  19536. var a = new Node(this.polygons);
  19537. var b = new Node(csg.polygons);
  19538. a.invert();
  19539. b.clipTo(a);
  19540. b.invert();
  19541. a.clipTo(b);
  19542. b.clipTo(a);
  19543. a.build(b.allPolygons());
  19544. a.invert();
  19545. this.polygons = a.allPolygons();
  19546. };
  19547. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19548. // not modified.
  19549. CSG.prototype.inverse = function () {
  19550. var csg = this.clone();
  19551. csg.inverseInPlace();
  19552. return csg;
  19553. };
  19554. CSG.prototype.inverseInPlace = function () {
  19555. this.polygons.map(function (p) {
  19556. p.flip();
  19557. });
  19558. };
  19559. // This is used to keep meshes transformations so they can be restored
  19560. // when we build back a Babylon Mesh
  19561. // NB : All CSG operations are performed in world coordinates
  19562. CSG.prototype.copyTransformAttributes = function (csg) {
  19563. this.matrix = csg.matrix;
  19564. this.position = csg.position;
  19565. this.rotation = csg.rotation;
  19566. this.scaling = csg.scaling;
  19567. return this;
  19568. };
  19569. // Build Raw mesh from CSG
  19570. // Coordinates here are in world space
  19571. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19572. var matrix = this.matrix.clone();
  19573. matrix.invert();
  19574. 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;
  19575. if (keepSubMeshes) {
  19576. // Sort Polygons, since subMeshes are indices range
  19577. polygons.sort(function (a, b) {
  19578. if (a.shared.meshId === b.shared.meshId) {
  19579. return a.shared.subMeshId - b.shared.subMeshId;
  19580. }
  19581. else {
  19582. return a.shared.meshId - b.shared.meshId;
  19583. }
  19584. });
  19585. }
  19586. for (var i = 0, il = polygons.length; i < il; i++) {
  19587. polygon = polygons[i];
  19588. // Building SubMeshes
  19589. if (!subMesh_dict[polygon.shared.meshId]) {
  19590. subMesh_dict[polygon.shared.meshId] = {};
  19591. }
  19592. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19593. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19594. indexStart: +Infinity,
  19595. indexEnd: -Infinity,
  19596. materialIndex: polygon.shared.materialIndex
  19597. };
  19598. }
  19599. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19600. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19601. polygonIndices[0] = 0;
  19602. polygonIndices[1] = j - 1;
  19603. polygonIndices[2] = j;
  19604. for (var k = 0; k < 3; k++) {
  19605. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19606. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19607. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19608. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19609. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19610. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19611. // Check if 2 points can be merged
  19612. 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)) {
  19613. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19614. uvs.push(uv.x, uv.y);
  19615. normals.push(normal.x, normal.y, normal.z);
  19616. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19617. }
  19618. indices.push(vertex_idx);
  19619. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19620. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19621. currentIndex++;
  19622. }
  19623. }
  19624. }
  19625. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19626. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19627. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19628. mesh.setIndices(indices);
  19629. if (keepSubMeshes) {
  19630. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19631. var materialIndexOffset = 0, materialMaxIndex;
  19632. mesh.subMeshes.length = 0;
  19633. for (var m in subMesh_dict) {
  19634. materialMaxIndex = -1;
  19635. for (var sm in subMesh_dict[m]) {
  19636. subMesh_obj = subMesh_dict[m][sm];
  19637. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19638. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19639. }
  19640. materialIndexOffset += ++materialMaxIndex;
  19641. }
  19642. }
  19643. return mesh;
  19644. };
  19645. // Build Mesh from CSG taking material and transforms into account
  19646. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19647. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19648. mesh.material = material;
  19649. mesh.position.copyFrom(this.position);
  19650. mesh.rotation.copyFrom(this.rotation);
  19651. mesh.scaling.copyFrom(this.scaling);
  19652. mesh.computeWorldMatrix(true);
  19653. return mesh;
  19654. };
  19655. return CSG;
  19656. })();
  19657. BABYLON.CSG = CSG;
  19658. })(BABYLON || (BABYLON = {}));
  19659. //# sourceMappingURL=babylon.csg.js.map
  19660. var BABYLON;
  19661. (function (BABYLON) {
  19662. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19663. __extends(OculusDistortionCorrectionPostProcess, _super);
  19664. //ANY
  19665. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19666. var _this = this;
  19667. _super.call(this, name, "oculusDistortionCorrection", [
  19668. 'LensCenter',
  19669. 'Scale',
  19670. 'ScaleIn',
  19671. 'HmdWarpParam'
  19672. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19673. this._isRightEye = isRightEye;
  19674. this._distortionFactors = cameraSettings.DistortionK;
  19675. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19676. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19677. this.onSizeChanged = function () {
  19678. _this.aspectRatio = _this.width * .5 / _this.height;
  19679. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19680. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19681. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19682. };
  19683. this.onApply = function (effect) {
  19684. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19685. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19686. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19687. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19688. };
  19689. }
  19690. return OculusDistortionCorrectionPostProcess;
  19691. })(BABYLON.PostProcess);
  19692. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19693. })(BABYLON || (BABYLON = {}));
  19694. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19695. // 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
  19696. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19697. var BABYLON;
  19698. (function (BABYLON) {
  19699. (function (JoystickAxis) {
  19700. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19701. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19702. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19703. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19704. var JoystickAxis = BABYLON.JoystickAxis;
  19705. var VirtualJoystick = (function () {
  19706. function VirtualJoystick(leftJoystick) {
  19707. var _this = this;
  19708. if (leftJoystick) {
  19709. this._leftJoystick = true;
  19710. }
  19711. else {
  19712. this._leftJoystick = false;
  19713. }
  19714. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19715. VirtualJoystick._globalJoystickIndex++;
  19716. // By default left & right arrow keys are moving the X
  19717. // and up & down keys are moving the Y
  19718. this._axisTargetedByLeftAndRight = 0 /* X */;
  19719. this._axisTargetedByUpAndDown = 1 /* Y */;
  19720. this.reverseLeftRight = false;
  19721. this.reverseUpDown = false;
  19722. // collections of pointers
  19723. this._touches = new BABYLON.VirtualJoystick.Collection();
  19724. this.deltaPosition = BABYLON.Vector3.Zero();
  19725. this._joystickSensibility = 25;
  19726. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19727. this._rotationSpeed = 25;
  19728. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19729. this._rotateOnAxisRelativeToMesh = false;
  19730. // injecting a canvas element on top of the canvas 3D game
  19731. if (!VirtualJoystick.vjCanvas) {
  19732. window.addEventListener("resize", function () {
  19733. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19734. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19735. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19736. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19737. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19738. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19739. }, false);
  19740. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19741. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19742. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19743. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19744. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19745. VirtualJoystick.vjCanvas.style.width = "100%";
  19746. VirtualJoystick.vjCanvas.style.height = "100%";
  19747. VirtualJoystick.vjCanvas.style.position = "absolute";
  19748. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19749. VirtualJoystick.vjCanvas.style.top = "0px";
  19750. VirtualJoystick.vjCanvas.style.left = "0px";
  19751. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19752. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19753. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19754. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19755. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19756. document.body.appendChild(VirtualJoystick.vjCanvas);
  19757. }
  19758. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19759. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19760. this.pressed = false;
  19761. // default joystick color
  19762. this._joystickColor = "cyan";
  19763. this._joystickPointerID = -1;
  19764. // current joystick position
  19765. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19766. // origin joystick position
  19767. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19768. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19769. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19770. _this._onPointerDown(evt);
  19771. }, false);
  19772. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19773. _this._onPointerMove(evt);
  19774. }, false);
  19775. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19776. _this._onPointerUp(evt);
  19777. }, false);
  19778. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19779. _this._onPointerUp(evt);
  19780. }, false);
  19781. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19782. evt.preventDefault(); // Disables system menu
  19783. }, false);
  19784. requestAnimationFrame(function () {
  19785. _this._drawVirtualJoystick();
  19786. });
  19787. }
  19788. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19789. this._joystickSensibility = newJoystickSensibility;
  19790. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19791. };
  19792. VirtualJoystick.prototype._onPointerDown = function (e) {
  19793. var positionOnScreenCondition;
  19794. e.preventDefault();
  19795. if (this._leftJoystick === true) {
  19796. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19797. }
  19798. else {
  19799. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19800. }
  19801. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19802. // First contact will be dedicated to the virtual joystick
  19803. this._joystickPointerID = e.pointerId;
  19804. this._joystickPointerStartPos.x = e.clientX;
  19805. this._joystickPointerStartPos.y = e.clientY;
  19806. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19807. this._deltaJoystickVector.x = 0;
  19808. this._deltaJoystickVector.y = 0;
  19809. this.pressed = true;
  19810. this._touches.add(e.pointerId.toString(), e);
  19811. }
  19812. else {
  19813. // You can only trigger the action buttons with a joystick declared
  19814. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19815. this._action();
  19816. this._touches.add(e.pointerId.toString(), e);
  19817. }
  19818. }
  19819. };
  19820. VirtualJoystick.prototype._onPointerMove = function (e) {
  19821. // If the current pointer is the one associated to the joystick (first touch contact)
  19822. if (this._joystickPointerID == e.pointerId) {
  19823. this._joystickPointerPos.x = e.clientX;
  19824. this._joystickPointerPos.y = e.clientY;
  19825. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19826. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19827. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19828. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19829. switch (this._axisTargetedByLeftAndRight) {
  19830. case 0 /* X */:
  19831. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19832. break;
  19833. case 1 /* Y */:
  19834. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19835. break;
  19836. case 2 /* Z */:
  19837. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19838. break;
  19839. }
  19840. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19841. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19842. switch (this._axisTargetedByUpAndDown) {
  19843. case 0 /* X */:
  19844. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19845. break;
  19846. case 1 /* Y */:
  19847. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19848. break;
  19849. case 2 /* Z */:
  19850. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19851. break;
  19852. }
  19853. }
  19854. else {
  19855. if (this._touches.item(e.pointerId.toString())) {
  19856. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19857. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19858. }
  19859. }
  19860. };
  19861. VirtualJoystick.prototype._onPointerUp = function (e) {
  19862. this._clearCanvas();
  19863. if (this._joystickPointerID == e.pointerId) {
  19864. this._joystickPointerID = -1;
  19865. this.pressed = false;
  19866. }
  19867. this._deltaJoystickVector.x = 0;
  19868. this._deltaJoystickVector.y = 0;
  19869. this._touches.remove(e.pointerId.toString());
  19870. };
  19871. /**
  19872. * Change the color of the virtual joystick
  19873. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19874. */
  19875. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19876. this._joystickColor = newColor;
  19877. };
  19878. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19879. this._action = action;
  19880. };
  19881. // Define which axis you'd like to control for left & right
  19882. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19883. switch (axis) {
  19884. case 0 /* X */:
  19885. case 1 /* Y */:
  19886. case 2 /* Z */:
  19887. this._axisTargetedByLeftAndRight = axis;
  19888. break;
  19889. default:
  19890. this._axisTargetedByLeftAndRight = 0 /* X */;
  19891. break;
  19892. }
  19893. };
  19894. // Define which axis you'd like to control for up & down
  19895. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19896. switch (axis) {
  19897. case 0 /* X */:
  19898. case 1 /* Y */:
  19899. case 2 /* Z */:
  19900. this._axisTargetedByUpAndDown = axis;
  19901. break;
  19902. default:
  19903. this._axisTargetedByUpAndDown = 1 /* Y */;
  19904. break;
  19905. }
  19906. };
  19907. VirtualJoystick.prototype._clearCanvas = function () {
  19908. if (this._leftJoystick) {
  19909. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19910. }
  19911. else {
  19912. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19913. }
  19914. };
  19915. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19916. var _this = this;
  19917. if (this.pressed) {
  19918. this._clearCanvas();
  19919. this._touches.forEach(function (touch) {
  19920. if (touch.pointerId === _this._joystickPointerID) {
  19921. VirtualJoystick.vjCanvasContext.beginPath();
  19922. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19923. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19924. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19925. VirtualJoystick.vjCanvasContext.stroke();
  19926. VirtualJoystick.vjCanvasContext.beginPath();
  19927. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19928. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19929. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19930. VirtualJoystick.vjCanvasContext.stroke();
  19931. VirtualJoystick.vjCanvasContext.beginPath();
  19932. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19933. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19934. VirtualJoystick.vjCanvasContext.stroke();
  19935. }
  19936. else {
  19937. VirtualJoystick.vjCanvasContext.beginPath();
  19938. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19939. VirtualJoystick.vjCanvasContext.beginPath();
  19940. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19941. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19942. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19943. VirtualJoystick.vjCanvasContext.stroke();
  19944. }
  19945. ;
  19946. });
  19947. }
  19948. requestAnimationFrame(function () {
  19949. _this._drawVirtualJoystick();
  19950. });
  19951. };
  19952. VirtualJoystick.prototype.releaseCanvas = function () {
  19953. if (VirtualJoystick.vjCanvas) {
  19954. document.body.removeChild(VirtualJoystick.vjCanvas);
  19955. VirtualJoystick.vjCanvas = null;
  19956. }
  19957. };
  19958. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  19959. VirtualJoystick._globalJoystickIndex = 0;
  19960. return VirtualJoystick;
  19961. })();
  19962. BABYLON.VirtualJoystick = VirtualJoystick;
  19963. })(BABYLON || (BABYLON = {}));
  19964. var BABYLON;
  19965. (function (BABYLON) {
  19966. var VirtualJoystick;
  19967. (function (VirtualJoystick) {
  19968. var Collection = (function () {
  19969. function Collection() {
  19970. this._count = 0;
  19971. this._collection = new Array();
  19972. }
  19973. Collection.prototype.Count = function () {
  19974. return this._count;
  19975. };
  19976. Collection.prototype.add = function (key, item) {
  19977. if (this._collection[key] != undefined) {
  19978. return undefined;
  19979. }
  19980. this._collection[key] = item;
  19981. return ++this._count;
  19982. };
  19983. Collection.prototype.remove = function (key) {
  19984. if (this._collection[key] == undefined) {
  19985. return undefined;
  19986. }
  19987. delete this._collection[key];
  19988. return --this._count;
  19989. };
  19990. Collection.prototype.item = function (key) {
  19991. return this._collection[key];
  19992. };
  19993. Collection.prototype.forEach = function (block) {
  19994. var key;
  19995. for (key in this._collection) {
  19996. if (this._collection.hasOwnProperty(key)) {
  19997. block(this._collection[key]);
  19998. }
  19999. }
  20000. };
  20001. return Collection;
  20002. })();
  20003. VirtualJoystick.Collection = Collection;
  20004. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20005. })(BABYLON || (BABYLON = {}));
  20006. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20007. var BABYLON;
  20008. (function (BABYLON) {
  20009. var OculusRiftDevKit2013_Metric = {
  20010. HResolution: 1280,
  20011. VResolution: 800,
  20012. HScreenSize: 0.149759993,
  20013. VScreenSize: 0.0935999975,
  20014. VScreenCenter: 0.0467999987,
  20015. EyeToScreenDistance: 0.0410000011,
  20016. LensSeparationDistance: 0.0635000020,
  20017. InterpupillaryDistance: 0.0640000030,
  20018. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20019. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20020. PostProcessScaleFactor: 1.714605507808412,
  20021. LensCenterOffset: 0.151976421
  20022. };
  20023. var _OculusInnerCamera = (function (_super) {
  20024. __extends(_OculusInnerCamera, _super);
  20025. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20026. _super.call(this, name, position, scene);
  20027. this._workMatrix = new BABYLON.Matrix();
  20028. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20029. // Constants
  20030. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20031. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20032. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20033. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20034. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20035. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20036. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20037. // Postprocess
  20038. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20039. }
  20040. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20041. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20042. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20043. return this._projectionMatrix;
  20044. };
  20045. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20046. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20047. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20048. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20049. // Computing target and final matrix
  20050. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20051. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20052. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20053. return this._viewMatrix;
  20054. };
  20055. return _OculusInnerCamera;
  20056. })(BABYLON.FreeCamera);
  20057. var OculusCamera = (function (_super) {
  20058. __extends(OculusCamera, _super);
  20059. function OculusCamera(name, position, scene) {
  20060. _super.call(this, name, position, scene);
  20061. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20062. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20063. this.subCameras.push(this._leftCamera);
  20064. this.subCameras.push(this._rightCamera);
  20065. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20066. }
  20067. OculusCamera.prototype._update = function () {
  20068. this._leftCamera.position.copyFrom(this.position);
  20069. this._rightCamera.position.copyFrom(this.position);
  20070. this._updateCamera(this._leftCamera);
  20071. this._updateCamera(this._rightCamera);
  20072. _super.prototype._update.call(this);
  20073. };
  20074. OculusCamera.prototype._updateCamera = function (camera) {
  20075. camera.minZ = this.minZ;
  20076. camera.maxZ = this.maxZ;
  20077. camera.rotation.x = this.rotation.x;
  20078. camera.rotation.y = this.rotation.y;
  20079. camera.rotation.z = this.rotation.z;
  20080. };
  20081. // Oculus events
  20082. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20083. var yaw = evt.alpha / 180 * Math.PI;
  20084. var pitch = evt.beta / 180 * Math.PI;
  20085. var roll = evt.gamma / 180 * Math.PI;
  20086. if (!this._offsetOrientation) {
  20087. this._offsetOrientation = {
  20088. yaw: yaw,
  20089. pitch: pitch,
  20090. roll: roll
  20091. };
  20092. return;
  20093. }
  20094. else {
  20095. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20096. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20097. this.rotation.z += this._offsetOrientation.roll - roll;
  20098. this._offsetOrientation.yaw = yaw;
  20099. this._offsetOrientation.pitch = pitch;
  20100. this._offsetOrientation.roll = roll;
  20101. }
  20102. };
  20103. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20104. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20105. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20106. };
  20107. OculusCamera.prototype.detachControl = function (element) {
  20108. _super.prototype.detachControl.call(this, element);
  20109. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20110. };
  20111. return OculusCamera;
  20112. })(BABYLON.FreeCamera);
  20113. BABYLON.OculusCamera = OculusCamera;
  20114. })(BABYLON || (BABYLON = {}));
  20115. //# sourceMappingURL=babylon.oculusCamera.js.map
  20116. var BABYLON;
  20117. (function (BABYLON) {
  20118. var OculusRiftDevKit2013_Metric = {
  20119. HResolution: 1280,
  20120. VResolution: 800,
  20121. HScreenSize: 0.149759993,
  20122. VScreenSize: 0.0935999975,
  20123. VScreenCenter: 0.0467999987,
  20124. EyeToScreenDistance: 0.0410000011,
  20125. LensSeparationDistance: 0.0635000020,
  20126. InterpupillaryDistance: 0.0640000030,
  20127. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20128. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20129. PostProcessScaleFactor: 1.714605507808412,
  20130. LensCenterOffset: 0.151976421
  20131. };
  20132. var _OculusInnerGamepadCamera = (function (_super) {
  20133. __extends(_OculusInnerGamepadCamera, _super);
  20134. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20135. _super.call(this, name, position, scene);
  20136. this._workMatrix = new BABYLON.Matrix();
  20137. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20138. // Constants
  20139. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20140. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20141. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20142. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20143. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20144. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20145. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20146. // Postprocess
  20147. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20148. }
  20149. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20150. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20151. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20152. return this._projectionMatrix;
  20153. };
  20154. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20155. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20156. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20157. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20158. // Computing target and final matrix
  20159. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20160. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20161. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20162. return this._viewMatrix;
  20163. };
  20164. return _OculusInnerGamepadCamera;
  20165. })(BABYLON.FreeCamera);
  20166. var OculusGamepadCamera = (function (_super) {
  20167. __extends(OculusGamepadCamera, _super);
  20168. function OculusGamepadCamera(name, position, scene) {
  20169. var _this = this;
  20170. _super.call(this, name, position, scene);
  20171. this.angularSensibility = 200;
  20172. this.moveSensibility = 75;
  20173. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20174. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20175. this.subCameras.push(this._leftCamera);
  20176. this.subCameras.push(this._rightCamera);
  20177. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20178. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20179. _this._onNewGameConnected(gamepad);
  20180. });
  20181. }
  20182. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20183. // Only the first gamepad can control the camera
  20184. if (gamepad.index === 0) {
  20185. this._gamepad = gamepad;
  20186. }
  20187. };
  20188. OculusGamepadCamera.prototype._update = function () {
  20189. this._leftCamera.position.copyFrom(this.position);
  20190. this._rightCamera.position.copyFrom(this.position);
  20191. this._updateCamera(this._leftCamera);
  20192. this._updateCamera(this._rightCamera);
  20193. _super.prototype._update.call(this);
  20194. };
  20195. OculusGamepadCamera.prototype._checkInputs = function () {
  20196. if (!this._gamepad) {
  20197. return;
  20198. }
  20199. var LSValues = this._gamepad.leftStick;
  20200. var normalizedLX = LSValues.x / this.moveSensibility;
  20201. var normalizedLY = LSValues.y / this.moveSensibility;
  20202. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20203. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20204. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20205. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20206. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20207. };
  20208. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20209. camera.minZ = this.minZ;
  20210. camera.maxZ = this.maxZ;
  20211. camera.rotation.x = this.rotation.x;
  20212. camera.rotation.y = this.rotation.y;
  20213. camera.rotation.z = this.rotation.z;
  20214. };
  20215. // Oculus events
  20216. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20217. var yaw = evt.alpha / 180 * Math.PI;
  20218. var pitch = evt.beta / 180 * Math.PI;
  20219. var roll = evt.gamma / 180 * Math.PI;
  20220. if (!this._offsetOrientation) {
  20221. this._offsetOrientation = {
  20222. yaw: yaw,
  20223. pitch: pitch,
  20224. roll: roll
  20225. };
  20226. return;
  20227. }
  20228. else {
  20229. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20230. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20231. this.rotation.z += this._offsetOrientation.roll - roll;
  20232. this._offsetOrientation.yaw = yaw;
  20233. this._offsetOrientation.pitch = pitch;
  20234. this._offsetOrientation.roll = roll;
  20235. }
  20236. };
  20237. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20238. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20239. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20240. };
  20241. OculusGamepadCamera.prototype.detachControl = function (element) {
  20242. _super.prototype.detachControl.call(this, element);
  20243. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20244. };
  20245. OculusGamepadCamera.prototype.dispose = function () {
  20246. this._gamepads.dispose();
  20247. _super.prototype.dispose.call(this);
  20248. };
  20249. return OculusGamepadCamera;
  20250. })(BABYLON.FreeCamera);
  20251. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20252. })(BABYLON || (BABYLON = {}));
  20253. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20254. var BABYLON;
  20255. (function (BABYLON) {
  20256. // We're mainly based on the logic defined into the FreeCamera code
  20257. var VirtualJoysticksCamera = (function (_super) {
  20258. __extends(VirtualJoysticksCamera, _super);
  20259. function VirtualJoysticksCamera(name, position, scene) {
  20260. _super.call(this, name, position, scene);
  20261. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20262. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20263. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20264. this._leftjoystick.setJoystickSensibility(0.15);
  20265. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20266. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20267. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20268. this._rightjoystick.reverseUpDown = true;
  20269. this._rightjoystick.setJoystickSensibility(0.05);
  20270. this._rightjoystick.setJoystickColor("yellow");
  20271. }
  20272. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20273. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20274. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20275. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20276. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20277. if (!this._leftjoystick.pressed) {
  20278. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20279. }
  20280. if (!this._rightjoystick.pressed) {
  20281. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20282. }
  20283. };
  20284. VirtualJoysticksCamera.prototype.dispose = function () {
  20285. this._leftjoystick.releaseCanvas();
  20286. _super.prototype.dispose.call(this);
  20287. };
  20288. return VirtualJoysticksCamera;
  20289. })(BABYLON.FreeCamera);
  20290. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20291. })(BABYLON || (BABYLON = {}));
  20292. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20293. var BABYLON;
  20294. (function (BABYLON) {
  20295. var ShaderMaterial = (function (_super) {
  20296. __extends(ShaderMaterial, _super);
  20297. function ShaderMaterial(name, scene, shaderPath, options) {
  20298. _super.call(this, name, scene);
  20299. this._textures = new Array();
  20300. this._floats = new Array();
  20301. this._floatsArrays = {};
  20302. this._colors3 = new Array();
  20303. this._colors4 = new Array();
  20304. this._vectors2 = new Array();
  20305. this._vectors3 = new Array();
  20306. this._matrices = new Array();
  20307. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20308. this._shaderPath = shaderPath;
  20309. options.needAlphaBlending = options.needAlphaBlending || false;
  20310. options.needAlphaTesting = options.needAlphaTesting || false;
  20311. options.attributes = options.attributes || ["position", "normal", "uv"];
  20312. options.uniforms = options.uniforms || ["worldViewProjection"];
  20313. options.samplers = options.samplers || [];
  20314. this._options = options;
  20315. }
  20316. ShaderMaterial.prototype.needAlphaBlending = function () {
  20317. return this._options.needAlphaBlending;
  20318. };
  20319. ShaderMaterial.prototype.needAlphaTesting = function () {
  20320. return this._options.needAlphaTesting;
  20321. };
  20322. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20323. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20324. this._options.uniforms.push(uniformName);
  20325. }
  20326. };
  20327. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20328. if (this._options.samplers.indexOf(name) === -1) {
  20329. this._options.samplers.push(name);
  20330. }
  20331. this._textures[name] = texture;
  20332. return this;
  20333. };
  20334. ShaderMaterial.prototype.setFloat = function (name, value) {
  20335. this._checkUniform(name);
  20336. this._floats[name] = value;
  20337. return this;
  20338. };
  20339. ShaderMaterial.prototype.setFloats = function (name, value) {
  20340. this._checkUniform(name);
  20341. this._floatsArrays[name] = value;
  20342. return this;
  20343. };
  20344. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20345. this._checkUniform(name);
  20346. this._colors3[name] = value;
  20347. return this;
  20348. };
  20349. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20350. this._checkUniform(name);
  20351. this._colors4[name] = value;
  20352. return this;
  20353. };
  20354. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20355. this._checkUniform(name);
  20356. this._vectors2[name] = value;
  20357. return this;
  20358. };
  20359. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20360. this._checkUniform(name);
  20361. this._vectors3[name] = value;
  20362. return this;
  20363. };
  20364. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20365. this._checkUniform(name);
  20366. this._matrices[name] = value;
  20367. return this;
  20368. };
  20369. ShaderMaterial.prototype.isReady = function () {
  20370. var scene = this.getScene();
  20371. var engine = scene.getEngine();
  20372. if (!this.checkReadyOnEveryCall) {
  20373. if (this._renderId === scene.getRenderId()) {
  20374. return true;
  20375. }
  20376. }
  20377. var previousEffect = this._effect;
  20378. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20379. if (!this._effect.isReady()) {
  20380. return false;
  20381. }
  20382. if (previousEffect !== this._effect) {
  20383. scene.resetCachedMaterial();
  20384. }
  20385. this._renderId = scene.getRenderId();
  20386. return true;
  20387. };
  20388. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  20389. var scene = this.getScene();
  20390. if (this._options.uniforms.indexOf("world") !== -1) {
  20391. this._effect.setMatrix("world", world);
  20392. }
  20393. if (this._options.uniforms.indexOf("worldView") !== -1) {
  20394. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  20395. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  20396. }
  20397. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  20398. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  20399. }
  20400. };
  20401. ShaderMaterial.prototype.bind = function (world) {
  20402. // Std values
  20403. this.bindOnlyWorldMatrix(world);
  20404. if (this.getScene().getCachedMaterial() !== this) {
  20405. if (this._options.uniforms.indexOf("view") !== -1) {
  20406. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  20407. }
  20408. if (this._options.uniforms.indexOf("projection") !== -1) {
  20409. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  20410. }
  20411. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  20412. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  20413. }
  20414. for (var name in this._textures) {
  20415. this._effect.setTexture(name, this._textures[name]);
  20416. }
  20417. for (name in this._floats) {
  20418. this._effect.setFloat(name, this._floats[name]);
  20419. }
  20420. for (name in this._floatsArrays) {
  20421. this._effect.setArray(name, this._floatsArrays[name]);
  20422. }
  20423. for (name in this._colors3) {
  20424. this._effect.setColor3(name, this._colors3[name]);
  20425. }
  20426. for (name in this._colors4) {
  20427. var color = this._colors4[name];
  20428. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20429. }
  20430. for (name in this._vectors2) {
  20431. this._effect.setVector2(name, this._vectors2[name]);
  20432. }
  20433. for (name in this._vectors3) {
  20434. this._effect.setVector3(name, this._vectors3[name]);
  20435. }
  20436. for (name in this._matrices) {
  20437. this._effect.setMatrix(name, this._matrices[name]);
  20438. }
  20439. }
  20440. _super.prototype.bind.call(this, world, null);
  20441. };
  20442. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20443. for (var name in this._textures) {
  20444. this._textures[name].dispose();
  20445. }
  20446. this._textures = [];
  20447. _super.prototype.dispose.call(this, forceDisposeEffect);
  20448. };
  20449. return ShaderMaterial;
  20450. })(BABYLON.Material);
  20451. BABYLON.ShaderMaterial = ShaderMaterial;
  20452. })(BABYLON || (BABYLON = {}));
  20453. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20454. (function (BABYLON) {
  20455. var VertexData = (function () {
  20456. function VertexData() {
  20457. }
  20458. VertexData.prototype.set = function (data, kind) {
  20459. switch (kind) {
  20460. case BABYLON.VertexBuffer.PositionKind:
  20461. this.positions = data;
  20462. break;
  20463. case BABYLON.VertexBuffer.NormalKind:
  20464. this.normals = data;
  20465. break;
  20466. case BABYLON.VertexBuffer.UVKind:
  20467. this.uvs = data;
  20468. break;
  20469. case BABYLON.VertexBuffer.UV2Kind:
  20470. this.uv2s = data;
  20471. break;
  20472. case BABYLON.VertexBuffer.ColorKind:
  20473. this.colors = data;
  20474. break;
  20475. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20476. this.matricesIndices = data;
  20477. break;
  20478. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20479. this.matricesWeights = data;
  20480. break;
  20481. }
  20482. };
  20483. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20484. this._applyTo(mesh, updatable);
  20485. };
  20486. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20487. this._applyTo(geometry, updatable);
  20488. };
  20489. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20490. this._update(mesh);
  20491. };
  20492. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20493. this._update(geometry);
  20494. };
  20495. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20496. if (this.positions) {
  20497. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20498. }
  20499. if (this.normals) {
  20500. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20501. }
  20502. if (this.uvs) {
  20503. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20504. }
  20505. if (this.uv2s) {
  20506. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20507. }
  20508. if (this.colors) {
  20509. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20510. }
  20511. if (this.matricesIndices) {
  20512. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20513. }
  20514. if (this.matricesWeights) {
  20515. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20516. }
  20517. if (this.indices) {
  20518. meshOrGeometry.setIndices(this.indices);
  20519. }
  20520. };
  20521. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20522. if (this.positions) {
  20523. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20524. }
  20525. if (this.normals) {
  20526. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20527. }
  20528. if (this.uvs) {
  20529. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20530. }
  20531. if (this.uv2s) {
  20532. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20533. }
  20534. if (this.colors) {
  20535. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20536. }
  20537. if (this.matricesIndices) {
  20538. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20539. }
  20540. if (this.matricesWeights) {
  20541. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20542. }
  20543. if (this.indices) {
  20544. meshOrGeometry.setIndices(this.indices);
  20545. }
  20546. };
  20547. VertexData.prototype.transform = function (matrix) {
  20548. var transformed = BABYLON.Vector3.Zero();
  20549. if (this.positions) {
  20550. var position = BABYLON.Vector3.Zero();
  20551. for (var index = 0; index < this.positions.length; index += 3) {
  20552. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20553. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20554. this.positions[index] = transformed.x;
  20555. this.positions[index + 1] = transformed.y;
  20556. this.positions[index + 2] = transformed.z;
  20557. }
  20558. }
  20559. if (this.normals) {
  20560. var normal = BABYLON.Vector3.Zero();
  20561. for (index = 0; index < this.normals.length; index += 3) {
  20562. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20563. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20564. this.normals[index] = transformed.x;
  20565. this.normals[index + 1] = transformed.y;
  20566. this.normals[index + 2] = transformed.z;
  20567. }
  20568. }
  20569. };
  20570. VertexData.prototype.merge = function (other) {
  20571. if (other.indices) {
  20572. if (!this.indices) {
  20573. this.indices = [];
  20574. }
  20575. var offset = this.positions ? this.positions.length / 3 : 0;
  20576. for (var index = 0; index < other.indices.length; index++) {
  20577. this.indices.push(other.indices[index] + offset);
  20578. }
  20579. }
  20580. if (other.positions) {
  20581. if (!this.positions) {
  20582. this.positions = [];
  20583. }
  20584. for (index = 0; index < other.positions.length; index++) {
  20585. this.positions.push(other.positions[index]);
  20586. }
  20587. }
  20588. if (other.normals) {
  20589. if (!this.normals) {
  20590. this.normals = [];
  20591. }
  20592. for (index = 0; index < other.normals.length; index++) {
  20593. this.normals.push(other.normals[index]);
  20594. }
  20595. }
  20596. if (other.uvs) {
  20597. if (!this.uvs) {
  20598. this.uvs = [];
  20599. }
  20600. for (index = 0; index < other.uvs.length; index++) {
  20601. this.uvs.push(other.uvs[index]);
  20602. }
  20603. }
  20604. if (other.uv2s) {
  20605. if (!this.uv2s) {
  20606. this.uv2s = [];
  20607. }
  20608. for (index = 0; index < other.uv2s.length; index++) {
  20609. this.uv2s.push(other.uv2s[index]);
  20610. }
  20611. }
  20612. if (other.matricesIndices) {
  20613. if (!this.matricesIndices) {
  20614. this.matricesIndices = [];
  20615. }
  20616. for (index = 0; index < other.matricesIndices.length; index++) {
  20617. this.matricesIndices.push(other.matricesIndices[index]);
  20618. }
  20619. }
  20620. if (other.matricesWeights) {
  20621. if (!this.matricesWeights) {
  20622. this.matricesWeights = [];
  20623. }
  20624. for (index = 0; index < other.matricesWeights.length; index++) {
  20625. this.matricesWeights.push(other.matricesWeights[index]);
  20626. }
  20627. }
  20628. if (other.colors) {
  20629. if (!this.colors) {
  20630. this.colors = [];
  20631. }
  20632. for (index = 0; index < other.colors.length; index++) {
  20633. this.colors.push(other.colors[index]);
  20634. }
  20635. }
  20636. };
  20637. // Statics
  20638. VertexData.ExtractFromMesh = function (mesh) {
  20639. return VertexData._ExtractFrom(mesh);
  20640. };
  20641. VertexData.ExtractFromGeometry = function (geometry) {
  20642. return VertexData._ExtractFrom(geometry);
  20643. };
  20644. VertexData._ExtractFrom = function (meshOrGeometry) {
  20645. var result = new BABYLON.VertexData();
  20646. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20647. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20648. }
  20649. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20650. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20651. }
  20652. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20653. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20654. }
  20655. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20656. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20657. }
  20658. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20659. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20660. }
  20661. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20662. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20663. }
  20664. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20665. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20666. }
  20667. result.indices = meshOrGeometry.getIndices();
  20668. return result;
  20669. };
  20670. VertexData.CreateBox = function (size) {
  20671. var normalsSource = [
  20672. new BABYLON.Vector3(0, 0, 1),
  20673. new BABYLON.Vector3(0, 0, -1),
  20674. new BABYLON.Vector3(1, 0, 0),
  20675. new BABYLON.Vector3(-1, 0, 0),
  20676. new BABYLON.Vector3(0, 1, 0),
  20677. new BABYLON.Vector3(0, -1, 0)
  20678. ];
  20679. var indices = [];
  20680. var positions = [];
  20681. var normals = [];
  20682. var uvs = [];
  20683. size = size || 1;
  20684. for (var index = 0; index < normalsSource.length; index++) {
  20685. var normal = normalsSource[index];
  20686. // Get two vectors perpendicular to the face normal and to each other.
  20687. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20688. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20689. // Six indices (two triangles) per face.
  20690. var verticesLength = positions.length / 3;
  20691. indices.push(verticesLength);
  20692. indices.push(verticesLength + 1);
  20693. indices.push(verticesLength + 2);
  20694. indices.push(verticesLength);
  20695. indices.push(verticesLength + 2);
  20696. indices.push(verticesLength + 3);
  20697. // Four vertices per face.
  20698. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20699. positions.push(vertex.x, vertex.y, vertex.z);
  20700. normals.push(normal.x, normal.y, normal.z);
  20701. uvs.push(1.0, 1.0);
  20702. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20703. positions.push(vertex.x, vertex.y, vertex.z);
  20704. normals.push(normal.x, normal.y, normal.z);
  20705. uvs.push(0.0, 1.0);
  20706. vertex = normal.add(side1).add(side2).scale(size / 2);
  20707. positions.push(vertex.x, vertex.y, vertex.z);
  20708. normals.push(normal.x, normal.y, normal.z);
  20709. uvs.push(0.0, 0.0);
  20710. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20711. positions.push(vertex.x, vertex.y, vertex.z);
  20712. normals.push(normal.x, normal.y, normal.z);
  20713. uvs.push(1.0, 0.0);
  20714. }
  20715. // Result
  20716. var vertexData = new BABYLON.VertexData();
  20717. vertexData.indices = indices;
  20718. vertexData.positions = positions;
  20719. vertexData.normals = normals;
  20720. vertexData.uvs = uvs;
  20721. return vertexData;
  20722. };
  20723. VertexData.CreateSphere = function (segments, diameter) {
  20724. segments = segments || 32;
  20725. diameter = diameter || 1;
  20726. var radius = diameter / 2;
  20727. var totalZRotationSteps = 2 + segments;
  20728. var totalYRotationSteps = 2 * totalZRotationSteps;
  20729. var indices = [];
  20730. var positions = [];
  20731. var normals = [];
  20732. var uvs = [];
  20733. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20734. var normalizedZ = zRotationStep / totalZRotationSteps;
  20735. var angleZ = (normalizedZ * Math.PI);
  20736. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20737. var normalizedY = yRotationStep / totalYRotationSteps;
  20738. var angleY = normalizedY * Math.PI * 2;
  20739. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20740. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20741. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20742. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20743. var vertex = complete.scale(radius);
  20744. var normal = BABYLON.Vector3.Normalize(vertex);
  20745. positions.push(vertex.x, vertex.y, vertex.z);
  20746. normals.push(normal.x, normal.y, normal.z);
  20747. uvs.push(normalizedZ, normalizedY);
  20748. }
  20749. if (zRotationStep > 0) {
  20750. var verticesCount = positions.length / 3;
  20751. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20752. indices.push((firstIndex));
  20753. indices.push((firstIndex + 1));
  20754. indices.push(firstIndex + totalYRotationSteps + 1);
  20755. indices.push((firstIndex + totalYRotationSteps + 1));
  20756. indices.push((firstIndex + 1));
  20757. indices.push((firstIndex + totalYRotationSteps + 2));
  20758. }
  20759. }
  20760. }
  20761. // Result
  20762. var vertexData = new BABYLON.VertexData();
  20763. vertexData.indices = indices;
  20764. vertexData.positions = positions;
  20765. vertexData.normals = normals;
  20766. vertexData.uvs = uvs;
  20767. return vertexData;
  20768. };
  20769. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20770. if (subdivisions === void 0) { subdivisions = 1; }
  20771. var radiusTop = diameterTop / 2;
  20772. var radiusBottom = diameterBottom / 2;
  20773. var indices = [];
  20774. var positions = [];
  20775. var normals = [];
  20776. var uvs = [];
  20777. height = height || 1;
  20778. diameterTop = diameterTop || 0.5;
  20779. diameterBottom = diameterBottom || 1;
  20780. tessellation = tessellation || 16;
  20781. subdivisions = subdivisions || 1;
  20782. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20783. var getCircleVector = function (i) {
  20784. var angle = (i * 2.0 * Math.PI / tessellation);
  20785. var dx = Math.cos(angle);
  20786. var dz = Math.sin(angle);
  20787. return new BABYLON.Vector3(dx, 0, dz);
  20788. };
  20789. var createCylinderCap = function (isTop) {
  20790. var radius = isTop ? radiusTop : radiusBottom;
  20791. if (radius == 0) {
  20792. return;
  20793. }
  20794. var vbase = positions.length / 3;
  20795. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20796. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20797. if (!isTop) {
  20798. offset.scaleInPlace(-1);
  20799. textureScale.x = -textureScale.x;
  20800. }
  20801. for (i = 0; i < tessellation; i++) {
  20802. var circleVector = getCircleVector(i);
  20803. var position = circleVector.scale(radius).add(offset);
  20804. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20805. positions.push(position.x, position.y, position.z);
  20806. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20807. }
  20808. for (var i = 0; i < tessellation - 2; i++) {
  20809. if (!isTop) {
  20810. indices.push(vbase);
  20811. indices.push(vbase + (i + 2) % tessellation);
  20812. indices.push(vbase + (i + 1) % tessellation);
  20813. }
  20814. else {
  20815. indices.push(vbase);
  20816. indices.push(vbase + (i + 1) % tessellation);
  20817. indices.push(vbase + (i + 2) % tessellation);
  20818. }
  20819. }
  20820. };
  20821. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20822. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20823. var stride = tessellation + 1;
  20824. for (var i = 0; i <= tessellation; i++) {
  20825. var circleVector = getCircleVector(i);
  20826. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20827. var position, radius = radiusBottom;
  20828. for (var s = 0; s <= subdivisions; s++) {
  20829. // Update variables
  20830. position = circleVector.scale(radius);
  20831. position.addInPlace(base.add(offset.scale(s)));
  20832. textureCoordinate.y += 1 / subdivisions;
  20833. radius += (radiusTop - radiusBottom) / subdivisions;
  20834. // Push in arrays
  20835. positions.push(position.x, position.y, position.z);
  20836. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20837. }
  20838. }
  20839. subdivisions += 1;
  20840. for (var s = 0; s < subdivisions - 1; s++) {
  20841. for (var i = 0; i <= tessellation; i++) {
  20842. indices.push(i * subdivisions + s);
  20843. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20844. indices.push(i * subdivisions + (s + 1));
  20845. indices.push(i * subdivisions + (s + 1));
  20846. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20847. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20848. }
  20849. }
  20850. // Create flat triangle fan caps to seal the top and bottom.
  20851. createCylinderCap(true);
  20852. createCylinderCap(false);
  20853. // Normals
  20854. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20855. // Result
  20856. var vertexData = new BABYLON.VertexData();
  20857. vertexData.indices = indices;
  20858. vertexData.positions = positions;
  20859. vertexData.normals = normals;
  20860. vertexData.uvs = uvs;
  20861. return vertexData;
  20862. };
  20863. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20864. var indices = [];
  20865. var positions = [];
  20866. var normals = [];
  20867. var uvs = [];
  20868. diameter = diameter || 1;
  20869. thickness = thickness || 0.5;
  20870. tessellation = tessellation || 16;
  20871. var stride = tessellation + 1;
  20872. for (var i = 0; i <= tessellation; i++) {
  20873. var u = i / tessellation;
  20874. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20875. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20876. for (var j = 0; j <= tessellation; j++) {
  20877. var v = 1 - j / tessellation;
  20878. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20879. var dx = Math.cos(innerAngle);
  20880. var dy = Math.sin(innerAngle);
  20881. // Create a vertex.
  20882. var normal = new BABYLON.Vector3(dx, dy, 0);
  20883. var position = normal.scale(thickness / 2);
  20884. var textureCoordinate = new BABYLON.Vector2(u, v);
  20885. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20886. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20887. positions.push(position.x, position.y, position.z);
  20888. normals.push(normal.x, normal.y, normal.z);
  20889. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20890. // And create indices for two triangles.
  20891. var nextI = (i + 1) % stride;
  20892. var nextJ = (j + 1) % stride;
  20893. indices.push(i * stride + j);
  20894. indices.push(i * stride + nextJ);
  20895. indices.push(nextI * stride + j);
  20896. indices.push(i * stride + nextJ);
  20897. indices.push(nextI * stride + nextJ);
  20898. indices.push(nextI * stride + j);
  20899. }
  20900. }
  20901. // Result
  20902. var vertexData = new BABYLON.VertexData();
  20903. vertexData.indices = indices;
  20904. vertexData.positions = positions;
  20905. vertexData.normals = normals;
  20906. vertexData.uvs = uvs;
  20907. return vertexData;
  20908. };
  20909. VertexData.CreateLines = function (points) {
  20910. var indices = [];
  20911. var positions = [];
  20912. for (var index = 0; index < points.length; index++) {
  20913. positions.push(points[index].x, points[index].y, points[index].z);
  20914. if (index > 0) {
  20915. indices.push(index - 1);
  20916. indices.push(index);
  20917. }
  20918. }
  20919. // Result
  20920. var vertexData = new BABYLON.VertexData();
  20921. vertexData.indices = indices;
  20922. vertexData.positions = positions;
  20923. return vertexData;
  20924. };
  20925. VertexData.CreateGround = function (width, height, subdivisions) {
  20926. var indices = [];
  20927. var positions = [];
  20928. var normals = [];
  20929. var uvs = [];
  20930. var row, col;
  20931. width = width || 1;
  20932. height = height || 1;
  20933. subdivisions = subdivisions || 1;
  20934. for (row = 0; row <= subdivisions; row++) {
  20935. for (col = 0; col <= subdivisions; col++) {
  20936. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20937. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20938. positions.push(position.x, position.y, position.z);
  20939. normals.push(normal.x, normal.y, normal.z);
  20940. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20941. }
  20942. }
  20943. for (row = 0; row < subdivisions; row++) {
  20944. for (col = 0; col < subdivisions; col++) {
  20945. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20946. indices.push(col + 1 + row * (subdivisions + 1));
  20947. indices.push(col + row * (subdivisions + 1));
  20948. indices.push(col + (row + 1) * (subdivisions + 1));
  20949. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20950. indices.push(col + row * (subdivisions + 1));
  20951. }
  20952. }
  20953. // Result
  20954. var vertexData = new BABYLON.VertexData();
  20955. vertexData.indices = indices;
  20956. vertexData.positions = positions;
  20957. vertexData.normals = normals;
  20958. vertexData.uvs = uvs;
  20959. return vertexData;
  20960. };
  20961. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  20962. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  20963. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  20964. var indices = [];
  20965. var positions = [];
  20966. var normals = [];
  20967. var uvs = [];
  20968. var row, col, tileRow, tileCol;
  20969. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  20970. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  20971. precision.w = (precision.w < 1) ? 1 : precision.w;
  20972. precision.h = (precision.h < 1) ? 1 : precision.h;
  20973. var tileSize = {
  20974. 'w': (xmax - xmin) / subdivisions.w,
  20975. 'h': (zmax - zmin) / subdivisions.h
  20976. };
  20977. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  20978. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  20979. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  20980. }
  20981. }
  20982. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  20983. // Indices
  20984. var base = positions.length / 3;
  20985. var rowLength = precision.w + 1;
  20986. for (row = 0; row < precision.h; row++) {
  20987. for (col = 0; col < precision.w; col++) {
  20988. var square = [
  20989. base + col + row * rowLength,
  20990. base + (col + 1) + row * rowLength,
  20991. base + (col + 1) + (row + 1) * rowLength,
  20992. base + col + (row + 1) * rowLength
  20993. ];
  20994. indices.push(square[1]);
  20995. indices.push(square[2]);
  20996. indices.push(square[3]);
  20997. indices.push(square[0]);
  20998. indices.push(square[1]);
  20999. indices.push(square[3]);
  21000. }
  21001. }
  21002. // Position, normals and uvs
  21003. var position = BABYLON.Vector3.Zero();
  21004. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21005. for (row = 0; row <= precision.h; row++) {
  21006. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21007. for (col = 0; col <= precision.w; col++) {
  21008. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21009. position.y = 0;
  21010. positions.push(position.x, position.y, position.z);
  21011. normals.push(normal.x, normal.y, normal.z);
  21012. uvs.push(col / precision.w, row / precision.h);
  21013. }
  21014. }
  21015. }
  21016. // Result
  21017. var vertexData = new BABYLON.VertexData();
  21018. vertexData.indices = indices;
  21019. vertexData.positions = positions;
  21020. vertexData.normals = normals;
  21021. vertexData.uvs = uvs;
  21022. return vertexData;
  21023. };
  21024. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21025. var indices = [];
  21026. var positions = [];
  21027. var normals = [];
  21028. var uvs = [];
  21029. var row, col;
  21030. for (row = 0; row <= subdivisions; row++) {
  21031. for (col = 0; col <= subdivisions; col++) {
  21032. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21033. // Compute height
  21034. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21035. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21036. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21037. var r = buffer[pos] / 255.0;
  21038. var g = buffer[pos + 1] / 255.0;
  21039. var b = buffer[pos + 2] / 255.0;
  21040. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21041. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21042. // Add vertex
  21043. positions.push(position.x, position.y, position.z);
  21044. normals.push(0, 0, 0);
  21045. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21046. }
  21047. }
  21048. for (row = 0; row < subdivisions; row++) {
  21049. for (col = 0; col < subdivisions; col++) {
  21050. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21051. indices.push(col + 1 + row * (subdivisions + 1));
  21052. indices.push(col + row * (subdivisions + 1));
  21053. indices.push(col + (row + 1) * (subdivisions + 1));
  21054. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21055. indices.push(col + row * (subdivisions + 1));
  21056. }
  21057. }
  21058. // Normals
  21059. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21060. // Result
  21061. var vertexData = new BABYLON.VertexData();
  21062. vertexData.indices = indices;
  21063. vertexData.positions = positions;
  21064. vertexData.normals = normals;
  21065. vertexData.uvs = uvs;
  21066. return vertexData;
  21067. };
  21068. VertexData.CreatePlane = function (size) {
  21069. var indices = [];
  21070. var positions = [];
  21071. var normals = [];
  21072. var uvs = [];
  21073. size = size || 1;
  21074. // Vertices
  21075. var halfSize = size / 2.0;
  21076. positions.push(-halfSize, -halfSize, 0);
  21077. normals.push(0, 0, -1.0);
  21078. uvs.push(0.0, 0.0);
  21079. positions.push(halfSize, -halfSize, 0);
  21080. normals.push(0, 0, -1.0);
  21081. uvs.push(1.0, 0.0);
  21082. positions.push(halfSize, halfSize, 0);
  21083. normals.push(0, 0, -1.0);
  21084. uvs.push(1.0, 1.0);
  21085. positions.push(-halfSize, halfSize, 0);
  21086. normals.push(0, 0, -1.0);
  21087. uvs.push(0.0, 1.0);
  21088. // Indices
  21089. indices.push(0);
  21090. indices.push(1);
  21091. indices.push(2);
  21092. indices.push(0);
  21093. indices.push(2);
  21094. indices.push(3);
  21095. // Result
  21096. var vertexData = new BABYLON.VertexData();
  21097. vertexData.indices = indices;
  21098. vertexData.positions = positions;
  21099. vertexData.normals = normals;
  21100. vertexData.uvs = uvs;
  21101. return vertexData;
  21102. };
  21103. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21104. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  21105. var indices = [];
  21106. var positions = [];
  21107. var normals = [];
  21108. var uvs = [];
  21109. radius = radius || 2;
  21110. tube = tube || 0.5;
  21111. radialSegments = radialSegments || 32;
  21112. tubularSegments = tubularSegments || 32;
  21113. p = p || 2;
  21114. q = q || 3;
  21115. // Helper
  21116. var getPos = function (angle) {
  21117. var cu = Math.cos(angle);
  21118. var su = Math.sin(angle);
  21119. var quOverP = q / p * angle;
  21120. var cs = Math.cos(quOverP);
  21121. var tx = radius * (2 + cs) * 0.5 * cu;
  21122. var ty = radius * (2 + cs) * su * 0.5;
  21123. var tz = radius * Math.sin(quOverP) * 0.5;
  21124. return new BABYLON.Vector3(tx, ty, tz);
  21125. };
  21126. for (var i = 0; i <= radialSegments; i++) {
  21127. var modI = i % radialSegments;
  21128. var u = modI / radialSegments * 2 * p * Math.PI;
  21129. var p1 = getPos(u);
  21130. var p2 = getPos(u + 0.01);
  21131. var tang = p2.subtract(p1);
  21132. var n = p2.add(p1);
  21133. var bitan = BABYLON.Vector3.Cross(tang, n);
  21134. n = BABYLON.Vector3.Cross(bitan, tang);
  21135. bitan.normalize();
  21136. n.normalize();
  21137. for (var j = 0; j < tubularSegments; j++) {
  21138. var modJ = j % tubularSegments;
  21139. var v = modJ / tubularSegments * 2 * Math.PI;
  21140. var cx = -tube * Math.cos(v);
  21141. var cy = tube * Math.sin(v);
  21142. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21143. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21144. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21145. uvs.push(i / radialSegments);
  21146. uvs.push(j / tubularSegments);
  21147. }
  21148. }
  21149. for (i = 0; i < radialSegments; i++) {
  21150. for (j = 0; j < tubularSegments; j++) {
  21151. var jNext = (j + 1) % tubularSegments;
  21152. var a = i * tubularSegments + j;
  21153. var b = (i + 1) * tubularSegments + j;
  21154. var c = (i + 1) * tubularSegments + jNext;
  21155. var d = i * tubularSegments + jNext;
  21156. indices.push(d);
  21157. indices.push(b);
  21158. indices.push(a);
  21159. indices.push(d);
  21160. indices.push(c);
  21161. indices.push(b);
  21162. }
  21163. }
  21164. // Normals
  21165. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21166. // Result
  21167. var vertexData = new BABYLON.VertexData();
  21168. vertexData.indices = indices;
  21169. vertexData.positions = positions;
  21170. vertexData.normals = normals;
  21171. vertexData.uvs = uvs;
  21172. return vertexData;
  21173. };
  21174. // Tools
  21175. VertexData.ComputeNormals = function (positions, indices, normals) {
  21176. var positionVectors = [];
  21177. var facesOfVertices = [];
  21178. var index;
  21179. for (index = 0; index < positions.length; index += 3) {
  21180. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21181. positionVectors.push(vector3);
  21182. facesOfVertices.push([]);
  21183. }
  21184. // Compute normals
  21185. var facesNormals = [];
  21186. for (index = 0; index < indices.length / 3; index++) {
  21187. var i1 = indices[index * 3];
  21188. var i2 = indices[index * 3 + 1];
  21189. var i3 = indices[index * 3 + 2];
  21190. var p1 = positionVectors[i1];
  21191. var p2 = positionVectors[i2];
  21192. var p3 = positionVectors[i3];
  21193. var p1p2 = p1.subtract(p2);
  21194. var p3p2 = p3.subtract(p2);
  21195. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21196. facesOfVertices[i1].push(index);
  21197. facesOfVertices[i2].push(index);
  21198. facesOfVertices[i3].push(index);
  21199. }
  21200. for (index = 0; index < positionVectors.length; index++) {
  21201. var faces = facesOfVertices[index];
  21202. var normal = BABYLON.Vector3.Zero();
  21203. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21204. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21205. }
  21206. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21207. normals[index * 3] = normal.x;
  21208. normals[index * 3 + 1] = normal.y;
  21209. normals[index * 3 + 2] = normal.z;
  21210. }
  21211. };
  21212. return VertexData;
  21213. })();
  21214. BABYLON.VertexData = VertexData;
  21215. })(BABYLON || (BABYLON = {}));
  21216. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  21217. var BABYLON;
  21218. (function (BABYLON) {
  21219. var buildCamera = function (that, name) {
  21220. that._leftCamera.isIntermediate = true;
  21221. that.subCameras.push(that._leftCamera);
  21222. that.subCameras.push(that._rightCamera);
  21223. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  21224. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  21225. that._anaglyphPostProcess.onApply = function (effect) {
  21226. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  21227. };
  21228. that._update();
  21229. };
  21230. var AnaglyphArcRotateCamera = (function (_super) {
  21231. __extends(AnaglyphArcRotateCamera, _super);
  21232. // ANY
  21233. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  21234. _super.call(this, name, alpha, beta, radius, target, scene);
  21235. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21236. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  21237. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  21238. buildCamera(this, name);
  21239. }
  21240. AnaglyphArcRotateCamera.prototype._update = function () {
  21241. this._updateCamera(this._leftCamera);
  21242. this._updateCamera(this._rightCamera);
  21243. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  21244. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  21245. _super.prototype._update.call(this);
  21246. };
  21247. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  21248. camera.beta = this.beta;
  21249. camera.radius = this.radius;
  21250. camera.minZ = this.minZ;
  21251. camera.maxZ = this.maxZ;
  21252. camera.fov = this.fov;
  21253. camera.target = this.target;
  21254. };
  21255. return AnaglyphArcRotateCamera;
  21256. })(BABYLON.ArcRotateCamera);
  21257. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  21258. var AnaglyphFreeCamera = (function (_super) {
  21259. __extends(AnaglyphFreeCamera, _super);
  21260. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  21261. _super.call(this, name, position, scene);
  21262. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  21263. this._transformMatrix = new BABYLON.Matrix();
  21264. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  21265. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  21266. buildCamera(this, name);
  21267. }
  21268. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  21269. var target = this.getTarget();
  21270. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  21271. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  21272. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  21273. };
  21274. AnaglyphFreeCamera.prototype._update = function () {
  21275. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  21276. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  21277. this._updateCamera(this._leftCamera);
  21278. this._updateCamera(this._rightCamera);
  21279. _super.prototype._update.call(this);
  21280. };
  21281. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  21282. camera.minZ = this.minZ;
  21283. camera.maxZ = this.maxZ;
  21284. camera.fov = this.fov;
  21285. camera.viewport = this.viewport;
  21286. camera.setTarget(this.getTarget());
  21287. };
  21288. return AnaglyphFreeCamera;
  21289. })(BABYLON.FreeCamera);
  21290. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  21291. })(BABYLON || (BABYLON = {}));
  21292. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  21293. var BABYLON;
  21294. (function (BABYLON) {
  21295. var AnaglyphPostProcess = (function (_super) {
  21296. __extends(AnaglyphPostProcess, _super);
  21297. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21298. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  21299. }
  21300. return AnaglyphPostProcess;
  21301. })(BABYLON.PostProcess);
  21302. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  21303. })(BABYLON || (BABYLON = {}));
  21304. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  21305. (function (BABYLON) {
  21306. var Tags = (function () {
  21307. function Tags() {
  21308. }
  21309. Tags.EnableFor = function (obj) {
  21310. obj._tags = obj._tags || {};
  21311. obj.hasTags = function () {
  21312. return Tags.HasTags(obj);
  21313. };
  21314. obj.addTags = function (tagsString) {
  21315. return Tags.AddTagsTo(obj, tagsString);
  21316. };
  21317. obj.removeTags = function (tagsString) {
  21318. return Tags.RemoveTagsFrom(obj, tagsString);
  21319. };
  21320. obj.matchesTagsQuery = function (tagsQuery) {
  21321. return Tags.MatchesQuery(obj, tagsQuery);
  21322. };
  21323. };
  21324. Tags.DisableFor = function (obj) {
  21325. delete obj._tags;
  21326. delete obj.hasTags;
  21327. delete obj.addTags;
  21328. delete obj.removeTags;
  21329. delete obj.matchesTagsQuery;
  21330. };
  21331. Tags.HasTags = function (obj) {
  21332. if (!obj._tags) {
  21333. return false;
  21334. }
  21335. return !BABYLON.Tools.IsEmpty(obj._tags);
  21336. };
  21337. Tags.GetTags = function (obj) {
  21338. if (!obj._tags) {
  21339. return null;
  21340. }
  21341. return obj._tags;
  21342. };
  21343. // the tags 'true' and 'false' are reserved and cannot be used as tags
  21344. // a tag cannot start with '||', '&&', and '!'
  21345. // it cannot contain whitespaces
  21346. Tags.AddTagsTo = function (obj, tagsString) {
  21347. if (!tagsString) {
  21348. return;
  21349. }
  21350. var tags = tagsString.split(" ");
  21351. for (var t in tags) {
  21352. Tags._AddTagTo(obj, tags[t]);
  21353. }
  21354. };
  21355. Tags._AddTagTo = function (obj, tag) {
  21356. tag = tag.trim();
  21357. if (tag === "" || tag === "true" || tag === "false") {
  21358. return;
  21359. }
  21360. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  21361. return;
  21362. }
  21363. Tags.EnableFor(obj);
  21364. obj._tags[tag] = true;
  21365. };
  21366. Tags.RemoveTagsFrom = function (obj, tagsString) {
  21367. if (!Tags.HasTags(obj)) {
  21368. return;
  21369. }
  21370. var tags = tagsString.split(" ");
  21371. for (var t in tags) {
  21372. Tags._RemoveTagFrom(obj, tags[t]);
  21373. }
  21374. };
  21375. Tags._RemoveTagFrom = function (obj, tag) {
  21376. delete obj._tags[tag];
  21377. };
  21378. Tags.MatchesQuery = function (obj, tagsQuery) {
  21379. if (tagsQuery === undefined) {
  21380. return true;
  21381. }
  21382. if (tagsQuery === "") {
  21383. return Tags.HasTags(obj);
  21384. }
  21385. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  21386. };
  21387. return Tags;
  21388. })();
  21389. BABYLON.Tags = Tags;
  21390. })(BABYLON || (BABYLON = {}));
  21391. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  21392. (function (BABYLON) {
  21393. var Internals;
  21394. (function (Internals) {
  21395. var AndOrNotEvaluator = (function () {
  21396. function AndOrNotEvaluator() {
  21397. }
  21398. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  21399. if (!query.match(/\([^\(\)]*\)/g)) {
  21400. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  21401. }
  21402. else {
  21403. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  21404. // remove parenthesis
  21405. r = r.slice(1, r.length - 1);
  21406. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  21407. });
  21408. }
  21409. if (query === "true") {
  21410. return true;
  21411. }
  21412. if (query === "false") {
  21413. return false;
  21414. }
  21415. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  21416. };
  21417. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  21418. evaluateCallback = evaluateCallback || (function (r) {
  21419. return r === "true" ? true : false;
  21420. });
  21421. var result;
  21422. var or = parenthesisContent.split("||");
  21423. for (var i in or) {
  21424. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21425. var and = ori.split("&&");
  21426. if (and.length > 1) {
  21427. for (var j = 0; j < and.length; ++j) {
  21428. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21429. if (andj !== "true" && andj !== "false") {
  21430. if (andj[0] === "!") {
  21431. result = !evaluateCallback(andj.substring(1));
  21432. }
  21433. else {
  21434. result = evaluateCallback(andj);
  21435. }
  21436. }
  21437. else {
  21438. result = andj === "true" ? true : false;
  21439. }
  21440. if (!result) {
  21441. ori = "false";
  21442. break;
  21443. }
  21444. }
  21445. }
  21446. if (result || ori === "true") {
  21447. result = true;
  21448. break;
  21449. }
  21450. // result equals false (or undefined)
  21451. if (ori !== "true" && ori !== "false") {
  21452. if (ori[0] === "!") {
  21453. result = !evaluateCallback(ori.substring(1));
  21454. }
  21455. else {
  21456. result = evaluateCallback(ori);
  21457. }
  21458. }
  21459. else {
  21460. result = ori === "true" ? true : false;
  21461. }
  21462. }
  21463. // the whole parenthesis scope is replaced by 'true' or 'false'
  21464. return result ? "true" : "false";
  21465. };
  21466. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21467. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21468. // remove whitespaces
  21469. r = r.replace(/[\s]/g, function () { return ""; });
  21470. return r.length % 2 ? "!" : "";
  21471. });
  21472. booleanString = booleanString.trim();
  21473. if (booleanString === "!true") {
  21474. booleanString = "false";
  21475. }
  21476. else if (booleanString === "!false") {
  21477. booleanString = "true";
  21478. }
  21479. return booleanString;
  21480. };
  21481. return AndOrNotEvaluator;
  21482. })();
  21483. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21484. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21485. })(BABYLON || (BABYLON = {}));
  21486. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21487. (function (BABYLON) {
  21488. var PostProcessRenderPass = (function () {
  21489. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21490. this._enabled = true;
  21491. this._refCount = 0;
  21492. this._name = name;
  21493. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21494. this.setRenderList(renderList);
  21495. this._renderTexture.onBeforeRender = beforeRender;
  21496. this._renderTexture.onAfterRender = afterRender;
  21497. this._scene = scene;
  21498. this._renderList = renderList;
  21499. }
  21500. // private
  21501. PostProcessRenderPass.prototype._incRefCount = function () {
  21502. if (this._refCount === 0) {
  21503. this._scene.customRenderTargets.push(this._renderTexture);
  21504. }
  21505. return ++this._refCount;
  21506. };
  21507. PostProcessRenderPass.prototype._decRefCount = function () {
  21508. this._refCount--;
  21509. if (this._refCount <= 0) {
  21510. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21511. }
  21512. return this._refCount;
  21513. };
  21514. PostProcessRenderPass.prototype._update = function () {
  21515. this.setRenderList(this._renderList);
  21516. };
  21517. // public
  21518. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21519. this._renderTexture.renderList = renderList;
  21520. };
  21521. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21522. return this._renderTexture;
  21523. };
  21524. return PostProcessRenderPass;
  21525. })();
  21526. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21527. })(BABYLON || (BABYLON = {}));
  21528. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21529. (function (BABYLON) {
  21530. var PostProcessRenderEffect = (function () {
  21531. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21532. this._engine = engine;
  21533. this._name = name;
  21534. this._singleInstance = singleInstance || true;
  21535. this._getPostProcess = getPostProcess;
  21536. this._cameras = [];
  21537. this._indicesForCamera = [];
  21538. this._postProcesses = {};
  21539. this._renderPasses = {};
  21540. this._renderEffectAsPasses = {};
  21541. }
  21542. PostProcessRenderEffect.prototype._update = function () {
  21543. for (var renderPassName in this._renderPasses) {
  21544. this._renderPasses[renderPassName]._update();
  21545. }
  21546. };
  21547. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21548. this._renderPasses[renderPass._name] = renderPass;
  21549. this._linkParameters();
  21550. };
  21551. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21552. delete this._renderPasses[renderPass._name];
  21553. this._linkParameters();
  21554. };
  21555. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21556. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21557. this._linkParameters();
  21558. };
  21559. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21560. for (var renderPassName in this._renderPasses) {
  21561. if (renderPassName === passName) {
  21562. return this._renderPasses[passName];
  21563. }
  21564. }
  21565. };
  21566. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21567. this._renderPasses = {};
  21568. this._linkParameters();
  21569. };
  21570. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21571. var cameraKey;
  21572. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21573. for (var i = 0; i < _cam.length; i++) {
  21574. var camera = _cam[i];
  21575. var cameraName = camera.name;
  21576. if (this._singleInstance) {
  21577. cameraKey = 0;
  21578. }
  21579. else {
  21580. cameraKey = cameraName;
  21581. }
  21582. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21583. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21584. if (!this._indicesForCamera[cameraName]) {
  21585. this._indicesForCamera[cameraName] = [];
  21586. }
  21587. this._indicesForCamera[cameraName].push(index);
  21588. if (this._cameras.indexOf(camera) === -1) {
  21589. this._cameras[cameraName] = camera;
  21590. }
  21591. for (var passName in this._renderPasses) {
  21592. this._renderPasses[passName]._incRefCount();
  21593. }
  21594. }
  21595. this._linkParameters();
  21596. };
  21597. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21598. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21599. for (var i = 0; i < _cam.length; i++) {
  21600. var camera = _cam[i];
  21601. var cameraName = camera.name;
  21602. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21603. var index = this._cameras.indexOf(cameraName);
  21604. this._indicesForCamera.splice(index, 1);
  21605. this._cameras.splice(index, 1);
  21606. for (var passName in this._renderPasses) {
  21607. this._renderPasses[passName]._decRefCount();
  21608. }
  21609. }
  21610. };
  21611. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21612. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21613. for (var i = 0; i < _cam.length; i++) {
  21614. var camera = _cam[i];
  21615. var cameraName = camera.name;
  21616. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21617. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21618. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21619. }
  21620. }
  21621. for (var passName in this._renderPasses) {
  21622. this._renderPasses[passName]._incRefCount();
  21623. }
  21624. }
  21625. };
  21626. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21627. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21628. for (var i = 0; i < _cam.length; i++) {
  21629. var camera = _cam[i];
  21630. var cameraName = camera.Name;
  21631. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21632. for (var passName in this._renderPasses) {
  21633. this._renderPasses[passName]._decRefCount();
  21634. }
  21635. }
  21636. };
  21637. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21638. if (this._singleInstance) {
  21639. return this._postProcesses[0];
  21640. }
  21641. else {
  21642. return this._postProcesses[camera.name];
  21643. }
  21644. };
  21645. PostProcessRenderEffect.prototype._linkParameters = function () {
  21646. var _this = this;
  21647. for (var index in this._postProcesses) {
  21648. if (this.applyParameters) {
  21649. this.applyParameters(this._postProcesses[index]);
  21650. }
  21651. this._postProcesses[index].onBeforeRender = function (effect) {
  21652. _this._linkTextures(effect);
  21653. };
  21654. }
  21655. };
  21656. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21657. for (var renderPassName in this._renderPasses) {
  21658. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21659. }
  21660. for (var renderEffectName in this._renderEffectAsPasses) {
  21661. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21662. }
  21663. };
  21664. return PostProcessRenderEffect;
  21665. })();
  21666. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21667. })(BABYLON || (BABYLON = {}));
  21668. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21669. (function (BABYLON) {
  21670. var PostProcessRenderPipeline = (function () {
  21671. function PostProcessRenderPipeline(engine, name) {
  21672. this._engine = engine;
  21673. this._name = name;
  21674. this._renderEffects = {};
  21675. this._renderEffectsForIsolatedPass = {};
  21676. this._cameras = [];
  21677. }
  21678. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21679. this._renderEffects[renderEffect._name] = renderEffect;
  21680. };
  21681. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21682. var renderEffects = this._renderEffects[renderEffectName];
  21683. if (!renderEffects) {
  21684. return;
  21685. }
  21686. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21687. };
  21688. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21689. var renderEffects = this._renderEffects[renderEffectName];
  21690. if (!renderEffects) {
  21691. return;
  21692. }
  21693. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21694. };
  21695. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21696. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21697. var indicesToDelete = [];
  21698. for (var i = 0; i < _cam.length; i++) {
  21699. var camera = _cam[i];
  21700. var cameraName = camera.name;
  21701. if (this._cameras.indexOf(camera) === -1) {
  21702. this._cameras[cameraName] = camera;
  21703. }
  21704. else if (unique) {
  21705. indicesToDelete.push(i);
  21706. }
  21707. }
  21708. for (var i = 0; i < indicesToDelete.length; i++) {
  21709. cameras.splice(indicesToDelete[i], 1);
  21710. }
  21711. for (var renderEffectName in this._renderEffects) {
  21712. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21713. }
  21714. };
  21715. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21716. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21717. for (var renderEffectName in this._renderEffects) {
  21718. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21719. }
  21720. for (var i = 0; i < _cam.length; i++) {
  21721. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21722. }
  21723. };
  21724. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21725. var _this = this;
  21726. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21727. var pass = null;
  21728. for (var renderEffectName in this._renderEffects) {
  21729. pass = this._renderEffects[renderEffectName].getPass(passName);
  21730. if (pass != null) {
  21731. break;
  21732. }
  21733. }
  21734. if (pass === null) {
  21735. return;
  21736. }
  21737. for (var renderEffectName in this._renderEffects) {
  21738. this._renderEffects[renderEffectName]._disable(_cam);
  21739. }
  21740. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21741. for (var i = 0; i < _cam.length; i++) {
  21742. var camera = _cam[i];
  21743. var cameraName = camera.name;
  21744. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21745. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21746. });
  21747. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21748. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21749. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21750. }
  21751. };
  21752. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21753. var _this = this;
  21754. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21755. for (var i = 0; i < _cam.length; i++) {
  21756. var camera = _cam[i];
  21757. var cameraName = camera.name;
  21758. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21759. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21760. });
  21761. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21762. }
  21763. for (var renderEffectName in this._renderEffects) {
  21764. this._renderEffects[renderEffectName]._enable(_cam);
  21765. }
  21766. };
  21767. PostProcessRenderPipeline.prototype._update = function () {
  21768. for (var renderEffectName in this._renderEffects) {
  21769. this._renderEffects[renderEffectName]._update();
  21770. }
  21771. for (var i = 0; i < this._cameras.length; i++) {
  21772. var cameraName = this._cameras[i].name;
  21773. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21774. this._renderEffectsForIsolatedPass[cameraName]._update();
  21775. }
  21776. }
  21777. };
  21778. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21779. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21780. return PostProcessRenderPipeline;
  21781. })();
  21782. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21783. })(BABYLON || (BABYLON = {}));
  21784. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  21785. (function (BABYLON) {
  21786. var PostProcessRenderPipelineManager = (function () {
  21787. function PostProcessRenderPipelineManager() {
  21788. this._renderPipelines = {};
  21789. }
  21790. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21791. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21792. };
  21793. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21794. var renderPipeline = this._renderPipelines[renderPipelineName];
  21795. if (!renderPipeline) {
  21796. return;
  21797. }
  21798. renderPipeline._attachCameras(cameras, unique);
  21799. };
  21800. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21801. var renderPipeline = this._renderPipelines[renderPipelineName];
  21802. if (!renderPipeline) {
  21803. return;
  21804. }
  21805. renderPipeline._detachCameras(cameras);
  21806. };
  21807. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21808. var renderPipeline = this._renderPipelines[renderPipelineName];
  21809. if (!renderPipeline) {
  21810. return;
  21811. }
  21812. renderPipeline._enableEffect(renderEffectName, cameras);
  21813. };
  21814. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21815. var renderPipeline = this._renderPipelines[renderPipelineName];
  21816. if (!renderPipeline) {
  21817. return;
  21818. }
  21819. renderPipeline._disableEffect(renderEffectName, cameras);
  21820. };
  21821. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21822. var renderPipeline = this._renderPipelines[renderPipelineName];
  21823. if (!renderPipeline) {
  21824. return;
  21825. }
  21826. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21827. };
  21828. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21829. var renderPipeline = this._renderPipelines[renderPipelineName];
  21830. if (!renderPipeline) {
  21831. return;
  21832. }
  21833. renderPipeline._disableDisplayOnlyPass(cameras);
  21834. };
  21835. PostProcessRenderPipelineManager.prototype.update = function () {
  21836. for (var renderPipelineName in this._renderPipelines) {
  21837. this._renderPipelines[renderPipelineName]._update();
  21838. }
  21839. };
  21840. return PostProcessRenderPipelineManager;
  21841. })();
  21842. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21843. })(BABYLON || (BABYLON = {}));
  21844. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21845. var BABYLON;
  21846. (function (BABYLON) {
  21847. var DisplayPassPostProcess = (function (_super) {
  21848. __extends(DisplayPassPostProcess, _super);
  21849. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21850. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21851. }
  21852. return DisplayPassPostProcess;
  21853. })(BABYLON.PostProcess);
  21854. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21855. })(BABYLON || (BABYLON = {}));
  21856. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  21857. (function (BABYLON) {
  21858. var BoundingBoxRenderer = (function () {
  21859. function BoundingBoxRenderer(scene) {
  21860. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21861. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21862. this.showBackLines = true;
  21863. this.renderList = new BABYLON.SmartArray(32);
  21864. this._scene = scene;
  21865. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21866. attributes: ["position"],
  21867. uniforms: ["worldViewProjection", "color"]
  21868. });
  21869. var engine = this._scene.getEngine();
  21870. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21871. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21872. 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]);
  21873. }
  21874. BoundingBoxRenderer.prototype.reset = function () {
  21875. this.renderList.reset();
  21876. };
  21877. BoundingBoxRenderer.prototype.render = function () {
  21878. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21879. return;
  21880. }
  21881. var engine = this._scene.getEngine();
  21882. engine.setDepthWrite(false);
  21883. this._colorShader._preBind();
  21884. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21885. var boundingBox = this.renderList.data[boundingBoxIndex];
  21886. var min = boundingBox.minimum;
  21887. var max = boundingBox.maximum;
  21888. var diff = max.subtract(min);
  21889. var median = min.add(diff.scale(0.5));
  21890. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21891. // VBOs
  21892. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21893. if (this.showBackLines) {
  21894. // Back
  21895. engine.setDepthFunctionToGreaterOrEqual();
  21896. this._scene.resetCachedMaterial();
  21897. this._colorShader.setColor4("color", this.backColor.toColor4());
  21898. this._colorShader.bind(worldMatrix);
  21899. // Draw order
  21900. engine.draw(false, 0, 24);
  21901. }
  21902. // Front
  21903. engine.setDepthFunctionToLess();
  21904. this._scene.resetCachedMaterial();
  21905. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21906. this._colorShader.bind(worldMatrix);
  21907. // Draw order
  21908. engine.draw(false, 0, 24);
  21909. }
  21910. this._colorShader.unbind();
  21911. engine.setDepthFunctionToLessOrEqual();
  21912. engine.setDepthWrite(true);
  21913. };
  21914. BoundingBoxRenderer.prototype.dispose = function () {
  21915. this._colorShader.dispose();
  21916. this._vb.dispose();
  21917. this._scene.getEngine()._releaseBuffer(this._ib);
  21918. };
  21919. return BoundingBoxRenderer;
  21920. })();
  21921. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21922. })(BABYLON || (BABYLON = {}));
  21923. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  21924. (function (BABYLON) {
  21925. var Internals;
  21926. (function (Internals) {
  21927. /*
  21928. * Based on jsTGALoader - Javascript loader for TGA file
  21929. * By Vincent Thibault
  21930. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21931. */
  21932. var TGATools = (function () {
  21933. function TGATools() {
  21934. }
  21935. TGATools.GetTGAHeader = function (data) {
  21936. var offset = 0;
  21937. var header = {
  21938. id_length: data[offset++],
  21939. colormap_type: data[offset++],
  21940. image_type: data[offset++],
  21941. colormap_index: data[offset++] | data[offset++] << 8,
  21942. colormap_length: data[offset++] | data[offset++] << 8,
  21943. colormap_size: data[offset++],
  21944. origin: [
  21945. data[offset++] | data[offset++] << 8,
  21946. data[offset++] | data[offset++] << 8
  21947. ],
  21948. width: data[offset++] | data[offset++] << 8,
  21949. height: data[offset++] | data[offset++] << 8,
  21950. pixel_size: data[offset++],
  21951. flags: data[offset++]
  21952. };
  21953. return header;
  21954. };
  21955. TGATools.UploadContent = function (gl, data) {
  21956. // Not enough data to contain header ?
  21957. if (data.length < 19) {
  21958. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  21959. return;
  21960. }
  21961. // Read Header
  21962. var offset = 18;
  21963. var header = TGATools.GetTGAHeader(data);
  21964. // Assume it's a valid Targa file.
  21965. if (header.id_length + offset > data.length) {
  21966. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  21967. return;
  21968. }
  21969. // Skip not needed data
  21970. offset += header.id_length;
  21971. var use_rle = false;
  21972. var use_pal = false;
  21973. var use_rgb = false;
  21974. var use_grey = false;
  21975. switch (header.image_type) {
  21976. case TGATools._TYPE_RLE_INDEXED:
  21977. use_rle = true;
  21978. case TGATools._TYPE_INDEXED:
  21979. use_pal = true;
  21980. break;
  21981. case TGATools._TYPE_RLE_RGB:
  21982. use_rle = true;
  21983. case TGATools._TYPE_RGB:
  21984. use_rgb = true;
  21985. break;
  21986. case TGATools._TYPE_RLE_GREY:
  21987. use_rle = true;
  21988. case TGATools._TYPE_GREY:
  21989. use_grey = true;
  21990. break;
  21991. }
  21992. var pixel_data;
  21993. var numAlphaBits = header.flags & 0xf;
  21994. var pixel_size = header.pixel_size >> 3;
  21995. var pixel_total = header.width * header.height * pixel_size;
  21996. // Read palettes
  21997. var palettes;
  21998. if (use_pal) {
  21999. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22000. }
  22001. // Read LRE
  22002. if (use_rle) {
  22003. pixel_data = new Uint8Array(pixel_total);
  22004. var c, count, i;
  22005. var localOffset = 0;
  22006. var pixels = new Uint8Array(pixel_size);
  22007. while (offset < pixel_total && localOffset < pixel_total) {
  22008. c = data[offset++];
  22009. count = (c & 0x7f) + 1;
  22010. // RLE pixels
  22011. if (c & 0x80) {
  22012. for (i = 0; i < pixel_size; ++i) {
  22013. pixels[i] = data[offset++];
  22014. }
  22015. for (i = 0; i < count; ++i) {
  22016. pixel_data.set(pixels, localOffset + i * pixel_size);
  22017. }
  22018. localOffset += pixel_size * count;
  22019. }
  22020. else {
  22021. count *= pixel_size;
  22022. for (i = 0; i < count; ++i) {
  22023. pixel_data[localOffset + i] = data[offset++];
  22024. }
  22025. localOffset += count;
  22026. }
  22027. }
  22028. }
  22029. else {
  22030. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22031. }
  22032. // Load to texture
  22033. var x_start, y_start, x_step, y_step, y_end, x_end;
  22034. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22035. default:
  22036. case TGATools._ORIGIN_UL:
  22037. x_start = 0;
  22038. x_step = 1;
  22039. x_end = header.width;
  22040. y_start = 0;
  22041. y_step = 1;
  22042. y_end = header.height;
  22043. break;
  22044. case TGATools._ORIGIN_BL:
  22045. x_start = 0;
  22046. x_step = 1;
  22047. x_end = header.width;
  22048. y_start = header.height - 1;
  22049. y_step = -1;
  22050. y_end = -1;
  22051. break;
  22052. case TGATools._ORIGIN_UR:
  22053. x_start = header.width - 1;
  22054. x_step = -1;
  22055. x_end = -1;
  22056. y_start = 0;
  22057. y_step = 1;
  22058. y_end = header.height;
  22059. break;
  22060. case TGATools._ORIGIN_BR:
  22061. x_start = header.width - 1;
  22062. x_step = -1;
  22063. x_end = -1;
  22064. y_start = header.height - 1;
  22065. y_step = -1;
  22066. y_end = -1;
  22067. break;
  22068. }
  22069. // Load the specify method
  22070. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22071. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22072. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22073. };
  22074. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22075. var image = pixel_data, colormap = palettes;
  22076. var width = header.width, height = header.height;
  22077. var color, i = 0, x, y;
  22078. var imageData = new Uint8Array(width * height * 4);
  22079. for (y = y_start; y !== y_end; y += y_step) {
  22080. for (x = x_start; x !== x_end; x += x_step, i++) {
  22081. color = image[i];
  22082. imageData[(x + width * y) * 4 + 3] = 255;
  22083. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22084. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22085. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22086. }
  22087. }
  22088. return imageData;
  22089. };
  22090. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22091. var image = pixel_data;
  22092. var width = header.width, height = header.height;
  22093. var color, i = 0, x, y;
  22094. var imageData = new Uint8Array(width * height * 4);
  22095. for (y = y_start; y !== y_end; y += y_step) {
  22096. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22097. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22098. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22099. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22100. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22101. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22102. }
  22103. }
  22104. return imageData;
  22105. };
  22106. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22107. var image = pixel_data;
  22108. var width = header.width, height = header.height;
  22109. var i = 0, x, y;
  22110. var imageData = new Uint8Array(width * height * 4);
  22111. for (y = y_start; y !== y_end; y += y_step) {
  22112. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22113. imageData[(x + width * y) * 4 + 3] = 255;
  22114. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22115. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22116. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22117. }
  22118. }
  22119. return imageData;
  22120. };
  22121. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22122. var image = pixel_data;
  22123. var width = header.width, height = header.height;
  22124. var i = 0, x, y;
  22125. var imageData = new Uint8Array(width * height * 4);
  22126. for (y = y_start; y !== y_end; y += y_step) {
  22127. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22128. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22129. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22130. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22131. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22132. }
  22133. }
  22134. return imageData;
  22135. };
  22136. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22137. var image = pixel_data;
  22138. var width = header.width, height = header.height;
  22139. var color, i = 0, x, y;
  22140. var imageData = new Uint8Array(width * height * 4);
  22141. for (y = y_start; y !== y_end; y += y_step) {
  22142. for (x = x_start; x !== x_end; x += x_step, i++) {
  22143. color = image[i];
  22144. imageData[(x + width * y) * 4 + 0] = color;
  22145. imageData[(x + width * y) * 4 + 1] = color;
  22146. imageData[(x + width * y) * 4 + 2] = color;
  22147. imageData[(x + width * y) * 4 + 3] = 255;
  22148. }
  22149. }
  22150. return imageData;
  22151. };
  22152. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22153. var image = pixel_data;
  22154. var width = header.width, height = header.height;
  22155. var i = 0, x, y;
  22156. var imageData = new Uint8Array(width * height * 4);
  22157. for (y = y_start; y !== y_end; y += y_step) {
  22158. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22159. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22160. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22161. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22162. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22163. }
  22164. }
  22165. return imageData;
  22166. };
  22167. TGATools._TYPE_NO_DATA = 0;
  22168. TGATools._TYPE_INDEXED = 1;
  22169. TGATools._TYPE_RGB = 2;
  22170. TGATools._TYPE_GREY = 3;
  22171. TGATools._TYPE_RLE_INDEXED = 9;
  22172. TGATools._TYPE_RLE_RGB = 10;
  22173. TGATools._TYPE_RLE_GREY = 11;
  22174. TGATools._ORIGIN_MASK = 0x30;
  22175. TGATools._ORIGIN_SHIFT = 0x04;
  22176. TGATools._ORIGIN_BL = 0x00;
  22177. TGATools._ORIGIN_BR = 0x01;
  22178. TGATools._ORIGIN_UL = 0x02;
  22179. TGATools._ORIGIN_UR = 0x03;
  22180. return TGATools;
  22181. })();
  22182. Internals.TGATools = TGATools;
  22183. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22184. })(BABYLON || (BABYLON = {}));
  22185. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  22186. (function (BABYLON) {
  22187. var Internals;
  22188. (function (Internals) {
  22189. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  22190. // All values and structures referenced from:
  22191. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  22192. var DDS_MAGIC = 0x20534444;
  22193. 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;
  22194. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  22195. 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;
  22196. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  22197. function FourCCToInt32(value) {
  22198. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  22199. }
  22200. function Int32ToFourCC(value) {
  22201. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  22202. }
  22203. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  22204. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  22205. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  22206. var headerLengthInt = 31; // The header length in 32 bit ints
  22207. // Offsets into the header array
  22208. var off_magic = 0;
  22209. var off_size = 1;
  22210. var off_flags = 2;
  22211. var off_height = 3;
  22212. var off_width = 4;
  22213. var off_mipmapCount = 7;
  22214. var off_pfFlags = 20;
  22215. var off_pfFourCC = 21;
  22216. var off_RGBbpp = 22;
  22217. var off_RMask = 23;
  22218. var off_GMask = 24;
  22219. var off_BMask = 25;
  22220. var off_AMask = 26;
  22221. var off_caps1 = 27;
  22222. var off_caps2 = 28;
  22223. ;
  22224. var DDSTools = (function () {
  22225. function DDSTools() {
  22226. }
  22227. DDSTools.GetDDSInfo = function (arrayBuffer) {
  22228. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  22229. var mipmapCount = 1;
  22230. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  22231. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22232. }
  22233. return {
  22234. width: header[off_width],
  22235. height: header[off_height],
  22236. mipmapCount: mipmapCount,
  22237. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  22238. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  22239. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  22240. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  22241. };
  22242. };
  22243. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22244. var byteArray = new Uint8Array(dataLength);
  22245. var srcData = new Uint8Array(arrayBuffer);
  22246. var index = 0;
  22247. for (var y = height - 1; y >= 0; y--) {
  22248. for (var x = 0; x < width; x++) {
  22249. var srcPos = dataOffset + (x + y * width) * 4;
  22250. byteArray[index + 2] = srcData[srcPos];
  22251. byteArray[index + 1] = srcData[srcPos + 1];
  22252. byteArray[index] = srcData[srcPos + 2];
  22253. byteArray[index + 3] = srcData[srcPos + 3];
  22254. index += 4;
  22255. }
  22256. }
  22257. return byteArray;
  22258. };
  22259. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22260. var byteArray = new Uint8Array(dataLength);
  22261. var srcData = new Uint8Array(arrayBuffer);
  22262. var index = 0;
  22263. for (var y = height - 1; y >= 0; y--) {
  22264. for (var x = 0; x < width; x++) {
  22265. var srcPos = dataOffset + (x + y * width) * 3;
  22266. byteArray[index + 2] = srcData[srcPos];
  22267. byteArray[index + 1] = srcData[srcPos + 1];
  22268. byteArray[index] = srcData[srcPos + 2];
  22269. index += 3;
  22270. }
  22271. }
  22272. return byteArray;
  22273. };
  22274. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  22275. var byteArray = new Uint8Array(dataLength);
  22276. var srcData = new Uint8Array(arrayBuffer);
  22277. var index = 0;
  22278. for (var y = height - 1; y >= 0; y--) {
  22279. for (var x = 0; x < width; x++) {
  22280. var srcPos = dataOffset + (x + y * width);
  22281. byteArray[index] = srcData[srcPos];
  22282. index++;
  22283. }
  22284. }
  22285. return byteArray;
  22286. };
  22287. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  22288. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  22289. if (header[off_magic] != DDS_MAGIC) {
  22290. BABYLON.Tools.Error("Invalid magic number in DDS header");
  22291. return;
  22292. }
  22293. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  22294. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  22295. return;
  22296. }
  22297. if (info.isFourCC) {
  22298. fourCC = header[off_pfFourCC];
  22299. switch (fourCC) {
  22300. case FOURCC_DXT1:
  22301. blockBytes = 8;
  22302. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  22303. break;
  22304. case FOURCC_DXT3:
  22305. blockBytes = 16;
  22306. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  22307. break;
  22308. case FOURCC_DXT5:
  22309. blockBytes = 16;
  22310. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  22311. break;
  22312. default:
  22313. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  22314. return;
  22315. }
  22316. }
  22317. mipmapCount = 1;
  22318. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  22319. mipmapCount = Math.max(1, header[off_mipmapCount]);
  22320. }
  22321. var bpp = header[off_RGBbpp];
  22322. for (var face = 0; face < faces; face++) {
  22323. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  22324. width = header[off_width];
  22325. height = header[off_height];
  22326. dataOffset = header[off_size] + 4;
  22327. for (i = 0; i < mipmapCount; ++i) {
  22328. if (info.isRGB) {
  22329. if (bpp == 24) {
  22330. dataLength = width * height * 3;
  22331. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22332. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  22333. }
  22334. else {
  22335. dataLength = width * height * 4;
  22336. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22337. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  22338. }
  22339. }
  22340. else if (info.isLuminance) {
  22341. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  22342. var unpaddedRowSize = width;
  22343. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  22344. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  22345. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  22346. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  22347. }
  22348. else {
  22349. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  22350. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  22351. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  22352. }
  22353. dataOffset += dataLength;
  22354. width *= 0.5;
  22355. height *= 0.5;
  22356. width = Math.max(1.0, width);
  22357. height = Math.max(1.0, height);
  22358. }
  22359. }
  22360. };
  22361. return DDSTools;
  22362. })();
  22363. Internals.DDSTools = DDSTools;
  22364. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22365. })(BABYLON || (BABYLON = {}));
  22366. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  22367. (function (BABYLON) {
  22368. var SmartArray = (function () {
  22369. function SmartArray(capacity) {
  22370. this.length = 0;
  22371. this._duplicateId = 0;
  22372. this.data = new Array(capacity);
  22373. this._id = SmartArray._GlobalId++;
  22374. }
  22375. SmartArray.prototype.push = function (value) {
  22376. this.data[this.length++] = value;
  22377. if (this.length > this.data.length) {
  22378. this.data.length *= 2;
  22379. }
  22380. if (!value.__smartArrayFlags) {
  22381. value.__smartArrayFlags = {};
  22382. }
  22383. value.__smartArrayFlags[this._id] = this._duplicateId;
  22384. };
  22385. SmartArray.prototype.pushNoDuplicate = function (value) {
  22386. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  22387. return;
  22388. }
  22389. this.push(value);
  22390. };
  22391. SmartArray.prototype.sort = function (compareFn) {
  22392. this.data.sort(compareFn);
  22393. };
  22394. SmartArray.prototype.reset = function () {
  22395. this.length = 0;
  22396. this._duplicateId++;
  22397. };
  22398. SmartArray.prototype.concat = function (array) {
  22399. if (array.length === 0) {
  22400. return;
  22401. }
  22402. if (this.length + array.length > this.data.length) {
  22403. this.data.length = (this.length + array.length) * 2;
  22404. }
  22405. for (var index = 0; index < array.length; index++) {
  22406. this.data[this.length++] = (array.data || array)[index];
  22407. }
  22408. };
  22409. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  22410. if (array.length === 0) {
  22411. return;
  22412. }
  22413. if (this.length + array.length > this.data.length) {
  22414. this.data.length = (this.length + array.length) * 2;
  22415. }
  22416. for (var index = 0; index < array.length; index++) {
  22417. var item = (array.data || array)[index];
  22418. this.pushNoDuplicate(item);
  22419. }
  22420. };
  22421. SmartArray.prototype.indexOf = function (value) {
  22422. var position = this.data.indexOf(value);
  22423. if (position >= this.length) {
  22424. return -1;
  22425. }
  22426. return position;
  22427. };
  22428. // Statics
  22429. SmartArray._GlobalId = 0;
  22430. return SmartArray;
  22431. })();
  22432. BABYLON.SmartArray = SmartArray;
  22433. })(BABYLON || (BABYLON = {}));
  22434. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22435. (function (BABYLON) {
  22436. var CannonJSPlugin = (function () {
  22437. function CannonJSPlugin() {
  22438. this._registeredMeshes = [];
  22439. this._physicsMaterials = [];
  22440. this.updateBodyPosition = function (mesh) {
  22441. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22442. var registeredMesh = this._registeredMeshes[index];
  22443. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22444. var body = registeredMesh.body;
  22445. var center = mesh.getBoundingInfo().boundingBox.center;
  22446. body.position.set(center.x, center.z, center.y);
  22447. body.quaternion.x = mesh.rotationQuaternion.x;
  22448. body.quaternion.z = mesh.rotationQuaternion.y;
  22449. body.quaternion.y = mesh.rotationQuaternion.z;
  22450. body.quaternion.w = -mesh.rotationQuaternion.w;
  22451. return;
  22452. }
  22453. }
  22454. };
  22455. }
  22456. CannonJSPlugin.prototype.initialize = function (iterations) {
  22457. if (iterations === void 0) { iterations = 10; }
  22458. this._world = new CANNON.World();
  22459. this._world.broadphase = new CANNON.NaiveBroadphase();
  22460. this._world.solver.iterations = iterations;
  22461. };
  22462. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22463. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22464. };
  22465. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22466. this._world.step(delta);
  22467. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22468. var registeredMesh = this._registeredMeshes[index];
  22469. if (registeredMesh.isChild) {
  22470. continue;
  22471. }
  22472. // Body position
  22473. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22474. var deltaPos = registeredMesh.delta;
  22475. if (deltaPos) {
  22476. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22477. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22478. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22479. }
  22480. else {
  22481. registeredMesh.mesh.position.x = bodyX;
  22482. registeredMesh.mesh.position.y = bodyZ;
  22483. registeredMesh.mesh.position.z = bodyY;
  22484. }
  22485. if (!registeredMesh.mesh.rotationQuaternion) {
  22486. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22487. }
  22488. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22489. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22490. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22491. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22492. }
  22493. };
  22494. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22495. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22496. };
  22497. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22498. this.unregisterMesh(mesh);
  22499. mesh.computeWorldMatrix(true);
  22500. switch (impostor) {
  22501. case BABYLON.PhysicsEngine.SphereImpostor:
  22502. var bbox = mesh.getBoundingInfo().boundingBox;
  22503. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22504. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22505. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22506. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22507. case BABYLON.PhysicsEngine.BoxImpostor:
  22508. bbox = mesh.getBoundingInfo().boundingBox;
  22509. var min = bbox.minimumWorld;
  22510. var max = bbox.maximumWorld;
  22511. var box = max.subtract(min).scale(0.5);
  22512. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22513. case BABYLON.PhysicsEngine.PlaneImpostor:
  22514. return this._createPlane(mesh, options);
  22515. case BABYLON.PhysicsEngine.MeshImpostor:
  22516. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22517. var rawFaces = mesh.getIndices();
  22518. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22519. }
  22520. return null;
  22521. };
  22522. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22523. var shape = new CANNON.Sphere(radius);
  22524. if (!options) {
  22525. return shape;
  22526. }
  22527. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22528. };
  22529. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22530. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22531. if (!options) {
  22532. return shape;
  22533. }
  22534. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22535. };
  22536. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22537. var shape = new CANNON.Plane();
  22538. if (!options) {
  22539. return shape;
  22540. }
  22541. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22542. };
  22543. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22544. var verts = [], faces = [];
  22545. mesh.computeWorldMatrix(true);
  22546. for (var i = 0; i < rawVerts.length; i += 3) {
  22547. var transformed = BABYLON.Vector3.Zero();
  22548. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22549. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22550. }
  22551. for (var j = 0; j < rawFaces.length; j += 3) {
  22552. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22553. }
  22554. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22555. if (!options) {
  22556. return shape;
  22557. }
  22558. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22559. };
  22560. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22561. var index;
  22562. var mat;
  22563. for (index = 0; index < this._physicsMaterials.length; index++) {
  22564. mat = this._physicsMaterials[index];
  22565. if (mat.friction === friction && mat.restitution === restitution) {
  22566. return mat;
  22567. }
  22568. }
  22569. var currentMat = new CANNON.Material();
  22570. currentMat.friction = friction;
  22571. currentMat.restitution = restitution;
  22572. this._physicsMaterials.push(currentMat);
  22573. for (index = 0; index < this._physicsMaterials.length; index++) {
  22574. mat = this._physicsMaterials[index];
  22575. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22576. contactMaterial.contactEquationStiffness = 1e10;
  22577. contactMaterial.contactEquationRegularizationTime = 10;
  22578. this._world.addContactMaterial(contactMaterial);
  22579. }
  22580. return currentMat;
  22581. };
  22582. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22583. var initialRotation = null;
  22584. if (mesh.rotationQuaternion) {
  22585. initialRotation = mesh.rotationQuaternion.clone();
  22586. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22587. }
  22588. // The delta between the mesh position and the mesh bounding box center
  22589. var bbox = mesh.getBoundingInfo().boundingBox;
  22590. var deltaPosition = mesh.position.subtract(bbox.center);
  22591. var material = this._addMaterial(friction, restitution);
  22592. var body = new CANNON.RigidBody(mass, shape, material);
  22593. if (initialRotation) {
  22594. body.quaternion.x = initialRotation.x;
  22595. body.quaternion.z = initialRotation.y;
  22596. body.quaternion.y = initialRotation.z;
  22597. body.quaternion.w = -initialRotation.w;
  22598. }
  22599. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22600. this._world.add(body);
  22601. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22602. return body;
  22603. };
  22604. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22605. var compoundShape = new CANNON.Compound();
  22606. for (var index = 0; index < parts.length; index++) {
  22607. var mesh = parts[index].mesh;
  22608. var shape = this.registerMesh(mesh, parts[index].impostor);
  22609. if (index == 0) {
  22610. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22611. }
  22612. else {
  22613. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22614. }
  22615. }
  22616. var initialMesh = parts[0].mesh;
  22617. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22618. body.parts = parts;
  22619. return body;
  22620. };
  22621. CannonJSPlugin.prototype._unbindBody = function (body) {
  22622. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22623. var registeredMesh = this._registeredMeshes[index];
  22624. if (registeredMesh.body === body) {
  22625. registeredMesh.body = null;
  22626. registeredMesh.delta = 0;
  22627. }
  22628. }
  22629. };
  22630. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22631. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22632. var registeredMesh = this._registeredMeshes[index];
  22633. if (registeredMesh.mesh === mesh) {
  22634. // Remove body
  22635. if (registeredMesh.body) {
  22636. this._world.remove(registeredMesh.body);
  22637. this._unbindBody(registeredMesh.body);
  22638. }
  22639. this._registeredMeshes.splice(index, 1);
  22640. return;
  22641. }
  22642. }
  22643. };
  22644. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22645. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22646. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22647. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22648. var registeredMesh = this._registeredMeshes[index];
  22649. if (registeredMesh.mesh === mesh) {
  22650. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22651. return;
  22652. }
  22653. }
  22654. };
  22655. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22656. var body1 = null, body2 = null;
  22657. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22658. var registeredMesh = this._registeredMeshes[index];
  22659. if (registeredMesh.mesh === mesh1) {
  22660. body1 = registeredMesh.body;
  22661. }
  22662. else if (registeredMesh.mesh === mesh2) {
  22663. body2 = registeredMesh.body;
  22664. }
  22665. }
  22666. if (!body1 || !body2) {
  22667. return false;
  22668. }
  22669. 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));
  22670. this._world.addConstraint(constraint);
  22671. return true;
  22672. };
  22673. CannonJSPlugin.prototype.dispose = function () {
  22674. while (this._registeredMeshes.length) {
  22675. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22676. }
  22677. };
  22678. CannonJSPlugin.prototype.isSupported = function () {
  22679. return window.CANNON !== undefined;
  22680. };
  22681. return CannonJSPlugin;
  22682. })();
  22683. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22684. })(BABYLON || (BABYLON = {}));
  22685. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22686. var BABYLON;
  22687. (function (BABYLON) {
  22688. var Condition = (function () {
  22689. function Condition(actionManager) {
  22690. this._actionManager = actionManager;
  22691. }
  22692. Condition.prototype.isValid = function () {
  22693. return true;
  22694. };
  22695. Condition.prototype._getProperty = function (propertyPath) {
  22696. return this._actionManager._getProperty(propertyPath);
  22697. };
  22698. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22699. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22700. };
  22701. return Condition;
  22702. })();
  22703. BABYLON.Condition = Condition;
  22704. var ValueCondition = (function (_super) {
  22705. __extends(ValueCondition, _super);
  22706. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22707. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22708. _super.call(this, actionManager);
  22709. this.propertyPath = propertyPath;
  22710. this.value = value;
  22711. this.operator = operator;
  22712. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22713. this._property = this._getProperty(this.propertyPath);
  22714. }
  22715. Object.defineProperty(ValueCondition, "IsEqual", {
  22716. get: function () {
  22717. return ValueCondition._IsEqual;
  22718. },
  22719. enumerable: true,
  22720. configurable: true
  22721. });
  22722. Object.defineProperty(ValueCondition, "IsDifferent", {
  22723. get: function () {
  22724. return ValueCondition._IsDifferent;
  22725. },
  22726. enumerable: true,
  22727. configurable: true
  22728. });
  22729. Object.defineProperty(ValueCondition, "IsGreater", {
  22730. get: function () {
  22731. return ValueCondition._IsGreater;
  22732. },
  22733. enumerable: true,
  22734. configurable: true
  22735. });
  22736. Object.defineProperty(ValueCondition, "IsLesser", {
  22737. get: function () {
  22738. return ValueCondition._IsLesser;
  22739. },
  22740. enumerable: true,
  22741. configurable: true
  22742. });
  22743. // Methods
  22744. ValueCondition.prototype.isValid = function () {
  22745. switch (this.operator) {
  22746. case ValueCondition.IsGreater:
  22747. return this._target[this._property] > this.value;
  22748. case ValueCondition.IsLesser:
  22749. return this._target[this._property] < this.value;
  22750. case ValueCondition.IsEqual:
  22751. case ValueCondition.IsDifferent:
  22752. var check;
  22753. if (this.value.equals) {
  22754. check = this.value.equals(this._target[this._property]);
  22755. }
  22756. else {
  22757. check = this.value === this._target[this._property];
  22758. }
  22759. return this.operator === ValueCondition.IsEqual ? check : !check;
  22760. }
  22761. return false;
  22762. };
  22763. // Statics
  22764. ValueCondition._IsEqual = 0;
  22765. ValueCondition._IsDifferent = 1;
  22766. ValueCondition._IsGreater = 2;
  22767. ValueCondition._IsLesser = 3;
  22768. return ValueCondition;
  22769. })(Condition);
  22770. BABYLON.ValueCondition = ValueCondition;
  22771. var PredicateCondition = (function (_super) {
  22772. __extends(PredicateCondition, _super);
  22773. function PredicateCondition(actionManager, predicate) {
  22774. _super.call(this, actionManager);
  22775. this.predicate = predicate;
  22776. }
  22777. PredicateCondition.prototype.isValid = function () {
  22778. return this.predicate();
  22779. };
  22780. return PredicateCondition;
  22781. })(Condition);
  22782. BABYLON.PredicateCondition = PredicateCondition;
  22783. var StateCondition = (function (_super) {
  22784. __extends(StateCondition, _super);
  22785. function StateCondition(actionManager, target, value) {
  22786. _super.call(this, actionManager);
  22787. this.value = value;
  22788. this._target = target;
  22789. }
  22790. // Methods
  22791. StateCondition.prototype.isValid = function () {
  22792. return this._target.state === this.value;
  22793. };
  22794. return StateCondition;
  22795. })(Condition);
  22796. BABYLON.StateCondition = StateCondition;
  22797. })(BABYLON || (BABYLON = {}));
  22798. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  22799. (function (BABYLON) {
  22800. var Action = (function () {
  22801. function Action(triggerOptions, condition) {
  22802. this.triggerOptions = triggerOptions;
  22803. if (triggerOptions.parameter) {
  22804. this.trigger = triggerOptions.trigger;
  22805. this._triggerParameter = triggerOptions.parameter;
  22806. }
  22807. else {
  22808. this.trigger = triggerOptions;
  22809. }
  22810. this._nextActiveAction = this;
  22811. this._condition = condition;
  22812. }
  22813. // Methods
  22814. Action.prototype._prepare = function () {
  22815. };
  22816. Action.prototype.getTriggerParameter = function () {
  22817. return this._triggerParameter;
  22818. };
  22819. Action.prototype._executeCurrent = function (evt) {
  22820. if (this._condition) {
  22821. var currentRenderId = this._actionManager.getScene().getRenderId();
  22822. // We cache the current evaluation for the current frame
  22823. if (this._condition._evaluationId === currentRenderId) {
  22824. if (!this._condition._currentResult) {
  22825. return;
  22826. }
  22827. }
  22828. else {
  22829. this._condition._evaluationId = currentRenderId;
  22830. if (!this._condition.isValid()) {
  22831. this._condition._currentResult = false;
  22832. return;
  22833. }
  22834. this._condition._currentResult = true;
  22835. }
  22836. }
  22837. this._nextActiveAction.execute(evt);
  22838. if (this._nextActiveAction._child) {
  22839. if (!this._nextActiveAction._child._actionManager) {
  22840. this._nextActiveAction._child._actionManager = this._actionManager;
  22841. }
  22842. this._nextActiveAction = this._nextActiveAction._child;
  22843. }
  22844. else {
  22845. this._nextActiveAction = this;
  22846. }
  22847. };
  22848. Action.prototype.execute = function (evt) {
  22849. };
  22850. Action.prototype.then = function (action) {
  22851. this._child = action;
  22852. action._actionManager = this._actionManager;
  22853. action._prepare();
  22854. return action;
  22855. };
  22856. Action.prototype._getProperty = function (propertyPath) {
  22857. return this._actionManager._getProperty(propertyPath);
  22858. };
  22859. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22860. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22861. };
  22862. return Action;
  22863. })();
  22864. BABYLON.Action = Action;
  22865. })(BABYLON || (BABYLON = {}));
  22866. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  22867. (function (BABYLON) {
  22868. /**
  22869. * ActionEvent is the event beint sent when an action is triggered.
  22870. */
  22871. var ActionEvent = (function () {
  22872. /**
  22873. * @constructor
  22874. * @param source The mesh that triggered the action.
  22875. * @param pointerX the X mouse cursor position at the time of the event
  22876. * @param pointerY the Y mouse cursor position at the time of the event
  22877. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  22878. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  22879. */
  22880. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22881. this.source = source;
  22882. this.pointerX = pointerX;
  22883. this.pointerY = pointerY;
  22884. this.meshUnderPointer = meshUnderPointer;
  22885. this.sourceEvent = sourceEvent;
  22886. }
  22887. /**
  22888. * Helper function to auto-create an ActionEvent from a source mesh.
  22889. * @param source the source mesh that triggered the event
  22890. * @param evt {Event} The original (browser) event
  22891. */
  22892. ActionEvent.CreateNew = function (source, evt) {
  22893. var scene = source.getScene();
  22894. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22895. };
  22896. /**
  22897. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  22898. * @param scene the scene where the event occurred
  22899. * @param evt {Event} The original (browser) event
  22900. */
  22901. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22902. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22903. };
  22904. return ActionEvent;
  22905. })();
  22906. BABYLON.ActionEvent = ActionEvent;
  22907. /**
  22908. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  22909. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  22910. */
  22911. var ActionManager = (function () {
  22912. function ActionManager(scene) {
  22913. // Members
  22914. this.actions = new Array();
  22915. this._scene = scene;
  22916. scene._actionManagers.push(this);
  22917. }
  22918. Object.defineProperty(ActionManager, "NothingTrigger", {
  22919. get: function () {
  22920. return ActionManager._NothingTrigger;
  22921. },
  22922. enumerable: true,
  22923. configurable: true
  22924. });
  22925. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22926. get: function () {
  22927. return ActionManager._OnPickTrigger;
  22928. },
  22929. enumerable: true,
  22930. configurable: true
  22931. });
  22932. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22933. get: function () {
  22934. return ActionManager._OnLeftPickTrigger;
  22935. },
  22936. enumerable: true,
  22937. configurable: true
  22938. });
  22939. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22940. get: function () {
  22941. return ActionManager._OnRightPickTrigger;
  22942. },
  22943. enumerable: true,
  22944. configurable: true
  22945. });
  22946. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  22947. get: function () {
  22948. return ActionManager._OnCenterPickTrigger;
  22949. },
  22950. enumerable: true,
  22951. configurable: true
  22952. });
  22953. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  22954. get: function () {
  22955. return ActionManager._OnPointerOverTrigger;
  22956. },
  22957. enumerable: true,
  22958. configurable: true
  22959. });
  22960. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  22961. get: function () {
  22962. return ActionManager._OnPointerOutTrigger;
  22963. },
  22964. enumerable: true,
  22965. configurable: true
  22966. });
  22967. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  22968. get: function () {
  22969. return ActionManager._OnEveryFrameTrigger;
  22970. },
  22971. enumerable: true,
  22972. configurable: true
  22973. });
  22974. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  22975. get: function () {
  22976. return ActionManager._OnIntersectionEnterTrigger;
  22977. },
  22978. enumerable: true,
  22979. configurable: true
  22980. });
  22981. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  22982. get: function () {
  22983. return ActionManager._OnIntersectionExitTrigger;
  22984. },
  22985. enumerable: true,
  22986. configurable: true
  22987. });
  22988. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  22989. get: function () {
  22990. return ActionManager._OnKeyDownTrigger;
  22991. },
  22992. enumerable: true,
  22993. configurable: true
  22994. });
  22995. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  22996. get: function () {
  22997. return ActionManager._OnKeyUpTrigger;
  22998. },
  22999. enumerable: true,
  23000. configurable: true
  23001. });
  23002. // Methods
  23003. ActionManager.prototype.dispose = function () {
  23004. var index = this._scene._actionManagers.indexOf(this);
  23005. if (index > -1) {
  23006. this._scene._actionManagers.splice(index, 1);
  23007. }
  23008. };
  23009. ActionManager.prototype.getScene = function () {
  23010. return this._scene;
  23011. };
  23012. /**
  23013. * Does this action manager handles actions of any of the given triggers
  23014. * @param {number[]} triggers - the triggers to be tested
  23015. * @return {boolean} whether one (or more) of the triggers is handeled
  23016. */
  23017. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23018. for (var index = 0; index < this.actions.length; index++) {
  23019. var action = this.actions[index];
  23020. if (triggers.indexOf(action.trigger) > -1) {
  23021. return true;
  23022. }
  23023. }
  23024. return false;
  23025. };
  23026. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23027. /**
  23028. * Does this action manager has pointer triggers
  23029. * @return {boolean} whether or not it has pointer triggers
  23030. */
  23031. get: function () {
  23032. for (var index = 0; index < this.actions.length; index++) {
  23033. var action = this.actions[index];
  23034. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23035. return true;
  23036. }
  23037. }
  23038. return false;
  23039. },
  23040. enumerable: true,
  23041. configurable: true
  23042. });
  23043. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23044. /**
  23045. * Does this action manager has pick triggers
  23046. * @return {boolean} whether or not it has pick triggers
  23047. */
  23048. get: function () {
  23049. for (var index = 0; index < this.actions.length; index++) {
  23050. var action = this.actions[index];
  23051. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23052. return true;
  23053. }
  23054. }
  23055. return false;
  23056. },
  23057. enumerable: true,
  23058. configurable: true
  23059. });
  23060. /**
  23061. * Registers an action to this action manager
  23062. * @param {BABYLON.Action} action - the action to be registered
  23063. * @return {BABYLON.Action} the action amended (prepared) after registration
  23064. */
  23065. ActionManager.prototype.registerAction = function (action) {
  23066. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23067. if (this.getScene().actionManager !== this) {
  23068. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23069. return null;
  23070. }
  23071. }
  23072. this.actions.push(action);
  23073. action._actionManager = this;
  23074. action._prepare();
  23075. return action;
  23076. };
  23077. /**
  23078. * Process a specific trigger
  23079. * @param {number} trigger - the trigger to process
  23080. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23081. */
  23082. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23083. for (var index = 0; index < this.actions.length; index++) {
  23084. var action = this.actions[index];
  23085. if (action.trigger === trigger) {
  23086. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23087. var parameter = action.getTriggerParameter();
  23088. if (parameter) {
  23089. if (evt.sourceEvent.key !== parameter) {
  23090. continue;
  23091. }
  23092. }
  23093. }
  23094. action._executeCurrent(evt);
  23095. }
  23096. }
  23097. };
  23098. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23099. var properties = propertyPath.split(".");
  23100. for (var index = 0; index < properties.length - 1; index++) {
  23101. target = target[properties[index]];
  23102. }
  23103. return target;
  23104. };
  23105. ActionManager.prototype._getProperty = function (propertyPath) {
  23106. var properties = propertyPath.split(".");
  23107. return properties[properties.length - 1];
  23108. };
  23109. // Statics
  23110. ActionManager._NothingTrigger = 0;
  23111. ActionManager._OnPickTrigger = 1;
  23112. ActionManager._OnLeftPickTrigger = 2;
  23113. ActionManager._OnRightPickTrigger = 3;
  23114. ActionManager._OnCenterPickTrigger = 4;
  23115. ActionManager._OnPointerOverTrigger = 5;
  23116. ActionManager._OnPointerOutTrigger = 6;
  23117. ActionManager._OnEveryFrameTrigger = 7;
  23118. ActionManager._OnIntersectionEnterTrigger = 8;
  23119. ActionManager._OnIntersectionExitTrigger = 9;
  23120. ActionManager._OnKeyDownTrigger = 10;
  23121. ActionManager._OnKeyUpTrigger = 11;
  23122. return ActionManager;
  23123. })();
  23124. BABYLON.ActionManager = ActionManager;
  23125. })(BABYLON || (BABYLON = {}));
  23126. //# sourceMappingURL=babylon.actionManager.js.map
  23127. var BABYLON;
  23128. (function (BABYLON) {
  23129. var InterpolateValueAction = (function (_super) {
  23130. __extends(InterpolateValueAction, _super);
  23131. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23132. if (duration === void 0) { duration = 1000; }
  23133. _super.call(this, triggerOptions, condition);
  23134. this.propertyPath = propertyPath;
  23135. this.value = value;
  23136. this.duration = duration;
  23137. this.stopOtherAnimations = stopOtherAnimations;
  23138. this._target = target;
  23139. }
  23140. InterpolateValueAction.prototype._prepare = function () {
  23141. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23142. this._property = this._getProperty(this.propertyPath);
  23143. };
  23144. InterpolateValueAction.prototype.execute = function () {
  23145. var scene = this._actionManager.getScene();
  23146. var keys = [
  23147. {
  23148. frame: 0,
  23149. value: this._target[this._property]
  23150. },
  23151. {
  23152. frame: 100,
  23153. value: this.value
  23154. }
  23155. ];
  23156. var dataType;
  23157. if (typeof this.value === "number") {
  23158. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23159. }
  23160. else if (this.value instanceof BABYLON.Color3) {
  23161. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23162. }
  23163. else if (this.value instanceof BABYLON.Vector3) {
  23164. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23165. }
  23166. else if (this.value instanceof BABYLON.Matrix) {
  23167. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23168. }
  23169. else if (this.value instanceof BABYLON.Quaternion) {
  23170. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23171. }
  23172. else {
  23173. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23174. return;
  23175. }
  23176. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23177. animation.setKeys(keys);
  23178. if (this.stopOtherAnimations) {
  23179. scene.stopAnimation(this._target);
  23180. }
  23181. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  23182. };
  23183. return InterpolateValueAction;
  23184. })(BABYLON.Action);
  23185. BABYLON.InterpolateValueAction = InterpolateValueAction;
  23186. })(BABYLON || (BABYLON = {}));
  23187. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  23188. var BABYLON;
  23189. (function (BABYLON) {
  23190. var SwitchBooleanAction = (function (_super) {
  23191. __extends(SwitchBooleanAction, _super);
  23192. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  23193. _super.call(this, triggerOptions, condition);
  23194. this.propertyPath = propertyPath;
  23195. this._target = target;
  23196. }
  23197. SwitchBooleanAction.prototype._prepare = function () {
  23198. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23199. this._property = this._getProperty(this.propertyPath);
  23200. };
  23201. SwitchBooleanAction.prototype.execute = function () {
  23202. this._target[this._property] = !this._target[this._property];
  23203. };
  23204. return SwitchBooleanAction;
  23205. })(BABYLON.Action);
  23206. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  23207. var SetStateAction = (function (_super) {
  23208. __extends(SetStateAction, _super);
  23209. function SetStateAction(triggerOptions, target, value, condition) {
  23210. _super.call(this, triggerOptions, condition);
  23211. this.value = value;
  23212. this._target = target;
  23213. }
  23214. SetStateAction.prototype.execute = function () {
  23215. this._target.state = this.value;
  23216. };
  23217. return SetStateAction;
  23218. })(BABYLON.Action);
  23219. BABYLON.SetStateAction = SetStateAction;
  23220. var SetValueAction = (function (_super) {
  23221. __extends(SetValueAction, _super);
  23222. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  23223. _super.call(this, triggerOptions, condition);
  23224. this.propertyPath = propertyPath;
  23225. this.value = value;
  23226. this._target = target;
  23227. }
  23228. SetValueAction.prototype._prepare = function () {
  23229. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23230. this._property = this._getProperty(this.propertyPath);
  23231. };
  23232. SetValueAction.prototype.execute = function () {
  23233. this._target[this._property] = this.value;
  23234. };
  23235. return SetValueAction;
  23236. })(BABYLON.Action);
  23237. BABYLON.SetValueAction = SetValueAction;
  23238. var IncrementValueAction = (function (_super) {
  23239. __extends(IncrementValueAction, _super);
  23240. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  23241. _super.call(this, triggerOptions, condition);
  23242. this.propertyPath = propertyPath;
  23243. this.value = value;
  23244. this._target = target;
  23245. }
  23246. IncrementValueAction.prototype._prepare = function () {
  23247. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23248. this._property = this._getProperty(this.propertyPath);
  23249. if (typeof this._target[this._property] !== "number") {
  23250. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  23251. }
  23252. };
  23253. IncrementValueAction.prototype.execute = function () {
  23254. this._target[this._property] += this.value;
  23255. };
  23256. return IncrementValueAction;
  23257. })(BABYLON.Action);
  23258. BABYLON.IncrementValueAction = IncrementValueAction;
  23259. var PlayAnimationAction = (function (_super) {
  23260. __extends(PlayAnimationAction, _super);
  23261. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  23262. _super.call(this, triggerOptions, condition);
  23263. this.from = from;
  23264. this.to = to;
  23265. this.loop = loop;
  23266. this._target = target;
  23267. }
  23268. PlayAnimationAction.prototype._prepare = function () {
  23269. };
  23270. PlayAnimationAction.prototype.execute = function () {
  23271. var scene = this._actionManager.getScene();
  23272. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  23273. };
  23274. return PlayAnimationAction;
  23275. })(BABYLON.Action);
  23276. BABYLON.PlayAnimationAction = PlayAnimationAction;
  23277. var StopAnimationAction = (function (_super) {
  23278. __extends(StopAnimationAction, _super);
  23279. function StopAnimationAction(triggerOptions, target, condition) {
  23280. _super.call(this, triggerOptions, condition);
  23281. this._target = target;
  23282. }
  23283. StopAnimationAction.prototype._prepare = function () {
  23284. };
  23285. StopAnimationAction.prototype.execute = function () {
  23286. var scene = this._actionManager.getScene();
  23287. scene.stopAnimation(this._target);
  23288. };
  23289. return StopAnimationAction;
  23290. })(BABYLON.Action);
  23291. BABYLON.StopAnimationAction = StopAnimationAction;
  23292. var DoNothingAction = (function (_super) {
  23293. __extends(DoNothingAction, _super);
  23294. function DoNothingAction(triggerOptions, condition) {
  23295. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  23296. _super.call(this, triggerOptions, condition);
  23297. }
  23298. DoNothingAction.prototype.execute = function () {
  23299. };
  23300. return DoNothingAction;
  23301. })(BABYLON.Action);
  23302. BABYLON.DoNothingAction = DoNothingAction;
  23303. var CombineAction = (function (_super) {
  23304. __extends(CombineAction, _super);
  23305. function CombineAction(triggerOptions, children, condition) {
  23306. _super.call(this, triggerOptions, condition);
  23307. this.children = children;
  23308. }
  23309. CombineAction.prototype._prepare = function () {
  23310. for (var index = 0; index < this.children.length; index++) {
  23311. this.children[index]._actionManager = this._actionManager;
  23312. this.children[index]._prepare();
  23313. }
  23314. };
  23315. CombineAction.prototype.execute = function (evt) {
  23316. for (var index = 0; index < this.children.length; index++) {
  23317. this.children[index].execute(evt);
  23318. }
  23319. };
  23320. return CombineAction;
  23321. })(BABYLON.Action);
  23322. BABYLON.CombineAction = CombineAction;
  23323. var ExecuteCodeAction = (function (_super) {
  23324. __extends(ExecuteCodeAction, _super);
  23325. function ExecuteCodeAction(triggerOptions, func, condition) {
  23326. _super.call(this, triggerOptions, condition);
  23327. this.func = func;
  23328. }
  23329. ExecuteCodeAction.prototype.execute = function (evt) {
  23330. this.func(evt);
  23331. };
  23332. return ExecuteCodeAction;
  23333. })(BABYLON.Action);
  23334. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  23335. var SetParentAction = (function (_super) {
  23336. __extends(SetParentAction, _super);
  23337. function SetParentAction(triggerOptions, target, parent, condition) {
  23338. _super.call(this, triggerOptions, condition);
  23339. this._target = target;
  23340. this._parent = parent;
  23341. }
  23342. SetParentAction.prototype._prepare = function () {
  23343. };
  23344. SetParentAction.prototype.execute = function () {
  23345. if (this._target.parent === this._parent) {
  23346. return;
  23347. }
  23348. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  23349. invertParentWorldMatrix.invert();
  23350. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  23351. this._target.parent = this._parent;
  23352. };
  23353. return SetParentAction;
  23354. })(BABYLON.Action);
  23355. BABYLON.SetParentAction = SetParentAction;
  23356. })(BABYLON || (BABYLON = {}));
  23357. //# sourceMappingURL=babylon.directActions.js.map
  23358. var BABYLON;
  23359. (function (BABYLON) {
  23360. var Geometry = (function () {
  23361. function Geometry(id, scene, vertexData, updatable, mesh) {
  23362. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23363. this._totalVertices = 0;
  23364. this._indices = [];
  23365. this.id = id;
  23366. this._engine = scene.getEngine();
  23367. this._meshes = [];
  23368. this._scene = scene;
  23369. // vertexData
  23370. if (vertexData) {
  23371. this.setAllVerticesData(vertexData, updatable);
  23372. }
  23373. else {
  23374. this._totalVertices = 0;
  23375. this._indices = [];
  23376. }
  23377. // applyToMesh
  23378. if (mesh) {
  23379. this.applyToMesh(mesh);
  23380. }
  23381. }
  23382. Geometry.prototype.getScene = function () {
  23383. return this._scene;
  23384. };
  23385. Geometry.prototype.getEngine = function () {
  23386. return this._engine;
  23387. };
  23388. Geometry.prototype.isReady = function () {
  23389. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  23390. };
  23391. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  23392. vertexData.applyToGeometry(this, updatable);
  23393. };
  23394. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  23395. this._vertexBuffers = this._vertexBuffers || {};
  23396. if (this._vertexBuffers[kind]) {
  23397. this._vertexBuffers[kind].dispose();
  23398. }
  23399. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  23400. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23401. stride = this._vertexBuffers[kind].getStrideSize();
  23402. this._totalVertices = data.length / stride;
  23403. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23404. var meshes = this._meshes;
  23405. var numOfMeshes = meshes.length;
  23406. for (var index = 0; index < numOfMeshes; index++) {
  23407. var mesh = meshes[index];
  23408. mesh._resetPointsArrayCache();
  23409. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23410. mesh._createGlobalSubMesh();
  23411. mesh.computeWorldMatrix(true);
  23412. }
  23413. }
  23414. };
  23415. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  23416. var vertexBuffer = this.getVertexBuffer(kind);
  23417. if (!vertexBuffer) {
  23418. return;
  23419. }
  23420. vertexBuffer.updateDirectly(data, offset);
  23421. };
  23422. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  23423. var vertexBuffer = this.getVertexBuffer(kind);
  23424. if (!vertexBuffer) {
  23425. return;
  23426. }
  23427. vertexBuffer.update(data);
  23428. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23429. var extend;
  23430. var stride = vertexBuffer.getStrideSize();
  23431. this._totalVertices = data.length / stride;
  23432. if (updateExtends) {
  23433. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  23434. }
  23435. var meshes = this._meshes;
  23436. var numOfMeshes = meshes.length;
  23437. for (var index = 0; index < numOfMeshes; index++) {
  23438. var mesh = meshes[index];
  23439. mesh._resetPointsArrayCache();
  23440. if (updateExtends) {
  23441. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23442. }
  23443. }
  23444. }
  23445. };
  23446. Geometry.prototype.getTotalVertices = function () {
  23447. if (!this.isReady()) {
  23448. return 0;
  23449. }
  23450. return this._totalVertices;
  23451. };
  23452. Geometry.prototype.getVerticesData = function (kind) {
  23453. var vertexBuffer = this.getVertexBuffer(kind);
  23454. if (!vertexBuffer) {
  23455. return null;
  23456. }
  23457. return vertexBuffer.getData();
  23458. };
  23459. Geometry.prototype.getVertexBuffer = function (kind) {
  23460. if (!this.isReady()) {
  23461. return null;
  23462. }
  23463. return this._vertexBuffers[kind];
  23464. };
  23465. Geometry.prototype.getVertexBuffers = function () {
  23466. if (!this.isReady()) {
  23467. return null;
  23468. }
  23469. return this._vertexBuffers;
  23470. };
  23471. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23472. if (!this._vertexBuffers) {
  23473. if (this._delayInfo) {
  23474. return this._delayInfo.indexOf(kind) !== -1;
  23475. }
  23476. return false;
  23477. }
  23478. return this._vertexBuffers[kind] !== undefined;
  23479. };
  23480. Geometry.prototype.getVerticesDataKinds = function () {
  23481. var result = [];
  23482. if (!this._vertexBuffers && this._delayInfo) {
  23483. for (var kind in this._delayInfo) {
  23484. result.push(kind);
  23485. }
  23486. }
  23487. else {
  23488. for (kind in this._vertexBuffers) {
  23489. result.push(kind);
  23490. }
  23491. }
  23492. return result;
  23493. };
  23494. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23495. if (this._indexBuffer) {
  23496. this._engine._releaseBuffer(this._indexBuffer);
  23497. }
  23498. this._indices = indices;
  23499. if (this._meshes.length !== 0 && this._indices) {
  23500. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23501. }
  23502. if (totalVertices !== undefined) {
  23503. this._totalVertices = totalVertices;
  23504. }
  23505. var meshes = this._meshes;
  23506. var numOfMeshes = meshes.length;
  23507. for (var index = 0; index < numOfMeshes; index++) {
  23508. meshes[index]._createGlobalSubMesh();
  23509. }
  23510. };
  23511. Geometry.prototype.getTotalIndices = function () {
  23512. if (!this.isReady()) {
  23513. return 0;
  23514. }
  23515. return this._indices.length;
  23516. };
  23517. Geometry.prototype.getIndices = function () {
  23518. if (!this.isReady()) {
  23519. return null;
  23520. }
  23521. return this._indices;
  23522. };
  23523. Geometry.prototype.getIndexBuffer = function () {
  23524. if (!this.isReady()) {
  23525. return null;
  23526. }
  23527. return this._indexBuffer;
  23528. };
  23529. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23530. var meshes = this._meshes;
  23531. var index = meshes.indexOf(mesh);
  23532. if (index === -1) {
  23533. return;
  23534. }
  23535. for (var kind in this._vertexBuffers) {
  23536. this._vertexBuffers[kind].dispose();
  23537. }
  23538. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23539. this._indexBuffer = null;
  23540. }
  23541. meshes.splice(index, 1);
  23542. mesh._geometry = null;
  23543. if (meshes.length === 0 && shouldDispose) {
  23544. this.dispose();
  23545. }
  23546. };
  23547. Geometry.prototype.applyToMesh = function (mesh) {
  23548. if (mesh._geometry === this) {
  23549. return;
  23550. }
  23551. var previousGeometry = mesh._geometry;
  23552. if (previousGeometry) {
  23553. previousGeometry.releaseForMesh(mesh);
  23554. }
  23555. var meshes = this._meshes;
  23556. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23557. mesh._geometry = this;
  23558. this._scene.pushGeometry(this);
  23559. meshes.push(mesh);
  23560. if (this.isReady()) {
  23561. this._applyToMesh(mesh);
  23562. }
  23563. else {
  23564. mesh._boundingInfo = this._boundingInfo;
  23565. }
  23566. };
  23567. Geometry.prototype._applyToMesh = function (mesh) {
  23568. var numOfMeshes = this._meshes.length;
  23569. for (var kind in this._vertexBuffers) {
  23570. if (numOfMeshes === 1) {
  23571. this._vertexBuffers[kind].create();
  23572. }
  23573. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23574. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23575. mesh._resetPointsArrayCache();
  23576. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23577. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23578. mesh._createGlobalSubMesh();
  23579. //bounding info was just created again, world matrix should be applied again.
  23580. mesh._updateBoundingInfo();
  23581. }
  23582. }
  23583. // indexBuffer
  23584. if (numOfMeshes === 1 && this._indices) {
  23585. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23586. }
  23587. if (this._indexBuffer) {
  23588. this._indexBuffer.references = numOfMeshes;
  23589. }
  23590. };
  23591. Geometry.prototype.load = function (scene, onLoaded) {
  23592. var _this = this;
  23593. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23594. return;
  23595. }
  23596. if (this.isReady()) {
  23597. if (onLoaded) {
  23598. onLoaded();
  23599. }
  23600. return;
  23601. }
  23602. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23603. scene._addPendingData(this);
  23604. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23605. _this._delayLoadingFunction(JSON.parse(data), _this);
  23606. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23607. _this._delayInfo = [];
  23608. scene._removePendingData(_this);
  23609. var meshes = _this._meshes;
  23610. var numOfMeshes = meshes.length;
  23611. for (var index = 0; index < numOfMeshes; index++) {
  23612. _this._applyToMesh(meshes[index]);
  23613. }
  23614. if (onLoaded) {
  23615. onLoaded();
  23616. }
  23617. }, function () {
  23618. }, scene.database);
  23619. };
  23620. Geometry.prototype.dispose = function () {
  23621. var meshes = this._meshes;
  23622. var numOfMeshes = meshes.length;
  23623. var index;
  23624. for (index = 0; index < numOfMeshes; index++) {
  23625. this.releaseForMesh(meshes[index]);
  23626. }
  23627. this._meshes = [];
  23628. for (var kind in this._vertexBuffers) {
  23629. this._vertexBuffers[kind].dispose();
  23630. }
  23631. this._vertexBuffers = [];
  23632. this._totalVertices = 0;
  23633. if (this._indexBuffer) {
  23634. this._engine._releaseBuffer(this._indexBuffer);
  23635. }
  23636. this._indexBuffer = null;
  23637. this._indices = [];
  23638. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23639. this.delayLoadingFile = null;
  23640. this._delayLoadingFunction = null;
  23641. this._delayInfo = [];
  23642. this._boundingInfo = null; // todo: .dispose()
  23643. var geometries = this._scene.getGeometries();
  23644. index = geometries.indexOf(this);
  23645. if (index > -1) {
  23646. geometries.splice(index, 1);
  23647. }
  23648. };
  23649. Geometry.prototype.copy = function (id) {
  23650. var vertexData = new BABYLON.VertexData();
  23651. vertexData.indices = [];
  23652. var indices = this.getIndices();
  23653. for (var index = 0; index < indices.length; index++) {
  23654. vertexData.indices.push(indices[index]);
  23655. }
  23656. var updatable = false;
  23657. var stopChecking = false;
  23658. for (var kind in this._vertexBuffers) {
  23659. vertexData.set(this.getVerticesData(kind), kind);
  23660. if (!stopChecking) {
  23661. updatable = this.getVertexBuffer(kind).isUpdatable();
  23662. stopChecking = !updatable;
  23663. }
  23664. }
  23665. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23666. geometry.delayLoadState = this.delayLoadState;
  23667. geometry.delayLoadingFile = this.delayLoadingFile;
  23668. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23669. for (kind in this._delayInfo) {
  23670. geometry._delayInfo = geometry._delayInfo || [];
  23671. geometry._delayInfo.push(kind);
  23672. }
  23673. // Bounding info
  23674. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23675. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23676. return geometry;
  23677. };
  23678. // Statics
  23679. Geometry.ExtractFromMesh = function (mesh, id) {
  23680. var geometry = mesh._geometry;
  23681. if (!geometry) {
  23682. return null;
  23683. }
  23684. return geometry.copy(id);
  23685. };
  23686. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23687. // be aware Math.random() could cause collisions
  23688. Geometry.RandomId = function () {
  23689. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23690. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23691. return v.toString(16);
  23692. });
  23693. };
  23694. return Geometry;
  23695. })();
  23696. BABYLON.Geometry = Geometry;
  23697. /////// Primitives //////////////////////////////////////////////
  23698. var Geometry;
  23699. (function (Geometry) {
  23700. var Primitives;
  23701. (function (Primitives) {
  23702. /// Abstract class
  23703. var _Primitive = (function (_super) {
  23704. __extends(_Primitive, _super);
  23705. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23706. this._beingRegenerated = true;
  23707. this._canBeRegenerated = canBeRegenerated;
  23708. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23709. this._beingRegenerated = false;
  23710. }
  23711. _Primitive.prototype.canBeRegenerated = function () {
  23712. return this._canBeRegenerated;
  23713. };
  23714. _Primitive.prototype.regenerate = function () {
  23715. if (!this._canBeRegenerated) {
  23716. return;
  23717. }
  23718. this._beingRegenerated = true;
  23719. this.setAllVerticesData(this._regenerateVertexData(), false);
  23720. this._beingRegenerated = false;
  23721. };
  23722. _Primitive.prototype.asNewGeometry = function (id) {
  23723. return _super.prototype.copy.call(this, id);
  23724. };
  23725. // overrides
  23726. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23727. if (!this._beingRegenerated) {
  23728. return;
  23729. }
  23730. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23731. };
  23732. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23733. if (!this._beingRegenerated) {
  23734. return;
  23735. }
  23736. _super.prototype.setVerticesData.call(this, kind, data, false);
  23737. };
  23738. // to override
  23739. // protected
  23740. _Primitive.prototype._regenerateVertexData = function () {
  23741. throw new Error("Abstract method");
  23742. };
  23743. _Primitive.prototype.copy = function (id) {
  23744. throw new Error("Must be overriden in sub-classes.");
  23745. };
  23746. return _Primitive;
  23747. })(Geometry);
  23748. Primitives._Primitive = _Primitive;
  23749. var Box = (function (_super) {
  23750. __extends(Box, _super);
  23751. function Box(id, scene, size, canBeRegenerated, mesh) {
  23752. this.size = size;
  23753. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23754. }
  23755. Box.prototype._regenerateVertexData = function () {
  23756. return BABYLON.VertexData.CreateBox(this.size);
  23757. };
  23758. Box.prototype.copy = function (id) {
  23759. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23760. };
  23761. return Box;
  23762. })(_Primitive);
  23763. Primitives.Box = Box;
  23764. var Sphere = (function (_super) {
  23765. __extends(Sphere, _super);
  23766. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23767. this.segments = segments;
  23768. this.diameter = diameter;
  23769. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23770. }
  23771. Sphere.prototype._regenerateVertexData = function () {
  23772. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23773. };
  23774. Sphere.prototype.copy = function (id) {
  23775. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23776. };
  23777. return Sphere;
  23778. })(_Primitive);
  23779. Primitives.Sphere = Sphere;
  23780. var Cylinder = (function (_super) {
  23781. __extends(Cylinder, _super);
  23782. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23783. if (subdivisions === void 0) { subdivisions = 1; }
  23784. this.height = height;
  23785. this.diameterTop = diameterTop;
  23786. this.diameterBottom = diameterBottom;
  23787. this.tessellation = tessellation;
  23788. this.subdivisions = subdivisions;
  23789. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23790. }
  23791. Cylinder.prototype._regenerateVertexData = function () {
  23792. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23793. };
  23794. Cylinder.prototype.copy = function (id) {
  23795. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23796. };
  23797. return Cylinder;
  23798. })(_Primitive);
  23799. Primitives.Cylinder = Cylinder;
  23800. var Torus = (function (_super) {
  23801. __extends(Torus, _super);
  23802. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23803. this.diameter = diameter;
  23804. this.thickness = thickness;
  23805. this.tessellation = tessellation;
  23806. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23807. }
  23808. Torus.prototype._regenerateVertexData = function () {
  23809. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23810. };
  23811. Torus.prototype.copy = function (id) {
  23812. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23813. };
  23814. return Torus;
  23815. })(_Primitive);
  23816. Primitives.Torus = Torus;
  23817. var Ground = (function (_super) {
  23818. __extends(Ground, _super);
  23819. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23820. this.width = width;
  23821. this.height = height;
  23822. this.subdivisions = subdivisions;
  23823. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23824. }
  23825. Ground.prototype._regenerateVertexData = function () {
  23826. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23827. };
  23828. Ground.prototype.copy = function (id) {
  23829. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23830. };
  23831. return Ground;
  23832. })(_Primitive);
  23833. Primitives.Ground = Ground;
  23834. var TiledGround = (function (_super) {
  23835. __extends(TiledGround, _super);
  23836. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23837. this.xmin = xmin;
  23838. this.zmin = zmin;
  23839. this.xmax = xmax;
  23840. this.zmax = zmax;
  23841. this.subdivisions = subdivisions;
  23842. this.precision = precision;
  23843. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23844. }
  23845. TiledGround.prototype._regenerateVertexData = function () {
  23846. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23847. };
  23848. TiledGround.prototype.copy = function (id) {
  23849. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23850. };
  23851. return TiledGround;
  23852. })(_Primitive);
  23853. Primitives.TiledGround = TiledGround;
  23854. var Plane = (function (_super) {
  23855. __extends(Plane, _super);
  23856. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23857. this.size = size;
  23858. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23859. }
  23860. Plane.prototype._regenerateVertexData = function () {
  23861. return BABYLON.VertexData.CreatePlane(this.size);
  23862. };
  23863. Plane.prototype.copy = function (id) {
  23864. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23865. };
  23866. return Plane;
  23867. })(_Primitive);
  23868. Primitives.Plane = Plane;
  23869. var TorusKnot = (function (_super) {
  23870. __extends(TorusKnot, _super);
  23871. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23872. this.radius = radius;
  23873. this.tube = tube;
  23874. this.radialSegments = radialSegments;
  23875. this.tubularSegments = tubularSegments;
  23876. this.p = p;
  23877. this.q = q;
  23878. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23879. }
  23880. TorusKnot.prototype._regenerateVertexData = function () {
  23881. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23882. };
  23883. TorusKnot.prototype.copy = function (id) {
  23884. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23885. };
  23886. return TorusKnot;
  23887. })(_Primitive);
  23888. Primitives.TorusKnot = TorusKnot;
  23889. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  23890. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  23891. })(BABYLON || (BABYLON = {}));
  23892. //# sourceMappingURL=babylon.geometry.js.map
  23893. var BABYLON;
  23894. (function (BABYLON) {
  23895. var Gamepads = (function () {
  23896. function Gamepads(ongamedpadconnected) {
  23897. var _this = this;
  23898. this.babylonGamepads = [];
  23899. this.oneGamepadConnected = false;
  23900. this.isMonitoring = false;
  23901. this.gamepadEventSupported = 'GamepadEvent' in window;
  23902. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23903. 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=";
  23904. this._callbackGamepadConnected = ongamedpadconnected;
  23905. if (this.gamepadSupportAvailable) {
  23906. // Checking if the gamepad connected event is supported (like in Firefox)
  23907. if (this.gamepadEventSupported) {
  23908. window.addEventListener('gamepadconnected', function (evt) {
  23909. _this._onGamepadConnected(evt);
  23910. }, false);
  23911. window.addEventListener('gamepaddisconnected', function (evt) {
  23912. _this._onGamepadDisconnected(evt);
  23913. }, false);
  23914. }
  23915. else {
  23916. this._startMonitoringGamepads();
  23917. }
  23918. if (!this.oneGamepadConnected) {
  23919. this._insertGamepadDOMInstructions();
  23920. }
  23921. }
  23922. else {
  23923. this._insertGamepadDOMNotSupported();
  23924. }
  23925. }
  23926. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23927. Gamepads.gamepadDOMInfo = document.createElement("div");
  23928. var buttonAImage = document.createElement("img");
  23929. buttonAImage.src = this.buttonADataURL;
  23930. var spanMessage = document.createElement("span");
  23931. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23932. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23933. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23934. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23935. Gamepads.gamepadDOMInfo.style.width = "100%";
  23936. Gamepads.gamepadDOMInfo.style.height = "48px";
  23937. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23938. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23939. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23940. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23941. buttonAImage.style.position = "relative";
  23942. buttonAImage.style.bottom = "8px";
  23943. spanMessage.style.position = "relative";
  23944. spanMessage.style.fontSize = "32px";
  23945. spanMessage.style.bottom = "32px";
  23946. spanMessage.style.color = "green";
  23947. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23948. };
  23949. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  23950. Gamepads.gamepadDOMInfo = document.createElement("div");
  23951. var spanMessage = document.createElement("span");
  23952. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  23953. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23954. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23955. Gamepads.gamepadDOMInfo.style.width = "100%";
  23956. Gamepads.gamepadDOMInfo.style.height = "40px";
  23957. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23958. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23959. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23960. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23961. spanMessage.style.position = "relative";
  23962. spanMessage.style.fontSize = "32px";
  23963. spanMessage.style.color = "red";
  23964. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23965. };
  23966. Gamepads.prototype.dispose = function () {
  23967. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23968. };
  23969. Gamepads.prototype._onGamepadConnected = function (evt) {
  23970. var newGamepad = this._addNewGamepad(evt.gamepad);
  23971. if (this._callbackGamepadConnected)
  23972. this._callbackGamepadConnected(newGamepad);
  23973. this._startMonitoringGamepads();
  23974. };
  23975. Gamepads.prototype._addNewGamepad = function (gamepad) {
  23976. if (!this.oneGamepadConnected) {
  23977. this.oneGamepadConnected = true;
  23978. if (Gamepads.gamepadDOMInfo) {
  23979. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23980. Gamepads.gamepadDOMInfo = null;
  23981. }
  23982. }
  23983. var newGamepad;
  23984. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  23985. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  23986. }
  23987. else {
  23988. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  23989. }
  23990. this.babylonGamepads.push(newGamepad);
  23991. return newGamepad;
  23992. };
  23993. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  23994. for (var i in this.babylonGamepads) {
  23995. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  23996. this.babylonGamepads.splice(i, 1);
  23997. break;
  23998. }
  23999. }
  24000. // If no gamepads are left, stop the polling loop.
  24001. if (this.babylonGamepads.length == 0) {
  24002. this._stopMonitoringGamepads();
  24003. }
  24004. };
  24005. Gamepads.prototype._startMonitoringGamepads = function () {
  24006. if (!this.isMonitoring) {
  24007. this.isMonitoring = true;
  24008. this._checkGamepadsStatus();
  24009. }
  24010. };
  24011. Gamepads.prototype._stopMonitoringGamepads = function () {
  24012. this.isMonitoring = false;
  24013. };
  24014. Gamepads.prototype._checkGamepadsStatus = function () {
  24015. var _this = this;
  24016. // updating gamepad objects
  24017. this._updateGamepadObjects();
  24018. for (var i in this.babylonGamepads) {
  24019. this.babylonGamepads[i].update();
  24020. }
  24021. if (this.isMonitoring) {
  24022. if (window.requestAnimationFrame) {
  24023. window.requestAnimationFrame(function () {
  24024. _this._checkGamepadsStatus();
  24025. });
  24026. }
  24027. else if (window.mozRequestAnimationFrame) {
  24028. window.mozRequestAnimationFrame(function () {
  24029. _this._checkGamepadsStatus();
  24030. });
  24031. }
  24032. else if (window.webkitRequestAnimationFrame) {
  24033. window.webkitRequestAnimationFrame(function () {
  24034. _this._checkGamepadsStatus();
  24035. });
  24036. }
  24037. }
  24038. };
  24039. // This function is called only on Chrome, which does not yet support
  24040. // connection/disconnection events, but requires you to monitor
  24041. // an array for changes.
  24042. Gamepads.prototype._updateGamepadObjects = function () {
  24043. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24044. for (var i = 0; i < gamepads.length; i++) {
  24045. if (gamepads[i]) {
  24046. if (!(gamepads[i].index in this.babylonGamepads)) {
  24047. var newGamepad = this._addNewGamepad(gamepads[i]);
  24048. if (this._callbackGamepadConnected) {
  24049. this._callbackGamepadConnected(newGamepad);
  24050. }
  24051. }
  24052. else {
  24053. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24054. }
  24055. }
  24056. }
  24057. };
  24058. return Gamepads;
  24059. })();
  24060. BABYLON.Gamepads = Gamepads;
  24061. var StickValues = (function () {
  24062. function StickValues(x, y) {
  24063. this.x = x;
  24064. this.y = y;
  24065. }
  24066. return StickValues;
  24067. })();
  24068. BABYLON.StickValues = StickValues;
  24069. var Gamepad = (function () {
  24070. function Gamepad(id, index, browserGamepad) {
  24071. this.id = id;
  24072. this.index = index;
  24073. this.browserGamepad = browserGamepad;
  24074. if (this.browserGamepad.axes.length >= 2) {
  24075. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24076. }
  24077. if (this.browserGamepad.axes.length >= 4) {
  24078. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24079. }
  24080. }
  24081. Gamepad.prototype.onleftstickchanged = function (callback) {
  24082. this._onleftstickchanged = callback;
  24083. };
  24084. Gamepad.prototype.onrightstickchanged = function (callback) {
  24085. this._onrightstickchanged = callback;
  24086. };
  24087. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24088. get: function () {
  24089. return this._leftStick;
  24090. },
  24091. set: function (newValues) {
  24092. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24093. this._onleftstickchanged(newValues);
  24094. }
  24095. this._leftStick = newValues;
  24096. },
  24097. enumerable: true,
  24098. configurable: true
  24099. });
  24100. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24101. get: function () {
  24102. return this._rightStick;
  24103. },
  24104. set: function (newValues) {
  24105. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24106. this._onrightstickchanged(newValues);
  24107. }
  24108. this._rightStick = newValues;
  24109. },
  24110. enumerable: true,
  24111. configurable: true
  24112. });
  24113. Gamepad.prototype.update = function () {
  24114. if (this._leftStick) {
  24115. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24116. }
  24117. if (this._rightStick) {
  24118. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24119. }
  24120. };
  24121. return Gamepad;
  24122. })();
  24123. BABYLON.Gamepad = Gamepad;
  24124. var GenericPad = (function (_super) {
  24125. __extends(GenericPad, _super);
  24126. function GenericPad(id, index, gamepad) {
  24127. _super.call(this, id, index, gamepad);
  24128. this.id = id;
  24129. this.index = index;
  24130. this.gamepad = gamepad;
  24131. this._buttons = new Array(gamepad.buttons.length);
  24132. }
  24133. GenericPad.prototype.onbuttondown = function (callback) {
  24134. this._onbuttondown = callback;
  24135. };
  24136. GenericPad.prototype.onbuttonup = function (callback) {
  24137. this._onbuttonup = callback;
  24138. };
  24139. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  24140. if (newValue !== currentValue) {
  24141. if (this._onbuttondown && newValue === 1) {
  24142. this._onbuttondown(buttonIndex);
  24143. }
  24144. if (this._onbuttonup && newValue === 0) {
  24145. this._onbuttonup(buttonIndex);
  24146. }
  24147. }
  24148. return newValue;
  24149. };
  24150. GenericPad.prototype.update = function () {
  24151. _super.prototype.update.call(this);
  24152. for (var index = 0; index < this._buttons.length; index++) {
  24153. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  24154. }
  24155. };
  24156. return GenericPad;
  24157. })(Gamepad);
  24158. BABYLON.GenericPad = GenericPad;
  24159. (function (Xbox360Button) {
  24160. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  24161. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  24162. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  24163. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  24164. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  24165. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  24166. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  24167. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  24168. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  24169. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  24170. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  24171. var Xbox360Button = BABYLON.Xbox360Button;
  24172. (function (Xbox360Dpad) {
  24173. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  24174. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  24175. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  24176. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  24177. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  24178. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  24179. var Xbox360Pad = (function (_super) {
  24180. __extends(Xbox360Pad, _super);
  24181. function Xbox360Pad() {
  24182. _super.apply(this, arguments);
  24183. this._leftTrigger = 0;
  24184. this._rightTrigger = 0;
  24185. this._buttonA = 0;
  24186. this._buttonB = 0;
  24187. this._buttonX = 0;
  24188. this._buttonY = 0;
  24189. this._buttonBack = 0;
  24190. this._buttonStart = 0;
  24191. this._buttonLB = 0;
  24192. this._buttonRB = 0;
  24193. this._buttonLeftStick = 0;
  24194. this._buttonRightStick = 0;
  24195. this._dPadUp = 0;
  24196. this._dPadDown = 0;
  24197. this._dPadLeft = 0;
  24198. this._dPadRight = 0;
  24199. }
  24200. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  24201. this._onlefttriggerchanged = callback;
  24202. };
  24203. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  24204. this._onrighttriggerchanged = callback;
  24205. };
  24206. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  24207. get: function () {
  24208. return this._leftTrigger;
  24209. },
  24210. set: function (newValue) {
  24211. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  24212. this._onlefttriggerchanged(newValue);
  24213. }
  24214. this._leftTrigger = newValue;
  24215. },
  24216. enumerable: true,
  24217. configurable: true
  24218. });
  24219. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  24220. get: function () {
  24221. return this._rightTrigger;
  24222. },
  24223. set: function (newValue) {
  24224. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  24225. this._onrighttriggerchanged(newValue);
  24226. }
  24227. this._rightTrigger = newValue;
  24228. },
  24229. enumerable: true,
  24230. configurable: true
  24231. });
  24232. Xbox360Pad.prototype.onbuttondown = function (callback) {
  24233. this._onbuttondown = callback;
  24234. };
  24235. Xbox360Pad.prototype.onbuttonup = function (callback) {
  24236. this._onbuttonup = callback;
  24237. };
  24238. Xbox360Pad.prototype.ondpaddown = function (callback) {
  24239. this._ondpaddown = callback;
  24240. };
  24241. Xbox360Pad.prototype.ondpadup = function (callback) {
  24242. this._ondpadup = callback;
  24243. };
  24244. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  24245. if (newValue !== currentValue) {
  24246. if (this._onbuttondown && newValue === 1) {
  24247. this._onbuttondown(buttonType);
  24248. }
  24249. if (this._onbuttonup && newValue === 0) {
  24250. this._onbuttonup(buttonType);
  24251. }
  24252. }
  24253. return newValue;
  24254. };
  24255. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  24256. if (newValue !== currentValue) {
  24257. if (this._ondpaddown && newValue === 1) {
  24258. this._ondpaddown(buttonType);
  24259. }
  24260. if (this._ondpadup && newValue === 0) {
  24261. this._ondpadup(buttonType);
  24262. }
  24263. }
  24264. return newValue;
  24265. };
  24266. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  24267. get: function () {
  24268. return this._buttonA;
  24269. },
  24270. set: function (value) {
  24271. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  24272. },
  24273. enumerable: true,
  24274. configurable: true
  24275. });
  24276. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  24277. get: function () {
  24278. return this._buttonB;
  24279. },
  24280. set: function (value) {
  24281. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  24282. },
  24283. enumerable: true,
  24284. configurable: true
  24285. });
  24286. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  24287. get: function () {
  24288. return this._buttonX;
  24289. },
  24290. set: function (value) {
  24291. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  24292. },
  24293. enumerable: true,
  24294. configurable: true
  24295. });
  24296. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  24297. get: function () {
  24298. return this._buttonY;
  24299. },
  24300. set: function (value) {
  24301. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  24302. },
  24303. enumerable: true,
  24304. configurable: true
  24305. });
  24306. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  24307. get: function () {
  24308. return this._buttonStart;
  24309. },
  24310. set: function (value) {
  24311. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  24312. },
  24313. enumerable: true,
  24314. configurable: true
  24315. });
  24316. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  24317. get: function () {
  24318. return this._buttonBack;
  24319. },
  24320. set: function (value) {
  24321. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  24322. },
  24323. enumerable: true,
  24324. configurable: true
  24325. });
  24326. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  24327. get: function () {
  24328. return this._buttonLB;
  24329. },
  24330. set: function (value) {
  24331. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  24332. },
  24333. enumerable: true,
  24334. configurable: true
  24335. });
  24336. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  24337. get: function () {
  24338. return this._buttonRB;
  24339. },
  24340. set: function (value) {
  24341. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  24342. },
  24343. enumerable: true,
  24344. configurable: true
  24345. });
  24346. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  24347. get: function () {
  24348. return this._buttonLeftStick;
  24349. },
  24350. set: function (value) {
  24351. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  24352. },
  24353. enumerable: true,
  24354. configurable: true
  24355. });
  24356. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  24357. get: function () {
  24358. return this._buttonRightStick;
  24359. },
  24360. set: function (value) {
  24361. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  24362. },
  24363. enumerable: true,
  24364. configurable: true
  24365. });
  24366. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  24367. get: function () {
  24368. return this._dPadUp;
  24369. },
  24370. set: function (value) {
  24371. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  24372. },
  24373. enumerable: true,
  24374. configurable: true
  24375. });
  24376. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  24377. get: function () {
  24378. return this._dPadDown;
  24379. },
  24380. set: function (value) {
  24381. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  24382. },
  24383. enumerable: true,
  24384. configurable: true
  24385. });
  24386. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  24387. get: function () {
  24388. return this._dPadLeft;
  24389. },
  24390. set: function (value) {
  24391. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  24392. },
  24393. enumerable: true,
  24394. configurable: true
  24395. });
  24396. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  24397. get: function () {
  24398. return this._dPadRight;
  24399. },
  24400. set: function (value) {
  24401. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  24402. },
  24403. enumerable: true,
  24404. configurable: true
  24405. });
  24406. Xbox360Pad.prototype.update = function () {
  24407. _super.prototype.update.call(this);
  24408. this.buttonA = this.browserGamepad.buttons[0].value;
  24409. this.buttonB = this.browserGamepad.buttons[1].value;
  24410. this.buttonX = this.browserGamepad.buttons[2].value;
  24411. this.buttonY = this.browserGamepad.buttons[3].value;
  24412. this.buttonLB = this.browserGamepad.buttons[4].value;
  24413. this.buttonRB = this.browserGamepad.buttons[5].value;
  24414. this.leftTrigger = this.browserGamepad.buttons[6].value;
  24415. this.rightTrigger = this.browserGamepad.buttons[7].value;
  24416. this.buttonBack = this.browserGamepad.buttons[8].value;
  24417. this.buttonStart = this.browserGamepad.buttons[9].value;
  24418. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  24419. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  24420. this.dPadUp = this.browserGamepad.buttons[12].value;
  24421. this.dPadDown = this.browserGamepad.buttons[13].value;
  24422. this.dPadLeft = this.browserGamepad.buttons[14].value;
  24423. this.dPadRight = this.browserGamepad.buttons[15].value;
  24424. };
  24425. return Xbox360Pad;
  24426. })(Gamepad);
  24427. BABYLON.Xbox360Pad = Xbox360Pad;
  24428. })(BABYLON || (BABYLON = {}));
  24429. //# sourceMappingURL=babylon.gamepads.js.map
  24430. var BABYLON;
  24431. (function (BABYLON) {
  24432. // We're mainly based on the logic defined into the FreeCamera code
  24433. var GamepadCamera = (function (_super) {
  24434. __extends(GamepadCamera, _super);
  24435. function GamepadCamera(name, position, scene) {
  24436. var _this = this;
  24437. _super.call(this, name, position, scene);
  24438. this.angularSensibility = 200;
  24439. this.moveSensibility = 75;
  24440. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  24441. _this._onNewGameConnected(gamepad);
  24442. });
  24443. }
  24444. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  24445. // Only the first gamepad can control the camera
  24446. if (gamepad.index === 0) {
  24447. this._gamepad = gamepad;
  24448. }
  24449. };
  24450. GamepadCamera.prototype._checkInputs = function () {
  24451. if (!this._gamepad) {
  24452. return;
  24453. }
  24454. var LSValues = this._gamepad.leftStick;
  24455. var normalizedLX = LSValues.x / this.moveSensibility;
  24456. var normalizedLY = LSValues.y / this.moveSensibility;
  24457. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  24458. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  24459. var RSValues = this._gamepad.rightStick;
  24460. var normalizedRX = RSValues.x / this.angularSensibility;
  24461. var normalizedRY = RSValues.y / this.angularSensibility;
  24462. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  24463. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  24464. ;
  24465. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24466. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  24467. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24468. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24469. };
  24470. GamepadCamera.prototype.dispose = function () {
  24471. this._gamepads.dispose();
  24472. _super.prototype.dispose.call(this);
  24473. };
  24474. return GamepadCamera;
  24475. })(BABYLON.FreeCamera);
  24476. BABYLON.GamepadCamera = GamepadCamera;
  24477. })(BABYLON || (BABYLON = {}));
  24478. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24479. var BABYLON;
  24480. (function (BABYLON) {
  24481. var LinesMesh = (function (_super) {
  24482. __extends(LinesMesh, _super);
  24483. function LinesMesh(name, scene, updatable) {
  24484. if (updatable === void 0) { updatable = false; }
  24485. _super.call(this, name, scene);
  24486. this.color = new BABYLON.Color3(1, 1, 1);
  24487. this.alpha = 1;
  24488. this._indices = new Array();
  24489. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24490. attributes: ["position"],
  24491. uniforms: ["worldViewProjection", "color"],
  24492. needAlphaBlending: true
  24493. });
  24494. }
  24495. Object.defineProperty(LinesMesh.prototype, "material", {
  24496. get: function () {
  24497. return this._colorShader;
  24498. },
  24499. enumerable: true,
  24500. configurable: true
  24501. });
  24502. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24503. get: function () {
  24504. return false;
  24505. },
  24506. enumerable: true,
  24507. configurable: true
  24508. });
  24509. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24510. get: function () {
  24511. return false;
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24517. var engine = this.getScene().getEngine();
  24518. var indexToBind = this._geometry.getIndexBuffer();
  24519. // VBOs
  24520. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24521. // Color
  24522. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24523. };
  24524. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24525. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24526. return;
  24527. }
  24528. var engine = this.getScene().getEngine();
  24529. // Draw order
  24530. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24531. };
  24532. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24533. return null;
  24534. };
  24535. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24536. this._colorShader.dispose();
  24537. _super.prototype.dispose.call(this, doNotRecurse);
  24538. };
  24539. return LinesMesh;
  24540. })(BABYLON.Mesh);
  24541. BABYLON.LinesMesh = LinesMesh;
  24542. })(BABYLON || (BABYLON = {}));
  24543. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24544. (function (BABYLON) {
  24545. var OutlineRenderer = (function () {
  24546. function OutlineRenderer(scene) {
  24547. this._scene = scene;
  24548. }
  24549. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24550. if (useOverlay === void 0) { useOverlay = false; }
  24551. var scene = this._scene;
  24552. var engine = this._scene.getEngine();
  24553. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24554. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24555. return;
  24556. }
  24557. var mesh = subMesh.getRenderingMesh();
  24558. var material = subMesh.getMaterial();
  24559. engine.enableEffect(this._effect);
  24560. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24561. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24562. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24563. // Bones
  24564. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  24565. if (useBones) {
  24566. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24567. }
  24568. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24569. // Alpha test
  24570. if (material && material.needAlphaTesting()) {
  24571. var alphaTexture = material.getAlphaTestTexture();
  24572. this._effect.setTexture("diffuseSampler", alphaTexture);
  24573. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24574. }
  24575. if (hardwareInstancedRendering) {
  24576. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  24577. }
  24578. else {
  24579. if (batch.renderSelf[subMesh._id]) {
  24580. this._effect.setMatrix("world", mesh.getWorldMatrix());
  24581. // Draw
  24582. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24583. }
  24584. if (batch.visibleInstances[subMesh._id]) {
  24585. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24586. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24587. this._effect.setMatrix("world", instance.getWorldMatrix());
  24588. // Draw
  24589. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24590. }
  24591. }
  24592. }
  24593. };
  24594. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24595. var defines = [];
  24596. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24597. var mesh = subMesh.getMesh();
  24598. var material = subMesh.getMaterial();
  24599. // Alpha test
  24600. if (material && material.needAlphaTesting()) {
  24601. defines.push("#define ALPHATEST");
  24602. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24603. attribs.push(BABYLON.VertexBuffer.UVKind);
  24604. defines.push("#define UV1");
  24605. }
  24606. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24607. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24608. defines.push("#define UV2");
  24609. }
  24610. }
  24611. // Bones
  24612. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24613. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24614. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24615. defines.push("#define BONES");
  24616. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24617. }
  24618. // Instances
  24619. if (useInstances) {
  24620. defines.push("#define INSTANCES");
  24621. attribs.push("world0");
  24622. attribs.push("world1");
  24623. attribs.push("world2");
  24624. attribs.push("world3");
  24625. }
  24626. // Get correct effect
  24627. var join = defines.join("\n");
  24628. if (this._cachedDefines != join) {
  24629. this._cachedDefines = join;
  24630. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24631. }
  24632. return this._effect.isReady();
  24633. };
  24634. return OutlineRenderer;
  24635. })();
  24636. BABYLON.OutlineRenderer = OutlineRenderer;
  24637. })(BABYLON || (BABYLON = {}));
  24638. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24639. (function (BABYLON) {
  24640. var MeshAssetTask = (function () {
  24641. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24642. this.name = name;
  24643. this.meshesNames = meshesNames;
  24644. this.rootUrl = rootUrl;
  24645. this.sceneFilename = sceneFilename;
  24646. this.isCompleted = false;
  24647. }
  24648. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24649. var _this = this;
  24650. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24651. _this.loadedMeshes = meshes;
  24652. _this.loadedParticleSystems = particleSystems;
  24653. _this.loadedSkeletons = skeletons;
  24654. _this.isCompleted = true;
  24655. if (_this.onSuccess) {
  24656. _this.onSuccess(_this);
  24657. }
  24658. onSuccess();
  24659. }, null, function () {
  24660. if (_this.onError) {
  24661. _this.onError(_this);
  24662. }
  24663. onError();
  24664. });
  24665. };
  24666. return MeshAssetTask;
  24667. })();
  24668. BABYLON.MeshAssetTask = MeshAssetTask;
  24669. var TextFileAssetTask = (function () {
  24670. function TextFileAssetTask(name, url) {
  24671. this.name = name;
  24672. this.url = url;
  24673. this.isCompleted = false;
  24674. }
  24675. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24676. var _this = this;
  24677. BABYLON.Tools.LoadFile(this.url, function (data) {
  24678. _this.text = data;
  24679. _this.isCompleted = true;
  24680. if (_this.onSuccess) {
  24681. _this.onSuccess(_this);
  24682. }
  24683. onSuccess();
  24684. }, null, scene.database, false, function () {
  24685. if (_this.onError) {
  24686. _this.onError(_this);
  24687. }
  24688. onError();
  24689. });
  24690. };
  24691. return TextFileAssetTask;
  24692. })();
  24693. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24694. var BinaryFileAssetTask = (function () {
  24695. function BinaryFileAssetTask(name, url) {
  24696. this.name = name;
  24697. this.url = url;
  24698. this.isCompleted = false;
  24699. }
  24700. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24701. var _this = this;
  24702. BABYLON.Tools.LoadFile(this.url, function (data) {
  24703. _this.data = data;
  24704. _this.isCompleted = true;
  24705. if (_this.onSuccess) {
  24706. _this.onSuccess(_this);
  24707. }
  24708. onSuccess();
  24709. }, null, scene.database, true, function () {
  24710. if (_this.onError) {
  24711. _this.onError(_this);
  24712. }
  24713. onError();
  24714. });
  24715. };
  24716. return BinaryFileAssetTask;
  24717. })();
  24718. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24719. var ImageAssetTask = (function () {
  24720. function ImageAssetTask(name, url) {
  24721. this.name = name;
  24722. this.url = url;
  24723. this.isCompleted = false;
  24724. }
  24725. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24726. var _this = this;
  24727. var img = new Image();
  24728. img.onload = function () {
  24729. _this.image = img;
  24730. _this.isCompleted = true;
  24731. if (_this.onSuccess) {
  24732. _this.onSuccess(_this);
  24733. }
  24734. onSuccess();
  24735. };
  24736. img.onerror = function () {
  24737. if (_this.onError) {
  24738. _this.onError(_this);
  24739. }
  24740. onError();
  24741. };
  24742. img.src = this.url;
  24743. };
  24744. return ImageAssetTask;
  24745. })();
  24746. BABYLON.ImageAssetTask = ImageAssetTask;
  24747. var TextureAssetTask = (function () {
  24748. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24749. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24750. this.name = name;
  24751. this.url = url;
  24752. this.noMipmap = noMipmap;
  24753. this.invertY = invertY;
  24754. this.samplingMode = samplingMode;
  24755. this.isCompleted = false;
  24756. }
  24757. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24758. var _this = this;
  24759. var onload = function () {
  24760. _this.isCompleted = true;
  24761. if (_this.onSuccess) {
  24762. _this.onSuccess(_this);
  24763. }
  24764. onSuccess();
  24765. };
  24766. var onerror = function () {
  24767. if (_this.onError) {
  24768. _this.onError(_this);
  24769. }
  24770. onError();
  24771. };
  24772. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24773. };
  24774. return TextureAssetTask;
  24775. })();
  24776. BABYLON.TextureAssetTask = TextureAssetTask;
  24777. var AssetsManager = (function () {
  24778. function AssetsManager(scene) {
  24779. this._tasks = new Array();
  24780. this._waitingTasksCount = 0;
  24781. this.useDefaultLoadingScreen = true;
  24782. this._scene = scene;
  24783. }
  24784. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24785. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24786. this._tasks.push(task);
  24787. return task;
  24788. };
  24789. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24790. var task = new TextFileAssetTask(taskName, url);
  24791. this._tasks.push(task);
  24792. return task;
  24793. };
  24794. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24795. var task = new BinaryFileAssetTask(taskName, url);
  24796. this._tasks.push(task);
  24797. return task;
  24798. };
  24799. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24800. var task = new ImageAssetTask(taskName, url);
  24801. this._tasks.push(task);
  24802. return task;
  24803. };
  24804. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24805. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24806. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24807. this._tasks.push(task);
  24808. return task;
  24809. };
  24810. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24811. this._waitingTasksCount--;
  24812. if (this._waitingTasksCount === 0) {
  24813. if (this.onFinish) {
  24814. this.onFinish(this._tasks);
  24815. }
  24816. this._scene.getEngine().hideLoadingUI();
  24817. }
  24818. };
  24819. AssetsManager.prototype._runTask = function (task) {
  24820. var _this = this;
  24821. task.run(this._scene, function () {
  24822. if (_this.onTaskSuccess) {
  24823. _this.onTaskSuccess(task);
  24824. }
  24825. _this._decreaseWaitingTasksCount();
  24826. }, function () {
  24827. if (_this.onTaskError) {
  24828. _this.onTaskError(task);
  24829. }
  24830. _this._decreaseWaitingTasksCount();
  24831. });
  24832. };
  24833. AssetsManager.prototype.reset = function () {
  24834. this._tasks = new Array();
  24835. return this;
  24836. };
  24837. AssetsManager.prototype.load = function () {
  24838. this._waitingTasksCount = this._tasks.length;
  24839. if (this._waitingTasksCount === 0) {
  24840. if (this.onFinish) {
  24841. this.onFinish(this._tasks);
  24842. }
  24843. return this;
  24844. }
  24845. if (this.useDefaultLoadingScreen) {
  24846. this._scene.getEngine().displayLoadingUI();
  24847. }
  24848. for (var index = 0; index < this._tasks.length; index++) {
  24849. var task = this._tasks[index];
  24850. this._runTask(task);
  24851. }
  24852. return this;
  24853. };
  24854. return AssetsManager;
  24855. })();
  24856. BABYLON.AssetsManager = AssetsManager;
  24857. })(BABYLON || (BABYLON = {}));
  24858. //# sourceMappingURL=babylon.assetsManager.js.map
  24859. var BABYLON;
  24860. (function (BABYLON) {
  24861. var VRDeviceOrientationCamera = (function (_super) {
  24862. __extends(VRDeviceOrientationCamera, _super);
  24863. function VRDeviceOrientationCamera(name, position, scene) {
  24864. _super.call(this, name, position, scene);
  24865. this._alpha = 0;
  24866. this._beta = 0;
  24867. this._gamma = 0;
  24868. }
  24869. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24870. this._alpha = +evt.alpha | 0;
  24871. this._beta = +evt.beta | 0;
  24872. this._gamma = +evt.gamma | 0;
  24873. if (this._gamma < 0) {
  24874. this._gamma = 90 + this._gamma;
  24875. }
  24876. else {
  24877. // Incline it in the correct angle.
  24878. this._gamma = 270 - this._gamma;
  24879. }
  24880. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24881. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24882. this.rotation.z = this._beta / 180.0 * Math.PI;
  24883. };
  24884. return VRDeviceOrientationCamera;
  24885. })(BABYLON.OculusCamera);
  24886. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24887. })(BABYLON || (BABYLON = {}));
  24888. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24889. var BABYLON;
  24890. (function (BABYLON) {
  24891. var WebVRCamera = (function (_super) {
  24892. __extends(WebVRCamera, _super);
  24893. function WebVRCamera(name, position, scene) {
  24894. _super.call(this, name, position, scene);
  24895. this._hmdDevice = null;
  24896. this._sensorDevice = null;
  24897. this._cacheState = null;
  24898. this._cacheQuaternion = new BABYLON.Quaternion();
  24899. this._cacheRotation = BABYLON.Vector3.Zero();
  24900. this._vrEnabled = false;
  24901. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24902. }
  24903. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24904. var size = devices.length;
  24905. var i = 0;
  24906. // Reset devices.
  24907. this._sensorDevice = null;
  24908. this._hmdDevice = null;
  24909. while (i < size && this._hmdDevice === null) {
  24910. if (devices[i] instanceof HMDVRDevice) {
  24911. this._hmdDevice = devices[i];
  24912. }
  24913. i++;
  24914. }
  24915. i = 0;
  24916. while (i < size && this._sensorDevice === null) {
  24917. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24918. this._sensorDevice = devices[i];
  24919. }
  24920. i++;
  24921. }
  24922. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24923. };
  24924. WebVRCamera.prototype._update = function () {
  24925. if (this._vrEnabled) {
  24926. this._cacheState = this._sensorDevice.getState();
  24927. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24928. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24929. this.rotation.x = -this._cacheRotation.z;
  24930. this.rotation.y = -this._cacheRotation.y;
  24931. this.rotation.z = this._cacheRotation.x;
  24932. }
  24933. _super.prototype._update.call(this);
  24934. };
  24935. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24936. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24937. if (navigator.getVRDevices) {
  24938. navigator.getVRDevices().then(this._getWebVRDevices);
  24939. }
  24940. else if (navigator.mozGetVRDevices) {
  24941. navigator.mozGetVRDevices(this._getWebVRDevices);
  24942. }
  24943. };
  24944. WebVRCamera.prototype.detachControl = function (element) {
  24945. _super.prototype.detachControl.call(this, element);
  24946. this._vrEnabled = false;
  24947. };
  24948. return WebVRCamera;
  24949. })(BABYLON.OculusCamera);
  24950. BABYLON.WebVRCamera = WebVRCamera;
  24951. })(BABYLON || (BABYLON = {}));
  24952. //# sourceMappingURL=babylon.webVRCamera.js.map
  24953. var BABYLON;
  24954. (function (BABYLON) {
  24955. // Standard optimizations
  24956. var SceneOptimization = (function () {
  24957. function SceneOptimization(priority) {
  24958. if (priority === void 0) { priority = 0; }
  24959. this.priority = priority;
  24960. this.apply = function (scene) {
  24961. return true; // Return true if everything that can be done was applied
  24962. };
  24963. }
  24964. return SceneOptimization;
  24965. })();
  24966. BABYLON.SceneOptimization = SceneOptimization;
  24967. var TextureOptimization = (function (_super) {
  24968. __extends(TextureOptimization, _super);
  24969. function TextureOptimization(priority, maximumSize) {
  24970. var _this = this;
  24971. if (priority === void 0) { priority = 0; }
  24972. if (maximumSize === void 0) { maximumSize = 1024; }
  24973. _super.call(this, priority);
  24974. this.priority = priority;
  24975. this.maximumSize = maximumSize;
  24976. this.apply = function (scene) {
  24977. var allDone = true;
  24978. for (var index = 0; index < scene.textures.length; index++) {
  24979. var texture = scene.textures[index];
  24980. if (!texture.canRescale) {
  24981. continue;
  24982. }
  24983. var currentSize = texture.getSize();
  24984. var maxDimension = Math.max(currentSize.width, currentSize.height);
  24985. if (maxDimension > _this.maximumSize) {
  24986. texture.scale(0.5);
  24987. allDone = false;
  24988. }
  24989. }
  24990. return allDone;
  24991. };
  24992. }
  24993. return TextureOptimization;
  24994. })(SceneOptimization);
  24995. BABYLON.TextureOptimization = TextureOptimization;
  24996. var HardwareScalingOptimization = (function (_super) {
  24997. __extends(HardwareScalingOptimization, _super);
  24998. function HardwareScalingOptimization(priority, maximumScale) {
  24999. var _this = this;
  25000. if (priority === void 0) { priority = 0; }
  25001. if (maximumScale === void 0) { maximumScale = 2; }
  25002. _super.call(this, priority);
  25003. this.priority = priority;
  25004. this.maximumScale = maximumScale;
  25005. this._currentScale = 1;
  25006. this.apply = function (scene) {
  25007. _this._currentScale++;
  25008. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25009. return _this._currentScale >= _this.maximumScale;
  25010. };
  25011. }
  25012. return HardwareScalingOptimization;
  25013. })(SceneOptimization);
  25014. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25015. var ShadowsOptimization = (function (_super) {
  25016. __extends(ShadowsOptimization, _super);
  25017. function ShadowsOptimization() {
  25018. _super.apply(this, arguments);
  25019. this.apply = function (scene) {
  25020. scene.shadowsEnabled = false;
  25021. return true;
  25022. };
  25023. }
  25024. return ShadowsOptimization;
  25025. })(SceneOptimization);
  25026. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25027. var PostProcessesOptimization = (function (_super) {
  25028. __extends(PostProcessesOptimization, _super);
  25029. function PostProcessesOptimization() {
  25030. _super.apply(this, arguments);
  25031. this.apply = function (scene) {
  25032. scene.postProcessesEnabled = false;
  25033. return true;
  25034. };
  25035. }
  25036. return PostProcessesOptimization;
  25037. })(SceneOptimization);
  25038. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25039. var LensFlaresOptimization = (function (_super) {
  25040. __extends(LensFlaresOptimization, _super);
  25041. function LensFlaresOptimization() {
  25042. _super.apply(this, arguments);
  25043. this.apply = function (scene) {
  25044. scene.lensFlaresEnabled = false;
  25045. return true;
  25046. };
  25047. }
  25048. return LensFlaresOptimization;
  25049. })(SceneOptimization);
  25050. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25051. var ParticlesOptimization = (function (_super) {
  25052. __extends(ParticlesOptimization, _super);
  25053. function ParticlesOptimization() {
  25054. _super.apply(this, arguments);
  25055. this.apply = function (scene) {
  25056. scene.particlesEnabled = false;
  25057. return true;
  25058. };
  25059. }
  25060. return ParticlesOptimization;
  25061. })(SceneOptimization);
  25062. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25063. var RenderTargetsOptimization = (function (_super) {
  25064. __extends(RenderTargetsOptimization, _super);
  25065. function RenderTargetsOptimization() {
  25066. _super.apply(this, arguments);
  25067. this.apply = function (scene) {
  25068. scene.renderTargetsEnabled = false;
  25069. return true;
  25070. };
  25071. }
  25072. return RenderTargetsOptimization;
  25073. })(SceneOptimization);
  25074. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25075. var MergeMeshesOptimization = (function (_super) {
  25076. __extends(MergeMeshesOptimization, _super);
  25077. function MergeMeshesOptimization() {
  25078. var _this = this;
  25079. _super.apply(this, arguments);
  25080. this._canBeMerged = function (abstractMesh) {
  25081. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25082. return false;
  25083. }
  25084. var mesh = abstractMesh;
  25085. if (!mesh.isVisible || !mesh.isEnabled()) {
  25086. return false;
  25087. }
  25088. if (mesh.instances.length > 0) {
  25089. return false;
  25090. }
  25091. if (mesh.skeleton || mesh.hasLODLevels) {
  25092. return false;
  25093. }
  25094. return true;
  25095. };
  25096. this.apply = function (scene) {
  25097. var globalPool = scene.meshes.slice(0);
  25098. var globalLength = globalPool.length;
  25099. for (var index = 0; index < globalLength; index++) {
  25100. var currentPool = new Array();
  25101. var current = globalPool[index];
  25102. // Checks
  25103. if (!_this._canBeMerged(current)) {
  25104. continue;
  25105. }
  25106. currentPool.push(current);
  25107. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25108. var otherMesh = globalPool[subIndex];
  25109. if (!_this._canBeMerged(otherMesh)) {
  25110. continue;
  25111. }
  25112. if (otherMesh.material !== current.material) {
  25113. continue;
  25114. }
  25115. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25116. continue;
  25117. }
  25118. currentPool.push(otherMesh);
  25119. globalLength--;
  25120. globalPool.splice(subIndex, 1);
  25121. subIndex--;
  25122. }
  25123. if (currentPool.length < 2) {
  25124. continue;
  25125. }
  25126. // Merge meshes
  25127. BABYLON.Mesh.MergeMeshes(currentPool);
  25128. }
  25129. return true;
  25130. };
  25131. }
  25132. return MergeMeshesOptimization;
  25133. })(SceneOptimization);
  25134. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  25135. // Options
  25136. var SceneOptimizerOptions = (function () {
  25137. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  25138. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  25139. if (trackerDuration === void 0) { trackerDuration = 2000; }
  25140. this.targetFrameRate = targetFrameRate;
  25141. this.trackerDuration = trackerDuration;
  25142. this.optimizations = new Array();
  25143. }
  25144. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  25145. var result = new SceneOptimizerOptions(targetFrameRate);
  25146. var priority = 0;
  25147. result.optimizations.push(new MergeMeshesOptimization(priority));
  25148. result.optimizations.push(new ShadowsOptimization(priority));
  25149. result.optimizations.push(new LensFlaresOptimization(priority));
  25150. // Next priority
  25151. priority++;
  25152. result.optimizations.push(new PostProcessesOptimization(priority));
  25153. result.optimizations.push(new ParticlesOptimization(priority));
  25154. // Next priority
  25155. priority++;
  25156. result.optimizations.push(new TextureOptimization(priority, 1024));
  25157. return result;
  25158. };
  25159. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  25160. var result = new SceneOptimizerOptions(targetFrameRate);
  25161. var priority = 0;
  25162. result.optimizations.push(new MergeMeshesOptimization(priority));
  25163. result.optimizations.push(new ShadowsOptimization(priority));
  25164. result.optimizations.push(new LensFlaresOptimization(priority));
  25165. // Next priority
  25166. priority++;
  25167. result.optimizations.push(new PostProcessesOptimization(priority));
  25168. result.optimizations.push(new ParticlesOptimization(priority));
  25169. // Next priority
  25170. priority++;
  25171. result.optimizations.push(new TextureOptimization(priority, 512));
  25172. // Next priority
  25173. priority++;
  25174. result.optimizations.push(new RenderTargetsOptimization(priority));
  25175. // Next priority
  25176. priority++;
  25177. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  25178. return result;
  25179. };
  25180. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  25181. var result = new SceneOptimizerOptions(targetFrameRate);
  25182. var priority = 0;
  25183. result.optimizations.push(new MergeMeshesOptimization(priority));
  25184. result.optimizations.push(new ShadowsOptimization(priority));
  25185. result.optimizations.push(new LensFlaresOptimization(priority));
  25186. // Next priority
  25187. priority++;
  25188. result.optimizations.push(new PostProcessesOptimization(priority));
  25189. result.optimizations.push(new ParticlesOptimization(priority));
  25190. // Next priority
  25191. priority++;
  25192. result.optimizations.push(new TextureOptimization(priority, 256));
  25193. // Next priority
  25194. priority++;
  25195. result.optimizations.push(new RenderTargetsOptimization(priority));
  25196. // Next priority
  25197. priority++;
  25198. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  25199. return result;
  25200. };
  25201. return SceneOptimizerOptions;
  25202. })();
  25203. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  25204. // Scene optimizer tool
  25205. var SceneOptimizer = (function () {
  25206. function SceneOptimizer() {
  25207. }
  25208. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  25209. // TODO: add an epsilon
  25210. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  25211. if (onSuccess) {
  25212. onSuccess();
  25213. }
  25214. return;
  25215. }
  25216. // Apply current level of optimizations
  25217. var allDone = true;
  25218. var noOptimizationApplied = true;
  25219. for (var index = 0; index < options.optimizations.length; index++) {
  25220. var optimization = options.optimizations[index];
  25221. if (optimization.priority === currentPriorityLevel) {
  25222. noOptimizationApplied = false;
  25223. allDone = allDone && optimization.apply(scene);
  25224. }
  25225. }
  25226. // If no optimization was applied, this is a failure :(
  25227. if (noOptimizationApplied) {
  25228. if (onFailure) {
  25229. onFailure();
  25230. }
  25231. return;
  25232. }
  25233. // If all optimizations were done, move to next level
  25234. if (allDone) {
  25235. currentPriorityLevel++;
  25236. }
  25237. // Let's the system running for a specific amount of time before checking FPS
  25238. scene.executeWhenReady(function () {
  25239. setTimeout(function () {
  25240. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  25241. }, options.trackerDuration);
  25242. });
  25243. };
  25244. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  25245. if (!options) {
  25246. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  25247. }
  25248. // Let's the system running for a specific amount of time before checking FPS
  25249. scene.executeWhenReady(function () {
  25250. setTimeout(function () {
  25251. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  25252. }, options.trackerDuration);
  25253. });
  25254. };
  25255. return SceneOptimizer;
  25256. })();
  25257. BABYLON.SceneOptimizer = SceneOptimizer;
  25258. })(BABYLON || (BABYLON = {}));
  25259. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  25260. (function (BABYLON) {
  25261. var Internals;
  25262. (function (Internals) {
  25263. var MeshLODLevel = (function () {
  25264. function MeshLODLevel(distance, mesh) {
  25265. this.distance = distance;
  25266. this.mesh = mesh;
  25267. }
  25268. return MeshLODLevel;
  25269. })();
  25270. Internals.MeshLODLevel = MeshLODLevel;
  25271. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  25272. })(BABYLON || (BABYLON = {}));
  25273. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  25274. (function (BABYLON) {
  25275. var AudioEngine = (function () {
  25276. function AudioEngine() {
  25277. this.audioContext = null;
  25278. this.canUseWebAudio = false;
  25279. try {
  25280. if (typeof AudioContext !== 'undefined') {
  25281. this.audioContext = new AudioContext();
  25282. this.canUseWebAudio = true;
  25283. }
  25284. else if (typeof webkitAudioContext !== 'undefined') {
  25285. this.audioContext = new webkitAudioContext();
  25286. this.canUseWebAudio = true;
  25287. }
  25288. else {
  25289. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  25290. }
  25291. }
  25292. catch (e) {
  25293. this.canUseWebAudio = false;
  25294. BABYLON.Tools.Error("Web Audio: " + e.message);
  25295. }
  25296. // create a global volume gain node
  25297. if (this.canUseWebAudio) {
  25298. this.masterGain = this.audioContext.createGain();
  25299. this.masterGain.gain.value = 1;
  25300. this.masterGain.connect(this.audioContext.destination);
  25301. }
  25302. }
  25303. AudioEngine.prototype.dispose = function () {
  25304. if (this.canUseWebAudio) {
  25305. if (this._connectedAnalyser) {
  25306. this._connectedAnalyser.stopDebugCanvas();
  25307. this._connectedAnalyser.dispose();
  25308. this.masterGain.disconnect();
  25309. this.masterGain.connect(this.audioContext.destination);
  25310. this._connectedAnalyser = null;
  25311. }
  25312. this.masterGain.gain.value = 1;
  25313. }
  25314. };
  25315. AudioEngine.prototype.getGlobalVolume = function () {
  25316. if (this.canUseWebAudio) {
  25317. return this.masterGain.gain.value;
  25318. }
  25319. else {
  25320. return -1;
  25321. }
  25322. };
  25323. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  25324. if (this.canUseWebAudio) {
  25325. this.masterGain.gain.value = newVolume;
  25326. }
  25327. };
  25328. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  25329. if (this._connectedAnalyser) {
  25330. this._connectedAnalyser.stopDebugCanvas();
  25331. }
  25332. this._connectedAnalyser = analyser;
  25333. if (this.canUseWebAudio) {
  25334. this.masterGain.disconnect();
  25335. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  25336. }
  25337. };
  25338. return AudioEngine;
  25339. })();
  25340. BABYLON.AudioEngine = AudioEngine;
  25341. })(BABYLON || (BABYLON = {}));
  25342. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  25343. (function (BABYLON) {
  25344. var Sound = (function () {
  25345. /**
  25346. * Create a sound and attach it to a scene
  25347. * @param name Name of your sound
  25348. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  25349. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  25350. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  25351. */
  25352. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  25353. var _this = this;
  25354. this.autoplay = false;
  25355. this.loop = false;
  25356. this.useCustomAttenuation = false;
  25357. this.spatialSound = false;
  25358. this.refDistance = 1;
  25359. this.rolloffFactor = 1;
  25360. this.maxDistance = 100;
  25361. this.distanceModel = "linear";
  25362. this.panningModel = "HRTF";
  25363. this.playbackRate = 1;
  25364. this._startTime = 0;
  25365. this._startOffset = 0;
  25366. this._position = BABYLON.Vector3.Zero();
  25367. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  25368. this._volume = 1;
  25369. this._isLoaded = false;
  25370. this._isReadyToPlay = false;
  25371. this._isPlaying = false;
  25372. this._isDirectional = false;
  25373. // Used if you'd like to create a directional sound.
  25374. // If not set, the sound will be omnidirectional
  25375. this._coneInnerAngle = 360;
  25376. this._coneOuterAngle = 360;
  25377. this._coneOuterGain = 0;
  25378. this.name = name;
  25379. this._scene = scene;
  25380. this._audioEngine = this._scene.getEngine().getAudioEngine();
  25381. this._readyToPlayCallback = readyToPlayCallback;
  25382. // Default custom attenuation function is a linear attenuation
  25383. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  25384. if (currentDistance < maxDistance) {
  25385. return currentVolume * (1 - currentDistance / maxDistance);
  25386. }
  25387. else {
  25388. return 0;
  25389. }
  25390. };
  25391. if (options) {
  25392. this.autoplay = options.autoplay || false;
  25393. this.loop = options.loop || false;
  25394. // if volume === 0, we need another way to check this option
  25395. if (options.volume !== undefined) {
  25396. this._volume = options.volume;
  25397. }
  25398. this.spatialSound = options.spatialSound || false;
  25399. this.maxDistance = options.maxDistance || 100;
  25400. this.useCustomAttenuation = options.useCustomAttenuation || false;
  25401. this.rolloffFactor = options.rolloffFactor || 1;
  25402. this.refDistance = options.refDistance || 1;
  25403. this.distanceModel = options.distanceModel || "linear";
  25404. this.panningModel = options.panningModel || "HRTF";
  25405. this.playbackRate = options.playbackRate || 1;
  25406. }
  25407. if (this._audioEngine.canUseWebAudio) {
  25408. this._soundGain = this._audioEngine.audioContext.createGain();
  25409. this._soundGain.gain.value = this._volume;
  25410. this._inputAudioNode = this._soundGain;
  25411. this._ouputAudioNode = this._soundGain;
  25412. if (this.spatialSound) {
  25413. this._createSpatialParameters();
  25414. }
  25415. this._scene.mainSoundTrack.AddSound(this);
  25416. if (typeof (urlOrArrayBuffer) === "string") {
  25417. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  25418. _this._soundLoaded(data);
  25419. }, null, null, true);
  25420. }
  25421. else {
  25422. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  25423. this._soundLoaded(urlOrArrayBuffer);
  25424. }
  25425. else {
  25426. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  25427. }
  25428. }
  25429. }
  25430. }
  25431. Sound.prototype.dispose = function () {
  25432. if (this._audioEngine.canUseWebAudio && this._isReadyToPlay) {
  25433. if (this._isPlaying) {
  25434. this.stop();
  25435. }
  25436. this._isReadyToPlay = false;
  25437. if (this.soundTrackId === -1) {
  25438. this._scene.mainSoundTrack.RemoveSound(this);
  25439. }
  25440. else {
  25441. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  25442. }
  25443. this._soundGain.disconnect();
  25444. this._soundSource.disconnect();
  25445. if (this._soundPanner) {
  25446. this._soundPanner.disconnect();
  25447. this._soundPanner = null;
  25448. }
  25449. this._audioBuffer = null;
  25450. this._soundGain = null;
  25451. this._soundSource = null;
  25452. if (this._connectedMesh) {
  25453. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  25454. this._connectedMesh = null;
  25455. }
  25456. }
  25457. };
  25458. Sound.prototype._soundLoaded = function (audioData) {
  25459. var _this = this;
  25460. this._isLoaded = true;
  25461. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25462. _this._audioBuffer = buffer;
  25463. _this._isReadyToPlay = true;
  25464. if (_this.autoplay) {
  25465. _this.play();
  25466. }
  25467. if (_this._readyToPlayCallback) {
  25468. _this._readyToPlayCallback();
  25469. }
  25470. }, function (error) {
  25471. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25472. });
  25473. };
  25474. Sound.prototype.updateOptions = function (options) {
  25475. if (options) {
  25476. this.loop = options.loop || this.loop;
  25477. this.maxDistance = options.maxDistance || this.maxDistance;
  25478. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  25479. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  25480. this.refDistance = options.refDistance || this.refDistance;
  25481. this.distanceModel = options.distanceModel || this.distanceModel;
  25482. this.panningModel = options.panningModel || this.panningModel;
  25483. this.playbackRate = options.playbackRate || this.playbackRate;
  25484. }
  25485. };
  25486. Sound.prototype._createSpatialParameters = function () {
  25487. if (this._audioEngine.canUseWebAudio) {
  25488. this._soundPanner = this._audioEngine.audioContext.createPanner();
  25489. if (this.useCustomAttenuation) {
  25490. // Tricks to disable in a way embedded Web Audio attenuation
  25491. this._soundPanner.distanceModel = "linear";
  25492. this._soundPanner.maxDistance = Number.MAX_VALUE;
  25493. this._soundPanner.refDistance = 1;
  25494. this._soundPanner.rolloffFactor = 1;
  25495. this._soundPanner.panningModel = "HRTF";
  25496. }
  25497. else {
  25498. this._soundPanner.distanceModel = this.distanceModel;
  25499. this._soundPanner.maxDistance = this.maxDistance;
  25500. this._soundPanner.refDistance = this.refDistance;
  25501. this._soundPanner.rolloffFactor = this.rolloffFactor;
  25502. this._soundPanner.panningModel = this.panningModel;
  25503. }
  25504. this._soundPanner.connect(this._ouputAudioNode);
  25505. this._inputAudioNode = this._soundPanner;
  25506. }
  25507. };
  25508. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  25509. if (this._audioEngine.canUseWebAudio) {
  25510. this._ouputAudioNode.disconnect();
  25511. this._ouputAudioNode.connect(soundTrackAudioNode);
  25512. }
  25513. };
  25514. /**
  25515. * Transform this sound into a directional source
  25516. * @param coneInnerAngle Size of the inner cone in degree
  25517. * @param coneOuterAngle Size of the outer cone in degree
  25518. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  25519. */
  25520. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  25521. if (coneOuterAngle < coneInnerAngle) {
  25522. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  25523. return;
  25524. }
  25525. this._coneInnerAngle = coneInnerAngle;
  25526. this._coneOuterAngle = coneOuterAngle;
  25527. this._coneOuterGain = coneOuterGain;
  25528. this._isDirectional = true;
  25529. if (this._isPlaying && this.loop) {
  25530. this.stop();
  25531. this.play();
  25532. }
  25533. };
  25534. Sound.prototype.setPosition = function (newPosition) {
  25535. this._position = newPosition;
  25536. if (this._isPlaying && this.spatialSound) {
  25537. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25538. }
  25539. };
  25540. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  25541. this._localDirection = newLocalDirection;
  25542. if (this._connectedMesh && this._isPlaying) {
  25543. this._updateDirection();
  25544. }
  25545. };
  25546. Sound.prototype._updateDirection = function () {
  25547. var mat = this._connectedMesh.getWorldMatrix();
  25548. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25549. direction.normalize();
  25550. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25551. };
  25552. Sound.prototype.updateDistanceFromListener = function () {
  25553. if (this._connectedMesh && this.useCustomAttenuation) {
  25554. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25555. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25556. }
  25557. };
  25558. Sound.prototype.setAttenuationFunction = function (callback) {
  25559. this._customAttenuationFunction = callback;
  25560. };
  25561. /**
  25562. * Play the sound
  25563. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25564. */
  25565. Sound.prototype.play = function (time) {
  25566. if (this._isReadyToPlay) {
  25567. try {
  25568. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25569. if (!this._soundSource) {
  25570. if (this.spatialSound) {
  25571. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25572. if (this._isDirectional) {
  25573. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25574. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25575. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25576. if (this._connectedMesh) {
  25577. this._updateDirection();
  25578. }
  25579. else {
  25580. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25581. }
  25582. }
  25583. }
  25584. }
  25585. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  25586. this._soundSource.buffer = this._audioBuffer;
  25587. this._soundSource.connect(this._inputAudioNode);
  25588. this._soundSource.loop = this.loop;
  25589. this._soundSource.playbackRate.value = this.playbackRate;
  25590. this._startTime = startTime;
  25591. if (this.onended) {
  25592. this._soundSource.onended = this.onended;
  25593. }
  25594. this._soundSource.start(startTime, this._startOffset % this._soundSource.buffer.duration);
  25595. this._isPlaying = true;
  25596. }
  25597. catch (ex) {
  25598. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  25599. }
  25600. }
  25601. };
  25602. /**
  25603. * Stop the sound
  25604. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25605. */
  25606. Sound.prototype.stop = function (time) {
  25607. if (this._isPlaying) {
  25608. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25609. this._soundSource.stop(stopTime);
  25610. this._isPlaying = false;
  25611. }
  25612. };
  25613. Sound.prototype.pause = function () {
  25614. if (this._isPlaying) {
  25615. this._soundSource.stop(0);
  25616. this._startOffset += this._audioEngine.audioContext.currentTime - this._startTime;
  25617. }
  25618. };
  25619. Sound.prototype.setVolume = function (newVolume) {
  25620. this._volume = newVolume;
  25621. if (this._audioEngine.canUseWebAudio) {
  25622. this._soundGain.gain.value = newVolume;
  25623. }
  25624. };
  25625. Sound.prototype.getVolume = function () {
  25626. return this._volume;
  25627. };
  25628. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25629. var _this = this;
  25630. this._connectedMesh = meshToConnectTo;
  25631. if (!this.spatialSound) {
  25632. this._createSpatialParameters();
  25633. this.spatialSound = true;
  25634. if (this._isPlaying && this.loop) {
  25635. this.stop();
  25636. this.play();
  25637. }
  25638. }
  25639. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  25640. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  25641. };
  25642. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25643. this.setPosition(connectedMesh.position);
  25644. if (this._isDirectional && this._isPlaying) {
  25645. this._updateDirection();
  25646. }
  25647. };
  25648. return Sound;
  25649. })();
  25650. BABYLON.Sound = Sound;
  25651. })(BABYLON || (BABYLON = {}));
  25652. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25653. (function (BABYLON) {
  25654. var SoundTrack = (function () {
  25655. function SoundTrack(scene, options) {
  25656. this.id = -1;
  25657. this._isMainTrack = false;
  25658. this._scene = scene;
  25659. this._audioEngine = scene.getEngine().getAudioEngine();
  25660. this.soundCollection = new Array();
  25661. if (this._audioEngine.canUseWebAudio) {
  25662. this._trackGain = this._audioEngine.audioContext.createGain();
  25663. this._trackGain.connect(this._audioEngine.masterGain);
  25664. if (options) {
  25665. if (options.volume) {
  25666. this._trackGain.gain.value = options.volume;
  25667. }
  25668. if (options.mainTrack) {
  25669. this._isMainTrack = options.mainTrack;
  25670. }
  25671. }
  25672. }
  25673. if (!this._isMainTrack) {
  25674. this._scene.soundTracks.push(this);
  25675. this.id = this._scene.soundTracks.length - 1;
  25676. }
  25677. }
  25678. SoundTrack.prototype.dispose = function () {
  25679. if (this._audioEngine.canUseWebAudio) {
  25680. if (this._connectedAnalyser) {
  25681. this._connectedAnalyser.stopDebugCanvas();
  25682. }
  25683. while (this.soundCollection.length) {
  25684. this.soundCollection[0].dispose();
  25685. }
  25686. this._trackGain.disconnect();
  25687. this._trackGain = null;
  25688. }
  25689. };
  25690. SoundTrack.prototype.AddSound = function (sound) {
  25691. sound.connectToSoundTrackAudioNode(this._trackGain);
  25692. if (sound.soundTrackId) {
  25693. if (sound.soundTrackId === -1) {
  25694. this._scene.mainSoundTrack.RemoveSound(sound);
  25695. }
  25696. else {
  25697. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25698. }
  25699. }
  25700. this.soundCollection.push(sound);
  25701. sound.soundTrackId = this.id;
  25702. };
  25703. SoundTrack.prototype.RemoveSound = function (sound) {
  25704. var index = this.soundCollection.indexOf(sound);
  25705. if (index !== -1) {
  25706. this.soundCollection.splice(index, 1);
  25707. }
  25708. };
  25709. SoundTrack.prototype.setVolume = function (newVolume) {
  25710. if (this._audioEngine.canUseWebAudio) {
  25711. this._trackGain.gain.value = newVolume;
  25712. }
  25713. };
  25714. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  25715. if (this._connectedAnalyser) {
  25716. this._connectedAnalyser.stopDebugCanvas();
  25717. }
  25718. this._connectedAnalyser = analyser;
  25719. if (this._audioEngine.canUseWebAudio) {
  25720. this._trackGain.disconnect();
  25721. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  25722. }
  25723. };
  25724. return SoundTrack;
  25725. })();
  25726. BABYLON.SoundTrack = SoundTrack;
  25727. })(BABYLON || (BABYLON = {}));
  25728. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  25729. (function (BABYLON) {
  25730. var DebugLayer = (function () {
  25731. function DebugLayer(scene) {
  25732. var _this = this;
  25733. this._enabled = false;
  25734. this._labelsEnabled = false;
  25735. this._displayStatistics = true;
  25736. this._displayTree = false;
  25737. this._displayLogs = false;
  25738. this._identityMatrix = BABYLON.Matrix.Identity();
  25739. this.axisRatio = 0.02;
  25740. this.accentColor = "orange";
  25741. this._scene = scene;
  25742. this._syncPositions = function () {
  25743. var engine = _this._scene.getEngine();
  25744. var canvasRect = engine.getRenderingCanvasClientRect();
  25745. if (_this._showUI) {
  25746. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  25747. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  25748. _this._statsDiv.style.width = "400px";
  25749. _this._statsDiv.style.height = "auto";
  25750. _this._statsSubsetDiv.style.maxHeight = "240px";
  25751. _this._optionsDiv.style.left = "0px";
  25752. _this._optionsDiv.style.top = "10px";
  25753. _this._optionsDiv.style.width = "200px";
  25754. _this._optionsDiv.style.height = "auto";
  25755. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  25756. _this._logDiv.style.left = "0px";
  25757. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  25758. _this._logDiv.style.width = "600px";
  25759. _this._logDiv.style.height = "160px";
  25760. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  25761. _this._treeDiv.style.top = "10px";
  25762. _this._treeDiv.style.width = "300px";
  25763. _this._treeDiv.style.height = "auto";
  25764. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  25765. }
  25766. _this._globalDiv.style.left = canvasRect.left + "px";
  25767. _this._globalDiv.style.top = canvasRect.top + "px";
  25768. _this._drawingCanvas.style.left = "0px";
  25769. _this._drawingCanvas.style.top = "0px";
  25770. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  25771. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  25772. var devicePixelRatio = window.devicePixelRatio || 1;
  25773. var context = _this._drawingContext;
  25774. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  25775. _this._ratio = devicePixelRatio / backingStoreRatio;
  25776. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  25777. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  25778. };
  25779. this._onCanvasClick = function (evt) {
  25780. _this._clickPosition = {
  25781. x: evt.clientX * _this._ratio,
  25782. y: evt.clientY * _this._ratio
  25783. };
  25784. };
  25785. this._syncData = function () {
  25786. if (_this._showUI) {
  25787. if (_this._displayStatistics) {
  25788. _this._displayStats();
  25789. _this._statsDiv.style.display = "";
  25790. }
  25791. else {
  25792. _this._statsDiv.style.display = "none";
  25793. }
  25794. if (_this._displayLogs) {
  25795. _this._logDiv.style.display = "";
  25796. }
  25797. else {
  25798. _this._logDiv.style.display = "none";
  25799. }
  25800. if (_this._displayTree) {
  25801. _this._treeDiv.style.display = "";
  25802. if (_this._needToRefreshMeshesTree) {
  25803. _this._needToRefreshMeshesTree = false;
  25804. _this._refreshMeshesTreeContent();
  25805. }
  25806. }
  25807. else {
  25808. _this._treeDiv.style.display = "none";
  25809. }
  25810. }
  25811. if (_this._labelsEnabled || !_this._showUI) {
  25812. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  25813. var engine = _this._scene.getEngine();
  25814. var viewport = _this._scene.activeCamera.viewport;
  25815. var globalViewport = viewport.toGlobal(engine);
  25816. // Meshes
  25817. var meshes = _this._scene.getActiveMeshes();
  25818. for (var index = 0; index < meshes.length; index++) {
  25819. var mesh = meshes.data[index];
  25820. var position = mesh.getBoundingInfo().boundingSphere.center;
  25821. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25822. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25823. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25824. }
  25825. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25826. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25827. mesh.renderOverlay = !mesh.renderOverlay;
  25828. }, function () {
  25829. return mesh.renderOverlay ? 'red' : 'black';
  25830. });
  25831. }
  25832. }
  25833. // Cameras
  25834. var cameras = _this._scene.cameras;
  25835. for (index = 0; index < cameras.length; index++) {
  25836. var camera = cameras[index];
  25837. if (camera === _this._scene.activeCamera) {
  25838. continue;
  25839. }
  25840. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25841. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25842. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25843. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25844. _this._scene.activeCamera = camera;
  25845. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25846. }, function () {
  25847. return "purple";
  25848. });
  25849. }
  25850. }
  25851. // Lights
  25852. var lights = _this._scene.lights;
  25853. for (index = 0; index < lights.length; index++) {
  25854. var light = lights[index];
  25855. if (light.position) {
  25856. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25857. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25858. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25859. light.setEnabled(!light.isEnabled());
  25860. }, function () {
  25861. return light.isEnabled() ? "orange" : "gray";
  25862. });
  25863. }
  25864. }
  25865. }
  25866. }
  25867. _this._clickPosition = undefined;
  25868. };
  25869. }
  25870. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25871. while (this._treeSubsetDiv.hasChildNodes()) {
  25872. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25873. }
  25874. // Add meshes
  25875. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25876. sortedArray.sort(function (a, b) {
  25877. if (a.name === b.name) {
  25878. return 0;
  25879. }
  25880. return (a.name > b.name) ? 1 : -1;
  25881. });
  25882. for (var index = 0; index < sortedArray.length; index++) {
  25883. var mesh = sortedArray[index];
  25884. if (!mesh.isEnabled()) {
  25885. continue;
  25886. }
  25887. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25888. m.isVisible = element.checked;
  25889. }, mesh);
  25890. }
  25891. };
  25892. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25893. this._drawingContext.beginPath();
  25894. this._drawingContext.moveTo(zero.x, zero.y);
  25895. this._drawingContext.lineTo(unit.x, unit.y);
  25896. this._drawingContext.strokeStyle = color;
  25897. this._drawingContext.lineWidth = 4;
  25898. this._drawingContext.stroke();
  25899. this._drawingContext.font = "normal 14px Segoe UI";
  25900. this._drawingContext.fillStyle = color;
  25901. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25902. };
  25903. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25904. var position = mesh.getBoundingInfo().boundingSphere.center;
  25905. var worldMatrix = mesh.getWorldMatrix();
  25906. 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());
  25907. var unit = (unprojectedVector.subtract(position)).length();
  25908. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25909. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25910. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25911. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25912. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25913. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25914. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25915. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25916. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25917. };
  25918. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25919. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25920. this._drawingContext.font = "normal 12px Segoe UI";
  25921. var textMetrics = this._drawingContext.measureText(text);
  25922. var centerX = projectedPosition.x - textMetrics.width / 2;
  25923. var centerY = projectedPosition.y;
  25924. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  25925. onClick();
  25926. }
  25927. this._drawingContext.beginPath();
  25928. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  25929. this._drawingContext.fillStyle = getFillStyle();
  25930. this._drawingContext.globalAlpha = 0.5;
  25931. this._drawingContext.fill();
  25932. this._drawingContext.globalAlpha = 1.0;
  25933. this._drawingContext.strokeStyle = '#FFFFFF';
  25934. this._drawingContext.lineWidth = 1;
  25935. this._drawingContext.stroke();
  25936. this._drawingContext.fillStyle = "#FFFFFF";
  25937. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  25938. this._drawingContext.beginPath();
  25939. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  25940. this._drawingContext.fill();
  25941. }
  25942. };
  25943. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  25944. if (!this._clickPosition) {
  25945. return false;
  25946. }
  25947. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  25948. return false;
  25949. }
  25950. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  25951. return false;
  25952. }
  25953. return true;
  25954. };
  25955. DebugLayer.prototype.isVisible = function () {
  25956. return this._enabled;
  25957. };
  25958. DebugLayer.prototype.hide = function () {
  25959. if (!this._enabled) {
  25960. return;
  25961. }
  25962. this._enabled = false;
  25963. var engine = this._scene.getEngine();
  25964. this._scene.unregisterAfterRender(this._syncData);
  25965. document.body.removeChild(this._globalDiv);
  25966. window.removeEventListener("resize", this._syncPositions);
  25967. this._scene.forceShowBoundingBoxes = false;
  25968. this._scene.forceWireframe = false;
  25969. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  25970. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  25971. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  25972. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  25973. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  25974. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  25975. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  25976. this._scene.shadowsEnabled = true;
  25977. this._scene.particlesEnabled = true;
  25978. this._scene.postProcessesEnabled = true;
  25979. this._scene.collisionsEnabled = true;
  25980. this._scene.lightsEnabled = true;
  25981. this._scene.texturesEnabled = true;
  25982. this._scene.lensFlaresEnabled = true;
  25983. this._scene.proceduralTexturesEnabled = true;
  25984. this._scene.renderTargetsEnabled = true;
  25985. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  25986. };
  25987. DebugLayer.prototype.show = function (showUI) {
  25988. if (showUI === void 0) { showUI = true; }
  25989. if (this._enabled) {
  25990. return;
  25991. }
  25992. this._enabled = true;
  25993. this._showUI = showUI;
  25994. var engine = this._scene.getEngine();
  25995. this._globalDiv = document.createElement("div");
  25996. document.body.appendChild(this._globalDiv);
  25997. this._generateDOMelements();
  25998. window.addEventListener("resize", this._syncPositions);
  25999. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26000. this._syncPositions();
  26001. this._scene.registerAfterRender(this._syncData);
  26002. };
  26003. DebugLayer.prototype._clearLabels = function () {
  26004. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26005. for (var index = 0; index < this._scene.meshes.length; index++) {
  26006. var mesh = this._scene.meshes[index];
  26007. mesh.renderOverlay = false;
  26008. }
  26009. };
  26010. DebugLayer.prototype._generateheader = function (root, text) {
  26011. var header = document.createElement("div");
  26012. header.innerHTML = text + "&nbsp;";
  26013. header.style.textAlign = "right";
  26014. header.style.width = "100%";
  26015. header.style.color = "white";
  26016. header.style.backgroundColor = "Black";
  26017. header.style.padding = "5px 5px 4px 0px";
  26018. header.style.marginLeft = "-5px";
  26019. header.style.fontWeight = "bold";
  26020. root.appendChild(header);
  26021. };
  26022. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26023. var label = document.createElement("label");
  26024. label.innerHTML = title;
  26025. label.style.color = color;
  26026. root.appendChild(label);
  26027. root.appendChild(document.createElement("br"));
  26028. };
  26029. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26030. if (tag === void 0) { tag = null; }
  26031. var label = document.createElement("label");
  26032. var boundingBoxesCheckbox = document.createElement("input");
  26033. boundingBoxesCheckbox.type = "checkbox";
  26034. boundingBoxesCheckbox.checked = initialState;
  26035. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26036. task(evt.target, tag);
  26037. });
  26038. label.appendChild(boundingBoxesCheckbox);
  26039. var container = document.createElement("span");
  26040. var leftPart = document.createElement("span");
  26041. var rightPart = document.createElement("span");
  26042. rightPart.style.cssFloat = "right";
  26043. leftPart.innerHTML = leftTitle;
  26044. rightPart.innerHTML = rightTitle;
  26045. rightPart.style.fontSize = "12px";
  26046. rightPart.style.maxWidth = "200px";
  26047. container.appendChild(leftPart);
  26048. container.appendChild(rightPart);
  26049. label.appendChild(container);
  26050. root.appendChild(label);
  26051. root.appendChild(document.createElement("br"));
  26052. };
  26053. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  26054. if (tag === void 0) { tag = null; }
  26055. var label = document.createElement("label");
  26056. var boundingBoxesCheckbox = document.createElement("input");
  26057. boundingBoxesCheckbox.type = "checkbox";
  26058. boundingBoxesCheckbox.checked = initialState;
  26059. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26060. task(evt.target, tag);
  26061. });
  26062. label.appendChild(boundingBoxesCheckbox);
  26063. label.appendChild(document.createTextNode(title));
  26064. root.appendChild(label);
  26065. root.appendChild(document.createElement("br"));
  26066. };
  26067. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  26068. if (tag === void 0) { tag = null; }
  26069. var label = document.createElement("label");
  26070. var boundingBoxesRadio = document.createElement("input");
  26071. boundingBoxesRadio.type = "radio";
  26072. boundingBoxesRadio.name = name;
  26073. boundingBoxesRadio.checked = initialState;
  26074. boundingBoxesRadio.addEventListener("change", function (evt) {
  26075. task(evt.target, tag);
  26076. });
  26077. label.appendChild(boundingBoxesRadio);
  26078. label.appendChild(document.createTextNode(title));
  26079. root.appendChild(label);
  26080. root.appendChild(document.createElement("br"));
  26081. };
  26082. DebugLayer.prototype._generateDOMelements = function () {
  26083. var _this = this;
  26084. this._globalDiv.id = "DebugLayer";
  26085. this._globalDiv.style.position = "absolute";
  26086. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  26087. this._globalDiv.style.fontSize = "14px";
  26088. this._globalDiv.style.color = "white";
  26089. // Drawing canvas
  26090. this._drawingCanvas = document.createElement("canvas");
  26091. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  26092. this._drawingCanvas.style.position = "absolute";
  26093. this._drawingCanvas.style.pointerEvents = "none";
  26094. this._drawingContext = this._drawingCanvas.getContext("2d");
  26095. this._globalDiv.appendChild(this._drawingCanvas);
  26096. if (this._showUI) {
  26097. var background = "rgba(128, 128, 128, 0.4)";
  26098. var border = "rgb(180, 180, 180) solid 1px";
  26099. // Stats
  26100. this._statsDiv = document.createElement("div");
  26101. this._statsDiv.id = "DebugLayerStats";
  26102. this._statsDiv.style.border = border;
  26103. this._statsDiv.style.position = "absolute";
  26104. this._statsDiv.style.background = background;
  26105. this._statsDiv.style.padding = "0px 0px 0px 5px";
  26106. this._generateheader(this._statsDiv, "STATISTICS");
  26107. this._statsSubsetDiv = document.createElement("div");
  26108. this._statsSubsetDiv.style.paddingTop = "5px";
  26109. this._statsSubsetDiv.style.paddingBottom = "5px";
  26110. this._statsSubsetDiv.style.overflowY = "auto";
  26111. this._statsDiv.appendChild(this._statsSubsetDiv);
  26112. // Tree
  26113. this._treeDiv = document.createElement("div");
  26114. this._treeDiv.id = "DebugLayerTree";
  26115. this._treeDiv.style.border = border;
  26116. this._treeDiv.style.position = "absolute";
  26117. this._treeDiv.style.background = background;
  26118. this._treeDiv.style.padding = "0px 0px 0px 5px";
  26119. this._treeDiv.style.display = "none";
  26120. this._generateheader(this._treeDiv, "MESHES TREE");
  26121. this._treeSubsetDiv = document.createElement("div");
  26122. this._treeSubsetDiv.style.paddingTop = "5px";
  26123. this._treeSubsetDiv.style.paddingRight = "5px";
  26124. this._treeSubsetDiv.style.overflowY = "auto";
  26125. this._treeSubsetDiv.style.maxHeight = "300px";
  26126. this._treeDiv.appendChild(this._treeSubsetDiv);
  26127. this._needToRefreshMeshesTree = true;
  26128. // Logs
  26129. this._logDiv = document.createElement("div");
  26130. this._logDiv.style.border = border;
  26131. this._logDiv.id = "DebugLayerLogs";
  26132. this._logDiv.style.position = "absolute";
  26133. this._logDiv.style.background = background;
  26134. this._logDiv.style.padding = "0px 0px 0px 5px";
  26135. this._logDiv.style.display = "none";
  26136. this._generateheader(this._logDiv, "LOGS");
  26137. this._logSubsetDiv = document.createElement("div");
  26138. this._logSubsetDiv.style.height = "127px";
  26139. this._logSubsetDiv.style.paddingTop = "5px";
  26140. this._logSubsetDiv.style.overflowY = "auto";
  26141. this._logSubsetDiv.style.fontSize = "12px";
  26142. this._logSubsetDiv.style.fontFamily = "consolas";
  26143. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  26144. this._logDiv.appendChild(this._logSubsetDiv);
  26145. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  26146. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  26147. };
  26148. // Options
  26149. this._optionsDiv = document.createElement("div");
  26150. this._optionsDiv.id = "DebugLayerOptions";
  26151. this._optionsDiv.style.border = border;
  26152. this._optionsDiv.style.position = "absolute";
  26153. this._optionsDiv.style.background = background;
  26154. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  26155. this._optionsDiv.style.overflowY = "auto";
  26156. this._generateheader(this._optionsDiv, "OPTIONS");
  26157. this._optionsSubsetDiv = document.createElement("div");
  26158. this._optionsSubsetDiv.style.paddingTop = "5px";
  26159. this._optionsSubsetDiv.style.paddingBottom = "5px";
  26160. this._optionsSubsetDiv.style.overflowY = "auto";
  26161. this._optionsSubsetDiv.style.maxHeight = "200px";
  26162. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  26163. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  26164. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  26165. _this._displayStatistics = element.checked;
  26166. });
  26167. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  26168. _this._displayLogs = element.checked;
  26169. });
  26170. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  26171. _this._displayTree = element.checked;
  26172. _this._needToRefreshMeshesTree = true;
  26173. });
  26174. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26175. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  26176. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  26177. _this._scene.forceShowBoundingBoxes = element.checked;
  26178. });
  26179. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  26180. _this._labelsEnabled = element.checked;
  26181. if (!_this._labelsEnabled) {
  26182. _this._clearLabels();
  26183. }
  26184. });
  26185. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  26186. if (element.checked) {
  26187. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  26188. }
  26189. else {
  26190. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  26191. }
  26192. });
  26193. ;
  26194. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26195. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  26196. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  26197. if (element.checked) {
  26198. _this._scene.forceWireframe = false;
  26199. _this._scene.forcePointsCloud = false;
  26200. }
  26201. });
  26202. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  26203. if (element.checked) {
  26204. _this._scene.forceWireframe = true;
  26205. _this._scene.forcePointsCloud = false;
  26206. }
  26207. });
  26208. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  26209. if (element.checked) {
  26210. _this._scene.forceWireframe = false;
  26211. _this._scene.forcePointsCloud = true;
  26212. }
  26213. });
  26214. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26215. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  26216. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  26217. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  26218. });
  26219. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  26220. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  26221. });
  26222. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  26223. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  26224. });
  26225. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  26226. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  26227. });
  26228. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  26229. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  26230. });
  26231. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  26232. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  26233. });
  26234. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  26235. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  26236. });
  26237. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  26238. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  26239. });
  26240. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  26241. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  26242. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  26243. _this._scene.animationsEnabled = element.checked;
  26244. });
  26245. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  26246. _this._scene.collisionsEnabled = element.checked;
  26247. });
  26248. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  26249. _this._scene.fogEnabled = element.checked;
  26250. });
  26251. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  26252. _this._scene.lensFlaresEnabled = element.checked;
  26253. });
  26254. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  26255. _this._scene.lightsEnabled = element.checked;
  26256. });
  26257. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  26258. _this._scene.particlesEnabled = element.checked;
  26259. });
  26260. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  26261. _this._scene.postProcessesEnabled = element.checked;
  26262. });
  26263. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  26264. _this._scene.proceduralTexturesEnabled = element.checked;
  26265. });
  26266. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  26267. _this._scene.renderTargetsEnabled = element.checked;
  26268. });
  26269. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  26270. _this._scene.shadowsEnabled = element.checked;
  26271. });
  26272. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  26273. _this._scene.skeletonsEnabled = element.checked;
  26274. });
  26275. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  26276. _this._scene.texturesEnabled = element.checked;
  26277. });
  26278. this._globalDiv.appendChild(this._statsDiv);
  26279. this._globalDiv.appendChild(this._logDiv);
  26280. this._globalDiv.appendChild(this._optionsDiv);
  26281. this._globalDiv.appendChild(this._treeDiv);
  26282. }
  26283. };
  26284. DebugLayer.prototype._displayStats = function () {
  26285. var scene = this._scene;
  26286. var engine = scene.getEngine();
  26287. var glInfo = engine.getGlInfo();
  26288. 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>";
  26289. if (this.customStatsFunction) {
  26290. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  26291. }
  26292. };
  26293. return DebugLayer;
  26294. })();
  26295. BABYLON.DebugLayer = DebugLayer;
  26296. })(BABYLON || (BABYLON = {}));
  26297. //# sourceMappingURL=babylon.debugLayer.js.map
  26298. var BABYLON;
  26299. (function (BABYLON) {
  26300. var RawTexture = (function (_super) {
  26301. __extends(RawTexture, _super);
  26302. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  26303. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26304. if (invertY === void 0) { invertY = false; }
  26305. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26306. _super.call(this, null, scene, !generateMipMaps, invertY);
  26307. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  26308. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26309. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26310. }
  26311. // Statics
  26312. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26313. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26314. if (invertY === void 0) { invertY = false; }
  26315. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26316. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  26317. };
  26318. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26319. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26320. if (invertY === void 0) { invertY = false; }
  26321. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26322. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26323. };
  26324. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26325. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26326. if (invertY === void 0) { invertY = false; }
  26327. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26328. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  26329. };
  26330. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26331. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26332. if (invertY === void 0) { invertY = false; }
  26333. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26334. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  26335. };
  26336. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  26337. if (generateMipMaps === void 0) { generateMipMaps = true; }
  26338. if (invertY === void 0) { invertY = false; }
  26339. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26340. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  26341. };
  26342. return RawTexture;
  26343. })(BABYLON.Texture);
  26344. BABYLON.RawTexture = RawTexture;
  26345. })(BABYLON || (BABYLON = {}));
  26346. //# sourceMappingURL=babylon.rawTexture.js.map
  26347. var BABYLON;
  26348. (function (BABYLON) {
  26349. var IndexedVector2 = (function (_super) {
  26350. __extends(IndexedVector2, _super);
  26351. function IndexedVector2(original, index) {
  26352. _super.call(this, original.x, original.y);
  26353. this.index = index;
  26354. }
  26355. return IndexedVector2;
  26356. })(BABYLON.Vector2);
  26357. var PolygonPoints = (function () {
  26358. function PolygonPoints() {
  26359. this.elements = new Array();
  26360. }
  26361. PolygonPoints.prototype.add = function (originalPoints) {
  26362. var _this = this;
  26363. var result = new Array();
  26364. originalPoints.forEach(function (point) {
  26365. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  26366. var newPoint = new IndexedVector2(point, _this.elements.length);
  26367. result.push(newPoint);
  26368. _this.elements.push(newPoint);
  26369. }
  26370. });
  26371. return result;
  26372. };
  26373. PolygonPoints.prototype.computeBounds = function () {
  26374. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26375. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  26376. this.elements.forEach(function (point) {
  26377. // x
  26378. if (point.x < lmin.x) {
  26379. lmin.x = point.x;
  26380. }
  26381. else if (point.x > lmax.x) {
  26382. lmax.x = point.x;
  26383. }
  26384. // y
  26385. if (point.y < lmin.y) {
  26386. lmin.y = point.y;
  26387. }
  26388. else if (point.y > lmax.y) {
  26389. lmax.y = point.y;
  26390. }
  26391. });
  26392. return {
  26393. min: lmin,
  26394. max: lmax,
  26395. width: lmax.x - lmin.x,
  26396. height: lmax.y - lmin.y
  26397. };
  26398. };
  26399. return PolygonPoints;
  26400. })();
  26401. var Polygon = (function () {
  26402. function Polygon() {
  26403. }
  26404. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  26405. return [
  26406. new BABYLON.Vector2(xmin, ymin),
  26407. new BABYLON.Vector2(xmax, ymin),
  26408. new BABYLON.Vector2(xmax, ymax),
  26409. new BABYLON.Vector2(xmin, ymax)
  26410. ];
  26411. };
  26412. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  26413. if (cx === void 0) { cx = 0; }
  26414. if (cy === void 0) { cy = 0; }
  26415. if (numberOfSides === void 0) { numberOfSides = 32; }
  26416. var result = new Array();
  26417. var angle = 0;
  26418. var increment = (Math.PI * 2) / numberOfSides;
  26419. for (var i = 0; i < numberOfSides; i++) {
  26420. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  26421. angle -= increment;
  26422. }
  26423. return result;
  26424. };
  26425. Polygon.Parse = function (input) {
  26426. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  26427. var i, result = [];
  26428. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  26429. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  26430. }
  26431. return result;
  26432. };
  26433. Polygon.StartingAt = function (x, y) {
  26434. return BABYLON.Path2.StartingAt(x, y);
  26435. };
  26436. return Polygon;
  26437. })();
  26438. BABYLON.Polygon = Polygon;
  26439. var PolygonMeshBuilder = (function () {
  26440. function PolygonMeshBuilder(name, contours, scene) {
  26441. this._points = new PolygonPoints();
  26442. if (!("poly2tri" in window)) {
  26443. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  26444. }
  26445. this._name = name;
  26446. this._scene = scene;
  26447. var points;
  26448. if (contours instanceof BABYLON.Path2) {
  26449. points = contours.getPoints();
  26450. }
  26451. else {
  26452. points = contours;
  26453. }
  26454. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  26455. }
  26456. PolygonMeshBuilder.prototype.addHole = function (hole) {
  26457. this._swctx.addHole(this._points.add(hole));
  26458. return this;
  26459. };
  26460. PolygonMeshBuilder.prototype.build = function (updatable) {
  26461. if (updatable === void 0) { updatable = false; }
  26462. var result = new BABYLON.Mesh(this._name, this._scene);
  26463. var normals = [];
  26464. var positions = [];
  26465. var uvs = [];
  26466. var bounds = this._points.computeBounds();
  26467. this._points.elements.forEach(function (p) {
  26468. normals.push(0, 1.0, 0);
  26469. positions.push(p.x, 0, p.y);
  26470. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  26471. });
  26472. var indices = [];
  26473. this._swctx.triangulate();
  26474. this._swctx.getTriangles().forEach(function (triangle) {
  26475. triangle.getPoints().forEach(function (point) {
  26476. indices.push(point.index);
  26477. });
  26478. });
  26479. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  26480. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  26481. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  26482. result.setIndices(indices);
  26483. return result;
  26484. };
  26485. return PolygonMeshBuilder;
  26486. })();
  26487. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  26488. })(BABYLON || (BABYLON = {}));
  26489. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  26490. (function (BABYLON) {
  26491. var SimplificationSettings = (function () {
  26492. function SimplificationSettings(quality, distance) {
  26493. this.quality = quality;
  26494. this.distance = distance;
  26495. }
  26496. return SimplificationSettings;
  26497. })();
  26498. BABYLON.SimplificationSettings = SimplificationSettings;
  26499. /**
  26500. * The implemented types of simplification.
  26501. * At the moment only Quadratic Error Decimation is implemented.
  26502. */
  26503. (function (SimplificationType) {
  26504. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  26505. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  26506. var SimplificationType = BABYLON.SimplificationType;
  26507. var DecimationTriangle = (function () {
  26508. function DecimationTriangle(vertices) {
  26509. this.vertices = vertices;
  26510. this.error = new Array(4);
  26511. this.deleted = false;
  26512. this.isDirty = false;
  26513. this.borderFactor = 0;
  26514. }
  26515. return DecimationTriangle;
  26516. })();
  26517. BABYLON.DecimationTriangle = DecimationTriangle;
  26518. var DecimationVertex = (function () {
  26519. function DecimationVertex(position, normal, uv, id) {
  26520. this.position = position;
  26521. this.normal = normal;
  26522. this.uv = uv;
  26523. this.id = id;
  26524. this.isBorder = true;
  26525. this.q = new QuadraticMatrix();
  26526. this.triangleCount = 0;
  26527. this.triangleStart = 0;
  26528. }
  26529. return DecimationVertex;
  26530. })();
  26531. BABYLON.DecimationVertex = DecimationVertex;
  26532. var QuadraticMatrix = (function () {
  26533. function QuadraticMatrix(data) {
  26534. this.data = new Array(10);
  26535. for (var i = 0; i < 10; ++i) {
  26536. if (data && data[i]) {
  26537. this.data[i] = data[i];
  26538. }
  26539. else {
  26540. this.data[i] = 0;
  26541. }
  26542. }
  26543. }
  26544. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  26545. 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];
  26546. return det;
  26547. };
  26548. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  26549. for (var i = 0; i < 10; ++i) {
  26550. this.data[i] += matrix.data[i];
  26551. }
  26552. };
  26553. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  26554. for (var i = 0; i < 10; ++i) {
  26555. this.data[i] += data[i];
  26556. }
  26557. };
  26558. QuadraticMatrix.prototype.add = function (matrix) {
  26559. var m = new QuadraticMatrix();
  26560. for (var i = 0; i < 10; ++i) {
  26561. m.data[i] = this.data[i] + matrix.data[i];
  26562. }
  26563. return m;
  26564. };
  26565. QuadraticMatrix.FromData = function (a, b, c, d) {
  26566. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26567. };
  26568. //returning an array to avoid garbage collection
  26569. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26570. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26571. };
  26572. return QuadraticMatrix;
  26573. })();
  26574. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26575. var Reference = (function () {
  26576. function Reference(vertexId, triangleId) {
  26577. this.vertexId = vertexId;
  26578. this.triangleId = triangleId;
  26579. }
  26580. return Reference;
  26581. })();
  26582. BABYLON.Reference = Reference;
  26583. /**
  26584. * An implementation of the Quadratic Error simplification algorithm.
  26585. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26586. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26587. * @author RaananW
  26588. */
  26589. var QuadraticErrorSimplification = (function () {
  26590. function QuadraticErrorSimplification(_mesh) {
  26591. this._mesh = _mesh;
  26592. this.initialised = false;
  26593. this.syncIterations = 5000;
  26594. this.aggressiveness = 7;
  26595. this.decimationIterations = 100;
  26596. }
  26597. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26598. var _this = this;
  26599. this.initWithMesh(this._mesh, function () {
  26600. _this.runDecimation(settings, successCallback);
  26601. });
  26602. };
  26603. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26604. var _this = this;
  26605. var targetCount = ~~(this.triangles.length * settings.quality);
  26606. var deletedTriangles = 0;
  26607. var triangleCount = this.triangles.length;
  26608. var iterationFunction = function (iteration, callback) {
  26609. setTimeout(function () {
  26610. if (iteration % 5 === 0) {
  26611. _this.updateMesh(iteration === 0);
  26612. }
  26613. for (var i = 0; i < _this.triangles.length; ++i) {
  26614. _this.triangles[i].isDirty = false;
  26615. }
  26616. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26617. var trianglesIterator = function (i) {
  26618. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  26619. var t = _this.triangles[tIdx];
  26620. if (!t)
  26621. return;
  26622. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26623. return;
  26624. }
  26625. for (var j = 0; j < 3; ++j) {
  26626. if (t.error[j] < threshold) {
  26627. var deleted0 = [];
  26628. var deleted1 = [];
  26629. var i0 = t.vertices[j];
  26630. var i1 = t.vertices[(j + 1) % 3];
  26631. var v0 = _this.vertices[i0];
  26632. var v1 = _this.vertices[i1];
  26633. if (v0.isBorder !== v1.isBorder)
  26634. continue;
  26635. var p = BABYLON.Vector3.Zero();
  26636. var n = BABYLON.Vector3.Zero();
  26637. var uv = BABYLON.Vector2.Zero();
  26638. var color = new BABYLON.Color4(0, 0, 0, 1);
  26639. _this.calculateError(v0, v1, p, n, uv, color);
  26640. var delTr = [];
  26641. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  26642. continue;
  26643. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  26644. continue;
  26645. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  26646. continue;
  26647. }
  26648. v0.normal = n;
  26649. if (v0.uv)
  26650. v0.uv = uv;
  26651. else if (v0.color)
  26652. v0.color = color;
  26653. v0.q = v1.q.add(v0.q);
  26654. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  26655. continue;
  26656. if (p.equals(v0.position))
  26657. continue;
  26658. v0.position = p;
  26659. var tStart = _this.references.length;
  26660. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26661. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26662. var tCount = _this.references.length - tStart;
  26663. if (tCount <= v0.triangleCount) {
  26664. if (tCount) {
  26665. for (var c = 0; c < tCount; c++) {
  26666. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26667. }
  26668. }
  26669. }
  26670. else {
  26671. v0.triangleStart = tStart;
  26672. }
  26673. v0.triangleCount = tCount;
  26674. break;
  26675. }
  26676. }
  26677. };
  26678. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26679. return (triangleCount - deletedTriangles <= targetCount);
  26680. });
  26681. }, 0);
  26682. };
  26683. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26684. if (triangleCount - deletedTriangles <= targetCount)
  26685. loop.breakLoop();
  26686. else {
  26687. iterationFunction(loop.index, function () {
  26688. loop.executeNext();
  26689. });
  26690. }
  26691. }, function () {
  26692. setTimeout(function () {
  26693. successCallback(_this.reconstructMesh());
  26694. }, 0);
  26695. });
  26696. };
  26697. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26698. var _this = this;
  26699. if (!mesh)
  26700. return;
  26701. this.vertices = [];
  26702. this.triangles = [];
  26703. this._mesh = mesh;
  26704. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26705. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26706. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26707. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26708. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26709. var indices = mesh.getIndices();
  26710. var vertexInit = function (i) {
  26711. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  26712. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26713. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26714. }
  26715. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26716. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  26717. }
  26718. _this.vertices.push(vertex);
  26719. };
  26720. var totalVertices = mesh.getTotalVertices();
  26721. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26722. var indicesInit = function (i) {
  26723. var pos = i * 3;
  26724. var i0 = indices[pos + 0];
  26725. var i1 = indices[pos + 1];
  26726. var i2 = indices[pos + 2];
  26727. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26728. _this.triangles.push(triangle);
  26729. };
  26730. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26731. _this.init(callback);
  26732. });
  26733. });
  26734. };
  26735. QuadraticErrorSimplification.prototype.init = function (callback) {
  26736. var _this = this;
  26737. var triangleInit1 = function (i) {
  26738. var t = _this.triangles[i];
  26739. 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();
  26740. for (var j = 0; j < 3; j++) {
  26741. _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))));
  26742. }
  26743. };
  26744. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  26745. var triangleInit2 = function (i) {
  26746. var t = _this.triangles[i];
  26747. for (var j = 0; j < 3; ++j) {
  26748. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  26749. }
  26750. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26751. };
  26752. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  26753. _this.initialised = true;
  26754. callback();
  26755. });
  26756. });
  26757. };
  26758. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  26759. var newTriangles = [];
  26760. var i;
  26761. for (i = 0; i < this.vertices.length; ++i) {
  26762. this.vertices[i].triangleCount = 0;
  26763. }
  26764. var t;
  26765. var j;
  26766. for (i = 0; i < this.triangles.length; ++i) {
  26767. if (!this.triangles[i].deleted) {
  26768. t = this.triangles[i];
  26769. for (j = 0; j < 3; ++j) {
  26770. this.vertices[t.vertices[j]].triangleCount = 1;
  26771. }
  26772. newTriangles.push(t);
  26773. }
  26774. }
  26775. var newVerticesOrder = [];
  26776. //compact vertices, get the IDs of the vertices used.
  26777. var dst = 0;
  26778. for (i = 0; i < this.vertices.length; ++i) {
  26779. if (this.vertices[i].triangleCount) {
  26780. this.vertices[i].triangleStart = dst;
  26781. this.vertices[dst].position = this.vertices[i].position;
  26782. this.vertices[dst].normal = this.vertices[i].normal;
  26783. this.vertices[dst].uv = this.vertices[i].uv;
  26784. this.vertices[dst].color = this.vertices[i].color;
  26785. newVerticesOrder.push(i);
  26786. dst++;
  26787. }
  26788. }
  26789. for (i = 0; i < newTriangles.length; ++i) {
  26790. t = newTriangles[i];
  26791. for (j = 0; j < 3; ++j) {
  26792. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  26793. }
  26794. }
  26795. this.vertices = this.vertices.slice(0, dst);
  26796. var newPositionData = [];
  26797. var newNormalData = [];
  26798. var newUVsData = [];
  26799. var newColorsData = [];
  26800. for (i = 0; i < newVerticesOrder.length; ++i) {
  26801. newPositionData.push(this.vertices[i].position.x);
  26802. newPositionData.push(this.vertices[i].position.y);
  26803. newPositionData.push(this.vertices[i].position.z);
  26804. newNormalData.push(this.vertices[i].normal.x);
  26805. newNormalData.push(this.vertices[i].normal.y);
  26806. newNormalData.push(this.vertices[i].normal.z);
  26807. if (this.vertices[i].uv) {
  26808. newUVsData.push(this.vertices[i].uv.x);
  26809. newUVsData.push(this.vertices[i].uv.y);
  26810. }
  26811. else if (this.vertices[i].color) {
  26812. newColorsData.push(this.vertices[i].color.r);
  26813. newColorsData.push(this.vertices[i].color.g);
  26814. newColorsData.push(this.vertices[i].color.b);
  26815. newColorsData.push(this.vertices[i].color.a);
  26816. }
  26817. }
  26818. var newIndicesArray = [];
  26819. for (i = 0; i < newTriangles.length; ++i) {
  26820. newIndicesArray.push(newTriangles[i].vertices[0]);
  26821. newIndicesArray.push(newTriangles[i].vertices[1]);
  26822. newIndicesArray.push(newTriangles[i].vertices[2]);
  26823. }
  26824. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  26825. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  26826. newMesh.material = this._mesh.material;
  26827. newMesh.parent = this._mesh.parent;
  26828. newMesh.setIndices(newIndicesArray);
  26829. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  26830. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  26831. if (newUVsData.length > 0)
  26832. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  26833. if (newColorsData.length > 0)
  26834. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  26835. //preparing the skeleton support
  26836. if (this._mesh.skeleton) {
  26837. }
  26838. return newMesh;
  26839. };
  26840. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  26841. for (var i = 0; i < vertex1.triangleCount; ++i) {
  26842. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  26843. if (t.deleted)
  26844. continue;
  26845. var s = this.references[vertex1.triangleStart + i].vertexId;
  26846. var id1 = t.vertices[(s + 1) % 3];
  26847. var id2 = t.vertices[(s + 2) % 3];
  26848. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  26849. deletedArray[i] = true;
  26850. delTr.push(t);
  26851. continue;
  26852. }
  26853. var d1 = this.vertices[id1].position.subtract(point);
  26854. d1 = d1.normalize();
  26855. var d2 = this.vertices[id2].position.subtract(point);
  26856. d2 = d2.normalize();
  26857. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26858. return true;
  26859. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26860. deletedArray[i] = false;
  26861. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26862. return true;
  26863. }
  26864. return false;
  26865. };
  26866. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26867. var newDeleted = deletedTriangles;
  26868. for (var i = 0; i < vertex.triangleCount; ++i) {
  26869. var ref = this.references[vertex.triangleStart + i];
  26870. var t = this.triangles[ref.triangleId];
  26871. if (t.deleted)
  26872. continue;
  26873. if (deletedArray[i]) {
  26874. t.deleted = true;
  26875. newDeleted++;
  26876. continue;
  26877. }
  26878. t.vertices[ref.vertexId] = vertexId;
  26879. t.isDirty = true;
  26880. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26881. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26882. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26883. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26884. this.references.push(ref);
  26885. }
  26886. return newDeleted;
  26887. };
  26888. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26889. for (var i = 0; i < this.vertices.length; ++i) {
  26890. var vCount = [];
  26891. var vId = [];
  26892. var v = this.vertices[i];
  26893. var j;
  26894. for (j = 0; j < v.triangleCount; ++j) {
  26895. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26896. for (var ii = 0; ii < 3; ii++) {
  26897. var ofs = 0;
  26898. var id = triangle.vertices[ii];
  26899. while (ofs < vCount.length) {
  26900. if (vId[ofs] === id)
  26901. break;
  26902. ++ofs;
  26903. }
  26904. if (ofs === vCount.length) {
  26905. vCount.push(1);
  26906. vId.push(id);
  26907. }
  26908. else {
  26909. vCount[ofs]++;
  26910. }
  26911. }
  26912. }
  26913. for (j = 0; j < vCount.length; ++j) {
  26914. if (vCount[j] === 1) {
  26915. this.vertices[vId[j]].isBorder = true;
  26916. }
  26917. else {
  26918. this.vertices[vId[j]].isBorder = false;
  26919. }
  26920. }
  26921. }
  26922. };
  26923. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  26924. if (identifyBorders === void 0) { identifyBorders = false; }
  26925. var i;
  26926. if (!identifyBorders) {
  26927. var newTrianglesVector = [];
  26928. for (i = 0; i < this.triangles.length; ++i) {
  26929. if (!this.triangles[i].deleted) {
  26930. newTrianglesVector.push(this.triangles[i]);
  26931. }
  26932. }
  26933. this.triangles = newTrianglesVector;
  26934. }
  26935. for (i = 0; i < this.vertices.length; ++i) {
  26936. this.vertices[i].triangleCount = 0;
  26937. this.vertices[i].triangleStart = 0;
  26938. }
  26939. var t;
  26940. var j;
  26941. var v;
  26942. for (i = 0; i < this.triangles.length; ++i) {
  26943. t = this.triangles[i];
  26944. for (j = 0; j < 3; ++j) {
  26945. v = this.vertices[t.vertices[j]];
  26946. v.triangleCount++;
  26947. }
  26948. }
  26949. var tStart = 0;
  26950. for (i = 0; i < this.vertices.length; ++i) {
  26951. this.vertices[i].triangleStart = tStart;
  26952. tStart += this.vertices[i].triangleCount;
  26953. this.vertices[i].triangleCount = 0;
  26954. }
  26955. var newReferences = new Array(this.triangles.length * 3);
  26956. for (i = 0; i < this.triangles.length; ++i) {
  26957. t = this.triangles[i];
  26958. for (j = 0; j < 3; ++j) {
  26959. v = this.vertices[t.vertices[j]];
  26960. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  26961. v.triangleCount++;
  26962. }
  26963. }
  26964. this.references = newReferences;
  26965. if (identifyBorders) {
  26966. this.identifyBorder();
  26967. }
  26968. };
  26969. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  26970. var x = point.x;
  26971. var y = point.y;
  26972. var z = point.z;
  26973. 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];
  26974. };
  26975. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  26976. var q = vertex1.q.add(vertex2.q);
  26977. var border = vertex1.isBorder && vertex2.isBorder;
  26978. var error = 0;
  26979. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  26980. if (qDet !== 0 && !border) {
  26981. if (!pointResult) {
  26982. pointResult = BABYLON.Vector3.Zero();
  26983. }
  26984. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  26985. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  26986. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  26987. error = this.vertexError(q, pointResult);
  26988. //TODO this should be correctly calculated
  26989. if (normalResult) {
  26990. normalResult.copyFrom(vertex1.normal);
  26991. if (vertex1.uv)
  26992. uvResult.copyFrom(vertex1.uv);
  26993. else if (vertex1.color)
  26994. colorResult.copyFrom(vertex1.color);
  26995. }
  26996. }
  26997. else {
  26998. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  26999. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27000. var error1 = this.vertexError(q, vertex1.position);
  27001. var error2 = this.vertexError(q, vertex2.position);
  27002. var error3 = this.vertexError(q, p3);
  27003. error = Math.min(error1, error2, error3);
  27004. if (error === error1) {
  27005. if (pointResult) {
  27006. pointResult.copyFrom(vertex1.position);
  27007. normalResult.copyFrom(vertex1.normal);
  27008. if (vertex1.uv)
  27009. uvResult.copyFrom(vertex1.uv);
  27010. else if (vertex1.color)
  27011. colorResult.copyFrom(vertex1.color);
  27012. }
  27013. }
  27014. else if (error === error2) {
  27015. if (pointResult) {
  27016. pointResult.copyFrom(vertex2.position);
  27017. normalResult.copyFrom(vertex2.normal);
  27018. if (vertex2.uv)
  27019. uvResult.copyFrom(vertex2.uv);
  27020. else if (vertex2.color)
  27021. colorResult.copyFrom(vertex2.color);
  27022. }
  27023. }
  27024. else {
  27025. if (pointResult) {
  27026. pointResult.copyFrom(p3);
  27027. normalResult.copyFrom(vertex1.normal);
  27028. if (vertex1.uv)
  27029. uvResult.copyFrom(vertex1.uv);
  27030. else if (vertex1.color)
  27031. colorResult.copyFrom(vertex1.color);
  27032. }
  27033. }
  27034. }
  27035. return error;
  27036. };
  27037. return QuadraticErrorSimplification;
  27038. })();
  27039. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  27040. })(BABYLON || (BABYLON = {}));
  27041. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  27042. (function (BABYLON) {
  27043. var Analyser = (function () {
  27044. function Analyser(scene) {
  27045. this.SMOOTHING = 0.75;
  27046. this.FFT_SIZE = 512;
  27047. this.BARGRAPHAMPLITUDE = 256;
  27048. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  27049. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  27050. this._scene = scene;
  27051. this._audioEngine = scene.getEngine().getAudioEngine();
  27052. if (this._audioEngine.canUseWebAudio) {
  27053. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  27054. this._webAudioAnalyser.minDecibels = -140;
  27055. this._webAudioAnalyser.maxDecibels = 0;
  27056. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27057. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  27058. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  27059. }
  27060. }
  27061. Analyser.prototype.getFrequencyBinCount = function () {
  27062. if (this._audioEngine.canUseWebAudio) {
  27063. return this._webAudioAnalyser.frequencyBinCount;
  27064. }
  27065. else {
  27066. return 0;
  27067. }
  27068. };
  27069. Analyser.prototype.getByteFrequencyData = function () {
  27070. if (this._audioEngine.canUseWebAudio) {
  27071. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27072. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27073. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  27074. }
  27075. return this._byteFreqs;
  27076. };
  27077. Analyser.prototype.getByteTimeDomainData = function () {
  27078. if (this._audioEngine.canUseWebAudio) {
  27079. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27080. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27081. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  27082. }
  27083. return this._byteTime;
  27084. };
  27085. Analyser.prototype.getFloatFrequencyData = function () {
  27086. if (this._audioEngine.canUseWebAudio) {
  27087. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  27088. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  27089. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  27090. }
  27091. return this._floatFreqs;
  27092. };
  27093. Analyser.prototype.drawDebugCanvas = function () {
  27094. var _this = this;
  27095. if (this._audioEngine.canUseWebAudio) {
  27096. if (!this._debugCanvas) {
  27097. this._debugCanvas = document.createElement("canvas");
  27098. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  27099. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  27100. this._debugCanvas.style.position = "absolute";
  27101. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  27102. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  27103. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  27104. document.body.appendChild(this._debugCanvas);
  27105. this._registerFunc = function () {
  27106. _this.drawDebugCanvas();
  27107. };
  27108. this._scene.registerBeforeRender(this._registerFunc);
  27109. }
  27110. if (this._registerFunc) {
  27111. var workingArray = this.getByteFrequencyData();
  27112. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  27113. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  27114. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  27115. var value = workingArray[i];
  27116. var percent = value / this.BARGRAPHAMPLITUDE;
  27117. var height = this.DEBUGCANVASSIZE.height * percent;
  27118. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  27119. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  27120. var hue = i / this.getFrequencyBinCount() * 360;
  27121. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  27122. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  27123. }
  27124. }
  27125. }
  27126. };
  27127. Analyser.prototype.stopDebugCanvas = function () {
  27128. if (this._debugCanvas) {
  27129. this._scene.unregisterBeforeRender(this._registerFunc);
  27130. this._registerFunc = null;
  27131. document.body.removeChild(this._debugCanvas);
  27132. this._debugCanvas = null;
  27133. this._debugCanvasContext = null;
  27134. }
  27135. };
  27136. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  27137. if (this._audioEngine.canUseWebAudio) {
  27138. inputAudioNode.connect(this._webAudioAnalyser);
  27139. this._webAudioAnalyser.connect(outputAudioNode);
  27140. }
  27141. };
  27142. Analyser.prototype.dispose = function () {
  27143. if (this._audioEngine.canUseWebAudio) {
  27144. this._webAudioAnalyser.disconnect();
  27145. }
  27146. };
  27147. return Analyser;
  27148. })();
  27149. BABYLON.Analyser = Analyser;
  27150. })(BABYLON || (BABYLON = {}));
  27151. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  27152. (function (BABYLON) {
  27153. var DepthRenderer = (function () {
  27154. function DepthRenderer(scene, type) {
  27155. var _this = this;
  27156. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  27157. this._viewMatrix = BABYLON.Matrix.Zero();
  27158. this._projectionMatrix = BABYLON.Matrix.Zero();
  27159. this._transformMatrix = BABYLON.Matrix.Zero();
  27160. this._worldViewProjection = BABYLON.Matrix.Zero();
  27161. this._scene = scene;
  27162. var engine = scene.getEngine();
  27163. // Render target
  27164. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  27165. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27166. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27167. this._depthMap.refreshRate = 1;
  27168. this._depthMap.renderParticles = false;
  27169. this._depthMap.renderList = null;
  27170. // Custom render function
  27171. var renderSubMesh = function (subMesh) {
  27172. var mesh = subMesh.getRenderingMesh();
  27173. var scene = _this._scene;
  27174. var engine = scene.getEngine();
  27175. // Culling
  27176. engine.setState(subMesh.getMaterial().backFaceCulling);
  27177. // Managing instances
  27178. var batch = mesh._getInstancesRenderList(subMesh._id);
  27179. if (batch.mustReturn) {
  27180. return;
  27181. }
  27182. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  27183. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  27184. engine.enableEffect(_this._effect);
  27185. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  27186. var material = subMesh.getMaterial();
  27187. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27188. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  27189. // Alpha test
  27190. if (material && material.needAlphaTesting()) {
  27191. var alphaTexture = material.getAlphaTestTexture();
  27192. _this._effect.setTexture("diffuseSampler", alphaTexture);
  27193. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27194. }
  27195. // Bones
  27196. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  27197. if (useBones) {
  27198. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27199. }
  27200. if (hardwareInstancedRendering) {
  27201. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  27202. }
  27203. else {
  27204. if (batch.renderSelf[subMesh._id]) {
  27205. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  27206. // Draw
  27207. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  27208. }
  27209. if (batch.visibleInstances[subMesh._id]) {
  27210. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  27211. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  27212. _this._effect.setMatrix("world", instance.getWorldMatrix());
  27213. // Draw
  27214. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  27215. }
  27216. }
  27217. }
  27218. }
  27219. };
  27220. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  27221. var index;
  27222. for (index = 0; index < opaqueSubMeshes.length; index++) {
  27223. renderSubMesh(opaqueSubMeshes.data[index]);
  27224. }
  27225. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  27226. renderSubMesh(alphaTestSubMeshes.data[index]);
  27227. }
  27228. };
  27229. }
  27230. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  27231. var defines = [];
  27232. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27233. var mesh = subMesh.getMesh();
  27234. var scene = mesh.getScene();
  27235. var material = subMesh.getMaterial();
  27236. // Alpha test
  27237. if (material && material.needAlphaTesting()) {
  27238. defines.push("#define ALPHATEST");
  27239. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27240. attribs.push(BABYLON.VertexBuffer.UVKind);
  27241. defines.push("#define UV1");
  27242. }
  27243. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27244. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27245. defines.push("#define UV2");
  27246. }
  27247. }
  27248. // Bones
  27249. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27250. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27251. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27252. defines.push("#define BONES");
  27253. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27254. }
  27255. // Instances
  27256. if (useInstances) {
  27257. defines.push("#define INSTANCES");
  27258. attribs.push("world0");
  27259. attribs.push("world1");
  27260. attribs.push("world2");
  27261. attribs.push("world3");
  27262. }
  27263. // Get correct effect
  27264. var join = defines.join("\n");
  27265. if (this._cachedDefines !== join) {
  27266. this._cachedDefines = join;
  27267. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  27268. }
  27269. return this._effect.isReady();
  27270. };
  27271. DepthRenderer.prototype.getDepthMap = function () {
  27272. return this._depthMap;
  27273. };
  27274. // Methods
  27275. DepthRenderer.prototype.dispose = function () {
  27276. this._depthMap.dispose();
  27277. };
  27278. return DepthRenderer;
  27279. })();
  27280. BABYLON.DepthRenderer = DepthRenderer;
  27281. })(BABYLON || (BABYLON = {}));
  27282. //# sourceMappingURL=babylon.depthRenderer.js.map