babylon.canvas2d.js 973 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909
  1. BABYLON.Effect.ShadersStore['ellipse2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  2. BABYLON.Effect.ShadersStore['ellipse2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}";
  3. BABYLON.Effect.ShadersStore['lines2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  4. BABYLON.Effect.ShadersStore['lines2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}";
  5. BABYLON.Effect.ShadersStore['rect2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  6. BABYLON.Effect.ShadersStore['rect2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}";
  7. BABYLON.Effect.ShadersStore['sprite2dPixelShader'] = "varying vec2 vUV;\nvarying float vOpacity;\n#ifdef Scale9\nvarying vec2 vTopLeftUV;\nvarying vec2 vBottomRightUV;\nvarying vec4 vScale9;\nvarying vec2 vScaleFactor;\n#endif\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec2 uv=vUV;\n#ifdef Scale9\nvec2 sizeUV=vBottomRightUV-vTopLeftUV;\n\nfloat leftPartUV=vTopLeftUV.x+(vScale9.x/vScaleFactor.x);\nfloat rightPartUV=vTopLeftUV.x+sizeUV.x-((sizeUV.x-vScale9.z)/vScaleFactor.x);\nif (vUV.x<leftPartUV) {\nuv.x=vTopLeftUV.x+((vUV.x- vTopLeftUV.x)*vScaleFactor.x);\n}\nelse if (vUV.x>rightPartUV) {\nuv.x=vTopLeftUV.x+vScale9.z+((vUV.x-rightPartUV)*vScaleFactor.x);\n}\nelse {\nfloat r=(vUV.x-leftPartUV)/(rightPartUV-leftPartUV);\nuv.x=vTopLeftUV.x+vScale9.x+((vScale9.z-vScale9.x)*r);\n}\n\nfloat topPartUV=(vTopLeftUV.y+(vScale9.y/vScaleFactor.y));\nfloat bottomPartUV=(vTopLeftUV.y+sizeUV.y-((sizeUV.y-vScale9.w)/vScaleFactor.y));\nif (vUV.y<topPartUV) {\nuv.y=vTopLeftUV.y+((vUV.y-vTopLeftUV.y)*vScaleFactor.y);\n}\nelse if (vUV.y>bottomPartUV) {\nuv.y=vTopLeftUV.y+vScale9.w+((vUV.y-bottomPartUV)*vScaleFactor.y);\n}\nelse {\nfloat r=(vUV.y-topPartUV)/(bottomPartUV-topPartUV);\nuv.y=vTopLeftUV.y+vScale9.y+((vScale9.w-vScale9.y)*r);\n}\n#endif\nvec4 color=texture2D(diffuseSampler,uv);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}";
  8. BABYLON.Effect.ShadersStore['sprite2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\n#ifdef Scale9\natt vec2 scaleFactor;\n#endif\natt vec2 textureSize;\n\natt vec3 properties;\n#ifdef Scale9\natt vec4 scale9;\n#endif\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\n#ifdef Scale9\nvarying vec2 vTopLeftUV;\nvarying vec2 vBottomRightUV;\nvarying vec4 vScale9;\nvarying vec2 vScaleFactor;\n#endif\nvoid main(void) {\nvec2 pos2;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x),topLeftUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),topLeftUV.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\n#ifdef Scale9\nif (invertY == 1.0) {\nvTopLeftUV=vec2(topLeftUV.x,1.0-(topLeftUV.y+sizeUV.y));\nvBottomRightUV=vec2(topLeftUV.x+sizeUV.x,1.0-topLeftUV.y);\nvScale9=vec4(scale9.x,sizeUV.y-scale9.w,scale9.z,sizeUV.y-scale9.y);\n}\nelse {\nvTopLeftUV=topLeftUV;\nvBottomRightUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\nvScale9=scale9;\n}\nvScaleFactor=scaleFactor;\n#endif\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ";
  9. BABYLON.Effect.ShadersStore['text2dPixelShader'] = "\nvarying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\n#ifdef SignedDistanceField\nfloat dist=texture2D(diffuseSampler,vUV).r;\nif (dist<0.5) {\ndiscard;\n}\n\n\n\n\n\ngl_FragColor=vec4(vColor.xyz*dist,vColor.a);\n#else\nvec4 color=texture2D(diffuseSampler,vUV);\nif (color.a == 0.0) {\ndiscard;\n}\n#ifdef FontTexture\ngl_FragColor=vec4(color.xxxx)*vColor;\n#else\ngl_FragColor=color*vColor;\n#endif\n#endif\n}";
  10. BABYLON.Effect.ShadersStore['text2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}";
  11. BABYLON.Effect.ShadersStore['wireframe2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  12. BABYLON.Effect.ShadersStore['wireframe2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute vec2 pos;\nattribute vec4 col;\n\n\n\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec4 vColor;\nvoid main(void) {\nvec4 p=vec4(pos.xy,1.0,1.0);\nvColor=vec4(col.xyz,col.w*opacity);\nvec4 pp=vec4(dot(p,transformX),dot(p,transformY),zBias.x,1);\nif (properties.x == 1.0) {\npp.xy=pp.xy-mod(pp.xy,properties.yz)+(properties.yz*0.5);\n}\ngl_Position=pp;\n} ";
  13. var BABYLON;
  14. (function (BABYLON) {
  15. /**
  16. * This class stores the data to make 2D transformation using a Translation (tX, tY), a Scale (sX, sY) and a rotation around the Z axis (rZ).
  17. * You can multiply two Transform2D object to produce the result of their concatenation.
  18. * You can transform a given Point (a Vector2D instance) with a Transform2D object or with the Invert of the Transform2D object.
  19. * There no need to compute/store the Invert of a Transform2D as the invertTranform methods are almost as fast as the transform ones.
  20. * This class is as light as it could be and the transformation operations are pretty optimal.
  21. */
  22. var Transform2D = (function () {
  23. function Transform2D() {
  24. this.translation = BABYLON.Vector2.Zero();
  25. this.rotation = 0;
  26. this.scale = new BABYLON.Vector2(1, 1);
  27. }
  28. /**
  29. * Set the Transform2D object with the given values
  30. * @param translation The translation to set
  31. * @param rotation The rotation (in radian) to set
  32. * @param scale The scale to set
  33. */
  34. Transform2D.prototype.set = function (translation, rotation, scale) {
  35. this.translation.copyFrom(translation);
  36. this.rotation = rotation;
  37. this.scale.copyFrom(scale);
  38. };
  39. /**
  40. * Set the Transform2D object from float values
  41. * @param transX The translation on X axis, nothing is set if not specified
  42. * @param transY The translation on Y axis, nothing is set if not specified
  43. * @param rotation The rotation in radian, nothing is set if not specified
  44. * @param scaleX The scale along the X axis, nothing is set if not specified
  45. * @param scaleY The scale along the Y axis, nothing is set if not specified
  46. */
  47. Transform2D.prototype.setFromFloats = function (transX, transY, rotation, scaleX, scaleY) {
  48. if (transX) {
  49. this.translation.x = transX;
  50. }
  51. if (transY) {
  52. this.translation.y = transY;
  53. }
  54. if (rotation) {
  55. this.rotation = rotation;
  56. }
  57. if (scaleX) {
  58. this.scale.x = scaleX;
  59. }
  60. if (scaleY) {
  61. this.scale.y = scaleY;
  62. }
  63. };
  64. /**
  65. * Return a copy of the object
  66. */
  67. Transform2D.prototype.clone = function () {
  68. var res = new Transform2D();
  69. res.translation.copyFrom(this.translation);
  70. res.rotation = this.rotation;
  71. res.scale.copyFrom(this.scale);
  72. return res;
  73. };
  74. /**
  75. * Convert a given degree angle into its radian equivalent
  76. * @param angleDegree the number to convert
  77. */
  78. Transform2D.ToRadian = function (angleDegree) {
  79. return angleDegree * Math.PI * 2 / 360;
  80. };
  81. /**
  82. * Create a new instance and returns it
  83. * @param translation The translation to store, default is (0,0)
  84. * @param rotation The rotation to store, default is 0
  85. * @param scale The scale to store, default is (1,1)
  86. */
  87. Transform2D.Make = function (translation, rotation, scale) {
  88. var res = new Transform2D();
  89. if (translation) {
  90. res.translation.copyFrom(translation);
  91. }
  92. if (rotation) {
  93. res.rotation = rotation;
  94. }
  95. if (scale) {
  96. res.scale.copyFrom(scale);
  97. }
  98. return res;
  99. };
  100. /**
  101. * Set the given Transform2D object with the given values
  102. * @param translation The translation to store, default is (0,0)
  103. * @param rotation The rotation to store, default is 0
  104. * @param scale The scale to store, default is (1,1)
  105. */
  106. Transform2D.MakeToRef = function (res, translation, rotation, scale) {
  107. if (translation) {
  108. res.translation.copyFrom(translation);
  109. }
  110. else {
  111. res.translation.copyFromFloats(0, 0);
  112. }
  113. if (rotation) {
  114. res.rotation = rotation;
  115. }
  116. else {
  117. res.rotation = 0;
  118. }
  119. if (scale) {
  120. res.scale.copyFrom(scale);
  121. }
  122. else {
  123. res.scale.copyFromFloats(1, 1);
  124. }
  125. };
  126. /**
  127. * Create a Transform2D object from float values
  128. * @param transX The translation on X axis, 0 per default
  129. * @param transY The translation on Y axis, 0 per default
  130. * @param rotation The rotation in radian, 0 per default
  131. * @param scaleX The scale along the X axis, 1 per default
  132. * @param scaleY The scale along the Y axis, 1 per default
  133. */
  134. Transform2D.MakeFromFloats = function (transX, transY, rotation, scaleX, scaleY) {
  135. var res = new Transform2D();
  136. if (transX) {
  137. res.translation.x = transX;
  138. }
  139. if (transY) {
  140. res.translation.y = transY;
  141. }
  142. if (rotation) {
  143. res.rotation = rotation;
  144. }
  145. if (scaleX) {
  146. res.scale.x = scaleX;
  147. }
  148. if (scaleY) {
  149. res.scale.y = scaleY;
  150. }
  151. return res;
  152. };
  153. /**
  154. * Set the given Transform2D object with the given float values
  155. * @param transX The translation on X axis, 0 per default
  156. * @param transY The translation on Y axis, 0 per default
  157. * @param rotation The rotation in radian, 0 per default
  158. * @param scaleX The scale along the X axis, 1 per default
  159. * @param scaleY The scale along the Y axis, 1 per default
  160. */
  161. Transform2D.MakeFromFloatsToRef = function (res, transX, transY, rotation, scaleX, scaleY) {
  162. res.translation.x = (transX != null) ? transX : 0;
  163. res.translation.y = (transY != null) ? transY : 0;
  164. res.rotation = (rotation != null) ? rotation : 0;
  165. res.scale.x = (scaleX != null) ? scaleX : 1;
  166. res.scale.y = (scaleY != null) ? scaleY : 1;
  167. };
  168. /**
  169. * Create a Transform2D containing only Zeroed values
  170. */
  171. Transform2D.Zero = function () {
  172. var res = new Transform2D();
  173. res.scale.copyFromFloats(0, 0);
  174. return res;
  175. };
  176. /**
  177. * Copy the value of the other object into 'this'
  178. * @param other The other object to copy values from
  179. */
  180. Transform2D.prototype.copyFrom = function (other) {
  181. this.translation.copyFrom(other.translation);
  182. this.rotation = other.rotation;
  183. this.scale.copyFrom(other.scale);
  184. };
  185. Transform2D.prototype.toMatrix2D = function () {
  186. var res = new Matrix2D();
  187. this.toMatrix2DToRef(res);
  188. return res;
  189. };
  190. Transform2D.prototype.toMatrix2DToRef = function (res) {
  191. var tx = this.translation.x;
  192. var ty = this.translation.y;
  193. var r = this.rotation;
  194. var cosr = Math.cos(r);
  195. var sinr = Math.sin(r);
  196. var sx = this.scale.x;
  197. var sy = this.scale.y;
  198. res.m[0] = cosr * sx;
  199. res.m[1] = sinr * sy;
  200. res.m[2] = -sinr * sx;
  201. res.m[3] = cosr * sy;
  202. res.m[4] = tx;
  203. res.m[5] = ty;
  204. };
  205. /**
  206. * In place transformation from a parent matrix.
  207. * @param parent transform object. "this" will be the result of parent * this
  208. */
  209. Transform2D.prototype.multiplyToThis = function (parent) {
  210. this.multiplyToRef(parent, this);
  211. };
  212. /**
  213. * Transform this object with a parent and return the result. Result = parent * this
  214. * @param parent The parent transformation
  215. */
  216. Transform2D.prototype.multiply = function (parent) {
  217. var res = new Transform2D();
  218. this.multiplyToRef(parent, res);
  219. return res;
  220. };
  221. /**
  222. * Transform a point and store the result in the very same object
  223. * @param p Transform this point and change the values with the transformed ones
  224. */
  225. Transform2D.prototype.transformPointInPlace = function (p) {
  226. this.transformPointToRef(p, p);
  227. };
  228. /**
  229. * Transform a point and store the result into a reference object
  230. * @param p The point to transform
  231. * @param res Will contain the new transformed coordinates. Can be the object of 'p'.
  232. */
  233. Transform2D.prototype.transformPointToRef = function (p, res) {
  234. this.transformFloatsToRef(p.x, p.y, res);
  235. };
  236. /**
  237. * Transform this object with a parent and store the result in reference object
  238. * @param parent The parent transformation
  239. * @param result Will contain parent * this. Can be the object of either parent or 'this'
  240. */
  241. Transform2D.prototype.multiplyToRef = function (parent, result) {
  242. if (!parent || !result) {
  243. throw new Error("Valid parent and result objects must be specified");
  244. }
  245. var tx = this.translation.x;
  246. var ty = this.translation.y;
  247. var ptx = parent.translation.x;
  248. var pty = parent.translation.y;
  249. var pr = parent.rotation;
  250. var psx = parent.scale.x;
  251. var psy = parent.scale.y;
  252. var cosr = Math.cos(pr);
  253. var sinr = Math.sin(pr);
  254. result.translation.x = (((tx * cosr) - (ty * sinr)) * psx) + ptx;
  255. result.translation.y = (((tx * sinr) + (ty * cosr)) * psy) + pty;
  256. this.scale.multiplyToRef(parent.scale, result.scale);
  257. result.rotation = this.rotation;
  258. };
  259. /**
  260. * Transform the given coordinates and store the result in a Vector2 object
  261. * @param x The X coordinate to transform
  262. * @param y The Y coordinate to transform
  263. * @param res The Vector2 object that will contain the result of the transformation
  264. */
  265. Transform2D.prototype.transformFloatsToRef = function (x, y, res) {
  266. var tx = this.translation.x;
  267. var ty = this.translation.y;
  268. var pr = this.rotation;
  269. var sx = this.scale.x;
  270. var sy = this.scale.y;
  271. var cosr = Math.cos(pr);
  272. var sinr = Math.sin(pr);
  273. res.x = (((x * cosr) - (y * sinr)) * sx) + tx;
  274. res.y = (((x * sinr) + (y * cosr)) * sy) + ty;
  275. };
  276. /**
  277. * Invert transform the given coordinates and store the result in a reference object. res = invert(this) * (x,y)
  278. * @param p Transform this point and change the values with the transformed ones
  279. * @param res Will contain the result of the invert transformation.
  280. */
  281. Transform2D.prototype.invertTransformFloatsToRef = function (x, y, res) {
  282. var px = x - this.translation.x;
  283. var py = y - this.translation.y;
  284. var pr = -this.rotation;
  285. var sx = this.scale.x;
  286. var sy = this.scale.y;
  287. var psx = (sx === 1) ? 1 : (1 / sx);
  288. var psy = (sy === 1) ? 1 : (1 / sy);
  289. var cosr = Math.cos(pr);
  290. var sinr = Math.sin(pr);
  291. res.x = (((px * cosr) - (py * sinr)) * psx);
  292. res.y = (((px * sinr) + (py * cosr)) * psy);
  293. };
  294. /**
  295. * Transform a point and return the result
  296. * @param p the point to transform
  297. */
  298. Transform2D.prototype.transformPoint = function (p) {
  299. var res = BABYLON.Vector2.Zero();
  300. this.transformPointToRef(p, res);
  301. return res;
  302. };
  303. /**
  304. * Transform the given coordinates and return the result in a Vector2 object
  305. * @param x The X coordinate to transform
  306. * @param y The Y coordinate to transform
  307. */
  308. Transform2D.prototype.transformFloats = function (x, y) {
  309. var res = BABYLON.Vector2.Zero();
  310. this.transformFloatsToRef(x, y, res);
  311. return res;
  312. };
  313. /**
  314. * Invert transform a given point and store the result in the very same object. p = invert(this) * p
  315. * @param p Transform this point and change the values with the transformed ones
  316. */
  317. Transform2D.prototype.invertTransformPointInPlace = function (p) {
  318. this.invertTransformPointToRef(p, p);
  319. };
  320. /**
  321. * Invert transform a given point and store the result in a reference object. res = invert(this) * p
  322. * @param p Transform this point and change the values with the transformed ones
  323. * @param res Will contain the result of the invert transformation. 'res' can be the same object as 'p'
  324. */
  325. Transform2D.prototype.invertTransformPointToRef = function (p, res) {
  326. this.invertTransformFloatsToRef(p.x, p.y, res);
  327. };
  328. /**
  329. * Invert transform a given point and return the result. return = invert(this) * p
  330. * @param p The Point to transform
  331. */
  332. Transform2D.prototype.invertTransformPoint = function (p) {
  333. var res = BABYLON.Vector2.Zero();
  334. this.invertTransformPointToRef(p, res);
  335. return res;
  336. };
  337. /**
  338. * Invert transform the given coordinates and return the result. return = invert(this) * (x,y)
  339. * @param x The X coordinate to transform
  340. * @param y The Y coordinate to transform
  341. */
  342. Transform2D.prototype.invertTransformFloats = function (x, y) {
  343. var res = BABYLON.Vector2.Zero();
  344. this.invertTransformFloatsToRef(x, y, res);
  345. return res;
  346. };
  347. return Transform2D;
  348. }());
  349. BABYLON.Transform2D = Transform2D;
  350. /**
  351. * A class storing a Matrix for 2D transformations
  352. * The stored matrix is a 2*3 Matrix
  353. * I [0,1] [mX, mY] R [ CosZ, SinZ] T [ 0, 0] S [Sx, 0]
  354. * D = [2,3] = [nX, nY] O = [-SinZ, CosZ] R = [ 0, 0] C = [ 0, Sy]
  355. * X [4,5] [tX, tY] T [ 0 , 0 ] N [Tx, Ty] L [ 0, 0]
  356. *
  357. * IDX = index, zero based. ROT = Z axis Rotation. TRN = Translation. SCL = Scale.
  358. */
  359. var Matrix2D = (function () {
  360. function Matrix2D() {
  361. this.m = new Float32Array(6);
  362. }
  363. Matrix2D.Identity = function () {
  364. var res = new Matrix2D();
  365. Matrix2D.IdentityToRef(res);
  366. return res;
  367. };
  368. Matrix2D.IdentityToRef = function (res) {
  369. res.m[1] = res.m[2] = res.m[4] = res.m[5] = 0;
  370. res.m[0] = res.m[3] = 1;
  371. };
  372. Matrix2D.prototype.copyFrom = function (other) {
  373. for (var i = 0; i < 6; i++) {
  374. this.m[i] = other.m[i];
  375. }
  376. };
  377. Matrix2D.prototype.determinant = function () {
  378. return (this.m[0] * this.m[3]) - (this.m[1] * this.m[2]);
  379. };
  380. Matrix2D.prototype.invertToThis = function () {
  381. this.invertToRef(this);
  382. };
  383. Matrix2D.prototype.invert = function () {
  384. var res = new Matrix2D();
  385. this.invertToRef(res);
  386. return res;
  387. };
  388. Matrix2D.prototype.invertToRef = function (res) {
  389. var a00 = this.m[0], a01 = this.m[1], a10 = this.m[2], a11 = this.m[3], a20 = this.m[4], a21 = this.m[5];
  390. var det21 = a21 * a10 - a11 * a20;
  391. var det = (a00 * a11) - (a01 * a10);
  392. if (det < (BABYLON.Epsilon * BABYLON.Epsilon)) {
  393. throw new Error("Can't invert matrix, near null determinant");
  394. }
  395. det = 1 / det;
  396. res.m[0] = a11 * det;
  397. res.m[1] = -a01 * det;
  398. res.m[2] = -a10 * det;
  399. res.m[3] = a00 * det;
  400. res.m[4] = det21 * det;
  401. res.m[5] = (-a21 * a00 + a01 * a20) * det;
  402. };
  403. Matrix2D.prototype.multiplyToThis = function (other) {
  404. this.multiplyToRef(other, this);
  405. };
  406. Matrix2D.prototype.multiply = function (other) {
  407. var res = new Matrix2D();
  408. this.multiplyToRef(other, res);
  409. return res;
  410. };
  411. Matrix2D.prototype.multiplyToRef = function (other, result) {
  412. var tm0 = this.m[0];
  413. var tm1 = this.m[1];
  414. //var tm2 = this.m[2];
  415. //var tm3 = this.m[3];
  416. var tm4 = this.m[2];
  417. var tm5 = this.m[3];
  418. //var tm6 = this.m[6];
  419. //var tm7 = this.m[7];
  420. var tm8 = this.m[4];
  421. var tm9 = this.m[5];
  422. //var tm10 = this.m[10];
  423. //var tm11 = this.m[11];
  424. //var tm12 = this.m[12];
  425. //var tm13 = this.m[13];
  426. //var tm14 = this.m[14];
  427. //var tm15 = this.m[15];
  428. var om0 = other.m[0];
  429. var om1 = other.m[1];
  430. //var om2 = other.m[2];
  431. //var om3 = other.m[3];
  432. var om4 = other.m[2];
  433. var om5 = other.m[3];
  434. //var om6 = other.m[6];
  435. //var om7 = other.m[7];
  436. var om8 = other.m[4];
  437. var om9 = other.m[5];
  438. //var om10 = other.m[10];
  439. //var om11 = other.m[11];
  440. //var om12 = other.m[12];
  441. //var om13 = other.m[13];
  442. //var om14 = other.m[14];
  443. //var om15 = other.m[15];
  444. result.m[0] = tm0 * om0 + tm1 * om4;
  445. result.m[1] = tm0 * om1 + tm1 * om5;
  446. //result.m[2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  447. //result.m[3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  448. result.m[2] = tm4 * om0 + tm5 * om4;
  449. result.m[3] = tm4 * om1 + tm5 * om5;
  450. //result.m[6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  451. //result.m[7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  452. result.m[4] = tm8 * om0 + tm9 * om4 + om8;
  453. result.m[5] = tm8 * om1 + tm9 * om5 + om9;
  454. //result.m[10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  455. //result.m[11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  456. //result.m[12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  457. //result.m[13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  458. //result.m[14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  459. //result.m[15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  460. };
  461. Matrix2D.prototype.transformFloats = function (x, y) {
  462. var res = BABYLON.Vector2.Zero();
  463. this.transformFloatsToRef(x, y, res);
  464. return res;
  465. };
  466. Matrix2D.prototype.transformFloatsToRef = function (x, y, r) {
  467. r.x = x * this.m[0] + y * this.m[2] + this.m[4];
  468. r.y = x * this.m[1] + y * this.m[3] + this.m[5];
  469. };
  470. Matrix2D.prototype.transformPoint = function (p) {
  471. var res = BABYLON.Vector2.Zero();
  472. this.transformFloatsToRef(p.x, p.y, res);
  473. return res;
  474. };
  475. Matrix2D.prototype.transformPointToRef = function (p, r) {
  476. this.transformFloatsToRef(p.x, p.y, r);
  477. };
  478. return Matrix2D;
  479. }());
  480. BABYLON.Matrix2D = Matrix2D;
  481. /**
  482. * Stores information about a 2D Triangle.
  483. * This class stores the 3 vertices but also the center and radius of the triangle
  484. */
  485. var Tri2DInfo = (function () {
  486. /**
  487. * Construct an instance of Tri2DInfo, you can either pass null to a, b and c and the instance will be allocated "clear", or give actual triangle info and the center/radius will be computed
  488. */
  489. function Tri2DInfo(a, b, c) {
  490. if (a === null && b === null && c === null) {
  491. this.a = BABYLON.Vector2.Zero();
  492. this.b = BABYLON.Vector2.Zero();
  493. this.c = BABYLON.Vector2.Zero();
  494. this.center = BABYLON.Vector2.Zero();
  495. this.radius = 0;
  496. return;
  497. }
  498. this.a = a.clone();
  499. this.b = b.clone();
  500. this.c = c.clone();
  501. this._updateCenterRadius();
  502. }
  503. Tri2DInfo.Zero = function () {
  504. return new Tri2DInfo(null, null, null);
  505. };
  506. Tri2DInfo.prototype.set = function (a, b, c) {
  507. this.a.copyFrom(a);
  508. this.b.copyFrom(b);
  509. this.c.copyFrom(c);
  510. this._updateCenterRadius();
  511. };
  512. Tri2DInfo.prototype.transformInPlace = function (transform) {
  513. BABYLON.Vector2.TransformToRef(this.a, transform, this.a);
  514. BABYLON.Vector2.TransformToRef(this.b, transform, this.b);
  515. BABYLON.Vector2.TransformToRef(this.c, transform, this.c);
  516. this._updateCenterRadius();
  517. };
  518. Tri2DInfo.prototype.doesContain = function (p) {
  519. return BABYLON.Vector2.PointInTriangle(p, this.a, this.b, this.c);
  520. };
  521. Tri2DInfo.prototype._updateCenterRadius = function () {
  522. this.center.x = (this.a.x + this.b.x + this.c.x) / 3;
  523. this.center.y = (this.a.y + this.b.y + this.c.y) / 3;
  524. var la = BABYLON.Vector2.DistanceSquared(this.a, this.center);
  525. var lb = BABYLON.Vector2.DistanceSquared(this.b, this.center);
  526. var lc = BABYLON.Vector2.DistanceSquared(this.c, this.center);
  527. var rs = Math.max(Math.max(la, lb), lc);
  528. this.radius = Math.sqrt(rs);
  529. };
  530. return Tri2DInfo;
  531. }());
  532. BABYLON.Tri2DInfo = Tri2DInfo;
  533. /**
  534. * Stores an array of 2D Triangles.
  535. * Internally the data is stored as a Float32Array to minimize the memory footprint.
  536. * This can use the Tri2DInfo class as proxy for storing/retrieving data.
  537. * The array can't grow, it's fixed size.
  538. */
  539. var Tri2DArray = (function () {
  540. function Tri2DArray(count) {
  541. this._count = count;
  542. this._array = new Float32Array(9 * count);
  543. }
  544. /**
  545. * Clear the content and allocate a new array to store the given count of triangles
  546. * @param count The new count of triangles to store
  547. */
  548. Tri2DArray.prototype.clear = function (count) {
  549. if (this._count === count) {
  550. return;
  551. }
  552. this._count = count;
  553. this._array = new Float32Array(9 * count);
  554. };
  555. /**
  556. * Store a given triangle at the given index
  557. * @param index the 0 based index to store the triangle in the array
  558. * @param a the A vertex of the triangle
  559. * @param b the B vertex of the triangle
  560. * @param c the C vertex of the triangle
  561. */
  562. Tri2DArray.prototype.storeTriangle = function (index, a, b, c) {
  563. var center = new BABYLON.Vector2((a.x + b.x + c.x) / 3, (a.y + b.y + c.y) / 3);
  564. var la = BABYLON.Vector2.DistanceSquared(a, center);
  565. var lb = BABYLON.Vector2.DistanceSquared(b, center);
  566. var lc = BABYLON.Vector2.DistanceSquared(c, center);
  567. var rs = Math.max(Math.max(la, lb), lc);
  568. var radius = Math.sqrt(rs);
  569. var offset = index * 9;
  570. this._array[offset + 0] = a.x;
  571. this._array[offset + 1] = a.y;
  572. this._array[offset + 2] = b.x;
  573. this._array[offset + 3] = b.y;
  574. this._array[offset + 4] = c.x;
  575. this._array[offset + 5] = c.y;
  576. this._array[offset + 6] = center.x;
  577. this._array[offset + 7] = center.y;
  578. this._array[offset + 8] = radius;
  579. };
  580. /**
  581. * Store a triangle in a Tri2DInfo object
  582. * @param index the index of the triangle to store
  583. * @param tri2dInfo the instance that will contain the data, it must be already allocated with its inner object also allocated
  584. */
  585. Tri2DArray.prototype.storeToTri2DInfo = function (index, tri2dInfo) {
  586. if (index >= this._count) {
  587. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  588. }
  589. var offset = index * 9;
  590. tri2dInfo.a.x = this._array[offset + 0];
  591. tri2dInfo.a.y = this._array[offset + 1];
  592. tri2dInfo.b.x = this._array[offset + 2];
  593. tri2dInfo.b.y = this._array[offset + 3];
  594. tri2dInfo.c.x = this._array[offset + 4];
  595. tri2dInfo.c.y = this._array[offset + 5];
  596. tri2dInfo.center.x = this._array[offset + 6];
  597. tri2dInfo.center.y = this._array[offset + 7];
  598. tri2dInfo.radius = this._array[offset + 8];
  599. };
  600. /**
  601. * Transform the given triangle and store its result in the array
  602. * @param index The index to store the result to
  603. * @param tri2dInfo The triangle to transform
  604. * @param transform The transformation matrix
  605. */
  606. Tri2DArray.prototype.transformAndStoreToTri2DInfo = function (index, tri2dInfo, transform) {
  607. if (index >= this._count) {
  608. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  609. }
  610. var offset = index * 9;
  611. tri2dInfo.a.x = this._array[offset + 0];
  612. tri2dInfo.a.y = this._array[offset + 1];
  613. tri2dInfo.b.x = this._array[offset + 2];
  614. tri2dInfo.b.y = this._array[offset + 3];
  615. tri2dInfo.c.x = this._array[offset + 4];
  616. tri2dInfo.c.y = this._array[offset + 5];
  617. tri2dInfo.transformInPlace(transform);
  618. };
  619. Object.defineProperty(Tri2DArray.prototype, "count", {
  620. /**
  621. * Get the element count that can be stored in this array
  622. * @returns {}
  623. */
  624. get: function () {
  625. return this._count;
  626. },
  627. enumerable: true,
  628. configurable: true
  629. });
  630. /**
  631. * Check if a given point intersects with at least one of the triangles stored in the array.
  632. * If true is returned the point is intersecting with at least one triangle, false if it doesn't intersect with any of them
  633. * @param p The point to check
  634. */
  635. Tri2DArray.prototype.doesContain = function (p) {
  636. Tri2DArray._checkInitStatics();
  637. var a = Tri2DArray.tempT[0];
  638. for (var i = 0; i < this.count; i++) {
  639. this.storeToTri2DInfo(i, a);
  640. if (a.doesContain(p)) {
  641. return true;
  642. }
  643. }
  644. return false;
  645. };
  646. /**
  647. * Make a intersection test between two sets of triangles. The triangles of setB will be transformed to the frame of reference of the setA using the given bToATransform matrix.
  648. * If true is returned at least one triangle intersects with another of the other set, otherwise false is returned.
  649. * @param setA The first set of triangles
  650. * @param setB The second set of triangles
  651. * @param bToATransform The transformation matrix to transform the setB triangles into the frame of reference of the setA
  652. */
  653. Tri2DArray.doesIntersect = function (setA, setB, bToATransform) {
  654. Tri2DArray._checkInitStatics();
  655. var a = Tri2DArray.tempT[0];
  656. var b = Tri2DArray.tempT[1];
  657. var v0 = Tri2DArray.tempV[0];
  658. for (var curB = 0; curB < setB.count; curB++) {
  659. setB.transformAndStoreToTri2DInfo(curB, b, bToATransform);
  660. for (var curA = 0; curA < setA.count; curA++) {
  661. setA.storeToTri2DInfo(curA, a);
  662. // Fast rejection first
  663. v0.x = a.center.x - b.center.x;
  664. v0.y = a.center.y - b.center.y;
  665. if (v0.lengthSquared() > ((a.radius * a.radius) + (b.radius * b.radius))) {
  666. continue;
  667. }
  668. // Actual intersection test
  669. if (Math2D.TriangleTriangleDosIntersect(a.a, a.b, a.c, b.a, b.b, b.c)) {
  670. return true;
  671. }
  672. }
  673. }
  674. return false;
  675. };
  676. Tri2DArray._checkInitStatics = function () {
  677. if (Tri2DArray.tempT !== null) {
  678. return;
  679. }
  680. Tri2DArray.tempT = new Array(2);
  681. Tri2DArray.tempT[0] = new Tri2DInfo(null, null, null);
  682. Tri2DArray.tempT[1] = new Tri2DInfo(null, null, null);
  683. Tri2DArray.tempV = new Array(6);
  684. for (var i = 0; i < 6; i++) {
  685. Tri2DArray.tempV[i] = BABYLON.Vector2.Zero();
  686. }
  687. };
  688. return Tri2DArray;
  689. }());
  690. Tri2DArray.tempV = null;
  691. Tri2DArray.tempT = null;
  692. BABYLON.Tri2DArray = Tri2DArray;
  693. /**
  694. * Some 2D Math helpers functions
  695. */
  696. var Math2D = (function () {
  697. function Math2D() {
  698. }
  699. Math2D.Dot = function (a, b) {
  700. return a.x * b.x + a.y * b.y;
  701. };
  702. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  703. // Note: this one might also be considered with the above one proves to not be good enough: http://jsfiddle.net/justin_c_rounds/Gd2S2/light/
  704. Math2D.LineLineDoesIntersect = function (segA1, segA2, segB1, segB2) {
  705. var s1_x = segA2.x - segA1.x;
  706. var s1_y = segA2.y - segA1.y;
  707. var s2_x = segB2.x - segB1.x;
  708. var s2_y = segB2.y - segB1.y;
  709. var s = (-s1_y * (segA1.x - segB1.x) + s1_x * (segA1.y - segB1.y)) / (-s2_x * s1_y + s1_x * s2_y);
  710. var t = (s2_x * (segA1.y - segB1.y) - s2_y * (segA1.x - segB1.x)) / (-s2_x * s1_y + s1_x * s2_y);
  711. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  712. return true;
  713. }
  714. return false;
  715. };
  716. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  717. Math2D.LineLineIntersection = function (p0, p1, p2, p3) {
  718. var s1_x = p1.x - p0.x;
  719. var s1_y = p1.y - p0.y;
  720. var s2_x = p3.x - p2.x;
  721. var s2_y = p3.y - p2.y;
  722. var s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y);
  723. var t = (s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y);
  724. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  725. return { res: true, xr: p0.x + (t * s1_x), yr: p0.y + (t * s1_y) };
  726. }
  727. return { res: false, xr: 0, yr: 0 };
  728. };
  729. // Tell me that it's slow and I'll answer: yes it is!
  730. // If you fancy to implement the SAT (Separating Axis Theorem) version: BE MY VERY WELCOMED GUEST!
  731. Math2D.TriangleTriangleDosIntersect = function (tri1A, tri1B, tri1C, tri2A, tri2B, tri2C) {
  732. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2B))
  733. return true;
  734. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2C))
  735. return true;
  736. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2B, tri2C))
  737. return true;
  738. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2B))
  739. return true;
  740. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2C))
  741. return true;
  742. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2B, tri2C))
  743. return true;
  744. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2B))
  745. return true;
  746. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2C))
  747. return true;
  748. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2B, tri2C))
  749. return true;
  750. if (BABYLON.Vector2.PointInTriangle(tri2A, tri1A, tri1B, tri1C) &&
  751. BABYLON.Vector2.PointInTriangle(tri2B, tri1A, tri1B, tri1C) &&
  752. BABYLON.Vector2.PointInTriangle(tri2C, tri1A, tri1B, tri1C))
  753. return true;
  754. if (BABYLON.Vector2.PointInTriangle(tri1A, tri2A, tri2B, tri2C) &&
  755. BABYLON.Vector2.PointInTriangle(tri1B, tri2A, tri2B, tri2C) &&
  756. BABYLON.Vector2.PointInTriangle(tri1C, tri2A, tri2B, tri2C))
  757. return true;
  758. return false;
  759. };
  760. return Math2D;
  761. }());
  762. Math2D.v0 = BABYLON.Vector2.Zero();
  763. Math2D.v1 = BABYLON.Vector2.Zero();
  764. Math2D.v2 = BABYLON.Vector2.Zero();
  765. })(BABYLON || (BABYLON = {}));
  766. //# sourceMappingURL=babylon.math2D.js.map
  767. var BABYLON;
  768. (function (BABYLON) {
  769. var PropertyChangedInfo = (function () {
  770. function PropertyChangedInfo() {
  771. }
  772. return PropertyChangedInfo;
  773. }());
  774. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  775. /**
  776. * The purpose of this class is to provide a base implementation of the IPropertyChanged interface for the user to avoid rewriting a code needlessly.
  777. * Typical use of this class is to check for equality in a property set(), then call the onPropertyChanged method if values are different after the new value is set. The protected method will notify observers of the change.
  778. * Remark: onPropertyChanged detects reentrant code and acts in a way to make sure everything is fine, fast and allocation friendly (when there no reentrant code which should be 99% of the time)
  779. */
  780. var PropertyChangedBase = (function () {
  781. function PropertyChangedBase() {
  782. this._propertyChanged = null;
  783. }
  784. /**
  785. * Protected method to call when there's a change of value in a property set
  786. * @param propName the name of the concerned property
  787. * @param oldValue its old value
  788. * @param newValue its new value
  789. * @param mask an optional observable mask
  790. */
  791. PropertyChangedBase.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  792. if (this.propertyChanged.hasObservers()) {
  793. var pci = PropertyChangedBase.calling ? new PropertyChangedInfo() : PropertyChangedBase.pci;
  794. pci.oldValue = oldValue;
  795. pci.newValue = newValue;
  796. pci.propertyName = propName;
  797. try {
  798. PropertyChangedBase.calling = true;
  799. this.propertyChanged.notifyObservers(pci, mask);
  800. }
  801. finally {
  802. PropertyChangedBase.calling = false;
  803. }
  804. }
  805. };
  806. Object.defineProperty(PropertyChangedBase.prototype, "propertyChanged", {
  807. /**
  808. * An observable that is triggered when a property (using of the XXXXLevelProperty decorator) has its value changing.
  809. * You can add an observer that will be triggered only for a given set of Properties using the Mask feature of the Observable and the corresponding Prim2DPropInfo.flagid value (e.g. Prim2DBase.positionProperty.flagid|Prim2DBase.rotationProperty.flagid to be notified only about position or rotation change)
  810. */
  811. get: function () {
  812. if (!this._propertyChanged) {
  813. this._propertyChanged = new BABYLON.Observable();
  814. }
  815. return this._propertyChanged;
  816. },
  817. enumerable: true,
  818. configurable: true
  819. });
  820. return PropertyChangedBase;
  821. }());
  822. PropertyChangedBase.pci = new PropertyChangedInfo();
  823. PropertyChangedBase.calling = false;
  824. BABYLON.PropertyChangedBase = PropertyChangedBase;
  825. })(BABYLON || (BABYLON = {}));
  826. //# sourceMappingURL=babylon.IPropertyChanged.js.map
  827. var __extends = (this && this.__extends) || function (d, b) {
  828. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  829. function __() { this.constructor = d; }
  830. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  831. };
  832. var BABYLON;
  833. (function (BABYLON) {
  834. /**
  835. * Class for the ObservableArray.onArrayChanged observable
  836. */
  837. var ArrayChanged = (function () {
  838. function ArrayChanged() {
  839. this.action = 0;
  840. this.newItems = new Array();
  841. this.removedItems = new Array();
  842. this.changedItems = new Array();
  843. this.newStartingIndex = -1;
  844. this.removedStartingIndex = -1;
  845. }
  846. Object.defineProperty(ArrayChanged, "clearAction", {
  847. /**
  848. * The content of the array was totally cleared
  849. */
  850. get: function () {
  851. return ArrayChanged._clearAction;
  852. },
  853. enumerable: true,
  854. configurable: true
  855. });
  856. Object.defineProperty(ArrayChanged, "newItemsAction", {
  857. /**
  858. * A new item was added, the newItems field contains the key/value pairs
  859. */
  860. get: function () {
  861. return ArrayChanged._newItemsAction;
  862. },
  863. enumerable: true,
  864. configurable: true
  865. });
  866. Object.defineProperty(ArrayChanged, "removedItemsAction", {
  867. /**
  868. * An existing item was removed, the removedKey field contains its key
  869. */
  870. get: function () {
  871. return ArrayChanged._removedItemsAction;
  872. },
  873. enumerable: true,
  874. configurable: true
  875. });
  876. Object.defineProperty(ArrayChanged, "changedItemAction", {
  877. /**
  878. * One or many items in the array were changed, the
  879. */
  880. get: function () {
  881. return ArrayChanged._changedItemAction;
  882. },
  883. enumerable: true,
  884. configurable: true
  885. });
  886. Object.defineProperty(ArrayChanged, "replacedArrayAction", {
  887. /**
  888. * The array's content was totally changed
  889. * Depending on the method that used this mode the ChangedArray object may contains more information
  890. */
  891. get: function () {
  892. return ArrayChanged._replacedArrayAction;
  893. },
  894. enumerable: true,
  895. configurable: true
  896. });
  897. Object.defineProperty(ArrayChanged, "lengthChangedAction", {
  898. /**
  899. * The length of the array changed
  900. */
  901. get: function () {
  902. return ArrayChanged._lengthChangedAction;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. ArrayChanged.prototype.clear = function () {
  908. this.action = 0;
  909. this.newItems.splice(0);
  910. this.removedItems.splice(0);
  911. this.changedItems.splice(0);
  912. this.removedStartingIndex = this.removedStartingIndex = this.changedStartingIndex = 0;
  913. };
  914. return ArrayChanged;
  915. }());
  916. ArrayChanged._clearAction = 0x1;
  917. ArrayChanged._newItemsAction = 0x2;
  918. ArrayChanged._removedItemsAction = 0x4;
  919. ArrayChanged._replacedArrayAction = 0x8;
  920. ArrayChanged._lengthChangedAction = 0x10;
  921. ArrayChanged._changedItemAction = 0x20;
  922. BABYLON.ArrayChanged = ArrayChanged;
  923. var OAWatchedObjectChangedInfo = (function () {
  924. function OAWatchedObjectChangedInfo() {
  925. }
  926. return OAWatchedObjectChangedInfo;
  927. }());
  928. BABYLON.OAWatchedObjectChangedInfo = OAWatchedObjectChangedInfo;
  929. /**
  930. * This class mimics the Javascript Array and TypeScript Array<T> classes, adding new features concerning the Observable pattern.
  931. *
  932. */
  933. var ObservableArray = (function (_super) {
  934. __extends(ObservableArray, _super);
  935. /**
  936. * Create an Observable Array.
  937. * @param watchObjectsPropertyChange
  938. * @param array and optional array that will be encapsulated by this ObservableArray instance. That's right, it's NOT a copy!
  939. */
  940. function ObservableArray(watchObjectsPropertyChange, array) {
  941. var _this = _super.call(this) || this;
  942. _this.dci = new ArrayChanged();
  943. _this._callingArrayChanged = false;
  944. _this._array = (array != null) ? array : new Array();
  945. _this.dci = new ArrayChanged();
  946. _this._callingArrayChanged = false;
  947. _this._arrayChanged = null;
  948. _this._callingWatchedObjectChanged = false;
  949. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  950. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  951. _this._woci = new OAWatchedObjectChangedInfo();
  952. return _this;
  953. }
  954. Object.defineProperty(ObservableArray.prototype, "length", {
  955. /**
  956. * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
  957. */
  958. get: function () {
  959. return this._array.length;
  960. },
  961. set: function (value) {
  962. if (value === this._array.length) {
  963. return;
  964. }
  965. var oldLength = this._array.length;
  966. this._array.length = value;
  967. this.onPropertyChanged("length", oldLength, this._array.length);
  968. },
  969. enumerable: true,
  970. configurable: true
  971. });
  972. ObservableArray.prototype.getAt = function (index) {
  973. return this._array[index];
  974. };
  975. ObservableArray.prototype.setAt = function (index, value) {
  976. if (index < 0) {
  977. return false;
  978. }
  979. var insertion = (index >= this._array.length) || this._array[index] === undefined;
  980. var oldLength = 0;
  981. if (insertion) {
  982. oldLength = this._array.length;
  983. }
  984. else if (this._watchObjectsPropertyChange) {
  985. this._removeWatchedElement(this._array[index]);
  986. }
  987. this._array[index] = value;
  988. if (this._watchObjectsPropertyChange) {
  989. this._addWatchedElement(value);
  990. }
  991. if (insertion) {
  992. this.onPropertyChanged("length", oldLength, this._array.length);
  993. }
  994. var ac = this.getArrayChangedObject();
  995. if (ac) {
  996. ac.action = insertion ? ArrayChanged.newItemsAction : ArrayChanged.changedItemAction;
  997. if (insertion) {
  998. ac.newItems.splice(0, ac.newItems.length, { index: index, value: value });
  999. ac.newStartingIndex = index;
  1000. ac.changedItems.splice(0);
  1001. }
  1002. else {
  1003. ac.newItems.splice(0);
  1004. ac.changedStartingIndex = index;
  1005. ac.changedItems.splice(0, ac.changedItems.length, { index: index, value: value });
  1006. }
  1007. ac.removedItems.splice(0);
  1008. ac.removedStartingIndex = -1;
  1009. this.callArrayChanged(ac);
  1010. }
  1011. };
  1012. /**
  1013. * Returns a string representation of an array.
  1014. */
  1015. ObservableArray.prototype.toString = function () {
  1016. return this._array.toString();
  1017. };
  1018. ObservableArray.prototype.toLocaleString = function () {
  1019. return this._array.toLocaleString();
  1020. };
  1021. /**
  1022. * Appends new elements to an array, and returns the new length of the array.
  1023. * @param items New elements of the Array.
  1024. */
  1025. ObservableArray.prototype.push = function () {
  1026. var items = [];
  1027. for (var _i = 0; _i < arguments.length; _i++) {
  1028. items[_i] = arguments[_i];
  1029. }
  1030. var oldLength = this._array.length;
  1031. var n = (_a = this._array).push.apply(_a, items);
  1032. if (this._watchObjectsPropertyChange) {
  1033. this._addWatchedElement.apply(this, items);
  1034. }
  1035. this.onPropertyChanged("length", oldLength, this._array.length);
  1036. var ac = this.getArrayChangedObject();
  1037. if (ac) {
  1038. ac.action = ArrayChanged.newItemsAction;
  1039. ac.newStartingIndex = oldLength;
  1040. this.feedNotifArray.apply(this, [ac.newItems, oldLength].concat(items));
  1041. this.callArrayChanged(ac);
  1042. }
  1043. return n;
  1044. var _a;
  1045. };
  1046. /**
  1047. * Removes the last element from an array and returns it.
  1048. */
  1049. ObservableArray.prototype.pop = function () {
  1050. var firstRemove = this._array.length - 1;
  1051. var res = this._array.pop();
  1052. if (res && this._watchObjectsPropertyChange) {
  1053. this._removeWatchedElement(res);
  1054. }
  1055. if (firstRemove !== -1) {
  1056. this.onPropertyChanged("length", this._array.length + 1, this._array.length);
  1057. var ac = this.getArrayChangedObject();
  1058. if (ac) {
  1059. ac.action = ArrayChanged.removedItemsAction;
  1060. ac.removedStartingIndex = firstRemove;
  1061. this.feedNotifArray(ac.removedItems, firstRemove, res);
  1062. }
  1063. }
  1064. return res;
  1065. };
  1066. /**
  1067. * Combines two or more arrays.
  1068. * @param items Additional items to add to the end of array1.
  1069. */
  1070. ObservableArray.prototype.concat = function () {
  1071. var items = [];
  1072. for (var _i = 0; _i < arguments.length; _i++) {
  1073. items[_i] = arguments[_i];
  1074. }
  1075. return new ObservableArray(this._watchObjectsPropertyChange, (_a = this._array).concat.apply(_a, items));
  1076. var _a;
  1077. };
  1078. /**
  1079. * Adds all the elements of an array separated by the specified separator string.
  1080. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
  1081. */
  1082. ObservableArray.prototype.join = function (separator) {
  1083. return this._array.join(separator);
  1084. };
  1085. /**
  1086. * Reverses the elements in an Array.
  1087. * The arrayChanged action is
  1088. */
  1089. ObservableArray.prototype.reverse = function () {
  1090. var res = this._array.reverse();
  1091. var ac = this.getArrayChangedObject();
  1092. ac.action = ArrayChanged.replacedArrayAction;
  1093. return res;
  1094. };
  1095. /**
  1096. * Removes the first element from an array and returns it, shift all subsequents element one element before.
  1097. * The ArrayChange action is replacedArrayAction, the whole array changes and must be reevaluate as such, the removed element is in removedItems.
  1098. *
  1099. */
  1100. ObservableArray.prototype.shift = function () {
  1101. var oldLength = this._array.length;
  1102. var res = this._array.shift();
  1103. if (this._watchedObjectChanged && res != null) {
  1104. this._removeWatchedElement(res);
  1105. }
  1106. if (oldLength !== 0) {
  1107. this.onPropertyChanged("length", oldLength, this._array.length);
  1108. var ac = this.getArrayChangedObject();
  1109. if (ac) {
  1110. ac.action = ArrayChanged.replacedArrayAction;
  1111. ac.removedItems.splice(0, ac.removedItems.length, { index: 0, value: res });
  1112. ac.newItems.splice(0);
  1113. ac.changedItems.splice(0);
  1114. ac.removedStartingIndex = 0;
  1115. this.callArrayChanged(ac);
  1116. }
  1117. }
  1118. return res;
  1119. };
  1120. /**
  1121. * Returns a section of an array.
  1122. * @param start The beginning of the specified portion of the array.
  1123. * @param end The end of the specified portion of the array.
  1124. */
  1125. ObservableArray.prototype.slice = function (start, end) {
  1126. return new ObservableArray(this._watchObjectsPropertyChange, this._array.slice(start, end));
  1127. };
  1128. /**
  1129. * Sorts an array.
  1130. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.
  1131. * On the contrary of the Javascript Array's implementation, this method returns nothing
  1132. */
  1133. ObservableArray.prototype.sort = function (compareFn) {
  1134. var oldLength = this._array.length;
  1135. this._array.sort(compareFn);
  1136. if (oldLength !== 0) {
  1137. var ac = this.getArrayChangedObject();
  1138. if (ac) {
  1139. ac.clear();
  1140. ac.action = ArrayChanged.replacedArrayAction;
  1141. this.callArrayChanged(ac);
  1142. }
  1143. }
  1144. };
  1145. /**
  1146. * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
  1147. * @param start The zero-based location in the array from which to start removing elements.
  1148. * @param deleteCount The number of elements to remove.
  1149. * @param items Elements to insert into the array in place of the deleted elements.
  1150. */
  1151. ObservableArray.prototype.splice = function (start, deleteCount) {
  1152. var items = [];
  1153. for (var _i = 2; _i < arguments.length; _i++) {
  1154. items[_i - 2] = arguments[_i];
  1155. }
  1156. var oldLength = this._array.length;
  1157. if (this._watchObjectsPropertyChange) {
  1158. for (var i = start; i < start + deleteCount; i++) {
  1159. var val = this._array[i];
  1160. if (this._watchObjectsPropertyChange && val != null) {
  1161. this._removeWatchedElement(val);
  1162. }
  1163. }
  1164. }
  1165. var res = (_a = this._array).splice.apply(_a, [start, deleteCount].concat(items));
  1166. if (this._watchObjectsPropertyChange) {
  1167. this._addWatchedElement.apply(this, items);
  1168. }
  1169. if (oldLength !== this._array.length) {
  1170. this.onPropertyChanged("length", oldLength, this._array.length);
  1171. }
  1172. var ac = this.getArrayChangedObject();
  1173. if (ac) {
  1174. ac.clear();
  1175. ac.action = ArrayChanged.replacedArrayAction;
  1176. this.callArrayChanged(ac);
  1177. }
  1178. return res;
  1179. var _a;
  1180. };
  1181. /**
  1182. * Inserts new elements at the start of an array.
  1183. * @param items Elements to insert at the start of the Array.
  1184. * The ChangedArray action is replacedArrayAction, newItems contains the list of the added items
  1185. */
  1186. ObservableArray.prototype.unshift = function () {
  1187. var items = [];
  1188. for (var _i = 0; _i < arguments.length; _i++) {
  1189. items[_i] = arguments[_i];
  1190. }
  1191. var oldLength = this._array.length;
  1192. var res = (_a = this._array).unshift.apply(_a, items);
  1193. if (this._watchObjectsPropertyChange) {
  1194. this._addWatchedElement.apply(this, items);
  1195. }
  1196. this.onPropertyChanged("length", oldLength, this._array.length);
  1197. var ac = this.getArrayChangedObject();
  1198. if (ac) {
  1199. ac.clear();
  1200. ac.action = ArrayChanged.replacedArrayAction;
  1201. ac.newStartingIndex = 0, this.feedNotifArray.apply(this, [ac.newItems, 0].concat(items));
  1202. this.callArrayChanged(ac);
  1203. }
  1204. return res;
  1205. var _a;
  1206. };
  1207. /**
  1208. * Returns the index of the first occurrence of a value in an array.
  1209. * @param searchElement The value to locate in the array.
  1210. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
  1211. */
  1212. ObservableArray.prototype.indexOf = function (searchElement, fromIndex) {
  1213. return this._array.indexOf(searchElement, fromIndex);
  1214. };
  1215. /**
  1216. * Returns the index of the last occurrence of a specified value in an array.
  1217. * @param searchElement The value to locate in the array.
  1218. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.
  1219. */
  1220. ObservableArray.prototype.lastIndexOf = function (searchElement, fromIndex) {
  1221. return this._array.lastIndexOf(searchElement, fromIndex);
  1222. };
  1223. /**
  1224. * Determines whether all the members of an array satisfy the specified test.
  1225. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.
  1226. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1227. */
  1228. ObservableArray.prototype.every = function (callbackfn, thisArg) {
  1229. return this._array.every(callbackfn, thisArg);
  1230. };
  1231. /**
  1232. * Determines whether the specified callback function returns true for any element of an array.
  1233. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.
  1234. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1235. */
  1236. ObservableArray.prototype.some = function (callbackfn, thisArg) {
  1237. return this._array.some(callbackfn, thisArg);
  1238. };
  1239. /**
  1240. * Performs the specified action for each element in an array.
  1241. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
  1242. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1243. */
  1244. ObservableArray.prototype.forEach = function (callbackfn, thisArg) {
  1245. return this._array.forEach(callbackfn, thisArg);
  1246. };
  1247. /**
  1248. * Calls a defined callback function on each element of an array, and returns an array that contains the results.
  1249. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
  1250. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1251. */
  1252. ObservableArray.prototype.map = function (callbackfn, thisArg) {
  1253. return this._array.map(callbackfn, thisArg);
  1254. };
  1255. /**
  1256. * Returns the elements of an array that meet the condition specified in a callback function.
  1257. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
  1258. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1259. */
  1260. ObservableArray.prototype.filter = function (callbackfn, thisArg) {
  1261. return this._array.filter(callbackfn, thisArg);
  1262. };
  1263. /**
  1264. * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
  1265. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
  1266. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
  1267. */
  1268. ObservableArray.prototype.reduce = function (callbackfn, initialValue) {
  1269. return this._array.reduce(callbackfn);
  1270. };
  1271. /**
  1272. * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
  1273. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
  1274. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
  1275. */
  1276. ObservableArray.prototype.reduceRight = function (callbackfn, initialValue) {
  1277. return this._array.reduceRight(callbackfn);
  1278. };
  1279. Object.defineProperty(ObservableArray.prototype, "arrayChanged", {
  1280. get: function () {
  1281. if (!this._arrayChanged) {
  1282. this._arrayChanged = new BABYLON.Observable();
  1283. }
  1284. return this._arrayChanged;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. ObservableArray.prototype.getArrayChangedObject = function () {
  1290. if (this._arrayChanged && this._arrayChanged.hasObservers()) {
  1291. var ac = this._callingArrayChanged ? new ArrayChanged() : this.dci;
  1292. return ac;
  1293. }
  1294. return null;
  1295. };
  1296. ObservableArray.prototype.feedNotifArray = function (array, startindIndex) {
  1297. var items = [];
  1298. for (var _i = 2; _i < arguments.length; _i++) {
  1299. items[_i - 2] = arguments[_i];
  1300. }
  1301. array.splice(0);
  1302. for (var i = 0; i < items.length; i++) {
  1303. var value = this._array[i + startindIndex];
  1304. if (value !== undefined) {
  1305. array.push({ index: i + startindIndex, value: value });
  1306. }
  1307. }
  1308. };
  1309. ObservableArray.prototype.callArrayChanged = function (ac) {
  1310. try {
  1311. this._callingArrayChanged = true;
  1312. this.arrayChanged.notifyObservers(ac, ac.action);
  1313. }
  1314. finally {
  1315. this._callingArrayChanged = false;
  1316. }
  1317. };
  1318. Object.defineProperty(ObservableArray.prototype, "watchedObjectChanged", {
  1319. get: function () {
  1320. if (!this._watchedObjectChanged) {
  1321. this._watchedObjectChanged = new BABYLON.Observable();
  1322. }
  1323. return this._watchedObjectChanged;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. ObservableArray.prototype._addWatchedElement = function () {
  1329. var _this = this;
  1330. var items = [];
  1331. for (var _i = 0; _i < arguments.length; _i++) {
  1332. items[_i] = arguments[_i];
  1333. }
  1334. var _loop_1 = function (curItem) {
  1335. if (curItem["propertyChanged"]) {
  1336. var key_1 = curItem["__ObsArrayObjID__"];
  1337. // The object may already be part of another ObsArray, so there already be a valid ID
  1338. if (!key_1) {
  1339. key_1 = BABYLON.Tools.RandomId();
  1340. curItem["__ObsArrayObjID__"] = key_1;
  1341. }
  1342. this_1._watchedObjectList.add(key_1, curItem.propertyChanged.add(function (e, d) {
  1343. _this.onWatchedObjectChanged(key_1, curItem, e);
  1344. }));
  1345. }
  1346. };
  1347. var this_1 = this;
  1348. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  1349. var curItem = items_1[_a];
  1350. _loop_1(curItem);
  1351. }
  1352. };
  1353. ObservableArray.prototype._removeWatchedElement = function () {
  1354. var items = [];
  1355. for (var _i = 0; _i < arguments.length; _i++) {
  1356. items[_i] = arguments[_i];
  1357. }
  1358. for (var _a = 0, items_2 = items; _a < items_2.length; _a++) {
  1359. var curItem = items_2[_a];
  1360. var key = curItem["__ObsArrayObjID__"];
  1361. if (key != null) {
  1362. var observer = this._watchedObjectList.getAndRemove(key);
  1363. curItem.propertyChanged.remove(observer);
  1364. }
  1365. }
  1366. };
  1367. ObservableArray.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  1368. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  1369. var woci = this._callingWatchedObjectChanged ? new OAWatchedObjectChangedInfo() : this._woci;
  1370. woci.object = object;
  1371. woci.propertyChanged = propChanged;
  1372. try {
  1373. this._callingWatchedObjectChanged = true;
  1374. this.watchedObjectChanged.notifyObservers(woci);
  1375. }
  1376. finally {
  1377. this._callingWatchedObjectChanged = false;
  1378. }
  1379. }
  1380. };
  1381. return ObservableArray;
  1382. }(BABYLON.PropertyChangedBase));
  1383. BABYLON.ObservableArray = ObservableArray;
  1384. })(BABYLON || (BABYLON = {}));
  1385. //# sourceMappingURL=babylon.observableArray.js.map
  1386. var __extends = (this && this.__extends) || function (d, b) {
  1387. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1388. function __() { this.constructor = d; }
  1389. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1390. };
  1391. var BABYLON;
  1392. (function (BABYLON) {
  1393. /**
  1394. * Class for the ObservableStringDictionary.onDictionaryChanged observable
  1395. */
  1396. var DictionaryChanged = (function () {
  1397. function DictionaryChanged() {
  1398. }
  1399. Object.defineProperty(DictionaryChanged, "clearAction", {
  1400. /**
  1401. * The content of the dictionary was totally cleared
  1402. */
  1403. get: function () {
  1404. return DictionaryChanged._clearAction;
  1405. },
  1406. enumerable: true,
  1407. configurable: true
  1408. });
  1409. Object.defineProperty(DictionaryChanged, "newItemAction", {
  1410. /**
  1411. * A new item was added, the newItem field contains the key/value pair
  1412. */
  1413. get: function () {
  1414. return DictionaryChanged._newItemAction;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. Object.defineProperty(DictionaryChanged, "removedItemAction", {
  1420. /**
  1421. * An existing item was removed, the removedKey field contains its key
  1422. */
  1423. get: function () {
  1424. return DictionaryChanged._removedItemAction;
  1425. },
  1426. enumerable: true,
  1427. configurable: true
  1428. });
  1429. Object.defineProperty(DictionaryChanged, "itemValueChangedAction", {
  1430. /**
  1431. * An existing item had a value change, the changedItem field contains the key/value
  1432. */
  1433. get: function () {
  1434. return DictionaryChanged._itemValueChangedAction;
  1435. },
  1436. enumerable: true,
  1437. configurable: true
  1438. });
  1439. Object.defineProperty(DictionaryChanged, "replacedAction", {
  1440. /**
  1441. * The dictionary's content was reset and replaced by the content of another dictionary.
  1442. * DictionaryChanged<T> contains no further information about this action
  1443. */
  1444. get: function () {
  1445. return DictionaryChanged._replacedAction;
  1446. },
  1447. enumerable: true,
  1448. configurable: true
  1449. });
  1450. return DictionaryChanged;
  1451. }());
  1452. DictionaryChanged._clearAction = 0x1;
  1453. DictionaryChanged._newItemAction = 0x2;
  1454. DictionaryChanged._removedItemAction = 0x4;
  1455. DictionaryChanged._itemValueChangedAction = 0x8;
  1456. DictionaryChanged._replacedAction = 0x10;
  1457. BABYLON.DictionaryChanged = DictionaryChanged;
  1458. var OSDWatchedObjectChangedInfo = (function () {
  1459. function OSDWatchedObjectChangedInfo() {
  1460. }
  1461. return OSDWatchedObjectChangedInfo;
  1462. }());
  1463. BABYLON.OSDWatchedObjectChangedInfo = OSDWatchedObjectChangedInfo;
  1464. var ObservableStringDictionary = (function (_super) {
  1465. __extends(ObservableStringDictionary, _super);
  1466. function ObservableStringDictionary(watchObjectsPropertyChange) {
  1467. var _this = _super.call(this) || this;
  1468. _this._propertyChanged = null;
  1469. _this._dictionaryChanged = null;
  1470. _this.dci = new DictionaryChanged();
  1471. _this._callingDicChanged = false;
  1472. _this._watchedObjectChanged = null;
  1473. _this._callingWatchedObjectChanged = false;
  1474. _this._woci = new OSDWatchedObjectChangedInfo();
  1475. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  1476. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  1477. return _this;
  1478. }
  1479. /**
  1480. * This will clear this dictionary and copy the content from the 'source' one.
  1481. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  1482. * @param source the dictionary to take the content from and copy to this dictionary
  1483. */
  1484. ObservableStringDictionary.prototype.copyFrom = function (source) {
  1485. var _this = this;
  1486. var oldCount = this.count;
  1487. // Don't rely on this class' implementation for clear/add otherwise tons of notification will be thrown
  1488. _super.prototype.clear.call(this);
  1489. source.forEach(function (t, v) { return _this._add(t, v, false, _this._watchObjectsPropertyChange); });
  1490. this.onDictionaryChanged(DictionaryChanged.replacedAction, null, null, null);
  1491. this.onPropertyChanged("count", oldCount, this.count);
  1492. };
  1493. /**
  1494. * Get a value from its key or add it if it doesn't exist.
  1495. * This method will ensure you that a given key/data will be present in the dictionary.
  1496. * @param key the given key to get the matching value from
  1497. * @param factory the factory that will create the value if the key is not present in the dictionary.
  1498. * The factory will only be invoked if there's no data for the given key.
  1499. * @return the value corresponding to the key.
  1500. */
  1501. ObservableStringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  1502. var _this = this;
  1503. var val = _super.prototype.getOrAddWithFactory.call(this, key, function (k) {
  1504. var v = factory(key);
  1505. _this._add(key, v, true, _this._watchObjectsPropertyChange);
  1506. return v;
  1507. });
  1508. return val;
  1509. };
  1510. /**
  1511. * Add a new key and its corresponding value
  1512. * @param key the key to add
  1513. * @param value the value corresponding to the key
  1514. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  1515. */
  1516. ObservableStringDictionary.prototype.add = function (key, value) {
  1517. return this._add(key, value, true, this._watchObjectsPropertyChange);
  1518. };
  1519. ObservableStringDictionary.prototype.getAndRemove = function (key) {
  1520. var val = _super.prototype.get.call(this, key);
  1521. this._remove(key, true, val);
  1522. return val;
  1523. };
  1524. ObservableStringDictionary.prototype._add = function (key, value, fireNotif, registerWatcher) {
  1525. if (_super.prototype.add.call(this, key, value)) {
  1526. if (fireNotif) {
  1527. this.onDictionaryChanged(DictionaryChanged.newItemAction, { key: key, value: value }, null, null);
  1528. this.onPropertyChanged("count", this.count - 1, this.count);
  1529. }
  1530. if (registerWatcher) {
  1531. this._addWatchedElement(key, value);
  1532. }
  1533. return true;
  1534. }
  1535. return false;
  1536. };
  1537. ObservableStringDictionary.prototype._addWatchedElement = function (key, el) {
  1538. var _this = this;
  1539. if (el["propertyChanged"]) {
  1540. this._watchedObjectList.add(key, el.propertyChanged.add(function (e, d) {
  1541. _this.onWatchedObjectChanged(key, el, e);
  1542. }));
  1543. }
  1544. };
  1545. ObservableStringDictionary.prototype._removeWatchedElement = function (key, el) {
  1546. var observer = this._watchedObjectList.getAndRemove(key);
  1547. if (el["propertyChanged"]) {
  1548. el.propertyChanged.remove(observer);
  1549. }
  1550. };
  1551. ObservableStringDictionary.prototype.set = function (key, value) {
  1552. var oldValue = this.get(key);
  1553. if (this._watchObjectsPropertyChange) {
  1554. this._removeWatchedElement(key, oldValue);
  1555. }
  1556. if (_super.prototype.set.call(this, key, value)) {
  1557. this.onDictionaryChanged(DictionaryChanged.itemValueChangedAction, null, null, { key: key, oldValue: oldValue, newValue: value });
  1558. this._addWatchedElement(key, value);
  1559. return true;
  1560. }
  1561. return false;
  1562. };
  1563. /**
  1564. * Remove a key/value from the dictionary.
  1565. * @param key the key to remove
  1566. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  1567. */
  1568. ObservableStringDictionary.prototype.remove = function (key) {
  1569. return this._remove(key, true);
  1570. };
  1571. ObservableStringDictionary.prototype._remove = function (key, fireNotif, element) {
  1572. if (!element) {
  1573. element = this.get(key);
  1574. }
  1575. if (!element) {
  1576. return false;
  1577. }
  1578. if (_super.prototype.remove.call(this, key) === undefined) {
  1579. return false;
  1580. }
  1581. this.onDictionaryChanged(DictionaryChanged.removedItemAction, null, key, null);
  1582. this.onPropertyChanged("count", this.count + 1, this.count);
  1583. if (this._watchObjectsPropertyChange) {
  1584. this._removeWatchedElement(key, element);
  1585. }
  1586. return true;
  1587. };
  1588. /**
  1589. * Clear the whole content of the dictionary
  1590. */
  1591. ObservableStringDictionary.prototype.clear = function () {
  1592. var _this = this;
  1593. if (this._watchedObjectList) {
  1594. this._watchedObjectList.forEach(function (k, v) {
  1595. var el = _this.get(k);
  1596. _this._removeWatchedElement(k, el);
  1597. });
  1598. this._watchedObjectList.clear();
  1599. }
  1600. var oldCount = this.count;
  1601. _super.prototype.clear.call(this);
  1602. this.onDictionaryChanged(DictionaryChanged.clearAction, null, null, null);
  1603. this.onPropertyChanged("count", oldCount, 0);
  1604. };
  1605. Object.defineProperty(ObservableStringDictionary.prototype, "propertyChanged", {
  1606. get: function () {
  1607. if (!this._propertyChanged) {
  1608. this._propertyChanged = new BABYLON.Observable();
  1609. }
  1610. return this._propertyChanged;
  1611. },
  1612. enumerable: true,
  1613. configurable: true
  1614. });
  1615. ObservableStringDictionary.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  1616. if (this._propertyChanged && this._propertyChanged.hasObservers()) {
  1617. var pci = ObservableStringDictionary.callingPropChanged ? new BABYLON.PropertyChangedInfo() : ObservableStringDictionary.pci;
  1618. pci.oldValue = oldValue;
  1619. pci.newValue = newValue;
  1620. pci.propertyName = propName;
  1621. try {
  1622. ObservableStringDictionary.callingPropChanged = true;
  1623. this.propertyChanged.notifyObservers(pci, mask);
  1624. }
  1625. finally {
  1626. ObservableStringDictionary.callingPropChanged = false;
  1627. }
  1628. }
  1629. };
  1630. Object.defineProperty(ObservableStringDictionary.prototype, "dictionaryChanged", {
  1631. get: function () {
  1632. if (!this._dictionaryChanged) {
  1633. this._dictionaryChanged = new BABYLON.Observable();
  1634. }
  1635. return this._dictionaryChanged;
  1636. },
  1637. enumerable: true,
  1638. configurable: true
  1639. });
  1640. ObservableStringDictionary.prototype.onDictionaryChanged = function (action, newItem, removedKey, changedItem) {
  1641. if (this._dictionaryChanged && this._dictionaryChanged.hasObservers()) {
  1642. var dci = this._callingDicChanged ? new DictionaryChanged() : this.dci;
  1643. dci.action = action;
  1644. dci.newItem = newItem;
  1645. dci.removedKey = removedKey;
  1646. dci.changedItem = changedItem;
  1647. try {
  1648. this._callingDicChanged = true;
  1649. this.dictionaryChanged.notifyObservers(dci, action);
  1650. }
  1651. finally {
  1652. this._callingDicChanged = false;
  1653. }
  1654. }
  1655. };
  1656. Object.defineProperty(ObservableStringDictionary.prototype, "watchedObjectChanged", {
  1657. get: function () {
  1658. if (!this._watchedObjectChanged) {
  1659. this._watchedObjectChanged = new BABYLON.Observable();
  1660. }
  1661. return this._watchedObjectChanged;
  1662. },
  1663. enumerable: true,
  1664. configurable: true
  1665. });
  1666. ObservableStringDictionary.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  1667. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  1668. var woci = this._callingWatchedObjectChanged ? new OSDWatchedObjectChangedInfo() : this._woci;
  1669. woci.key = key;
  1670. woci.object = object;
  1671. woci.propertyChanged = propChanged;
  1672. try {
  1673. this._callingWatchedObjectChanged = true;
  1674. this.watchedObjectChanged.notifyObservers(woci);
  1675. }
  1676. finally {
  1677. this._callingWatchedObjectChanged = false;
  1678. }
  1679. }
  1680. };
  1681. return ObservableStringDictionary;
  1682. }(BABYLON.StringDictionary));
  1683. ObservableStringDictionary.pci = new BABYLON.PropertyChangedInfo();
  1684. ObservableStringDictionary.callingPropChanged = false;
  1685. BABYLON.ObservableStringDictionary = ObservableStringDictionary;
  1686. })(BABYLON || (BABYLON = {}));
  1687. //# sourceMappingURL=babylon.observableStringDictionary.js.map
  1688. var __extends = (this && this.__extends) || function (d, b) {
  1689. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1690. function __() { this.constructor = d; }
  1691. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1692. };
  1693. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  1694. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  1695. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  1696. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  1697. return c > 3 && r && Object.defineProperty(target, key, r), r;
  1698. };
  1699. var BABYLON;
  1700. (function (BABYLON) {
  1701. /**
  1702. * This class given information about a given character.
  1703. */
  1704. var CharInfo = (function () {
  1705. function CharInfo() {
  1706. }
  1707. return CharInfo;
  1708. }());
  1709. BABYLON.CharInfo = CharInfo;
  1710. /**
  1711. * This is an abstract base class to hold a Texture that will contain a FontMap
  1712. */
  1713. var BaseFontTexture = (function (_super) {
  1714. __extends(BaseFontTexture, _super);
  1715. function BaseFontTexture(url, scene, noMipmap, invertY, samplingMode) {
  1716. if (noMipmap === void 0) { noMipmap = false; }
  1717. if (invertY === void 0) { invertY = true; }
  1718. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1719. var _this = _super.call(this, url, scene, noMipmap, invertY, samplingMode) || this;
  1720. _this._cachedFontId = null;
  1721. _this._charInfos = new BABYLON.StringDictionary();
  1722. return _this;
  1723. }
  1724. Object.defineProperty(BaseFontTexture.prototype, "isSuperSampled", {
  1725. /**
  1726. * Is the Font is using Super Sampling (each font texel is doubled).
  1727. */
  1728. get: function () {
  1729. return this._superSample;
  1730. },
  1731. enumerable: true,
  1732. configurable: true
  1733. });
  1734. Object.defineProperty(BaseFontTexture.prototype, "isSignedDistanceField", {
  1735. /**
  1736. * Is the Font was rendered using the Signed Distance Field algorithm
  1737. * @returns {}
  1738. */
  1739. get: function () {
  1740. return this._signedDistanceField;
  1741. },
  1742. enumerable: true,
  1743. configurable: true
  1744. });
  1745. Object.defineProperty(BaseFontTexture.prototype, "spaceWidth", {
  1746. /**
  1747. * Get the Width (in pixel) of the Space character
  1748. */
  1749. get: function () {
  1750. return this._spaceWidth;
  1751. },
  1752. enumerable: true,
  1753. configurable: true
  1754. });
  1755. Object.defineProperty(BaseFontTexture.prototype, "lineHeight", {
  1756. /**
  1757. * Get the Line height (in pixel)
  1758. */
  1759. get: function () {
  1760. return this._lineHeight;
  1761. },
  1762. enumerable: true,
  1763. configurable: true
  1764. });
  1765. /**
  1766. * Measure the width/height that will take a given text
  1767. * @param text the text to measure
  1768. * @param tabulationSize the size (in space character) of the tabulation character, default value must be 4
  1769. */
  1770. BaseFontTexture.prototype.measureText = function (text, tabulationSize) {
  1771. var maxWidth = 0;
  1772. var curWidth = 0;
  1773. var lineCount = 1;
  1774. var charxpos = 0;
  1775. // Parse each char of the string
  1776. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  1777. var char = text_1[_i];
  1778. // Next line feed?
  1779. if (char === "\n") {
  1780. maxWidth = Math.max(maxWidth, curWidth);
  1781. charxpos = 0;
  1782. curWidth = 0;
  1783. ++lineCount;
  1784. continue;
  1785. }
  1786. // Tabulation ?
  1787. if (char === "\t") {
  1788. var nextPos = charxpos + tabulationSize;
  1789. nextPos = nextPos - (nextPos % tabulationSize);
  1790. curWidth += (nextPos - charxpos) * this.spaceWidth;
  1791. charxpos = nextPos;
  1792. continue;
  1793. }
  1794. if (char < " ") {
  1795. continue;
  1796. }
  1797. var ci = this.getChar(char);
  1798. if (!ci) {
  1799. throw new Error("Character " + char + " is not supported by FontTexture " + this.name);
  1800. }
  1801. curWidth += ci.charWidth;
  1802. ++charxpos;
  1803. }
  1804. maxWidth = Math.max(maxWidth, curWidth);
  1805. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  1806. };
  1807. return BaseFontTexture;
  1808. }(BABYLON.Texture));
  1809. BABYLON.BaseFontTexture = BaseFontTexture;
  1810. var BitmapFontInfo = (function () {
  1811. function BitmapFontInfo() {
  1812. this.kerningDic = new BABYLON.StringDictionary();
  1813. this.charDic = new BABYLON.StringDictionary();
  1814. }
  1815. return BitmapFontInfo;
  1816. }());
  1817. BABYLON.BitmapFontInfo = BitmapFontInfo;
  1818. var BitmapFontTexture = (function (_super) {
  1819. __extends(BitmapFontTexture, _super);
  1820. function BitmapFontTexture(scene, bmFontUrl, textureUrl, noMipmap, invertY, samplingMode, onLoad, onError) {
  1821. if (textureUrl === void 0) { textureUrl = null; }
  1822. if (noMipmap === void 0) { noMipmap = false; }
  1823. if (invertY === void 0) { invertY = true; }
  1824. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1825. if (onLoad === void 0) { onLoad = null; }
  1826. if (onError === void 0) { onError = null; }
  1827. var _this = _super.call(this, null, scene, noMipmap, invertY, samplingMode) || this;
  1828. _this._usedCounter = 1;
  1829. var xhr = new XMLHttpRequest();
  1830. xhr.onreadystatechange = function () {
  1831. if (xhr.readyState === XMLHttpRequest.DONE) {
  1832. if (xhr.status === 200) {
  1833. var ext = bmFontUrl.split('.').pop().split(/\#|\?/)[0];
  1834. var plugins = BitmapFontTexture.plugins.get(ext.toLocaleLowerCase());
  1835. if (!plugins) {
  1836. if (onError) {
  1837. onError("couldn't find a plugin for this file extension", -1);
  1838. }
  1839. return;
  1840. }
  1841. var _loop_1 = function (p) {
  1842. var ret = p.loadFont(xhr.response, scene, invertY);
  1843. if (ret) {
  1844. var bfi = ret.bfi;
  1845. if (textureUrl != null) {
  1846. bfi.textureUrl = textureUrl;
  1847. }
  1848. else {
  1849. var baseUrl = bmFontUrl.substr(0, bmFontUrl.lastIndexOf("/") + 1);
  1850. bfi.textureUrl = baseUrl + bfi.textureFile;
  1851. }
  1852. _this._texture = scene.getEngine().createTexture(bfi.textureUrl, noMipmap, invertY, scene, samplingMode, function () {
  1853. if (ret.bfi && onLoad) {
  1854. onLoad();
  1855. }
  1856. });
  1857. _this._lineHeight = bfi.lineHeight;
  1858. _this._charInfos.copyFrom(bfi.charDic);
  1859. var ci = _this.getChar(" ");
  1860. if (ci) {
  1861. _this._spaceWidth = ci.charWidth;
  1862. }
  1863. else {
  1864. _this._charInfos.first(function (k, v) { return _this._spaceWidth = v.charWidth; });
  1865. }
  1866. if (!ret.bfi && onError) {
  1867. onError(ret.errorMsg, ret.errorCode);
  1868. }
  1869. return { value: void 0 };
  1870. }
  1871. };
  1872. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  1873. var p = plugins_1[_i];
  1874. var state_1 = _loop_1(p);
  1875. if (typeof state_1 === "object")
  1876. return state_1.value;
  1877. }
  1878. if (onError) {
  1879. onError("No plugin to load this BMFont file format", -1);
  1880. }
  1881. }
  1882. else {
  1883. if (onError) {
  1884. onError("Couldn't load file through HTTP Request, HTTP Status " + xhr.status, xhr.status);
  1885. }
  1886. }
  1887. }
  1888. };
  1889. xhr.open("GET", bmFontUrl, true);
  1890. xhr.send();
  1891. return _this;
  1892. }
  1893. BitmapFontTexture.GetCachedFontTexture = function (scene, fontTexture) {
  1894. var dic = scene.getOrAddExternalDataWithFactory("BitmapFontTextureCache", function () { return new BABYLON.StringDictionary(); });
  1895. var ft = dic.get(fontTexture.uid);
  1896. if (ft) {
  1897. ++ft._usedCounter;
  1898. return ft;
  1899. }
  1900. dic.add(fontTexture.uid, fontTexture);
  1901. return ft;
  1902. };
  1903. BitmapFontTexture.ReleaseCachedFontTexture = function (scene, fontTexture) {
  1904. var dic = scene.getExternalData("BitmapFontTextureCache");
  1905. if (!dic) {
  1906. return;
  1907. }
  1908. var font = dic.get(fontTexture.uid);
  1909. if (--font._usedCounter === 0) {
  1910. dic.remove(fontTexture.uid);
  1911. font.dispose();
  1912. }
  1913. };
  1914. Object.defineProperty(BitmapFontTexture.prototype, "isDynamicFontTexture", {
  1915. /**
  1916. * Is the font dynamically updated, if true is returned then you have to call the update() before using the font in rendering if new character were adding using getChar()
  1917. */
  1918. get: function () {
  1919. return false;
  1920. },
  1921. enumerable: true,
  1922. configurable: true
  1923. });
  1924. /**
  1925. * This method does nothing for a BitmapFontTexture object as it's a static texture
  1926. */
  1927. BitmapFontTexture.prototype.update = function () {
  1928. };
  1929. /**
  1930. * Retrieve the CharInfo object for a given character
  1931. * @param char the character to retrieve the CharInfo object from (e.g.: "A", "a", etc.)
  1932. */
  1933. BitmapFontTexture.prototype.getChar = function (char) {
  1934. return this._charInfos.get(char);
  1935. };
  1936. /**
  1937. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  1938. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  1939. */
  1940. BitmapFontTexture.prototype.incCachedFontTextureCounter = function () {
  1941. ++this._usedCounter;
  1942. };
  1943. /**
  1944. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  1945. */
  1946. BitmapFontTexture.prototype.decCachedFontTextureCounter = function () {
  1947. var dic = this.getScene().getExternalData("BitmapFontTextureCache");
  1948. if (!dic) {
  1949. return;
  1950. }
  1951. if (--this._usedCounter === 0) {
  1952. dic.remove(this._cachedFontId);
  1953. this.dispose();
  1954. }
  1955. };
  1956. BitmapFontTexture.addLoader = function (fileExtension, plugin) {
  1957. var a = BitmapFontTexture.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  1958. a.push(plugin);
  1959. };
  1960. return BitmapFontTexture;
  1961. }(BaseFontTexture));
  1962. BitmapFontTexture.plugins = new BABYLON.StringDictionary();
  1963. BABYLON.BitmapFontTexture = BitmapFontTexture;
  1964. /**
  1965. * This class is a special kind of texture which generates on the fly characters of a given css style "fontName".
  1966. * The generated texture will be updated when new characters will be retrieved using the getChar() method, but you have
  1967. * to call the update() method for the texture to fetch these changes, you can harmlessly call update any time you want, if no
  1968. * change were made, nothing will happen.
  1969. * The Font Texture can be rendered in three modes: normal size, super sampled size (x2) or using Signed Distance Field rendering.
  1970. * Signed Distance Field should be prefered because the texture can be rendered using AlphaTest instead of Transparency, which is way more faster. More about SDF here (http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf).
  1971. * The only flaw of SDF is that the rendering quality may not be the best or the edges too sharp is the font thickness is too thin.
  1972. */
  1973. var FontTexture = (function (_super) {
  1974. __extends(FontTexture, _super);
  1975. /**
  1976. * Create a new instance of the FontTexture class
  1977. * @param name the name of the texture
  1978. * @param font the font to use, use the W3C CSS notation
  1979. * @param scene the scene that owns the texture
  1980. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  1981. * @param samplingMode the texture sampling mode
  1982. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  1983. */
  1984. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  1985. if (maxCharCount === void 0) { maxCharCount = 200; }
  1986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1987. if (superSample === void 0) { superSample = false; }
  1988. if (signedDistanceField === void 0) { signedDistanceField = false; }
  1989. var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
  1990. _this._curCharCount = 0;
  1991. _this._lastUpdateCharCount = -1;
  1992. _this._usedCounter = 1;
  1993. _this.name = name;
  1994. _this.debugMode = false;
  1995. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  1996. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  1997. _this._sdfScale = 8;
  1998. _this._signedDistanceField = signedDistanceField;
  1999. _this._superSample = false;
  2000. // SDF will use super sample no matter what, the resolution is otherwise too poor to produce correct result
  2001. if (superSample || signedDistanceField) {
  2002. var sfont = _this.getSuperSampleFont(font);
  2003. if (sfont) {
  2004. _this._superSample = true;
  2005. font = sfont;
  2006. }
  2007. }
  2008. // First canvas creation to determine the size of the texture to create
  2009. _this._canvas = document.createElement("canvas");
  2010. _this._context = _this._canvas.getContext("2d");
  2011. _this._context.font = font;
  2012. _this._context.fillStyle = "white";
  2013. _this._context.textBaseline = "top";
  2014. var res = _this.getFontHeight(font, "j$|");
  2015. _this._lineHeightSuper = res.height; //+4;
  2016. _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
  2017. _this._offset = res.offset;
  2018. res = _this.getFontHeight(font, "f");
  2019. _this._baseLine = res.height + res.offset - _this._offset;
  2020. var maxCharWidth = Math.max(_this._context.measureText("W").width, _this._context.measureText("_").width);
  2021. _this._spaceWidthSuper = _this._context.measureText(" ").width;
  2022. _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
  2023. _this._xMargin = Math.ceil(maxCharWidth / 32);
  2024. _this._yMargin = _this._xMargin;
  2025. // This is an approximate size, but should always be able to fit at least the maxCharCount
  2026. var totalEstSurface = (Math.ceil(_this._lineHeightSuper) + (_this._yMargin * 2)) * (Math.ceil(maxCharWidth) + (_this._xMargin * 2)) * maxCharCount;
  2027. var edge = Math.sqrt(totalEstSurface);
  2028. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  2029. // Create the texture that will store the font characters
  2030. _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  2031. var textureSize = _this.getSize();
  2032. _this.hasAlpha = _this._signedDistanceField === false;
  2033. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  2034. _this._canvas = document.createElement("canvas");
  2035. _this._canvas.width = textureSize.width;
  2036. _this._canvas.height = textureSize.height;
  2037. _this._context = _this._canvas.getContext("2d");
  2038. _this._context.textBaseline = "top";
  2039. _this._context.font = font;
  2040. _this._context.fillStyle = "white";
  2041. _this._context.imageSmoothingEnabled = false;
  2042. _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  2043. // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
  2044. // into this 2D context, then get the bitmap data, create the SDF char and push the result in the _context (which hold the whole Font Texture content)
  2045. // So you can see this context as an intermediate one, because it is.
  2046. if (_this._signedDistanceField) {
  2047. var sdfC = document.createElement("canvas");
  2048. var s = _this._sdfScale;
  2049. sdfC.width = (Math.ceil(maxCharWidth) + _this._xMargin * 2) * s;
  2050. sdfC.height = (Math.ceil(_this._lineHeightSuper) + _this._yMargin * 2) * s;
  2051. var sdfCtx = sdfC.getContext("2d");
  2052. sdfCtx.scale(s, s);
  2053. sdfCtx.textBaseline = "top";
  2054. sdfCtx.font = font;
  2055. sdfCtx.fillStyle = "white";
  2056. sdfCtx.imageSmoothingEnabled = false;
  2057. _this._sdfCanvas = sdfC;
  2058. _this._sdfContext = sdfCtx;
  2059. }
  2060. _this._currentFreePosition = BABYLON.Vector2.Zero();
  2061. // Add the basic ASCII based characters
  2062. for (var i = 0x20; i < 0x7F; i++) {
  2063. var c = String.fromCharCode(i);
  2064. _this.getChar(c);
  2065. }
  2066. _this.update();
  2067. return _this;
  2068. //this._saveToImage("");
  2069. }
  2070. Object.defineProperty(FontTexture.prototype, "isDynamicFontTexture", {
  2071. get: function () {
  2072. return true;
  2073. },
  2074. enumerable: true,
  2075. configurable: true
  2076. });
  2077. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  2078. if (supersample === void 0) { supersample = false; }
  2079. if (signedDistanceField === void 0) { signedDistanceField = false; }
  2080. var dic = scene.getOrAddExternalDataWithFactory("FontTextureCache", function () { return new BABYLON.StringDictionary(); });
  2081. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  2082. var ft = dic.get(lfn);
  2083. if (ft) {
  2084. ++ft._usedCounter;
  2085. return ft;
  2086. }
  2087. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  2088. ft._cachedFontId = lfn;
  2089. dic.add(lfn, ft);
  2090. return ft;
  2091. };
  2092. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  2093. if (supersample === void 0) { supersample = false; }
  2094. if (signedDistanceField === void 0) { signedDistanceField = false; }
  2095. var dic = scene.getExternalData("FontTextureCache");
  2096. if (!dic) {
  2097. return;
  2098. }
  2099. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  2100. var font = dic.get(lfn);
  2101. if (--font._usedCounter === 0) {
  2102. dic.remove(lfn);
  2103. font.dispose();
  2104. }
  2105. };
  2106. FontTexture.prototype._saveToImage = function (url) {
  2107. var base64Image = this._canvas.toDataURL("image/png");
  2108. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2109. if (("download" in document.createElement("a"))) {
  2110. var a = window.document.createElement("a");
  2111. a.href = base64Image;
  2112. var date = new Date();
  2113. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) +
  2114. "-" +
  2115. date.getDate() +
  2116. "_" +
  2117. date.getHours() +
  2118. "-" +
  2119. ('0' + date.getMinutes()).slice(-2);
  2120. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  2121. window.document.body.appendChild(a);
  2122. a.addEventListener("click", function () {
  2123. a.parentElement.removeChild(a);
  2124. });
  2125. a.click();
  2126. }
  2127. else {
  2128. var newWindow = window.open("");
  2129. var img = newWindow.document.createElement("img");
  2130. img.src = base64Image;
  2131. newWindow.document.body.appendChild(img);
  2132. }
  2133. };
  2134. /**
  2135. * Make sure the given char is present in the font map.
  2136. * @param char the character to get or add
  2137. * @return the CharInfo instance corresponding to the given character
  2138. */
  2139. FontTexture.prototype.getChar = function (char) {
  2140. var _this = this;
  2141. if (char.length !== 1) {
  2142. return null;
  2143. }
  2144. var info = this._charInfos.get(char);
  2145. if (info) {
  2146. return info;
  2147. }
  2148. info = new CharInfo();
  2149. var measure = this._context.measureText(char);
  2150. var textureSize = this.getSize();
  2151. // we reached the end of the current line?
  2152. var width = Math.ceil(measure.width);
  2153. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  2154. this._currentFreePosition.x = 0;
  2155. this._currentFreePosition.y += Math.ceil(this._lineHeightSuper + this._yMargin * 2);
  2156. // No more room?
  2157. if (this._currentFreePosition.y > textureSize.height) {
  2158. return this.getChar("!");
  2159. }
  2160. }
  2161. var curPosX = this._currentFreePosition.x + 0.5;
  2162. var curPosY = this._currentFreePosition.y + 0.5;
  2163. var curPosXMargin = curPosX + this._xMargin;
  2164. var curPosYMargin = curPosY + this._yMargin;
  2165. var drawDebug = function (ctx) {
  2166. ctx.strokeStyle = "green";
  2167. ctx.beginPath();
  2168. ctx.rect(curPosXMargin, curPosYMargin, width, _this._lineHeightSuper);
  2169. ctx.closePath();
  2170. ctx.stroke();
  2171. ctx.strokeStyle = "blue";
  2172. ctx.beginPath();
  2173. ctx.moveTo(curPosXMargin, curPosYMargin + Math.round(_this._baseLine));
  2174. ctx.lineTo(curPosXMargin + width, curPosYMargin + Math.round(_this._baseLine));
  2175. ctx.closePath();
  2176. ctx.stroke();
  2177. };
  2178. // In SDF mode we render the character in an intermediate 2D context which scale the character this._sdfScale times (which is required to compute the SDF map accurately)
  2179. if (this._signedDistanceField) {
  2180. var s = this._sdfScale;
  2181. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  2182. // Coordinates are subject to the context's scale
  2183. this._sdfContext.fillText(char, this._xMargin + 0.5, this._yMargin + 0.5 - this._offset);
  2184. // Canvas Pixel Coordinates, no scale
  2185. var data = this._sdfContext.getImageData(0, 0, (width + (this._xMargin * 2)) * s, this._sdfCanvas.height);
  2186. var res = this._computeSDFChar(data);
  2187. this._context.putImageData(res, curPosX, curPosY);
  2188. if (this.debugMode) {
  2189. drawDebug(this._context);
  2190. }
  2191. }
  2192. else {
  2193. if (this.debugMode) {
  2194. drawDebug(this._context);
  2195. }
  2196. // Draw the character in the HTML canvas
  2197. this._context.fillText(char, curPosXMargin, curPosYMargin - this._offset);
  2198. // Premul Alpha manually
  2199. var id = this._context.getImageData(curPosXMargin, curPosYMargin, width, this._lineHeightSuper);
  2200. for (var i = 0; i < id.data.length; i += 4) {
  2201. var v = id.data[i + 3];
  2202. if (v > 0 && v < 255) {
  2203. id.data[i + 0] = v;
  2204. id.data[i + 1] = v;
  2205. id.data[i + 2] = v;
  2206. id.data[i + 3] = v;
  2207. }
  2208. }
  2209. this._context.putImageData(id, curPosXMargin, curPosYMargin);
  2210. }
  2211. // Fill the CharInfo object
  2212. info.topLeftUV = new BABYLON.Vector2((curPosXMargin) / textureSize.width, (this._currentFreePosition.y + this._yMargin) / textureSize.height);
  2213. info.bottomRightUV = new BABYLON.Vector2((curPosXMargin + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + this._yMargin) / textureSize.height));
  2214. info.yOffset = info.xOffset = 0;
  2215. if (this._signedDistanceField) {
  2216. var off = 1 / textureSize.width;
  2217. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  2218. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  2219. }
  2220. info.charWidth = this._superSample ? (width / 2) : width;
  2221. info.xAdvance = info.charWidth;
  2222. // Add the info structure
  2223. this._charInfos.add(char, info);
  2224. this._curCharCount++;
  2225. // Set the next position
  2226. this._currentFreePosition.x += Math.ceil(width + this._xMargin * 2);
  2227. return info;
  2228. };
  2229. FontTexture.prototype._computeSDFChar = function (source) {
  2230. var scl = this._sdfScale;
  2231. var sw = source.width;
  2232. var sh = source.height;
  2233. var dw = sw / scl;
  2234. var dh = sh / scl;
  2235. var roffx = 0;
  2236. var roffy = 0;
  2237. // We shouldn't look beyond half of the biggest between width and height
  2238. var radius = scl;
  2239. var br = radius - 1;
  2240. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  2241. var sx = dx * scl;
  2242. var sy = dy * scl;
  2243. // Looking out of the area? return true to make the test going on
  2244. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  2245. return true;
  2246. }
  2247. // Get the pixel we want
  2248. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  2249. var res = (val > 0) === lookVis;
  2250. if (!res) {
  2251. roffx = offX;
  2252. roffy = offY;
  2253. }
  2254. return res;
  2255. };
  2256. var lookupArea = function (dx, dy, lookVis) {
  2257. // Fast rejection test, if we have the same result in N, S, W, E at a distance which is the radius-1 then it means the data will be consistent in this area. That's because we've scale the rendering of the letter "radius" times, so a letter's pixel will be at least radius wide
  2258. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  2259. lookupSrc(dx, dy, 0, -br, lookVis) &&
  2260. lookupSrc(dx, dy, -br, 0, lookVis) &&
  2261. lookupSrc(dx, dy, br, 0, lookVis)) {
  2262. return 0;
  2263. }
  2264. for (var i = 1; i <= radius; i++) {
  2265. // Quick test N, S, W, E
  2266. if (!lookupSrc(dx, dy, 0, i, lookVis) || !lookupSrc(dx, dy, 0, -i, lookVis) || !lookupSrc(dx, dy, -i, 0, lookVis) || !lookupSrc(dx, dy, i, 0, lookVis)) {
  2267. return i * i; // Squared Distance is simple to compute in this case
  2268. }
  2269. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  2270. for (var j = 1; j <= i; j++) {
  2271. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  2272. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  2273. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  2274. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  2275. // We found the nearest texel having and opposite state, store the squared length
  2276. var res_1 = (i * i) + (j * j);
  2277. var count = 1;
  2278. // To improve quality we will sample the texels around this one, so it's 8 samples, we consider only the one having an opposite state, add them to the current res and will will compute the average at the end
  2279. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  2280. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  2281. ++count;
  2282. }
  2283. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  2284. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  2285. ++count;
  2286. }
  2287. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  2288. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  2289. ++count;
  2290. }
  2291. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  2292. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  2293. ++count;
  2294. }
  2295. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  2296. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  2297. ++count;
  2298. }
  2299. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  2300. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  2301. ++count;
  2302. }
  2303. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  2304. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  2305. ++count;
  2306. }
  2307. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  2308. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  2309. ++count;
  2310. }
  2311. // Compute the average based on the accumulated distance
  2312. return res_1 / count;
  2313. }
  2314. }
  2315. }
  2316. return 0;
  2317. };
  2318. var tmp = new Array(dw * dh);
  2319. for (var y = 0; y < dh; y++) {
  2320. for (var x = 0; x < dw; x++) {
  2321. var curState = lookupSrc(x, y, 0, 0, true);
  2322. var d = lookupArea(x, y, curState);
  2323. if (d === 0) {
  2324. d = radius * radius * 2;
  2325. }
  2326. tmp[(y * dw) + x] = curState ? d : -d;
  2327. }
  2328. }
  2329. var res = this._context.createImageData(dw, dh);
  2330. var size = dw * dh;
  2331. for (var j = 0; j < size; j++) {
  2332. var d = tmp[j];
  2333. var sign = (d < 0) ? -1 : 1;
  2334. d = Math.sqrt(Math.abs(d)) * sign;
  2335. d *= 127.5 / radius;
  2336. d += 127.5;
  2337. if (d < 0) {
  2338. d = 0;
  2339. }
  2340. else if (d > 255) {
  2341. d = 255;
  2342. }
  2343. d += 0.5;
  2344. res.data[j * 4 + 0] = d;
  2345. res.data[j * 4 + 1] = d;
  2346. res.data[j * 4 + 2] = d;
  2347. res.data[j * 4 + 3] = 255;
  2348. }
  2349. return res;
  2350. };
  2351. FontTexture.prototype.getSuperSampleFont = function (font) {
  2352. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  2353. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  2354. var res = font.toLocaleLowerCase().match(regex);
  2355. if (res == null) {
  2356. return null;
  2357. }
  2358. var size = parseInt(res[4]);
  2359. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  2360. var newFont = "";
  2361. for (var j = 1; j < res.length; j++) {
  2362. if (res[j] != null) {
  2363. newFont += res[j] + " ";
  2364. }
  2365. }
  2366. return newFont;
  2367. };
  2368. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  2369. FontTexture.prototype.getFontHeight = function (font, chars) {
  2370. var fontDraw = document.createElement("canvas");
  2371. fontDraw.width = 600;
  2372. fontDraw.height = 600;
  2373. var ctx = fontDraw.getContext('2d');
  2374. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  2375. ctx.textBaseline = 'top';
  2376. ctx.fillStyle = 'white';
  2377. ctx.font = font;
  2378. ctx.fillText(chars, 0, 0);
  2379. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  2380. var start = -1;
  2381. var end = -1;
  2382. for (var row = 0; row < fontDraw.height; row++) {
  2383. for (var column = 0; column < fontDraw.width; column++) {
  2384. var index = (row * fontDraw.width + column) * 4;
  2385. var pix = pixels[index];
  2386. if (pix === 0) {
  2387. if (column === fontDraw.width - 1 && start !== -1) {
  2388. end = row;
  2389. row = fontDraw.height;
  2390. break;
  2391. }
  2392. continue;
  2393. }
  2394. else {
  2395. if (start === -1) {
  2396. start = row;
  2397. }
  2398. break;
  2399. }
  2400. }
  2401. }
  2402. return { height: (end - start) + 1, offset: start };
  2403. };
  2404. Object.defineProperty(FontTexture.prototype, "canRescale", {
  2405. get: function () {
  2406. return false;
  2407. },
  2408. enumerable: true,
  2409. configurable: true
  2410. });
  2411. FontTexture.prototype.getContext = function () {
  2412. return this._context;
  2413. };
  2414. /**
  2415. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  2416. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  2417. */
  2418. FontTexture.prototype.update = function () {
  2419. // Update only if there's new char added since the previous update
  2420. if (this._lastUpdateCharCount < this._curCharCount) {
  2421. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  2422. this._lastUpdateCharCount = this._curCharCount;
  2423. }
  2424. };
  2425. // cloning should be prohibited, there's no point to duplicate this texture at all
  2426. FontTexture.prototype.clone = function () {
  2427. return null;
  2428. };
  2429. /**
  2430. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  2431. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  2432. */
  2433. FontTexture.prototype.incCachedFontTextureCounter = function () {
  2434. ++this._usedCounter;
  2435. };
  2436. /**
  2437. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  2438. */
  2439. FontTexture.prototype.decCachedFontTextureCounter = function () {
  2440. var dic = this.getScene().getExternalData("FontTextureCache");
  2441. if (!dic) {
  2442. return;
  2443. }
  2444. if (--this._usedCounter === 0) {
  2445. dic.remove(this._cachedFontId);
  2446. this.dispose();
  2447. }
  2448. };
  2449. return FontTexture;
  2450. }(BaseFontTexture));
  2451. BABYLON.FontTexture = FontTexture;
  2452. /**
  2453. * Orginial code from cocos2d-js, converted to TypeScript by Nockawa
  2454. * Load the Text version of the BMFont format, no XML or binary supported, just plain old text
  2455. */
  2456. var BMFontLoaderTxt = BMFontLoaderTxt_1 = (function () {
  2457. function BMFontLoaderTxt() {
  2458. }
  2459. BMFontLoaderTxt.prototype._parseStrToObj = function (str) {
  2460. var arr = str.match(BMFontLoaderTxt_1.ITEM_EXP);
  2461. if (!arr) {
  2462. return null;
  2463. }
  2464. var obj = {};
  2465. for (var i = 0, li = arr.length; i < li; i++) {
  2466. var tempStr = arr[i];
  2467. var index = tempStr.indexOf("=");
  2468. var key = tempStr.substring(0, index);
  2469. var value = tempStr.substring(index + 1);
  2470. if (value.match(BMFontLoaderTxt_1.INT_EXP))
  2471. value = parseInt(value);
  2472. else if (value[0] === '"')
  2473. value = value.substring(1, value.length - 1);
  2474. obj[key] = value;
  2475. }
  2476. return obj;
  2477. };
  2478. BMFontLoaderTxt.prototype._buildCharInfo = function (bfi, initialLine, obj, textureSize, invertY, chars) {
  2479. var char = null;
  2480. var x = null;
  2481. var y = null;
  2482. var width = null;
  2483. var height = null;
  2484. var xoffset = 0;
  2485. var yoffset = 0;
  2486. var xadvance = 0;
  2487. var ci = new CharInfo();
  2488. for (var key in obj) {
  2489. var value = obj[key];
  2490. switch (key) {
  2491. case "id":
  2492. char = String.fromCharCode(value);
  2493. break;
  2494. case "x":
  2495. x = value;
  2496. break;
  2497. case "y":
  2498. y = value;
  2499. break;
  2500. case "width":
  2501. width = value;
  2502. break;
  2503. case "height":
  2504. height = value;
  2505. break;
  2506. case "xadvance":
  2507. xadvance = value;
  2508. break;
  2509. case "xoffset":
  2510. xoffset = value;
  2511. break;
  2512. case "yoffset":
  2513. yoffset = value;
  2514. break;
  2515. }
  2516. }
  2517. if (x != null && y != null && width != null && height != null && char != null) {
  2518. ci.xAdvance = xadvance;
  2519. ci.xOffset = xoffset;
  2520. ci.yOffset = bfi.lineHeight - height - yoffset;
  2521. if (invertY) {
  2522. ci.topLeftUV = new BABYLON.Vector2(1 - (x / textureSize.width), 1 - (y / textureSize.height));
  2523. ci.bottomRightUV = new BABYLON.Vector2(1 - ((x + width) / textureSize.width), 1 - ((y + height) / textureSize.height));
  2524. }
  2525. else {
  2526. ci.topLeftUV = new BABYLON.Vector2(x / textureSize.width, y / textureSize.height);
  2527. ci.bottomRightUV = new BABYLON.Vector2((x + width) / textureSize.width, (y + height) / textureSize.height);
  2528. }
  2529. ci.charWidth = width;
  2530. chars.add(char, ci);
  2531. }
  2532. else {
  2533. console.log("Error while parsing line " + initialLine);
  2534. }
  2535. };
  2536. BMFontLoaderTxt.prototype.loadFont = function (fontContent, scene, invertY) {
  2537. var fontStr = fontContent;
  2538. var bfi = new BitmapFontInfo();
  2539. var errorCode = 0;
  2540. var errorMsg = "OK";
  2541. //padding
  2542. var info = fontStr.match(BMFontLoaderTxt_1.INFO_EXP);
  2543. var infoObj = this._parseStrToObj(info[0]);
  2544. if (!infoObj) {
  2545. return null;
  2546. }
  2547. var paddingArr = infoObj["padding"].split(",");
  2548. bfi.padding = new BABYLON.Vector4(parseInt(paddingArr[0]), parseInt(paddingArr[1]), parseInt(paddingArr[2]), parseInt(paddingArr[3]));
  2549. //common
  2550. var commonObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.COMMON_EXP)[0]);
  2551. bfi.lineHeight = commonObj["lineHeight"];
  2552. bfi.baseLine = commonObj["base"];
  2553. bfi.textureSize = new BABYLON.Size(commonObj["scaleW"], commonObj["scaleH"]);
  2554. var maxTextureSize = scene.getEngine()._gl.getParameter(0xd33);
  2555. if (commonObj["scaleW"] > maxTextureSize.width || commonObj["scaleH"] > maxTextureSize.height) {
  2556. errorMsg = "FontMap texture's size is bigger than what WebGL supports";
  2557. errorCode = -1;
  2558. }
  2559. else {
  2560. if (commonObj["pages"] !== 1) {
  2561. errorMsg = "FontMap must contain one page only.";
  2562. errorCode = -1;
  2563. }
  2564. else {
  2565. //page
  2566. var pageObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.PAGE_EXP)[0]);
  2567. if (pageObj["id"] !== 0) {
  2568. errorMsg = "Only one page of ID 0 is supported";
  2569. errorCode = -1;
  2570. }
  2571. else {
  2572. bfi.textureFile = pageObj["file"];
  2573. //char
  2574. var charLines = fontStr.match(BMFontLoaderTxt_1.CHAR_EXP);
  2575. for (var i = 0, li = charLines.length; i < li; i++) {
  2576. var charObj = this._parseStrToObj(charLines[i]);
  2577. this._buildCharInfo(bfi, charLines[i], charObj, bfi.textureSize, invertY, bfi.charDic);
  2578. }
  2579. //kerning
  2580. var kerningLines = fontStr.match(BMFontLoaderTxt_1.KERNING_EXP);
  2581. if (kerningLines) {
  2582. for (var i = 0, li = kerningLines.length; i < li; i++) {
  2583. var kerningObj = this._parseStrToObj(kerningLines[i]);
  2584. bfi.kerningDic.add(((kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)).toString(), kerningObj["amount"]);
  2585. }
  2586. }
  2587. }
  2588. }
  2589. }
  2590. return { bfi: bfi, errorCode: errorCode, errorMsg: errorMsg };
  2591. };
  2592. return BMFontLoaderTxt;
  2593. }());
  2594. BMFontLoaderTxt.INFO_EXP = /info [^\r\n]*(\r\n|$)/gi;
  2595. BMFontLoaderTxt.COMMON_EXP = /common [^\n]*(\n|$)/gi;
  2596. BMFontLoaderTxt.PAGE_EXP = /page [^\n]*(\n|$)/gi;
  2597. BMFontLoaderTxt.CHAR_EXP = /char [^\n]*(\n|$)/gi;
  2598. BMFontLoaderTxt.KERNING_EXP = /kerning [^\n]*(\n|$)/gi;
  2599. BMFontLoaderTxt.ITEM_EXP = /\w+=[^ \r\n]+/gi;
  2600. BMFontLoaderTxt.INT_EXP = /^[\-]?\d+$/;
  2601. BMFontLoaderTxt = BMFontLoaderTxt_1 = __decorate([
  2602. BitmapFontLoaderPlugin("fnt", new BMFontLoaderTxt_1())
  2603. ], BMFontLoaderTxt);
  2604. ;
  2605. function BitmapFontLoaderPlugin(fileExtension, plugin) {
  2606. return function () {
  2607. BitmapFontTexture.addLoader(fileExtension, plugin);
  2608. };
  2609. }
  2610. BABYLON.BitmapFontLoaderPlugin = BitmapFontLoaderPlugin;
  2611. var BMFontLoaderTxt_1;
  2612. })(BABYLON || (BABYLON = {}));
  2613. //# sourceMappingURL=babylon.fontTexture.js.map
  2614. var BABYLON;
  2615. (function (BABYLON) {
  2616. /**
  2617. * Stores 2D Bounding Information.
  2618. * This class handles a circle area and a bounding rectangle one.
  2619. */
  2620. var BoundingInfo2D = (function () {
  2621. function BoundingInfo2D() {
  2622. this.radius = 0;
  2623. this.center = BABYLON.Vector2.Zero();
  2624. this.extent = BABYLON.Vector2.Zero();
  2625. this._worldAABBDirty = false;
  2626. this._worldAABBDirtyObservable = null;
  2627. this._worldAABB = BABYLON.Vector4.Zero();
  2628. }
  2629. /**
  2630. * Create a BoundingInfo2D object from a given size
  2631. * @param size the size that will be used to set the extend, radius will be computed from it.
  2632. */
  2633. BoundingInfo2D.CreateFromSize = function (size) {
  2634. var r = new BoundingInfo2D();
  2635. BoundingInfo2D.CreateFromSizeToRef(size, r);
  2636. return r;
  2637. };
  2638. /**
  2639. * Create a BoundingInfo2D object from a given radius
  2640. * @param radius the radius to use, the extent will be computed from it.
  2641. */
  2642. BoundingInfo2D.CreateFromRadius = function (radius) {
  2643. var r = new BoundingInfo2D();
  2644. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  2645. return r;
  2646. };
  2647. /**
  2648. * Create a BoundingInfo2D object from a list of points.
  2649. * The resulted object will be the smallest bounding area that includes all the given points.
  2650. * @param points an array of points to compute the bounding object from.
  2651. */
  2652. BoundingInfo2D.CreateFromPoints = function (points) {
  2653. var r = new BoundingInfo2D();
  2654. BoundingInfo2D.CreateFromPointsToRef(points, r);
  2655. return r;
  2656. };
  2657. /**
  2658. * Update a BoundingInfo2D object using the given Size as input
  2659. * @param size the bounding data will be computed from this size.
  2660. * @param b must be a valid/allocated object, it will contain the result of the operation
  2661. */
  2662. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  2663. if (!size) {
  2664. size = BABYLON.Size.Zero();
  2665. }
  2666. b.center.x = +size.width / 2;
  2667. b.center.y = +size.height / 2;
  2668. b.extent.x = b.center.x;
  2669. b.extent.y = b.center.y;
  2670. b.radius = b.extent.length();
  2671. b._worldAABBDirty = true;
  2672. };
  2673. /**
  2674. * Update a BoundingInfo2D object using the given radius as input
  2675. * @param radius the bounding data will be computed from this radius
  2676. * @param b must be a valid/allocated object, it will contain the result of the operation
  2677. */
  2678. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  2679. b.center.x = b.center.y = 0;
  2680. var r = +radius;
  2681. b.extent.x = r;
  2682. b.extent.y = r;
  2683. b.radius = r;
  2684. b._worldAABBDirty = true;
  2685. };
  2686. /**
  2687. * Update a BoundingInfo2D object using the given points array as input
  2688. * @param points the point array to use to update the bounding data
  2689. * @param b must be a valid/allocated object, it will contain the result of the operation
  2690. */
  2691. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  2692. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  2693. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  2694. var p = points_1[_i];
  2695. xmin = Math.min(p.x, xmin);
  2696. xmax = Math.max(p.x, xmax);
  2697. ymin = Math.min(p.y, ymin);
  2698. ymax = Math.max(p.y, ymax);
  2699. }
  2700. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  2701. };
  2702. /**
  2703. * Update a BoundingInfo2D object using the given min/max values as input
  2704. * @param xmin the smallest x coordinate
  2705. * @param xmax the biggest x coordinate
  2706. * @param ymin the smallest y coordinate
  2707. * @param ymax the buggest y coordinate
  2708. * @param b must be a valid/allocated object, it will contain the result of the operation
  2709. */
  2710. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  2711. var w = xmax - xmin;
  2712. var h = ymax - ymin;
  2713. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  2714. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  2715. b.radius = b.extent.length();
  2716. b._worldAABBDirty = true;
  2717. };
  2718. /**
  2719. * Duplicate this instance and return a new one
  2720. * @return the duplicated instance
  2721. */
  2722. BoundingInfo2D.prototype.clone = function () {
  2723. var r = new BoundingInfo2D();
  2724. r.center = this.center.clone();
  2725. r.radius = this.radius;
  2726. r.extent = this.extent.clone();
  2727. return r;
  2728. };
  2729. BoundingInfo2D.prototype.clear = function () {
  2730. this.center.copyFromFloats(0, 0);
  2731. this.radius = 0;
  2732. this.extent.copyFromFloats(0, 0);
  2733. this._worldAABBDirty = true;
  2734. };
  2735. BoundingInfo2D.prototype.copyFrom = function (src) {
  2736. this.center.copyFrom(src.center);
  2737. this.radius = src.radius;
  2738. this.extent.copyFrom(src.extent);
  2739. this._worldAABBDirty = true;
  2740. };
  2741. BoundingInfo2D.prototype.equals = function (other) {
  2742. if (!other) {
  2743. return false;
  2744. }
  2745. return other.center.equals(this.center) && other.extent.equals(this.extent);
  2746. };
  2747. /**
  2748. * return the max extend of the bounding info
  2749. */
  2750. BoundingInfo2D.prototype.max = function () {
  2751. var r = BABYLON.Vector2.Zero();
  2752. this.maxToRef(r);
  2753. return r;
  2754. };
  2755. /**
  2756. * return the min/max extend of the bounding info.
  2757. * x, y, z, w are left, bottom, right and top
  2758. */
  2759. BoundingInfo2D.prototype.minMax = function () {
  2760. var r = BABYLON.Vector4.Zero();
  2761. this.minMaxToRef(r);
  2762. return r;
  2763. };
  2764. /**
  2765. * Update a vector2 with the max extend of the bounding info
  2766. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  2767. */
  2768. BoundingInfo2D.prototype.maxToRef = function (result) {
  2769. result.x = this.center.x + this.extent.x;
  2770. result.y = this.center.y + this.extent.y;
  2771. };
  2772. /**
  2773. * Update a vector4 with the min/max extend of the bounding info
  2774. * x, y, z, w are left, bottom, right and top
  2775. * @param result must be a valid/allocated vector4 that will contain the result of the operation
  2776. */
  2777. BoundingInfo2D.prototype.minMaxToRef = function (result) {
  2778. result.x = this.center.x - this.extent.x;
  2779. result.y = this.center.y - this.extent.y;
  2780. result.z = this.center.x + this.extent.x;
  2781. result.w = this.center.y + this.extent.y;
  2782. };
  2783. /**
  2784. * Return the size of the boundingInfo rect surface
  2785. */
  2786. BoundingInfo2D.prototype.size = function () {
  2787. var r = BABYLON.Size.Zero();
  2788. this.sizeToRef(r);
  2789. return r;
  2790. };
  2791. /**
  2792. * Stores in the result object the size of the boundingInfo rect surface
  2793. * @param result
  2794. */
  2795. BoundingInfo2D.prototype.sizeToRef = function (result) {
  2796. result.width = this.extent.x * 2;
  2797. result.height = this.extent.y * 2;
  2798. };
  2799. /**
  2800. * Inflate the boundingInfo with the given vector
  2801. * @param offset the extent will be incremented with offset and the radius will be computed again
  2802. */
  2803. BoundingInfo2D.prototype.inflate = function (offset) {
  2804. this.extent.addInPlace(offset);
  2805. this.radius = this.extent.length();
  2806. };
  2807. /**
  2808. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  2809. * @param matrix the transformation matrix to apply
  2810. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  2811. */
  2812. BoundingInfo2D.prototype.transform = function (matrix) {
  2813. var r = new BoundingInfo2D();
  2814. this.transformToRef(matrix, r);
  2815. return r;
  2816. };
  2817. /**
  2818. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  2819. * @param other the second BoundingInfo2D to compute the union with this one
  2820. * @return a new instance containing the result of the union
  2821. */
  2822. BoundingInfo2D.prototype.union = function (other) {
  2823. var r = new BoundingInfo2D();
  2824. this.unionToRef(other, r);
  2825. return r;
  2826. };
  2827. BoundingInfo2D.prototype.worldAABBIntersectionTest = function (other) {
  2828. var a = this.worldAABB;
  2829. var b = other.worldAABB;
  2830. return b.z >= a.x && b.x <= a.z && b.w >= a.y && b.y <= a.w;
  2831. };
  2832. /**
  2833. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  2834. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  2835. * @param matrix The matrix to use to compute the transformation
  2836. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  2837. */
  2838. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  2839. // Construct a bounding box based on the extent values
  2840. var p = BoundingInfo2D._transform;
  2841. p[0].x = this.center.x + this.extent.x;
  2842. p[0].y = this.center.y + this.extent.y;
  2843. p[1].x = this.center.x + this.extent.x;
  2844. p[1].y = this.center.y - this.extent.y;
  2845. p[2].x = this.center.x - this.extent.x;
  2846. p[2].y = this.center.y - this.extent.y;
  2847. p[3].x = this.center.x - this.extent.x;
  2848. p[3].y = this.center.y + this.extent.y;
  2849. // Transform the four points of the bounding box with the matrix
  2850. for (var i = 0; i < 4; i++) {
  2851. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  2852. }
  2853. BoundingInfo2D.CreateFromPointsToRef(p, result);
  2854. };
  2855. BoundingInfo2D.prototype._updateWorldAABB = function (worldMatrix) {
  2856. // Construct a bounding box based on the extent values
  2857. var p = BoundingInfo2D._transform;
  2858. p[0].x = this.center.x + this.extent.x;
  2859. p[0].y = this.center.y + this.extent.y;
  2860. p[1].x = this.center.x + this.extent.x;
  2861. p[1].y = this.center.y - this.extent.y;
  2862. p[2].x = this.center.x - this.extent.x;
  2863. p[2].y = this.center.y - this.extent.y;
  2864. p[3].x = this.center.x - this.extent.x;
  2865. p[3].y = this.center.y + this.extent.y;
  2866. // Transform the four points of the bounding box with the matrix
  2867. for (var i = 0; i < 4; i++) {
  2868. BABYLON.Vector2.TransformToRef(p[i], worldMatrix, p[i]);
  2869. }
  2870. this._worldAABB.x = Math.min(Math.min(p[0].x, p[1].x), Math.min(p[2].x, p[3].x));
  2871. this._worldAABB.y = Math.min(Math.min(p[0].y, p[1].y), Math.min(p[2].y, p[3].y));
  2872. this._worldAABB.z = Math.max(Math.max(p[0].x, p[1].x), Math.max(p[2].x, p[3].x));
  2873. this._worldAABB.w = Math.max(Math.max(p[0].y, p[1].y), Math.max(p[2].y, p[3].y));
  2874. };
  2875. Object.defineProperty(BoundingInfo2D.prototype, "worldAABBDirtyObservable", {
  2876. get: function () {
  2877. if (!this._worldAABBDirtyObservable) {
  2878. this._worldAABBDirtyObservable = new BABYLON.Observable();
  2879. }
  2880. return this._worldAABBDirtyObservable;
  2881. },
  2882. enumerable: true,
  2883. configurable: true
  2884. });
  2885. Object.defineProperty(BoundingInfo2D.prototype, "isWorldAABBDirty", {
  2886. get: function () {
  2887. return this._worldAABBDirty;
  2888. },
  2889. enumerable: true,
  2890. configurable: true
  2891. });
  2892. BoundingInfo2D.prototype.dirtyWorldAABB = function () {
  2893. if (this._worldAABBDirty) {
  2894. return;
  2895. }
  2896. this._worldAABBDirty = true;
  2897. if (this._worldAABBDirtyObservable && this._worldAABBDirtyObservable.hasObservers()) {
  2898. this._worldAABBDirtyObservable.notifyObservers(this);
  2899. }
  2900. };
  2901. Object.defineProperty(BoundingInfo2D.prototype, "worldAABB", {
  2902. /**
  2903. * Retrieve the world AABB, the Vector4's data is x=xmin, y=ymin, z=xmax, w=ymax
  2904. */
  2905. get: function () {
  2906. if (this._worldAABBDirty) {
  2907. if (!this.worldMatrixAccess) {
  2908. throw new Error("you must set the worldMatrixAccess function first");
  2909. }
  2910. this._updateWorldAABB(this.worldMatrixAccess());
  2911. this._worldAABBDirty = false;
  2912. }
  2913. return this._worldAABB;
  2914. },
  2915. enumerable: true,
  2916. configurable: true
  2917. });
  2918. /**
  2919. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  2920. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  2921. * @param other the second object used to compute the union
  2922. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  2923. */
  2924. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  2925. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  2926. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  2927. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  2928. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  2929. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  2930. };
  2931. /**
  2932. * Check if the given point is inside the BoundingInfo.
  2933. * The test is first made on the radius, then inside the rectangle described by the extent
  2934. * @param pickPosition the position to test
  2935. * @return true if the point is inside, false otherwise
  2936. */
  2937. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  2938. // is it inside the radius?
  2939. var pickLocal = pickPosition.subtract(this.center);
  2940. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  2941. // is it inside the rectangle?
  2942. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  2943. }
  2944. return false;
  2945. };
  2946. return BoundingInfo2D;
  2947. }());
  2948. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  2949. BABYLON.BoundingInfo2D = BoundingInfo2D;
  2950. })(BABYLON || (BABYLON = {}));
  2951. //# sourceMappingURL=babylon.bounding2d.js.map
  2952. var __extends = (this && this.__extends) || function (d, b) {
  2953. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  2954. function __() { this.constructor = d; }
  2955. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2956. };
  2957. var BABYLON;
  2958. (function (BABYLON) {
  2959. /**
  2960. * The base class for all implementation of a Primitive Collision Manager
  2961. */
  2962. var PrimitiveCollisionManagerBase = (function () {
  2963. function PrimitiveCollisionManagerBase(owner) {
  2964. this._owner = owner;
  2965. }
  2966. PrimitiveCollisionManagerBase.allocBasicPCM = function (owner, enableBorders) {
  2967. return new BasicPrimitiveCollisionManager(owner, enableBorders);
  2968. };
  2969. return PrimitiveCollisionManagerBase;
  2970. }());
  2971. BABYLON.PrimitiveCollisionManagerBase = PrimitiveCollisionManagerBase;
  2972. /**
  2973. * Base class of an Actor
  2974. */
  2975. var ActorInfoBase = (function () {
  2976. function ActorInfoBase() {
  2977. }
  2978. return ActorInfoBase;
  2979. }());
  2980. BABYLON.ActorInfoBase = ActorInfoBase;
  2981. var ActorInfo = (function (_super) {
  2982. __extends(ActorInfo, _super);
  2983. function ActorInfo(owner, actor, deep) {
  2984. var _this = _super.call(this) || this;
  2985. _this.owner = owner;
  2986. _this.prim = actor;
  2987. _this.flags = 0;
  2988. _this.presentInClusters = new BABYLON.StringDictionary();
  2989. _this.intersectWith = new BABYLON.ObservableStringDictionary(false);
  2990. _this.setFlags((deep ? ActorInfo.flagDeep : 0) | ActorInfo.flagDirty);
  2991. var bi = (deep ? actor.boundingInfo : actor.levelBoundingInfo);
  2992. // Dirty Actor if its WorldAABB changed
  2993. bi.worldAABBDirtyObservable.add(function (e, d) {
  2994. _this.owner.actorDirty(_this);
  2995. });
  2996. // Dirty Actor if it's getting enabled/disabled
  2997. actor.propertyChanged.add(function (e, d) {
  2998. if (d.mask === -1) {
  2999. return;
  3000. }
  3001. _this.setFlagsValue(ActorInfo.flagEnabled, e.newValue === true);
  3002. _this.owner.actorDirty(_this);
  3003. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  3004. return _this;
  3005. }
  3006. ActorInfo.prototype.setFlags = function (flags) {
  3007. this.flags |= flags;
  3008. };
  3009. ActorInfo.prototype.clearFlags = function (flags) {
  3010. this.flags &= ~flags;
  3011. };
  3012. ActorInfo.prototype.isAllFlagsSet = function (flags) {
  3013. return (this.flags & flags) === flags;
  3014. };
  3015. ActorInfo.prototype.isSomeFlagsSet = function (flags) {
  3016. return (this.flags & flags) !== 0;
  3017. };
  3018. ActorInfo.prototype.setFlagsValue = function (flags, value) {
  3019. if (value) {
  3020. this.flags |= flags;
  3021. }
  3022. else {
  3023. this.flags &= ~flags;
  3024. }
  3025. };
  3026. Object.defineProperty(ActorInfo.prototype, "worldAABB", {
  3027. get: function () {
  3028. return (this.isSomeFlagsSet(ActorInfo.flagDeep) ? this.prim.boundingInfo : this.prim.levelBoundingInfo).worldAABB;
  3029. },
  3030. enumerable: true,
  3031. configurable: true
  3032. });
  3033. Object.defineProperty(ActorInfo.prototype, "isEnabled", {
  3034. get: function () {
  3035. return this.isSomeFlagsSet(ActorInfo.flagEnabled);
  3036. },
  3037. enumerable: true,
  3038. configurable: true
  3039. });
  3040. Object.defineProperty(ActorInfo.prototype, "isDeep", {
  3041. get: function () {
  3042. return this.isSomeFlagsSet(ActorInfo.flagDeep);
  3043. },
  3044. enumerable: true,
  3045. configurable: true
  3046. });
  3047. Object.defineProperty(ActorInfo.prototype, "isDirty", {
  3048. get: function () {
  3049. return this.isSomeFlagsSet(ActorInfo.flagDirty);
  3050. },
  3051. enumerable: true,
  3052. configurable: true
  3053. });
  3054. Object.defineProperty(ActorInfo.prototype, "isRemoved", {
  3055. get: function () {
  3056. return this.isSomeFlagsSet(ActorInfo.flagRemoved);
  3057. },
  3058. enumerable: true,
  3059. configurable: true
  3060. });
  3061. return ActorInfo;
  3062. }(ActorInfoBase));
  3063. ActorInfo.flagDeep = 0x0001; // set if the actor boundingInfo must be used instead of the levelBoundingInfo
  3064. ActorInfo.flagEnabled = 0x0002; // set if the actor is enabled and should be considered for intersection tests
  3065. ActorInfo.flagDirty = 0x0004; // set if the actor's AABB is dirty
  3066. ActorInfo.flagRemoved = 0x0008; // set if the actor was removed from the PCM
  3067. var ClusterInfo = (function () {
  3068. function ClusterInfo() {
  3069. this.actors = new BABYLON.StringDictionary();
  3070. }
  3071. ClusterInfo.prototype.clear = function () {
  3072. this.actors.clear();
  3073. };
  3074. return ClusterInfo;
  3075. }());
  3076. var BasicPrimitiveCollisionManager = (function (_super) {
  3077. __extends(BasicPrimitiveCollisionManager, _super);
  3078. function BasicPrimitiveCollisionManager(owner, enableBorders) {
  3079. var _this = _super.call(this, owner) || this;
  3080. _this._actors = new BABYLON.StringDictionary();
  3081. _this._dirtyActors = new BABYLON.StringDictionary();
  3082. _this._clusters = null;
  3083. _this._maxActorByCluster = 0;
  3084. _this._AABBRenderPrim = null;
  3085. _this._canvasSize = BABYLON.Size.Zero();
  3086. _this._ClusterRenderPrim = null;
  3087. _this._debugTextBackground = null;
  3088. _this._clusterDirty = true;
  3089. _this._clusterSize = new BABYLON.Size(2, 2);
  3090. _this._clusterStep = BABYLON.Vector2.Zero();
  3091. _this._lastClusterResizeCounter = 0;
  3092. _this._freeClusters = new Array();
  3093. _this._enableBorder = enableBorders;
  3094. _this._debugUpdateOpCount = new BABYLON.PerfCounter();
  3095. _this._debugUpdateTime = new BABYLON.PerfCounter();
  3096. _this._intersectedActors = new BABYLON.ObservableStringDictionary(false);
  3097. _this._borderIntersecteddActors = new Array(4);
  3098. for (var j = 0; j < 4; j++) {
  3099. _this._borderIntersecteddActors[j] = new BABYLON.ObservableStringDictionary(false);
  3100. }
  3101. var flagId = BABYLON.Canvas2D.actualSizeProperty.flagId;
  3102. if (!BasicPrimitiveCollisionManager.WAABBCorners) {
  3103. BasicPrimitiveCollisionManager.WAABBCorners = new Array(4);
  3104. for (var i = 0; i < 4; i++) {
  3105. BasicPrimitiveCollisionManager.WAABBCorners[i] = BABYLON.Vector2.Zero();
  3106. }
  3107. BasicPrimitiveCollisionManager.WAABBCornersCluster = new Array(4);
  3108. for (var i = 0; i < 4; i++) {
  3109. BasicPrimitiveCollisionManager.WAABBCornersCluster[i] = BABYLON.Vector2.Zero();
  3110. }
  3111. }
  3112. owner.propertyChanged.add(function (e, d) {
  3113. if (d.mask === -1) {
  3114. return;
  3115. }
  3116. _this._clusterDirty = true;
  3117. console.log("canvas size changed");
  3118. }, flagId);
  3119. _this.debugRenderAABB = false;
  3120. _this.debugRenderClusters = false;
  3121. _this.debugStats = false;
  3122. return _this;
  3123. }
  3124. BasicPrimitiveCollisionManager.prototype._addActor = function (actor, deep) {
  3125. var _this = this;
  3126. return this._actors.getOrAddWithFactory(actor.uid, function () {
  3127. var ai = new ActorInfo(_this, actor, deep);
  3128. _this.actorDirty(ai);
  3129. return ai;
  3130. });
  3131. };
  3132. BasicPrimitiveCollisionManager.prototype._removeActor = function (actor) {
  3133. var ai = this._actors.getAndRemove(actor.uid);
  3134. ai.setFlags(ActorInfo.flagRemoved);
  3135. this.actorDirty(ai);
  3136. };
  3137. BasicPrimitiveCollisionManager.prototype.actorDirty = function (actor) {
  3138. actor.setFlags(ActorInfo.flagDirty);
  3139. this._dirtyActors.add(actor.prim.uid, actor);
  3140. };
  3141. BasicPrimitiveCollisionManager.prototype._update = function () {
  3142. this._canvasSize.copyFrom(this._owner.actualSize);
  3143. // Should we update the WireFrame2D Primitive that displays the WorldAABB ?
  3144. if (this.debugRenderAABB) {
  3145. if (this._dirtyActors.count > 0 || this._debugRenderAABBDirty) {
  3146. this._updateAABBDisplay();
  3147. }
  3148. }
  3149. if (this._AABBRenderPrim) {
  3150. this._AABBRenderPrim.levelVisible = this.debugRenderAABB;
  3151. }
  3152. var cw = this._clusterSize.width;
  3153. var ch = this._clusterSize.height;
  3154. // Check for Cluster resize
  3155. if (((this._clusterSize.width < 16 && this._clusterSize.height < 16 && this._maxActorByCluster >= 10) ||
  3156. (this._clusterSize.width > 2 && this._clusterSize.height > 2 && this._maxActorByCluster <= 7)) &&
  3157. this._lastClusterResizeCounter > 100) {
  3158. if (this._maxActorByCluster >= 10) {
  3159. ++cw;
  3160. ++ch;
  3161. }
  3162. else {
  3163. --cw;
  3164. --ch;
  3165. }
  3166. console.log("Change cluster size to " + cw + ":" + ch + ", max actor " + this._maxActorByCluster);
  3167. this._clusterDirty = true;
  3168. }
  3169. // Should we update the WireFrame2D Primitive that displays the clusters
  3170. if (this.debugRenderClusters && this._clusterDirty) {
  3171. this._updateClusterDisplay(cw, ch);
  3172. }
  3173. if (this._ClusterRenderPrim) {
  3174. this._ClusterRenderPrim.levelVisible = this.debugRenderClusters;
  3175. }
  3176. var updateStats = this.debugStats && (this._dirtyActors.count > 0 || this._clusterDirty);
  3177. this._debugUpdateTime.beginMonitoring();
  3178. // If the Cluster Size changed: rebuild it and add all actors. Otherwise add only new (dirty) actors
  3179. if (this._clusterDirty) {
  3180. this._initializeCluster(cw, ch);
  3181. this._rebuildAllActors();
  3182. }
  3183. else {
  3184. this._rebuildDirtyActors();
  3185. ++this._lastClusterResizeCounter;
  3186. }
  3187. // Proceed to the collision detection between primitives
  3188. this._collisionDetection();
  3189. this._debugUpdateTime.endMonitoring();
  3190. if (updateStats) {
  3191. this._updateDebugStats();
  3192. }
  3193. if (this._debugTextBackground) {
  3194. this._debugTextBackground.levelVisible = updateStats;
  3195. }
  3196. // Reset the dirty actor list: everything is processed
  3197. this._dirtyActors.clear();
  3198. };
  3199. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "debugRenderAABB", {
  3200. /**
  3201. * Renders the World AABB of all Actors
  3202. */
  3203. get: function () {
  3204. return this._debugRenderAABB;
  3205. },
  3206. set: function (val) {
  3207. if (this._debugRenderAABB === val) {
  3208. return;
  3209. }
  3210. this._debugRenderAABB = val;
  3211. this._debugRenderAABBDirty = true;
  3212. },
  3213. enumerable: true,
  3214. configurable: true
  3215. });
  3216. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "intersectedActors", {
  3217. get: function () {
  3218. return this._intersectedActors;
  3219. },
  3220. enumerable: true,
  3221. configurable: true
  3222. });
  3223. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "leftBorderIntersectedActors", {
  3224. get: function () {
  3225. return this._borderIntersecteddActors[0];
  3226. },
  3227. enumerable: true,
  3228. configurable: true
  3229. });
  3230. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "bottomBorderIntersectedActors", {
  3231. get: function () {
  3232. return this._borderIntersecteddActors[1];
  3233. },
  3234. enumerable: true,
  3235. configurable: true
  3236. });
  3237. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "rightBorderIntersectedActors", {
  3238. get: function () {
  3239. return this._borderIntersecteddActors[2];
  3240. },
  3241. enumerable: true,
  3242. configurable: true
  3243. });
  3244. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "topBorderIntersectedActors", {
  3245. get: function () {
  3246. return this._borderIntersecteddActors[3];
  3247. },
  3248. enumerable: true,
  3249. configurable: true
  3250. });
  3251. BasicPrimitiveCollisionManager.prototype._initializeCluster = function (countW, countH) {
  3252. // Check for free
  3253. if (this._clusters) {
  3254. for (var w = 0; w < this._clusterSize.height; w++) {
  3255. for (var h = 0; h < this._clusterSize.width; h++) {
  3256. this._freeClusterInfo(this._clusters[w][h]);
  3257. }
  3258. }
  3259. }
  3260. // Allocate
  3261. this._clusterSize.copyFromFloats(countW, countH);
  3262. this._clusters = [];
  3263. for (var w = 0; w < this._clusterSize.height; w++) {
  3264. this._clusters[w] = [];
  3265. for (var h = 0; h < this._clusterSize.width; h++) {
  3266. var ci = this._allocClusterInfo();
  3267. this._clusters[w][h] = ci;
  3268. }
  3269. }
  3270. this._clusterStep.copyFromFloats(this._owner.actualWidth / countW, this._owner.actualHeight / countH);
  3271. this._maxActorByCluster = 0;
  3272. this._lastClusterResizeCounter = 0;
  3273. this._clusterDirty = false;
  3274. };
  3275. BasicPrimitiveCollisionManager.prototype._rebuildAllActors = function () {
  3276. var _this = this;
  3277. this._actors.forEach(function (k, ai) {
  3278. _this._processActor(ai);
  3279. });
  3280. };
  3281. BasicPrimitiveCollisionManager.prototype._rebuildDirtyActors = function () {
  3282. var _this = this;
  3283. this._dirtyActors.forEach(function (k, ai) {
  3284. _this._processActor(ai);
  3285. });
  3286. };
  3287. BasicPrimitiveCollisionManager.prototype._processActor = function (actor) {
  3288. var _this = this;
  3289. // Check if the actor is being disabled or removed
  3290. if (!actor.isEnabled || actor.isRemoved) {
  3291. actor.presentInClusters.forEach(function (k, ci) {
  3292. ci.actors.remove(actor.prim.uid);
  3293. });
  3294. actor.presentInClusters.clear();
  3295. return;
  3296. }
  3297. var wab = actor.worldAABB;
  3298. // Build the worldAABB corners
  3299. var wac = BasicPrimitiveCollisionManager.WAABBCorners;
  3300. wac[0].copyFromFloats(wab.x, wab.y); // Bottom/Left
  3301. wac[1].copyFromFloats(wab.z, wab.y); // Bottom/Right
  3302. wac[2].copyFromFloats(wab.z, wab.w); // Top/Right
  3303. wac[3].copyFromFloats(wab.x, wab.w); // Top/Left
  3304. var cs = this._clusterStep;
  3305. var wacc = BasicPrimitiveCollisionManager.WAABBCornersCluster;
  3306. for (var i = 0; i < 4; i++) {
  3307. var p = wac[i];
  3308. var cx = (p.x - (p.x % cs.x)) / cs.x;
  3309. var cy = (p.y - (p.y % cs.y)) / cs.y;
  3310. wacc[i].copyFromFloats(Math.floor(cx), Math.floor(cy));
  3311. }
  3312. var opCount = 0;
  3313. var totalClusters = 0;
  3314. var newCI = new Array();
  3315. var sx = Math.max(0, wacc[0].x); // Start Cluster X
  3316. var sy = Math.max(0, wacc[0].y); // Start Cluster Y
  3317. var ex = Math.min(this._clusterSize.width - 1, wacc[2].x); // End Cluster X
  3318. var ey = Math.min(this._clusterSize.height - 1, wacc[2].y); // End Cluster Y
  3319. if (this._enableBorder) {
  3320. if (wac[0].x < 0) {
  3321. this._borderIntersecteddActors[0].add(actor.prim.uid, actor.prim);
  3322. }
  3323. else {
  3324. this._borderIntersecteddActors[0].remove(actor.prim.uid);
  3325. }
  3326. if (wac[0].y < 0) {
  3327. this._borderIntersecteddActors[1].add(actor.prim.uid, actor.prim);
  3328. }
  3329. else {
  3330. this._borderIntersecteddActors[1].remove(actor.prim.uid);
  3331. }
  3332. if (wac[2].x >= this._canvasSize.width) {
  3333. this._borderIntersecteddActors[2].add(actor.prim.uid, actor.prim);
  3334. }
  3335. else {
  3336. this._borderIntersecteddActors[2].remove(actor.prim.uid);
  3337. }
  3338. if (wac[2].y >= this._canvasSize.height) {
  3339. this._borderIntersecteddActors[3].add(actor.prim.uid, actor.prim);
  3340. }
  3341. else {
  3342. this._borderIntersecteddActors[3].remove(actor.prim.uid);
  3343. }
  3344. }
  3345. for (var y = sy; y <= ey; y++) {
  3346. var _loop_1 = function (x) {
  3347. var k = x + ":" + y;
  3348. var cx = x, cy = y;
  3349. var ci = actor.presentInClusters.getOrAddWithFactory(k, function (k) {
  3350. var nci = _this._getCluster(cx, cy);
  3351. nci.actors.add(actor.prim.uid, actor);
  3352. _this._maxActorByCluster = Math.max(_this._maxActorByCluster, nci.actors.count);
  3353. ++opCount;
  3354. ++totalClusters;
  3355. return nci;
  3356. });
  3357. newCI.push(ci);
  3358. };
  3359. for (var x = sx; x <= ex; x++) {
  3360. _loop_1(x);
  3361. }
  3362. }
  3363. // Check if there were no change
  3364. if (opCount === 0 && actor.presentInClusters.count === totalClusters) {
  3365. return;
  3366. }
  3367. // Build the array of the cluster where the actor is no longer in
  3368. var clusterToRemove = new Array();
  3369. actor.presentInClusters.forEach(function (k, ci) {
  3370. if (newCI.indexOf(ci) === -1) {
  3371. clusterToRemove.push(k);
  3372. // remove the primitive from the Cluster Info object
  3373. ci.actors.remove(actor.prim.uid);
  3374. }
  3375. });
  3376. // Remove these clusters from the actor's dictionary
  3377. for (var _i = 0, clusterToRemove_1 = clusterToRemove; _i < clusterToRemove_1.length; _i++) {
  3378. var key = clusterToRemove_1[_i];
  3379. actor.presentInClusters.remove(key);
  3380. }
  3381. };
  3382. // The algorithm is simple, we have previously partitioned the Actors in the Clusters: each actor has a list of the Cluster(s) it's inside.
  3383. // Then for a given Actor that is dirty we evaluate the intersection with all the other actors present in the same Cluster(s)
  3384. // So it's basically O(n²), BUT only inside a Cluster and only for dirty Actors.
  3385. BasicPrimitiveCollisionManager.prototype._collisionDetection = function () {
  3386. var _this = this;
  3387. var hash = BasicPrimitiveCollisionManager.CandidatesActors;
  3388. var prev = BasicPrimitiveCollisionManager.PreviousIntersections;
  3389. var opCount = 0;
  3390. this._dirtyActors.forEach(function (k1, ai1) {
  3391. ++opCount;
  3392. // Build the list of candidates
  3393. hash.clear();
  3394. ai1.presentInClusters.forEach(function (k, ci) {
  3395. ++opCount;
  3396. ci.actors.forEach(function (k, v) { return hash.add(k, v); });
  3397. });
  3398. var wab1 = ai1.worldAABB;
  3399. // Save the previous intersections
  3400. prev.clear();
  3401. prev.copyFrom(ai1.intersectWith);
  3402. ai1.intersectWith.clear();
  3403. // For each candidate
  3404. hash.forEach(function (k2, ai2) {
  3405. ++opCount;
  3406. // Check if we're testing against itself
  3407. if (k1 === k2) {
  3408. return;
  3409. }
  3410. var wab2 = ai2.worldAABB;
  3411. if (wab2.z >= wab1.x && wab2.x <= wab1.z && wab2.w >= wab1.y && wab2.y <= wab1.w) {
  3412. if (ai1.prim.intersectOtherPrim(ai2.prim)) {
  3413. ++opCount;
  3414. ai1.intersectWith.add(k2, ai2);
  3415. if (k1 < k2) {
  3416. _this._intersectedActors.add(k1 + ";" + k2, { a: ai1.prim, b: ai2.prim });
  3417. }
  3418. else {
  3419. _this._intersectedActors.add(k2 + ";" + k1, { a: ai2.prim, b: ai1.prim });
  3420. }
  3421. }
  3422. }
  3423. });
  3424. // Check and remove the associations that no longer exist in the main intersection list
  3425. prev.forEach(function (k, ai) {
  3426. if (!ai1.intersectWith.contains(k)) {
  3427. ++opCount;
  3428. _this._intersectedActors.remove((k < k1 ? k : k1) + ";" + (k < k1 ? k1 : k));
  3429. }
  3430. });
  3431. });
  3432. this._debugUpdateOpCount.fetchNewFrame();
  3433. this._debugUpdateOpCount.addCount(opCount, true);
  3434. };
  3435. BasicPrimitiveCollisionManager.prototype._getCluster = function (x, y) {
  3436. return this._clusters[x][y];
  3437. };
  3438. BasicPrimitiveCollisionManager.prototype._updateDebugStats = function () {
  3439. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  3440. var txt = "Primitive Collision Stats\n" +
  3441. (" - PCM Execution Time: " + format(this._debugUpdateTime.lastSecAverage) + "ms\n") +
  3442. (" - Operation Count: " + format(this._debugUpdateOpCount.current) + ", (avg:" + format(this._debugUpdateOpCount.lastSecAverage) + ", t:" + format(this._debugUpdateOpCount.total) + ")\n") +
  3443. (" - Max Actor per Cluster: " + this._maxActorByCluster + "\n") +
  3444. (" - Intersections count: " + this.intersectedActors.count);
  3445. if (!this._debugTextBackground) {
  3446. this._debugTextBackground = new BABYLON.Rectangle2D({
  3447. id: "###DEBUG PMC STATS###", parent: this._owner, marginAlignment: "h: left, v: top", fill: "#C0404080", padding: "10", margin: "10", roundRadius: 10, children: [
  3448. new BABYLON.Text2D(txt, { id: "###DEBUG PMC TEXT###", fontName: "12pt Lucida Console" })
  3449. ]
  3450. });
  3451. }
  3452. else {
  3453. this._debugTextBackground.levelVisible = true;
  3454. var text2d = this._debugTextBackground.children[0];
  3455. text2d.text = txt;
  3456. }
  3457. };
  3458. BasicPrimitiveCollisionManager.prototype._updateAABBDisplay = function () {
  3459. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.5, 0.8, 1.0, 1.0));
  3460. var v = BABYLON.Vector2.Zero();
  3461. this._actors.forEach(function (k, ai) {
  3462. if (ai.isEnabled) {
  3463. var ab = ai.worldAABB;
  3464. v.x = ab.x;
  3465. v.y = ab.y;
  3466. g.startLineStrip(v);
  3467. v.x = ab.z;
  3468. g.pushVertex(v);
  3469. v.y = ab.w;
  3470. g.pushVertex(v);
  3471. v.x = ab.x;
  3472. g.pushVertex(v);
  3473. v.y = ab.y;
  3474. g.endLineStrip(v);
  3475. }
  3476. });
  3477. if (!this._AABBRenderPrim) {
  3478. this._AABBRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: false, id: "###DEBUG PCM AABB###" });
  3479. }
  3480. else {
  3481. this._AABBRenderPrim.wireFrameGroups.set("main", g);
  3482. this._AABBRenderPrim.wireFrameGroupsDirty();
  3483. }
  3484. this._debugRenderAABBDirty = false;
  3485. };
  3486. BasicPrimitiveCollisionManager.prototype._updateClusterDisplay = function (cw, ch) {
  3487. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.8, 0.1, 0.5, 1.0));
  3488. var v1 = BABYLON.Vector2.Zero();
  3489. var v2 = BABYLON.Vector2.Zero();
  3490. // Vertical lines
  3491. var step = (this._owner.actualWidth - 1) / cw;
  3492. v1.y = 0;
  3493. v2.y = this._owner.actualHeight;
  3494. for (var x = 0; x <= cw; x++) {
  3495. g.pushVertex(v1);
  3496. g.pushVertex(v2);
  3497. v1.x += step;
  3498. v2.x += step;
  3499. }
  3500. // Horizontal lines
  3501. step = (this._owner.actualHeight - 1) / ch;
  3502. v1.x = v1.y = v2.y = 0;
  3503. v2.x = this._owner.actualWidth;
  3504. for (var y = 0; y <= ch; y++) {
  3505. g.pushVertex(v1);
  3506. g.pushVertex(v2);
  3507. v1.y += step;
  3508. v2.y += step;
  3509. }
  3510. if (!this._ClusterRenderPrim) {
  3511. this._ClusterRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: true, id: "###DEBUG PCM Clusters###" });
  3512. }
  3513. else {
  3514. this._ClusterRenderPrim.wireFrameGroups.set("main", g);
  3515. this._ClusterRenderPrim.wireFrameGroupsDirty();
  3516. }
  3517. };
  3518. // Basically: we don't want to spend our time playing with the GC each time the Cluster Array is rebuilt, so we keep a list of available
  3519. // ClusterInfo object and we have two method to allocate/free them. This way we always deal with the same objects.
  3520. // The free array never shrink, always grows...For the better...and the worst!
  3521. BasicPrimitiveCollisionManager.prototype._allocClusterInfo = function () {
  3522. if (this._freeClusters.length === 0) {
  3523. for (var i = 0; i < 8; i++) {
  3524. this._freeClusters.push(new ClusterInfo());
  3525. }
  3526. }
  3527. return this._freeClusters.pop();
  3528. };
  3529. BasicPrimitiveCollisionManager.prototype._freeClusterInfo = function (ci) {
  3530. ci.clear();
  3531. this._freeClusters.push(ci);
  3532. };
  3533. return BasicPrimitiveCollisionManager;
  3534. }(PrimitiveCollisionManagerBase));
  3535. BasicPrimitiveCollisionManager.WAABBCorners = null;
  3536. BasicPrimitiveCollisionManager.WAABBCornersCluster = null;
  3537. BasicPrimitiveCollisionManager.CandidatesActors = new BABYLON.StringDictionary();
  3538. BasicPrimitiveCollisionManager.PreviousIntersections = new BABYLON.StringDictionary();
  3539. })(BABYLON || (BABYLON = {}));
  3540. //# sourceMappingURL=babylon.primitiveCollisionManager.js.map
  3541. var __extends = (this && this.__extends) || function (d, b) {
  3542. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3543. function __() { this.constructor = d; }
  3544. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3545. };
  3546. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3547. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3548. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  3549. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  3550. return c > 3 && r && Object.defineProperty(target, key, r), r;
  3551. };
  3552. var BABYLON;
  3553. (function (BABYLON) {
  3554. var LayoutEngineBase = (function () {
  3555. function LayoutEngineBase() {
  3556. this.layoutDirtyOnPropertyChangedMask = 0;
  3557. }
  3558. LayoutEngineBase.prototype.updateLayout = function (prim) {
  3559. };
  3560. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  3561. get: function () {
  3562. return false;
  3563. },
  3564. enumerable: true,
  3565. configurable: true
  3566. });
  3567. LayoutEngineBase.prototype.isLocked = function () {
  3568. return this._isLocked;
  3569. };
  3570. LayoutEngineBase.prototype.lock = function () {
  3571. if (this._isLocked) {
  3572. return false;
  3573. }
  3574. this._isLocked = true;
  3575. return true;
  3576. };
  3577. return LayoutEngineBase;
  3578. }());
  3579. LayoutEngineBase = __decorate([
  3580. BABYLON.className("LayoutEngineBase", "BABYLON")
  3581. ], LayoutEngineBase);
  3582. BABYLON.LayoutEngineBase = LayoutEngineBase;
  3583. var CanvasLayoutEngine = CanvasLayoutEngine_1 = (function (_super) {
  3584. __extends(CanvasLayoutEngine, _super);
  3585. function CanvasLayoutEngine() {
  3586. var _this = _super.call(this) || this;
  3587. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  3588. return _this;
  3589. }
  3590. Object.defineProperty(CanvasLayoutEngine, "Singleton", {
  3591. get: function () {
  3592. if (!CanvasLayoutEngine_1._singleton) {
  3593. CanvasLayoutEngine_1._singleton = new CanvasLayoutEngine_1();
  3594. }
  3595. return CanvasLayoutEngine_1._singleton;
  3596. },
  3597. enumerable: true,
  3598. configurable: true
  3599. });
  3600. // A very simple (no) layout computing...
  3601. // The Canvas and its direct children gets the Canvas' size as Layout Area
  3602. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  3603. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  3604. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  3605. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3606. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3607. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3608. var child = _a[_i];
  3609. this._doUpdate(child);
  3610. }
  3611. }
  3612. };
  3613. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  3614. // Canvas ?
  3615. if (prim instanceof BABYLON.Canvas2D) {
  3616. prim.layoutArea = prim.actualSize; //.multiplyByFloats(prim.scaleX, prim.scaleY);
  3617. }
  3618. else if (prim.parent instanceof BABYLON.Canvas2D) {
  3619. prim.layoutArea = prim.owner.actualSize; //.multiplyByFloats(prim.owner.scaleX, prim.owner.scaleY);
  3620. }
  3621. else {
  3622. var contentArea = prim.parent.contentArea;
  3623. // Can be null if the parent's content area depend of its children, the computation will be done in many passes
  3624. if (contentArea) {
  3625. prim.layoutArea = contentArea;
  3626. }
  3627. }
  3628. };
  3629. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  3630. get: function () {
  3631. return true;
  3632. },
  3633. enumerable: true,
  3634. configurable: true
  3635. });
  3636. return CanvasLayoutEngine;
  3637. }(LayoutEngineBase));
  3638. CanvasLayoutEngine._singleton = null;
  3639. CanvasLayoutEngine = CanvasLayoutEngine_1 = __decorate([
  3640. BABYLON.className("CanvasLayoutEngine", "BABYLON")
  3641. ], CanvasLayoutEngine);
  3642. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  3643. var StackPanelLayoutEngine = StackPanelLayoutEngine_1 = (function (_super) {
  3644. __extends(StackPanelLayoutEngine, _super);
  3645. function StackPanelLayoutEngine() {
  3646. var _this = _super.call(this) || this;
  3647. _this._isHorizontal = true;
  3648. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  3649. return _this;
  3650. }
  3651. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  3652. get: function () {
  3653. if (!StackPanelLayoutEngine_1._horizontal) {
  3654. StackPanelLayoutEngine_1._horizontal = new StackPanelLayoutEngine_1();
  3655. StackPanelLayoutEngine_1._horizontal.isHorizontal = true;
  3656. StackPanelLayoutEngine_1._horizontal.lock();
  3657. }
  3658. return StackPanelLayoutEngine_1._horizontal;
  3659. },
  3660. enumerable: true,
  3661. configurable: true
  3662. });
  3663. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  3664. get: function () {
  3665. if (!StackPanelLayoutEngine_1._vertical) {
  3666. StackPanelLayoutEngine_1._vertical = new StackPanelLayoutEngine_1();
  3667. StackPanelLayoutEngine_1._vertical.isHorizontal = false;
  3668. StackPanelLayoutEngine_1._vertical.lock();
  3669. }
  3670. return StackPanelLayoutEngine_1._vertical;
  3671. },
  3672. enumerable: true,
  3673. configurable: true
  3674. });
  3675. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  3676. get: function () {
  3677. return this._isHorizontal;
  3678. },
  3679. set: function (val) {
  3680. if (this.isLocked()) {
  3681. return;
  3682. }
  3683. this._isHorizontal = val;
  3684. },
  3685. enumerable: true,
  3686. configurable: true
  3687. });
  3688. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  3689. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3690. var primLayoutArea = prim.layoutArea;
  3691. var isSizeAuto = prim.isSizeAuto;
  3692. // If we're not in autoSize the layoutArea of the prim having the stack panel must be computed in order for us to compute the children' position.
  3693. // If there's at least one auto size (Horizontal or Vertical) we will have to figure the layoutArea ourselves
  3694. if (!primLayoutArea && !isSizeAuto) {
  3695. return;
  3696. }
  3697. // console.log("Compute Stack Panel Layout " + ++StackPanelLayoutEngine.computeCounter);
  3698. var x = 0;
  3699. var y = 0;
  3700. var horizonStackPanel = this.isHorizontal;
  3701. // If the stack panel is horizontal we check if the primitive height is auto or not, if it's auto then we have to compute the required height, otherwise we just take the actualHeight. If the stack panel is vertical we do the same but with width
  3702. var max = 0;
  3703. var stackPanelLayoutArea = StackPanelLayoutEngine_1.stackPanelLayoutArea;
  3704. if (horizonStackPanel) {
  3705. if (prim.isVerticalSizeAuto) {
  3706. max = 0;
  3707. stackPanelLayoutArea.height = 0;
  3708. }
  3709. else {
  3710. max = prim.layoutArea.height;
  3711. stackPanelLayoutArea.height = prim.layoutArea.height;
  3712. stackPanelLayoutArea.width = 0;
  3713. }
  3714. }
  3715. else {
  3716. if (prim.isHorizontalSizeAuto) {
  3717. max = 0;
  3718. stackPanelLayoutArea.width = 0;
  3719. }
  3720. else {
  3721. max = prim.layoutArea.width;
  3722. stackPanelLayoutArea.width = prim.layoutArea.width;
  3723. stackPanelLayoutArea.height = 0;
  3724. }
  3725. }
  3726. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3727. var child = _a[_i];
  3728. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3729. continue;
  3730. }
  3731. if (child._hasMargin) {
  3732. // Calling computeWithAlignment will return us the area taken by "child" which is its layoutArea
  3733. // We also have the dstOffset which will give us the y position in horizontal mode or x position in vertical mode.
  3734. // The alignment offset on the other axis is simply ignored as it doesn't make any sense (e.g. horizontal alignment is ignored in horizontal mode)
  3735. child.margin.computeWithAlignment(stackPanelLayoutArea, child.actualSize, child.marginAlignment, child.actualScale, StackPanelLayoutEngine_1.dstOffset, StackPanelLayoutEngine_1.dstArea, true);
  3736. child.layoutArea = StackPanelLayoutEngine_1.dstArea;
  3737. }
  3738. else {
  3739. child.margin.computeArea(child.actualSize, child.actualScale, StackPanelLayoutEngine_1.dstArea);
  3740. child.layoutArea = StackPanelLayoutEngine_1.dstArea;
  3741. }
  3742. max = Math.max(max, horizonStackPanel ? StackPanelLayoutEngine_1.dstArea.height : StackPanelLayoutEngine_1.dstArea.width);
  3743. }
  3744. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  3745. var child = _c[_b];
  3746. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3747. continue;
  3748. }
  3749. var layoutArea = child.layoutArea;
  3750. if (horizonStackPanel) {
  3751. child.layoutAreaPos = new BABYLON.Vector2(x, 0);
  3752. x += layoutArea.width;
  3753. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  3754. }
  3755. else {
  3756. child.layoutAreaPos = new BABYLON.Vector2(0, y);
  3757. y += layoutArea.height;
  3758. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  3759. }
  3760. }
  3761. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3762. }
  3763. };
  3764. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  3765. get: function () {
  3766. return false;
  3767. },
  3768. enumerable: true,
  3769. configurable: true
  3770. });
  3771. return StackPanelLayoutEngine;
  3772. }(LayoutEngineBase));
  3773. StackPanelLayoutEngine._horizontal = null;
  3774. StackPanelLayoutEngine._vertical = null;
  3775. StackPanelLayoutEngine.stackPanelLayoutArea = BABYLON.Size.Zero();
  3776. StackPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  3777. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  3778. StackPanelLayoutEngine.computeCounter = 0;
  3779. StackPanelLayoutEngine = StackPanelLayoutEngine_1 = __decorate([
  3780. BABYLON.className("StackPanelLayoutEngine", "BABYLON")
  3781. ], StackPanelLayoutEngine);
  3782. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  3783. /**
  3784. * GridData is used specify what row(s) and column(s) a primitive is placed in when its parent is using a Grid Panel Layout.
  3785. */
  3786. var GridData = (function () {
  3787. /**
  3788. * Create a Grid Data that describes where a primitive will be placed in a Grid Panel Layout.
  3789. * @param row the row number of the grid
  3790. * @param column the column number of the grid
  3791. * @param rowSpan the number of rows a primitive will occupy
  3792. * @param columnSpan the number of columns a primitive will occupy
  3793. **/
  3794. function GridData(row, column, rowSpan, columnSpan) {
  3795. this.row = row;
  3796. this.column = column;
  3797. this.rowSpan = (rowSpan == null) ? 1 : rowSpan;
  3798. this.columnSpan = (columnSpan == null) ? 1 : columnSpan;
  3799. }
  3800. return GridData;
  3801. }());
  3802. BABYLON.GridData = GridData;
  3803. var GridDimensionDefinition = (function () {
  3804. function GridDimensionDefinition() {
  3805. }
  3806. GridDimensionDefinition.prototype._parse = function (value, res) {
  3807. var v = value.toLocaleLowerCase().trim();
  3808. if (v.indexOf("auto") === 0) {
  3809. res(null, null, GridDimensionDefinition.Auto);
  3810. }
  3811. else if (v.indexOf("*") !== -1) {
  3812. var i = v.indexOf("*");
  3813. var w = 1;
  3814. if (i > 0) {
  3815. w = parseFloat(v.substr(0, i));
  3816. }
  3817. res(w, null, GridDimensionDefinition.Stars);
  3818. }
  3819. else {
  3820. var w = parseFloat(v);
  3821. res(w, w, GridDimensionDefinition.Pixels);
  3822. }
  3823. };
  3824. return GridDimensionDefinition;
  3825. }());
  3826. GridDimensionDefinition.Pixels = 1;
  3827. GridDimensionDefinition.Stars = 2;
  3828. GridDimensionDefinition.Auto = 3;
  3829. var RowDefinition = (function (_super) {
  3830. __extends(RowDefinition, _super);
  3831. function RowDefinition() {
  3832. return _super.apply(this, arguments) || this;
  3833. }
  3834. return RowDefinition;
  3835. }(GridDimensionDefinition));
  3836. var ColumnDefinition = (function (_super) {
  3837. __extends(ColumnDefinition, _super);
  3838. function ColumnDefinition() {
  3839. return _super.apply(this, arguments) || this;
  3840. }
  3841. return ColumnDefinition;
  3842. }(GridDimensionDefinition));
  3843. var GridPanelLayoutEngine = GridPanelLayoutEngine_1 = (function (_super) {
  3844. __extends(GridPanelLayoutEngine, _super);
  3845. function GridPanelLayoutEngine(settings) {
  3846. var _this = _super.call(this) || this;
  3847. _this._children = [];
  3848. _this._rowBottoms = [];
  3849. _this._columnLefts = [];
  3850. _this._rowHeights = [];
  3851. _this._columnWidths = [];
  3852. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  3853. _this._rows = new Array();
  3854. _this._columns = new Array();
  3855. if (settings.rows) {
  3856. var _loop_1 = function (row) {
  3857. var r = new RowDefinition();
  3858. r._parse(row.height, function (v, vp, t) {
  3859. r.height = v;
  3860. r.heightPixels = vp;
  3861. r.heightType = t;
  3862. });
  3863. this_1._rows.push(r);
  3864. };
  3865. var this_1 = this;
  3866. for (var _i = 0, _a = settings.rows; _i < _a.length; _i++) {
  3867. var row = _a[_i];
  3868. _loop_1(row);
  3869. }
  3870. }
  3871. if (settings.columns) {
  3872. var _loop_2 = function (col) {
  3873. var r = new ColumnDefinition();
  3874. r._parse(col.width, function (v, vp, t) {
  3875. r.width = v;
  3876. r.widthPixels = vp;
  3877. r.widthType = t;
  3878. });
  3879. this_2._columns.push(r);
  3880. };
  3881. var this_2 = this;
  3882. for (var _b = 0, _c = settings.columns; _b < _c.length; _b++) {
  3883. var col = _c[_b];
  3884. _loop_2(col);
  3885. }
  3886. }
  3887. return _this;
  3888. }
  3889. GridPanelLayoutEngine.prototype.updateLayout = function (prim) {
  3890. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3891. if (!prim.layoutArea) {
  3892. return;
  3893. }
  3894. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3895. var child = _a[_i];
  3896. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3897. continue;
  3898. }
  3899. if (child._hasMargin) {
  3900. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, child.actualScale, GridPanelLayoutEngine_1.dstOffset, GridPanelLayoutEngine_1.dstArea, true);
  3901. }
  3902. else {
  3903. child.margin.computeArea(child.actualSize, child.actualScale, GridPanelLayoutEngine_1.dstArea);
  3904. }
  3905. child.layoutArea = GridPanelLayoutEngine_1.dstArea;
  3906. }
  3907. this._updateGrid(prim);
  3908. var _children = this._children;
  3909. var rl = this._rows.length;
  3910. var cl = this._columns.length;
  3911. var columnWidth = 0;
  3912. var rowHeight = 0;
  3913. var dstArea = GridPanelLayoutEngine_1.dstArea;
  3914. var dstAreaPos = GridPanelLayoutEngine_1.dstAreaPos;
  3915. for (var i = 0; i < _children.length; i++) {
  3916. var children = _children[i];
  3917. if (children) {
  3918. var bottom = this._rowBottoms[i];
  3919. var rowHeight_1 = this._rowHeights[i];
  3920. var oBottom = bottom;
  3921. var oRowHeight = rowHeight_1;
  3922. for (var j = 0; j < children.length; j++) {
  3923. var left = this._columnLefts[j];
  3924. var columnWidth_1 = this._columnWidths[j];
  3925. var child = children[j];
  3926. if (child) {
  3927. var gd = child.layoutData;
  3928. if (gd.columnSpan > 1) {
  3929. for (var k = j + 1; k < gd.columnSpan + j && k < cl; k++) {
  3930. columnWidth_1 += this._columnWidths[k];
  3931. }
  3932. }
  3933. if (gd.rowSpan > 1) {
  3934. for (var k = i + 1; k < gd.rowSpan + i && k < rl; k++) {
  3935. rowHeight_1 += this._rowHeights[k];
  3936. bottom = this._rowBottoms[k];
  3937. }
  3938. }
  3939. dstArea.width = columnWidth_1;
  3940. dstArea.height = rowHeight_1;
  3941. child.layoutArea = dstArea;
  3942. dstAreaPos.x = left;
  3943. dstAreaPos.y = bottom;
  3944. child.layoutAreaPos = dstAreaPos;
  3945. bottom = oBottom;
  3946. rowHeight_1 = oRowHeight;
  3947. }
  3948. }
  3949. }
  3950. }
  3951. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3952. }
  3953. };
  3954. Object.defineProperty(GridPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  3955. get: function () {
  3956. return false;
  3957. },
  3958. enumerable: true,
  3959. configurable: true
  3960. });
  3961. GridPanelLayoutEngine.prototype._getMaxChildHeightInRow = function (rowNum) {
  3962. var rows = this._rows;
  3963. var cl = this._columns.length;
  3964. var rl = this._rows.length;
  3965. var children = this._children;
  3966. var row = rows[rowNum];
  3967. var maxHeight = 0;
  3968. if (children && children[rowNum]) {
  3969. for (var i = 0; i < cl; i++) {
  3970. var child = children[rowNum][i];
  3971. if (child) {
  3972. var span = child.layoutData.rowSpan;
  3973. if (maxHeight < child.layoutArea.height / span) {
  3974. maxHeight = child.layoutArea.height / span;
  3975. }
  3976. }
  3977. }
  3978. }
  3979. return maxHeight;
  3980. };
  3981. GridPanelLayoutEngine.prototype._getMaxChildWidthInColumn = function (colNum) {
  3982. var columns = this._columns;
  3983. var cl = this._columns.length;
  3984. var rl = this._rows.length;
  3985. var children = this._children;
  3986. var column = columns[colNum];
  3987. var maxWidth = 0;
  3988. if (children) {
  3989. for (var i = 0; i < rl; i++) {
  3990. if (children[i]) {
  3991. var child = children[i][colNum];
  3992. if (child) {
  3993. var span = child.layoutData.columnSpan;
  3994. if (maxWidth < child.layoutArea.width / span) {
  3995. maxWidth = child.layoutArea.width / span;
  3996. }
  3997. }
  3998. }
  3999. }
  4000. }
  4001. return maxWidth;
  4002. };
  4003. GridPanelLayoutEngine.prototype._updateGrid = function (prim) {
  4004. var _children = this._children;
  4005. //remove prim.children from _children
  4006. for (var i_1 = 0; i_1 < _children.length; i_1++) {
  4007. var children = _children[i_1];
  4008. if (children) {
  4009. children.length = 0;
  4010. }
  4011. }
  4012. var childrenThatSpan;
  4013. //add prim.children to _children
  4014. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  4015. var child = _a[_i];
  4016. if (!child.layoutData) {
  4017. continue;
  4018. }
  4019. var gd = child.layoutData;
  4020. if (!_children[gd.row]) {
  4021. _children[gd.row] = [];
  4022. }
  4023. if (gd.columnSpan == 1 && gd.rowSpan == 1) {
  4024. _children[gd.row][gd.column] = child;
  4025. }
  4026. else {
  4027. if (!childrenThatSpan) {
  4028. childrenThatSpan = [];
  4029. }
  4030. //when children span, we need to add them to _children whereever they span to so that
  4031. //_getMaxChildHeightInRow and _getMaxChildWidthInColumn will work correctly.
  4032. childrenThatSpan.push(child);
  4033. for (var i_2 = gd.row; i_2 < gd.row + gd.rowSpan; i_2++) {
  4034. for (var j = gd.column; j < gd.column + gd.columnSpan; j++) {
  4035. _children[i_2][j] = child;
  4036. }
  4037. }
  4038. }
  4039. }
  4040. var rows = this._rows;
  4041. var columns = this._columns;
  4042. var rl = this._rows.length;
  4043. var cl = this._columns.length;
  4044. //get fixed and auto row heights first
  4045. var starIndexes = [];
  4046. var totalStars = 0;
  4047. var rowHeights = 0;
  4048. var columnWidths = 0;
  4049. for (var i_3 = 0; i_3 < rl; i_3++) {
  4050. var row = this._rows[i_3];
  4051. if (row.heightType == GridDimensionDefinition.Auto) {
  4052. this._rowHeights[i_3] = this._getMaxChildHeightInRow(i_3);
  4053. rowHeights += this._rowHeights[i_3];
  4054. }
  4055. else if (row.heightType == GridDimensionDefinition.Pixels) {
  4056. var maxChildHeight = this._getMaxChildHeightInRow(i_3);
  4057. this._rowHeights[i_3] = Math.max(row.heightPixels, maxChildHeight);
  4058. rowHeights += this._rowHeights[i_3];
  4059. }
  4060. else if (row.heightType == GridDimensionDefinition.Stars) {
  4061. starIndexes.push(i_3);
  4062. totalStars += row.height;
  4063. }
  4064. }
  4065. //star row heights
  4066. if (starIndexes.length > 0) {
  4067. var remainingHeight = prim.contentArea.height - rowHeights;
  4068. for (var i_4 = 0; i_4 < starIndexes.length; i_4++) {
  4069. var rowIndex = starIndexes[i_4];
  4070. var starHeight = (this._rows[rowIndex].height / totalStars) * remainingHeight;
  4071. var maxChildHeight = this._getMaxChildHeightInRow(i_4);
  4072. this._rowHeights[rowIndex] = Math.max(starHeight, maxChildHeight);
  4073. }
  4074. }
  4075. //get fixed and auto column widths
  4076. starIndexes.length = 0;
  4077. totalStars = 0;
  4078. for (var i_5 = 0; i_5 < cl; i_5++) {
  4079. var column = this._columns[i_5];
  4080. if (column.widthType == GridDimensionDefinition.Auto) {
  4081. this._columnWidths[i_5] = this._getMaxChildWidthInColumn(i_5);
  4082. columnWidths += this._columnWidths[i_5];
  4083. }
  4084. else if (column.widthType == GridDimensionDefinition.Pixels) {
  4085. var maxChildWidth = this._getMaxChildWidthInColumn(i_5);
  4086. this._columnWidths[i_5] = Math.max(column.widthPixels, maxChildWidth);
  4087. columnWidths += this._columnWidths[i_5];
  4088. }
  4089. else if (column.widthType == GridDimensionDefinition.Stars) {
  4090. starIndexes.push(i_5);
  4091. totalStars += column.width;
  4092. }
  4093. }
  4094. //star column widths
  4095. if (starIndexes.length > 0) {
  4096. var remainingWidth = prim.contentArea.width - columnWidths;
  4097. for (var i_6 = 0; i_6 < starIndexes.length; i_6++) {
  4098. var columnIndex = starIndexes[i_6];
  4099. var starWidth = (this._columns[columnIndex].width / totalStars) * remainingWidth;
  4100. var maxChildWidth = this._getMaxChildWidthInColumn(i_6);
  4101. this._columnWidths[columnIndex] = Math.max(starWidth, maxChildWidth);
  4102. }
  4103. }
  4104. var y = 0;
  4105. this._rowBottoms[rl - 1] = y;
  4106. for (var i_7 = rl - 2; i_7 >= 0; i_7--) {
  4107. y += this._rowHeights[i_7 + 1];
  4108. this._rowBottoms[i_7] = y;
  4109. }
  4110. var x = 0;
  4111. this._columnLefts[0] = x;
  4112. for (var i_8 = 1; i_8 < cl; i_8++) {
  4113. x += this._columnWidths[i_8 - 1];
  4114. this._columnLefts[i_8] = x;
  4115. }
  4116. //remove duplicate references to children that span
  4117. if (childrenThatSpan) {
  4118. for (var i = 0; i < childrenThatSpan.length; i++) {
  4119. var child = childrenThatSpan[i];
  4120. var gd = child.layoutData;
  4121. for (var i_9 = gd.row; i_9 < gd.row + gd.rowSpan; i_9++) {
  4122. for (var j = gd.column; j < gd.column + gd.columnSpan; j++) {
  4123. if (i_9 == gd.row && j == gd.column) {
  4124. continue;
  4125. }
  4126. if (_children[i_9][j] == child) {
  4127. _children[i_9][j] = null;
  4128. }
  4129. }
  4130. }
  4131. }
  4132. }
  4133. };
  4134. return GridPanelLayoutEngine;
  4135. }(LayoutEngineBase));
  4136. GridPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  4137. GridPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  4138. GridPanelLayoutEngine.dstAreaPos = BABYLON.Vector2.Zero();
  4139. GridPanelLayoutEngine = GridPanelLayoutEngine_1 = __decorate([
  4140. BABYLON.className("GridPanelLayoutEngine", "BABYLON")
  4141. ], GridPanelLayoutEngine);
  4142. BABYLON.GridPanelLayoutEngine = GridPanelLayoutEngine;
  4143. var CanvasLayoutEngine_1, StackPanelLayoutEngine_1, GridPanelLayoutEngine_1;
  4144. })(BABYLON || (BABYLON = {}));
  4145. //# sourceMappingURL=babylon.canvas2dLayoutEngine.js.map
  4146. var __extends = (this && this.__extends) || function (d, b) {
  4147. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4148. function __() { this.constructor = d; }
  4149. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4150. };
  4151. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4152. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4153. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4154. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  4155. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4156. };
  4157. var BABYLON;
  4158. (function (BABYLON) {
  4159. /**
  4160. * Base class implementing the ILocable interface.
  4161. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  4162. */
  4163. var LockableBase = (function () {
  4164. function LockableBase() {
  4165. }
  4166. LockableBase.prototype.isLocked = function () {
  4167. return this._isLocked;
  4168. };
  4169. LockableBase.prototype.lock = function () {
  4170. if (this._isLocked) {
  4171. return true;
  4172. }
  4173. this.onLock();
  4174. this._isLocked = true;
  4175. return false;
  4176. };
  4177. /**
  4178. * Protected handler that will be called when the instance is about to be locked.
  4179. */
  4180. LockableBase.prototype.onLock = function () {
  4181. };
  4182. return LockableBase;
  4183. }());
  4184. BABYLON.LockableBase = LockableBase;
  4185. var SolidColorBrush2D = (function (_super) {
  4186. __extends(SolidColorBrush2D, _super);
  4187. function SolidColorBrush2D(color, lock) {
  4188. if (lock === void 0) { lock = false; }
  4189. var _this = _super.call(this) || this;
  4190. _this._color = color;
  4191. if (lock) {
  4192. {
  4193. _this.lock();
  4194. }
  4195. }
  4196. return _this;
  4197. }
  4198. /**
  4199. * Return true if the brush is transparent, false if it's totally opaque
  4200. */
  4201. SolidColorBrush2D.prototype.isTransparent = function () {
  4202. return this._color && this._color.a < 1.0;
  4203. };
  4204. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  4205. /**
  4206. * The color used by this instance to render
  4207. * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
  4208. */
  4209. get: function () {
  4210. return this._color;
  4211. },
  4212. set: function (value) {
  4213. if (this.isLocked()) {
  4214. return;
  4215. }
  4216. this._color = value;
  4217. },
  4218. enumerable: true,
  4219. configurable: true
  4220. });
  4221. /**
  4222. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  4223. */
  4224. SolidColorBrush2D.prototype.toString = function () {
  4225. return this._color.toHexString();
  4226. };
  4227. return SolidColorBrush2D;
  4228. }(LockableBase));
  4229. SolidColorBrush2D = __decorate([
  4230. BABYLON.className("SolidColorBrush2D", "BABYLON")
  4231. ], SolidColorBrush2D);
  4232. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  4233. var GradientColorBrush2D = (function (_super) {
  4234. __extends(GradientColorBrush2D, _super);
  4235. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  4236. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  4237. if (rotation === void 0) { rotation = 0; }
  4238. if (scale === void 0) { scale = 1; }
  4239. if (lock === void 0) { lock = false; }
  4240. var _this = _super.call(this) || this;
  4241. _this._color1 = color1;
  4242. _this._color2 = color2;
  4243. _this._translation = translation;
  4244. _this._rotation = rotation;
  4245. _this._scale = scale;
  4246. if (lock) {
  4247. _this.lock();
  4248. }
  4249. return _this;
  4250. }
  4251. /**
  4252. * Return true if the brush is transparent, false if it's totally opaque
  4253. */
  4254. GradientColorBrush2D.prototype.isTransparent = function () {
  4255. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  4256. };
  4257. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  4258. /**
  4259. * First color, the blend will start from this color
  4260. */
  4261. get: function () {
  4262. return this._color1;
  4263. },
  4264. set: function (value) {
  4265. if (this.isLocked()) {
  4266. return;
  4267. }
  4268. this._color1 = value;
  4269. },
  4270. enumerable: true,
  4271. configurable: true
  4272. });
  4273. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  4274. /**
  4275. * Second color, the blend will end to this color
  4276. */
  4277. get: function () {
  4278. return this._color2;
  4279. },
  4280. set: function (value) {
  4281. if (this.isLocked()) {
  4282. return;
  4283. }
  4284. this._color2 = value;
  4285. },
  4286. enumerable: true,
  4287. configurable: true
  4288. });
  4289. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  4290. /**
  4291. * Translation vector to apply on the blend
  4292. * Default is [0;0]
  4293. */
  4294. get: function () {
  4295. return this._translation;
  4296. },
  4297. set: function (value) {
  4298. if (this.isLocked()) {
  4299. return;
  4300. }
  4301. this._translation = value;
  4302. },
  4303. enumerable: true,
  4304. configurable: true
  4305. });
  4306. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  4307. /**
  4308. * Rotation in radian to apply to the brush
  4309. * Default direction of the brush is vertical, you can change this using this property.
  4310. * Default is 0.
  4311. */
  4312. get: function () {
  4313. return this._rotation;
  4314. },
  4315. set: function (value) {
  4316. if (this.isLocked()) {
  4317. return;
  4318. }
  4319. this._rotation = value;
  4320. },
  4321. enumerable: true,
  4322. configurable: true
  4323. });
  4324. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  4325. /**
  4326. * Scale factor to apply to the gradient.
  4327. * Default is 1: no scale.
  4328. */
  4329. get: function () {
  4330. return this._scale;
  4331. },
  4332. set: function (value) {
  4333. if (this.isLocked()) {
  4334. return;
  4335. }
  4336. this._scale = value;
  4337. },
  4338. enumerable: true,
  4339. configurable: true
  4340. });
  4341. /**
  4342. * Return a string describing the brush
  4343. */
  4344. GradientColorBrush2D.prototype.toString = function () {
  4345. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  4346. };
  4347. /**
  4348. * Build a unique key string for the given parameters
  4349. */
  4350. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  4351. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  4352. };
  4353. return GradientColorBrush2D;
  4354. }(LockableBase));
  4355. GradientColorBrush2D = __decorate([
  4356. BABYLON.className("GradientColorBrush2D", "BABYLON")
  4357. ], GradientColorBrush2D);
  4358. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  4359. })(BABYLON || (BABYLON = {}));
  4360. //# sourceMappingURL=babylon.brushes2d.js.map
  4361. var __extends = (this && this.__extends) || function (d, b) {
  4362. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4363. function __() { this.constructor = d; }
  4364. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4365. };
  4366. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4367. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4368. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4369. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  4370. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4371. };
  4372. var BABYLON;
  4373. (function (BABYLON) {
  4374. var Prim2DClassInfo = (function () {
  4375. function Prim2DClassInfo() {
  4376. }
  4377. return Prim2DClassInfo;
  4378. }());
  4379. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  4380. var Prim2DPropInfo = (function () {
  4381. function Prim2DPropInfo() {
  4382. }
  4383. return Prim2DPropInfo;
  4384. }());
  4385. Prim2DPropInfo.PROPKIND_MODEL = 1;
  4386. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  4387. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  4388. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  4389. var ClassTreeInfo = (function () {
  4390. function ClassTreeInfo(baseClass, type, classContentFactory) {
  4391. this._baseClass = baseClass;
  4392. this._type = type;
  4393. this._subClasses = new Array();
  4394. this._levelContent = new BABYLON.StringDictionary();
  4395. this._classContentFactory = classContentFactory;
  4396. }
  4397. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  4398. get: function () {
  4399. if (!this._classContent) {
  4400. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  4401. }
  4402. return this._classContent;
  4403. },
  4404. enumerable: true,
  4405. configurable: true
  4406. });
  4407. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  4408. get: function () {
  4409. return this._type;
  4410. },
  4411. enumerable: true,
  4412. configurable: true
  4413. });
  4414. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  4415. get: function () {
  4416. return this._levelContent;
  4417. },
  4418. enumerable: true,
  4419. configurable: true
  4420. });
  4421. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  4422. get: function () {
  4423. if (!this._fullContent) {
  4424. var dic_1 = new BABYLON.StringDictionary();
  4425. var curLevel = this;
  4426. while (curLevel) {
  4427. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  4428. curLevel = curLevel._baseClass;
  4429. }
  4430. this._fullContent = dic_1;
  4431. }
  4432. return this._fullContent;
  4433. },
  4434. enumerable: true,
  4435. configurable: true
  4436. });
  4437. ClassTreeInfo.prototype.getLevelOf = function (type) {
  4438. // Are we already there?
  4439. if (type === this._type) {
  4440. return this;
  4441. }
  4442. var baseProto = Object.getPrototypeOf(type);
  4443. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  4444. if (!curProtoContent) {
  4445. this.getLevelOf(baseProto);
  4446. }
  4447. return this.getOrAddType(baseProto, type);
  4448. };
  4449. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  4450. // Are we at the level corresponding to the baseType?
  4451. // If so, get or add the level we're looking for
  4452. if (baseType === this._type) {
  4453. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  4454. var subType = _a[_i];
  4455. if (subType.type === type) {
  4456. return subType.node;
  4457. }
  4458. }
  4459. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  4460. var info = { type: type, node: node };
  4461. this._subClasses.push(info);
  4462. return info.node;
  4463. }
  4464. // Recurse down to keep looking for the node corresponding to the baseTypeName
  4465. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  4466. var subType = _c[_b];
  4467. var info = subType.node.getOrAddType(baseType, type);
  4468. if (info) {
  4469. return info;
  4470. }
  4471. }
  4472. return null;
  4473. };
  4474. ClassTreeInfo.get = function (type) {
  4475. var dic = type["__classTreeInfo"];
  4476. if (!dic) {
  4477. return null;
  4478. }
  4479. return dic.getLevelOf(type);
  4480. };
  4481. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  4482. var dic = type["__classTreeInfo"];
  4483. if (!dic) {
  4484. dic = new ClassTreeInfo(null, type, classContentFactory);
  4485. type["__classTreeInfo"] = dic;
  4486. }
  4487. return dic;
  4488. };
  4489. return ClassTreeInfo;
  4490. }());
  4491. BABYLON.ClassTreeInfo = ClassTreeInfo;
  4492. var DataBinding = DataBinding_1 = (function () {
  4493. function DataBinding() {
  4494. this._converter = null;
  4495. this._mode = DataBinding_1.MODE_DEFAULT;
  4496. this._uiElementId = null;
  4497. this._dataSource = null;
  4498. this._currentDataSource = null;
  4499. this._propertyPathName = null;
  4500. this._stringFormat = null;
  4501. this._updateSourceTrigger = DataBinding_1.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  4502. this._boundTo = null;
  4503. this._owner = null;
  4504. this._updateCounter = 0;
  4505. }
  4506. Object.defineProperty(DataBinding.prototype, "converter", {
  4507. /**
  4508. * Provide a callback that will convert the value obtained by the Data Binding to the type of the SmartProperty it's bound to.
  4509. * If no value are set, then it's assumed that the sourceValue is of the same type as the SmartProperty's one.
  4510. * If the SmartProperty type is a basic data type (string, boolean or number) and no converter is specified but the sourceValue is of a different type, the conversion will be implicitly made, if possible.
  4511. * @param sourceValue the source object retrieve by the Data Binding mechanism
  4512. * @returns the object of a compatible type with the SmartProperty it's bound to
  4513. */
  4514. get: function () {
  4515. return this._converter;
  4516. },
  4517. set: function (value) {
  4518. if (this._converter === value) {
  4519. return;
  4520. }
  4521. this._converter = value;
  4522. },
  4523. enumerable: true,
  4524. configurable: true
  4525. });
  4526. Object.defineProperty(DataBinding.prototype, "mode", {
  4527. /**
  4528. * Set the mode to use for the data flow in the binding. Set one of the MODE_xxx static member of this class. If not specified then MODE_DEFAULT will be used
  4529. */
  4530. get: function () {
  4531. if (this._mode === DataBinding_1.MODE_DEFAULT) {
  4532. return this._boundTo.bindingMode;
  4533. }
  4534. return this._mode;
  4535. },
  4536. set: function (value) {
  4537. if (this._mode === value) {
  4538. return;
  4539. }
  4540. this._mode = value;
  4541. },
  4542. enumerable: true,
  4543. configurable: true
  4544. });
  4545. Object.defineProperty(DataBinding.prototype, "uiElementId", {
  4546. /**
  4547. * You can override the Data Source object with this member which is the Id of a uiElement existing in the UI Logical tree.
  4548. * If not set and source no set too, then the dataSource property will be used.
  4549. */
  4550. get: function () {
  4551. return this._uiElementId;
  4552. },
  4553. set: function (value) {
  4554. if (this._uiElementId === value) {
  4555. return;
  4556. }
  4557. this._uiElementId = value;
  4558. },
  4559. enumerable: true,
  4560. configurable: true
  4561. });
  4562. Object.defineProperty(DataBinding.prototype, "dataSource", {
  4563. /**
  4564. * You can override the Data Source object with this member which is the source object to use directly.
  4565. * If not set and uiElement no set too, then the dataSource property of the SmartPropertyBase object will be used.
  4566. */
  4567. get: function () {
  4568. return this._dataSource;
  4569. },
  4570. set: function (value) {
  4571. if (this._dataSource === value) {
  4572. return;
  4573. }
  4574. this._dataSource = value;
  4575. },
  4576. enumerable: true,
  4577. configurable: true
  4578. });
  4579. Object.defineProperty(DataBinding.prototype, "propertyPathName", {
  4580. /**
  4581. * The path & name of the property to get from the source object.
  4582. * Once the Source object is evaluated (it's either the one got from uiElementId, source or dataSource) you can specify which property of this object is the value to bind to the smartProperty.
  4583. * If nothing is set then the source object will be used.
  4584. * You can specify an indirect property using the format "firstProperty.indirectProperty" like "address.postalCode" if the source is a Customer object which contains an address property and the Address class contains a postalCode property.
  4585. * If the property is an Array and you want to address a particular element then use the 'arrayProperty[index]' notation. For example "phoneNumbers[0]" to get the first element of the phoneNumber property which is an array.
  4586. */
  4587. get: function () {
  4588. return this._propertyPathName;
  4589. },
  4590. set: function (value) {
  4591. if (this._propertyPathName === value) {
  4592. return;
  4593. }
  4594. if (this._owner) {
  4595. }
  4596. this._propertyPathName = value;
  4597. if (this._owner) {
  4598. }
  4599. },
  4600. enumerable: true,
  4601. configurable: true
  4602. });
  4603. Object.defineProperty(DataBinding.prototype, "stringFormat", {
  4604. /**
  4605. * If the Smart Property is of the string type, you can use the string interpolation notation to provide how the sourceValue will be formatted, reference to the source value must be made via the token: ${value}. For instance `Customer Name: ${value}`
  4606. */
  4607. get: function () {
  4608. return this._stringFormat;
  4609. },
  4610. set: function (value) {
  4611. if (this._stringFormat === value) {
  4612. return;
  4613. }
  4614. this._stringFormat = value;
  4615. },
  4616. enumerable: true,
  4617. configurable: true
  4618. });
  4619. Object.defineProperty(DataBinding.prototype, "updateSourceTrigger", {
  4620. /**
  4621. * Specify how the source should be updated, use one of the UPDATESOURCETRIGGER_xxx member of this class, if not specified then UPDATESOURCETRIGGER_DEFAULT will be used.
  4622. */
  4623. get: function () {
  4624. return this._updateSourceTrigger;
  4625. },
  4626. set: function (value) {
  4627. if (this._updateSourceTrigger === value) {
  4628. return;
  4629. }
  4630. this._updateSourceTrigger = value;
  4631. },
  4632. enumerable: true,
  4633. configurable: true
  4634. });
  4635. DataBinding.prototype.canUpdateTarget = function (resetUpdateCounter) {
  4636. if (resetUpdateCounter) {
  4637. this._updateCounter = 0;
  4638. }
  4639. var mode = this.mode;
  4640. if (mode === DataBinding_1.MODE_ONETIME) {
  4641. return this._updateCounter === 0;
  4642. }
  4643. if (mode === DataBinding_1.MODE_ONEWAYTOSOURCE) {
  4644. return false;
  4645. }
  4646. return true;
  4647. };
  4648. DataBinding.prototype.updateTarget = function () {
  4649. var value = this._getActualDataSource();
  4650. var properties = this.propertyPathName.split(".");
  4651. for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
  4652. var propertyName = properties_1[_i];
  4653. value = value[propertyName];
  4654. }
  4655. this._storeBoundValue(this._owner, value);
  4656. };
  4657. DataBinding.prototype._storeBoundValue = function (watcher, value) {
  4658. if ((++this._updateCounter > 1) && (this.mode === DataBinding_1.MODE_ONETIME)) {
  4659. return;
  4660. }
  4661. var newValue = value;
  4662. if (this._converter) {
  4663. newValue = this._converter(value);
  4664. }
  4665. if (this._stringFormat) {
  4666. newValue = this._stringFormat(newValue);
  4667. }
  4668. watcher[this._boundTo.name] = newValue;
  4669. };
  4670. DataBinding.prototype._getActualDataSource = function () {
  4671. if (this.dataSource) {
  4672. return this.dataSource;
  4673. }
  4674. if (this.uiElementId) {
  4675. // TODO Find UIElement
  4676. return null;
  4677. }
  4678. return this._owner.dataSource;
  4679. };
  4680. DataBinding.prototype._registerDataSource = function (updateTarget) {
  4681. var ds = this._getActualDataSource();
  4682. if (ds === this._currentDataSource) {
  4683. return;
  4684. }
  4685. if (this._currentDataSource) {
  4686. BindingHelper.unregisterDataSource(this._currentDataSource, this, 0);
  4687. }
  4688. if (ds) {
  4689. BindingHelper.registerDataSource(ds, this);
  4690. if (updateTarget && this.canUpdateTarget(true)) {
  4691. this.updateTarget();
  4692. }
  4693. }
  4694. this._currentDataSource = ds;
  4695. };
  4696. DataBinding.prototype._unregisterDataSource = function () {
  4697. var ds = this._getActualDataSource();
  4698. if (ds) {
  4699. BindingHelper.unregisterDataSource(ds, this, 0);
  4700. }
  4701. };
  4702. return DataBinding;
  4703. }());
  4704. /**
  4705. * Use the mode specified in the SmartProperty declaration
  4706. */
  4707. DataBinding.MODE_DEFAULT = 1;
  4708. /**
  4709. * Update the binding target only once when the Smart Property's value is first accessed
  4710. */
  4711. DataBinding.MODE_ONETIME = 2;
  4712. /**
  4713. * Update the smart property when the source changes.
  4714. * The source won't be updated if the smart property value is set.
  4715. */
  4716. DataBinding.MODE_ONEWAY = 3;
  4717. /**
  4718. * Only update the source when the target's data is changing.
  4719. */
  4720. DataBinding.MODE_ONEWAYTOSOURCE = 4;
  4721. /**
  4722. * Update the bind target when the source changes and update the source when the Smart Property value is set.
  4723. */
  4724. DataBinding.MODE_TWOWAY = 5;
  4725. /**
  4726. * Use the Update Source Trigger defined in the SmartProperty declaration
  4727. */
  4728. DataBinding.UPDATESOURCETRIGGER_DEFAULT = 1;
  4729. /**
  4730. * Update the source as soon as the Smart Property has a value change
  4731. */
  4732. DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED = 2;
  4733. /**
  4734. * Update the source when the binding target loses focus
  4735. */
  4736. DataBinding.UPDATESOURCETRIGGER_LOSTFOCUS = 3;
  4737. /**
  4738. * Update the source will be made by explicitly calling the UpdateFromDataSource method
  4739. */
  4740. DataBinding.UPDATESOURCETRIGGER_EXPLICIT = 4;
  4741. DataBinding = DataBinding_1 = __decorate([
  4742. BABYLON.className("DataBinding", "BABYLON")
  4743. ], DataBinding);
  4744. BABYLON.DataBinding = DataBinding;
  4745. var SmartPropertyBase = SmartPropertyBase_1 = (function (_super) {
  4746. __extends(SmartPropertyBase, _super);
  4747. function SmartPropertyBase() {
  4748. var _this = _super.call(this) || this;
  4749. _this._dataSource = null;
  4750. _this._dataSourceObserver = null;
  4751. _this._instanceDirtyFlags = 0;
  4752. _this._isDisposed = false;
  4753. _this._bindings = null;
  4754. _this._hasBinding = 0;
  4755. _this._bindingSourceChanged = 0;
  4756. _this._disposeObservable = null;
  4757. return _this;
  4758. }
  4759. Object.defineProperty(SmartPropertyBase.prototype, "disposeObservable", {
  4760. get: function () {
  4761. if (!this._disposeObservable) {
  4762. this._disposeObservable = new BABYLON.Observable();
  4763. }
  4764. return this._disposeObservable;
  4765. },
  4766. enumerable: true,
  4767. configurable: true
  4768. });
  4769. Object.defineProperty(SmartPropertyBase.prototype, "isDisposed", {
  4770. /**
  4771. * Check if the object is disposed or not.
  4772. * @returns true if the object is dispose, false otherwise.
  4773. */
  4774. get: function () {
  4775. return this._isDisposed;
  4776. },
  4777. enumerable: true,
  4778. configurable: true
  4779. });
  4780. /**
  4781. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  4782. * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
  4783. */
  4784. SmartPropertyBase.prototype.dispose = function () {
  4785. if (this.isDisposed) {
  4786. return false;
  4787. }
  4788. if (this._disposeObservable && this._disposeObservable.hasObservers()) {
  4789. this._disposeObservable.notifyObservers(this);
  4790. }
  4791. this._isDisposed = true;
  4792. return true;
  4793. };
  4794. /**
  4795. * Check if a given set of properties are dirty or not.
  4796. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  4797. * @return true if at least one property is dirty, false if none of them are.
  4798. */
  4799. SmartPropertyBase.prototype.checkPropertiesDirty = function (flags) {
  4800. return (this._instanceDirtyFlags & flags) !== 0;
  4801. };
  4802. /**
  4803. * Clear a given set of properties.
  4804. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  4805. * @return the new set of property still marked as dirty
  4806. */
  4807. SmartPropertyBase.prototype.clearPropertiesDirty = function (flags) {
  4808. this._instanceDirtyFlags &= ~flags;
  4809. return this._instanceDirtyFlags;
  4810. };
  4811. SmartPropertyBase.prototype._resetPropertiesDirty = function () {
  4812. this._instanceDirtyFlags = 0;
  4813. };
  4814. /**
  4815. * Add an externally attached data from its key.
  4816. * This method call will fail and return false, if such key already exists.
  4817. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  4818. * @param key the unique key that identifies the data
  4819. * @param data the data object to associate to the key for this Engine instance
  4820. * @return true if no such key were already present and the data was added successfully, false otherwise
  4821. */
  4822. SmartPropertyBase.prototype.addExternalData = function (key, data) {
  4823. if (!this._externalData) {
  4824. this._externalData = new BABYLON.StringDictionary();
  4825. }
  4826. return this._externalData.add(key, data);
  4827. };
  4828. /**
  4829. * Get an externally attached data from its key
  4830. * @param key the unique key that identifies the data
  4831. * @return the associated data, if present (can be null), or undefined if not present
  4832. */
  4833. SmartPropertyBase.prototype.getExternalData = function (key) {
  4834. if (!this._externalData) {
  4835. return null;
  4836. }
  4837. return this._externalData.get(key);
  4838. };
  4839. /**
  4840. * Get an externally attached data from its key, create it using a factory if it's not already present
  4841. * @param key the unique key that identifies the data
  4842. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  4843. * @return the associated data, can be null if the factory returned null.
  4844. */
  4845. SmartPropertyBase.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  4846. if (!this._externalData) {
  4847. this._externalData = new BABYLON.StringDictionary();
  4848. }
  4849. return this._externalData.getOrAddWithFactory(key, factory);
  4850. };
  4851. /**
  4852. * Remove an externally attached data from the Engine instance
  4853. * @param key the unique key that identifies the data
  4854. * @return true if the data was successfully removed, false if it doesn't exist
  4855. */
  4856. SmartPropertyBase.prototype.removeExternalData = function (key) {
  4857. if (!this._externalData) {
  4858. return false;
  4859. }
  4860. return this._externalData.remove(key);
  4861. };
  4862. SmartPropertyBase._hookProperty = function (propId, piStore, kind, settings) {
  4863. return function (target, propName, descriptor) {
  4864. if (!settings) {
  4865. settings = {};
  4866. }
  4867. var propInfo = SmartPropertyBase_1._createPropInfo(target, propName, propId, kind, settings);
  4868. if (piStore) {
  4869. piStore(propInfo);
  4870. }
  4871. var getter = descriptor.get, setter = descriptor.set;
  4872. var typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  4873. // Overload the property setter implementation to add our own logic
  4874. descriptor.set = function (val) {
  4875. if (!setter) {
  4876. throw Error("Property '" + propInfo.name + "' of type '" + BABYLON.Tools.getFullClassName(this) + "' has no setter defined but was invoked as if it had one.");
  4877. }
  4878. // check for disposed first, do nothing
  4879. if (this.isDisposed) {
  4880. return;
  4881. }
  4882. var curVal = getter.call(this);
  4883. if (SmartPropertyBase_1._checkUnchanged(curVal, val)) {
  4884. return;
  4885. }
  4886. // Cast the object we're working one
  4887. var prim = this;
  4888. // Change the value
  4889. setter.call(this, val);
  4890. // Notify change, dirty flags update
  4891. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  4892. };
  4893. };
  4894. };
  4895. SmartPropertyBase._createPropInfo = function (target, propName, propId, kind, settings) {
  4896. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  4897. var node = dic.getLevelOf(target);
  4898. var propInfo = node.levelContent.get(propId.toString());
  4899. if (propInfo) {
  4900. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  4901. }
  4902. // Create, setup and add the PropInfo object to our prop dictionary
  4903. propInfo = new Prim2DPropInfo();
  4904. propInfo.id = propId;
  4905. propInfo.flagId = Math.pow(2, propId);
  4906. propInfo.kind = kind;
  4907. propInfo.name = propName;
  4908. propInfo.bindingMode = (settings.bindingMode !== undefined) ? settings.bindingMode : DataBinding.MODE_TWOWAY;
  4909. propInfo.bindingUpdateSourceTrigger = (settings.bindingUpdateSourceTrigger !== undefined) ? settings.bindingUpdateSourceTrigger : DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  4910. propInfo.dirtyBoundingInfo = (settings.dirtyBoundingInfo !== undefined) ? settings.dirtyBoundingInfo : false;
  4911. propInfo.dirtyParentBoundingInfo = (settings.dirtyParentBoundingBox !== undefined) ? settings.dirtyParentBoundingBox : false;
  4912. propInfo.typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  4913. node.levelContent.add(propName, propInfo);
  4914. return propInfo;
  4915. };
  4916. Object.defineProperty(SmartPropertyBase.prototype, "propDic", {
  4917. /**
  4918. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  4919. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  4920. */
  4921. get: function () {
  4922. if (!this._propInfo) {
  4923. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  4924. if (!cti) {
  4925. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  4926. }
  4927. this._propInfo = cti.fullContent;
  4928. }
  4929. return this._propInfo;
  4930. },
  4931. enumerable: true,
  4932. configurable: true
  4933. });
  4934. SmartPropertyBase._checkUnchanged = function (curValue, newValue) {
  4935. // Nothing to nothing: nothing to do!
  4936. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  4937. return true;
  4938. }
  4939. // Check value unchanged
  4940. if ((curValue != null) && (newValue != null)) {
  4941. if (typeof (curValue.equals) == "function") {
  4942. if (curValue.equals(newValue)) {
  4943. return true;
  4944. }
  4945. }
  4946. else {
  4947. if (curValue === newValue) {
  4948. return true;
  4949. }
  4950. }
  4951. }
  4952. return false;
  4953. };
  4954. SmartPropertyBase.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  4955. // Trigger property changed
  4956. var info = SmartPropertyBase_1.propChangeGuarding ? new BABYLON.PropertyChangedInfo() : SmartPropertyPrim.propChangedInfo;
  4957. info.oldValue = curValue;
  4958. info.newValue = newValue;
  4959. info.propertyName = propName;
  4960. var propMask = propInfo ? propInfo.flagId : -1;
  4961. try {
  4962. SmartPropertyBase_1.propChangeGuarding = true;
  4963. this.propertyChanged.notifyObservers(info, propMask);
  4964. }
  4965. finally {
  4966. SmartPropertyBase_1.propChangeGuarding = false;
  4967. }
  4968. };
  4969. SmartPropertyBase.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  4970. if (this.isDisposed) {
  4971. return;
  4972. }
  4973. if (!propInfo) {
  4974. return;
  4975. }
  4976. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  4977. };
  4978. Object.defineProperty(SmartPropertyBase.prototype, "dataSource", {
  4979. /**
  4980. * Set the object from which Smart Properties using Binding will take/update their data from/to.
  4981. * When the object is part of a graph (with parent/children relationship) if the dataSource of a given instance is not specified, then the parent's one is used.
  4982. */
  4983. get: function () {
  4984. // Don't access to _dataSource directly but via a call to the _getDataSource method which can be overloaded in inherited classes
  4985. return this._getDataSource();
  4986. },
  4987. set: function (value) {
  4988. if (this._dataSource === value) {
  4989. return;
  4990. }
  4991. var oldValue = this._dataSource;
  4992. this._dataSource = value;
  4993. if (this._bindings && value != null) {
  4994. // Register the bindings
  4995. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  4996. var binding = _a[_i];
  4997. if (binding != null) {
  4998. binding._registerDataSource(true);
  4999. }
  5000. }
  5001. }
  5002. this.onPropertyChanged("dataSource", oldValue, value);
  5003. },
  5004. enumerable: true,
  5005. configurable: true
  5006. });
  5007. // Inheriting classes can overload this method to provides additional logic for dataSource access
  5008. SmartPropertyBase.prototype._getDataSource = function () {
  5009. return this._dataSource;
  5010. };
  5011. SmartPropertyBase.prototype.createSimpleDataBinding = function (propInfo, propertyPathName, mode) {
  5012. if (mode === void 0) { mode = DataBinding.MODE_DEFAULT; }
  5013. var binding = new DataBinding();
  5014. binding.propertyPathName = propertyPathName;
  5015. binding.mode = mode;
  5016. return this.createDataBinding(propInfo, binding);
  5017. };
  5018. SmartPropertyBase.prototype.createDataBinding = function (propInfo, binding) {
  5019. if (!this._bindings) {
  5020. this._bindings = new Array();
  5021. }
  5022. if (!binding || binding._owner != null) {
  5023. throw Error("A valid/unused Binding must be passed.");
  5024. }
  5025. // Unregister a potentially existing binding for this property
  5026. this.removeDataBinding(propInfo);
  5027. // register the binding
  5028. binding._owner = this;
  5029. binding._boundTo = propInfo;
  5030. this._bindings[propInfo.id] = binding;
  5031. this._hasBinding |= propInfo.flagId;
  5032. binding._registerDataSource(true);
  5033. return binding;
  5034. };
  5035. SmartPropertyBase.prototype.removeDataBinding = function (propInfo) {
  5036. if ((this._hasBinding & propInfo.flagId) === 0) {
  5037. return false;
  5038. }
  5039. var curBinding = this._bindings[propInfo.id];
  5040. curBinding._unregisterDataSource();
  5041. this._bindings[propInfo.id] = null;
  5042. this._hasBinding &= ~propInfo.flagId;
  5043. return true;
  5044. };
  5045. SmartPropertyBase.prototype.updateFromDataSource = function () {
  5046. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  5047. var binding = _a[_i];
  5048. if (binding) {
  5049. }
  5050. }
  5051. };
  5052. return SmartPropertyBase;
  5053. }(BABYLON.PropertyChangedBase));
  5054. SmartPropertyBase.propChangedInfo = new BABYLON.PropertyChangedInfo();
  5055. SmartPropertyBase.propChangeGuarding = false;
  5056. SmartPropertyBase = SmartPropertyBase_1 = __decorate([
  5057. BABYLON.className("SmartPropertyBase", "BABYLON")
  5058. ], SmartPropertyBase);
  5059. BABYLON.SmartPropertyBase = SmartPropertyBase;
  5060. var BindingInfo = (function () {
  5061. function BindingInfo(binding, level, isLast) {
  5062. this.binding = binding;
  5063. this.level = level;
  5064. this.isLast = isLast;
  5065. }
  5066. return BindingInfo;
  5067. }());
  5068. var MonitoredObjectData = (function () {
  5069. function MonitoredObjectData(monitoredObject) {
  5070. var _this = this;
  5071. this.monitoredObject = monitoredObject;
  5072. this.monitoredIntermediateProperties = new BABYLON.StringDictionary();
  5073. this.observer = this.monitoredObject.propertyChanged.add(function (e, s) { _this.propertyChangedHandler(e.propertyName, e.oldValue, e.newValue); });
  5074. this.boundProperties = new BABYLON.StringDictionary();
  5075. this.monitoredIntermediateMask = 0;
  5076. this.boundPropertiesMask = 0;
  5077. }
  5078. MonitoredObjectData.prototype.propertyChangedHandler = function (propName, oldValue, newValue) {
  5079. var propId = BindingHelper._getPropertyID(this.monitoredObject, propName);
  5080. var propIdStr = propId.toString();
  5081. // Loop through all the registered bindings for this property that had a value change
  5082. if ((this.boundPropertiesMask & propId) !== 0) {
  5083. var bindingInfos = this.boundProperties.get(propIdStr);
  5084. for (var _i = 0, bindingInfos_1 = bindingInfos; _i < bindingInfos_1.length; _i++) {
  5085. var bi = bindingInfos_1[_i];
  5086. if (!bi.isLast) {
  5087. BindingHelper.unregisterDataSource(this.monitoredObject, bi.binding, bi.level);
  5088. BindingHelper.registerDataSource(bi.binding._currentDataSource, bi.binding);
  5089. }
  5090. if (bi.binding.canUpdateTarget(false)) {
  5091. bi.binding.updateTarget();
  5092. }
  5093. }
  5094. }
  5095. };
  5096. return MonitoredObjectData;
  5097. }());
  5098. var BindingHelper = (function () {
  5099. function BindingHelper() {
  5100. }
  5101. BindingHelper.registerDataSource = function (dataSource, binding) {
  5102. var properties = binding.propertyPathName.split(".");
  5103. var ownerMod = null;
  5104. var ownerInterPropId = 0;
  5105. var propertyOwner = dataSource;
  5106. var _loop_1 = function (i) {
  5107. var propName = properties[i];
  5108. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  5109. var propIdStr = propId.toString();
  5110. var mod = void 0;
  5111. if (ownerMod) {
  5112. var o_1 = ownerMod;
  5113. var po_1 = propertyOwner;
  5114. var oii_1 = ownerInterPropId;
  5115. mod = ownerMod.monitoredIntermediateProperties.getOrAddWithFactory(oii_1.toString(), function (k) {
  5116. o_1.monitoredIntermediateMask |= oii_1;
  5117. return BindingHelper._getMonitoredObjectData(po_1);
  5118. });
  5119. }
  5120. else {
  5121. mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  5122. }
  5123. var m = mod;
  5124. var bindingInfos = mod.boundProperties.getOrAddWithFactory(propIdStr, function (k) {
  5125. m.boundPropertiesMask |= propId;
  5126. return new Array();
  5127. });
  5128. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  5129. if (!bi) {
  5130. bindingInfos.push(new BindingInfo(binding, i, (i + 1) === properties.length));
  5131. }
  5132. ownerMod = mod;
  5133. ownerInterPropId = propId;
  5134. propertyOwner = propertyOwner[propName];
  5135. };
  5136. for (var i = 0; i < properties.length; i++) {
  5137. _loop_1(i);
  5138. }
  5139. };
  5140. BindingHelper.unregisterDataSource = function (dataSource, binding, level) {
  5141. var properties = binding.propertyPathName.split(".");
  5142. var propertyOwner = dataSource;
  5143. var mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  5144. for (var i = 0; i < properties.length; i++) {
  5145. var propName = properties[i];
  5146. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  5147. var propIdStr = propId.toString();
  5148. if (i >= level) {
  5149. mod = BindingHelper._unregisterBinding(mod, propId, binding);
  5150. }
  5151. else {
  5152. mod = mod.monitoredIntermediateProperties.get(propIdStr);
  5153. }
  5154. propertyOwner = propertyOwner[propName];
  5155. }
  5156. };
  5157. BindingHelper._unregisterBinding = function (mod, propertyID, binding) {
  5158. var propertyIDStr = propertyID.toString();
  5159. var res = null;
  5160. // Check if the property is registered as an intermediate and remove it
  5161. if ((mod.monitoredIntermediateMask & propertyID) !== 0) {
  5162. res = mod.monitoredIntermediateProperties.get(propertyIDStr);
  5163. mod.monitoredIntermediateProperties.remove(propertyIDStr);
  5164. // Update the mask
  5165. mod.monitoredIntermediateMask &= ~propertyID;
  5166. }
  5167. // Check if the property is registered as a final property and remove it
  5168. if ((mod.boundPropertiesMask & propertyID) !== 0) {
  5169. var bindingInfos = mod.boundProperties.get(propertyIDStr);
  5170. // Find the binding and remove it
  5171. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  5172. if (bi) {
  5173. var bii = bindingInfos.indexOf(bi);
  5174. bindingInfos.splice(bii, 1);
  5175. }
  5176. // If the array is empty, update the mask
  5177. if (bindingInfos.length === 0) {
  5178. mod.boundPropertiesMask &= ~propertyID;
  5179. }
  5180. }
  5181. // Check if the MOD is empty and unregister the observer and remove it from the list of MODs
  5182. if (mod.boundPropertiesMask === 0 && mod.monitoredIntermediateMask === 0) {
  5183. // Unregister the observer on Property Change
  5184. mod.monitoredObject.propertyChanged.remove(mod.observer);
  5185. // Remove the MOD from the dic
  5186. var objectId = BindingHelper._getObjectId(mod.monitoredObject);
  5187. BindingHelper._monitoredObjects.remove(objectId);
  5188. }
  5189. return res;
  5190. };
  5191. BindingHelper._getMonitoredObjectData = function (object) {
  5192. var objectId = BindingHelper._getObjectId(object);
  5193. var mod = BindingHelper._monitoredObjects.getOrAddWithFactory(objectId, function (k) { return new MonitoredObjectData(object); });
  5194. return mod;
  5195. };
  5196. BindingHelper._getObjectId = function (obj) {
  5197. var id = obj["__bindingHelperObjectId__"];
  5198. if (id == null) {
  5199. id = BABYLON.Tools.RandomId();
  5200. obj["__bindingHelperObjectId__"] = id;
  5201. return id;
  5202. }
  5203. return id;
  5204. };
  5205. BindingHelper._getObjectTypePropertyIDs = function (obj) {
  5206. var fullName = BABYLON.Tools.getFullClassName(obj);
  5207. if (!fullName) {
  5208. throw Error("Types involved in Data Binding must be decorated with the @className decorator");
  5209. }
  5210. var d = BindingHelper._propertiesID.getOrAddWithFactory(fullName, function () { return new BABYLON.StringDictionary(); });
  5211. return d;
  5212. };
  5213. BindingHelper._getPropertyID = function (object, propName) {
  5214. var otd = BindingHelper._getObjectTypePropertyIDs(object);
  5215. // Make sure we have a WatchedPropertyData for this property of this object type. This will contains the flagIg of the watched property.
  5216. // We use this flagId to flag for each watched instance which properties are watched, as final or intermediate and which directions are used
  5217. var propData = otd.getOrAddWithFactory(propName, function (k) { return 1 << otd.count; });
  5218. return propData;
  5219. };
  5220. return BindingHelper;
  5221. }());
  5222. BindingHelper._propertiesID = new BABYLON.StringDictionary();
  5223. BindingHelper._monitoredObjects = new BABYLON.StringDictionary();
  5224. var SmartPropertyPrim = SmartPropertyPrim_1 = (function (_super) {
  5225. __extends(SmartPropertyPrim, _super);
  5226. function SmartPropertyPrim() {
  5227. var _this = _super.call(this) || this;
  5228. _this._flags = 0;
  5229. _this._uid = null;
  5230. _this._modelKey = null;
  5231. _this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  5232. _this._boundingInfo = new BABYLON.BoundingInfo2D();
  5233. _this.animations = new Array();
  5234. return _this;
  5235. }
  5236. /**
  5237. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  5238. * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
  5239. */
  5240. SmartPropertyPrim.prototype.dispose = function () {
  5241. if (this.isDisposed) {
  5242. return false;
  5243. }
  5244. _super.prototype.dispose.call(this);
  5245. // Don't set to null, it may upset somebody...
  5246. this.animations.splice(0);
  5247. return true;
  5248. };
  5249. Object.defineProperty(SmartPropertyPrim.prototype, "uid", {
  5250. /**
  5251. * return a unique identifier for the Canvas2D
  5252. */
  5253. get: function () {
  5254. if (!this._uid) {
  5255. this._uid = BABYLON.Tools.RandomId();
  5256. }
  5257. return this._uid;
  5258. },
  5259. enumerable: true,
  5260. configurable: true
  5261. });
  5262. /**
  5263. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  5264. * Look at Sprite2D for more information
  5265. */
  5266. SmartPropertyPrim.prototype.getAnimatables = function () {
  5267. return new Array();
  5268. };
  5269. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  5270. /**
  5271. * Property giving the Model Key associated to the property.
  5272. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  5273. * @returns the model key string.
  5274. */
  5275. get: function () {
  5276. var _this = this;
  5277. // No need to compute it?
  5278. if (!this._isFlagSet(SmartPropertyPrim_1.flagModelDirty) && this._modelKey) {
  5279. return this._modelKey;
  5280. }
  5281. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  5282. var propDic = this.propDic;
  5283. propDic.forEach(function (k, v) {
  5284. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  5285. var propVal = _this[v.name];
  5286. // Special case, array, this WON'T WORK IN ALL CASES, all entries have to be of the same type and it must be a BJS well known one
  5287. if (propVal && propVal.constructor === Array) {
  5288. var firstVal = propVal[0];
  5289. if (!firstVal) {
  5290. propVal = 0;
  5291. }
  5292. else {
  5293. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  5294. }
  5295. }
  5296. var value = "[null]";
  5297. if (propVal != null) {
  5298. if (v.typeLevelCompare) {
  5299. value = BABYLON.Tools.getClassName(propVal);
  5300. }
  5301. else {
  5302. // String Dictionaries' content are too complex, with use a Random GUID to make the model unique
  5303. if (propVal instanceof BABYLON.StringDictionary) {
  5304. value = BABYLON.Tools.RandomId();
  5305. }
  5306. else if (propVal instanceof BABYLON.BaseTexture) {
  5307. value = propVal.uid;
  5308. }
  5309. else {
  5310. value = propVal.toString();
  5311. }
  5312. }
  5313. }
  5314. modelKey += v.name + ":" + value + ";";
  5315. }
  5316. });
  5317. this._clearFlags(SmartPropertyPrim_1.flagModelDirty);
  5318. this._modelKey = modelKey;
  5319. return modelKey;
  5320. },
  5321. enumerable: true,
  5322. configurable: true
  5323. });
  5324. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  5325. /**
  5326. * States if the Primitive is dirty and should be rendered again next time.
  5327. * @returns true is dirty, false otherwise
  5328. */
  5329. get: function () {
  5330. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim_1.flagModelDirty | SmartPropertyPrim_1.flagModelUpdate | SmartPropertyPrim_1.flagPositioningDirty | SmartPropertyPrim_1.flagLayoutDirty);
  5331. },
  5332. enumerable: true,
  5333. configurable: true
  5334. });
  5335. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  5336. this._setFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  5337. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  5338. if (this instanceof BABYLON.Prim2DBase) {
  5339. var curprim = this;
  5340. while (curprim) {
  5341. curprim._setFlags(SmartPropertyPrim_1.flagBoundingInfoDirty);
  5342. if (curprim.isSizeAuto) {
  5343. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  5344. if (curprim._isFlagSet(SmartPropertyPrim_1.flagUsePositioning)) {
  5345. curprim._setFlags(SmartPropertyPrim_1.flagPositioningDirty);
  5346. }
  5347. }
  5348. if (curprim instanceof BABYLON.Group2D) {
  5349. if (curprim.isRenderableGroup) {
  5350. break;
  5351. }
  5352. }
  5353. curprim = curprim.parent;
  5354. }
  5355. }
  5356. };
  5357. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  5358. _super.prototype._handlePropChanged.call(this, curValue, newValue, propName, propInfo, typeLevelCompare);
  5359. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  5360. if (propInfo.dirtyBoundingInfo) {
  5361. this._boundingBoxDirty();
  5362. }
  5363. else if (propInfo.dirtyParentBoundingInfo) {
  5364. var p = this._parent;
  5365. if (p != null) {
  5366. p._boundingBoxDirty();
  5367. }
  5368. }
  5369. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  5370. if (this instanceof BABYLON.Group2D && this._renderableData) {
  5371. this.handleGroupChanged(propInfo);
  5372. }
  5373. // Check for parent layout dirty
  5374. if (this instanceof BABYLON.Prim2DBase) {
  5375. var p = this._parent;
  5376. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  5377. p._setLayoutDirty();
  5378. }
  5379. var that = this;
  5380. if (that.layoutEngine && (that.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  5381. this._setLayoutDirty();
  5382. }
  5383. }
  5384. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  5385. var instanceDirty = false;
  5386. if (typeLevelCompare && curValue != null && newValue != null) {
  5387. var cvProto = curValue.__proto__;
  5388. var nvProto = newValue.__proto__;
  5389. instanceDirty = (cvProto === nvProto);
  5390. }
  5391. // Set the dirty flags
  5392. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  5393. if (!this.isDirty) {
  5394. this.onPrimBecomesDirty();
  5395. this._setFlags(SmartPropertyPrim_1.flagModelDirty);
  5396. }
  5397. }
  5398. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  5399. var propMask = propInfo.flagId;
  5400. this.onPrimitivePropertyDirty(propMask);
  5401. }
  5402. };
  5403. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  5404. this.onPrimBecomesDirty();
  5405. this._instanceDirtyFlags |= propFlagId;
  5406. };
  5407. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  5408. };
  5409. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  5410. _super.prototype._resetPropertiesDirty.call(this);
  5411. this._clearFlags(SmartPropertyPrim_1.flagPrimInDirtyList | SmartPropertyPrim_1.flagNeedRefresh);
  5412. };
  5413. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  5414. /**
  5415. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  5416. */
  5417. get: function () {
  5418. if (this._isFlagSet(SmartPropertyPrim_1.flagLevelBoundingInfoDirty)) {
  5419. if (this.updateLevelBoundingInfo()) {
  5420. this._boundingInfo.dirtyWorldAABB();
  5421. this._clearFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  5422. }
  5423. else {
  5424. this._levelBoundingInfo.clear();
  5425. }
  5426. }
  5427. return this._levelBoundingInfo;
  5428. },
  5429. enumerable: true,
  5430. configurable: true
  5431. });
  5432. /**
  5433. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  5434. */
  5435. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  5436. return false;
  5437. };
  5438. /**
  5439. * Property method called when the Primitive becomes dirty
  5440. */
  5441. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  5442. };
  5443. /**
  5444. * Check if a given flag is set
  5445. * @param flag the flag value
  5446. * @return true if set, false otherwise
  5447. */
  5448. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  5449. return (this._flags & flag) !== 0;
  5450. };
  5451. /**
  5452. * Check if all given flags are set
  5453. * @param flags the flags ORed
  5454. * @return true if all the flags are set, false otherwise
  5455. */
  5456. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  5457. return (this._flags & flags) === flags;
  5458. };
  5459. /**
  5460. * Check if at least one flag of the given flags is set
  5461. * @param flags the flags ORed
  5462. * @return true if at least one flag is set, false otherwise
  5463. */
  5464. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  5465. return (this._flags & flags) !== 0;
  5466. };
  5467. /**
  5468. * Clear the given flags
  5469. * @param flags the flags to clear
  5470. */
  5471. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  5472. this._flags &= ~flags;
  5473. };
  5474. /**
  5475. * Set the given flags to true state
  5476. * @param flags the flags ORed to set
  5477. * @return the flags state before this call
  5478. */
  5479. SmartPropertyPrim.prototype._setFlags = function (flags) {
  5480. var cur = this._flags;
  5481. this._flags |= flags;
  5482. return cur;
  5483. };
  5484. /**
  5485. * Change the state of the given flags
  5486. * @param flags the flags ORed to change
  5487. * @param state true to set them, false to clear them
  5488. */
  5489. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  5490. if (state) {
  5491. this._flags |= flags;
  5492. }
  5493. else {
  5494. this._flags &= ~flags;
  5495. }
  5496. };
  5497. return SmartPropertyPrim;
  5498. }(SmartPropertyBase));
  5499. SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT = 0;
  5500. SmartPropertyPrim.flagNoPartOfLayout = 0x0000001; // set if the primitive's position/size must not be computed by Layout Engine
  5501. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  5502. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  5503. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  5504. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  5505. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  5506. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  5507. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  5508. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  5509. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  5510. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  5511. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  5512. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  5513. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  5514. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  5515. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  5516. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  5517. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  5518. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  5519. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  5520. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  5521. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0200000; // set if the layout bounding info is dirty
  5522. SmartPropertyPrim.flagCollisionActor = 0x0400000; // set if the primitive is part of the collision engine
  5523. SmartPropertyPrim.flagModelUpdate = 0x0800000; // set if the primitive's model data is to update
  5524. SmartPropertyPrim.flagLocalTransformDirty = 0x1000000; // set if the local transformation matrix must be recomputed
  5525. SmartPropertyPrim.flagUsePositioning = 0x2000000; // set if the primitive rely on the positioning engine (padding or margin is used)
  5526. SmartPropertyPrim.flagComputingPositioning = 0x4000000; // set if the positioning engine is computing the primitive, used to avoid re entrance
  5527. SmartPropertyPrim = SmartPropertyPrim_1 = __decorate([
  5528. BABYLON.className("SmartPropertyPrim", "BABYLON")
  5529. ], SmartPropertyPrim);
  5530. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  5531. function dependencyProperty(propId, piStore, mode, updateSourceTrigger) {
  5532. if (mode === void 0) { mode = DataBinding.MODE_TWOWAY; }
  5533. if (updateSourceTrigger === void 0) { updateSourceTrigger = DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED; }
  5534. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { bindingMode: mode, bindingUpdateSourceTrigger: updateSourceTrigger });
  5535. }
  5536. BABYLON.dependencyProperty = dependencyProperty;
  5537. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  5538. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  5539. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  5540. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  5541. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_MODEL, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  5542. }
  5543. BABYLON.modelLevelProperty = modelLevelProperty;
  5544. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  5545. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  5546. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  5547. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  5548. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_INSTANCE, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  5549. }
  5550. BABYLON.instanceLevelProperty = instanceLevelProperty;
  5551. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  5552. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  5553. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  5554. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  5555. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  5556. }
  5557. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  5558. var DataBinding_1, SmartPropertyBase_1, SmartPropertyPrim_1;
  5559. })(BABYLON || (BABYLON = {}));
  5560. //# sourceMappingURL=babylon.smartPropertyPrim.js.map
  5561. var __extends = (this && this.__extends) || function (d, b) {
  5562. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5563. function __() { this.constructor = d; }
  5564. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5565. };
  5566. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  5567. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  5568. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  5569. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5570. return c > 3 && r && Object.defineProperty(target, key, r), r;
  5571. };
  5572. var BABYLON;
  5573. (function (BABYLON) {
  5574. var PrepareRender2DContext = (function () {
  5575. function PrepareRender2DContext() {
  5576. this.forceRefreshPrimitive = false;
  5577. }
  5578. return PrepareRender2DContext;
  5579. }());
  5580. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  5581. var Render2DContext = (function () {
  5582. function Render2DContext(renderMode) {
  5583. this._renderMode = renderMode;
  5584. this.useInstancing = false;
  5585. this.groupInfoPartData = null;
  5586. this.partDataStartIndex = this.partDataEndIndex = null;
  5587. this.instancedBuffers = null;
  5588. }
  5589. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  5590. /**
  5591. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  5592. */
  5593. get: function () {
  5594. return this._renderMode;
  5595. },
  5596. enumerable: true,
  5597. configurable: true
  5598. });
  5599. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  5600. /**
  5601. * The set of primitives to render is opaque.
  5602. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  5603. */
  5604. get: function () {
  5605. return Render2DContext._renderModeOpaque;
  5606. },
  5607. enumerable: true,
  5608. configurable: true
  5609. });
  5610. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  5611. /**
  5612. * The set of primitives to render is using Alpha Test (aka masking).
  5613. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeOpaque and is depth independent (i.e. primitives are not sorted by depth). Depth Compare and Write are both enabled.
  5614. */
  5615. get: function () {
  5616. return Render2DContext._renderModeAlphaTest;
  5617. },
  5618. enumerable: true,
  5619. configurable: true
  5620. });
  5621. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  5622. /**
  5623. * The set of primitives to render is transparent.
  5624. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeAlphaTest and is depth dependent (i.e. primitives are stored by depth and rendered back to front). Depth Compare is on, but Depth write is Off.
  5625. */
  5626. get: function () {
  5627. return Render2DContext._renderModeTransparent;
  5628. },
  5629. enumerable: true,
  5630. configurable: true
  5631. });
  5632. return Render2DContext;
  5633. }());
  5634. Render2DContext._renderModeOpaque = 1;
  5635. Render2DContext._renderModeAlphaTest = 2;
  5636. Render2DContext._renderModeTransparent = 3;
  5637. BABYLON.Render2DContext = Render2DContext;
  5638. /**
  5639. * This class store information for the pointerEventObservable Observable.
  5640. * The Observable is divided into many sub events (using the Mask feature of the Observable pattern): PointerOver, PointerEnter, PointerDown, PointerMouseWheel, PointerMove, PointerUp, PointerDown, PointerLeave, PointerGotCapture and PointerLostCapture.
  5641. */
  5642. var PrimitivePointerInfo = (function () {
  5643. function PrimitivePointerInfo() {
  5644. this.primitivePointerPos = BABYLON.Vector2.Zero();
  5645. this.tilt = BABYLON.Vector2.Zero();
  5646. this.cancelBubble = false;
  5647. }
  5648. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  5649. // The behavior is based on the HTML specifications of the Pointer Events (https://www.w3.org/TR/pointerevents/#list-of-pointer-events). This is not 100% compliant and not meant to be, but still, it's based on these specs for most use cases to be programmed the same way (as closest as possible) as it would have been in HTML.
  5650. /**
  5651. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  5652. * Bubbles: yes
  5653. */
  5654. get: function () {
  5655. return PrimitivePointerInfo._pointerOver;
  5656. },
  5657. enumerable: true,
  5658. configurable: true
  5659. });
  5660. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  5661. /**
  5662. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  5663. * Bubbles: no
  5664. */
  5665. get: function () {
  5666. return PrimitivePointerInfo._pointerEnter;
  5667. },
  5668. enumerable: true,
  5669. configurable: true
  5670. });
  5671. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  5672. /**
  5673. * This event type is raised when a pointer enters the active button state (non-zero value in the buttons property). For mouse it's when the device transitions from no buttons depressed to at least one button depressed. For touch/pen this is when a physical contact is made.
  5674. * Bubbles: yes
  5675. */
  5676. get: function () {
  5677. return PrimitivePointerInfo._pointerDown;
  5678. },
  5679. enumerable: true,
  5680. configurable: true
  5681. });
  5682. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  5683. /**
  5684. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  5685. * Bubbles: yes
  5686. */
  5687. get: function () {
  5688. return PrimitivePointerInfo._pointerMouseWheel;
  5689. },
  5690. enumerable: true,
  5691. configurable: true
  5692. });
  5693. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  5694. /**
  5695. * This event type is raised when a pointer change coordinates or when a pointer changes button state, pressure, tilt, or contact geometry and the circumstances produce no other pointers events.
  5696. * Bubbles: yes
  5697. */
  5698. get: function () {
  5699. return PrimitivePointerInfo._pointerMove;
  5700. },
  5701. enumerable: true,
  5702. configurable: true
  5703. });
  5704. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  5705. /**
  5706. * This event type is raised when the pointer leaves the active buttons states (zero value in the buttons property). For mouse, this is when the device transitions from at least one button depressed to no buttons depressed. For touch/pen, this is when physical contact is removed.
  5707. * Bubbles: yes
  5708. */
  5709. get: function () {
  5710. return PrimitivePointerInfo._pointerUp;
  5711. },
  5712. enumerable: true,
  5713. configurable: true
  5714. });
  5715. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  5716. /**
  5717. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  5718. * Bubbles: yes
  5719. */
  5720. get: function () {
  5721. return PrimitivePointerInfo._pointerOut;
  5722. },
  5723. enumerable: true,
  5724. configurable: true
  5725. });
  5726. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  5727. /**
  5728. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  5729. * Bubbles: no
  5730. */
  5731. get: function () {
  5732. return PrimitivePointerInfo._pointerLeave;
  5733. },
  5734. enumerable: true,
  5735. configurable: true
  5736. });
  5737. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  5738. /**
  5739. * This event type is raised when a primitive receives the pointer capture. This event is fired at the element that is receiving pointer capture. Subsequent events for that pointer will be fired at this element.
  5740. * Bubbles: yes
  5741. */
  5742. get: function () {
  5743. return PrimitivePointerInfo._pointerGotCapture;
  5744. },
  5745. enumerable: true,
  5746. configurable: true
  5747. });
  5748. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  5749. /**
  5750. * This event type is raised after pointer capture is released for a pointer.
  5751. * Bubbles: yes
  5752. */
  5753. get: function () {
  5754. return PrimitivePointerInfo._pointerLostCapture;
  5755. },
  5756. enumerable: true,
  5757. configurable: true
  5758. });
  5759. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  5760. get: function () {
  5761. return PrimitivePointerInfo._mouseWheelPrecision;
  5762. },
  5763. enumerable: true,
  5764. configurable: true
  5765. });
  5766. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  5767. this.relatedTarget = prim;
  5768. this.relatedTargetPointerPos = primPointerPos;
  5769. };
  5770. PrimitivePointerInfo.getEventTypeName = function (mask) {
  5771. switch (mask) {
  5772. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  5773. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  5774. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  5775. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  5776. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  5777. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  5778. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  5779. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  5780. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  5781. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  5782. }
  5783. };
  5784. return PrimitivePointerInfo;
  5785. }());
  5786. PrimitivePointerInfo._pointerOver = 0x0001;
  5787. PrimitivePointerInfo._pointerEnter = 0x0002;
  5788. PrimitivePointerInfo._pointerDown = 0x0004;
  5789. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  5790. PrimitivePointerInfo._pointerMove = 0x0010;
  5791. PrimitivePointerInfo._pointerUp = 0x0020;
  5792. PrimitivePointerInfo._pointerOut = 0x0040;
  5793. PrimitivePointerInfo._pointerLeave = 0x0080;
  5794. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  5795. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  5796. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  5797. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  5798. /**
  5799. * Defines the horizontal and vertical alignment information for a Primitive.
  5800. */
  5801. var PrimitiveAlignment = PrimitiveAlignment_1 = (function () {
  5802. function PrimitiveAlignment(changeCallback) {
  5803. this._changedCallback = changeCallback;
  5804. this._horizontal = PrimitiveAlignment_1.AlignLeft;
  5805. this._vertical = PrimitiveAlignment_1.AlignBottom;
  5806. }
  5807. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  5808. /**
  5809. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  5810. */
  5811. get: function () { return PrimitiveAlignment_1._AlignLeft; },
  5812. enumerable: true,
  5813. configurable: true
  5814. });
  5815. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  5816. /**
  5817. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  5818. */
  5819. get: function () { return PrimitiveAlignment_1._AlignTop; },
  5820. enumerable: true,
  5821. configurable: true
  5822. });
  5823. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  5824. /**
  5825. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  5826. */
  5827. get: function () { return PrimitiveAlignment_1._AlignRight; },
  5828. enumerable: true,
  5829. configurable: true
  5830. });
  5831. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  5832. /**
  5833. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  5834. */
  5835. get: function () { return PrimitiveAlignment_1._AlignBottom; },
  5836. enumerable: true,
  5837. configurable: true
  5838. });
  5839. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  5840. /**
  5841. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  5842. */
  5843. get: function () { return PrimitiveAlignment_1._AlignCenter; },
  5844. enumerable: true,
  5845. configurable: true
  5846. });
  5847. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  5848. /**
  5849. * The content is stretched toward the opposite edges of the Primitive
  5850. */
  5851. get: function () { return PrimitiveAlignment_1._AlignStretch; },
  5852. enumerable: true,
  5853. configurable: true
  5854. });
  5855. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  5856. /**
  5857. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  5858. */
  5859. get: function () {
  5860. return this._horizontal;
  5861. },
  5862. set: function (value) {
  5863. if (this._horizontal === value) {
  5864. return;
  5865. }
  5866. this._horizontal = value;
  5867. this.onChangeCallback();
  5868. },
  5869. enumerable: true,
  5870. configurable: true
  5871. });
  5872. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  5873. /**
  5874. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  5875. */
  5876. get: function () {
  5877. return this._vertical;
  5878. },
  5879. set: function (value) {
  5880. if (this._vertical === value) {
  5881. return;
  5882. }
  5883. this._vertical = value;
  5884. this.onChangeCallback();
  5885. },
  5886. enumerable: true,
  5887. configurable: true
  5888. });
  5889. PrimitiveAlignment.prototype.onChangeCallback = function () {
  5890. if (this._changedCallback) {
  5891. this._changedCallback();
  5892. }
  5893. };
  5894. /**
  5895. * Set the horizontal alignment from a string value.
  5896. * @param text can be either: 'left','right','center','stretch'
  5897. */
  5898. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  5899. var v = text.trim().toLocaleLowerCase();
  5900. switch (v) {
  5901. case "left":
  5902. this.horizontal = PrimitiveAlignment_1.AlignLeft;
  5903. return;
  5904. case "right":
  5905. this.horizontal = PrimitiveAlignment_1.AlignRight;
  5906. return;
  5907. case "center":
  5908. this.horizontal = PrimitiveAlignment_1.AlignCenter;
  5909. return;
  5910. case "stretch":
  5911. this.horizontal = PrimitiveAlignment_1.AlignStretch;
  5912. return;
  5913. }
  5914. };
  5915. /**
  5916. * Set the vertical alignment from a string value.
  5917. * @param text can be either: 'top','bottom','center','stretch'
  5918. */
  5919. PrimitiveAlignment.prototype.setVertical = function (text) {
  5920. var v = text.trim().toLocaleLowerCase();
  5921. switch (v) {
  5922. case "top":
  5923. this.vertical = PrimitiveAlignment_1.AlignTop;
  5924. return;
  5925. case "bottom":
  5926. this.vertical = PrimitiveAlignment_1.AlignBottom;
  5927. return;
  5928. case "center":
  5929. this.vertical = PrimitiveAlignment_1.AlignCenter;
  5930. return;
  5931. case "stretch":
  5932. this.vertical = PrimitiveAlignment_1.AlignStretch;
  5933. return;
  5934. }
  5935. };
  5936. /**
  5937. * Set the horizontal and or vertical alignments from a string value.
  5938. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  5939. */
  5940. PrimitiveAlignment.prototype.fromString = function (value) {
  5941. var m = value.trim().split(",");
  5942. if (m.length === 1) {
  5943. this.setHorizontal(m[0]);
  5944. this.setVertical(m[0]);
  5945. }
  5946. else {
  5947. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  5948. var v = m_1[_i];
  5949. v = v.toLocaleLowerCase().trim();
  5950. // Horizontal
  5951. var i = v.indexOf("h:");
  5952. if (i === -1) {
  5953. i = v.indexOf("horizontal:");
  5954. }
  5955. if (i !== -1) {
  5956. v = v.substr(v.indexOf(":") + 1);
  5957. this.setHorizontal(v);
  5958. continue;
  5959. }
  5960. // Vertical
  5961. i = v.indexOf("v:");
  5962. if (i === -1) {
  5963. i = v.indexOf("vertical:");
  5964. }
  5965. if (i !== -1) {
  5966. v = v.substr(v.indexOf(":") + 1);
  5967. this.setVertical(v);
  5968. continue;
  5969. }
  5970. }
  5971. }
  5972. };
  5973. PrimitiveAlignment.prototype.copyFrom = function (pa) {
  5974. this._horizontal = pa._horizontal;
  5975. this._vertical = pa._vertical;
  5976. this.onChangeCallback();
  5977. };
  5978. PrimitiveAlignment.prototype.clone = function () {
  5979. var pa = new PrimitiveAlignment_1();
  5980. pa._horizontal = this._horizontal;
  5981. pa._vertical = this._vertical;
  5982. return pa;
  5983. };
  5984. Object.defineProperty(PrimitiveAlignment.prototype, "isDefault", {
  5985. get: function () {
  5986. return this.horizontal === PrimitiveAlignment_1.AlignLeft && this.vertical === PrimitiveAlignment_1.AlignBottom;
  5987. },
  5988. enumerable: true,
  5989. configurable: true
  5990. });
  5991. return PrimitiveAlignment;
  5992. }());
  5993. PrimitiveAlignment._AlignLeft = 1;
  5994. PrimitiveAlignment._AlignTop = 1; // Same as left
  5995. PrimitiveAlignment._AlignRight = 2;
  5996. PrimitiveAlignment._AlignBottom = 2; // Same as right
  5997. PrimitiveAlignment._AlignCenter = 3;
  5998. PrimitiveAlignment._AlignStretch = 4;
  5999. PrimitiveAlignment = PrimitiveAlignment_1 = __decorate([
  6000. BABYLON.className("PrimitiveAlignment", "BABYLON")
  6001. ], PrimitiveAlignment);
  6002. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  6003. /**
  6004. * Stores information about a Primitive that was intersected
  6005. */
  6006. var PrimitiveIntersectedInfo = (function () {
  6007. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  6008. this.prim = prim;
  6009. this.intersectionLocation = intersectionLocation;
  6010. }
  6011. return PrimitiveIntersectedInfo;
  6012. }());
  6013. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  6014. /**
  6015. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  6016. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  6017. */
  6018. var PrimitiveThickness = PrimitiveThickness_1 = (function () {
  6019. function PrimitiveThickness(parentAccess, changedCallback) {
  6020. this._parentAccess = parentAccess;
  6021. this._changedCallback = changedCallback;
  6022. this._pixels = new Array(4);
  6023. this._percentages = new Array(4);
  6024. this._setType(0, PrimitiveThickness_1.Auto);
  6025. this._setType(1, PrimitiveThickness_1.Auto);
  6026. this._setType(2, PrimitiveThickness_1.Auto);
  6027. this._setType(3, PrimitiveThickness_1.Auto);
  6028. this._pixels[0] = 0;
  6029. this._pixels[1] = 0;
  6030. this._pixels[2] = 0;
  6031. this._pixels[3] = 0;
  6032. }
  6033. /**
  6034. * Set the thickness from a string value
  6035. * @param thickness format is "top: <value>, left:<value>, right:<value>, bottom:<value>" or "<value>" (same for all edges) each are optional, auto will be set if it's omitted.
  6036. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6037. */
  6038. PrimitiveThickness.prototype.fromString = function (thickness) {
  6039. this._clear();
  6040. var m = thickness.trim().split(",");
  6041. // Special case, one value to apply to all edges
  6042. if (m.length === 1 && thickness.indexOf(":") === -1) {
  6043. this._setStringValue(m[0], 0, false);
  6044. this._setStringValue(m[0], 1, false);
  6045. this._setStringValue(m[0], 2, false);
  6046. this._setStringValue(m[0], 3, false);
  6047. this.onChangeCallback();
  6048. return;
  6049. }
  6050. var res = false;
  6051. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  6052. var cm = m_2[_i];
  6053. res = this._extractString(cm, false) || res;
  6054. }
  6055. if (!res) {
  6056. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  6057. }
  6058. // Check the margin that weren't set and set them in auto
  6059. if ((this._flags & 0x000F) === 0)
  6060. this._flags |= PrimitiveThickness_1.Pixel << 0;
  6061. if ((this._flags & 0x00F0) === 0)
  6062. this._flags |= PrimitiveThickness_1.Pixel << 4;
  6063. if ((this._flags & 0x0F00) === 0)
  6064. this._flags |= PrimitiveThickness_1.Pixel << 8;
  6065. if ((this._flags & 0xF000) === 0)
  6066. this._flags |= PrimitiveThickness_1.Pixel << 12;
  6067. this.onChangeCallback();
  6068. };
  6069. /**
  6070. * Set the thickness from multiple string
  6071. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6072. * @param top the top thickness to set
  6073. * @param left the left thickness to set
  6074. * @param right the right thickness to set
  6075. * @param bottom the bottom thickness to set
  6076. */
  6077. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  6078. this._clear();
  6079. this._setStringValue(top, 0, false);
  6080. this._setStringValue(left, 1, false);
  6081. this._setStringValue(right, 2, false);
  6082. this._setStringValue(bottom, 3, false);
  6083. this.onChangeCallback();
  6084. return this;
  6085. };
  6086. /**
  6087. * Set the thickness from pixel values
  6088. * @param top the top thickness in pixels to set
  6089. * @param left the left thickness in pixels to set
  6090. * @param right the right thickness in pixels to set
  6091. * @param bottom the bottom thickness in pixels to set
  6092. */
  6093. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  6094. this._clear();
  6095. this._pixels[0] = top;
  6096. this._pixels[1] = left;
  6097. this._pixels[2] = right;
  6098. this._pixels[3] = bottom;
  6099. this.onChangeCallback();
  6100. return this;
  6101. };
  6102. /**
  6103. * Apply the same pixel value to all edges
  6104. * @param margin the value to set, in pixels.
  6105. */
  6106. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  6107. this._clear();
  6108. this._pixels[0] = margin;
  6109. this._pixels[1] = margin;
  6110. this._pixels[2] = margin;
  6111. this._pixels[3] = margin;
  6112. this.onChangeCallback();
  6113. return this;
  6114. };
  6115. PrimitiveThickness.prototype.copyFrom = function (pt) {
  6116. this._clear();
  6117. for (var i = 0; i < 4; i++) {
  6118. this._pixels[i] = pt._pixels[i];
  6119. this._percentages[i] = pt._percentages[i];
  6120. }
  6121. this._flags = pt._flags;
  6122. this.onChangeCallback();
  6123. };
  6124. /**
  6125. * Set all edges in auto
  6126. */
  6127. PrimitiveThickness.prototype.auto = function () {
  6128. this._clear();
  6129. this._flags = (PrimitiveThickness_1.Auto << 0) | (PrimitiveThickness_1.Auto << 4) | (PrimitiveThickness_1.Auto << 8) | (PrimitiveThickness_1.Auto << 12);
  6130. this._pixels[0] = 0;
  6131. this._pixels[1] = 0;
  6132. this._pixels[2] = 0;
  6133. this._pixels[3] = 0;
  6134. this.onChangeCallback();
  6135. return this;
  6136. };
  6137. PrimitiveThickness.prototype._clear = function () {
  6138. this._flags = 0;
  6139. this._pixels[0] = 0;
  6140. this._pixels[1] = 0;
  6141. this._pixels[2] = 0;
  6142. this._pixels[3] = 0;
  6143. this._percentages[0] = null;
  6144. this._percentages[1] = null;
  6145. this._percentages[2] = null;
  6146. this._percentages[3] = null;
  6147. };
  6148. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  6149. var v = value.trim().toLocaleLowerCase();
  6150. if (v.indexOf("top:") === 0) {
  6151. v = v.substr(4).trim();
  6152. return this._setStringValue(v, 0, emitChanged);
  6153. }
  6154. if (v.indexOf("left:") === 0) {
  6155. v = v.substr(5).trim();
  6156. return this._setStringValue(v, 1, emitChanged);
  6157. }
  6158. if (v.indexOf("right:") === 0) {
  6159. v = v.substr(6).trim();
  6160. return this._setStringValue(v, 2, emitChanged);
  6161. }
  6162. if (v.indexOf("bottom:") === 0) {
  6163. v = v.substr(7).trim();
  6164. return this._setStringValue(v, 3, emitChanged);
  6165. }
  6166. return false;
  6167. };
  6168. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  6169. // Check for auto
  6170. var v = value.trim().toLocaleLowerCase();
  6171. if (v === "auto") {
  6172. if (this._isType(index, PrimitiveThickness_1.Auto)) {
  6173. return true;
  6174. }
  6175. this._setType(index, PrimitiveThickness_1.Auto);
  6176. this._pixels[index] = 0;
  6177. if (emitChanged) {
  6178. this.onChangeCallback();
  6179. }
  6180. }
  6181. else if (v === "inherit") {
  6182. if (this._isType(index, PrimitiveThickness_1.Inherit)) {
  6183. return true;
  6184. }
  6185. this._setType(index, PrimitiveThickness_1.Inherit);
  6186. this._pixels[index] = null;
  6187. if (emitChanged) {
  6188. this.onChangeCallback();
  6189. }
  6190. }
  6191. else {
  6192. var pI = v.indexOf("%");
  6193. // Check for percentage
  6194. if (pI !== -1) {
  6195. var n_1 = v.substr(0, pI);
  6196. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  6197. if (this._isType(index, PrimitiveThickness_1.Percentage) && (this._percentages[index] === number_1)) {
  6198. return true;
  6199. }
  6200. this._setType(index, PrimitiveThickness_1.Percentage);
  6201. if (isNaN(number_1)) {
  6202. return false;
  6203. }
  6204. this._percentages[index] = number_1;
  6205. if (emitChanged) {
  6206. this.onChangeCallback();
  6207. }
  6208. return true;
  6209. }
  6210. // Check for pixel
  6211. var n = void 0;
  6212. pI = v.indexOf("px");
  6213. if (pI !== -1) {
  6214. n = v.substr(0, pI).trim();
  6215. }
  6216. else {
  6217. n = v;
  6218. }
  6219. var number = Number(n);
  6220. if (this._isType(index, PrimitiveThickness_1.Pixel) && (this._pixels[index] === number)) {
  6221. return true;
  6222. }
  6223. if (isNaN(number)) {
  6224. return false;
  6225. }
  6226. this._pixels[index] = number;
  6227. this._setType(index, PrimitiveThickness_1.Pixel);
  6228. if (emitChanged) {
  6229. this.onChangeCallback();
  6230. }
  6231. return true;
  6232. }
  6233. };
  6234. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  6235. // Round the value because, well, it's the thing to do! Otherwise we'll have sub-pixel stuff, and the no change comparison just below will almost never work for PrimitiveThickness values inside a hierarchy of Primitives
  6236. value = Math.round(value);
  6237. if (this._isType(index, PrimitiveThickness_1.Pixel) && this._pixels[index] === value) {
  6238. return;
  6239. }
  6240. this._setType(index, PrimitiveThickness_1.Pixel);
  6241. this._pixels[index] = value;
  6242. if (emitChanged) {
  6243. this.onChangeCallback();
  6244. }
  6245. };
  6246. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  6247. // Clip Value to bounds
  6248. value = Math.min(1, value);
  6249. value = Math.max(0, value);
  6250. value = Math.round(value * 100) / 100; // 0.01 precision
  6251. if (this._isType(index, PrimitiveThickness_1.Percentage) && this._percentages[index] === value) {
  6252. return;
  6253. }
  6254. this._setType(index, PrimitiveThickness_1.Percentage);
  6255. this._percentages[index] = value;
  6256. if (emitChanged) {
  6257. this.onChangeCallback();
  6258. }
  6259. };
  6260. PrimitiveThickness.prototype._getStringValue = function (index) {
  6261. var f = (this._flags >> (index * 4)) & 0xF;
  6262. switch (f) {
  6263. case PrimitiveThickness_1.Auto:
  6264. return "auto";
  6265. case PrimitiveThickness_1.Pixel:
  6266. return this._pixels[index] + "px";
  6267. case PrimitiveThickness_1.Percentage:
  6268. return this._percentages[index] * 100 + "%";
  6269. case PrimitiveThickness_1.Inherit:
  6270. return "inherit";
  6271. }
  6272. return "";
  6273. };
  6274. PrimitiveThickness.prototype._isType = function (index, type) {
  6275. var f = (this._flags >> (index * 4)) & 0xF;
  6276. return f === type;
  6277. };
  6278. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  6279. var t = (this._flags >> (index * 4)) & 0xF;
  6280. if (processInherit && (t === PrimitiveThickness_1.Inherit)) {
  6281. var p = this._parentAccess();
  6282. if (p) {
  6283. return p._getType(index, true);
  6284. }
  6285. return PrimitiveThickness_1.Auto;
  6286. }
  6287. return t;
  6288. };
  6289. PrimitiveThickness.prototype._setType = function (index, type) {
  6290. this._flags &= ~(0xF << (index * 4));
  6291. this._flags |= type << (index * 4);
  6292. };
  6293. PrimitiveThickness.prototype.setTop = function (value) {
  6294. if (typeof value === "string") {
  6295. this._setStringValue(value, 0, true);
  6296. }
  6297. else {
  6298. this.topPixels = value;
  6299. }
  6300. };
  6301. PrimitiveThickness.prototype.setLeft = function (value) {
  6302. if (typeof value === "string") {
  6303. this._setStringValue(value, 1, true);
  6304. }
  6305. else {
  6306. this.leftPixels = value;
  6307. }
  6308. };
  6309. PrimitiveThickness.prototype.setRight = function (value) {
  6310. if (typeof value === "string") {
  6311. this._setStringValue(value, 2, true);
  6312. }
  6313. else {
  6314. this.rightPixels = value;
  6315. }
  6316. };
  6317. PrimitiveThickness.prototype.setBottom = function (value) {
  6318. if (typeof value === "string") {
  6319. this._setStringValue(value, 3, true);
  6320. }
  6321. else {
  6322. this.bottomPixels = value;
  6323. }
  6324. };
  6325. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  6326. /**
  6327. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6328. */
  6329. get: function () {
  6330. return this._getStringValue(0);
  6331. },
  6332. set: function (value) {
  6333. this._setStringValue(value, 0, true);
  6334. },
  6335. enumerable: true,
  6336. configurable: true
  6337. });
  6338. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  6339. /**
  6340. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6341. */
  6342. get: function () {
  6343. return this._getStringValue(1);
  6344. },
  6345. set: function (value) {
  6346. this._setStringValue(value, 1, true);
  6347. },
  6348. enumerable: true,
  6349. configurable: true
  6350. });
  6351. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  6352. /**
  6353. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6354. */
  6355. get: function () {
  6356. return this._getStringValue(2);
  6357. },
  6358. set: function (value) {
  6359. this._setStringValue(value, 2, true);
  6360. },
  6361. enumerable: true,
  6362. configurable: true
  6363. });
  6364. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  6365. /**
  6366. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6367. */
  6368. get: function () {
  6369. return this._getStringValue(3);
  6370. },
  6371. set: function (value) {
  6372. this._setStringValue(value, 3, true);
  6373. },
  6374. enumerable: true,
  6375. configurable: true
  6376. });
  6377. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  6378. /**
  6379. * Get/set the top thickness in pixel.
  6380. */
  6381. get: function () {
  6382. return this._pixels[0];
  6383. },
  6384. set: function (value) {
  6385. this._setPixels(value, 0, true);
  6386. },
  6387. enumerable: true,
  6388. configurable: true
  6389. });
  6390. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  6391. /**
  6392. * Get/set the left thickness in pixel.
  6393. */
  6394. get: function () {
  6395. return this._pixels[1];
  6396. },
  6397. set: function (value) {
  6398. this._setPixels(value, 1, true);
  6399. },
  6400. enumerable: true,
  6401. configurable: true
  6402. });
  6403. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  6404. /**
  6405. * Get/set the right thickness in pixel.
  6406. */
  6407. get: function () {
  6408. return this._pixels[2];
  6409. },
  6410. set: function (value) {
  6411. this._setPixels(value, 2, true);
  6412. },
  6413. enumerable: true,
  6414. configurable: true
  6415. });
  6416. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  6417. /**
  6418. * Get/set the bottom thickness in pixel.
  6419. */
  6420. get: function () {
  6421. return this._pixels[3];
  6422. },
  6423. set: function (value) {
  6424. this._setPixels(value, 3, true);
  6425. },
  6426. enumerable: true,
  6427. configurable: true
  6428. });
  6429. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  6430. /**
  6431. * Get/set the top thickness in percentage.
  6432. * The get will return a valid value only if the edge type is percentage.
  6433. * The Set will change the edge mode if needed
  6434. */
  6435. get: function () {
  6436. return this._percentages[0];
  6437. },
  6438. set: function (value) {
  6439. this._setPercentage(value, 0, true);
  6440. },
  6441. enumerable: true,
  6442. configurable: true
  6443. });
  6444. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  6445. /**
  6446. * Get/set the left thickness in percentage.
  6447. * The get will return a valid value only if the edge mode is percentage.
  6448. * The Set will change the edge mode if needed
  6449. */
  6450. get: function () {
  6451. return this._percentages[1];
  6452. },
  6453. set: function (value) {
  6454. this._setPercentage(value, 1, true);
  6455. },
  6456. enumerable: true,
  6457. configurable: true
  6458. });
  6459. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  6460. /**
  6461. * Get/set the right thickness in percentage.
  6462. * The get will return a valid value only if the edge mode is percentage.
  6463. * The Set will change the edge mode if needed
  6464. */
  6465. get: function () {
  6466. return this._percentages[2];
  6467. },
  6468. set: function (value) {
  6469. this._setPercentage(value, 2, true);
  6470. },
  6471. enumerable: true,
  6472. configurable: true
  6473. });
  6474. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  6475. /**
  6476. * Get/set the bottom thickness in percentage.
  6477. * The get will return a valid value only if the edge mode is percentage.
  6478. * The Set will change the edge mode if needed
  6479. */
  6480. get: function () {
  6481. return this._percentages[3];
  6482. },
  6483. set: function (value) {
  6484. this._setPercentage(value, 3, true);
  6485. },
  6486. enumerable: true,
  6487. configurable: true
  6488. });
  6489. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  6490. /**
  6491. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  6492. */
  6493. get: function () {
  6494. return this._getType(0, false);
  6495. },
  6496. set: function (mode) {
  6497. this._setType(0, mode);
  6498. },
  6499. enumerable: true,
  6500. configurable: true
  6501. });
  6502. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  6503. /**
  6504. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  6505. */
  6506. get: function () {
  6507. return this._getType(1, false);
  6508. },
  6509. set: function (mode) {
  6510. this._setType(1, mode);
  6511. },
  6512. enumerable: true,
  6513. configurable: true
  6514. });
  6515. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  6516. /**
  6517. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  6518. */
  6519. get: function () {
  6520. return this._getType(2, false);
  6521. },
  6522. set: function (mode) {
  6523. this._setType(2, mode);
  6524. },
  6525. enumerable: true,
  6526. configurable: true
  6527. });
  6528. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  6529. /**
  6530. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  6531. */
  6532. get: function () {
  6533. return this._getType(3, false);
  6534. },
  6535. set: function (mode) {
  6536. this._setType(3, mode);
  6537. },
  6538. enumerable: true,
  6539. configurable: true
  6540. });
  6541. Object.defineProperty(PrimitiveThickness.prototype, "isDefault", {
  6542. get: function () {
  6543. return this._flags === 0x1111;
  6544. },
  6545. enumerable: true,
  6546. configurable: true
  6547. });
  6548. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  6549. var type = this._getType(index, false);
  6550. if (type === PrimitiveThickness_1.Inherit) {
  6551. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  6552. return;
  6553. }
  6554. if (type !== PrimitiveThickness_1.Percentage) {
  6555. return;
  6556. }
  6557. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  6558. this._pixels[index] = pixels;
  6559. if (emitChanged) {
  6560. this.onChangeCallback();
  6561. }
  6562. };
  6563. PrimitiveThickness.prototype.onChangeCallback = function () {
  6564. if (this._changedCallback) {
  6565. this._changedCallback();
  6566. }
  6567. };
  6568. /**
  6569. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  6570. * @param sourceArea the source area where the content must be sized/positioned
  6571. * @param contentSize the content size to position/resize
  6572. * @param alignment the alignment setting
  6573. * @param dstOffset the position of the content, x, y, z, w are left, bottom, right, top
  6574. * @param dstArea the new size of the content
  6575. */
  6576. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, contentScale, dstOffset, dstArea, computeLayoutArea, computeAxis) {
  6577. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  6578. if (computeAxis === void 0) { computeAxis = PrimitiveThickness_1.ComputeAll; }
  6579. // Fetch some data
  6580. var topType = this._getType(0, true);
  6581. var leftType = this._getType(1, true);
  6582. var rightType = this._getType(2, true);
  6583. var bottomType = this._getType(3, true);
  6584. var hasWidth = contentSize && (contentSize.width != null);
  6585. var hasHeight = contentSize && (contentSize.height != null);
  6586. var sx = contentScale.x;
  6587. var sy = contentScale.y;
  6588. var width = hasWidth ? contentSize.width : 0;
  6589. var height = hasHeight ? contentSize.height : 0;
  6590. var isTopAuto = topType === PrimitiveThickness_1.Auto;
  6591. var isLeftAuto = leftType === PrimitiveThickness_1.Auto;
  6592. var isRightAuto = rightType === PrimitiveThickness_1.Auto;
  6593. var isBottomAuto = bottomType === PrimitiveThickness_1.Auto;
  6594. if (computeAxis & PrimitiveThickness_1.ComputeH) {
  6595. switch (alignment.horizontal) {
  6596. case PrimitiveAlignment.AlignLeft:
  6597. {
  6598. var leftPixels = 0;
  6599. if (!isLeftAuto) {
  6600. this._computePixels(1, sourceArea, true);
  6601. leftPixels = this.leftPixels;
  6602. }
  6603. var rightPixels = 0;
  6604. if (!isRightAuto) {
  6605. this._computePixels(2, sourceArea, true);
  6606. rightPixels = this.rightPixels;
  6607. }
  6608. dstOffset.x = leftPixels;
  6609. dstArea.width = width;
  6610. dstOffset.z = rightPixels;
  6611. if (computeLayoutArea) {
  6612. dstArea.width += leftPixels + rightPixels;
  6613. }
  6614. break;
  6615. }
  6616. case PrimitiveAlignment.AlignRight:
  6617. {
  6618. var leftPixels = 0;
  6619. if (!isLeftAuto) {
  6620. this._computePixels(1, sourceArea, true);
  6621. leftPixels = this.leftPixels;
  6622. }
  6623. var rightPixels = 0;
  6624. if (!isRightAuto) {
  6625. this._computePixels(2, sourceArea, true);
  6626. rightPixels = this.rightPixels;
  6627. }
  6628. dstOffset.x = Math.round(sourceArea.width - ((width * sx) + rightPixels));
  6629. dstArea.width = width;
  6630. dstOffset.z = leftPixels;
  6631. if (computeLayoutArea) {
  6632. dstArea.width += leftPixels + rightPixels;
  6633. }
  6634. break;
  6635. }
  6636. case PrimitiveAlignment.AlignStretch:
  6637. {
  6638. if (isLeftAuto) {
  6639. dstOffset.x = 0;
  6640. }
  6641. else {
  6642. this._computePixels(1, sourceArea, true);
  6643. dstOffset.x = this.leftPixels;
  6644. }
  6645. var rightPixels = 0;
  6646. if (!isRightAuto) {
  6647. this._computePixels(2, sourceArea, true);
  6648. rightPixels = this.rightPixels;
  6649. }
  6650. if (computeLayoutArea) {
  6651. dstArea.width = sourceArea.width;
  6652. }
  6653. else {
  6654. dstArea.width = sourceArea.width - (dstOffset.x + rightPixels);
  6655. }
  6656. dstOffset.z = this.rightPixels;
  6657. break;
  6658. }
  6659. case PrimitiveAlignment.AlignCenter:
  6660. {
  6661. if (!isLeftAuto) {
  6662. this._computePixels(1, sourceArea, true);
  6663. }
  6664. if (!isRightAuto) {
  6665. this._computePixels(2, sourceArea, true);
  6666. }
  6667. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  6668. var center = ((sourceArea.width - (width * sx)) / 2);
  6669. dstOffset.x = Math.round(center + offset);
  6670. if (computeLayoutArea) {
  6671. dstArea.width = width + this.leftPixels + this.rightPixels;
  6672. }
  6673. else {
  6674. dstArea.width = width;
  6675. }
  6676. dstOffset.z = Math.round(center - offset);
  6677. break;
  6678. }
  6679. }
  6680. }
  6681. if (computeAxis & PrimitiveThickness_1.ComputeV) {
  6682. switch (alignment.vertical) {
  6683. case PrimitiveAlignment.AlignBottom:
  6684. {
  6685. var bottomPixels = 0;
  6686. if (!isBottomAuto) {
  6687. this._computePixels(3, sourceArea, true);
  6688. bottomPixels = this.bottomPixels;
  6689. }
  6690. var topPixels = 0;
  6691. if (!isTopAuto) {
  6692. this._computePixels(0, sourceArea, true);
  6693. topPixels = this.topPixels;
  6694. }
  6695. dstOffset.y = bottomPixels;
  6696. dstArea.height = height;
  6697. dstOffset.w = topPixels;
  6698. if (computeLayoutArea) {
  6699. dstArea.height += bottomPixels + topPixels;
  6700. }
  6701. break;
  6702. }
  6703. case PrimitiveAlignment.AlignTop:
  6704. {
  6705. var bottomPixels = 0;
  6706. if (!isBottomAuto) {
  6707. this._computePixels(3, sourceArea, true);
  6708. bottomPixels = this.bottomPixels;
  6709. }
  6710. var topPixels = 0;
  6711. if (!isTopAuto) {
  6712. this._computePixels(0, sourceArea, true);
  6713. topPixels = this.topPixels;
  6714. }
  6715. dstOffset.y = Math.round(sourceArea.height - ((height * sy) + topPixels));
  6716. dstArea.height = height;
  6717. dstOffset.w = bottomPixels;
  6718. if (computeLayoutArea) {
  6719. dstArea.height += bottomPixels + topPixels;
  6720. }
  6721. // console.log(`Compute Alignment Source Area: ${sourceArea}, Content Size: ${contentSize}`);
  6722. break;
  6723. }
  6724. case PrimitiveAlignment.AlignStretch:
  6725. {
  6726. if (isBottomAuto) {
  6727. dstOffset.y = 0;
  6728. }
  6729. else {
  6730. this._computePixels(3, sourceArea, true);
  6731. dstOffset.y = this.bottomPixels;
  6732. }
  6733. var top_1 = 0;
  6734. if (!isTopAuto) {
  6735. this._computePixels(0, sourceArea, true);
  6736. top_1 = this.topPixels;
  6737. }
  6738. if (computeLayoutArea) {
  6739. dstArea.height = sourceArea.height;
  6740. }
  6741. else {
  6742. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  6743. }
  6744. dstOffset.w = this.topPixels;
  6745. break;
  6746. }
  6747. case PrimitiveAlignment.AlignCenter:
  6748. {
  6749. if (!isTopAuto) {
  6750. this._computePixels(0, sourceArea, true);
  6751. }
  6752. if (!isBottomAuto) {
  6753. this._computePixels(3, sourceArea, true);
  6754. }
  6755. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  6756. var center = (sourceArea.height - (height * sy)) / 2;
  6757. dstOffset.y = Math.round(center + offset);
  6758. if (computeLayoutArea) {
  6759. dstArea.height = height + this.bottomPixels + this.topPixels;
  6760. }
  6761. else {
  6762. dstArea.height = height;
  6763. }
  6764. dstOffset.w = Math.round(center - offset);
  6765. break;
  6766. }
  6767. }
  6768. }
  6769. };
  6770. /**
  6771. * Compute an area and its position considering this thickness properties based on a given source area
  6772. * @param sourceArea the source area
  6773. * @param dstOffset the position of the resulting area
  6774. * @param dstArea the size of the resulting area
  6775. */
  6776. PrimitiveThickness.prototype.compute = function (sourceArea, sourceAreaScale, dstOffset, dstArea, computeLayoutArea) {
  6777. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  6778. this._computePixels(0, sourceArea, true);
  6779. this._computePixels(1, sourceArea, true);
  6780. this._computePixels(2, sourceArea, true);
  6781. this._computePixels(3, sourceArea, true);
  6782. var sx = sourceAreaScale.x;
  6783. var sy = sourceAreaScale.y;
  6784. dstOffset.x = this.leftPixels;
  6785. if (computeLayoutArea) {
  6786. dstArea.width = (sourceArea.width * sx) + (dstOffset.x + this.rightPixels);
  6787. }
  6788. else {
  6789. dstArea.width = (sourceArea.width * sx) - (dstOffset.x + this.rightPixels);
  6790. }
  6791. dstOffset.y = this.bottomPixels;
  6792. if (computeLayoutArea) {
  6793. dstArea.height = (sourceArea.height * sy) + (dstOffset.y + this.topPixels);
  6794. }
  6795. else {
  6796. dstArea.height = (sourceArea.height * sy) - (dstOffset.y + this.topPixels);
  6797. }
  6798. dstOffset.z = this.rightPixels;
  6799. dstOffset.w = this.topPixels;
  6800. };
  6801. /**
  6802. * Compute an area considering this thickness properties based on a given source area
  6803. * @param sourceArea the source area
  6804. * @param result the resulting area
  6805. */
  6806. PrimitiveThickness.prototype.computeArea = function (sourceArea, sourceScale, result) {
  6807. this._computePixels(0, sourceArea, true);
  6808. this._computePixels(1, sourceArea, true);
  6809. this._computePixels(2, sourceArea, true);
  6810. this._computePixels(3, sourceArea, true);
  6811. result.width = this.leftPixels + (sourceArea.width * sourceScale.x) + this.rightPixels;
  6812. result.height = this.bottomPixels + (sourceArea.height * sourceScale.y) + this.topPixels;
  6813. };
  6814. PrimitiveThickness.prototype.enlarge = function (sourceArea, sourceScale, dstOffset, enlargedArea) {
  6815. this._computePixels(0, sourceArea, true);
  6816. this._computePixels(1, sourceArea, true);
  6817. this._computePixels(2, sourceArea, true);
  6818. this._computePixels(3, sourceArea, true);
  6819. dstOffset.x = this.leftPixels;
  6820. enlargedArea.width = (sourceArea.width * sourceScale.x) + (dstOffset.x + this.rightPixels);
  6821. dstOffset.y = this.bottomPixels;
  6822. enlargedArea.height = (sourceArea.height * sourceScale.y) + (dstOffset.y + this.topPixels);
  6823. dstOffset.z = this.rightPixels;
  6824. dstOffset.w = this.topPixels;
  6825. };
  6826. return PrimitiveThickness;
  6827. }());
  6828. PrimitiveThickness.Auto = 0x1;
  6829. PrimitiveThickness.Inherit = 0x2;
  6830. PrimitiveThickness.Percentage = 0x4;
  6831. PrimitiveThickness.Pixel = 0x8;
  6832. PrimitiveThickness.ComputeH = 0x1;
  6833. PrimitiveThickness.ComputeV = 0x2;
  6834. PrimitiveThickness.ComputeAll = 0x03;
  6835. PrimitiveThickness = PrimitiveThickness_1 = __decorate([
  6836. BABYLON.className("PrimitiveThickness", "BABYLON")
  6837. ], PrimitiveThickness);
  6838. BABYLON.PrimitiveThickness = PrimitiveThickness;
  6839. /**
  6840. * Main class used for the Primitive Intersection API
  6841. */
  6842. var IntersectInfo2D = (function () {
  6843. function IntersectInfo2D() {
  6844. this.findFirstOnly = false;
  6845. this.intersectHidden = false;
  6846. this.pickPosition = BABYLON.Vector2.Zero();
  6847. }
  6848. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  6849. /**
  6850. * true if at least one primitive intersected during the test
  6851. */
  6852. get: function () {
  6853. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  6854. },
  6855. enumerable: true,
  6856. configurable: true
  6857. });
  6858. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  6859. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  6860. var cur = _a[_i];
  6861. if (cur.prim === prim) {
  6862. return cur.intersectionLocation;
  6863. }
  6864. }
  6865. return null;
  6866. };
  6867. // Internals, don't use
  6868. IntersectInfo2D.prototype._exit = function (firstLevel) {
  6869. if (firstLevel) {
  6870. this._globalPickPosition = null;
  6871. }
  6872. };
  6873. return IntersectInfo2D;
  6874. }());
  6875. BABYLON.IntersectInfo2D = IntersectInfo2D;
  6876. var Prim2DBase = Prim2DBase_1 = (function (_super) {
  6877. __extends(Prim2DBase, _super);
  6878. function Prim2DBase(settings) {
  6879. var _this;
  6880. // Avoid checking every time if the object exists
  6881. if (settings == null) {
  6882. settings = {};
  6883. }
  6884. // BASE CLASS CALL
  6885. _this = _super.call(this) || this;
  6886. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  6887. var owner;
  6888. var parent;
  6889. if (Prim2DBase_1._isCanvasInit) {
  6890. owner = _this;
  6891. parent = null;
  6892. _this._canvasPreInit(settings);
  6893. }
  6894. else {
  6895. if (settings.parent != null) {
  6896. parent = settings.parent;
  6897. owner = settings.parent.owner;
  6898. if (!owner) {
  6899. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  6900. }
  6901. if (!(_this instanceof BABYLON.Group2D) && !(_this instanceof BABYLON.Sprite2D && settings.id != null && settings.id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  6902. throw new Error("Can't create a primitive with the canvas as direct parent when the caching strategy is TOPLEVELGROUPS. You need to create a Group below the canvas and use it as the parent for the primitive");
  6903. }
  6904. }
  6905. }
  6906. // Fields initialization
  6907. _this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  6908. _this._size = null; //Size.Zero();
  6909. _this._scale = new BABYLON.Vector2(1, 1);
  6910. _this._postScale = new BABYLON.Vector2(1, 1);
  6911. _this._actualSize = null;
  6912. _this._internalSize = BABYLON.Size.Zero();
  6913. _this._layoutArea = null;
  6914. _this._layoutAreaPos = null;
  6915. _this._layoutBoundingInfo = null;
  6916. _this._marginOffset = BABYLON.Vector4.Zero();
  6917. _this._paddingOffset = BABYLON.Vector4.Zero();
  6918. _this._parentPaddingOffset = BABYLON.Vector2.Zero();
  6919. _this._parentContentArea = BABYLON.Size.Zero();
  6920. _this._lastAutoSizeArea = BABYLON.Size.Zero();
  6921. _this._contentArea = BABYLON.Size.Zero();
  6922. _this._marginSize = null;
  6923. _this._pointerEventObservable = new BABYLON.Observable();
  6924. _this._owner = owner;
  6925. _this._parent = null;
  6926. _this._margin = null;
  6927. _this._padding = null;
  6928. _this._marginAlignment = null;
  6929. _this._id = settings.id;
  6930. _this._children = new Array();
  6931. _this._localTransform = new BABYLON.Matrix();
  6932. _this._localLayoutTransform = new BABYLON.Matrix();
  6933. _this._globalTransform = null;
  6934. _this._invGlobalTransform = null;
  6935. _this._globalTransformProcessStep = 0;
  6936. _this._globalTransformStep = 0;
  6937. _this._renderGroup = null;
  6938. _this._primLinearPosition = 0;
  6939. _this._manualZOrder = null;
  6940. _this._zOrder = 0;
  6941. _this._zMax = 0;
  6942. _this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  6943. _this._actualOpacity = 0;
  6944. _this._actualScale = BABYLON.Vector2.Zero();
  6945. _this._displayDebugAreas = false;
  6946. _this._debugAreaGroup = null;
  6947. _this._primTriArray = null;
  6948. _this._primTriArrayDirty = true;
  6949. if (owner) {
  6950. _this.onSetOwner();
  6951. }
  6952. _this._levelBoundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  6953. _this._boundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  6954. var isPickable = true;
  6955. var isContainer = true;
  6956. if (settings.isPickable !== undefined) {
  6957. isPickable = settings.isPickable;
  6958. }
  6959. if (settings.isContainer !== undefined) {
  6960. isContainer = settings.isContainer;
  6961. }
  6962. if (settings.dontInheritParentScale) {
  6963. _this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  6964. }
  6965. _this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  6966. if (settings.opacity != null) {
  6967. _this._opacity = settings.opacity;
  6968. }
  6969. else {
  6970. _this._opacity = 1;
  6971. }
  6972. _this._updateRenderMode();
  6973. if (settings.childrenFlatZOrder) {
  6974. _this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  6975. }
  6976. // If the parent is given, initialize the hierarchy/owner related data
  6977. if (parent != null) {
  6978. parent.addChild(_this);
  6979. _this._hierarchyDepth = parent._hierarchyDepth + 1;
  6980. _this._patchHierarchy(parent.owner);
  6981. }
  6982. // If it's a group, detect its own states
  6983. if (_this.owner && _this instanceof BABYLON.Group2D) {
  6984. var group = _this;
  6985. group.detectGroupStates();
  6986. }
  6987. // Time to insert children if some are specified
  6988. if (settings.children != null) {
  6989. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  6990. var child = _a[_i];
  6991. _this.addChild(child);
  6992. // Good time to patch the hierarchy, it won't go very far if there's no need to
  6993. if (_this.owner != null && _this._hierarchyDepth != null) {
  6994. child._patchHierarchy(_this.owner);
  6995. }
  6996. }
  6997. }
  6998. if (settings.zOrder != null) {
  6999. _this.zOrder = settings.zOrder;
  7000. }
  7001. // Set the model related properties
  7002. if (settings.position != null) {
  7003. _this.position = settings.position;
  7004. }
  7005. else if (settings.x != null || settings.y != null) {
  7006. _this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  7007. }
  7008. else {
  7009. _this._position = null;
  7010. }
  7011. _this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  7012. if (settings.scale != null) {
  7013. _this.scale = settings.scale;
  7014. }
  7015. else {
  7016. if (settings.scaleX != null) {
  7017. _this.scaleX = settings.scaleX;
  7018. }
  7019. if (settings.scaleY != null) {
  7020. _this.scaleY = settings.scaleY;
  7021. }
  7022. }
  7023. _this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  7024. _this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  7025. // Layout Engine
  7026. if (settings.layoutEngine != null) {
  7027. if (typeof settings.layoutEngine === "string") {
  7028. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  7029. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  7030. _this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  7031. }
  7032. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  7033. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  7034. }
  7035. else if (name_1.indexOf("verticalstackpanel") === 0) {
  7036. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  7037. }
  7038. }
  7039. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  7040. _this.layoutEngine = settings.layoutEngine;
  7041. }
  7042. }
  7043. // Set the layout/margin stuffs
  7044. if (settings.marginTop) {
  7045. _this.margin.setTop(settings.marginTop);
  7046. }
  7047. if (settings.marginLeft) {
  7048. _this.margin.setLeft(settings.marginLeft);
  7049. }
  7050. if (settings.marginRight) {
  7051. _this.margin.setRight(settings.marginRight);
  7052. }
  7053. if (settings.marginBottom) {
  7054. _this.margin.setBottom(settings.marginBottom);
  7055. }
  7056. if (settings.margin) {
  7057. if (typeof settings.margin === "string") {
  7058. _this.margin.fromString(settings.margin);
  7059. }
  7060. else {
  7061. _this.margin.fromUniformPixels(settings.margin);
  7062. }
  7063. }
  7064. if (settings.marginHAlignment) {
  7065. _this.marginAlignment.horizontal = settings.marginHAlignment;
  7066. }
  7067. if (settings.marginVAlignment) {
  7068. _this.marginAlignment.vertical = settings.marginVAlignment;
  7069. }
  7070. if (settings.marginAlignment) {
  7071. _this.marginAlignment.fromString(settings.marginAlignment);
  7072. }
  7073. if (settings.paddingTop) {
  7074. _this.padding.setTop(settings.paddingTop);
  7075. }
  7076. if (settings.paddingLeft) {
  7077. _this.padding.setLeft(settings.paddingLeft);
  7078. }
  7079. if (settings.paddingRight) {
  7080. _this.padding.setRight(settings.paddingRight);
  7081. }
  7082. if (settings.paddingBottom) {
  7083. _this.padding.setBottom(settings.paddingBottom);
  7084. }
  7085. if (settings.padding) {
  7086. if (typeof settings.padding === "string") {
  7087. _this.padding.fromString(settings.padding);
  7088. }
  7089. else {
  7090. _this.padding.fromUniformPixels(settings.padding);
  7091. }
  7092. }
  7093. if (settings.layoutData) {
  7094. _this.layoutData = settings.layoutData;
  7095. }
  7096. _this._updatePositioningState();
  7097. // Dirty layout and positioning
  7098. _this._parentLayoutDirty();
  7099. _this._positioningDirty();
  7100. // Add in the PCM
  7101. if (settings.levelCollision || settings.deepCollision) {
  7102. _this._actorInfo = _this.owner._primitiveCollisionManager._addActor(_this, settings.deepCollision === true);
  7103. _this._setFlags(BABYLON.SmartPropertyPrim.flagCollisionActor);
  7104. }
  7105. else {
  7106. _this._actorInfo = null;
  7107. }
  7108. return _this;
  7109. }
  7110. Object.defineProperty(Prim2DBase.prototype, "intersectWithObservable", {
  7111. /**
  7112. * Return the ChangedDictionary observable of the StringDictionary containing the primitives intersecting with this one
  7113. */
  7114. get: function () {
  7115. if (!this._actorInfo) {
  7116. return null;
  7117. }
  7118. return this._actorInfo.intersectWith.dictionaryChanged;
  7119. },
  7120. enumerable: true,
  7121. configurable: true
  7122. });
  7123. Object.defineProperty(Prim2DBase.prototype, "intersectWith", {
  7124. /**
  7125. * Return the ObservableStringDictionary containing all the primitives intersecting with this one.
  7126. * The key is the primitive uid, the value is the ActorInfo object
  7127. * @returns {}
  7128. */
  7129. get: function () {
  7130. if (!this._actorInfo) {
  7131. return null;
  7132. }
  7133. return this._actorInfo.intersectWith;
  7134. },
  7135. enumerable: true,
  7136. configurable: true
  7137. });
  7138. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  7139. get: function () {
  7140. if (!this._actionManager) {
  7141. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  7142. }
  7143. return this._actionManager;
  7144. },
  7145. enumerable: true,
  7146. configurable: true
  7147. });
  7148. /**
  7149. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  7150. * @param predicate the predicate to test on each parent
  7151. * @return the first primitive where the predicate was successful
  7152. */
  7153. Prim2DBase.prototype.traverseUp = function (predicate) {
  7154. var p = this;
  7155. while (p != null) {
  7156. if (predicate(p)) {
  7157. return p;
  7158. }
  7159. p = p._parent;
  7160. }
  7161. return null;
  7162. };
  7163. Object.defineProperty(Prim2DBase.prototype, "owner", {
  7164. /**
  7165. * Retrieve the owner Canvas2D
  7166. */
  7167. get: function () {
  7168. return this._owner;
  7169. },
  7170. enumerable: true,
  7171. configurable: true
  7172. });
  7173. Object.defineProperty(Prim2DBase.prototype, "parent", {
  7174. /**
  7175. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  7176. */
  7177. get: function () {
  7178. return this._parent;
  7179. },
  7180. enumerable: true,
  7181. configurable: true
  7182. });
  7183. Object.defineProperty(Prim2DBase.prototype, "children", {
  7184. /**
  7185. * The array of direct children primitives
  7186. */
  7187. get: function () {
  7188. return this._children;
  7189. },
  7190. enumerable: true,
  7191. configurable: true
  7192. });
  7193. Object.defineProperty(Prim2DBase.prototype, "id", {
  7194. /**
  7195. * The identifier of this primitive, may not be unique, it's for information purpose only
  7196. */
  7197. get: function () {
  7198. return this._id;
  7199. },
  7200. set: function (value) {
  7201. if (this._id === value) {
  7202. return;
  7203. }
  7204. var oldValue = this._id;
  7205. this.onPropertyChanged("id", oldValue, this._id);
  7206. },
  7207. enumerable: true,
  7208. configurable: true
  7209. });
  7210. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  7211. get: function () {
  7212. // If we don't use positioning engine the actual position is the position
  7213. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  7214. return this.position;
  7215. }
  7216. // We use the positioning engine, if the variable is fetched, it's up to date, return it
  7217. if (this._actualPosition != null) {
  7218. return this._actualPosition;
  7219. }
  7220. this._updatePositioning();
  7221. return this._actualPosition;
  7222. },
  7223. /**
  7224. * DO NOT INVOKE for internal purpose only
  7225. */
  7226. set: function (val) {
  7227. if (!this._actualPosition) {
  7228. this._actualPosition = val.clone();
  7229. }
  7230. else {
  7231. this._actualPosition.copyFrom(val);
  7232. }
  7233. },
  7234. enumerable: true,
  7235. configurable: true
  7236. });
  7237. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  7238. /**
  7239. * Shortcut to actualPosition.x
  7240. */
  7241. get: function () {
  7242. return this.actualPosition.x;
  7243. },
  7244. set: function (val) {
  7245. this._actualPosition.x = val;
  7246. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  7247. },
  7248. enumerable: true,
  7249. configurable: true
  7250. });
  7251. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  7252. /**
  7253. * Shortcut to actualPosition.y
  7254. */
  7255. get: function () {
  7256. return this.actualPosition.y;
  7257. },
  7258. set: function (val) {
  7259. this._actualPosition.y = val;
  7260. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  7261. },
  7262. enumerable: true,
  7263. configurable: true
  7264. });
  7265. Object.defineProperty(Prim2DBase.prototype, "position", {
  7266. /**
  7267. * Position of the primitive, relative to its parent.
  7268. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  7269. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  7270. * Setting this property may have no effect is specific alignment are in effect.
  7271. */
  7272. get: function () {
  7273. if (!this._position) {
  7274. this._position = BABYLON.Vector2.Zero();
  7275. }
  7276. return this._position;
  7277. },
  7278. set: function (value) {
  7279. if (!this._checkPositionChange()) {
  7280. return;
  7281. }
  7282. if (!value) {
  7283. this._position = null;
  7284. }
  7285. else {
  7286. if (!this._position) {
  7287. this._position = value.clone();
  7288. }
  7289. else {
  7290. this._position.copyFrom(value);
  7291. }
  7292. }
  7293. this._actualPosition = null;
  7294. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  7295. },
  7296. enumerable: true,
  7297. configurable: true
  7298. });
  7299. Object.defineProperty(Prim2DBase.prototype, "x", {
  7300. /**
  7301. * Direct access to the position.x value of the primitive
  7302. * Use this property when you only want to change one component of the position property
  7303. */
  7304. get: function () {
  7305. if (!this._position) {
  7306. return null;
  7307. }
  7308. return this._position.x;
  7309. },
  7310. set: function (value) {
  7311. if (!this._checkPositionChange()) {
  7312. return;
  7313. }
  7314. if (value == null) {
  7315. throw new Error("Can't set a null x in primitive " + this.id + ", only the position can be turned to null");
  7316. }
  7317. if (!this._position) {
  7318. this._position = BABYLON.Vector2.Zero();
  7319. }
  7320. if (this._position.x === value) {
  7321. return;
  7322. }
  7323. this._position.x = value;
  7324. this._actualPosition = null;
  7325. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  7326. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  7327. },
  7328. enumerable: true,
  7329. configurable: true
  7330. });
  7331. Object.defineProperty(Prim2DBase.prototype, "y", {
  7332. /**
  7333. * Direct access to the position.y value of the primitive
  7334. * Use this property when you only want to change one component of the position property
  7335. */
  7336. get: function () {
  7337. if (!this._position) {
  7338. return null;
  7339. }
  7340. return this._position.y;
  7341. },
  7342. set: function (value) {
  7343. if (!this._checkPositionChange()) {
  7344. return;
  7345. }
  7346. if (value == null) {
  7347. throw new Error("Can't set a null y in primitive " + this.id + ", only the position can be turned to null");
  7348. }
  7349. if (!this._position) {
  7350. this._position = BABYLON.Vector2.Zero();
  7351. }
  7352. if (this._position.y === value) {
  7353. return;
  7354. }
  7355. this._position.y = value;
  7356. this._actualPosition = null;
  7357. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  7358. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  7359. },
  7360. enumerable: true,
  7361. configurable: true
  7362. });
  7363. Object.defineProperty(Prim2DBase.prototype, "size", {
  7364. /**
  7365. * Size of the primitive or its bounding area
  7366. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  7367. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  7368. */
  7369. get: function () {
  7370. return this.internalGetSize();
  7371. },
  7372. set: function (value) {
  7373. this.internalSetSize(value);
  7374. },
  7375. enumerable: true,
  7376. configurable: true
  7377. });
  7378. Prim2DBase.prototype.internalGetSize = function () {
  7379. if (!this._size || this._size.width == null || this._size.height == null) {
  7380. var bbr = Prim2DBase_1.boundinbBoxReentrency;
  7381. if (bbr !== -1 && bbr <= (this.hierarchyDepth || 0)) {
  7382. return Prim2DBase_1.nullSize;
  7383. }
  7384. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  7385. return this._internalSize;
  7386. }
  7387. Prim2DBase_1.boundinbBoxReentrency = this.hierarchyDepth || 0;
  7388. var b = this.layoutBoundingInfo;
  7389. Prim2DBase_1.boundinbBoxReentrency = -1;
  7390. Prim2DBase_1._size.copyFrom(this._internalSize);
  7391. b.sizeToRef(this._internalSize);
  7392. if (!this._internalSize.equals(Prim2DBase_1._size)) {
  7393. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, this._internalSize);
  7394. this._positioningDirty();
  7395. }
  7396. return this._internalSize || Prim2DBase_1._nullSize;
  7397. }
  7398. return this._size || Prim2DBase_1._nullSize;
  7399. };
  7400. Prim2DBase.prototype.internalSetSize = function (value) {
  7401. if (!value) {
  7402. this._size = null;
  7403. }
  7404. else {
  7405. if (!this._size) {
  7406. this._size = value.clone();
  7407. }
  7408. else {
  7409. this._size.copyFrom(value);
  7410. }
  7411. }
  7412. this._actualSize = null;
  7413. this._updatePositioningState();
  7414. this._positioningDirty();
  7415. };
  7416. Object.defineProperty(Prim2DBase.prototype, "width", {
  7417. /**
  7418. * Direct access to the size.width value of the primitive
  7419. * Use this property when you only want to change one component of the size property
  7420. */
  7421. get: function () {
  7422. if (!this.size) {
  7423. return null;
  7424. }
  7425. return this.size.width;
  7426. },
  7427. set: function (value) {
  7428. if (this.size && this.size.width === value) {
  7429. return;
  7430. }
  7431. if (!this.size) {
  7432. this.size = new BABYLON.Size(value, 0);
  7433. }
  7434. else {
  7435. this.size.width = value;
  7436. }
  7437. this._actualSize = null;
  7438. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  7439. this._positioningDirty();
  7440. },
  7441. enumerable: true,
  7442. configurable: true
  7443. });
  7444. Object.defineProperty(Prim2DBase.prototype, "height", {
  7445. /**
  7446. * Direct access to the size.height value of the primitive
  7447. * Use this property when you only want to change one component of the size property
  7448. */
  7449. get: function () {
  7450. if (!this.size) {
  7451. return null;
  7452. }
  7453. return this.size.height;
  7454. },
  7455. set: function (value) {
  7456. if (this.size && this.size.height === value) {
  7457. return;
  7458. }
  7459. if (!this.size) {
  7460. this.size = new BABYLON.Size(0, value);
  7461. }
  7462. else {
  7463. this.size.height = value;
  7464. }
  7465. this._actualSize = null;
  7466. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  7467. this._positioningDirty();
  7468. },
  7469. enumerable: true,
  7470. configurable: true
  7471. });
  7472. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  7473. get: function () {
  7474. return this._rotation;
  7475. },
  7476. set: function (value) {
  7477. this._rotation = value;
  7478. },
  7479. enumerable: true,
  7480. configurable: true
  7481. });
  7482. Object.defineProperty(Prim2DBase.prototype, "scale", {
  7483. get: function () {
  7484. return this._scale.x;
  7485. },
  7486. set: function (value) {
  7487. this._scale.x = this._scale.y = value;
  7488. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7489. this._spreadActualScaleDirty();
  7490. this._positioningDirty();
  7491. },
  7492. enumerable: true,
  7493. configurable: true
  7494. });
  7495. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  7496. /**
  7497. * Return the size of the primitive as it's being rendered into the target.
  7498. * This value may be different of the size property when layout/alignment is used or specific primitive types can implement a custom logic through this property.
  7499. * BEWARE: don't use the setter, it's for internal purpose only
  7500. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  7501. */
  7502. get: function () {
  7503. // If we don't use positioning engine the actual size is the size
  7504. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  7505. return this.size;
  7506. }
  7507. // We use the positioning engine, if the variable is fetched, it's up to date, return it
  7508. if (this._actualSize) {
  7509. return this._actualSize;
  7510. }
  7511. this._updatePositioning();
  7512. return this._actualSize;
  7513. },
  7514. set: function (value) {
  7515. if (this._actualSize && this._actualSize.equals(value)) {
  7516. return;
  7517. }
  7518. if (!this._actualSize) {
  7519. this._actualSize = value.clone();
  7520. }
  7521. else {
  7522. this._actualSize.copyFrom(value);
  7523. }
  7524. },
  7525. enumerable: true,
  7526. configurable: true
  7527. });
  7528. Object.defineProperty(Prim2DBase.prototype, "actualWidth", {
  7529. /**
  7530. * Shortcut to actualSize.width
  7531. */
  7532. get: function () {
  7533. return this.actualSize.width;
  7534. },
  7535. set: function (val) {
  7536. this._actualSize.width = val;
  7537. this._triggerPropertyChanged(Prim2DBase_1.actualSizeProperty, this._actualSize);
  7538. },
  7539. enumerable: true,
  7540. configurable: true
  7541. });
  7542. Object.defineProperty(Prim2DBase.prototype, "actualHeight", {
  7543. /**
  7544. * Shortcut to actualPosition.height
  7545. */
  7546. get: function () {
  7547. return this.actualSize.height;
  7548. },
  7549. set: function (val) {
  7550. this._actualSize.height = val;
  7551. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualSize);
  7552. },
  7553. enumerable: true,
  7554. configurable: true
  7555. });
  7556. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  7557. get: function () {
  7558. if (this._manualZOrder != null) {
  7559. return this._manualZOrder;
  7560. }
  7561. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7562. this._updateZOrder();
  7563. }
  7564. return (1 - this._zOrder);
  7565. },
  7566. enumerable: true,
  7567. configurable: true
  7568. });
  7569. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  7570. /**
  7571. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  7572. * The Primitive's size won't be less than specified.
  7573. * The default value depends of the Primitive type
  7574. */
  7575. get: function () {
  7576. return this._minSize;
  7577. },
  7578. set: function (value) {
  7579. if (this._minSize && value && this._minSize.equals(value)) {
  7580. return;
  7581. }
  7582. if (!this._minSize) {
  7583. this._minSize = value.clone();
  7584. }
  7585. else {
  7586. this._minSize.copyFrom(value);
  7587. }
  7588. this._parentLayoutDirty();
  7589. },
  7590. enumerable: true,
  7591. configurable: true
  7592. });
  7593. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  7594. /**
  7595. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  7596. * The Primitive's size won't be more than specified.
  7597. * The default value depends of the Primitive type
  7598. */
  7599. get: function () {
  7600. return this._maxSize;
  7601. },
  7602. set: function (value) {
  7603. if (this._maxSize && value && this._maxSize.equals(value)) {
  7604. return;
  7605. }
  7606. if (!this._maxSize) {
  7607. this._maxSize = value.clone();
  7608. }
  7609. else {
  7610. this._maxSize.copyFrom(value);
  7611. }
  7612. this._parentLayoutDirty();
  7613. },
  7614. enumerable: true,
  7615. configurable: true
  7616. });
  7617. Object.defineProperty(Prim2DBase.prototype, "origin", {
  7618. /**
  7619. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  7620. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  7621. * For instance:
  7622. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  7623. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  7624. * 0,1 means the center is top/left
  7625. * @returns The normalized center.
  7626. */
  7627. get: function () {
  7628. return this._origin;
  7629. },
  7630. set: function (value) {
  7631. if (!this._origin) {
  7632. this._origin = value.clone();
  7633. }
  7634. else {
  7635. this._origin.copyFrom(value);
  7636. }
  7637. },
  7638. enumerable: true,
  7639. configurable: true
  7640. });
  7641. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  7642. get: function () {
  7643. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  7644. },
  7645. set: function (value) {
  7646. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  7652. get: function () {
  7653. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  7654. },
  7655. set: function (value) {
  7656. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  7657. },
  7658. enumerable: true,
  7659. configurable: true
  7660. });
  7661. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  7662. get: function () {
  7663. return this._manualZOrder;
  7664. },
  7665. set: function (value) {
  7666. if (this._manualZOrder === value) {
  7667. return;
  7668. }
  7669. this._manualZOrder = value;
  7670. this.onZOrderChanged();
  7671. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  7672. this._actualZOrderChangedObservable.notifyObservers(value);
  7673. }
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  7679. get: function () {
  7680. return this._manualZOrder != null;
  7681. },
  7682. enumerable: true,
  7683. configurable: true
  7684. });
  7685. Object.defineProperty(Prim2DBase.prototype, "margin", {
  7686. get: function () {
  7687. var _this = this;
  7688. if (!this._margin) {
  7689. this._margin = new PrimitiveThickness(function () {
  7690. if (!_this.parent) {
  7691. return null;
  7692. }
  7693. return _this.parent.margin;
  7694. }, function () { return _this._positioningDirty(); });
  7695. this._updatePositioningState();
  7696. }
  7697. return this._margin;
  7698. },
  7699. set: function (value) {
  7700. if (!value) {
  7701. this._margin = null;
  7702. }
  7703. else {
  7704. this.margin.copyFrom(value);
  7705. }
  7706. this._updatePositioningState();
  7707. },
  7708. enumerable: true,
  7709. configurable: true
  7710. });
  7711. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  7712. /**
  7713. * Check for both margin and marginAlignment, return true if at least one of them is specified with a non default value
  7714. */
  7715. get: function () {
  7716. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. Object.defineProperty(Prim2DBase.prototype, "padding", {
  7722. get: function () {
  7723. var _this = this;
  7724. if (!this._padding) {
  7725. this._padding = new PrimitiveThickness(function () {
  7726. if (!_this.parent) {
  7727. return null;
  7728. }
  7729. return _this.parent.padding;
  7730. }, function () { return _this._positioningDirty(); });
  7731. this._updatePositioningState();
  7732. }
  7733. return this._padding;
  7734. },
  7735. set: function (value) {
  7736. if (!value) {
  7737. this._padding = null;
  7738. }
  7739. else {
  7740. this.padding.copyFrom(value);
  7741. }
  7742. this._updatePositioningState();
  7743. },
  7744. enumerable: true,
  7745. configurable: true
  7746. });
  7747. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  7748. get: function () {
  7749. return this._padding !== null && !this._padding.isDefault;
  7750. },
  7751. enumerable: true,
  7752. configurable: true
  7753. });
  7754. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  7755. get: function () {
  7756. var _this = this;
  7757. if (!this._marginAlignment) {
  7758. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  7759. this._updatePositioningState();
  7760. }
  7761. return this._marginAlignment;
  7762. },
  7763. set: function (value) {
  7764. if (!value) {
  7765. this._marginAlignment = null;
  7766. }
  7767. else {
  7768. this.marginAlignment.copyFrom(value);
  7769. }
  7770. this._updatePositioningState();
  7771. },
  7772. enumerable: true,
  7773. configurable: true
  7774. });
  7775. Object.defineProperty(Prim2DBase.prototype, "_hasMarginAlignment", {
  7776. /**
  7777. * Check if there a marginAlignment specified (non null and not default)
  7778. */
  7779. get: function () {
  7780. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  7781. },
  7782. enumerable: true,
  7783. configurable: true
  7784. });
  7785. Prim2DBase.prototype._updatePositioningState = function () {
  7786. var value = this._hasMargin || this._hasPadding || this.isSizeAuto;
  7787. // console.log(`${this.id} with parent ${this._parent ? this._parent.id : "[none]"} state: ${value} `);
  7788. this._changeFlags(BABYLON.SmartPropertyPrim.flagUsePositioning, value);
  7789. };
  7790. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  7791. get: function () {
  7792. return this._opacity;
  7793. },
  7794. set: function (value) {
  7795. if (value < 0) {
  7796. value = 0;
  7797. }
  7798. else if (value > 1) {
  7799. value = 1;
  7800. }
  7801. if (this._opacity === value) {
  7802. return;
  7803. }
  7804. this._opacity = value;
  7805. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  7806. this._spreadActualOpacityChanged();
  7807. this._updateRenderMode();
  7808. },
  7809. enumerable: true,
  7810. configurable: true
  7811. });
  7812. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  7813. get: function () {
  7814. return this._scale.x;
  7815. },
  7816. set: function (value) {
  7817. this._scale.x = value;
  7818. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7819. this._spreadActualScaleDirty();
  7820. this._positioningDirty();
  7821. },
  7822. enumerable: true,
  7823. configurable: true
  7824. });
  7825. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  7826. get: function () {
  7827. return this._scale.y;
  7828. },
  7829. set: function (value) {
  7830. this._scale.y = value;
  7831. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7832. this._spreadActualScaleDirty();
  7833. this._positioningDirty();
  7834. },
  7835. enumerable: true,
  7836. configurable: true
  7837. });
  7838. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  7839. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7840. var child = _a[_i];
  7841. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7842. child._spreadActualScaleDirty();
  7843. }
  7844. };
  7845. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  7846. /**
  7847. * Returns the actual scale of this Primitive, the value is computed from the scale property of this primitive, multiplied by the actualScale of its parent one (if any). The Vector2 object returned contains the scale for both X and Y axis
  7848. */
  7849. get: function () {
  7850. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  7851. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  7852. var sx = this.scaleX;
  7853. var sy = this.scaleY;
  7854. while (cur) {
  7855. sx *= cur.scaleX;
  7856. sy *= cur.scaleY;
  7857. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  7858. }
  7859. this._actualScale.copyFromFloats(sx, sy);
  7860. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7861. }
  7862. return this._actualScale;
  7863. },
  7864. enumerable: true,
  7865. configurable: true
  7866. });
  7867. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  7868. /**
  7869. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  7870. */
  7871. get: function () {
  7872. return this.actualScale.x;
  7873. },
  7874. enumerable: true,
  7875. configurable: true
  7876. });
  7877. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  7878. /**
  7879. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  7880. */
  7881. get: function () {
  7882. return this.actualScale.y;
  7883. },
  7884. enumerable: true,
  7885. configurable: true
  7886. });
  7887. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  7888. /**
  7889. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  7890. */
  7891. get: function () {
  7892. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  7893. var cur = this.parent;
  7894. var op = this.opacity;
  7895. while (cur) {
  7896. op *= cur.opacity;
  7897. cur = cur.parent;
  7898. }
  7899. this._actualOpacity = op;
  7900. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  7901. }
  7902. return this._actualOpacity;
  7903. },
  7904. enumerable: true,
  7905. configurable: true
  7906. });
  7907. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  7908. /**
  7909. * Get/set the layout engine to use for this primitive.
  7910. * The default layout engine is the CanvasLayoutEngine.
  7911. */
  7912. get: function () {
  7913. if (!this._layoutEngine) {
  7914. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  7915. }
  7916. return this._layoutEngine;
  7917. },
  7918. set: function (value) {
  7919. if (this._layoutEngine === value) {
  7920. return;
  7921. }
  7922. this._changeLayoutEngine(value);
  7923. },
  7924. enumerable: true,
  7925. configurable: true
  7926. });
  7927. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  7928. /**
  7929. * Get/set the layout are of this primitive.
  7930. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  7931. * The setter should only be called by a Layout Engine class.
  7932. */
  7933. get: function () {
  7934. return this._layoutArea;
  7935. },
  7936. set: function (val) {
  7937. if (this._layoutArea && this._layoutArea.equals(val)) {
  7938. return;
  7939. }
  7940. this._positioningDirty();
  7941. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  7942. if (this.parent) {
  7943. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7944. }
  7945. if (!this._layoutArea) {
  7946. this._layoutArea = val.clone();
  7947. }
  7948. else {
  7949. this._layoutArea.copyFrom(val);
  7950. }
  7951. },
  7952. enumerable: true,
  7953. configurable: true
  7954. });
  7955. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  7956. /**
  7957. * Get/set the layout area position (relative to the parent primitive).
  7958. * The setter should only be called by a Layout Engine class.
  7959. */
  7960. get: function () {
  7961. return this._layoutAreaPos;
  7962. },
  7963. set: function (val) {
  7964. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  7965. return;
  7966. }
  7967. if (this.parent) {
  7968. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7969. }
  7970. this._positioningDirty();
  7971. if (!this._layoutAreaPos) {
  7972. this._layoutAreaPos = val.clone();
  7973. }
  7974. else {
  7975. this._layoutAreaPos.copyFrom(val);
  7976. }
  7977. this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
  7978. },
  7979. enumerable: true,
  7980. configurable: true
  7981. });
  7982. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  7983. /**
  7984. * Define if the Primitive can be subject to intersection test or not (default is true)
  7985. */
  7986. get: function () {
  7987. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  7988. },
  7989. set: function (value) {
  7990. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  7991. },
  7992. enumerable: true,
  7993. configurable: true
  7994. });
  7995. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  7996. /**
  7997. * Define if the Primitive acts as a container or not
  7998. * A container will encapsulate its children for interaction event.
  7999. * If it's not a container events will be process down to children if the primitive is not pickable.
  8000. * Default value is true
  8001. */
  8002. get: function () {
  8003. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  8004. },
  8005. set: function (value) {
  8006. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  8007. },
  8008. enumerable: true,
  8009. configurable: true
  8010. });
  8011. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  8012. /**
  8013. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  8014. */
  8015. get: function () {
  8016. return this._hierarchyDepth;
  8017. },
  8018. enumerable: true,
  8019. configurable: true
  8020. });
  8021. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  8022. /**
  8023. * Retrieve the Group that is responsible to render this primitive
  8024. */
  8025. get: function () {
  8026. return this._renderGroup;
  8027. },
  8028. enumerable: true,
  8029. configurable: true
  8030. });
  8031. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  8032. /**
  8033. * Get the global transformation matrix of the primitive
  8034. */
  8035. get: function () {
  8036. if (this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  8037. this.updateCachedStates(false);
  8038. }
  8039. return this._globalTransform;
  8040. },
  8041. enumerable: true,
  8042. configurable: true
  8043. });
  8044. /**
  8045. * return the global position of the primitive, relative to its canvas
  8046. */
  8047. Prim2DBase.prototype.getGlobalPosition = function () {
  8048. var v = new BABYLON.Vector2(0, 0);
  8049. this.getGlobalPositionByRef(v);
  8050. return v;
  8051. };
  8052. /**
  8053. * return the global position of the primitive, relative to its canvas
  8054. * @param v the valid Vector2 object where the global position will be stored
  8055. */
  8056. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  8057. v.x = this.globalTransform.m[12];
  8058. v.y = this.globalTransform.m[13];
  8059. };
  8060. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  8061. /**
  8062. * Get invert of the global transformation matrix of the primitive
  8063. */
  8064. get: function () {
  8065. this._updateLocalTransform();
  8066. return this._invGlobalTransform;
  8067. },
  8068. enumerable: true,
  8069. configurable: true
  8070. });
  8071. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  8072. /**
  8073. * Get the local transformation of the primitive
  8074. */
  8075. get: function () {
  8076. this._updateLocalTransform();
  8077. return this._localTransform;
  8078. },
  8079. enumerable: true,
  8080. configurable: true
  8081. });
  8082. Object.defineProperty(Prim2DBase.prototype, "localLayoutTransform", {
  8083. get: function () {
  8084. this._updateLocalTransform();
  8085. return this._localLayoutTransform;
  8086. },
  8087. enumerable: true,
  8088. configurable: true
  8089. });
  8090. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  8091. /**
  8092. * Get the boundingInfo associated to the primitive and its children.
  8093. * The value is supposed to be always up to date
  8094. */
  8095. get: function () {
  8096. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  8097. if (this.owner) {
  8098. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  8099. }
  8100. var sizedByContent = this.isSizedByContent;
  8101. if (sizedByContent) {
  8102. this._boundingInfo.clear();
  8103. }
  8104. else {
  8105. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  8106. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  8107. return this._boundingInfo;
  8108. }
  8109. }
  8110. var bi = this._boundingInfo;
  8111. var tps = new BABYLON.BoundingInfo2D();
  8112. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8113. var curChild = _a[_i];
  8114. var bb = curChild.boundingInfo;
  8115. bb.transformToRef(curChild.localTransform, tps);
  8116. bi.unionToRef(tps, bi);
  8117. }
  8118. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  8119. }
  8120. return this._boundingInfo;
  8121. },
  8122. enumerable: true,
  8123. configurable: true
  8124. });
  8125. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  8126. /**
  8127. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  8128. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  8129. */
  8130. get: function () {
  8131. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  8132. if (this._owner) {
  8133. this._owner.addLayoutBoundingInfoUpdateCounter(1);
  8134. }
  8135. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  8136. this.owner.addUpdateLayoutCounter(1);
  8137. this._layoutEngine.updateLayout(this);
  8138. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  8139. }
  8140. var lbb = new BABYLON.BoundingInfo2D();
  8141. var sizedByContent = this.isSizedByContent;
  8142. if (sizedByContent) {
  8143. lbb.clear();
  8144. }
  8145. else {
  8146. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.marginSize, lbb);
  8147. }
  8148. var tps = Prim2DBase_1._tpsBB;
  8149. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8150. var curChild = _a[_i];
  8151. if (curChild._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  8152. continue;
  8153. }
  8154. var bb = curChild.layoutBoundingInfo;
  8155. bb.transformToRef(curChild.localLayoutTransform, tps);
  8156. lbb.unionToRef(tps, lbb);
  8157. }
  8158. // Update content area
  8159. Prim2DBase_1._curContentArea.copyFrom(this._contentArea);
  8160. var size = Prim2DBase_1._size2;
  8161. lbb.sizeToRef(this._contentArea);
  8162. lbb.sizeToRef(size);
  8163. if (!Prim2DBase_1._curContentArea.equals(this._contentArea)) {
  8164. this._setLayoutDirty();
  8165. }
  8166. // Apply padding
  8167. if (this._hasPadding) {
  8168. var padding = this.padding;
  8169. size.width += padding.leftPixels + padding.rightPixels;
  8170. size.height += padding.bottomPixels + padding.topPixels;
  8171. this._paddingOffset.copyFromFloats(padding.leftPixels, padding.bottomPixels, padding.rightPixels, padding.topPixels);
  8172. this._getActualSizeFromContentToRef(size, this._paddingOffset, size);
  8173. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, lbb);
  8174. }
  8175. else {
  8176. this._paddingOffset.copyFromFloats(0, 0, 0, 0);
  8177. }
  8178. // Check if the layoutBoundingInfo changed
  8179. var changed = false;
  8180. if (!this._layoutBoundingInfo) {
  8181. this._layoutBoundingInfo = lbb.clone();
  8182. changed = true;
  8183. }
  8184. else if (!this._layoutBoundingInfo.equals(lbb)) {
  8185. this._layoutBoundingInfo.copyFrom(lbb);
  8186. changed = true;
  8187. }
  8188. if (changed) {
  8189. var p = this._parent;
  8190. while (p) {
  8191. if (p.isSizedByContent) {
  8192. p._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  8193. p.onPrimitivePropertyDirty(Prim2DBase_1.actualSizeProperty.flagId);
  8194. }
  8195. else {
  8196. break;
  8197. }
  8198. p = p._parent;
  8199. }
  8200. this.onPrimitivePropertyDirty(Prim2DBase_1.actualSizeProperty.flagId);
  8201. }
  8202. //console.log(`Compute BoundingLayout of ${this.id}, extent: ${this._layoutBoundingInfo.extent}`);
  8203. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  8204. }
  8205. return this._layoutBoundingInfo;
  8206. },
  8207. enumerable: true,
  8208. configurable: true
  8209. });
  8210. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  8211. /**
  8212. * Determine if the size is automatically computed or fixed because manually specified.
  8213. * Use the actualSize property to get the final/real size of the primitive
  8214. * @returns true if the size is automatically computed, false if it were manually specified.
  8215. */
  8216. get: function () {
  8217. var size = this._size;
  8218. return size == null || (size.width == null && size.height == null);
  8219. },
  8220. enumerable: true,
  8221. configurable: true
  8222. });
  8223. Object.defineProperty(Prim2DBase.prototype, "isHorizontalSizeAuto", {
  8224. /**
  8225. * Determine if the horizontal size is automatically computed or fixed because manually specified.
  8226. * Use the actualSize property to get the final/real size of the primitive
  8227. * @returns true if the horizontal size is automatically computed, false if it were manually specified.
  8228. */
  8229. get: function () {
  8230. var size = this._size;
  8231. return size == null || size.width == null;
  8232. },
  8233. enumerable: true,
  8234. configurable: true
  8235. });
  8236. Object.defineProperty(Prim2DBase.prototype, "isVerticalSizeAuto", {
  8237. /**
  8238. * Determine if the vertical size is automatically computed or fixed because manually specified.
  8239. * Use the actualSize property to get the final/real size of the primitive
  8240. * @returns true if the vertical size is automatically computed, false if it were manually specified.
  8241. */
  8242. get: function () {
  8243. var size = this._size;
  8244. return size == null || size.height == null;
  8245. },
  8246. enumerable: true,
  8247. configurable: true
  8248. });
  8249. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  8250. /**
  8251. * Return true if this prim has an auto size which is set by the children's global bounding box
  8252. */
  8253. get: function () {
  8254. return (this._size == null) && (this._children.length > 0);
  8255. },
  8256. enumerable: true,
  8257. configurable: true
  8258. });
  8259. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  8260. /**
  8261. * Determine if the position is automatically computed or fixed because manually specified.
  8262. * Use the actualPosition property to get the final/real position of the primitive
  8263. * @returns true if the position is automatically computed, false if it were manually specified.
  8264. */
  8265. get: function () {
  8266. return this._position == null;
  8267. },
  8268. enumerable: true,
  8269. configurable: true
  8270. });
  8271. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  8272. /**
  8273. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  8274. */
  8275. get: function () {
  8276. return this._pointerEventObservable;
  8277. },
  8278. enumerable: true,
  8279. configurable: true
  8280. });
  8281. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  8282. get: function () {
  8283. if (!this._actualZOrderChangedObservable) {
  8284. this._actualZOrderChangedObservable = new BABYLON.Observable();
  8285. }
  8286. return this._actualZOrderChangedObservable;
  8287. },
  8288. enumerable: true,
  8289. configurable: true
  8290. });
  8291. Object.defineProperty(Prim2DBase.prototype, "displayDebugAreas", {
  8292. get: function () {
  8293. return this._displayDebugAreas;
  8294. },
  8295. set: function (value) {
  8296. if (this._displayDebugAreas === value) {
  8297. return;
  8298. }
  8299. if (value === false) {
  8300. this._debugAreaGroup.dispose();
  8301. this._debugAreaGroup = null;
  8302. }
  8303. else {
  8304. var layoutFill = "#F0808040"; // Red - Layout area
  8305. var layoutBorder = "#F08080FF";
  8306. var marginFill = "#F0F04040"; // Yellow - Margin area
  8307. var marginBorder = "#F0F040FF";
  8308. var paddingFill = "#F040F040"; // Magenta - Padding Area
  8309. var paddingBorder = "#F040F0FF";
  8310. var contentFill = "#40F0F040"; // Cyan - Content area
  8311. var contentBorder = "#40F0F0FF";
  8312. var s = new BABYLON.Size(10, 10);
  8313. var p = BABYLON.Vector2.Zero();
  8314. this._debugAreaGroup = new BABYLON.Group2D({ dontInheritParentScale: true,
  8315. parent: (this.parent != null) ? this.parent : this, id: "###DEBUG AREA GROUP###", children: [
  8316. new BABYLON.Group2D({
  8317. id: "###Layout Area###", position: p, size: s, children: [
  8318. new BABYLON.Rectangle2D({ id: "###Layout Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: layoutBorder }),
  8319. new BABYLON.Rectangle2D({ id: "###Layout Top###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  8320. new BABYLON.Rectangle2D({ id: "###Layout Left###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  8321. new BABYLON.Rectangle2D({ id: "###Layout Right###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  8322. new BABYLON.Rectangle2D({ id: "###Layout Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill })
  8323. ]
  8324. }),
  8325. new BABYLON.Group2D({
  8326. id: "###Margin Area###", position: p, size: s, children: [
  8327. new BABYLON.Rectangle2D({ id: "###Margin Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: marginBorder }),
  8328. new BABYLON.Rectangle2D({ id: "###Margin Top###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  8329. new BABYLON.Rectangle2D({ id: "###Margin Left###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  8330. new BABYLON.Rectangle2D({ id: "###Margin Right###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  8331. new BABYLON.Rectangle2D({ id: "###Margin Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill })
  8332. ]
  8333. }),
  8334. new BABYLON.Group2D({
  8335. id: "###Padding Area###", position: p, size: s, children: [
  8336. new BABYLON.Rectangle2D({ id: "###Padding Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: paddingBorder }),
  8337. new BABYLON.Rectangle2D({ id: "###Padding Top###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  8338. new BABYLON.Rectangle2D({ id: "###Padding Left###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  8339. new BABYLON.Rectangle2D({ id: "###Padding Right###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  8340. new BABYLON.Rectangle2D({ id: "###Padding Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill })
  8341. ]
  8342. }),
  8343. new BABYLON.Group2D({
  8344. id: "###Content Area###", position: p, size: s, children: [
  8345. new BABYLON.Rectangle2D({ id: "###Content Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: contentBorder }),
  8346. new BABYLON.Rectangle2D({ id: "###Content Top###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  8347. new BABYLON.Rectangle2D({ id: "###Content Left###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  8348. new BABYLON.Rectangle2D({ id: "###Content Right###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  8349. new BABYLON.Rectangle2D({ id: "###Content Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill })
  8350. ]
  8351. })
  8352. ]
  8353. });
  8354. this._debugAreaGroup._setFlags(BABYLON.SmartPropertyPrim.flagNoPartOfLayout);
  8355. this._updateDebugArea();
  8356. }
  8357. this._displayDebugAreas = value;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. Prim2DBase.prototype._updateDebugArea = function () {
  8363. if (Prim2DBase_1._updatingDebugArea === true) {
  8364. return;
  8365. }
  8366. Prim2DBase_1._updatingDebugArea = true;
  8367. var areaNames = ["Layout", "Margin", "Padding", "Content"];
  8368. var areaZones = ["Area", "Frame", "Top", "Left", "Right", "Bottom"];
  8369. var prims = new Array(4);
  8370. // Get all the primitives used to display the areas
  8371. for (var i = 0; i < 4; i++) {
  8372. prims[i] = new Array(6);
  8373. for (var j = 0; j < 6; j++) {
  8374. prims[i][j] = this._debugAreaGroup.findById("###" + areaNames[i] + " " + areaZones[j] + "###");
  8375. if (j > 1) {
  8376. prims[i][j].levelVisible = false;
  8377. }
  8378. }
  8379. }
  8380. // Update the visibility status of layout/margin/padding
  8381. var hasLayout = this._layoutAreaPos != null;
  8382. var hasPos = (this.actualPosition.x !== 0) || (this.actualPosition.y !== 0);
  8383. var hasMargin = this._hasMargin;
  8384. var hasPadding = this._hasPadding;
  8385. prims[0][0].levelVisible = hasLayout;
  8386. prims[1][0].levelVisible = hasMargin;
  8387. prims[2][0].levelVisible = hasPadding;
  8388. prims[3][0].levelVisible = true;
  8389. // Current offset
  8390. var curOffset = BABYLON.Vector2.Zero();
  8391. // Store the area info of the layout area
  8392. var curAreaIndex = 0;
  8393. // Store data about each area
  8394. var areaInfo = new Array(4);
  8395. var storeAreaInfo = function (pos, size) {
  8396. var min = pos.clone();
  8397. var max = pos.clone();
  8398. if (size.width > 0) {
  8399. max.x += size.width;
  8400. }
  8401. if (size.height > 0) {
  8402. max.y += size.height;
  8403. }
  8404. areaInfo[curAreaIndex++] = { off: pos, size: size, min: min, max: max };
  8405. };
  8406. var isCanvas = this instanceof BABYLON.Canvas2D;
  8407. var marginH = this._marginOffset.x + this._marginOffset.z;
  8408. var marginV = this._marginOffset.y + this._marginOffset.w;
  8409. var actualSize = this.actualSize.multiplyByFloats(isCanvas ? 1 : this.scaleX, isCanvas ? 1 : this.scaleY);
  8410. var w = hasLayout ? (this.layoutAreaPos.x + this.layoutArea.width) : (marginH + actualSize.width);
  8411. var h = hasLayout ? (this.layoutAreaPos.y + this.layoutArea.height) : (marginV + actualSize.height);
  8412. var pos = (!hasLayout && !hasMargin && !hasPadding && hasPos) ? this.actualPosition : BABYLON.Vector2.Zero();
  8413. storeAreaInfo(pos, new BABYLON.Size(w, h));
  8414. // Compute the layout related data
  8415. if (hasLayout) {
  8416. var layoutOffset = this.layoutAreaPos.clone();
  8417. storeAreaInfo(layoutOffset, (hasMargin || hasPadding) ? this.layoutArea.clone() : actualSize.clone());
  8418. curOffset = layoutOffset.clone();
  8419. }
  8420. // Compute margin data
  8421. if (hasMargin) {
  8422. var marginOffset = curOffset.clone();
  8423. marginOffset.x += this._marginOffset.x;
  8424. marginOffset.y += this._marginOffset.y;
  8425. var marginArea = actualSize;
  8426. storeAreaInfo(marginOffset, marginArea);
  8427. curOffset = marginOffset.clone();
  8428. }
  8429. if (hasPadding) {
  8430. var contentOffset = curOffset.clone();
  8431. contentOffset.x += this._paddingOffset.x;
  8432. contentOffset.y += this._paddingOffset.y;
  8433. var contentArea = this.contentArea;
  8434. storeAreaInfo(contentOffset, contentArea);
  8435. curOffset = curOffset.add(contentOffset);
  8436. }
  8437. // Helper function that set the pos and size of a given prim
  8438. var setArea = function (i, j, pos, size) {
  8439. prims[i][j].position = pos;
  8440. prims[i][j].size = size;
  8441. };
  8442. var setFullRect = function (i, pos, size) {
  8443. var plist = prims[i];
  8444. plist[2].levelVisible = true;
  8445. plist[3].levelVisible = false;
  8446. plist[4].levelVisible = false;
  8447. plist[5].levelVisible = false;
  8448. setArea(i, 1, pos, size);
  8449. setArea(i, 2, pos, size);
  8450. };
  8451. var setQuadRect = function (i, areaIndex) {
  8452. var plist = prims[i];
  8453. plist[2].levelVisible = true;
  8454. plist[3].levelVisible = true;
  8455. plist[4].levelVisible = true;
  8456. plist[5].levelVisible = true;
  8457. var ca = areaInfo[areaIndex];
  8458. var na = areaInfo[areaIndex + 1];
  8459. var tp = new BABYLON.Vector2(ca.min.x, na.max.y);
  8460. var ts = new BABYLON.Size(ca.size.width, ca.max.y - tp.y);
  8461. var lp = new BABYLON.Vector2(ca.min.x, na.min.y);
  8462. var ls = new BABYLON.Size(na.min.x - ca.min.x, na.max.y - na.min.y);
  8463. var rp = new BABYLON.Vector2(na.max.x, na.min.y);
  8464. var rs = new BABYLON.Size(ca.max.x - na.max.x, na.max.y - na.min.y);
  8465. var bp = new BABYLON.Vector2(ca.min.x, ca.min.y);
  8466. var bs = new BABYLON.Size(ca.size.width, na.min.y - ca.min.y);
  8467. // Frame
  8468. plist[1].position = ca.off;
  8469. plist[1].size = ca.size;
  8470. // Top rect
  8471. plist[2].position = tp;
  8472. plist[2].size = ts;
  8473. // Left rect
  8474. plist[3].position = lp;
  8475. plist[3].size = ls;
  8476. // Right rect
  8477. plist[4].position = rp;
  8478. plist[4].size = rs;
  8479. // Bottom rect
  8480. plist[5].position = bp;
  8481. plist[5].size = bs;
  8482. };
  8483. var areaCount = curAreaIndex;
  8484. curAreaIndex = 0;
  8485. // Available zones
  8486. var availableZones = [false, hasLayout, hasMargin, hasPadding, true];
  8487. for (var k = 1; k < 5; k++) {
  8488. if (availableZones[k]) {
  8489. var ai = areaInfo[curAreaIndex];
  8490. setArea(k - 1, 0, BABYLON.Vector2.Zero(), ai.size);
  8491. // setArea(k-1, 1, Vector2.Zero(), ai.size);
  8492. if (k === 4) {
  8493. setFullRect(k - 1, ai.off, ai.size);
  8494. }
  8495. else {
  8496. setQuadRect(k - 1, curAreaIndex);
  8497. }
  8498. ++curAreaIndex;
  8499. }
  8500. }
  8501. Prim2DBase_1._updatingDebugArea = false;
  8502. };
  8503. Prim2DBase.prototype.findById = function (id) {
  8504. if (this._id === id) {
  8505. return this;
  8506. }
  8507. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8508. var child = _a[_i];
  8509. var r = child.findById(id);
  8510. if (r != null) {
  8511. return r;
  8512. }
  8513. }
  8514. };
  8515. Prim2DBase.prototype.onZOrderChanged = function () {
  8516. };
  8517. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  8518. return false;
  8519. };
  8520. /**
  8521. * Capture all the Events of the given PointerId for this primitive.
  8522. * Don't forget to call releasePointerEventsCapture when done.
  8523. * @param pointerId the Id of the pointer to capture the events from.
  8524. */
  8525. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  8526. return this.owner._setPointerCapture(pointerId, this);
  8527. };
  8528. /**
  8529. * Release a captured pointer made with setPointerEventCapture.
  8530. * @param pointerId the Id of the pointer to release the capture from.
  8531. */
  8532. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  8533. return this.owner._releasePointerCapture(pointerId, this);
  8534. };
  8535. /**
  8536. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  8537. * @param intersectInfo contains the settings of the intersection to perform, to setup before calling this method as well as the result, available after a call to this method.
  8538. */
  8539. Prim2DBase.prototype.intersect = function (intersectInfo) {
  8540. if (!intersectInfo) {
  8541. return false;
  8542. }
  8543. // If this is null it means this method is call for the first level, initialize stuffs
  8544. var firstLevel = !intersectInfo._globalPickPosition;
  8545. if (firstLevel) {
  8546. // Compute the pickPosition in global space and use it to find the local position for each level down, always relative from the world to get the maximum accuracy (and speed). The other way would have been to compute in local every level down relative to its parent's local, which wouldn't be as accurate (even if javascript number is 80bits accurate).
  8547. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  8548. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  8549. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  8550. intersectInfo.intersectedPrimitives = new Array();
  8551. intersectInfo.topMostIntersectedPrimitive = null;
  8552. }
  8553. if (!Prim2DBase_1._bypassGroup2DExclusion && this instanceof BABYLON.Group2D && this.isCachedGroup && !this.isRenderableGroup) {
  8554. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8555. intersectInfo._exit(firstLevel);
  8556. return false;
  8557. }
  8558. if (!intersectInfo.intersectHidden && !this.isVisible) {
  8559. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8560. intersectInfo._exit(firstLevel);
  8561. return false;
  8562. }
  8563. var id = this.id;
  8564. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  8565. try {
  8566. Prim2DBase_1._bypassGroup2DExclusion = true;
  8567. var ownerGroup = this.getExternalData("__cachedGroup__");
  8568. return ownerGroup.intersect(intersectInfo);
  8569. }
  8570. finally {
  8571. Prim2DBase_1._bypassGroup2DExclusion = false;
  8572. }
  8573. }
  8574. // If we're testing a cachedGroup, we must reject pointer outside its levelBoundingInfo because children primitives could be partially clipped outside so we must not accept them as intersected when it's the case (because they're not visually visible).
  8575. var isIntersectionTest = false;
  8576. if (this instanceof BABYLON.Group2D) {
  8577. var g = this;
  8578. isIntersectionTest = g.isCachedGroup;
  8579. }
  8580. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  8581. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8582. intersectInfo._exit(firstLevel);
  8583. return false;
  8584. }
  8585. // Fast rejection test with boundingInfo
  8586. var boundingIntersected = true;
  8587. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  8588. if (this.isContainer) {
  8589. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8590. intersectInfo._exit(firstLevel);
  8591. return false;
  8592. }
  8593. boundingIntersected = false;
  8594. }
  8595. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  8596. var levelIntersectRes = false;
  8597. if (this.isPickable) {
  8598. levelIntersectRes = boundingIntersected && this.levelIntersect(intersectInfo);
  8599. if (levelIntersectRes) {
  8600. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  8601. intersectInfo.intersectedPrimitives.push(pii);
  8602. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  8603. intersectInfo.topMostIntersectedPrimitive = pii;
  8604. }
  8605. // If we must stop at the first intersection, we're done, quit!
  8606. if (intersectInfo.findFirstOnly) {
  8607. intersectInfo._exit(firstLevel);
  8608. return true;
  8609. }
  8610. }
  8611. }
  8612. // Recurse to children if needed
  8613. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  8614. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8615. var curChild = _a[_i];
  8616. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  8617. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  8618. continue;
  8619. }
  8620. // Must compute the localPickLocation for the children level
  8621. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  8622. // If we got an intersection with the child and we only need to find the first one, quit!
  8623. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  8624. intersectInfo._exit(firstLevel);
  8625. return true;
  8626. }
  8627. }
  8628. }
  8629. intersectInfo._exit(firstLevel);
  8630. return intersectInfo.isIntersected;
  8631. };
  8632. Prim2DBase.prototype.intersectOtherPrim = function (other) {
  8633. var setA = this.triList;
  8634. var setB = other.triList;
  8635. return BABYLON.Tri2DArray.doesIntersect(setA, setB, other.globalTransform.multiply(this.globalTransform.clone().invert()));
  8636. };
  8637. Object.defineProperty(Prim2DBase.prototype, "triList", {
  8638. get: function () {
  8639. if (this._primTriArrayDirty) {
  8640. this.updateTriArray();
  8641. this._primTriArrayDirty = false;
  8642. }
  8643. return this._primTriArray;
  8644. },
  8645. enumerable: true,
  8646. configurable: true
  8647. });
  8648. // This is the worst implementation, if the top level primitive doesn't override this method we will just store a quad that defines the bounding rect of the prim
  8649. Prim2DBase.prototype.updateTriArray = function () {
  8650. if (this._primTriArray == null) {
  8651. this._primTriArray = new BABYLON.Tri2DArray(2);
  8652. }
  8653. else {
  8654. this._primTriArray.clear(2);
  8655. }
  8656. var size = this.actualSize;
  8657. var lb = new BABYLON.Vector2(0, 0);
  8658. var rt = new BABYLON.Vector2(size.width, size.height);
  8659. var lt = new BABYLON.Vector2(0, size.height);
  8660. var rb = new BABYLON.Vector2(size.width, 0);
  8661. this._primTriArray.storeTriangle(0, lb, lt, rt);
  8662. this._primTriArray.storeTriangle(1, lb, rt, rb);
  8663. };
  8664. /**
  8665. * Move a child object into a new position regarding its siblings to change its rendering order.
  8666. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  8667. * @param child the object to move
  8668. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  8669. */
  8670. Prim2DBase.prototype.moveChild = function (child, previous) {
  8671. if (child.parent !== this) {
  8672. return false;
  8673. }
  8674. var childIndex = this._children.indexOf(child);
  8675. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  8676. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  8677. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  8678. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  8679. }
  8680. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  8681. return true;
  8682. };
  8683. /**
  8684. * Move the given child so it's displayed on the top of all its siblings
  8685. * @param child the primitive to move to the top
  8686. */
  8687. Prim2DBase.prototype.moveChildToTop = function (child) {
  8688. return this.moveChild(child, this._children[this._children.length - 1]);
  8689. };
  8690. /**
  8691. * Move the given child so it's displayed on the bottom of all its siblings
  8692. * @param child the primitive to move to the top
  8693. */
  8694. Prim2DBase.prototype.moveChildToBottom = function (child) {
  8695. return this.moveChild(child, null);
  8696. };
  8697. /**
  8698. * Move this primitive to be at the top among all its sibling
  8699. */
  8700. Prim2DBase.prototype.moveToTop = function () {
  8701. if (this.parent == null) {
  8702. return false;
  8703. }
  8704. return this.parent.moveChildToTop(this);
  8705. };
  8706. /**
  8707. * Move this primitive to be at the bottom among all its sibling
  8708. */
  8709. Prim2DBase.prototype.moveToBottom = function () {
  8710. if (this.parent == null) {
  8711. return false;
  8712. }
  8713. return this.parent.moveChildToBottom(this);
  8714. };
  8715. Prim2DBase.prototype.addChild = function (child) {
  8716. child._parent = this;
  8717. this._boundingBoxDirty();
  8718. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  8719. if (flat) {
  8720. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  8721. child._setZOrder(this._zOrder, true);
  8722. child._zMax = this._zOrder;
  8723. }
  8724. else {
  8725. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  8726. }
  8727. var length = this._children.push(child);
  8728. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  8729. };
  8730. /**
  8731. * Dispose the primitive, remove it from its parent.
  8732. */
  8733. Prim2DBase.prototype.dispose = function () {
  8734. if (!_super.prototype.dispose.call(this)) {
  8735. return false;
  8736. }
  8737. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagCollisionActor)) {
  8738. this.owner._primitiveCollisionManager._removeActor(this);
  8739. this._actorInfo = null;
  8740. }
  8741. if (this._pointerEventObservable) {
  8742. this._pointerEventObservable.clear();
  8743. this._pointerEventObservable = null;
  8744. }
  8745. if (this._actionManager) {
  8746. this._actionManager.dispose();
  8747. this._actionManager = null;
  8748. }
  8749. this.owner.scene.stopAnimation(this);
  8750. // If there's a parent, remove this object from its parent list
  8751. if (this._parent) {
  8752. if (this instanceof BABYLON.Group2D) {
  8753. var g = this;
  8754. if (g.isRenderableGroup) {
  8755. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  8756. if (parentRenderable != null) {
  8757. var l = parentRenderable._renderableData._childrenRenderableGroups;
  8758. var i_1 = l.indexOf(g);
  8759. if (i_1 !== -1) {
  8760. l.splice(i_1, 1);
  8761. }
  8762. }
  8763. }
  8764. }
  8765. var i = this._parent._children.indexOf(this);
  8766. if (i !== undefined) {
  8767. this._parent._children.splice(i, 1);
  8768. }
  8769. this._parent = null;
  8770. }
  8771. // Recurse dispose to children
  8772. if (this._children) {
  8773. while (this._children.length > 0) {
  8774. this._children[this._children.length - 1].dispose();
  8775. }
  8776. }
  8777. return true;
  8778. };
  8779. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  8780. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  8781. this._renderGroup._addPrimToDirtyList(this);
  8782. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  8783. }
  8784. };
  8785. Prim2DBase.prototype._needPrepare = function () {
  8786. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagModelUpdate | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  8787. };
  8788. Prim2DBase.prototype._prepareRender = function (context) {
  8789. this._prepareRenderPre(context);
  8790. this._prepareRenderPost(context);
  8791. };
  8792. Prim2DBase.prototype._prepareRenderPre = function (context) {
  8793. };
  8794. Prim2DBase.prototype._prepareRenderPost = function (context) {
  8795. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  8796. if (this instanceof BABYLON.Group2D) {
  8797. var self = this;
  8798. if (self.isRenderableGroup) {
  8799. return;
  8800. }
  8801. }
  8802. // Check if we need to recurse the prepare to children primitives
  8803. // - must have children
  8804. // - the global transform of this level have changed, or
  8805. // - the visible state of primitive has changed
  8806. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  8807. this.checkPropertiesDirty(Prim2DBase_1.isVisibleProperty.flagId))) {
  8808. this._children.forEach(function (c) {
  8809. // As usual stop the recursion if we meet a renderable group
  8810. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  8811. c._prepareRender(context);
  8812. }
  8813. });
  8814. }
  8815. // Finally reset the dirty flags as we've processed everything
  8816. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  8817. this._instanceDirtyFlags = 0;
  8818. };
  8819. Prim2DBase.prototype._canvasPreInit = function (settings) {
  8820. };
  8821. Prim2DBase.CheckParent = function (parent) {
  8822. //if (!Prim2DBase._isCanvasInit && !parent) {
  8823. // throw new Error("A Primitive needs a valid Parent, it can be any kind of Primitives based types, even the Canvas (with the exception that only Group2D can be direct child of a Canvas if the cache strategy used is TOPLEVELGROUPS)");
  8824. //}
  8825. };
  8826. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  8827. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  8828. var cur = list_1[_i];
  8829. cur.updateCachedStates(recurse);
  8830. }
  8831. };
  8832. Prim2DBase.prototype._parentLayoutDirty = function () {
  8833. if (!this._parent || this._parent.isDisposed) {
  8834. return;
  8835. }
  8836. this._parent._setLayoutDirty();
  8837. };
  8838. Prim2DBase.prototype._setLayoutDirty = function () {
  8839. this.onPrimBecomesDirty();
  8840. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  8841. };
  8842. Prim2DBase.prototype._checkPositionChange = function () {
  8843. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  8844. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  8845. return false;
  8846. }
  8847. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  8848. if (this instanceof BABYLON.Group2D && this.trackedNode == null) {
  8849. console.log("You can't set the position/x/y of " + this.id + " properties while positioning engine is used (margin, margin alignment and/or padding are set");
  8850. return false;
  8851. }
  8852. }
  8853. return true;
  8854. };
  8855. Prim2DBase.prototype._positioningDirty = function () {
  8856. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  8857. return;
  8858. }
  8859. this.onPrimBecomesDirty();
  8860. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  8861. };
  8862. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  8863. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8864. var child = _a[_i];
  8865. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  8866. child._updateRenderMode();
  8867. child.onPrimBecomesDirty();
  8868. child._spreadActualOpacityChanged();
  8869. }
  8870. };
  8871. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  8872. this._layoutEngine = engine;
  8873. };
  8874. Prim2DBase.prototype._updateLocalTransform = function () {
  8875. var tflags = Prim2DBase_1.actualPositionProperty.flagId | Prim2DBase_1.rotationProperty.flagId | Prim2DBase_1.scaleProperty.flagId | Prim2DBase_1.scaleXProperty.flagId | Prim2DBase_1.scaleYProperty.flagId | Prim2DBase_1.originProperty.flagId;
  8876. if (this.checkPropertiesDirty(tflags) || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  8877. if (this.owner) {
  8878. this.owner.addupdateLocalTransformCounter(1);
  8879. }
  8880. // Check for positioning update
  8881. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  8882. this._updatePositioning();
  8883. }
  8884. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  8885. var local;
  8886. var pos = this._position ? this.position : (this.layoutAreaPos || Prim2DBase_1._v0);
  8887. var scale = new BABYLON.Vector3(this._scale.x, this._scale.y, 1);
  8888. var postScale = this._postScale;
  8889. var canvasScale = Prim2DBase_1._iv3;
  8890. var hasCanvasScale = false;
  8891. if (this._parent instanceof BABYLON.Canvas2D) {
  8892. hasCanvasScale = true;
  8893. canvasScale = this._parent._canvasLevelScale || Prim2DBase_1._iv3;
  8894. }
  8895. var globalScale = scale.multiplyByFloats(postScale.x * canvasScale.x, postScale.y * canvasScale.y, 1);
  8896. if (this._origin.x === 0 && this._origin.y === 0) {
  8897. // ###MATRIX PART###
  8898. {
  8899. local = BABYLON.Matrix.Compose(globalScale, rot, new BABYLON.Vector3(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0));
  8900. this._localTransform = local;
  8901. this._localLayoutTransform = BABYLON.Matrix.Compose(globalScale, rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  8902. }
  8903. }
  8904. else {
  8905. // ###MATRIX PART###
  8906. {
  8907. // -Origin offset
  8908. var t0 = Prim2DBase_1._t0;
  8909. var t1 = Prim2DBase_1._t1;
  8910. var t2 = Prim2DBase_1._t2;
  8911. var as = Prim2DBase_1._ts0;
  8912. as.copyFrom(this.actualSize);
  8913. as.width /= postScale.x;
  8914. as.height /= postScale.y;
  8915. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, t0);
  8916. // -Origin * rotation
  8917. rot.toRotationMatrix(t1);
  8918. t0.multiplyToRef(t1, t2);
  8919. // -Origin * rotation * scale
  8920. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, t0);
  8921. t2.multiplyToRef(t0, t1);
  8922. // -Origin * rotation * scale * Origin
  8923. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x), (as.height * this._origin.y), 0, t2);
  8924. t1.multiplyToRef(t2, t0);
  8925. // -Origin * rotation * scale * Origin * postScale
  8926. BABYLON.Matrix.ScalingToRef(postScale.x, postScale.y, 1, t1);
  8927. t0.multiplyToRef(t1, t2);
  8928. // -Origin * rotation * scale * Origin * postScale * Position
  8929. BABYLON.Matrix.TranslationToRef(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0, t0);
  8930. t2.multiplyToRef(t0, this._localTransform);
  8931. if (hasCanvasScale) {
  8932. BABYLON.Matrix.ScalingToRef(canvasScale.x, canvasScale.y, canvasScale.z, Prim2DBase_1._t1);
  8933. this._localTransform.multiplyToRef(Prim2DBase_1._t1, this._localTransform);
  8934. }
  8935. this._localLayoutTransform = BABYLON.Matrix.Compose(globalScale, rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  8936. }
  8937. }
  8938. this.clearPropertiesDirty(tflags);
  8939. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  8940. this._clearFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
  8941. return true;
  8942. }
  8943. return false;
  8944. };
  8945. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  8946. if (this.isDisposed) {
  8947. return;
  8948. }
  8949. this.owner.addCachedGroupRenderCounter(1);
  8950. // Check if the parent is synced
  8951. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  8952. this._parent.updateCachedStates(false);
  8953. }
  8954. // Update Z-Order if needed
  8955. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  8956. this._updateZOrder();
  8957. }
  8958. // Update actualSize only if there' not positioning to recompute and the size changed
  8959. // Otherwise positioning will take care of it.
  8960. var sizeDirty = this.checkPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  8961. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  8962. var size = this.size;
  8963. this.onPropertyChanged("actualSize", size, size, Prim2DBase_1.actualSizeProperty.flagId);
  8964. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  8965. }
  8966. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  8967. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  8968. // Check for layout update
  8969. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  8970. this.owner.addUpdateLayoutCounter(1);
  8971. this._layoutEngine.updateLayout(this);
  8972. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  8973. }
  8974. var autoContentChanged = false;
  8975. if (this.isSizeAuto) {
  8976. if (!this._lastAutoSizeArea) {
  8977. autoContentChanged = this.actualSize !== null;
  8978. }
  8979. else {
  8980. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  8981. }
  8982. }
  8983. // Check for positioning update
  8984. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  8985. this._updatePositioning();
  8986. if (sizeDirty) {
  8987. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  8988. }
  8989. positioningComputed = true;
  8990. }
  8991. if (positioningComputed && this._parent) {
  8992. this._parentContentArea.copyFrom(this._parent.contentArea);
  8993. }
  8994. // Check if we must update this prim
  8995. if ((this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty))) {
  8996. this.owner.addUpdateGlobalTransformCounter(1);
  8997. var curVisibleState = this.isVisible;
  8998. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  8999. // Detect a change of visibility
  9000. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  9001. // Get/compute the localTransform
  9002. var localDirty = this._updateLocalTransform();
  9003. var parentPaddingChanged = false;
  9004. var parentPaddingOffset = Prim2DBase_1._v0;
  9005. if (this._parent) {
  9006. parentPaddingOffset = new BABYLON.Vector2(this._parent._paddingOffset.x, this._parent._paddingOffset.y);
  9007. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  9008. }
  9009. // Check if there are changes in the parent that will force us to update the global matrix
  9010. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  9011. // Check if we have to update the globalTransform
  9012. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  9013. //###MATRIX PART###
  9014. {
  9015. var globalTransform = this._parent ? this._parent._globalTransform : null;
  9016. var localTransform = void 0;
  9017. Prim2DBase_1._transMtx.copyFrom(this._localTransform);
  9018. Prim2DBase_1._transMtx.m[12] += parentPaddingOffset.x;
  9019. Prim2DBase_1._transMtx.m[13] += parentPaddingOffset.y;
  9020. localTransform = Prim2DBase_1._transMtx;
  9021. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  9022. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  9023. }
  9024. this._levelBoundingInfo.dirtyWorldAABB();
  9025. this._boundingInfo.dirtyWorldAABB();
  9026. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  9027. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  9028. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  9029. }
  9030. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  9031. }
  9032. if (recurse) {
  9033. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9034. var child = _a[_i];
  9035. // Stop the recursion if we meet a renderable group
  9036. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  9037. }
  9038. }
  9039. };
  9040. Prim2DBase.prototype._updatePositioning = function () {
  9041. var _this = this;
  9042. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9043. // Just in case, if may happen and if we don't clear some computation will keep going on forever
  9044. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  9045. return;
  9046. }
  9047. var success = true;
  9048. // Check if re-entrance is occurring
  9049. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagComputingPositioning) /* || (hasMargin && !this._layoutArea)*/) {
  9050. if (!this._actualSize) {
  9051. this._actualSize = this.size.clone() || BABYLON.Size.Zero();
  9052. this._contentArea.copyFrom(this._actualSize);
  9053. }
  9054. if (!this._marginSize) {
  9055. this._marginSize = this._actualSize.clone();
  9056. }
  9057. if (!this._actualPosition) {
  9058. this._actualPosition = BABYLON.Vector2.Zero();
  9059. }
  9060. return;
  9061. }
  9062. if (this.owner) {
  9063. this.owner.addUpdatePositioningCounter(1);
  9064. }
  9065. // Set the flag to avoid re-entrance
  9066. this._setFlags(BABYLON.SmartPropertyPrim.flagComputingPositioning);
  9067. try {
  9068. var isSizeAuto = this.isSizeAuto;
  9069. var isVSizeAuto = this.isVerticalSizeAuto;
  9070. var isHSizeAuto = this.isHorizontalSizeAuto;
  9071. var ma = this._marginAlignment ? this._marginAlignment.clone() : new PrimitiveAlignment();
  9072. var csize = this.size;
  9073. // Auto Create PaddingArea if there's no actualSize on width&|height to allocate the whole content available to the paddingArea where the actualSize is null
  9074. if (!this._hasMarginAlignment && (!isSizeAuto && (csize.width == null || csize.height == null))) {
  9075. if (isSizeAuto || this.actualSize.width == null) {
  9076. ma.horizontal = PrimitiveAlignment.AlignStretch;
  9077. }
  9078. if (isSizeAuto || this.actualSize.height == null) {
  9079. ma.vertical = PrimitiveAlignment.AlignStretch;
  9080. }
  9081. }
  9082. var hasMargin = (this._margin !== null && !this._margin.isDefault) || (ma !== null && !ma.isDefault);
  9083. var newSize = Prim2DBase_1._size;
  9084. var hasH = false;
  9085. var hasV = false;
  9086. var size = this.size || Prim2DBase_1._nullSize;
  9087. var paddingApplied_1 = false;
  9088. var hasPadding = this._hasPadding;
  9089. var autoSizeComputed_1 = false;
  9090. //let contentAreaComputed = false;
  9091. // Compute the size
  9092. // The size is the size of the prim or the computed one if there's a marginAlignment of Stretch
  9093. if (hasMargin) {
  9094. var layoutArea = this.layoutArea;
  9095. if (layoutArea /*&& layoutArea.width >= size.width */ && ma.horizontal === PrimitiveAlignment.AlignStretch) {
  9096. this.margin.computeWithAlignment(layoutArea, size, ma, this.actualScale, this._marginOffset, newSize, false, PrimitiveThickness.ComputeH);
  9097. hasH = true;
  9098. }
  9099. if (layoutArea /*&& layoutArea.height >= size.height */ && ma.vertical === PrimitiveAlignment.AlignStretch) {
  9100. this.margin.computeWithAlignment(layoutArea, size, ma, this.actualScale, this._marginOffset, newSize, false, PrimitiveThickness.ComputeV);
  9101. hasV = true;
  9102. }
  9103. }
  9104. var computeAutoSize = function () {
  9105. if (autoSizeComputed_1) {
  9106. return;
  9107. }
  9108. var bi = _this.layoutBoundingInfo;
  9109. bi.sizeToRef(Prim2DBase_1._size2);
  9110. autoSizeComputed_1 = true;
  9111. paddingApplied_1 = true;
  9112. };
  9113. if (!hasH) {
  9114. // If the Horizontal size is Auto, we have to compute it from its content and padding
  9115. if (isHSizeAuto) {
  9116. computeAutoSize();
  9117. newSize.width = Prim2DBase_1._size2.width;
  9118. }
  9119. else {
  9120. newSize.width = size.width;
  9121. }
  9122. }
  9123. if (!hasV) {
  9124. // If the Vertical size is Auto, we have to compute it from its content and padding
  9125. if (isVSizeAuto) {
  9126. computeAutoSize();
  9127. newSize.height = Prim2DBase_1._size2.height;
  9128. }
  9129. else {
  9130. newSize.height = size.height;
  9131. }
  9132. }
  9133. if (!isVSizeAuto || !isHSizeAuto) {
  9134. Prim2DBase_1._curContentArea.copyFrom(this._contentArea);
  9135. if (hasPadding) {
  9136. this._getInitialContentAreaToRef(newSize, Prim2DBase_1._icZone, Prim2DBase_1._icArea);
  9137. Prim2DBase_1._icArea.width = Math.max(0, Prim2DBase_1._icArea.width);
  9138. Prim2DBase_1._icArea.height = Math.max(0, Prim2DBase_1._icArea.height);
  9139. this.padding.compute(Prim2DBase_1._icArea, this.actualScale, this._paddingOffset, Prim2DBase_1._size2);
  9140. if (!isHSizeAuto) {
  9141. this._paddingOffset.x += Prim2DBase_1._icZone.x;
  9142. this._paddingOffset.z -= Prim2DBase_1._icZone.z;
  9143. this._contentArea.width = Prim2DBase_1._size2.width;
  9144. }
  9145. if (!isVSizeAuto) {
  9146. this._paddingOffset.y += Prim2DBase_1._icZone.y;
  9147. this._paddingOffset.w -= Prim2DBase_1._icZone.w;
  9148. this._contentArea.height = Prim2DBase_1._size2.height;
  9149. }
  9150. }
  9151. else {
  9152. this._contentArea.copyFrom(newSize);
  9153. }
  9154. if (!Prim2DBase_1._curContentArea.equals(this._contentArea)) {
  9155. this._setLayoutDirty();
  9156. }
  9157. paddingApplied_1 = true;
  9158. }
  9159. // Finally we apply margin to determine the position
  9160. if (hasMargin) {
  9161. var layoutArea = this.layoutArea;
  9162. var mo = this._marginOffset;
  9163. var margin = this.margin;
  9164. // We compute margin only if the layoutArea is as big as the contentSize, sometime this code is triggered when the layoutArea is
  9165. // not yet set and computing alignment would result into a bad size.
  9166. // So we make sure with compute alignment only if the layoutArea is good
  9167. if (layoutArea && layoutArea.width >= newSize.width && layoutArea.height >= newSize.height) {
  9168. margin.computeWithAlignment(layoutArea, newSize, ma, new BABYLON.Vector2(1, 1) /*this.actualScale*/, mo, Prim2DBase_1._size2);
  9169. }
  9170. else {
  9171. mo.copyFromFloats(0, 0, 0, 0);
  9172. }
  9173. var mw = newSize.width + margin.leftPixels + margin.rightPixels;
  9174. var mh = newSize.height + margin.bottomPixels + margin.topPixels;
  9175. if (!this._marginSize) {
  9176. this._marginSize = new BABYLON.Size(mw, mh);
  9177. }
  9178. else {
  9179. this._marginSize.copyFromFloats(mw, mh);
  9180. }
  9181. }
  9182. else {
  9183. if (!this._marginSize) {
  9184. this._marginSize = newSize.clone();
  9185. }
  9186. else {
  9187. this._marginSize.copyFrom(newSize);
  9188. }
  9189. }
  9190. var lap = this.layoutAreaPos;
  9191. this.actualPosition = new BABYLON.Vector2(this._marginOffset.x + (lap ? lap.x : 0), this._marginOffset.y + (lap ? lap.y : 0));
  9192. this.actualSize = Prim2DBase_1._size.clone();
  9193. this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
  9194. if (isSizeAuto) {
  9195. this._lastAutoSizeArea = this.actualSize;
  9196. }
  9197. if (this.displayDebugAreas) {
  9198. this._updateDebugArea();
  9199. }
  9200. }
  9201. finally {
  9202. this._clearFlags(BABYLON.SmartPropertyPrim.flagComputingPositioning);
  9203. // Remove dirty flag
  9204. if (success) {
  9205. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  9206. }
  9207. }
  9208. };
  9209. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  9210. /**
  9211. * Get the content are of this primitive, this area is computed the primitive size and using the padding property.
  9212. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  9213. */
  9214. get: function () {
  9215. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9216. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  9217. this._updatePositioning();
  9218. }
  9219. return this._contentArea;
  9220. }
  9221. else {
  9222. return this.size;
  9223. }
  9224. },
  9225. enumerable: true,
  9226. configurable: true
  9227. });
  9228. Object.defineProperty(Prim2DBase.prototype, "marginSize", {
  9229. get: function () {
  9230. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9231. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  9232. this._updatePositioning();
  9233. }
  9234. return this._marginSize;
  9235. }
  9236. else {
  9237. return this.size;
  9238. }
  9239. },
  9240. enumerable: true,
  9241. configurable: true
  9242. });
  9243. Prim2DBase.prototype._patchHierarchy = function (owner) {
  9244. if (this._owner == null) {
  9245. this._owner = owner;
  9246. this.onSetOwner();
  9247. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  9248. }
  9249. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  9250. if (this._renderGroup != null) {
  9251. return;
  9252. }
  9253. if (this instanceof BABYLON.Group2D) {
  9254. var group = this;
  9255. group.detectGroupStates();
  9256. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  9257. group.owner._registerTrackedNode(this);
  9258. }
  9259. }
  9260. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  9261. if (this._parent) {
  9262. this._parentLayoutDirty();
  9263. }
  9264. // Make sure the prim is in the dirtyList if it should be
  9265. if (this._renderGroup && this.isDirty) {
  9266. var list = this._renderGroup._renderableData._primDirtyList;
  9267. var i = list.indexOf(this);
  9268. if (i === -1) {
  9269. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  9270. list.push(this);
  9271. }
  9272. }
  9273. // Recurse
  9274. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9275. var child = _a[_i];
  9276. child._hierarchyDepth = this._hierarchyDepth + 1;
  9277. child._patchHierarchy(owner);
  9278. }
  9279. };
  9280. Prim2DBase.prototype.onSetOwner = function () {
  9281. };
  9282. Prim2DBase.prototype._updateZOrder = function () {
  9283. var prevLinPos = this._primLinearPosition;
  9284. var startI = 0;
  9285. var startZ = this._zOrder;
  9286. // We must start rebuilding Z-Order from the Prim before the first one that changed, because we know its Z-Order is correct, so are its children, but it's better to recompute everything from this point instead of finding the last valid children
  9287. var childrenCount = this._children.length;
  9288. if (this._firstZDirtyIndex > 0) {
  9289. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  9290. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  9291. prevLinPos = prevPrim._primLinearPosition;
  9292. startI = this._firstZDirtyIndex - 1;
  9293. startZ = prevPrim._zOrder;
  9294. }
  9295. }
  9296. var startPos = prevLinPos;
  9297. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  9298. Prim2DBase_1._totalCount = 0;
  9299. for (var i = startI; i < childrenCount; i++) {
  9300. var child = this._children[i];
  9301. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  9302. }
  9303. // Compute the new Z-Order for all the primitives
  9304. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  9305. var zDelta = (this._zMax - startZ) / (Prim2DBase_1._totalCount * (Prim2DBase_1._zRebuildReentrency ? 1 : 1.2));
  9306. // If the computed delta is less than the smallest allowed by the depth buffer, we rebuild the Z-Order from the very beginning of the primitive's children (that is, the first) to redistribute uniformly the Z.
  9307. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  9308. // Check for re-entrance, if the flag is true we already attempted a rebuild but couldn't get a better zDelta, go up in the hierarchy to rebuilt one level up, hoping to get this time a decent delta, otherwise, recurse until we got it or when no parent is reached, which would mean the canvas would have more than 16 millions of primitives...
  9309. if (Prim2DBase_1._zRebuildReentrency) {
  9310. var p = this._parent;
  9311. if (p == null) {
  9312. // Can't find a good Z delta and we're in the canvas, which mean we're dealing with too many objects (which should never happen, but well...)
  9313. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  9314. Prim2DBase_1._zRebuildReentrency = false;
  9315. return;
  9316. }
  9317. p._firstZDirtyIndex = 0;
  9318. return p._updateZOrder();
  9319. }
  9320. Prim2DBase_1._zRebuildReentrency = true;
  9321. this._firstZDirtyIndex = 0;
  9322. this._updateZOrder();
  9323. Prim2DBase_1._zRebuildReentrency = false;
  9324. }
  9325. for (var i = startI; i < childrenCount; i++) {
  9326. var child = this._children[i];
  9327. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  9328. }
  9329. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  9330. for (var _i = 0, _a = Prim2DBase_1._zOrderChangedNotifList; _i < _a.length; _i++) {
  9331. var p = _a[_i];
  9332. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  9333. }
  9334. Prim2DBase_1._zOrderChangedNotifList.splice(0);
  9335. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  9336. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9337. };
  9338. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  9339. if (this.isManualZOrder) {
  9340. return prevLinPos;
  9341. }
  9342. this._primLinearPosition = ++prevLinPos;
  9343. Prim2DBase_1._totalCount++;
  9344. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  9345. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  9346. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9347. var child = _a[_i];
  9348. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  9349. }
  9350. }
  9351. return prevLinPos;
  9352. };
  9353. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  9354. if (this.isManualZOrder) {
  9355. return null;
  9356. }
  9357. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  9358. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  9359. this._setZOrder(newZ, false);
  9360. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  9361. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  9362. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9363. }
  9364. var curZ = newZ;
  9365. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  9366. if (isFlat) {
  9367. if (this._children.length > 0) {
  9368. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  9369. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9370. var child = _a[_i];
  9371. child._updatePrimitiveFlatZOrder(this._zOrder);
  9372. }
  9373. }
  9374. }
  9375. else {
  9376. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  9377. var child = _c[_b];
  9378. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  9379. if (r != null) {
  9380. curZ = r;
  9381. }
  9382. }
  9383. }
  9384. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  9385. return curZ;
  9386. };
  9387. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  9388. if (this.isManualZOrder) {
  9389. return;
  9390. }
  9391. this._setZOrder(newZ, false);
  9392. this._zMax = newZ;
  9393. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  9394. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  9395. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9396. }
  9397. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9398. var child = _a[_i];
  9399. child._updatePrimitiveFlatZOrder(newZ);
  9400. }
  9401. };
  9402. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  9403. if (newZ !== this._zOrder) {
  9404. this._zOrder = newZ;
  9405. this.onPrimBecomesDirty();
  9406. this.onZOrderChanged();
  9407. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  9408. if (directEmit) {
  9409. this._actualZOrderChangedObservable.notifyObservers(newZ);
  9410. }
  9411. else {
  9412. Prim2DBase_1._zOrderChangedNotifList.push(this);
  9413. }
  9414. }
  9415. }
  9416. };
  9417. Prim2DBase.prototype._updateRenderMode = function () {
  9418. };
  9419. /**
  9420. * This method is used to alter the contentArea of the Primitive before margin is applied.
  9421. * In most of the case you won't need to override this method, but it can prove some usefulness, check the Rectangle2D class for a concrete application.
  9422. * @param primSize the current size of the primitive
  9423. * @param initialContentPosition the position of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing! x, y, z, w area left, bottom, right, top
  9424. * @param initialContentArea the size of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  9425. */
  9426. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  9427. initialContentArea.copyFrom(primSize);
  9428. initialContentPosition.x = initialContentPosition.y = initialContentPosition.z = initialContentPosition.w = 0;
  9429. };
  9430. /**
  9431. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  9432. * Check the Rectangle2D implementation for a concrete application.
  9433. * @param primSize the current size of the primitive
  9434. * @param newPrimSize the new size of the primitive. PLEASE ROUND THE values, we're talking about pixels and fraction of them are not our friends!
  9435. */
  9436. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, paddingOffset, newPrimSize) {
  9437. newPrimSize.copyFrom(primSize);
  9438. };
  9439. Object.defineProperty(Prim2DBase.prototype, "layoutData", {
  9440. /**
  9441. * Get/set the layout data to use for this primitive.
  9442. */
  9443. get: function () {
  9444. return this._layoutData;
  9445. },
  9446. set: function (value) {
  9447. if (this._layoutData === value) {
  9448. return;
  9449. }
  9450. this._layoutData = value;
  9451. },
  9452. enumerable: true,
  9453. configurable: true
  9454. });
  9455. return Prim2DBase;
  9456. }(BABYLON.SmartPropertyPrim));
  9457. Prim2DBase.PRIM2DBASE_PROPCOUNT = 25;
  9458. Prim2DBase._bigInt = Math.pow(2, 30);
  9459. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  9460. Prim2DBase._nullSize = BABYLON.Size.Zero();
  9461. Prim2DBase.boundinbBoxReentrency = -1;
  9462. Prim2DBase.nullSize = BABYLON.Size.Zero();
  9463. Prim2DBase._bMinMax = BABYLON.Vector4.Zero();
  9464. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  9465. Prim2DBase._bSize = BABYLON.Size.Zero();
  9466. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  9467. Prim2DBase._tpsBB2 = new BABYLON.BoundingInfo2D();
  9468. Prim2DBase._updatingDebugArea = false;
  9469. Prim2DBase._bypassGroup2DExclusion = false;
  9470. Prim2DBase._isCanvasInit = false;
  9471. Prim2DBase._t0 = new BABYLON.Matrix();
  9472. Prim2DBase._t1 = new BABYLON.Matrix();
  9473. Prim2DBase._t2 = new BABYLON.Matrix();
  9474. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  9475. Prim2DBase._v30 = BABYLON.Vector3.Zero(); // Must stay with the value 0,0,0
  9476. Prim2DBase._iv3 = new BABYLON.Vector3(1, 1, 1); // Must stay identity vector
  9477. Prim2DBase._ts0 = BABYLON.Size.Zero();
  9478. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  9479. Prim2DBase._transTT = BABYLON.Transform2D.Zero();
  9480. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  9481. Prim2DBase._icZone = BABYLON.Vector4.Zero();
  9482. Prim2DBase._icArea = BABYLON.Size.Zero();
  9483. Prim2DBase._size = BABYLON.Size.Zero();
  9484. Prim2DBase._size2 = BABYLON.Size.Zero();
  9485. Prim2DBase._curContentArea = BABYLON.Size.Zero();
  9486. Prim2DBase._zOrderChangedNotifList = new Array();
  9487. Prim2DBase._zRebuildReentrency = false;
  9488. Prim2DBase._totalCount = 0;
  9489. __decorate([
  9490. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase_1.actualPositionProperty = pi; }, false, false, true)
  9491. ], Prim2DBase.prototype, "actualPosition", null);
  9492. __decorate([
  9493. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 1, function (pi) { return Prim2DBase_1.actualXProperty = pi; }, false, false, true)
  9494. ], Prim2DBase.prototype, "actualX", null);
  9495. __decorate([
  9496. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 2, function (pi) { return Prim2DBase_1.actualYProperty = pi; }, false, false, true)
  9497. ], Prim2DBase.prototype, "actualY", null);
  9498. __decorate([
  9499. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 3, function (pi) { return Prim2DBase_1.positionProperty = pi; }, false, false, true)
  9500. ], Prim2DBase.prototype, "position", null);
  9501. __decorate([
  9502. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 4, function (pi) { return Prim2DBase_1.xProperty = pi; }, false, false, true)
  9503. ], Prim2DBase.prototype, "x", null);
  9504. __decorate([
  9505. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 5, function (pi) { return Prim2DBase_1.yProperty = pi; }, false, false, true)
  9506. ], Prim2DBase.prototype, "y", null);
  9507. __decorate([
  9508. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 6, function (pi) { return Prim2DBase_1.sizeProperty = pi; }, false, true)
  9509. ], Prim2DBase.prototype, "size", null);
  9510. __decorate([
  9511. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 7, function (pi) { return Prim2DBase_1.widthProperty = pi; }, false, true)
  9512. ], Prim2DBase.prototype, "width", null);
  9513. __decorate([
  9514. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 8, function (pi) { return Prim2DBase_1.heightProperty = pi; }, false, true)
  9515. ], Prim2DBase.prototype, "height", null);
  9516. __decorate([
  9517. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 9, function (pi) { return Prim2DBase_1.rotationProperty = pi; }, false, true)
  9518. ], Prim2DBase.prototype, "rotation", null);
  9519. __decorate([
  9520. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 10, function (pi) { return Prim2DBase_1.scaleProperty = pi; }, false, true)
  9521. ], Prim2DBase.prototype, "scale", null);
  9522. __decorate([
  9523. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 11, function (pi) { return Prim2DBase_1.actualSizeProperty = pi; }, false, true)
  9524. ], Prim2DBase.prototype, "actualSize", null);
  9525. __decorate([
  9526. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 12, function (pi) { return Prim2DBase_1.actualWidthProperty = pi; }, false, true)
  9527. ], Prim2DBase.prototype, "actualWidth", null);
  9528. __decorate([
  9529. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 13, function (pi) { return Prim2DBase_1.actualHeightProperty = pi; }, false, true)
  9530. ], Prim2DBase.prototype, "actualHeight", null);
  9531. __decorate([
  9532. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 14, function (pi) { return Prim2DBase_1.originProperty = pi; }, false, true)
  9533. ], Prim2DBase.prototype, "origin", null);
  9534. __decorate([
  9535. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 15, function (pi) { return Prim2DBase_1.levelVisibleProperty = pi; })
  9536. ], Prim2DBase.prototype, "levelVisible", null);
  9537. __decorate([
  9538. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 16, function (pi) { return Prim2DBase_1.isVisibleProperty = pi; })
  9539. ], Prim2DBase.prototype, "isVisible", null);
  9540. __decorate([
  9541. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 17, function (pi) { return Prim2DBase_1.zOrderProperty = pi; })
  9542. ], Prim2DBase.prototype, "zOrder", null);
  9543. __decorate([
  9544. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 18, function (pi) { return Prim2DBase_1.marginProperty = pi; })
  9545. ], Prim2DBase.prototype, "margin", null);
  9546. __decorate([
  9547. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 19, function (pi) { return Prim2DBase_1.paddingProperty = pi; })
  9548. ], Prim2DBase.prototype, "padding", null);
  9549. __decorate([
  9550. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 20, function (pi) { return Prim2DBase_1.marginAlignmentProperty = pi; })
  9551. ], Prim2DBase.prototype, "marginAlignment", null);
  9552. __decorate([
  9553. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 21, function (pi) { return Prim2DBase_1.opacityProperty = pi; })
  9554. ], Prim2DBase.prototype, "opacity", null);
  9555. __decorate([
  9556. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 22, function (pi) { return Prim2DBase_1.scaleXProperty = pi; }, false, true)
  9557. ], Prim2DBase.prototype, "scaleX", null);
  9558. __decorate([
  9559. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 23, function (pi) { return Prim2DBase_1.scaleYProperty = pi; }, false, true)
  9560. ], Prim2DBase.prototype, "scaleY", null);
  9561. __decorate([
  9562. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 24, function (pi) { return Prim2DBase_1.actualScaleProperty = pi; }, false, true)
  9563. ], Prim2DBase.prototype, "actualScale", null);
  9564. Prim2DBase = Prim2DBase_1 = __decorate([
  9565. BABYLON.className("Prim2DBase", "BABYLON")
  9566. ], Prim2DBase);
  9567. BABYLON.Prim2DBase = Prim2DBase;
  9568. var PrimitiveAlignment_1, PrimitiveThickness_1, Prim2DBase_1;
  9569. })(BABYLON || (BABYLON = {}));
  9570. //# sourceMappingURL=babylon.prim2dBase.js.map
  9571. var __extends = (this && this.__extends) || function (d, b) {
  9572. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9573. function __() { this.constructor = d; }
  9574. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9575. };
  9576. var BABYLON;
  9577. (function (BABYLON) {
  9578. var GroupInstanceInfo = (function () {
  9579. function GroupInstanceInfo(owner, mrc, partCount) {
  9580. this._partCount = partCount;
  9581. this.owner = owner;
  9582. this.modelRenderCache = mrc;
  9583. this.modelRenderCache.addRef();
  9584. this.partIndexFromId = new BABYLON.StringDictionary();
  9585. this._usedShaderCategories = new Array(partCount);
  9586. this._strides = new Array(partCount);
  9587. this._opaqueData = null;
  9588. this._alphaTestData = null;
  9589. this._transparentData = null;
  9590. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  9591. }
  9592. GroupInstanceInfo.prototype.dispose = function () {
  9593. if (this._isDisposed) {
  9594. return false;
  9595. }
  9596. if (this.modelRenderCache) {
  9597. this.modelRenderCache.dispose();
  9598. this.modelRenderCache = null;
  9599. }
  9600. var engine = this.owner.owner.engine;
  9601. if (this._opaqueData) {
  9602. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  9603. this._opaqueData = null;
  9604. }
  9605. if (this._alphaTestData) {
  9606. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  9607. this._alphaTestData = null;
  9608. }
  9609. if (this._transparentData) {
  9610. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  9611. this._transparentData = null;
  9612. }
  9613. this.partIndexFromId = null;
  9614. this._isDisposed = true;
  9615. return true;
  9616. };
  9617. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  9618. get: function () {
  9619. return this._opaqueData != null;
  9620. },
  9621. enumerable: true,
  9622. configurable: true
  9623. });
  9624. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  9625. get: function () {
  9626. return this._alphaTestData != null;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  9632. get: function () {
  9633. return this._transparentData != null;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  9639. get: function () {
  9640. if (!this._opaqueData) {
  9641. this._opaqueData = new Array(this._partCount);
  9642. for (var i = 0; i < this._partCount; i++) {
  9643. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  9644. }
  9645. }
  9646. return this._opaqueData;
  9647. },
  9648. enumerable: true,
  9649. configurable: true
  9650. });
  9651. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  9652. get: function () {
  9653. if (!this._alphaTestData) {
  9654. this._alphaTestData = new Array(this._partCount);
  9655. for (var i = 0; i < this._partCount; i++) {
  9656. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  9657. }
  9658. }
  9659. return this._alphaTestData;
  9660. },
  9661. enumerable: true,
  9662. configurable: true
  9663. });
  9664. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  9665. get: function () {
  9666. if (!this._transparentData) {
  9667. this._transparentData = new Array(this._partCount);
  9668. for (var i = 0; i < this._partCount; i++) {
  9669. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  9670. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  9671. }
  9672. }
  9673. return this._transparentData;
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. GroupInstanceInfo.prototype.sortTransparentData = function () {
  9679. if (!this.transparentOrderDirty) {
  9680. return;
  9681. }
  9682. for (var i = 0; i < this._transparentData.length; i++) {
  9683. var td = this._transparentData[i];
  9684. td._partData.sort();
  9685. }
  9686. this.transparentOrderDirty = false;
  9687. };
  9688. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  9689. get: function () {
  9690. return this._usedShaderCategories;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  9696. get: function () {
  9697. return this._strides;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. return GroupInstanceInfo;
  9703. }());
  9704. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  9705. var TransparentSegment = (function () {
  9706. function TransparentSegment() {
  9707. this.groupInsanceInfo = null;
  9708. this.startZ = 0;
  9709. this.endZ = 0;
  9710. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  9711. this.endDataIndex = 0;
  9712. this.partBuffers = null;
  9713. }
  9714. TransparentSegment.prototype.dispose = function (engine) {
  9715. if (this.partBuffers) {
  9716. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  9717. this.partBuffers.splice(0);
  9718. this.partBuffers = null;
  9719. }
  9720. };
  9721. return TransparentSegment;
  9722. }());
  9723. BABYLON.TransparentSegment = TransparentSegment;
  9724. var GroupInfoPartData = (function () {
  9725. function GroupInfoPartData(stride) {
  9726. this._partData = null;
  9727. this._partBuffer = null;
  9728. this._partBufferSize = 0;
  9729. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  9730. this._isDisposed = false;
  9731. }
  9732. GroupInfoPartData.prototype.dispose = function (engine) {
  9733. if (this._isDisposed) {
  9734. return false;
  9735. }
  9736. if (this._partBuffer) {
  9737. engine._releaseBuffer(this._partBuffer);
  9738. this._partBuffer = null;
  9739. }
  9740. this._partData = null;
  9741. this._isDisposed = true;
  9742. };
  9743. return GroupInfoPartData;
  9744. }());
  9745. BABYLON.GroupInfoPartData = GroupInfoPartData;
  9746. var TransparentGroupInfoPartData = (function (_super) {
  9747. __extends(TransparentGroupInfoPartData, _super);
  9748. function TransparentGroupInfoPartData(stride, zoff) {
  9749. var _this = _super.call(this, stride) || this;
  9750. _this._partData.compareValueOffset = zoff;
  9751. _this._partData.sortingAscending = false;
  9752. return _this;
  9753. }
  9754. return TransparentGroupInfoPartData;
  9755. }(GroupInfoPartData));
  9756. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  9757. var ModelRenderCache = (function () {
  9758. function ModelRenderCache(engine, modelKey) {
  9759. this._engine = engine;
  9760. this._modelKey = modelKey;
  9761. this._nextKey = 1;
  9762. this._refCounter = 1;
  9763. this._partData = null;
  9764. }
  9765. ModelRenderCache.prototype.dispose = function () {
  9766. if (--this._refCounter !== 0) {
  9767. return false;
  9768. }
  9769. // Remove the Model Render Cache from the global dictionary
  9770. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  9771. if (edata) {
  9772. edata.DisposeModelRenderCache(this);
  9773. }
  9774. return true;
  9775. };
  9776. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  9777. get: function () {
  9778. return this._refCounter <= 0;
  9779. },
  9780. enumerable: true,
  9781. configurable: true
  9782. });
  9783. ModelRenderCache.prototype.addRef = function () {
  9784. return ++this._refCounter;
  9785. };
  9786. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  9787. get: function () {
  9788. return this._modelKey;
  9789. },
  9790. enumerable: true,
  9791. configurable: true
  9792. });
  9793. ModelRenderCache.prototype.updateModelRenderCache = function (prim) {
  9794. return false;
  9795. };
  9796. /**
  9797. * Render the model instances
  9798. * @param instanceInfo
  9799. * @param context
  9800. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  9801. */
  9802. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  9803. return true;
  9804. };
  9805. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  9806. for (var i = 0; i < this._partData.length; i++) {
  9807. if (this._partData[i]._partId === partId) {
  9808. return i;
  9809. }
  9810. }
  9811. return null;
  9812. };
  9813. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  9814. var i = this.getPartIndexFromId(partId);
  9815. if (i === null) {
  9816. return null;
  9817. }
  9818. var ci = this._partsClassInfo[i];
  9819. var categories = this._partData[i]._partUsedCategories;
  9820. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  9821. return res;
  9822. };
  9823. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  9824. var pd = this._partData[partIndex];
  9825. var offset = (pd._partDataStride / 4) * elementCount;
  9826. var pci = this._partsClassInfo[partIndex];
  9827. var self = this;
  9828. pci.fullContent.forEach(function (k, v) {
  9829. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  9830. switch (v.dataType) {
  9831. case 4 /* float */:
  9832. {
  9833. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  9834. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  9835. break;
  9836. }
  9837. case 0 /* Vector2 */:
  9838. {
  9839. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  9840. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  9841. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  9842. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  9843. break;
  9844. }
  9845. case 5 /* Color3 */:
  9846. case 1 /* Vector3 */:
  9847. {
  9848. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  9849. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  9850. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  9851. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  9852. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  9853. break;
  9854. }
  9855. case 6 /* Color4 */:
  9856. case 2 /* Vector4 */:
  9857. {
  9858. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  9859. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  9860. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  9861. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  9862. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  9863. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  9864. break;
  9865. }
  9866. default:
  9867. }
  9868. }
  9869. });
  9870. };
  9871. return ModelRenderCache;
  9872. }());
  9873. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  9874. // let i = this.getPartIndexFromId(partId);
  9875. // if (i === null) {
  9876. // return null;
  9877. // }
  9878. // let pci = this._partsClassInfo[i];
  9879. // pci.fullContent.forEach((k, v) => {
  9880. // if (uniforms.indexOf(v.attributeName) !== -1) {
  9881. // v.uniformLocation = effect.getUniform(v.attributeName);
  9882. // }
  9883. // });
  9884. //}
  9885. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  9886. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  9887. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  9888. BABYLON.ModelRenderCache = ModelRenderCache;
  9889. var ModelRenderCachePartData = (function () {
  9890. function ModelRenderCachePartData() {
  9891. }
  9892. return ModelRenderCachePartData;
  9893. }());
  9894. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  9895. })(BABYLON || (BABYLON = {}));
  9896. //# sourceMappingURL=babylon.modelRenderCache.js.map
  9897. var __extends = (this && this.__extends) || function (d, b) {
  9898. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9899. function __() { this.constructor = d; }
  9900. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9901. };
  9902. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  9903. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  9904. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9905. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  9906. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9907. };
  9908. var BABYLON;
  9909. (function (BABYLON) {
  9910. var InstanceClassInfo = (function () {
  9911. function InstanceClassInfo(base) {
  9912. this._baseInfo = base;
  9913. this._nextOffset = new BABYLON.StringDictionary();
  9914. this._attributes = new Array();
  9915. }
  9916. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  9917. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  9918. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  9919. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  9920. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  9921. if (push) {
  9922. this._attributes.push(propInfo);
  9923. }
  9924. };
  9925. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  9926. var catInline = ";" + categories.join(";") + ";";
  9927. var res = new Array();
  9928. var curInfo = this;
  9929. while (curInfo) {
  9930. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  9931. var attrib = _a[_i];
  9932. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  9933. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  9934. var index = effect.getAttributeLocationByName(attrib.attributeName);
  9935. if (index === -1) {
  9936. throw new Error("Attribute " + attrib.attributeName + " was not found in Effect: " + effect.name + ". It's certainly no longer used in the Effect's Shaders");
  9937. }
  9938. var iai = new BABYLON.InstancingAttributeInfo();
  9939. iai.index = index;
  9940. iai.attributeSize = attrib.size / 4; // attrib.size is in byte and we need to store in "component" (i.e float is 1, vec3 is 3)
  9941. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  9942. iai.attributeName = attrib.attributeName;
  9943. res.push(iai);
  9944. }
  9945. }
  9946. curInfo = curInfo._baseInfo;
  9947. }
  9948. return res;
  9949. };
  9950. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  9951. var res = new Array();
  9952. var curInfo = this;
  9953. while (curInfo) {
  9954. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  9955. var attrib = _a[_i];
  9956. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  9957. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  9958. res.push(attrib.attributeName);
  9959. }
  9960. }
  9961. curInfo = curInfo._baseInfo;
  9962. }
  9963. return res;
  9964. };
  9965. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  9966. var curOffset = 0;
  9967. var curBase = this._baseInfo;
  9968. while (curBase) {
  9969. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  9970. curBase = curBase._baseInfo;
  9971. }
  9972. return curOffset;
  9973. };
  9974. return InstanceClassInfo;
  9975. }());
  9976. BABYLON.InstanceClassInfo = InstanceClassInfo;
  9977. var InstancePropInfo = (function () {
  9978. function InstancePropInfo() {
  9979. this.instanceOffset = new BABYLON.StringDictionary();
  9980. }
  9981. InstancePropInfo.prototype.setSize = function (val) {
  9982. if (val instanceof BABYLON.Vector2) {
  9983. this.size = 8;
  9984. this.dataType = 0 /* Vector2 */;
  9985. return;
  9986. }
  9987. if (val instanceof BABYLON.Vector3) {
  9988. this.size = 12;
  9989. this.dataType = 1 /* Vector3 */;
  9990. return;
  9991. }
  9992. if (val instanceof BABYLON.Vector4) {
  9993. this.size = 16;
  9994. this.dataType = 2 /* Vector4 */;
  9995. return;
  9996. }
  9997. if (val instanceof BABYLON.Matrix) {
  9998. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  9999. }
  10000. if (typeof (val) === "number") {
  10001. this.size = 4;
  10002. this.dataType = 4 /* float */;
  10003. return;
  10004. }
  10005. if (val instanceof BABYLON.Color3) {
  10006. this.size = 12;
  10007. this.dataType = 5 /* Color3 */;
  10008. return;
  10009. }
  10010. if (val instanceof BABYLON.Color4) {
  10011. this.size = 16;
  10012. this.dataType = 6 /* Color4 */;
  10013. return;
  10014. }
  10015. if (val instanceof BABYLON.Size) {
  10016. this.size = 8;
  10017. this.dataType = 7 /* Size */;
  10018. return;
  10019. }
  10020. return;
  10021. };
  10022. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  10023. switch (this.dataType) {
  10024. case 0 /* Vector2 */:
  10025. {
  10026. var v = val;
  10027. array[offset + 0] = v.x;
  10028. array[offset + 1] = v.y;
  10029. break;
  10030. }
  10031. case 1 /* Vector3 */:
  10032. {
  10033. var v = val;
  10034. array[offset + 0] = v.x;
  10035. array[offset + 1] = v.y;
  10036. array[offset + 2] = v.z;
  10037. break;
  10038. }
  10039. case 2 /* Vector4 */:
  10040. {
  10041. var v = val;
  10042. array[offset + 0] = v.x;
  10043. array[offset + 1] = v.y;
  10044. array[offset + 2] = v.z;
  10045. array[offset + 3] = v.w;
  10046. break;
  10047. }
  10048. case 5 /* Color3 */:
  10049. {
  10050. var v = val;
  10051. array[offset + 0] = v.r;
  10052. array[offset + 1] = v.g;
  10053. array[offset + 2] = v.b;
  10054. break;
  10055. }
  10056. case 6 /* Color4 */:
  10057. {
  10058. var v = val;
  10059. array[offset + 0] = v.r;
  10060. array[offset + 1] = v.g;
  10061. array[offset + 2] = v.b;
  10062. array[offset + 3] = v.a;
  10063. break;
  10064. }
  10065. case 4 /* float */:
  10066. {
  10067. var v = val;
  10068. array[offset] = v;
  10069. break;
  10070. }
  10071. case 3 /* Matrix */:
  10072. {
  10073. var v = val;
  10074. for (var i = 0; i < 16; i++) {
  10075. array[offset + i] = v.m[i];
  10076. }
  10077. break;
  10078. }
  10079. case 7 /* Size */:
  10080. {
  10081. var s = val;
  10082. array[offset + 0] = s.width;
  10083. array[offset + 1] = s.height;
  10084. break;
  10085. }
  10086. }
  10087. };
  10088. return InstancePropInfo;
  10089. }());
  10090. BABYLON.InstancePropInfo = InstancePropInfo;
  10091. function instanceData(category, shaderAttributeName) {
  10092. return function (target, propName, descriptor) {
  10093. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  10094. var node = dic.getLevelOf(target);
  10095. var instanceDataName = propName;
  10096. shaderAttributeName = shaderAttributeName || instanceDataName;
  10097. var info = node.levelContent.get(instanceDataName);
  10098. if (info) {
  10099. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  10100. }
  10101. info = new InstancePropInfo();
  10102. info.attributeName = shaderAttributeName;
  10103. info.category = category || null;
  10104. if (info.category) {
  10105. info.delimitedCategory = ";" + info.category + ";";
  10106. }
  10107. node.levelContent.add(instanceDataName, info);
  10108. descriptor.get = function () {
  10109. return null;
  10110. };
  10111. descriptor.set = function (val) {
  10112. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  10113. // Quit if it's the case, otherwise we could overwrite data somewhere...
  10114. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  10115. return;
  10116. }
  10117. if (!info.size) {
  10118. info.setSize(val);
  10119. node.classContent.mapProperty(info, true);
  10120. }
  10121. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  10122. node.classContent.mapProperty(info, false);
  10123. }
  10124. var obj = this;
  10125. if (obj.dataBuffer && obj.dataElements) {
  10126. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  10127. info.writeData(obj.dataBuffer.buffer, offset, val);
  10128. }
  10129. };
  10130. };
  10131. }
  10132. BABYLON.instanceData = instanceData;
  10133. var InstanceDataBase = (function () {
  10134. function InstanceDataBase(partId, dataElementCount) {
  10135. this.id = partId;
  10136. this.curElement = 0;
  10137. this._dataElementCount = dataElementCount;
  10138. this.renderMode = 0;
  10139. this.arrayLengthChanged = false;
  10140. }
  10141. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  10142. get: function () {
  10143. return null;
  10144. },
  10145. set: function (value) {
  10146. },
  10147. enumerable: true,
  10148. configurable: true
  10149. });
  10150. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  10151. get: function () {
  10152. return null;
  10153. },
  10154. set: function (value) {
  10155. },
  10156. enumerable: true,
  10157. configurable: true
  10158. });
  10159. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  10160. get: function () {
  10161. return null;
  10162. },
  10163. set: function (value) {
  10164. },
  10165. enumerable: true,
  10166. configurable: true
  10167. });
  10168. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  10169. get: function () {
  10170. return null;
  10171. },
  10172. set: function (value) {
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. InstanceDataBase.prototype.getClassTreeInfo = function () {
  10178. if (!this.typeInfo) {
  10179. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  10180. }
  10181. return this.typeInfo;
  10182. };
  10183. InstanceDataBase.prototype.allocElements = function () {
  10184. if (!this.dataBuffer || this.dataElements) {
  10185. return;
  10186. }
  10187. var res = new Array(this.dataElementCount);
  10188. for (var i = 0; i < this.dataElementCount; i++) {
  10189. res[i] = this.dataBuffer.allocElement();
  10190. }
  10191. this.dataElements = res;
  10192. };
  10193. InstanceDataBase.prototype.freeElements = function () {
  10194. if (!this.dataElements) {
  10195. return;
  10196. }
  10197. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  10198. var ei = _a[_i];
  10199. this.dataBuffer.freeElement(ei);
  10200. }
  10201. this.dataElements = null;
  10202. };
  10203. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  10204. get: function () {
  10205. return this._dataElementCount;
  10206. },
  10207. set: function (value) {
  10208. if (value === this._dataElementCount) {
  10209. return;
  10210. }
  10211. this.arrayLengthChanged = true;
  10212. this.freeElements();
  10213. this._dataElementCount = value;
  10214. this.allocElements();
  10215. },
  10216. enumerable: true,
  10217. configurable: true
  10218. });
  10219. return InstanceDataBase;
  10220. }());
  10221. __decorate([
  10222. instanceData()
  10223. ], InstanceDataBase.prototype, "zBias", null);
  10224. __decorate([
  10225. instanceData()
  10226. ], InstanceDataBase.prototype, "transformX", null);
  10227. __decorate([
  10228. instanceData()
  10229. ], InstanceDataBase.prototype, "transformY", null);
  10230. __decorate([
  10231. instanceData()
  10232. ], InstanceDataBase.prototype, "opacity", null);
  10233. BABYLON.InstanceDataBase = InstanceDataBase;
  10234. var RenderablePrim2D = RenderablePrim2D_1 = (function (_super) {
  10235. __extends(RenderablePrim2D, _super);
  10236. function RenderablePrim2D(settings) {
  10237. var _this = _super.call(this, settings) || this;
  10238. _this._transparentPrimitiveInfo = null;
  10239. return _this;
  10240. }
  10241. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  10242. get: function () {
  10243. return this._useTextureAlpha() || this._isPrimAlphaTest();
  10244. },
  10245. enumerable: true,
  10246. configurable: true
  10247. });
  10248. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  10249. get: function () {
  10250. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  10251. },
  10252. enumerable: true,
  10253. configurable: true
  10254. });
  10255. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  10256. get: function () {
  10257. return this._renderMode;
  10258. },
  10259. enumerable: true,
  10260. configurable: true
  10261. });
  10262. /**
  10263. * Dispose the primitive and its resources, remove it from its parent
  10264. */
  10265. RenderablePrim2D.prototype.dispose = function () {
  10266. if (!_super.prototype.dispose.call(this)) {
  10267. return false;
  10268. }
  10269. if (this.renderGroup) {
  10270. this.renderGroup._setCacheGroupDirty();
  10271. }
  10272. if (this._transparentPrimitiveInfo) {
  10273. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  10274. this._transparentPrimitiveInfo = null;
  10275. }
  10276. if (this._instanceDataParts) {
  10277. this._cleanupInstanceDataParts();
  10278. }
  10279. if (this._modelRenderCache) {
  10280. this._modelRenderCache.dispose();
  10281. this._modelRenderCache = null;
  10282. }
  10283. if (this._instanceDataParts) {
  10284. this._instanceDataParts.forEach(function (p) {
  10285. p.freeElements();
  10286. });
  10287. this._instanceDataParts = null;
  10288. }
  10289. return true;
  10290. };
  10291. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  10292. var gii = null;
  10293. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  10294. var part = _a[_i];
  10295. part.freeElements();
  10296. gii = part.groupInstanceInfo;
  10297. }
  10298. if (gii) {
  10299. var usedCount = 0;
  10300. if (gii.hasOpaqueData) {
  10301. var od = gii.opaqueData[0];
  10302. usedCount += od._partData.usedElementCount;
  10303. gii.opaqueDirty = true;
  10304. }
  10305. if (gii.hasAlphaTestData) {
  10306. var atd = gii.alphaTestData[0];
  10307. usedCount += atd._partData.usedElementCount;
  10308. gii.alphaTestDirty = true;
  10309. }
  10310. if (gii.hasTransparentData) {
  10311. var td = gii.transparentData[0];
  10312. usedCount += td._partData.usedElementCount;
  10313. gii.transparentDirty = true;
  10314. }
  10315. if (usedCount === 0 && gii.modelRenderCache != null) {
  10316. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  10317. gii.dispose();
  10318. }
  10319. if (this._modelRenderCache) {
  10320. this._modelRenderCache.dispose();
  10321. this._modelRenderCache = null;
  10322. }
  10323. }
  10324. this._instanceDataParts = null;
  10325. };
  10326. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  10327. _super.prototype._prepareRenderPre.call(this, context);
  10328. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  10329. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  10330. this._cleanupInstanceDataParts();
  10331. }
  10332. // Need to create the model?
  10333. var setupModelRenderCache = false;
  10334. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  10335. setupModelRenderCache = this._createModelRenderCache();
  10336. }
  10337. var gii = null;
  10338. var newInstance = false;
  10339. // Need to create the instance data parts?
  10340. if (!this._instanceDataParts) {
  10341. // Yes, flag it for later, more processing will have to be done
  10342. newInstance = true;
  10343. gii = this._createModelDataParts();
  10344. }
  10345. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  10346. if (setupModelRenderCache) {
  10347. this.setupModelRenderCache(this._modelRenderCache);
  10348. }
  10349. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelUpdate)) {
  10350. if (this._modelRenderCache.updateModelRenderCache(this)) {
  10351. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  10352. }
  10353. }
  10354. // At this stage we have everything correctly initialized, ModelRenderCache is setup, Model Instance data are good too, they have allocated elements in the Instanced DynamicFloatArray.
  10355. // The last thing to do is check if the instanced related data must be updated because a InstanceLevel property had changed or the primitive visibility changed.
  10356. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  10357. this._updateInstanceDataParts(gii);
  10358. }
  10359. };
  10360. RenderablePrim2D.prototype._createModelRenderCache = function () {
  10361. var _this = this;
  10362. var setupModelRenderCache = false;
  10363. if (this._modelRenderCache) {
  10364. this._modelRenderCache.dispose();
  10365. }
  10366. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  10367. var mrc = _this.createModelRenderCache(key);
  10368. setupModelRenderCache = true;
  10369. return mrc;
  10370. });
  10371. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  10372. // if this is still false it means the MRC already exists, so we add a reference to it
  10373. if (!setupModelRenderCache) {
  10374. this._modelRenderCache.addRef();
  10375. }
  10376. return setupModelRenderCache;
  10377. };
  10378. RenderablePrim2D.prototype._createModelDataParts = function () {
  10379. var _this = this;
  10380. // Create the instance data parts of the primitive and store them
  10381. var parts = this.createInstanceDataParts();
  10382. this._instanceDataParts = parts;
  10383. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  10384. if (!this._modelRenderCache._partData) {
  10385. this._setupModelRenderCache(parts);
  10386. }
  10387. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  10388. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  10389. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  10390. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  10391. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  10392. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  10393. var part = _this._instanceDataParts[j];
  10394. res.partIndexFromId.add(part.id.toString(), j);
  10395. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  10396. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  10397. }
  10398. return res;
  10399. });
  10400. // Get the GroupInfoDataPart corresponding to the render category of the part
  10401. var rm = 0;
  10402. var gipd = null;
  10403. if (this.isTransparent) {
  10404. gipd = gii.transparentData;
  10405. rm = BABYLON.Render2DContext.RenderModeTransparent;
  10406. }
  10407. else if (this.isAlphaTest) {
  10408. gipd = gii.alphaTestData;
  10409. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  10410. }
  10411. else {
  10412. gipd = gii.opaqueData;
  10413. rm = BABYLON.Render2DContext.RenderModeOpaque;
  10414. }
  10415. // For each instance data part of the primitive, allocate the instanced element it needs for render
  10416. for (var i = 0; i < parts.length; i++) {
  10417. var part = parts[i];
  10418. part.dataBuffer = gipd[i]._partData;
  10419. part.allocElements();
  10420. part.renderMode = rm;
  10421. part.groupInstanceInfo = gii;
  10422. }
  10423. return gii;
  10424. };
  10425. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  10426. var ctiArray = new Array();
  10427. this._modelRenderCache._partData = new Array();
  10428. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  10429. var dataPart = parts_1[_i];
  10430. var pd = new BABYLON.ModelRenderCachePartData();
  10431. this._modelRenderCache._partData.push(pd);
  10432. var cat = this.getUsedShaderCategories(dataPart);
  10433. var cti = dataPart.getClassTreeInfo();
  10434. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  10435. var curVisible = this.isVisible;
  10436. this.isVisible = true;
  10437. // We manually trigger refreshInstanceData for the only sake of evaluating each instance property size and offset in the instance data, this can only be made at runtime. Once it's done we have all the information to create the instance data buffer.
  10438. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  10439. var joinCat = ";" + cat.join(";") + ";";
  10440. pd._partJoinedUsedCategories = joinCat;
  10441. InstanceClassInfo._CurCategories = joinCat;
  10442. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  10443. if (!this.refreshInstanceDataPart(dataPart)) {
  10444. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  10445. }
  10446. this.afterRefreshForLayoutConstruction(dataPart, obj);
  10447. this.isVisible = curVisible;
  10448. var size = 0;
  10449. cti.fullContent.forEach(function (k, v) {
  10450. if (!v.category || cat.indexOf(v.category) !== -1) {
  10451. if (v.attributeName === "zBias") {
  10452. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  10453. }
  10454. if (!v.size) {
  10455. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  10456. }
  10457. else {
  10458. size += v.size;
  10459. }
  10460. }
  10461. });
  10462. pd._partDataStride = size;
  10463. pd._partUsedCategories = cat;
  10464. pd._partId = dataPart.id;
  10465. ctiArray.push(cti);
  10466. }
  10467. this._modelRenderCache._partsClassInfo = ctiArray;
  10468. };
  10469. RenderablePrim2D.prototype.onZOrderChanged = function () {
  10470. if (this.isTransparent && this._transparentPrimitiveInfo) {
  10471. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  10472. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  10473. // Flag the transparentData dirty has will have to sort it again
  10474. gii.transparentOrderDirty = true;
  10475. }
  10476. };
  10477. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  10478. return false;
  10479. };
  10480. RenderablePrim2D.prototype._useTextureAlpha = function () {
  10481. return false;
  10482. };
  10483. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  10484. return false;
  10485. };
  10486. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  10487. return false;
  10488. };
  10489. RenderablePrim2D.prototype._isPrimTransparent = function () {
  10490. return false;
  10491. };
  10492. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  10493. // Fetch the GroupInstanceInfo if we don't already have it
  10494. var rd = this.renderGroup._renderableData;
  10495. if (!gii) {
  10496. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  10497. }
  10498. var isTransparent = this.isTransparent;
  10499. var isAlphaTest = this.isAlphaTest;
  10500. var wereTransparent = false;
  10501. // Check a render mode change
  10502. var rmChanged = false;
  10503. if (this._instanceDataParts.length > 0) {
  10504. var firstPart = this._instanceDataParts[0];
  10505. var partRM = firstPart.renderMode;
  10506. var curRM = this.renderMode;
  10507. if (partRM !== curRM) {
  10508. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  10509. rmChanged = true;
  10510. var gipd = void 0;
  10511. switch (curRM) {
  10512. case BABYLON.Render2DContext.RenderModeTransparent:
  10513. gipd = gii.transparentData;
  10514. break;
  10515. case BABYLON.Render2DContext.RenderModeAlphaTest:
  10516. gipd = gii.alphaTestData;
  10517. break;
  10518. default:
  10519. gipd = gii.opaqueData;
  10520. }
  10521. for (var i = 0; i < this._instanceDataParts.length; i++) {
  10522. var part = this._instanceDataParts[i];
  10523. part.freeElements();
  10524. part.dataBuffer = gipd[i]._partData;
  10525. part.renderMode = curRM;
  10526. }
  10527. }
  10528. }
  10529. // Handle changes related to ZOffset
  10530. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  10531. if (isTransparent || wereTransparent) {
  10532. // Handle visibility change, which is also triggered when the primitive just got created
  10533. if (visChanged || rmChanged) {
  10534. if (this.isVisible && !wereTransparent) {
  10535. if (!this._transparentPrimitiveInfo) {
  10536. // Add the primitive to the list of transparent ones in the group that render is
  10537. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  10538. }
  10539. }
  10540. else {
  10541. if (this._transparentPrimitiveInfo) {
  10542. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  10543. this._transparentPrimitiveInfo = null;
  10544. }
  10545. }
  10546. gii.transparentOrderDirty = true;
  10547. }
  10548. }
  10549. var rebuildTrans = false;
  10550. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  10551. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  10552. var part = _a[_i];
  10553. var justAllocated = false;
  10554. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  10555. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  10556. part.allocElements();
  10557. justAllocated = true;
  10558. }
  10559. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  10560. // Will return false if the instance should not be rendered (not visible or other any reasons)
  10561. part.arrayLengthChanged = false;
  10562. if (!this.refreshInstanceDataPart(part)) {
  10563. // Free the data element
  10564. if (part.dataElements) {
  10565. part.freeElements();
  10566. }
  10567. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  10568. if (this.isVisible) {
  10569. rd._primNewDirtyList.push(this);
  10570. }
  10571. }
  10572. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  10573. }
  10574. this._instanceDirtyFlags = 0;
  10575. // Make the appropriate data dirty
  10576. if (isTransparent) {
  10577. gii.transparentDirty = true;
  10578. if (rebuildTrans) {
  10579. rd._transparentListChanged = true;
  10580. }
  10581. }
  10582. else if (isAlphaTest) {
  10583. gii.alphaTestDirty = true;
  10584. }
  10585. else {
  10586. gii.opaqueDirty = true;
  10587. }
  10588. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  10589. };
  10590. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  10591. var minOff = BABYLON.Prim2DBase._bigInt;
  10592. var maxOff = 0;
  10593. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  10594. var part = _a[_i];
  10595. if (part && part.dataElements) {
  10596. part.dataBuffer.pack();
  10597. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  10598. var el = _c[_b];
  10599. minOff = Math.min(minOff, el.offset);
  10600. maxOff = Math.max(maxOff, el.offset);
  10601. }
  10602. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  10603. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  10604. }
  10605. }
  10606. };
  10607. // This internal method is mainly used for transparency processing
  10608. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  10609. var length = this._instanceDataParts.length;
  10610. for (var i = 0; i < length; i++) {
  10611. var part = this._instanceDataParts[i];
  10612. if (part) {
  10613. var stride = part.dataBuffer.stride;
  10614. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  10615. // check if it's the last in the DFA
  10616. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  10617. return null;
  10618. }
  10619. // Return the Z of the next primitive that lies in the DFA
  10620. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  10621. }
  10622. }
  10623. return null;
  10624. };
  10625. // This internal method is mainly used for transparency processing
  10626. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  10627. var length = this._instanceDataParts.length;
  10628. for (var i = 0; i < length; i++) {
  10629. var part = this._instanceDataParts[i];
  10630. if (part) {
  10631. var stride = part.dataBuffer.stride;
  10632. var firstElementOffset = part.dataElements[0].offset;
  10633. // check if it's the first in the DFA
  10634. if (firstElementOffset === 0) {
  10635. return null;
  10636. }
  10637. // Return the Z of the previous primitive that lies in the DFA
  10638. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  10639. }
  10640. }
  10641. return null;
  10642. };
  10643. /**
  10644. * Transform a given point using the Primitive's origin setting.
  10645. * This method requires the Primitive's actualSize to be accurate
  10646. * @param p the point to transform
  10647. * @param originOffset an offset applied on the current origin before performing the transformation. Depending on which frame of reference your data is expressed you may have to apply a offset. (if you data is expressed from the bottom/left, no offset is required. If it's expressed from the center the a [-0.5;-0.5] offset has to be applied.
  10648. * @param res an allocated Vector2 that will receive the transformed content
  10649. */
  10650. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  10651. var actualSize = this.actualSize;
  10652. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  10653. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  10654. };
  10655. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  10656. this.transformPointWithOriginByRef(p, originOffset, res);
  10657. return res;
  10658. };
  10659. /**
  10660. * Get the info for a given effect based on the dataPart metadata
  10661. * @param dataPartId partId in part list to get the info
  10662. * @param vertexBufferAttributes vertex buffer attributes to manually add
  10663. * @param uniforms uniforms to manually add
  10664. * @param useInstanced specified if Instanced Array should be used, if null the engine caps will be used (so true if WebGL supports it, false otherwise), but you have the possibility to override the engine capability. However, if you manually set true but the engine does not support Instanced Array, this method will return null
  10665. */
  10666. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  10667. if (uniforms === void 0) { uniforms = null; }
  10668. if (useInstanced === void 0) { useInstanced = null; }
  10669. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  10670. if (!dataPart) {
  10671. return null;
  10672. }
  10673. var instancedArray = this.owner.supportInstancedArray;
  10674. if (useInstanced != null) {
  10675. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  10676. if (useInstanced && instancedArray === false) {
  10677. return null;
  10678. }
  10679. // Use the caller's setting
  10680. instancedArray = useInstanced;
  10681. }
  10682. var cti = dataPart.getClassTreeInfo();
  10683. var categories = this.getUsedShaderCategories(dataPart);
  10684. var att = cti.classContent.getShaderAttributes(categories);
  10685. var defines = "";
  10686. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  10687. if (instancedArray) {
  10688. defines += "#define Instanced\n";
  10689. }
  10690. return {
  10691. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  10692. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  10693. defines: defines
  10694. };
  10695. };
  10696. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  10697. get: function () {
  10698. return this._modelRenderCache;
  10699. },
  10700. enumerable: true,
  10701. configurable: true
  10702. });
  10703. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  10704. return null;
  10705. };
  10706. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  10707. };
  10708. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  10709. return null;
  10710. };
  10711. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  10712. return [];
  10713. };
  10714. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  10715. };
  10716. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  10717. };
  10718. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  10719. return true;
  10720. };
  10721. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  10722. if (!this.isVisible) {
  10723. return false;
  10724. }
  10725. part.isVisible = this.isVisible;
  10726. // Which means, if there's only one data element, we're update it from this method, otherwise it is the responsibility of the derived class to call updateInstanceDataPart as many times as needed, properly (look at Text2D's implementation for more information)
  10727. if (part.dataElementCount === 1) {
  10728. part.curElement = 0;
  10729. this.updateInstanceDataPart(part);
  10730. }
  10731. return true;
  10732. };
  10733. /**
  10734. * Update the instanceDataBase level properties of a part
  10735. * @param part the part to update
  10736. * @param positionOffset to use in multi part per primitive (e.g. the Text2D has N parts for N letter to display), this give the offset to apply (e.g. the position of the letter from the bottom/left corner of the text).
  10737. */
  10738. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  10739. if (positionOffset === void 0) { positionOffset = null; }
  10740. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  10741. var scl = RenderablePrim2D_1._s;
  10742. var rot = RenderablePrim2D_1._r;
  10743. var trn = RenderablePrim2D_1._t;
  10744. t.decompose(scl, rot, trn);
  10745. var pas = this.actualScale;
  10746. scl.x = pas.x;
  10747. scl.y = pas.y;
  10748. scl.z = 1;
  10749. t = BABYLON.Matrix.Compose(this.applyActualScaleOnTransform() ? scl : RenderablePrim2D_1._iV3, rot, trn);
  10750. var size = this.renderGroup.viewportSize;
  10751. var zBias = this.actualZOffset;
  10752. var offX = 0;
  10753. var offY = 0;
  10754. // If there's an offset, apply the global transformation matrix on it to get a global offset
  10755. if (positionOffset) {
  10756. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  10757. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  10758. }
  10759. // Have to convert the coordinates to clip space which is ranged between [-1;1] on X and Y axis, with 0,0 being the left/bottom corner
  10760. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  10761. // So for X:
  10762. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  10763. // - tx.w = (value * 2 / width) - 1: w stores the translation in renderGroup coordinates so (value * 2 / width) to switch to a clip space translation value. - 1 is to offset the overall [0;2] to [-1;1].
  10764. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  10765. var w = size.width;
  10766. var h = size.height;
  10767. var invZBias = 1 / zBias;
  10768. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0, ((t.m[12] + offX) * 2 / w) - 1);
  10769. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0, ((t.m[13] + offY) * 2 / h) - 1);
  10770. part.transformX = tx;
  10771. part.transformY = ty;
  10772. part.opacity = this.actualOpacity;
  10773. // Stores zBias and it's inverse value because that's needed to compute the clip space W coordinate (which is 1/Z, so 1/zBias)
  10774. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  10775. };
  10776. RenderablePrim2D.prototype._updateRenderMode = function () {
  10777. if (this.isTransparent) {
  10778. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  10779. }
  10780. else if (this.isAlphaTest) {
  10781. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  10782. }
  10783. else {
  10784. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  10785. }
  10786. };
  10787. return RenderablePrim2D;
  10788. }(BABYLON.Prim2DBase));
  10789. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  10790. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  10791. RenderablePrim2D._s = BABYLON.Vector3.Zero();
  10792. RenderablePrim2D._r = BABYLON.Quaternion.Identity();
  10793. RenderablePrim2D._t = BABYLON.Vector3.Zero();
  10794. RenderablePrim2D._iV3 = new BABYLON.Vector3(1, 1, 1); // Must stay identity vector3
  10795. __decorate([
  10796. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D_1.isAlphaTestProperty = pi; })
  10797. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  10798. __decorate([
  10799. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D_1.isTransparentProperty = pi; })
  10800. ], RenderablePrim2D.prototype, "isTransparent", null);
  10801. RenderablePrim2D = RenderablePrim2D_1 = __decorate([
  10802. BABYLON.className("RenderablePrim2D", "BABYLON")
  10803. ], RenderablePrim2D);
  10804. BABYLON.RenderablePrim2D = RenderablePrim2D;
  10805. var RenderablePrim2D_1;
  10806. })(BABYLON || (BABYLON = {}));
  10807. //# sourceMappingURL=babylon.renderablePrim2d.js.map
  10808. var __extends = (this && this.__extends) || function (d, b) {
  10809. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10810. function __() { this.constructor = d; }
  10811. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  10812. };
  10813. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  10814. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  10815. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  10816. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  10817. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10818. };
  10819. var BABYLON;
  10820. (function (BABYLON) {
  10821. var Shape2D = Shape2D_1 = (function (_super) {
  10822. __extends(Shape2D, _super);
  10823. function Shape2D(settings) {
  10824. var _this = _super.call(this, settings) || this;
  10825. if (!settings) {
  10826. settings = {};
  10827. }
  10828. var borderBrush = null;
  10829. if (settings.border) {
  10830. if (typeof (settings.border) === "string") {
  10831. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  10832. }
  10833. else {
  10834. borderBrush = settings.border;
  10835. }
  10836. }
  10837. var fillBrush = null;
  10838. if (settings.fill) {
  10839. if (typeof (settings.fill) === "string") {
  10840. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  10841. }
  10842. else {
  10843. fillBrush = settings.fill;
  10844. }
  10845. }
  10846. _this._isTransparent = false;
  10847. _this._oldTransparent = false;
  10848. _this.border = borderBrush;
  10849. _this.fill = fillBrush;
  10850. _this._updateTransparencyStatus();
  10851. _this.borderThickness = settings.borderThickness;
  10852. return _this;
  10853. }
  10854. Object.defineProperty(Shape2D.prototype, "border", {
  10855. get: function () {
  10856. return this._border;
  10857. },
  10858. set: function (value) {
  10859. this._border = value;
  10860. this._updateTransparencyStatus();
  10861. },
  10862. enumerable: true,
  10863. configurable: true
  10864. });
  10865. Object.defineProperty(Shape2D.prototype, "fill", {
  10866. /**
  10867. * Get/set the brush to render the Fill part of the Primitive
  10868. */
  10869. get: function () {
  10870. return this._fill;
  10871. },
  10872. set: function (value) {
  10873. this._fill = value;
  10874. this._updateTransparencyStatus();
  10875. },
  10876. enumerable: true,
  10877. configurable: true
  10878. });
  10879. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  10880. get: function () {
  10881. return this._borderThickness;
  10882. },
  10883. set: function (value) {
  10884. this._borderThickness = value;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  10890. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  10891. // Fill Part
  10892. if (dataPart.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  10893. var fill = this.fill;
  10894. if (fill instanceof BABYLON.SolidColorBrush2D) {
  10895. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLSOLID);
  10896. }
  10897. if (fill instanceof BABYLON.GradientColorBrush2D) {
  10898. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLGRADIENT);
  10899. }
  10900. }
  10901. // Border Part
  10902. if (dataPart.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  10903. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDER);
  10904. var border = this.border;
  10905. if (border instanceof BABYLON.SolidColorBrush2D) {
  10906. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERSOLID);
  10907. }
  10908. if (border instanceof BABYLON.GradientColorBrush2D) {
  10909. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERGRADIENT);
  10910. }
  10911. }
  10912. return cat;
  10913. };
  10914. Shape2D.prototype.applyActualScaleOnTransform = function () {
  10915. return false;
  10916. };
  10917. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  10918. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  10919. return false;
  10920. }
  10921. // Fill Part
  10922. if (part.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  10923. var d = part;
  10924. if (this.fill) {
  10925. var fill = this.fill;
  10926. if (fill instanceof BABYLON.SolidColorBrush2D) {
  10927. d.fillSolidColor = fill.color;
  10928. }
  10929. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  10930. d.fillGradientColor1 = fill.color1;
  10931. d.fillGradientColor2 = fill.color2;
  10932. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(fill.scale, fill.scale, fill.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), fill.rotation), new BABYLON.Vector3(fill.translation.x, fill.translation.y, 0));
  10933. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  10934. d.fillGradientTY = ty;
  10935. }
  10936. }
  10937. }
  10938. else if (part.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  10939. var d = part;
  10940. if (this.border) {
  10941. d.borderThickness = this.borderThickness;
  10942. var border = this.border;
  10943. if (border instanceof BABYLON.SolidColorBrush2D) {
  10944. d.borderSolidColor = border.color;
  10945. }
  10946. else if (border instanceof BABYLON.GradientColorBrush2D) {
  10947. d.borderGradientColor1 = border.color1;
  10948. d.borderGradientColor2 = border.color2;
  10949. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(border.scale, border.scale, border.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), border.rotation), new BABYLON.Vector3(border.translation.x, border.translation.y, 0));
  10950. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  10951. d.borderGradientTY = ty;
  10952. }
  10953. }
  10954. }
  10955. return true;
  10956. };
  10957. Shape2D.prototype._updateTransparencyStatus = function () {
  10958. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  10959. if (this._isTransparent !== this._oldTransparent) {
  10960. this._oldTransparent = this._isTransparent;
  10961. this._updateRenderMode();
  10962. }
  10963. };
  10964. Shape2D.prototype._mustUpdateInstance = function () {
  10965. var res = this._oldTransparent !== this._isTransparent;
  10966. if (res) {
  10967. this._updateRenderMode();
  10968. this._oldTransparent = this._isTransparent;
  10969. }
  10970. return res;
  10971. };
  10972. Shape2D.prototype._isPrimTransparent = function () {
  10973. return this._isTransparent;
  10974. };
  10975. return Shape2D;
  10976. }(BABYLON.RenderablePrim2D));
  10977. Shape2D.SHAPE2D_BORDERPARTID = 1;
  10978. Shape2D.SHAPE2D_FILLPARTID = 2;
  10979. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  10980. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  10981. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  10982. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  10983. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  10984. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  10985. __decorate([
  10986. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D_1.borderProperty = pi; }, true)
  10987. ], Shape2D.prototype, "border", null);
  10988. __decorate([
  10989. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D_1.fillProperty = pi; }, true)
  10990. ], Shape2D.prototype, "fill", null);
  10991. __decorate([
  10992. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D_1.borderThicknessProperty = pi; })
  10993. ], Shape2D.prototype, "borderThickness", null);
  10994. Shape2D = Shape2D_1 = __decorate([
  10995. BABYLON.className("Shape2D", "BABYLON")
  10996. ], Shape2D);
  10997. BABYLON.Shape2D = Shape2D;
  10998. var Shape2DInstanceData = (function (_super) {
  10999. __extends(Shape2DInstanceData, _super);
  11000. function Shape2DInstanceData() {
  11001. return _super.apply(this, arguments) || this;
  11002. }
  11003. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  11004. // FILL ATTRIBUTES
  11005. get: function () {
  11006. return null;
  11007. },
  11008. set: function (value) {
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  11014. get: function () {
  11015. return null;
  11016. },
  11017. set: function (value) {
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  11023. get: function () {
  11024. return null;
  11025. },
  11026. set: function (value) {
  11027. },
  11028. enumerable: true,
  11029. configurable: true
  11030. });
  11031. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  11032. get: function () {
  11033. return null;
  11034. },
  11035. set: function (value) {
  11036. },
  11037. enumerable: true,
  11038. configurable: true
  11039. });
  11040. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  11041. // BORDER ATTRIBUTES
  11042. get: function () {
  11043. return null;
  11044. },
  11045. set: function (value) {
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  11051. get: function () {
  11052. return null;
  11053. },
  11054. set: function (value) {
  11055. },
  11056. enumerable: true,
  11057. configurable: true
  11058. });
  11059. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  11060. get: function () {
  11061. return null;
  11062. },
  11063. set: function (value) {
  11064. },
  11065. enumerable: true,
  11066. configurable: true
  11067. });
  11068. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  11069. get: function () {
  11070. return null;
  11071. },
  11072. set: function (value) {
  11073. },
  11074. enumerable: true,
  11075. configurable: true
  11076. });
  11077. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  11078. get: function () {
  11079. return null;
  11080. },
  11081. set: function (value) {
  11082. },
  11083. enumerable: true,
  11084. configurable: true
  11085. });
  11086. return Shape2DInstanceData;
  11087. }(BABYLON.InstanceDataBase));
  11088. __decorate([
  11089. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  11090. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  11091. __decorate([
  11092. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  11093. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  11094. __decorate([
  11095. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  11096. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  11097. __decorate([
  11098. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  11099. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  11100. __decorate([
  11101. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  11102. ], Shape2DInstanceData.prototype, "borderThickness", null);
  11103. __decorate([
  11104. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  11105. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  11106. __decorate([
  11107. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  11108. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  11109. __decorate([
  11110. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  11111. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  11112. __decorate([
  11113. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  11114. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  11115. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  11116. var Shape2D_1;
  11117. })(BABYLON || (BABYLON = {}));
  11118. //# sourceMappingURL=babylon.shape2d.js.map
  11119. var __extends = (this && this.__extends) || function (d, b) {
  11120. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11121. function __() { this.constructor = d; }
  11122. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11123. };
  11124. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11125. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11126. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11127. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  11128. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11129. };
  11130. var BABYLON;
  11131. (function (BABYLON) {
  11132. var Group2D = Group2D_1 = (function (_super) {
  11133. __extends(Group2D, _super);
  11134. /**
  11135. * Create an Logical or Renderable Group.
  11136. * @param settings a combination of settings, possible ones are
  11137. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  11138. * - children: an array of direct children
  11139. * - id a text identifier, for information purpose
  11140. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  11141. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  11142. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  11143. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  11144. * - trackNode: if you want the ScreenSpaceCanvas to track the position of a given Scene Node, use this setting to specify the Node to track
  11145. * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
  11146. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  11147. * - zOrder: override the zOrder with the specified value
  11148. * - origin: define the normalized origin point location, default [0.5;0.5]
  11149. * - size: the size of the group. Alternatively the width and height properties can be set. If null the size will be computed from its content, default is null.
  11150. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  11151. * - layoutEngine: either an instance of a layout engine based class (StackPanel.Vertical, StackPanel.Horizontal) or a string ('canvas' for Canvas layout, 'StackPanel' or 'HorizontalStackPanel' for horizontal Stack Panel layout, 'VerticalStackPanel' for vertical Stack Panel layout).
  11152. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  11153. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  11154. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  11155. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  11156. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  11157. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  11158. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  11159. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11160. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11161. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11162. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11163. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  11164. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  11165. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  11166. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  11167. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11168. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11169. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11170. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11171. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  11172. */
  11173. function Group2D(settings) {
  11174. var _this;
  11175. if (settings == null) {
  11176. settings = {};
  11177. }
  11178. if (settings.origin == null) {
  11179. settings.origin = new BABYLON.Vector2(0, 0);
  11180. }
  11181. _this = _super.call(this, settings) || this;
  11182. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  11183. _this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  11184. _this._trackedNodeOffset = (settings.trackNodeOffset == null) ? null : settings.trackNodeOffset;
  11185. if (_this._trackedNode && _this.owner) {
  11186. _this.owner._registerTrackedNode(_this);
  11187. }
  11188. _this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  11189. var rd = _this._renderableData;
  11190. if (rd) {
  11191. rd._noResizeOnScale = (_this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  11192. }
  11193. _this.size = size;
  11194. _this._viewportPosition = BABYLON.Vector2.Zero();
  11195. _this._viewportSize = BABYLON.Size.Zero();
  11196. return _this;
  11197. }
  11198. Group2D._createCachedCanvasGroup = function (owner) {
  11199. var g = new Group2D_1({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true, isPickable: false, dontInheritParentScale: true });
  11200. return g;
  11201. };
  11202. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  11203. this._bindCacheTarget();
  11204. if (vertexData) {
  11205. var uv = vertexData.uvs;
  11206. var nodeuv = this._renderableData._cacheNodeUVs;
  11207. for (var i = 0; i < 4; i++) {
  11208. uv[i * 2 + 0] = nodeuv[i].x;
  11209. uv[i * 2 + 1] = nodeuv[i].y;
  11210. }
  11211. }
  11212. if (material) {
  11213. material.diffuseTexture = this._renderableData._cacheTexture;
  11214. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  11215. }
  11216. this._renderableData._cacheTexture.hasAlpha = true;
  11217. this._unbindCacheTarget();
  11218. };
  11219. Object.defineProperty(Group2D.prototype, "cachedRect", {
  11220. /**
  11221. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  11222. * If the `noWorldSpaceNode` options was used at the creation of a WorldSpaceCanvas, the rendering of the canvas must be made by the caller, so typically you want to bind the cacheTexture property to some material/mesh and you MUST use the Group2D.cachedUVs property to get the UV coordinates to use for your quad that will display the Canvas and NOT the PackedRect.UVs property which are incorrect because the allocated surface may be bigger (due to over-provisioning or shrinking without deallocating) than what the Group is actually using.
  11223. */
  11224. get: function () {
  11225. if (!this._renderableData) {
  11226. return null;
  11227. }
  11228. return this._renderableData._cacheNode;
  11229. },
  11230. enumerable: true,
  11231. configurable: true
  11232. });
  11233. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  11234. /**
  11235. * The UVs into the MapTexture that map the cached group
  11236. */
  11237. get: function () {
  11238. if (!this._renderableData) {
  11239. return null;
  11240. }
  11241. return this._renderableData._cacheNodeUVs;
  11242. },
  11243. enumerable: true,
  11244. configurable: true
  11245. });
  11246. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  11247. get: function () {
  11248. if (!this._renderableData) {
  11249. return null;
  11250. }
  11251. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  11252. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  11253. }
  11254. return this._renderableData._cacheNodeUVsChangedObservable;
  11255. },
  11256. enumerable: true,
  11257. configurable: true
  11258. });
  11259. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  11260. /**
  11261. * Access the texture that maintains a cached version of the Group2D.
  11262. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  11263. */
  11264. get: function () {
  11265. if (!this._renderableData) {
  11266. return null;
  11267. }
  11268. return this._renderableData._cacheTexture;
  11269. },
  11270. enumerable: true,
  11271. configurable: true
  11272. });
  11273. /**
  11274. * Call this method to remove this Group and its children from the Canvas
  11275. */
  11276. Group2D.prototype.dispose = function () {
  11277. if (!_super.prototype.dispose.call(this)) {
  11278. return false;
  11279. }
  11280. if (this._trackedNode != null) {
  11281. this.owner._unregisterTrackedNode(this);
  11282. this._trackedNode = null;
  11283. }
  11284. if (this._renderableData) {
  11285. this._renderableData.dispose(this.owner);
  11286. this._renderableData = null;
  11287. }
  11288. return true;
  11289. };
  11290. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  11291. /**
  11292. * @returns Returns true if the Group render content, false if it's a logical group only
  11293. */
  11294. get: function () {
  11295. return this._isRenderableGroup;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  11301. /**
  11302. * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time
  11303. */
  11304. get: function () {
  11305. return this._isCachedGroup;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(Group2D.prototype, "size", {
  11311. get: function () {
  11312. return this.internalGetSize();
  11313. },
  11314. /**
  11315. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  11316. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does.
  11317. */
  11318. set: function (val) {
  11319. this.internalSetSize(val);
  11320. },
  11321. enumerable: true,
  11322. configurable: true
  11323. });
  11324. Object.defineProperty(Group2D.prototype, "viewportSize", {
  11325. get: function () {
  11326. return this._viewportSize;
  11327. },
  11328. enumerable: true,
  11329. configurable: true
  11330. });
  11331. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  11332. /**
  11333. * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information.
  11334. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  11335. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all.
  11336. */
  11337. get: function () {
  11338. return this._cacheBehavior;
  11339. },
  11340. enumerable: true,
  11341. configurable: true
  11342. });
  11343. Group2D.prototype._addPrimToDirtyList = function (prim) {
  11344. this._renderableData._primDirtyList.push(prim);
  11345. };
  11346. Group2D.prototype._renderCachedCanvas = function () {
  11347. this.owner._addGroupRenderCount(1);
  11348. this.updateCachedStates(true);
  11349. var context = new BABYLON.PrepareRender2DContext();
  11350. this._prepareGroupRender(context);
  11351. this._groupRender();
  11352. };
  11353. Object.defineProperty(Group2D.prototype, "trackedNode", {
  11354. /**
  11355. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  11356. */
  11357. get: function () {
  11358. return this._trackedNode;
  11359. },
  11360. set: function (val) {
  11361. if (val != null) {
  11362. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  11363. this.owner._registerTrackedNode(this);
  11364. }
  11365. this._trackedNode = val;
  11366. }
  11367. else {
  11368. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  11369. this.owner._unregisterTrackedNode(this);
  11370. }
  11371. this._trackedNode = null;
  11372. }
  11373. },
  11374. enumerable: true,
  11375. configurable: true
  11376. });
  11377. Object.defineProperty(Group2D.prototype, "trackedNodeOffset", {
  11378. /**
  11379. * Get/set the offset of the tracked node in the tracked node's local space.
  11380. */
  11381. get: function () {
  11382. return this._trackedNodeOffset;
  11383. },
  11384. set: function (val) {
  11385. if (!this._trackedNodeOffset) {
  11386. this._trackedNodeOffset = val.clone();
  11387. }
  11388. else {
  11389. this._trackedNodeOffset.copyFrom(val);
  11390. }
  11391. },
  11392. enumerable: true,
  11393. configurable: true
  11394. });
  11395. Group2D.prototype.levelIntersect = function (intersectInfo) {
  11396. // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true
  11397. return true;
  11398. };
  11399. Group2D.prototype.updateLevelBoundingInfo = function () {
  11400. var size;
  11401. // If the size is set by the user, the boundingInfo is computed from this value
  11402. if (this.size) {
  11403. size = this.size;
  11404. }
  11405. else {
  11406. size = new BABYLON.Size(0, 0);
  11407. }
  11408. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  11409. return true;
  11410. };
  11411. // Method called only on renderable groups to prepare the rendering
  11412. Group2D.prototype._prepareGroupRender = function (context) {
  11413. var sortedDirtyList = null;
  11414. // Update the Global Transformation and visibility status of the changed primitives
  11415. var rd = this._renderableData;
  11416. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  11417. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  11418. this.updateCachedStatesOf(sortedDirtyList, true);
  11419. }
  11420. var s = this.actualSize;
  11421. var a = this.actualScale;
  11422. var hwsl = 1 / this.owner.engine.getHardwareScalingLevel();
  11423. var sw = Math.ceil(s.width * a.x * hwsl);
  11424. var sh = Math.ceil(s.height * a.y * hwsl);
  11425. // The dimension must be overridden when using the designSize feature, the ratio is maintain to compute a uniform scale, which is mandatory but if the designSize's ratio is different from the rendering surface's ratio, content will be clipped in some cases.
  11426. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  11427. if ((this instanceof BABYLON.Canvas2D || this.id === "__cachedCanvasGroup__") && this.owner.designSize != null) {
  11428. sw = this.owner.engine.getRenderWidth();
  11429. sh = this.owner.engine.getRenderHeight();
  11430. }
  11431. // Setup the size of the rendering viewport
  11432. // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute
  11433. if (!this._isCachedGroup) {
  11434. // Compute the WebGL viewport's location/size
  11435. var t = this._globalTransform.getTranslation();
  11436. var rs = this.owner._renderingSize.multiplyByFloats(hwsl, hwsl);
  11437. sh = Math.min(sh, rs.height - t.y);
  11438. sw = Math.min(sw, rs.width - t.x);
  11439. var x = t.x;
  11440. var y = t.y;
  11441. // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed
  11442. this._viewportPosition.x = x;
  11443. this._viewportPosition.y = y;
  11444. }
  11445. // For a cachedGroup we also check of the group's actualSize is changing, if it's the case then the rendering zone will be change so we also have to dirty all primitives to prepare them again.
  11446. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  11447. context.forceRefreshPrimitive = true;
  11448. this._viewportSize.width = sw;
  11449. this._viewportSize.height = sh;
  11450. }
  11451. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  11452. // If the group is cached, set the dirty flag to true because of the incoming changes
  11453. this._cacheGroupDirty = this._isCachedGroup;
  11454. rd._primNewDirtyList.splice(0);
  11455. // If it's a force refresh, prepare all the children
  11456. if (context.forceRefreshPrimitive) {
  11457. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11458. var p = _a[_i];
  11459. p._prepareRender(context);
  11460. }
  11461. }
  11462. else {
  11463. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  11464. // the hierarchyDepth in order to prepare primitives from top to bottom
  11465. if (!sortedDirtyList) {
  11466. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  11467. }
  11468. sortedDirtyList.forEach(function (p) {
  11469. // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them.
  11470. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check.
  11471. if (!p.isDisposed && p._needPrepare()) {
  11472. p._prepareRender(context);
  11473. }
  11474. });
  11475. }
  11476. // Everything is updated, clear the dirty list
  11477. rd._primDirtyList.forEach(function (p) {
  11478. if (rd._primNewDirtyList.indexOf(p) === -1) {
  11479. p._resetPropertiesDirty();
  11480. }
  11481. else {
  11482. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  11483. }
  11484. });
  11485. rd._primDirtyList.splice(0);
  11486. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  11487. }
  11488. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  11489. rd._childrenRenderableGroups.forEach(function (g) {
  11490. g._prepareGroupRender(context);
  11491. });
  11492. };
  11493. Group2D.prototype._groupRender = function () {
  11494. var _this = this;
  11495. var engine = this.owner.engine;
  11496. var failedCount = 0;
  11497. // First recurse to children render group to render them (in their cache or on screen)
  11498. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  11499. var childGroup = _a[_i];
  11500. childGroup._groupRender();
  11501. }
  11502. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  11503. if (!this.isCachedGroup || this._cacheGroupDirty) {
  11504. this.owner._addGroupRenderCount(1);
  11505. if (this.isCachedGroup) {
  11506. this._bindCacheTarget();
  11507. }
  11508. else {
  11509. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  11510. }
  11511. var curAlphaTest = engine.getAlphaTesting() === true;
  11512. var curDepthWrite = engine.getDepthWrite() === true;
  11513. // ===================================================================
  11514. // First pass, update the InstancedArray and render Opaque primitives
  11515. // Disable Alpha Testing, Enable Depth Write
  11516. engine.setAlphaTesting(false);
  11517. engine.setDepthWrite(true);
  11518. // For each different model of primitive to render
  11519. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  11520. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  11521. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  11522. var renderCount = _this._prepareContext(engine, context_1, v);
  11523. // If null is returned, there's no opaque data to render
  11524. if (renderCount === null) {
  11525. return;
  11526. }
  11527. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  11528. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  11529. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  11530. var renderFailed = !v.modelRenderCache.render(v, context_1);
  11531. // Update dirty flag/related
  11532. v.opaqueDirty = renderFailed;
  11533. failedCount += renderFailed ? 1 : 0;
  11534. }
  11535. });
  11536. // =======================================================================
  11537. // Second pass, update the InstancedArray and render AlphaTest primitives
  11538. // Enable Alpha Testing, Enable Depth Write
  11539. engine.setAlphaTesting(true);
  11540. engine.setDepthWrite(true);
  11541. // For each different model of primitive to render
  11542. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  11543. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  11544. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  11545. var renderCount = _this._prepareContext(engine, context_1, v);
  11546. // If null is returned, there's no opaque data to render
  11547. if (renderCount === null) {
  11548. return;
  11549. }
  11550. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  11551. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  11552. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  11553. var renderFailed = !v.modelRenderCache.render(v, context_1);
  11554. // Update dirty flag/related
  11555. v.opaqueDirty = renderFailed;
  11556. failedCount += renderFailed ? 1 : 0;
  11557. }
  11558. });
  11559. // =======================================================================
  11560. // Third pass, transparent primitive rendering
  11561. // Enable Alpha Testing, Disable Depth Write
  11562. engine.setAlphaTesting(true);
  11563. engine.setDepthWrite(false);
  11564. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  11565. if (this._renderableData._transparentListChanged) {
  11566. this._updateTransparentData();
  11567. }
  11568. // From this point on we have up to date data to render, so let's go
  11569. failedCount += this._renderTransparentData();
  11570. // =======================================================================
  11571. // Unbind target/restore viewport setting, clear dirty flag, and quit
  11572. // The group's content is no longer dirty
  11573. this._cacheGroupDirty = failedCount !== 0;
  11574. if (this.isCachedGroup) {
  11575. this._unbindCacheTarget();
  11576. }
  11577. else {
  11578. if (curVP) {
  11579. engine.setViewport(curVP);
  11580. }
  11581. }
  11582. // Restore saved states
  11583. engine.setAlphaTesting(curAlphaTest);
  11584. engine.setDepthWrite(curDepthWrite);
  11585. }
  11586. };
  11587. Group2D.prototype._setCacheGroupDirty = function () {
  11588. this._cacheGroupDirty = true;
  11589. };
  11590. Group2D.prototype._updateTransparentData = function () {
  11591. this.owner._addUpdateTransparentDataCount(1);
  11592. var rd = this._renderableData;
  11593. // Sort all the primitive from their depth, max (bottom) to min (top)
  11594. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  11595. var checkAndAddPrimInSegment = function (seg, tpiI) {
  11596. var tpi = rd._transparentPrimitives[tpiI];
  11597. // Fast rejection: if gii are different
  11598. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  11599. return false;
  11600. }
  11601. //let tpiZ = tpi._primitive.actualZOffset;
  11602. // We've made it so far, the tpi can be part of the segment, add it
  11603. tpi._transparentSegment = seg;
  11604. tpi._primitive._updateTransparentSegmentIndices(seg);
  11605. return true;
  11606. };
  11607. // Free the existing TransparentSegments
  11608. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  11609. var ts = _a[_i];
  11610. ts.dispose(this.owner.engine);
  11611. }
  11612. rd._transparentSegments.splice(0);
  11613. var prevSeg = null;
  11614. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  11615. var tpi = rd._transparentPrimitives[tpiI];
  11616. // Check if the Data in which the primitive is stored is not sorted properly
  11617. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  11618. tpi._groupInstanceInfo.sortTransparentData();
  11619. }
  11620. // Reset the segment, we have to create/rebuild it
  11621. tpi._transparentSegment = null;
  11622. // If there's a previous valid segment, check if this prim can be part of it
  11623. if (prevSeg) {
  11624. checkAndAddPrimInSegment(prevSeg, tpiI);
  11625. }
  11626. // If we couldn't insert in the adjacent segments, he have to create one
  11627. if (!tpi._transparentSegment) {
  11628. var ts = new BABYLON.TransparentSegment();
  11629. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  11630. var prim = tpi._primitive;
  11631. ts.startZ = prim.actualZOffset;
  11632. prim._updateTransparentSegmentIndices(ts);
  11633. ts.endZ = ts.startZ;
  11634. tpi._transparentSegment = ts;
  11635. rd._transparentSegments.push(ts);
  11636. }
  11637. // Update prevSeg
  11638. prevSeg = tpi._transparentSegment;
  11639. }
  11640. //rd._firstChangedPrim = null;
  11641. rd._transparentListChanged = false;
  11642. };
  11643. Group2D.prototype._renderTransparentData = function () {
  11644. var failedCount = 0;
  11645. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  11646. var rd = this._renderableData;
  11647. var useInstanced = this.owner.supportInstancedArray;
  11648. var length = rd._transparentSegments.length;
  11649. for (var i = 0; i < length; i++) {
  11650. context.instancedBuffers = null;
  11651. var ts = rd._transparentSegments[i];
  11652. var gii = ts.groupInsanceInfo;
  11653. var mrc = gii.modelRenderCache;
  11654. var engine = this.owner.engine;
  11655. var count = ts.endDataIndex - ts.startDataIndex;
  11656. // Use Instanced Array if it's supported and if there's at least minPartCountToUseInstancedArray prims to draw.
  11657. // We don't want to create an Instanced Buffer for less that minPartCountToUseInstancedArray prims
  11658. if (useInstanced && count >= this.owner.minPartCountToUseInstancedArray) {
  11659. if (!ts.partBuffers) {
  11660. var buffers = new Array();
  11661. for (var j = 0; j < gii.transparentData.length; j++) {
  11662. var gitd = gii.transparentData[j];
  11663. var dfa = gitd._partData;
  11664. var data = dfa.pack();
  11665. var stride = dfa.stride;
  11666. var neededSize = count * stride * 4;
  11667. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  11668. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  11669. engine.updateArrayBuffer(segData);
  11670. buffers.push(buffer);
  11671. }
  11672. ts.partBuffers = buffers;
  11673. }
  11674. else if (gii.transparentDirty) {
  11675. for (var j = 0; j < gii.transparentData.length; j++) {
  11676. var gitd = gii.transparentData[j];
  11677. var dfa = gitd._partData;
  11678. var data = dfa.pack();
  11679. var stride = dfa.stride;
  11680. var buffer = ts.partBuffers[j];
  11681. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  11682. engine.bindArrayBuffer(buffer);
  11683. engine.updateArrayBuffer(segData);
  11684. }
  11685. }
  11686. context.useInstancing = true;
  11687. context.instancesCount = count;
  11688. context.instancedBuffers = ts.partBuffers;
  11689. context.groupInfoPartData = gii.transparentData;
  11690. var renderFailed = !mrc.render(gii, context);
  11691. failedCount += renderFailed ? 1 : 0;
  11692. }
  11693. else {
  11694. context.useInstancing = false;
  11695. context.partDataStartIndex = ts.startDataIndex;
  11696. context.partDataEndIndex = ts.endDataIndex;
  11697. context.groupInfoPartData = gii.transparentData;
  11698. var renderFailed = !mrc.render(gii, context);
  11699. failedCount += renderFailed ? 1 : 0;
  11700. }
  11701. }
  11702. return failedCount;
  11703. };
  11704. Group2D.prototype._prepareContext = function (engine, context, gii) {
  11705. var gipd = null;
  11706. var setDirty;
  11707. var getDirty;
  11708. // Render Mode specifics
  11709. switch (context.renderMode) {
  11710. case BABYLON.Render2DContext.RenderModeOpaque:
  11711. {
  11712. if (!gii.hasOpaqueData) {
  11713. return null;
  11714. }
  11715. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  11716. getDirty = function () { return gii.opaqueDirty; };
  11717. context.groupInfoPartData = gii.opaqueData;
  11718. gipd = gii.opaqueData;
  11719. break;
  11720. }
  11721. case BABYLON.Render2DContext.RenderModeAlphaTest:
  11722. {
  11723. if (!gii.hasAlphaTestData) {
  11724. return null;
  11725. }
  11726. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  11727. getDirty = function () { return gii.alphaTestDirty; };
  11728. context.groupInfoPartData = gii.alphaTestData;
  11729. gipd = gii.alphaTestData;
  11730. break;
  11731. }
  11732. default:
  11733. throw new Error("_prepareContext is only for opaque or alphaTest");
  11734. }
  11735. var renderCount = 0;
  11736. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  11737. // Skip it if instanced arrays are not supported
  11738. if (this.owner.supportInstancedArray) {
  11739. // Flag for instancing
  11740. context.useInstancing = true;
  11741. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  11742. for (var i = 0; i < gipd.length; i++) {
  11743. var pid = gipd[i];
  11744. // If the instances of the model was changed, pack the data
  11745. var array = pid._partData;
  11746. var instanceData_1 = array.pack();
  11747. renderCount += array.usedElementCount;
  11748. // Compute the size the instance buffer should have
  11749. var neededSize = array.usedElementCount * array.stride * 4;
  11750. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  11751. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  11752. if (pid._partBuffer) {
  11753. engine.deleteInstancesBuffer(pid._partBuffer);
  11754. }
  11755. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  11756. pid._partBufferSize = neededSize;
  11757. setDirty(false);
  11758. // Update the WebGL buffer to match the new content of the instances data
  11759. engine.updateArrayBuffer(instanceData_1);
  11760. }
  11761. else if (getDirty()) {
  11762. // Update the WebGL buffer to match the new content of the instances data
  11763. engine.bindArrayBuffer(pid._partBuffer);
  11764. engine.updateArrayBuffer(instanceData_1);
  11765. }
  11766. }
  11767. setDirty(false);
  11768. }
  11769. else {
  11770. context.partDataStartIndex = 0;
  11771. // Find the first valid object to get the count
  11772. if (context.groupInfoPartData.length > 0) {
  11773. var i = 0;
  11774. while (!context.groupInfoPartData[i]) {
  11775. i++;
  11776. }
  11777. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  11778. }
  11779. }
  11780. return renderCount;
  11781. };
  11782. Group2D.prototype._setRenderingScale = function (scale) {
  11783. if (this._renderableData._renderingScale === scale) {
  11784. return;
  11785. }
  11786. this._renderableData._renderingScale = scale;
  11787. };
  11788. Group2D.prototype._bindCacheTarget = function () {
  11789. var curWidth;
  11790. var curHeight;
  11791. var rd = this._renderableData;
  11792. var rs = rd._renderingScale;
  11793. var noResizeScale = rd._noResizeOnScale;
  11794. var isCanvas = this.parent == null;
  11795. var scale;
  11796. if (noResizeScale) {
  11797. scale = isCanvas ? Group2D_1._uV : this.parent.actualScale;
  11798. }
  11799. else {
  11800. scale = this.actualScale;
  11801. }
  11802. if (isCanvas && this.owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS && this.owner.isScreenSpace) {
  11803. if (this.owner.designSize || this.owner.fitRenderingDevice) {
  11804. Group2D_1._s.width = this.owner.engine.getRenderWidth();
  11805. Group2D_1._s.height = this.owner.engine.getRenderHeight();
  11806. }
  11807. else {
  11808. Group2D_1._s.copyFrom(this.owner.size);
  11809. }
  11810. }
  11811. else {
  11812. Group2D_1._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  11813. Group2D_1._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  11814. }
  11815. var sizeChanged = !Group2D_1._s.equals(rd._cacheSize);
  11816. if (rd._cacheNode) {
  11817. var size = rd._cacheNode.contentSize;
  11818. // Check if we have to deallocate because the size is too small
  11819. if ((size.width < Group2D_1._s.width) || (size.height < Group2D_1._s.height)) {
  11820. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  11821. // For World space: no over-provisioning
  11822. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  11823. curWidth = Math.floor(Group2D_1._s.width * overprovisioning);
  11824. curHeight = Math.floor(Group2D_1._s.height * overprovisioning);
  11825. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  11826. rd._cacheTexture.freeRect(rd._cacheNode);
  11827. rd._cacheNode = null;
  11828. }
  11829. }
  11830. if (!rd._cacheNode) {
  11831. // Check if we have to allocate a rendering zone in the global cache texture
  11832. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  11833. rd._cacheNode = res.node;
  11834. rd._cacheTexture = res.texture;
  11835. if (rd._cacheRenderSprite) {
  11836. rd._cacheRenderSprite.dispose();
  11837. }
  11838. rd._cacheRenderSprite = res.sprite;
  11839. sizeChanged = true;
  11840. }
  11841. if (sizeChanged) {
  11842. rd._cacheSize.copyFrom(Group2D_1._s);
  11843. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  11844. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  11845. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  11846. }
  11847. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  11848. }
  11849. var n = rd._cacheNode;
  11850. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D_1._s, true);
  11851. };
  11852. Group2D.prototype._unbindCacheTarget = function () {
  11853. if (this._renderableData._cacheTexture) {
  11854. this._renderableData._cacheTexture.unbindTexture();
  11855. }
  11856. };
  11857. Group2D.prototype._spreadActualScaleDirty = function () {
  11858. if (this._renderableData && this._renderableData._cacheRenderSprite) {
  11859. this.handleGroupChanged(BABYLON.Prim2DBase.actualScaleProperty);
  11860. }
  11861. _super.prototype._spreadActualScaleDirty.call(this);
  11862. };
  11863. Group2D.prototype.handleGroupChanged = function (prop) {
  11864. // This method is only for cachedGroup
  11865. var rd = this._renderableData;
  11866. if (!rd) {
  11867. return;
  11868. }
  11869. var cachedSprite = rd._cacheRenderSprite;
  11870. if (!this.isCachedGroup || !cachedSprite) {
  11871. return;
  11872. }
  11873. // For now we only support these property changes
  11874. // TODO: add more! :)
  11875. switch (prop.id) {
  11876. case BABYLON.Prim2DBase.actualPositionProperty.id:
  11877. cachedSprite.actualPosition = this.actualPosition.clone();
  11878. if (cachedSprite.position != null) {
  11879. cachedSprite.position = cachedSprite.actualPosition.clone();
  11880. }
  11881. break;
  11882. case BABYLON.Prim2DBase.rotationProperty.id:
  11883. cachedSprite.rotation = this.rotation;
  11884. break;
  11885. case BABYLON.Prim2DBase.scaleProperty.id:
  11886. cachedSprite.scale = this.scale;
  11887. break;
  11888. case BABYLON.Prim2DBase.originProperty.id:
  11889. cachedSprite.origin = this.origin.clone();
  11890. break;
  11891. case Group2D_1.actualSizeProperty.id:
  11892. cachedSprite.size = this.actualSize.clone();
  11893. break;
  11894. }
  11895. };
  11896. Group2D.prototype.detectGroupStates = function () {
  11897. var isCanvas = this instanceof BABYLON.Canvas2D;
  11898. var canvasStrat = this.owner.cachingStrategy;
  11899. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  11900. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  11901. this._isRenderableGroup = isCanvas;
  11902. this._isCachedGroup = false;
  11903. }
  11904. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  11905. if (isCanvas) {
  11906. this._isRenderableGroup = true;
  11907. this._isCachedGroup = true;
  11908. }
  11909. else {
  11910. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  11911. this._isCachedGroup = false;
  11912. }
  11913. }
  11914. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  11915. if (isCanvas) {
  11916. this._isRenderableGroup = true;
  11917. this._isCachedGroup = false;
  11918. }
  11919. else {
  11920. if (this.hierarchyDepth === 1) {
  11921. this._isRenderableGroup = true;
  11922. this._isCachedGroup = true;
  11923. }
  11924. else {
  11925. this._isRenderableGroup = false;
  11926. this._isCachedGroup = false;
  11927. }
  11928. }
  11929. }
  11930. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  11931. if (isCanvas) {
  11932. this._isRenderableGroup = true;
  11933. this._isCachedGroup = false;
  11934. }
  11935. else {
  11936. var gcb = this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_OPTIONMASK;
  11937. if ((gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D_1.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  11938. this._isRenderableGroup = gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  11939. this._isCachedGroup = false;
  11940. }
  11941. if (gcb === Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  11942. this._isRenderableGroup = true;
  11943. this._isCachedGroup = true;
  11944. }
  11945. }
  11946. }
  11947. if (this._isRenderableGroup) {
  11948. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  11949. if (!this._renderableData) {
  11950. this._renderableData = new RenderableGroupData();
  11951. }
  11952. }
  11953. // If the group is tagged as renderable we add it to the renderable tree
  11954. if (this._isCachedGroup) {
  11955. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  11956. var cur = this.parent;
  11957. while (cur) {
  11958. if (cur instanceof Group2D_1 && cur._isRenderableGroup) {
  11959. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  11960. cur._renderableData._childrenRenderableGroups.push(this);
  11961. }
  11962. break;
  11963. }
  11964. cur = cur.parent;
  11965. }
  11966. }
  11967. };
  11968. Object.defineProperty(Group2D.prototype, "_cachedTexture", {
  11969. get: function () {
  11970. if (this._renderableData) {
  11971. return this._renderableData._cacheTexture;
  11972. }
  11973. return null;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. return Group2D;
  11979. }(BABYLON.Prim2DBase));
  11980. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  11981. /**
  11982. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  11983. */
  11984. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  11985. /**
  11986. * When used, this group's content won't be cached, no matter which strategy used.
  11987. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  11988. */
  11989. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  11990. /**
  11991. * When used, the group's content will be cached in the nearest cached parent group/canvas
  11992. */
  11993. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  11994. /**
  11995. * You can specify this behavior to any cached Group2D to indicate that you don't want the cached content to be resized when the Group's actualScale is changing. It will draw the content stretched or shrink which is faster than a resize. This setting is obviously for performance consideration, don't use it if you want the best rendering quality
  11996. */
  11997. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  11998. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  11999. Group2D._uV = new BABYLON.Vector2(1, 1);
  12000. Group2D._s = BABYLON.Size.Zero();
  12001. Group2D._unS = new BABYLON.Vector2(1, 1);
  12002. __decorate([
  12003. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D_1.sizeProperty = pi; }, false, true)
  12004. ], Group2D.prototype, "size", null);
  12005. Group2D = Group2D_1 = __decorate([
  12006. BABYLON.className("Group2D", "BABYLON")
  12007. ], Group2D);
  12008. BABYLON.Group2D = Group2D;
  12009. var RenderableGroupData = (function () {
  12010. function RenderableGroupData() {
  12011. this._primDirtyList = new Array();
  12012. this._primNewDirtyList = new Array();
  12013. this._childrenRenderableGroups = new Array();
  12014. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  12015. this._transparentPrimitives = new Array();
  12016. this._transparentSegments = new Array();
  12017. this._transparentListChanged = false;
  12018. this._cacheNode = null;
  12019. this._cacheTexture = null;
  12020. this._cacheRenderSprite = null;
  12021. this._renderingScale = 1;
  12022. this._cacheNodeUVs = null;
  12023. this._cacheNodeUVsChangedObservable = null;
  12024. this._cacheSize = BABYLON.Size.Zero();
  12025. this._useMipMap = false;
  12026. this._anisotropicLevel = 1;
  12027. this._noResizeOnScale = false;
  12028. }
  12029. RenderableGroupData.prototype.dispose = function (owner) {
  12030. var engine = owner.engine;
  12031. if (this._cacheRenderSprite) {
  12032. this._cacheRenderSprite.dispose();
  12033. this._cacheRenderSprite = null;
  12034. }
  12035. if (this._cacheTexture && this._cacheNode) {
  12036. this._cacheTexture.freeRect(this._cacheNode);
  12037. this._cacheTexture = null;
  12038. this._cacheNode = null;
  12039. }
  12040. if (this._primDirtyList) {
  12041. this._primDirtyList.splice(0);
  12042. this._primDirtyList = null;
  12043. }
  12044. if (this._renderGroupInstancesInfo) {
  12045. this._renderGroupInstancesInfo.forEach(function (k, v) {
  12046. v.dispose();
  12047. });
  12048. this._renderGroupInstancesInfo = null;
  12049. }
  12050. if (this._cacheNodeUVsChangedObservable) {
  12051. this._cacheNodeUVsChangedObservable.clear();
  12052. this._cacheNodeUVsChangedObservable = null;
  12053. }
  12054. if (this._transparentSegments) {
  12055. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  12056. var ts = _a[_i];
  12057. ts.dispose(engine);
  12058. }
  12059. this._transparentSegments.splice(0);
  12060. this._transparentSegments = null;
  12061. }
  12062. };
  12063. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  12064. var tpi = new TransparentPrimitiveInfo();
  12065. tpi._primitive = prim;
  12066. tpi._groupInstanceInfo = gii;
  12067. tpi._transparentSegment = null;
  12068. this._transparentPrimitives.push(tpi);
  12069. this._transparentListChanged = true;
  12070. return tpi;
  12071. };
  12072. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  12073. var index = this._transparentPrimitives.indexOf(tpi);
  12074. if (index !== -1) {
  12075. this._transparentPrimitives.splice(index, 1);
  12076. this._transparentListChanged = true;
  12077. }
  12078. };
  12079. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  12080. this._transparentListChanged = true;
  12081. //this.updateSmallestZChangedPrim(tpi);
  12082. };
  12083. return RenderableGroupData;
  12084. }());
  12085. BABYLON.RenderableGroupData = RenderableGroupData;
  12086. var TransparentPrimitiveInfo = (function () {
  12087. function TransparentPrimitiveInfo() {
  12088. }
  12089. return TransparentPrimitiveInfo;
  12090. }());
  12091. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  12092. var Group2D_1;
  12093. })(BABYLON || (BABYLON = {}));
  12094. //# sourceMappingURL=babylon.group2d.js.map
  12095. var __extends = (this && this.__extends) || function (d, b) {
  12096. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12097. function __() { this.constructor = d; }
  12098. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12099. };
  12100. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12101. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12102. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12103. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  12104. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12105. };
  12106. var BABYLON;
  12107. (function (BABYLON) {
  12108. var WireFrame2DRenderCache = (function (_super) {
  12109. __extends(WireFrame2DRenderCache, _super);
  12110. function WireFrame2DRenderCache() {
  12111. var _this = _super.apply(this, arguments) || this;
  12112. _this.effectsReady = false;
  12113. _this.vb = null;
  12114. _this.vtxCount = 0;
  12115. _this.instancingAttributes = null;
  12116. _this.effect = null;
  12117. _this.effectInstanced = null;
  12118. return _this;
  12119. }
  12120. WireFrame2DRenderCache.prototype.render = function (instanceInfo, context) {
  12121. // Do nothing if the shader is still loading/preparing
  12122. if (!this.effectsReady) {
  12123. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  12124. return false;
  12125. }
  12126. this.effectsReady = true;
  12127. }
  12128. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  12129. var canvas = instanceInfo.owner.owner;
  12130. var engine = canvas.engine;
  12131. var cur = engine.getAlphaMode();
  12132. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  12133. engine.enableEffect(effect);
  12134. engine.bindBuffersDirectly(this.vb, null, [2, 4], 24, effect);
  12135. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12136. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12137. }
  12138. var pid = context.groupInfoPartData[0];
  12139. if (context.useInstancing) {
  12140. if (!this.instancingAttributes) {
  12141. this.instancingAttributes = this.loadInstancingAttributes(WireFrame2D.WIREFRAME2D_MAINPARTID, effect);
  12142. }
  12143. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  12144. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12145. canvas._addDrawCallCount(1, context.renderMode);
  12146. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  12147. engine.drawUnIndexed(false, 0, this.vtxCount, count);
  12148. // engine.draw(true, 0, 6, count);
  12149. engine.unbindInstanceAttributes();
  12150. }
  12151. else {
  12152. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12153. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12154. this.setupUniforms(effect, 0, pid._partData, i);
  12155. engine.drawUnIndexed(false, 0, this.vtxCount);
  12156. }
  12157. }
  12158. engine.setAlphaMode(cur, true);
  12159. return true;
  12160. };
  12161. WireFrame2DRenderCache.prototype.updateModelRenderCache = function (prim) {
  12162. var w = prim;
  12163. w._updateVertexBuffer(this);
  12164. return true;
  12165. };
  12166. WireFrame2DRenderCache.prototype.dispose = function () {
  12167. if (!_super.prototype.dispose.call(this)) {
  12168. return false;
  12169. }
  12170. if (this.vb) {
  12171. this._engine._releaseBuffer(this.vb);
  12172. this.vb = null;
  12173. }
  12174. this.effect = null;
  12175. this.effectInstanced = null;
  12176. return true;
  12177. };
  12178. return WireFrame2DRenderCache;
  12179. }(BABYLON.ModelRenderCache));
  12180. BABYLON.WireFrame2DRenderCache = WireFrame2DRenderCache;
  12181. var WireFrameVertex2D = (function () {
  12182. function WireFrameVertex2D(p, c) {
  12183. if (c === void 0) { c = null; }
  12184. this.fromVector2(p);
  12185. if (c != null) {
  12186. this.fromColor4(c);
  12187. }
  12188. else {
  12189. this.r = this.g = this.b = this.a = 1;
  12190. }
  12191. }
  12192. WireFrameVertex2D.prototype.fromVector2 = function (p) {
  12193. this.x = p.x;
  12194. this.y = p.y;
  12195. };
  12196. WireFrameVertex2D.prototype.fromColor3 = function (c) {
  12197. this.r = c.r;
  12198. this.g = c.g;
  12199. this.b = c.b;
  12200. this.a = 1;
  12201. };
  12202. WireFrameVertex2D.prototype.fromColor4 = function (c) {
  12203. this.r = c.r;
  12204. this.g = c.g;
  12205. this.b = c.b;
  12206. this.a = c.a;
  12207. };
  12208. return WireFrameVertex2D;
  12209. }());
  12210. WireFrameVertex2D = __decorate([
  12211. BABYLON.className("WireFrameVertex2D", "BABYLON")
  12212. ], WireFrameVertex2D);
  12213. BABYLON.WireFrameVertex2D = WireFrameVertex2D;
  12214. var WireFrameGroup2D = (function () {
  12215. /**
  12216. * Construct a WireFrameGroup2D object
  12217. * @param id a unique ID among the Groups added to a given WireFrame2D primitive, if you don't specify an id, a random one will be generated. The id is immutable.
  12218. * @param defaultColor specify the default color that will be used when a vertex is pushed, white will be used if not specified.
  12219. */
  12220. function WireFrameGroup2D(id, defaultColor) {
  12221. if (id === void 0) { id = null; }
  12222. if (defaultColor === void 0) { defaultColor = null; }
  12223. this._id = (id == null) ? BABYLON.Tools.RandomId() : id;
  12224. this._uid = BABYLON.Tools.RandomId();
  12225. this._defaultColor = (defaultColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : defaultColor;
  12226. this._buildingStrip = false;
  12227. this._vertices = new Array();
  12228. }
  12229. Object.defineProperty(WireFrameGroup2D.prototype, "uid", {
  12230. get: function () {
  12231. return this._uid;
  12232. },
  12233. enumerable: true,
  12234. configurable: true
  12235. });
  12236. Object.defineProperty(WireFrameGroup2D.prototype, "id", {
  12237. /**
  12238. * Retrieve the ID of the group
  12239. */
  12240. get: function () {
  12241. return this._id;
  12242. },
  12243. enumerable: true,
  12244. configurable: true
  12245. });
  12246. /**
  12247. * Push a vertex in the array of vertices.
  12248. * If you're previously called startLineStrip, the vertex will be pushed twice in order to describe the end of a line and the start of a new one.
  12249. * @param p Position of the vertex
  12250. * @param c Color of the vertex, if null the default color of the group will be used
  12251. */
  12252. WireFrameGroup2D.prototype.pushVertex = function (p, c) {
  12253. if (c === void 0) { c = null; }
  12254. var v = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  12255. this._vertices.push(v);
  12256. if (this._buildingStrip) {
  12257. var v2 = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  12258. this._vertices.push(v2);
  12259. }
  12260. };
  12261. /**
  12262. * Start to store a Line Strip. The given vertex will be pushed in the array. The you have to call pushVertex to add subsequent vertices describing the strip and don't forget to call endLineStrip to close the strip!!!
  12263. * @param p Position of the vertex
  12264. * @param c Color of the vertex, if null the default color of the group will be used
  12265. */
  12266. WireFrameGroup2D.prototype.startLineStrip = function (p, c) {
  12267. if (c === void 0) { c = null; }
  12268. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  12269. this._buildingStrip = true;
  12270. };
  12271. /**
  12272. * Close the Strip by storing a last vertex
  12273. * @param p Position of the vertex
  12274. * @param c Color of the vertex, if null the default color of the group will be used
  12275. */
  12276. WireFrameGroup2D.prototype.endLineStrip = function (p, c) {
  12277. if (c === void 0) { c = null; }
  12278. this._buildingStrip = false;
  12279. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  12280. };
  12281. Object.defineProperty(WireFrameGroup2D.prototype, "vertices", {
  12282. /**
  12283. * Access to the array of Vertices, you can manipulate its content but BEWARE of what you're doing!
  12284. */
  12285. get: function () {
  12286. return this._vertices;
  12287. },
  12288. enumerable: true,
  12289. configurable: true
  12290. });
  12291. return WireFrameGroup2D;
  12292. }());
  12293. WireFrameGroup2D = __decorate([
  12294. BABYLON.className("WireFrameGroup2D", "BABYLON")
  12295. ], WireFrameGroup2D);
  12296. BABYLON.WireFrameGroup2D = WireFrameGroup2D;
  12297. var WireFrame2D = WireFrame2D_1 = (function (_super) {
  12298. __extends(WireFrame2D, _super);
  12299. /**
  12300. * Create an WireFrame 2D primitive
  12301. * @param wireFrameGroups an array of WireFrameGroup.
  12302. * @param settings a combination of settings, possible ones are
  12303. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  12304. * - children: an array of direct children
  12305. * - id a text identifier, for information purpose
  12306. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  12307. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12308. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12309. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  12310. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12311. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12312. * - zOrder: override the zOrder with the specified value
  12313. * - origin: define the normalized origin point location, default [0.5;0.5]
  12314. * - alignToPixel: the rendered lines will be aligned to the rendering device' pixels
  12315. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  12316. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  12317. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  12318. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  12319. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  12320. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  12321. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12322. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12323. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12324. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12325. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12326. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12327. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12328. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12329. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12330. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12331. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12332. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12333. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12334. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12335. */
  12336. function WireFrame2D(wireFrameGroups, settings) {
  12337. var _this;
  12338. if (!settings) {
  12339. settings = {};
  12340. }
  12341. _this = _super.call(this, settings) || this;
  12342. _this._wireFrameGroups = new BABYLON.StringDictionary();
  12343. for (var _i = 0, wireFrameGroups_1 = wireFrameGroups; _i < wireFrameGroups_1.length; _i++) {
  12344. var wfg = wireFrameGroups_1[_i];
  12345. _this._wireFrameGroups.add(wfg.id, wfg);
  12346. }
  12347. _this._vtxTransparent = false;
  12348. if (settings.size != null) {
  12349. _this.size = settings.size;
  12350. }
  12351. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  12352. return _this;
  12353. }
  12354. Object.defineProperty(WireFrame2D.prototype, "wireFrameGroups", {
  12355. get: function () {
  12356. return this._wireFrameGroups;
  12357. },
  12358. enumerable: true,
  12359. configurable: true
  12360. });
  12361. /**
  12362. * If you change the content of the wireFrameGroups you MUST call this method for the changes to be reflected during rendering
  12363. */
  12364. WireFrame2D.prototype.wireFrameGroupsDirty = function () {
  12365. this._setFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  12366. this.onPrimBecomesDirty();
  12367. };
  12368. Object.defineProperty(WireFrame2D.prototype, "size", {
  12369. get: function () {
  12370. if (this._size == null) {
  12371. this._computeMinMaxTrans();
  12372. }
  12373. return this._size;
  12374. },
  12375. set: function (value) {
  12376. this.internalSetSize(value);
  12377. },
  12378. enumerable: true,
  12379. configurable: true
  12380. });
  12381. WireFrame2D.prototype.updateLevelBoundingInfo = function () {
  12382. var v = this._computeMinMaxTrans();
  12383. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(v.x, v.z, v.y, v.w, this._levelBoundingInfo);
  12384. return true;
  12385. };
  12386. WireFrame2D.prototype.levelIntersect = function (intersectInfo) {
  12387. // TODO !
  12388. return true;
  12389. };
  12390. Object.defineProperty(WireFrame2D.prototype, "alignToPixel", {
  12391. /**
  12392. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  12393. */
  12394. get: function () {
  12395. return this._alignToPixel;
  12396. },
  12397. set: function (value) {
  12398. this._alignToPixel = value;
  12399. },
  12400. enumerable: true,
  12401. configurable: true
  12402. });
  12403. WireFrame2D.prototype.createModelRenderCache = function (modelKey) {
  12404. var renderCache = new WireFrame2DRenderCache(this.owner.engine, modelKey);
  12405. return renderCache;
  12406. };
  12407. WireFrame2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  12408. var renderCache = modelRenderCache;
  12409. var engine = this.owner.engine;
  12410. // Create the VertexBuffer
  12411. this._updateVertexBuffer(renderCache);
  12412. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  12413. var ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], true);
  12414. if (ei) {
  12415. renderCache.effectInstanced = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12416. }
  12417. ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], false);
  12418. renderCache.effect = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12419. return renderCache;
  12420. };
  12421. WireFrame2D.prototype._updateVertexBuffer = function (mrc) {
  12422. var engine = this.owner.engine;
  12423. if (mrc.vb != null) {
  12424. engine._releaseBuffer(mrc.vb);
  12425. }
  12426. var vtxCount = 0;
  12427. this._wireFrameGroups.forEach(function (k, v) { return vtxCount += v.vertices.length; });
  12428. var vb = new Float32Array(vtxCount * 6);
  12429. var i = 0;
  12430. this._wireFrameGroups.forEach(function (k, v) {
  12431. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  12432. var vtx = _a[_i];
  12433. vb[i++] = vtx.x;
  12434. vb[i++] = vtx.y;
  12435. vb[i++] = vtx.r;
  12436. vb[i++] = vtx.g;
  12437. vb[i++] = vtx.b;
  12438. vb[i++] = vtx.a;
  12439. }
  12440. });
  12441. mrc.vb = engine.createVertexBuffer(vb);
  12442. mrc.vtxCount = vtxCount;
  12443. };
  12444. WireFrame2D.prototype.refreshInstanceDataPart = function (part) {
  12445. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  12446. return false;
  12447. }
  12448. if (part.id === WireFrame2D_1.WIREFRAME2D_MAINPARTID) {
  12449. var d = this._instanceDataParts[0];
  12450. d.properties = new BABYLON.Vector3(this.alignToPixel ? 1 : 0, 2 / this.renderGroup.actualWidth, 2 / this.renderGroup.actualHeight);
  12451. }
  12452. return true;
  12453. };
  12454. WireFrame2D.prototype._computeMinMaxTrans = function () {
  12455. var xmin = Number.MAX_VALUE;
  12456. var xmax = Number.MIN_VALUE;
  12457. var ymin = Number.MAX_VALUE;
  12458. var ymax = Number.MIN_VALUE;
  12459. var transparent = false;
  12460. this._wireFrameGroups.forEach(function (k, v) {
  12461. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  12462. var vtx = _a[_i];
  12463. xmin = Math.min(xmin, vtx.x);
  12464. xmax = Math.max(xmax, vtx.x);
  12465. ymin = Math.min(ymin, vtx.y);
  12466. ymax = Math.max(ymax, vtx.y);
  12467. if (vtx.a < 1) {
  12468. transparent = true;
  12469. }
  12470. }
  12471. });
  12472. this._vtxTransparent = transparent;
  12473. this._size = new BABYLON.Size(xmax - xmin, ymax - ymin);
  12474. return new BABYLON.Vector4(xmin, ymin, xmax, ymax);
  12475. };
  12476. WireFrame2D.prototype.createInstanceDataParts = function () {
  12477. return [new WireFrame2DInstanceData(WireFrame2D_1.WIREFRAME2D_MAINPARTID)];
  12478. };
  12479. return WireFrame2D;
  12480. }(BABYLON.RenderablePrim2D));
  12481. WireFrame2D.WIREFRAME2D_MAINPARTID = 1;
  12482. __decorate([
  12483. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return WireFrame2D_1.wireFrameGroupsProperty = pi; })
  12484. ], WireFrame2D.prototype, "wireFrameGroups", null);
  12485. WireFrame2D = WireFrame2D_1 = __decorate([
  12486. BABYLON.className("WireFrame2D", "BABYLON")
  12487. ], WireFrame2D);
  12488. BABYLON.WireFrame2D = WireFrame2D;
  12489. var WireFrame2DInstanceData = (function (_super) {
  12490. __extends(WireFrame2DInstanceData, _super);
  12491. function WireFrame2DInstanceData(partId) {
  12492. return _super.call(this, partId, 1) || this;
  12493. }
  12494. Object.defineProperty(WireFrame2DInstanceData.prototype, "properties", {
  12495. // the properties is for now the alignedToPixel value
  12496. get: function () {
  12497. return null;
  12498. },
  12499. set: function (value) {
  12500. },
  12501. enumerable: true,
  12502. configurable: true
  12503. });
  12504. return WireFrame2DInstanceData;
  12505. }(BABYLON.InstanceDataBase));
  12506. __decorate([
  12507. BABYLON.instanceData()
  12508. ], WireFrame2DInstanceData.prototype, "properties", null);
  12509. BABYLON.WireFrame2DInstanceData = WireFrame2DInstanceData;
  12510. var WireFrame2D_1;
  12511. })(BABYLON || (BABYLON = {}));
  12512. //# sourceMappingURL=babylon.wireFrame2d.js.map
  12513. var __extends = (this && this.__extends) || function (d, b) {
  12514. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12515. function __() { this.constructor = d; }
  12516. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12517. };
  12518. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12519. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12520. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12521. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  12522. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12523. };
  12524. var BABYLON;
  12525. (function (BABYLON) {
  12526. var Rectangle2DRenderCache = (function (_super) {
  12527. __extends(Rectangle2DRenderCache, _super);
  12528. function Rectangle2DRenderCache(engine, modelKey) {
  12529. var _this = _super.call(this, engine, modelKey) || this;
  12530. _this.effectsReady = false;
  12531. _this.fillVB = null;
  12532. _this.fillIB = null;
  12533. _this.fillIndicesCount = 0;
  12534. _this.instancingFillAttributes = null;
  12535. _this.effectFill = null;
  12536. _this.effectFillInstanced = null;
  12537. _this.borderVB = null;
  12538. _this.borderIB = null;
  12539. _this.borderIndicesCount = 0;
  12540. _this.instancingBorderAttributes = null;
  12541. _this.effectBorder = null;
  12542. _this.effectBorderInstanced = null;
  12543. return _this;
  12544. }
  12545. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  12546. // Do nothing if the shader is still loading/preparing
  12547. if (!this.effectsReady) {
  12548. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  12549. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  12550. return false;
  12551. }
  12552. this.effectsReady = true;
  12553. }
  12554. var canvas = instanceInfo.owner.owner;
  12555. var engine = canvas.engine;
  12556. var depthFunction = 0;
  12557. if (this.effectFill && this.effectBorder) {
  12558. depthFunction = engine.getDepthFunction();
  12559. engine.setDepthFunctionToLessOrEqual();
  12560. }
  12561. var curAlphaMode = engine.getAlphaMode();
  12562. if (this.effectFill) {
  12563. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  12564. var pid = context.groupInfoPartData[partIndex];
  12565. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12566. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12567. }
  12568. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  12569. engine.enableEffect(effect);
  12570. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  12571. if (context.useInstancing) {
  12572. if (!this.instancingFillAttributes) {
  12573. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  12574. }
  12575. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  12576. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12577. canvas._addDrawCallCount(1, context.renderMode);
  12578. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  12579. engine.draw(true, 0, this.fillIndicesCount, count);
  12580. engine.unbindInstanceAttributes();
  12581. }
  12582. else {
  12583. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12584. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12585. this.setupUniforms(effect, partIndex, pid._partData, i);
  12586. engine.draw(true, 0, this.fillIndicesCount);
  12587. }
  12588. }
  12589. }
  12590. if (this.effectBorder) {
  12591. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  12592. var pid = context.groupInfoPartData[partIndex];
  12593. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12594. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12595. }
  12596. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  12597. engine.enableEffect(effect);
  12598. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  12599. if (context.useInstancing) {
  12600. if (!this.instancingBorderAttributes) {
  12601. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  12602. }
  12603. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  12604. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12605. canvas._addDrawCallCount(1, context.renderMode);
  12606. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  12607. engine.draw(true, 0, this.borderIndicesCount, count);
  12608. engine.unbindInstanceAttributes();
  12609. }
  12610. else {
  12611. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12612. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12613. this.setupUniforms(effect, partIndex, pid._partData, i);
  12614. engine.draw(true, 0, this.borderIndicesCount);
  12615. }
  12616. }
  12617. }
  12618. engine.setAlphaMode(curAlphaMode, true);
  12619. if (this.effectFill && this.effectBorder) {
  12620. engine.setDepthFunction(depthFunction);
  12621. }
  12622. return true;
  12623. };
  12624. Rectangle2DRenderCache.prototype.dispose = function () {
  12625. if (!_super.prototype.dispose.call(this)) {
  12626. return false;
  12627. }
  12628. if (this.fillVB) {
  12629. this._engine._releaseBuffer(this.fillVB);
  12630. this.fillVB = null;
  12631. }
  12632. if (this.fillIB) {
  12633. this._engine._releaseBuffer(this.fillIB);
  12634. this.fillIB = null;
  12635. }
  12636. this.effectFill = null;
  12637. this.effectFillInstanced = null;
  12638. this.effectBorder = null;
  12639. this.effectBorderInstanced = null;
  12640. if (this.borderVB) {
  12641. this._engine._releaseBuffer(this.borderVB);
  12642. this.borderVB = null;
  12643. }
  12644. if (this.borderIB) {
  12645. this._engine._releaseBuffer(this.borderIB);
  12646. this.borderIB = null;
  12647. }
  12648. return true;
  12649. };
  12650. return Rectangle2DRenderCache;
  12651. }(BABYLON.ModelRenderCache));
  12652. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  12653. var Rectangle2DInstanceData = (function (_super) {
  12654. __extends(Rectangle2DInstanceData, _super);
  12655. function Rectangle2DInstanceData(partId) {
  12656. return _super.call(this, partId, 1) || this;
  12657. }
  12658. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  12659. get: function () {
  12660. return null;
  12661. },
  12662. set: function (value) {
  12663. },
  12664. enumerable: true,
  12665. configurable: true
  12666. });
  12667. return Rectangle2DInstanceData;
  12668. }(BABYLON.Shape2DInstanceData));
  12669. __decorate([
  12670. BABYLON.instanceData()
  12671. ], Rectangle2DInstanceData.prototype, "properties", null);
  12672. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  12673. var Rectangle2D = Rectangle2D_1 = (function (_super) {
  12674. __extends(Rectangle2D, _super);
  12675. /**
  12676. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  12677. * @param settings a combination of settings, possible ones are
  12678. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  12679. * - children: an array of direct children
  12680. * - id a text identifier, for information purpose
  12681. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  12682. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12683. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12684. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12685. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12686. * - zOrder: override the zOrder with the specified value
  12687. * - origin: define the normalized origin point location, default [0.5;0.5]
  12688. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  12689. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  12690. * - fill: the brush used to draw the fill content of the rectangle, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  12691. * - border: the brush used to draw the border of the rectangle, you can set null to draw nothing (but you will have to set a fill brush), default is null. can also be a string value (see Canvas2D.GetBrushFromString)
  12692. * - borderThickness: the thickness of the drawn border, default is 1.
  12693. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  12694. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  12695. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  12696. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  12697. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  12698. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  12699. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12700. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12701. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12702. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12703. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12704. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12705. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12706. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12707. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12708. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12709. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12710. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12711. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12712. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12713. */
  12714. function Rectangle2D(settings) {
  12715. var _this;
  12716. // Avoid checking every time if the object exists
  12717. if (settings == null) {
  12718. settings = {};
  12719. }
  12720. _this = _super.call(this, settings) || this;
  12721. if (settings.size != null) {
  12722. _this.size = settings.size;
  12723. }
  12724. else if (settings.width || settings.height) {
  12725. var size = new BABYLON.Size(settings.width, settings.height);
  12726. _this.size = size;
  12727. }
  12728. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  12729. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  12730. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  12731. //this.size = size;
  12732. _this.roundRadius = roundRadius;
  12733. _this.borderThickness = borderThickness;
  12734. return _this;
  12735. }
  12736. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  12737. get: function () {
  12738. return this._notRounded;
  12739. },
  12740. set: function (value) {
  12741. this._notRounded = value;
  12742. },
  12743. enumerable: true,
  12744. configurable: true
  12745. });
  12746. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  12747. get: function () {
  12748. return this._roundRadius;
  12749. },
  12750. set: function (value) {
  12751. this._roundRadius = value;
  12752. this.notRounded = value === 0;
  12753. this._positioningDirty();
  12754. },
  12755. enumerable: true,
  12756. configurable: true
  12757. });
  12758. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  12759. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  12760. if (this.notRounded) {
  12761. return true;
  12762. }
  12763. // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
  12764. // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
  12765. // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
  12766. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  12767. var size = this.size;
  12768. Rectangle2D_1._i0.x = intersectInfo._localPickPosition.x;
  12769. Rectangle2D_1._i0.y = intersectInfo._localPickPosition.y;
  12770. var rr = this.roundRadius;
  12771. var rrs = rr * rr;
  12772. // Check if the point is in the bottom/left quarter area
  12773. Rectangle2D_1._i1.x = rr;
  12774. Rectangle2D_1._i1.y = rr;
  12775. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  12776. // Compute the intersection point in the quarter local space
  12777. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  12778. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  12779. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  12780. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  12781. }
  12782. // Check if the point is in the top/left quarter area
  12783. Rectangle2D_1._i1.x = rr;
  12784. Rectangle2D_1._i1.y = size.height - rr;
  12785. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  12786. // Compute the intersection point in the quarter local space
  12787. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  12788. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  12789. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  12790. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  12791. }
  12792. // Check if the point is in the top/right quarter area
  12793. Rectangle2D_1._i1.x = size.width - rr;
  12794. Rectangle2D_1._i1.y = size.height - rr;
  12795. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  12796. // Compute the intersection point in the quarter local space
  12797. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  12798. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  12799. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  12800. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  12801. }
  12802. // Check if the point is in the bottom/right quarter area
  12803. Rectangle2D_1._i1.x = size.width - rr;
  12804. Rectangle2D_1._i1.y = rr;
  12805. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  12806. // Compute the intersection point in the quarter local space
  12807. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  12808. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  12809. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  12810. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  12811. }
  12812. // At any other locations the point is guarantied to be inside
  12813. return true;
  12814. };
  12815. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  12816. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  12817. return true;
  12818. };
  12819. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  12820. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  12821. return renderCache;
  12822. };
  12823. Rectangle2D.prototype.updateTriArray = function () {
  12824. // Not Rounded = sharp edge rect, the default implementation is the right one!
  12825. if (this.notRounded) {
  12826. _super.prototype.updateTriArray.call(this);
  12827. return;
  12828. }
  12829. // Rounded Corner? It's more complicated! :)
  12830. var subDiv = Rectangle2D_1.roundSubdivisions * 4;
  12831. if (this._primTriArray == null) {
  12832. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  12833. }
  12834. else {
  12835. this._primTriArray.clear(subDiv);
  12836. }
  12837. var size = this.actualSize;
  12838. var w = size.width;
  12839. var h = size.height;
  12840. var r = this.roundRadius;
  12841. var rsub0 = subDiv * 0.25;
  12842. var rsub1 = subDiv * 0.50;
  12843. var rsub2 = subDiv * 0.75;
  12844. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  12845. var twopi = Math.PI * 2;
  12846. var nru = r / w;
  12847. var nrv = r / h;
  12848. var computePos = function (index, p) {
  12849. // right/bottom
  12850. if (index < rsub0) {
  12851. p.x = 1.0 - nru;
  12852. p.y = nrv;
  12853. }
  12854. else if (index < rsub1) {
  12855. p.x = nru;
  12856. p.y = nrv;
  12857. }
  12858. else if (index < rsub2) {
  12859. p.x = nru;
  12860. p.y = 1.0 - nrv;
  12861. }
  12862. else {
  12863. p.x = 1.0 - nru;
  12864. p.y = 1.0 - nrv;
  12865. }
  12866. var angle = twopi - (index * twopi / (subDiv - 0.5));
  12867. p.x += Math.cos(angle) * nru;
  12868. p.y += Math.sin(angle) * nrv;
  12869. p.x *= w;
  12870. p.y *= h;
  12871. };
  12872. console.log("Genetre TriList for " + this.id);
  12873. var first = BABYLON.Vector2.Zero();
  12874. var cur = BABYLON.Vector2.Zero();
  12875. computePos(0, first);
  12876. var prev = first.clone();
  12877. for (var index = 1; index < subDiv; index++) {
  12878. computePos(index, cur);
  12879. this._primTriArray.storeTriangle(index - 1, center, prev, cur);
  12880. console.log(index - 1 + ", " + center + ", " + prev + ", " + cur);
  12881. prev.copyFrom(cur);
  12882. }
  12883. this._primTriArray.storeTriangle(subDiv - 1, center, first, prev);
  12884. console.log(subDiv - 1 + ", " + center + ", " + prev + ", " + first);
  12885. };
  12886. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  12887. var renderCache = modelRenderCache;
  12888. var engine = this.owner.engine;
  12889. // Need to create WebGL resources for fill part?
  12890. if (this.fill) {
  12891. var vbSize = ((this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4) + 1;
  12892. var vb = new Float32Array(vbSize);
  12893. for (var i = 0; i < vbSize; i++) {
  12894. vb[i] = i;
  12895. }
  12896. renderCache.fillVB = engine.createVertexBuffer(vb);
  12897. var triCount = vbSize - 1;
  12898. var ib = new Float32Array(triCount * 3);
  12899. for (var i = 0; i < triCount; i++) {
  12900. ib[i * 3 + 0] = 0;
  12901. ib[i * 3 + 2] = i + 1;
  12902. ib[i * 3 + 1] = i + 2;
  12903. }
  12904. ib[triCount * 3 - 2] = 1;
  12905. renderCache.fillIB = engine.createIndexBuffer(ib);
  12906. renderCache.fillIndicesCount = triCount * 3;
  12907. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  12908. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  12909. if (ei) {
  12910. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12911. }
  12912. // Get the non instanced version
  12913. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  12914. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12915. }
  12916. // Need to create WebGL resource for border part?
  12917. if (this.border) {
  12918. var vbSize = (this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4 * 2;
  12919. var vb = new Float32Array(vbSize);
  12920. for (var i = 0; i < vbSize; i++) {
  12921. vb[i] = i;
  12922. }
  12923. renderCache.borderVB = engine.createVertexBuffer(vb);
  12924. var triCount = vbSize;
  12925. var rs = triCount / 2;
  12926. var ib = new Float32Array(triCount * 3);
  12927. for (var i = 0; i < rs; i++) {
  12928. var r0 = i;
  12929. var r1 = (i + 1) % rs;
  12930. ib[i * 6 + 0] = rs + r1;
  12931. ib[i * 6 + 1] = rs + r0;
  12932. ib[i * 6 + 2] = r0;
  12933. ib[i * 6 + 3] = r1;
  12934. ib[i * 6 + 4] = rs + r1;
  12935. ib[i * 6 + 5] = r0;
  12936. }
  12937. renderCache.borderIB = engine.createIndexBuffer(ib);
  12938. renderCache.borderIndicesCount = triCount * 3;
  12939. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  12940. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  12941. if (ei) {
  12942. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12943. }
  12944. // Get the non instanced version
  12945. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  12946. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12947. }
  12948. return renderCache;
  12949. };
  12950. // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius
  12951. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  12952. // Fall back to default implementation if there's no round Radius
  12953. if (this._notRounded) {
  12954. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  12955. }
  12956. else {
  12957. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  12958. initialContentPosition.x = initialContentPosition.y = rr;
  12959. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  12960. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  12961. initialContentPosition.z = primSize.width - (initialContentPosition.x + initialContentArea.width);
  12962. initialContentPosition.w = primSize.height - (initialContentPosition.y + initialContentArea.height);
  12963. }
  12964. };
  12965. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, paddingOffset, newPrimSize) {
  12966. // Fall back to default implementation if there's no round Radius
  12967. if (this._notRounded) {
  12968. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, paddingOffset, newPrimSize);
  12969. }
  12970. else {
  12971. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  12972. newPrimSize.copyFrom(primSize);
  12973. newPrimSize.width += rr * 2;
  12974. newPrimSize.height += rr * 2;
  12975. paddingOffset.x += rr;
  12976. paddingOffset.y += rr;
  12977. paddingOffset.z += rr;
  12978. paddingOffset.w += rr;
  12979. }
  12980. };
  12981. Rectangle2D.prototype.createInstanceDataParts = function () {
  12982. var res = new Array();
  12983. if (this.border) {
  12984. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  12985. }
  12986. if (this.fill) {
  12987. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  12988. }
  12989. return res;
  12990. };
  12991. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  12992. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  12993. return false;
  12994. }
  12995. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  12996. var d = part;
  12997. var size = this.actualSize;
  12998. var s = this.actualScale;
  12999. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  13000. }
  13001. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  13002. var d = part;
  13003. var size = this.actualSize;
  13004. var s = this.actualScale;
  13005. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  13006. }
  13007. return true;
  13008. };
  13009. return Rectangle2D;
  13010. }(BABYLON.Shape2D));
  13011. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  13012. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  13013. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  13014. Rectangle2D.roundSubdivisions = 16;
  13015. __decorate([
  13016. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D_1.notRoundedProperty = pi; })
  13017. ], Rectangle2D.prototype, "notRounded", null);
  13018. __decorate([
  13019. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D_1.roundRadiusProperty = pi; })
  13020. ], Rectangle2D.prototype, "roundRadius", null);
  13021. Rectangle2D = Rectangle2D_1 = __decorate([
  13022. BABYLON.className("Rectangle2D", "BABYLON")
  13023. ], Rectangle2D);
  13024. BABYLON.Rectangle2D = Rectangle2D;
  13025. var Rectangle2D_1;
  13026. })(BABYLON || (BABYLON = {}));
  13027. var __extends = (this && this.__extends) || function (d, b) {
  13028. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13029. function __() { this.constructor = d; }
  13030. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13031. };
  13032. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13033. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13034. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13035. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  13036. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13037. };
  13038. var BABYLON;
  13039. (function (BABYLON) {
  13040. var Ellipse2DRenderCache = (function (_super) {
  13041. __extends(Ellipse2DRenderCache, _super);
  13042. function Ellipse2DRenderCache(engine, modelKey) {
  13043. var _this = _super.call(this, engine, modelKey) || this;
  13044. _this.effectsReady = false;
  13045. _this.fillVB = null;
  13046. _this.fillIB = null;
  13047. _this.fillIndicesCount = 0;
  13048. _this.instancingFillAttributes = null;
  13049. _this.effectFillInstanced = null;
  13050. _this.effectFill = null;
  13051. _this.borderVB = null;
  13052. _this.borderIB = null;
  13053. _this.borderIndicesCount = 0;
  13054. _this.instancingBorderAttributes = null;
  13055. _this.effectBorderInstanced = null;
  13056. _this.effectBorder = null;
  13057. return _this;
  13058. }
  13059. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  13060. // Do nothing if the shader is still loading/preparing
  13061. if (!this.effectsReady) {
  13062. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  13063. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  13064. return false;
  13065. }
  13066. this.effectsReady = true;
  13067. }
  13068. var canvas = instanceInfo.owner.owner;
  13069. var engine = canvas.engine;
  13070. var depthFunction = 0;
  13071. if (this.effectFill && this.effectBorder) {
  13072. depthFunction = engine.getDepthFunction();
  13073. engine.setDepthFunctionToLessOrEqual();
  13074. }
  13075. var curAlphaMode = engine.getAlphaMode();
  13076. if (this.effectFill) {
  13077. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  13078. var pid = context.groupInfoPartData[partIndex];
  13079. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13080. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13081. }
  13082. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  13083. engine.enableEffect(effect);
  13084. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  13085. if (context.useInstancing) {
  13086. if (!this.instancingFillAttributes) {
  13087. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  13088. }
  13089. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13090. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13091. canvas._addDrawCallCount(1, context.renderMode);
  13092. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  13093. engine.draw(true, 0, this.fillIndicesCount, count);
  13094. engine.unbindInstanceAttributes();
  13095. }
  13096. else {
  13097. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13098. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13099. this.setupUniforms(effect, partIndex, pid._partData, i);
  13100. engine.draw(true, 0, this.fillIndicesCount);
  13101. }
  13102. }
  13103. }
  13104. if (this.effectBorder) {
  13105. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  13106. var pid = context.groupInfoPartData[partIndex];
  13107. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13108. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13109. }
  13110. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  13111. engine.enableEffect(effect);
  13112. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  13113. if (context.useInstancing) {
  13114. if (!this.instancingBorderAttributes) {
  13115. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  13116. }
  13117. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13118. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13119. canvas._addDrawCallCount(1, context.renderMode);
  13120. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  13121. engine.draw(true, 0, this.borderIndicesCount, count);
  13122. engine.unbindInstanceAttributes();
  13123. }
  13124. else {
  13125. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13126. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13127. this.setupUniforms(effect, partIndex, pid._partData, i);
  13128. engine.draw(true, 0, this.borderIndicesCount);
  13129. }
  13130. }
  13131. }
  13132. engine.setAlphaMode(curAlphaMode, true);
  13133. if (this.effectFill && this.effectBorder) {
  13134. engine.setDepthFunction(depthFunction);
  13135. }
  13136. return true;
  13137. };
  13138. Ellipse2DRenderCache.prototype.dispose = function () {
  13139. if (!_super.prototype.dispose.call(this)) {
  13140. return false;
  13141. }
  13142. if (this.fillVB) {
  13143. this._engine._releaseBuffer(this.fillVB);
  13144. this.fillVB = null;
  13145. }
  13146. if (this.fillIB) {
  13147. this._engine._releaseBuffer(this.fillIB);
  13148. this.fillIB = null;
  13149. }
  13150. this.effectFill = null;
  13151. this.effectFillInstanced = null;
  13152. this.effectBorder = null;
  13153. this.effectBorderInstanced = null;
  13154. if (this.borderVB) {
  13155. this._engine._releaseBuffer(this.borderVB);
  13156. this.borderVB = null;
  13157. }
  13158. if (this.borderIB) {
  13159. this._engine._releaseBuffer(this.borderIB);
  13160. this.borderIB = null;
  13161. }
  13162. return true;
  13163. };
  13164. return Ellipse2DRenderCache;
  13165. }(BABYLON.ModelRenderCache));
  13166. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  13167. var Ellipse2DInstanceData = (function (_super) {
  13168. __extends(Ellipse2DInstanceData, _super);
  13169. function Ellipse2DInstanceData(partId) {
  13170. return _super.call(this, partId, 1) || this;
  13171. }
  13172. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  13173. get: function () {
  13174. return null;
  13175. },
  13176. set: function (value) {
  13177. },
  13178. enumerable: true,
  13179. configurable: true
  13180. });
  13181. return Ellipse2DInstanceData;
  13182. }(BABYLON.Shape2DInstanceData));
  13183. __decorate([
  13184. BABYLON.instanceData()
  13185. ], Ellipse2DInstanceData.prototype, "properties", null);
  13186. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  13187. var Ellipse2D = Ellipse2D_1 = (function (_super) {
  13188. __extends(Ellipse2D, _super);
  13189. /**
  13190. * Create an Ellipse 2D Shape primitive
  13191. * @param settings a combination of settings, possible ones are
  13192. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  13193. * - children: an array of direct children
  13194. * - id: a text identifier, for information purpose
  13195. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13196. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13197. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13198. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13199. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13200. * - zOrder: override the zOrder with the specified value
  13201. * - origin: define the normalized origin point location, default [0.5;0.5]
  13202. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  13203. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  13204. * - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  13205. * - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  13206. * - borderThickness: the thickness of the drawn border, default is 1.
  13207. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  13208. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  13209. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  13210. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  13211. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  13212. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  13213. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13214. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13215. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13216. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13217. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13218. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13219. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13220. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13221. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13222. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13223. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13224. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13225. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13226. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13227. */
  13228. function Ellipse2D(settings) {
  13229. var _this;
  13230. // Avoid checking every time if the object exists
  13231. if (settings == null) {
  13232. settings = {};
  13233. }
  13234. _this = _super.call(this, settings) || this;
  13235. if (settings.size != null) {
  13236. _this.size = settings.size;
  13237. }
  13238. else if (settings.width || settings.height) {
  13239. var size = new BABYLON.Size(settings.width, settings.height);
  13240. _this.size = size;
  13241. }
  13242. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  13243. _this.subdivisions = sub;
  13244. return _this;
  13245. }
  13246. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  13247. get: function () {
  13248. return this._subdivisions;
  13249. },
  13250. set: function (value) {
  13251. this._subdivisions = value;
  13252. },
  13253. enumerable: true,
  13254. configurable: true
  13255. });
  13256. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  13257. var w = this.size.width / 2;
  13258. var h = this.size.height / 2;
  13259. var x = intersectInfo._localPickPosition.x - w;
  13260. var y = intersectInfo._localPickPosition.y - h;
  13261. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  13262. };
  13263. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  13264. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  13265. return true;
  13266. };
  13267. Ellipse2D.prototype.updateTriArray = function () {
  13268. var subDiv = this._subdivisions;
  13269. if (this._primTriArray == null) {
  13270. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  13271. }
  13272. else {
  13273. this._primTriArray.clear(subDiv);
  13274. }
  13275. var size = this.actualSize;
  13276. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  13277. var v1 = BABYLON.Vector2.Zero();
  13278. var v2 = BABYLON.Vector2.Zero();
  13279. for (var i = 0; i < subDiv; i++) {
  13280. var angle1 = Math.PI * 2 * (i - 1) / subDiv;
  13281. var angle2 = Math.PI * 2 * i / subDiv;
  13282. v1.x = ((Math.cos(angle1) / 2.0) + 0.5) * size.width;
  13283. v1.y = ((Math.sin(angle1) / 2.0) + 0.5) * size.height;
  13284. v2.x = ((Math.cos(angle2) / 2.0) + 0.5) * size.width;
  13285. v2.y = ((Math.sin(angle2) / 2.0) + 0.5) * size.height;
  13286. this._primTriArray.storeTriangle(i, center, v1, v2);
  13287. }
  13288. };
  13289. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  13290. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  13291. return renderCache;
  13292. };
  13293. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  13294. var renderCache = modelRenderCache;
  13295. var engine = this.owner.engine;
  13296. // Need to create WebGL resources for fill part?
  13297. if (this.fill) {
  13298. var vbSize = this.subdivisions + 1;
  13299. var vb = new Float32Array(vbSize);
  13300. for (var i = 0; i < vbSize; i++) {
  13301. vb[i] = i;
  13302. }
  13303. renderCache.fillVB = engine.createVertexBuffer(vb);
  13304. var triCount = vbSize - 1;
  13305. var ib = new Float32Array(triCount * 3);
  13306. for (var i = 0; i < triCount; i++) {
  13307. ib[i * 3 + 0] = 0;
  13308. ib[i * 3 + 2] = i + 2;
  13309. ib[i * 3 + 1] = i + 1;
  13310. }
  13311. ib[triCount * 3 - 1] = 1;
  13312. renderCache.fillIB = engine.createIndexBuffer(ib);
  13313. renderCache.fillIndicesCount = triCount * 3;
  13314. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  13315. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  13316. if (ei) {
  13317. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  13318. }
  13319. // Get the non instanced version
  13320. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  13321. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  13322. }
  13323. // Need to create WebGL resource for border part?
  13324. if (this.border) {
  13325. var vbSize = this.subdivisions * 2;
  13326. var vb = new Float32Array(vbSize);
  13327. for (var i = 0; i < vbSize; i++) {
  13328. vb[i] = i;
  13329. }
  13330. renderCache.borderVB = engine.createVertexBuffer(vb);
  13331. var triCount = vbSize;
  13332. var rs = triCount / 2;
  13333. var ib = new Float32Array(triCount * 3);
  13334. for (var i = 0; i < rs; i++) {
  13335. var r0 = i;
  13336. var r1 = (i + 1) % rs;
  13337. ib[i * 6 + 0] = rs + r1;
  13338. ib[i * 6 + 1] = rs + r0;
  13339. ib[i * 6 + 2] = r0;
  13340. ib[i * 6 + 3] = r1;
  13341. ib[i * 6 + 4] = rs + r1;
  13342. ib[i * 6 + 5] = r0;
  13343. }
  13344. renderCache.borderIB = engine.createIndexBuffer(ib);
  13345. renderCache.borderIndicesCount = (triCount * 3);
  13346. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  13347. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  13348. if (ei) {
  13349. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13350. }
  13351. // Get the non instanced version
  13352. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  13353. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13354. }
  13355. return renderCache;
  13356. };
  13357. Ellipse2D.prototype.createInstanceDataParts = function () {
  13358. var res = new Array();
  13359. if (this.border) {
  13360. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  13361. }
  13362. if (this.fill) {
  13363. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  13364. }
  13365. return res;
  13366. };
  13367. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  13368. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  13369. return false;
  13370. }
  13371. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  13372. var d = part;
  13373. var size = this.actualSize;
  13374. var s = this.actualScale;
  13375. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  13376. }
  13377. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  13378. var d = part;
  13379. var size = this.actualSize;
  13380. var s = this.actualScale;
  13381. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  13382. }
  13383. return true;
  13384. };
  13385. return Ellipse2D;
  13386. }(BABYLON.Shape2D));
  13387. __decorate([
  13388. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D_1.subdivisionsProperty = pi; })
  13389. ], Ellipse2D.prototype, "subdivisions", null);
  13390. Ellipse2D = Ellipse2D_1 = __decorate([
  13391. BABYLON.className("Ellipse2D", "BABYLON")
  13392. ], Ellipse2D);
  13393. BABYLON.Ellipse2D = Ellipse2D;
  13394. var Ellipse2D_1;
  13395. })(BABYLON || (BABYLON = {}));
  13396. var __extends = (this && this.__extends) || function (d, b) {
  13397. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13398. function __() { this.constructor = d; }
  13399. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13400. };
  13401. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13402. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13403. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13404. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  13405. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13406. };
  13407. var BABYLON;
  13408. (function (BABYLON) {
  13409. var Sprite2DRenderCache = (function (_super) {
  13410. __extends(Sprite2DRenderCache, _super);
  13411. function Sprite2DRenderCache() {
  13412. var _this = _super.apply(this, arguments) || this;
  13413. _this.effectsReady = false;
  13414. _this.vb = null;
  13415. _this.ib = null;
  13416. _this.instancingAttributes = null;
  13417. _this.texture = null;
  13418. _this.effect = null;
  13419. _this.effectInstanced = null;
  13420. return _this;
  13421. }
  13422. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  13423. // Do nothing if the shader is still loading/preparing
  13424. if (!this.effectsReady) {
  13425. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  13426. return false;
  13427. }
  13428. this.effectsReady = true;
  13429. }
  13430. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  13431. var canvas = instanceInfo.owner.owner;
  13432. var engine = canvas.engine;
  13433. var cur = engine.getAlphaMode();
  13434. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  13435. engine.enableEffect(effect);
  13436. effect.setTexture("diffuseSampler", this.texture);
  13437. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  13438. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13439. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13440. }
  13441. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  13442. var pid = context.groupInfoPartData[0];
  13443. if (context.useInstancing) {
  13444. if (!this.instancingAttributes) {
  13445. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  13446. }
  13447. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  13448. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13449. canvas._addDrawCallCount(1, context.renderMode);
  13450. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  13451. engine.draw(true, 0, 6, count);
  13452. engine.unbindInstanceAttributes();
  13453. }
  13454. else {
  13455. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13456. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13457. this.setupUniforms(effect, 0, pid._partData, i);
  13458. engine.draw(true, 0, 6);
  13459. }
  13460. }
  13461. engine.setAlphaMode(cur, true);
  13462. return true;
  13463. };
  13464. Sprite2DRenderCache.prototype.dispose = function () {
  13465. if (!_super.prototype.dispose.call(this)) {
  13466. return false;
  13467. }
  13468. if (this.vb) {
  13469. this._engine._releaseBuffer(this.vb);
  13470. this.vb = null;
  13471. }
  13472. if (this.ib) {
  13473. this._engine._releaseBuffer(this.ib);
  13474. this.ib = null;
  13475. }
  13476. //if (this.texture) {
  13477. // this.texture.dispose();
  13478. // this.texture = null;
  13479. //}
  13480. this.effect = null;
  13481. this.effectInstanced = null;
  13482. return true;
  13483. };
  13484. return Sprite2DRenderCache;
  13485. }(BABYLON.ModelRenderCache));
  13486. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  13487. var Sprite2D = Sprite2D_1 = (function (_super) {
  13488. __extends(Sprite2D, _super);
  13489. /**
  13490. * Create an 2D Sprite primitive
  13491. * @param texture the texture that stores the sprite to render
  13492. * @param settings a combination of settings, possible ones are
  13493. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  13494. * - children: an array of direct children
  13495. * - id a text identifier, for information purpose
  13496. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13497. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13498. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13499. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  13500. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13501. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13502. * - zOrder: override the zOrder with the specified value
  13503. * - origin: define the normalized origin point location, default [0.5;0.5]
  13504. * - spriteSize: the size of the sprite (in pixels) as it is stored in the texture, if null the size of the given texture will be used, default is null.
  13505. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  13506. * - spriteScaleFactor: DEPRECATED. Old behavior: say you want to display a sprite twice as big as its bitmap which is 64,64, you set the spriteSize to 128,128 and have to set the spriteScaleFactory to 0.5,0.5 in order to address only the 64,64 pixels of the bitmaps. Default is 1,1.
  13507. * - scale9: draw the sprite as a Scale9 sprite, see http://yannickloriot.com/2013/03/9-patch-technique-in-cocos2d/ for more info. x, y, w, z are left, bottom, right, top coordinate of the resizable box
  13508. * - invertY: if true the texture Y will be inverted, default is false.
  13509. * - alignToPixel: if true the sprite's texels will be aligned to the rendering viewport pixels, ensuring the best rendering quality but slow animations won't be done as smooth as if you set false. If false a texel could lies between two pixels, being blended by the texture sampling mode you choose, the rendering result won't be as good, but very slow animation will be overall better looking. Default is true: content will be aligned.
  13510. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  13511. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  13512. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  13513. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  13514. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  13515. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  13516. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13517. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13518. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13519. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13520. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13521. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13522. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13523. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13524. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13525. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13526. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13527. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13528. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13529. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13530. */
  13531. function Sprite2D(texture, settings) {
  13532. var _this;
  13533. if (!settings) {
  13534. settings = {};
  13535. }
  13536. _this = _super.call(this, settings) || this;
  13537. _this.texture = texture;
  13538. // This is removed to let the user the possibility to setup the addressing mode he wants
  13539. //this.texture.wrapU = Texture.CLAMP_ADDRESSMODE;
  13540. //this.texture.wrapV = Texture.CLAMP_ADDRESSMODE;
  13541. _this._useSize = false;
  13542. _this._spriteSize = (settings.spriteSize != null) ? settings.spriteSize.clone() : null;
  13543. _this._spriteLocation = (settings.spriteLocation != null) ? settings.spriteLocation.clone() : new BABYLON.Vector2(0, 0);
  13544. if (settings.size != null) {
  13545. _this.size = settings.size;
  13546. }
  13547. _this.spriteFrame = 0;
  13548. _this.invertY = (settings.invertY == null) ? false : settings.invertY;
  13549. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  13550. _this.useAlphaFromTexture = true;
  13551. _this._scale9 = (settings.scale9 != null) ? settings.scale9.clone() : null;
  13552. // If the user doesn't set a size, we'll use the texture's one, but if the texture is not loading, we HAVE to set a temporary dummy size otherwise the positioning engine will switch the marginAlignement to stretch/stretch, and WE DON'T WANT THAT.
  13553. // The fucking delayed texture sprite bug is fixed!
  13554. if (settings.spriteSize == null) {
  13555. _this.spriteSize = new BABYLON.Size(10, 10);
  13556. }
  13557. if (settings.spriteSize == null || !texture.isReady()) {
  13558. if (texture.isReady()) {
  13559. var s = texture.getBaseSize();
  13560. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  13561. _this._updateSpriteScaleFactor();
  13562. }
  13563. else {
  13564. texture.onLoadObservable.add(function () {
  13565. if (settings.spriteSize == null) {
  13566. var s = texture.getBaseSize();
  13567. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  13568. }
  13569. _this._updateSpriteScaleFactor();
  13570. _this._positioningDirty();
  13571. _this._setLayoutDirty();
  13572. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D_1.textureProperty.flagId; // To make sure the sprite is issued again for render
  13573. });
  13574. }
  13575. }
  13576. return _this;
  13577. }
  13578. Object.defineProperty(Sprite2D.prototype, "texture", {
  13579. get: function () {
  13580. return this._texture;
  13581. },
  13582. set: function (value) {
  13583. this._texture = value;
  13584. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  13585. },
  13586. enumerable: true,
  13587. configurable: true
  13588. });
  13589. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  13590. get: function () {
  13591. return this._useAlphaFromTexture;
  13592. },
  13593. set: function (value) {
  13594. if (this._useAlphaFromTexture === value) {
  13595. return;
  13596. }
  13597. this._useAlphaFromTexture = value;
  13598. this._updateRenderMode();
  13599. },
  13600. enumerable: true,
  13601. configurable: true
  13602. });
  13603. Object.defineProperty(Sprite2D.prototype, "size", {
  13604. get: function () {
  13605. if (this._size == null) {
  13606. return this.spriteSize;
  13607. }
  13608. return this.internalGetSize();
  13609. },
  13610. set: function (value) {
  13611. this._useSize = value != null;
  13612. this.internalSetSize(value);
  13613. this._updateSpriteScaleFactor();
  13614. },
  13615. enumerable: true,
  13616. configurable: true
  13617. });
  13618. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  13619. get: function () {
  13620. return this._spriteSize;
  13621. },
  13622. set: function (value) {
  13623. if (!this._spriteSize) {
  13624. this._spriteSize = value.clone();
  13625. }
  13626. else {
  13627. this._spriteSize.copyFrom(value);
  13628. }
  13629. this._updateSpriteScaleFactor();
  13630. },
  13631. enumerable: true,
  13632. configurable: true
  13633. });
  13634. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  13635. get: function () {
  13636. return this._spriteLocation;
  13637. },
  13638. set: function (value) {
  13639. if (!this._spriteLocation) {
  13640. this._spriteLocation = value.clone();
  13641. }
  13642. else {
  13643. this._spriteLocation.copyFrom(value);
  13644. }
  13645. },
  13646. enumerable: true,
  13647. configurable: true
  13648. });
  13649. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  13650. get: function () {
  13651. return this._spriteFrame;
  13652. },
  13653. set: function (value) {
  13654. this._spriteFrame = value;
  13655. },
  13656. enumerable: true,
  13657. configurable: true
  13658. });
  13659. Object.defineProperty(Sprite2D.prototype, "invertY", {
  13660. get: function () {
  13661. return this._invertY;
  13662. },
  13663. set: function (value) {
  13664. this._invertY = value;
  13665. },
  13666. enumerable: true,
  13667. configurable: true
  13668. });
  13669. Object.defineProperty(Sprite2D.prototype, "isScale9", {
  13670. get: function () {
  13671. return this._scale9 !== null;
  13672. },
  13673. enumerable: true,
  13674. configurable: true
  13675. });
  13676. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  13677. //@instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, pi => Sprite2D.spriteScaleFactorProperty = pi)
  13678. ///**
  13679. // * Get/set the sprite location (in pixels) in the texture
  13680. // */
  13681. //public get spriteScaleFactor(): Vector2 {
  13682. // return this._spriteScaleFactor;
  13683. //}
  13684. //public set spriteScaleFactor(value: Vector2) {
  13685. // this._spriteScaleFactor = value;
  13686. //}
  13687. /**
  13688. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  13689. */
  13690. get: function () {
  13691. return this._alignToPixel;
  13692. },
  13693. set: function (value) {
  13694. this._alignToPixel = value;
  13695. },
  13696. enumerable: true,
  13697. configurable: true
  13698. });
  13699. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  13700. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  13701. return true;
  13702. };
  13703. /**
  13704. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  13705. */
  13706. Sprite2D.prototype.getAnimatables = function () {
  13707. var res = new Array();
  13708. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  13709. res.push(this.texture);
  13710. }
  13711. return res;
  13712. };
  13713. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  13714. // If we've made it so far it means the boundingInfo intersection test succeed, the Sprite2D is shaped the same, so we always return true
  13715. return true;
  13716. };
  13717. Object.defineProperty(Sprite2D.prototype, "isSizeAuto", {
  13718. get: function () {
  13719. return this.size == null;
  13720. },
  13721. enumerable: true,
  13722. configurable: true
  13723. });
  13724. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  13725. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  13726. return renderCache;
  13727. };
  13728. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  13729. var renderCache = modelRenderCache;
  13730. var engine = this.owner.engine;
  13731. var vb = new Float32Array(4);
  13732. for (var i = 0; i < 4; i++) {
  13733. vb[i] = i;
  13734. }
  13735. renderCache.vb = engine.createVertexBuffer(vb);
  13736. var ib = new Float32Array(6);
  13737. ib[0] = 0;
  13738. ib[1] = 2;
  13739. ib[2] = 1;
  13740. ib[3] = 0;
  13741. ib[4] = 3;
  13742. ib[5] = 2;
  13743. renderCache.ib = engine.createIndexBuffer(ib);
  13744. renderCache.texture = this.texture;
  13745. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  13746. var ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  13747. if (ei) {
  13748. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13749. }
  13750. ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  13751. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13752. return renderCache;
  13753. };
  13754. Sprite2D.prototype.getUsedShaderCategories = function (dataPart) {
  13755. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  13756. if (dataPart.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  13757. var useScale9 = this._scale9 != null;
  13758. if (useScale9) {
  13759. cat.push(Sprite2D_1.SHAPE2D_CATEGORY_SCALE9);
  13760. }
  13761. }
  13762. return cat;
  13763. };
  13764. Sprite2D.prototype.createInstanceDataParts = function () {
  13765. return [new Sprite2DInstanceData(Sprite2D_1.SPRITE2D_MAINPARTID)];
  13766. };
  13767. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  13768. Sprite2D_1.layoutConstructMode = true;
  13769. };
  13770. // if obj contains something, we restore the _text property
  13771. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  13772. Sprite2D_1.layoutConstructMode = false;
  13773. };
  13774. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  13775. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  13776. return false;
  13777. }
  13778. if (!this.texture.isReady() && !Sprite2D_1.layoutConstructMode) {
  13779. return false;
  13780. }
  13781. if (part.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  13782. var d = this._instanceDataParts[0];
  13783. if (Sprite2D_1.layoutConstructMode) {
  13784. d.topLeftUV = BABYLON.Vector2.Zero();
  13785. d.sizeUV = BABYLON.Vector2.Zero();
  13786. d.properties = BABYLON.Vector3.Zero();
  13787. d.textureSize = BABYLON.Vector2.Zero();
  13788. d.scaleFactor = BABYLON.Vector2.Zero();
  13789. if (this.isScale9) {
  13790. d.scale9 = BABYLON.Vector4.Zero();
  13791. }
  13792. }
  13793. else {
  13794. var ts = this.texture.getBaseSize();
  13795. var ss = this.spriteSize;
  13796. var sl = this.spriteLocation;
  13797. var ssf = this.actualScale;
  13798. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  13799. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  13800. d.sizeUV = suv;
  13801. d.scaleFactor = ssf;
  13802. Sprite2D_1._prop.x = this.spriteFrame;
  13803. Sprite2D_1._prop.y = this.invertY ? 1 : 0;
  13804. Sprite2D_1._prop.z = this.alignToPixel ? 1 : 0;
  13805. d.properties = Sprite2D_1._prop;
  13806. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  13807. var scale9 = this._scale9;
  13808. if (scale9 != null) {
  13809. var normalizedScale9 = new BABYLON.Vector4(scale9.x * suv.x / ss.width, scale9.y * suv.y / ss.height, scale9.z * suv.x / ss.width, scale9.w * suv.y / ss.height);
  13810. d.scale9 = normalizedScale9;
  13811. }
  13812. }
  13813. }
  13814. return true;
  13815. };
  13816. Sprite2D.prototype._mustUpdateInstance = function () {
  13817. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  13818. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  13819. if (res) {
  13820. this._updateRenderMode();
  13821. }
  13822. return res;
  13823. };
  13824. Sprite2D.prototype._useTextureAlpha = function () {
  13825. return this.texture != null && this.texture.hasAlpha;
  13826. };
  13827. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  13828. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  13829. };
  13830. Sprite2D.prototype._updateSpriteScaleFactor = function () {
  13831. if (!this._useSize) {
  13832. return;
  13833. }
  13834. var sS = this.spriteSize;
  13835. var s = this.size;
  13836. if (s == null || sS == null) {
  13837. return;
  13838. }
  13839. this._postScale.x = s.width / sS.width;
  13840. this._postScale.y = s.height / sS.height;
  13841. };
  13842. return Sprite2D;
  13843. }(BABYLON.RenderablePrim2D));
  13844. Sprite2D.SPRITE2D_MAINPARTID = 1;
  13845. Sprite2D.SHAPE2D_CATEGORY_SCALE9 = "Scale9";
  13846. Sprite2D._prop = BABYLON.Vector3.Zero();
  13847. Sprite2D.layoutConstructMode = false;
  13848. __decorate([
  13849. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D_1.textureProperty = pi; })
  13850. ], Sprite2D.prototype, "texture", null);
  13851. __decorate([
  13852. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D_1.useAlphaFromTextureProperty = pi; })
  13853. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  13854. __decorate([
  13855. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D_1.spriteSizeProperty = pi; }, false, true)
  13856. ], Sprite2D.prototype, "spriteSize", null);
  13857. __decorate([
  13858. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D_1.spriteLocationProperty = pi; })
  13859. ], Sprite2D.prototype, "spriteLocation", null);
  13860. __decorate([
  13861. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D_1.spriteFrameProperty = pi; })
  13862. ], Sprite2D.prototype, "spriteFrame", null);
  13863. __decorate([
  13864. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D_1.invertYProperty = pi; })
  13865. ], Sprite2D.prototype, "invertY", null);
  13866. __decorate([
  13867. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 8, function (pi) { return Sprite2D_1.spriteScale9Property = pi; })
  13868. ], Sprite2D.prototype, "isScale9", null);
  13869. Sprite2D = Sprite2D_1 = __decorate([
  13870. BABYLON.className("Sprite2D", "BABYLON")
  13871. ], Sprite2D);
  13872. BABYLON.Sprite2D = Sprite2D;
  13873. var Sprite2DInstanceData = (function (_super) {
  13874. __extends(Sprite2DInstanceData, _super);
  13875. function Sprite2DInstanceData(partId) {
  13876. return _super.call(this, partId, 1) || this;
  13877. }
  13878. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  13879. get: function () {
  13880. return null;
  13881. },
  13882. set: function (value) {
  13883. },
  13884. enumerable: true,
  13885. configurable: true
  13886. });
  13887. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  13888. get: function () {
  13889. return null;
  13890. },
  13891. set: function (value) {
  13892. },
  13893. enumerable: true,
  13894. configurable: true
  13895. });
  13896. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  13897. get: function () {
  13898. return null;
  13899. },
  13900. set: function (value) {
  13901. },
  13902. enumerable: true,
  13903. configurable: true
  13904. });
  13905. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  13906. get: function () {
  13907. return null;
  13908. },
  13909. set: function (value) {
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  13915. // 3 floats being:
  13916. // - x: frame number to display
  13917. // - y: invertY setting
  13918. // - z: alignToPixel setting
  13919. get: function () {
  13920. return null;
  13921. },
  13922. set: function (value) {
  13923. },
  13924. enumerable: true,
  13925. configurable: true
  13926. });
  13927. Object.defineProperty(Sprite2DInstanceData.prototype, "scale9", {
  13928. get: function () {
  13929. return null;
  13930. },
  13931. set: function (value) {
  13932. },
  13933. enumerable: true,
  13934. configurable: true
  13935. });
  13936. return Sprite2DInstanceData;
  13937. }(BABYLON.InstanceDataBase));
  13938. __decorate([
  13939. BABYLON.instanceData()
  13940. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  13941. __decorate([
  13942. BABYLON.instanceData()
  13943. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  13944. __decorate([
  13945. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  13946. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  13947. __decorate([
  13948. BABYLON.instanceData()
  13949. ], Sprite2DInstanceData.prototype, "textureSize", null);
  13950. __decorate([
  13951. BABYLON.instanceData()
  13952. ], Sprite2DInstanceData.prototype, "properties", null);
  13953. __decorate([
  13954. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  13955. ], Sprite2DInstanceData.prototype, "scale9", null);
  13956. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  13957. var Sprite2D_1;
  13958. })(BABYLON || (BABYLON = {}));
  13959. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13960. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13961. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13962. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  13963. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13964. };
  13965. var BABYLON;
  13966. (function (BABYLON) {
  13967. /**
  13968. * This class will contains information about a sub picture present in an Atlas Picture.
  13969. */
  13970. var AtlasSubPictureInfo = (function () {
  13971. function AtlasSubPictureInfo() {
  13972. }
  13973. return AtlasSubPictureInfo;
  13974. }());
  13975. BABYLON.AtlasSubPictureInfo = AtlasSubPictureInfo;
  13976. /**
  13977. * This class represent an Atlas Picture, it contains the information of all the sub pictures and the Texture that stores the bitmap.
  13978. * You get an instance of this class using methods of the AtlasPictureInfoFactory
  13979. */
  13980. var AtlasPictureInfo = (function () {
  13981. function AtlasPictureInfo() {
  13982. }
  13983. /**
  13984. * Creates many sprite from the Atlas Picture
  13985. * @param filterCallback a predicate if true is returned then the corresponding sub picture will be used to create a sprite.
  13986. * The Predicate has many parameters:
  13987. * - index: just an index incremented at each sub picture submitted for Sprite creation
  13988. * - name: the sub picture's name
  13989. * - aspi: the AtlasSubPictureInfo corresponding to the submitted sub picture
  13990. * - settings: the Sprite2D creation settings, you can alter this JSON object but BEWARE, the alterations will be kept for subsequent Sprite2D creations!
  13991. * @param spriteSettings The Sprite2D settings to use for Sprite creation, this JSON object will be passed to the filterCallback for you to alter it, if needed.
  13992. */
  13993. AtlasPictureInfo.prototype.createSprites = function (filterCallback, spriteSettings) {
  13994. var _this = this;
  13995. var res = new Array();
  13996. var index = 0;
  13997. this.subPictures.forEach(function (k, v) {
  13998. if (!filterCallback || filterCallback(index++, k, v, spriteSettings)) {
  13999. var s = _this.createSprite(k, spriteSettings);
  14000. if (s) {
  14001. res.push(s);
  14002. }
  14003. }
  14004. });
  14005. return res;
  14006. };
  14007. /**
  14008. * Create one Sprite from a sub picture
  14009. * @param subPictureName the name of the sub picture to use
  14010. * @param spriteSettings the Sprite2D settings to use for the Sprite instance creation
  14011. */
  14012. AtlasPictureInfo.prototype.createSprite = function (subPictureName, spriteSettings) {
  14013. var spi = this.subPictures.get(subPictureName);
  14014. if (!spi) {
  14015. return null;
  14016. }
  14017. if (!spriteSettings) {
  14018. spriteSettings = {};
  14019. }
  14020. var s = spriteSettings;
  14021. s.id = subPictureName;
  14022. s.spriteLocation = spi.location;
  14023. s.spriteSize = spi.size;
  14024. var sprite = new BABYLON.Sprite2D(this.texture, spriteSettings);
  14025. return sprite;
  14026. };
  14027. return AtlasPictureInfo;
  14028. }());
  14029. BABYLON.AtlasPictureInfo = AtlasPictureInfo;
  14030. /**
  14031. * This if the Factory class containing static method to create Atlas Pictures Info objects or add new loaders
  14032. */
  14033. var AtlasPictureInfoFactory = (function () {
  14034. function AtlasPictureInfoFactory() {
  14035. }
  14036. /**
  14037. * Add a custom loader
  14038. * @param fileExtension must be the file extension (without the dot) of the file that is loaded by this loader (e.g.: json)
  14039. * @param plugin the instance of the loader
  14040. */
  14041. AtlasPictureInfoFactory.addLoader = function (fileExtension, plugin) {
  14042. var a = AtlasPictureInfoFactory.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  14043. a.push(plugin);
  14044. };
  14045. /**
  14046. * Load an Atlas Picture Info object from a data file at a given url and with a given texture
  14047. * @param texture the texture containing the atlas bitmap
  14048. * @param url the URL of the Atlas Info data file
  14049. * @param onLoad a callback that will be called when the AtlasPictureInfo object will be loaded and ready
  14050. * @param onError a callback that will be called in case of error
  14051. */
  14052. AtlasPictureInfoFactory.loadFromUrl = function (texture, url, onLoad, onError) {
  14053. if (onError === void 0) { onError = null; }
  14054. BABYLON.Tools.LoadFile(url, function (data) {
  14055. var ext = url.split('.').pop().split(/\#|\?/)[0];
  14056. var plugins = AtlasPictureInfoFactory.plugins.get(ext.toLocaleLowerCase());
  14057. if (!plugins) {
  14058. if (onError) {
  14059. onError("couldn't find a plugin for this file extension", -1);
  14060. }
  14061. return;
  14062. }
  14063. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  14064. var p = plugins_1[_i];
  14065. var ret = p.loadFile(data);
  14066. if (ret) {
  14067. if (ret.api) {
  14068. ret.api.texture = texture;
  14069. if (onLoad) {
  14070. onLoad(ret.api);
  14071. }
  14072. }
  14073. else if (onError) {
  14074. onError(ret.errorMsg, ret.errorCode);
  14075. }
  14076. return;
  14077. }
  14078. }
  14079. if (onError) {
  14080. onError("No plugin to load this Atlas Data file format", -1);
  14081. }
  14082. }, null, null, null, function () {
  14083. if (onError) {
  14084. onError("Couldn't load file", -1);
  14085. }
  14086. });
  14087. return null;
  14088. };
  14089. return AtlasPictureInfoFactory;
  14090. }());
  14091. AtlasPictureInfoFactory.plugins = new BABYLON.StringDictionary();
  14092. BABYLON.AtlasPictureInfoFactory = AtlasPictureInfoFactory;
  14093. // Loader class for the TexturePacker's JSON Array data format
  14094. var JSONArrayLoader = JSONArrayLoader_1 = (function () {
  14095. function JSONArrayLoader() {
  14096. }
  14097. JSONArrayLoader.prototype.loadFile = function (content) {
  14098. var errorMsg = null;
  14099. var errorCode = 0;
  14100. var root = null;
  14101. var api = null;
  14102. try {
  14103. var frames_1;
  14104. var meta = void 0;
  14105. try {
  14106. root = JSON.parse(content);
  14107. frames_1 = root.frames;
  14108. meta = root.meta;
  14109. if (!frames_1 || !meta) {
  14110. throw Error("Not a JSON Array file format");
  14111. }
  14112. }
  14113. catch (ex1) {
  14114. return null;
  14115. }
  14116. api = new AtlasPictureInfo();
  14117. api.atlasSize = new BABYLON.Size(meta.size.w, meta.size.h);
  14118. api.subPictures = new BABYLON.StringDictionary();
  14119. for (var _i = 0, frames_2 = frames_1; _i < frames_2.length; _i++) {
  14120. var f = frames_2[_i];
  14121. var aspi = new AtlasSubPictureInfo();
  14122. aspi.name = f.filename;
  14123. aspi.location = new BABYLON.Vector2(f.frame.x, api.atlasSize.height - (f.frame.y + f.frame.h));
  14124. aspi.size = new BABYLON.Size(f.frame.w, f.frame.h);
  14125. api.subPictures.add(aspi.name, aspi);
  14126. }
  14127. }
  14128. catch (ex2) {
  14129. errorMsg = "Unknown Exception: " + ex2;
  14130. errorCode = -2;
  14131. }
  14132. return { api: api, errorMsg: errorMsg, errorCode: errorCode };
  14133. };
  14134. return JSONArrayLoader;
  14135. }());
  14136. JSONArrayLoader = JSONArrayLoader_1 = __decorate([
  14137. AtlasLoaderPlugin("json", new JSONArrayLoader_1())
  14138. ], JSONArrayLoader);
  14139. /**
  14140. * Use this decorator when you declare an Atlas Loader Class for the loader to register itself automatically.
  14141. * @param fileExtension the extension of the file that the plugin is loading (there can be many plugin for the same extension)
  14142. * @param plugin an instance of the plugin class to add to the AtlasPictureInfoFactory
  14143. */
  14144. function AtlasLoaderPlugin(fileExtension, plugin) {
  14145. return function () {
  14146. AtlasPictureInfoFactory.addLoader(fileExtension, plugin);
  14147. };
  14148. }
  14149. BABYLON.AtlasLoaderPlugin = AtlasLoaderPlugin;
  14150. var JSONArrayLoader_1;
  14151. })(BABYLON || (BABYLON = {}));
  14152. var __extends = (this && this.__extends) || function (d, b) {
  14153. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14154. function __() { this.constructor = d; }
  14155. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14156. };
  14157. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  14158. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  14159. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14160. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  14161. return c > 3 && r && Object.defineProperty(target, key, r), r;
  14162. };
  14163. var BABYLON;
  14164. (function (BABYLON) {
  14165. var Text2DRenderCache = (function (_super) {
  14166. __extends(Text2DRenderCache, _super);
  14167. function Text2DRenderCache() {
  14168. var _this = _super.apply(this, arguments) || this;
  14169. _this.effectsReady = false;
  14170. _this.vb = null;
  14171. _this.ib = null;
  14172. _this.instancingAttributes = null;
  14173. _this.fontTexture = null;
  14174. _this.effect = null;
  14175. _this.effectInstanced = null;
  14176. _this.fontPremulAlpha = false;
  14177. return _this;
  14178. }
  14179. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  14180. // Do nothing if the shader is still loading/preparing
  14181. if (!this.effectsReady) {
  14182. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  14183. return false;
  14184. }
  14185. this.effectsReady = true;
  14186. }
  14187. var canvas = instanceInfo.owner.owner;
  14188. var engine = canvas.engine;
  14189. this.fontTexture.update();
  14190. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  14191. engine.enableEffect(effect);
  14192. effect.setTexture("diffuseSampler", this.fontTexture);
  14193. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  14194. var sdf = this.fontTexture.isSignedDistanceField;
  14195. // Enable alpha mode only if the texture is not using SDF, SDF is rendered in AlphaTest mode, which mean no alpha blend
  14196. var curAlphaMode;
  14197. if (!sdf) {
  14198. curAlphaMode = engine.getAlphaMode();
  14199. engine.setAlphaMode(this.fontPremulAlpha ? BABYLON.Engine.ALPHA_PREMULTIPLIED : BABYLON.Engine.ALPHA_COMBINE, true);
  14200. }
  14201. var pid = context.groupInfoPartData[0];
  14202. if (context.useInstancing) {
  14203. if (!this.instancingAttributes) {
  14204. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  14205. }
  14206. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  14207. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  14208. canvas._addDrawCallCount(1, context.renderMode);
  14209. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  14210. engine.draw(true, 0, 6, count);
  14211. engine.unbindInstanceAttributes();
  14212. }
  14213. else {
  14214. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  14215. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  14216. this.setupUniforms(effect, 0, pid._partData, i);
  14217. engine.draw(true, 0, 6);
  14218. }
  14219. }
  14220. if (!sdf) {
  14221. engine.setAlphaMode(curAlphaMode, true);
  14222. }
  14223. return true;
  14224. };
  14225. Text2DRenderCache.prototype.dispose = function () {
  14226. if (!_super.prototype.dispose.call(this)) {
  14227. return false;
  14228. }
  14229. if (this.vb) {
  14230. this._engine._releaseBuffer(this.vb);
  14231. this.vb = null;
  14232. }
  14233. if (this.ib) {
  14234. this._engine._releaseBuffer(this.ib);
  14235. this.ib = null;
  14236. }
  14237. if (this.fontTexture) {
  14238. this.fontTexture.decCachedFontTextureCounter();
  14239. this.fontTexture = null;
  14240. }
  14241. this.effect = null;
  14242. this.effectInstanced = null;
  14243. return true;
  14244. };
  14245. return Text2DRenderCache;
  14246. }(BABYLON.ModelRenderCache));
  14247. BABYLON.Text2DRenderCache = Text2DRenderCache;
  14248. var Text2DInstanceData = (function (_super) {
  14249. __extends(Text2DInstanceData, _super);
  14250. function Text2DInstanceData(partId, dataElementCount) {
  14251. return _super.call(this, partId, dataElementCount) || this;
  14252. }
  14253. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  14254. get: function () {
  14255. return null;
  14256. },
  14257. set: function (value) {
  14258. },
  14259. enumerable: true,
  14260. configurable: true
  14261. });
  14262. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  14263. get: function () {
  14264. return null;
  14265. },
  14266. set: function (value) {
  14267. },
  14268. enumerable: true,
  14269. configurable: true
  14270. });
  14271. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  14272. get: function () {
  14273. return null;
  14274. },
  14275. set: function (value) {
  14276. },
  14277. enumerable: true,
  14278. configurable: true
  14279. });
  14280. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  14281. get: function () {
  14282. return null;
  14283. },
  14284. set: function (value) {
  14285. },
  14286. enumerable: true,
  14287. configurable: true
  14288. });
  14289. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  14290. get: function () {
  14291. return null;
  14292. },
  14293. set: function (value) {
  14294. },
  14295. enumerable: true,
  14296. configurable: true
  14297. });
  14298. return Text2DInstanceData;
  14299. }(BABYLON.InstanceDataBase));
  14300. __decorate([
  14301. BABYLON.instanceData()
  14302. ], Text2DInstanceData.prototype, "topLeftUV", null);
  14303. __decorate([
  14304. BABYLON.instanceData()
  14305. ], Text2DInstanceData.prototype, "sizeUV", null);
  14306. __decorate([
  14307. BABYLON.instanceData()
  14308. ], Text2DInstanceData.prototype, "textureSize", null);
  14309. __decorate([
  14310. BABYLON.instanceData()
  14311. ], Text2DInstanceData.prototype, "color", null);
  14312. __decorate([
  14313. BABYLON.instanceData()
  14314. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  14315. BABYLON.Text2DInstanceData = Text2DInstanceData;
  14316. var Text2D = Text2D_1 = (function (_super) {
  14317. __extends(Text2D, _super);
  14318. /**
  14319. * Create a Text primitive
  14320. * @param text the text to display
  14321. * @param settings a combination of settings, possible ones are
  14322. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  14323. * - children: an array of direct children
  14324. * - id a text identifier, for information purpose
  14325. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  14326. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  14327. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  14328. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  14329. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  14330. * - zOrder: override the zOrder with the specified value
  14331. * - origin: define the normalized origin point location, default [0.5;0.5]
  14332. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  14333. * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in.
  14334. * - signedDistanceField: if true the text will be rendered using the SignedDistanceField technique. This technique has the advantage to be rendered order independent (then much less drawing calls), but only works on font that are a little more than one pixel wide on the screen but the rendering quality is excellent whatever the font size is on the screen (which is the purpose of this technique). Outlining/Shadow is not supported right now. If you can, you should use this mode, the quality and the performances are the best. Note that fontSuperSample has no effect when this mode is on.
  14335. * - bitmapFontTexture: set a BitmapFontTexture to use instead of a fontName.
  14336. * - fontTexturePremulAlpha: set true if the BitmapFontTexture use premultiplied alpha, default is false
  14337. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  14338. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  14339. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  14340. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  14341. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  14342. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  14343. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  14344. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  14345. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  14346. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  14347. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14348. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14349. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14350. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14351. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  14352. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  14353. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  14354. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  14355. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14356. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14357. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14358. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14359. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  14360. * - textAlignmentH: align text horizontally (Text2D.AlignLeft, Text2D.AlignCenter, Text2D.AlignRight)
  14361. * - textAlignmentV: align text vertically (Text2D.AlignTop, Text2D.AlignCenter, Text2D.AlignBottom)
  14362. * - textAlignment: a string defining the text alignment, text can be: [<h:|horizontal:><left|right|center>], [<v:|vertical:><top|bottom|center>]
  14363. * - wordWrap: if true the text will wrap inside content area
  14364. */
  14365. function Text2D(text, settings) {
  14366. var _this;
  14367. if (!settings) {
  14368. settings = {};
  14369. }
  14370. _this = _super.call(this, settings) || this;
  14371. if (settings.bitmapFontTexture != null) {
  14372. _this._fontTexture = settings.bitmapFontTexture;
  14373. _this._fontName = null;
  14374. _this._fontSuperSample = false;
  14375. _this._fontSDF = false;
  14376. var ft = _this._fontTexture;
  14377. if (ft != null && !ft.isReady()) {
  14378. ft.onLoadObservable.add(function () {
  14379. _this._positioningDirty();
  14380. _this._setLayoutDirty();
  14381. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId; // To make sure the Text2D is issued again for render
  14382. });
  14383. }
  14384. }
  14385. else {
  14386. _this._fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  14387. _this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  14388. _this._fontSDF = (settings.fontSignedDistanceField != null && settings.fontSignedDistanceField);
  14389. }
  14390. _this._defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor.clone();
  14391. _this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  14392. _this._textureIsPremulAlpha = settings.fontTexturePremulAlpha === true;
  14393. _this._textSize = null;
  14394. _this.text = text;
  14395. if (settings.size != null) {
  14396. _this.size = settings.size;
  14397. _this._sizeSetByUser = true;
  14398. }
  14399. else {
  14400. _this.size = null;
  14401. }
  14402. _this.textAlignmentH = (settings.textAlignmentH == null) ? Text2D_1.AlignLeft : settings.textAlignmentH;
  14403. _this.textAlignmentV = (settings.textAlignmentV == null) ? Text2D_1.AlignTop : settings.textAlignmentV;
  14404. _this.textAlignment = (settings.textAlignment == null) ? "" : settings.textAlignment;
  14405. _this._wordWrap = (settings.wordWrap == null) ? false : settings.wordWrap;
  14406. _this._updateRenderMode();
  14407. return _this;
  14408. }
  14409. Object.defineProperty(Text2D, "AlignLeft", {
  14410. /**
  14411. * Alignment is made relative to the left edge of the Content Area. Valid for horizontal alignment only.
  14412. */
  14413. get: function () { return Text2D_1._AlignLeft; },
  14414. enumerable: true,
  14415. configurable: true
  14416. });
  14417. Object.defineProperty(Text2D, "AlignTop", {
  14418. /**
  14419. * Alignment is made relative to the top edge of the Content Area. Valid for vertical alignment only.
  14420. */
  14421. get: function () { return Text2D_1._AlignTop; },
  14422. enumerable: true,
  14423. configurable: true
  14424. });
  14425. Object.defineProperty(Text2D, "AlignRight", {
  14426. /**
  14427. * Alignment is made relative to the right edge of the Content Area. Valid for horizontal alignment only.
  14428. */
  14429. get: function () { return Text2D_1._AlignRight; },
  14430. enumerable: true,
  14431. configurable: true
  14432. });
  14433. Object.defineProperty(Text2D, "AlignBottom", {
  14434. /**
  14435. * Alignment is made relative to the bottom edge of the Content Area. Valid for vertical alignment only.
  14436. */
  14437. get: function () { return Text2D_1._AlignBottom; },
  14438. enumerable: true,
  14439. configurable: true
  14440. });
  14441. Object.defineProperty(Text2D, "AlignCenter", {
  14442. /**
  14443. * Alignment is made to center the text from equal distance to the opposite edges of the Content Area
  14444. */
  14445. get: function () { return Text2D_1._AlignCenter; },
  14446. enumerable: true,
  14447. configurable: true
  14448. });
  14449. Object.defineProperty(Text2D.prototype, "fontName", {
  14450. get: function () {
  14451. return this._fontName;
  14452. },
  14453. set: function (value) {
  14454. if (this._fontName) {
  14455. throw new Error("Font Name change is not supported right now.");
  14456. }
  14457. this._fontName = value;
  14458. },
  14459. enumerable: true,
  14460. configurable: true
  14461. });
  14462. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  14463. get: function () {
  14464. return this._defaultFontColor;
  14465. },
  14466. set: function (value) {
  14467. if (!this._defaultFontColor) {
  14468. this._defaultFontColor = value.clone();
  14469. }
  14470. else {
  14471. this._defaultFontColor.copyFrom(value);
  14472. }
  14473. },
  14474. enumerable: true,
  14475. configurable: true
  14476. });
  14477. Object.defineProperty(Text2D.prototype, "text", {
  14478. get: function () {
  14479. return this._text;
  14480. },
  14481. set: function (value) {
  14482. if (!value) {
  14483. value = "";
  14484. }
  14485. this._text = value;
  14486. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  14487. if (!this._sizeSetByUser) {
  14488. this._size = null;
  14489. }
  14490. this._updateCharCount();
  14491. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  14492. var s = this.textSize;
  14493. },
  14494. enumerable: true,
  14495. configurable: true
  14496. });
  14497. Object.defineProperty(Text2D.prototype, "size", {
  14498. get: function () {
  14499. if (this._size != null) {
  14500. return this._size;
  14501. }
  14502. return this.textSize;
  14503. },
  14504. set: function (value) {
  14505. this.internalSetSize(value);
  14506. },
  14507. enumerable: true,
  14508. configurable: true
  14509. });
  14510. Object.defineProperty(Text2D.prototype, "fontSuperSample", {
  14511. get: function () {
  14512. return this._fontTexture && this._fontTexture.isSuperSampled;
  14513. },
  14514. enumerable: true,
  14515. configurable: true
  14516. });
  14517. Object.defineProperty(Text2D.prototype, "fontSignedDistanceField", {
  14518. get: function () {
  14519. return this._fontTexture && this._fontTexture.isSignedDistanceField;
  14520. },
  14521. enumerable: true,
  14522. configurable: true
  14523. });
  14524. Object.defineProperty(Text2D.prototype, "textureIsPremulAlpha", {
  14525. get: function () {
  14526. return this._textureIsPremulAlpha;
  14527. },
  14528. set: function (value) {
  14529. this._textureIsPremulAlpha = value;
  14530. },
  14531. enumerable: true,
  14532. configurable: true
  14533. });
  14534. Object.defineProperty(Text2D.prototype, "isSizeAuto", {
  14535. get: function () {
  14536. return false;
  14537. },
  14538. enumerable: true,
  14539. configurable: true
  14540. });
  14541. Object.defineProperty(Text2D.prototype, "isVerticalSizeAuto", {
  14542. get: function () {
  14543. return false;
  14544. },
  14545. enumerable: true,
  14546. configurable: true
  14547. });
  14548. Object.defineProperty(Text2D.prototype, "isHorizontalSizeAuto", {
  14549. get: function () {
  14550. return false;
  14551. },
  14552. enumerable: true,
  14553. configurable: true
  14554. });
  14555. Object.defineProperty(Text2D.prototype, "textSize", {
  14556. /**
  14557. * Get the area that bounds the text associated to the primitive
  14558. */
  14559. get: function () {
  14560. if (!this._textSize) {
  14561. if (this.owner && this._text) {
  14562. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  14563. if (!newSize.equals(this._textSize)) {
  14564. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  14565. this._positioningDirty();
  14566. }
  14567. this._textSize = newSize;
  14568. }
  14569. else {
  14570. return Text2D_1.nullSize;
  14571. }
  14572. }
  14573. return this._textSize;
  14574. },
  14575. enumerable: true,
  14576. configurable: true
  14577. });
  14578. Text2D.prototype.onSetOwner = function () {
  14579. if (!this._textSize) {
  14580. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  14581. this._setLayoutDirty();
  14582. this._positioningDirty();
  14583. this._actualSize = null;
  14584. }
  14585. };
  14586. Object.defineProperty(Text2D.prototype, "fontTexture", {
  14587. get: function () {
  14588. if (this._fontTexture) {
  14589. return this._fontTexture;
  14590. }
  14591. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  14592. return null;
  14593. }
  14594. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  14595. return this._fontTexture;
  14596. },
  14597. enumerable: true,
  14598. configurable: true
  14599. });
  14600. /**
  14601. * Dispose the primitive, remove it from its parent
  14602. */
  14603. Text2D.prototype.dispose = function () {
  14604. if (!_super.prototype.dispose.call(this)) {
  14605. return false;
  14606. }
  14607. if (this._fontTexture) {
  14608. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  14609. this._fontTexture = null;
  14610. }
  14611. return true;
  14612. };
  14613. Text2D.prototype.updateLevelBoundingInfo = function () {
  14614. if (!this.owner || !this._text) {
  14615. return false;
  14616. }
  14617. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  14618. return true;
  14619. };
  14620. Object.defineProperty(Text2D.prototype, "textAlignment", {
  14621. /**
  14622. * You can get/set the text alignment through this property
  14623. */
  14624. get: function () {
  14625. return this._textAlignment;
  14626. },
  14627. set: function (value) {
  14628. this._textAlignment = value;
  14629. this._setTextAlignmentfromString(value);
  14630. },
  14631. enumerable: true,
  14632. configurable: true
  14633. });
  14634. Text2D.prototype.levelIntersect = function (intersectInfo) {
  14635. // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
  14636. return true;
  14637. };
  14638. Text2D.prototype.createModelRenderCache = function (modelKey) {
  14639. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  14640. return renderCache;
  14641. };
  14642. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  14643. var renderCache = modelRenderCache;
  14644. var engine = this.owner.engine;
  14645. renderCache.fontTexture = this.fontTexture;
  14646. renderCache.fontTexture.incCachedFontTextureCounter();
  14647. renderCache.fontPremulAlpha = this.textureIsPremulAlpha;
  14648. var vb = new Float32Array(4);
  14649. for (var i = 0; i < 4; i++) {
  14650. vb[i] = i;
  14651. }
  14652. renderCache.vb = engine.createVertexBuffer(vb);
  14653. var ib = new Float32Array(6);
  14654. ib[0] = 0;
  14655. ib[1] = 2;
  14656. ib[2] = 1;
  14657. ib[3] = 0;
  14658. ib[4] = 3;
  14659. ib[5] = 2;
  14660. renderCache.ib = engine.createIndexBuffer(ib);
  14661. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  14662. var ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, true);
  14663. if (ei) {
  14664. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  14665. }
  14666. ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, false);
  14667. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  14668. return renderCache;
  14669. };
  14670. Text2D.prototype.createInstanceDataParts = function () {
  14671. return [new Text2DInstanceData(Text2D_1.TEXT2D_MAINPARTID, this._charCount)];
  14672. };
  14673. // Looks like a hack!? Yes! Because that's what it is!
  14674. // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
  14675. // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
  14676. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  14677. if (!this._charCount) {
  14678. var curText = this._text;
  14679. this.text = "A";
  14680. return curText;
  14681. }
  14682. };
  14683. // if obj contains something, we restore the _text property
  14684. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  14685. if (obj !== undefined) {
  14686. this.text = obj;
  14687. }
  14688. };
  14689. Text2D.prototype.getUsedShaderCategories = function (dataPart) {
  14690. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  14691. if (this._fontSDF) {
  14692. cat.push(Text2D_1.TEXT2D_CATEGORY_SDF);
  14693. }
  14694. if (this._fontTexture instanceof BABYLON.FontTexture) {
  14695. cat.push(Text2D_1.TEXT2D_CATEGORY_FONTTEXTURE);
  14696. }
  14697. return cat;
  14698. };
  14699. Text2D.prototype.refreshInstanceDataPart = function (part) {
  14700. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  14701. return false;
  14702. }
  14703. if (part.id === Text2D_1.TEXT2D_MAINPARTID) {
  14704. var d = part;
  14705. var texture = this.fontTexture;
  14706. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  14707. var ts = texture.getSize();
  14708. var offset = BABYLON.Vector2.Zero();
  14709. var lh = this.fontTexture.lineHeight;
  14710. d.dataElementCount = this._charCount;
  14711. d.curElement = 0;
  14712. var lineLengths = [];
  14713. var charWidths = [];
  14714. var charsPerLine = [];
  14715. var numCharsCurrenLine = 0;
  14716. var contentAreaWidth = this.contentArea.width;
  14717. var contentAreaHeight = this.contentArea.height;
  14718. var numCharsCurrentWord = 0;
  14719. var widthCurrentWord = 0;
  14720. var numWordsPerLine = 0;
  14721. var text = this.text;
  14722. var tabWidth = this._tabulationSize * texture.spaceWidth;
  14723. // First pass: analyze the text to build data like pixel length of each lines, width of each char, number of char per line
  14724. for (var i_1 = 0; i_1 < text.length; i_1++) {
  14725. var char = text[i_1];
  14726. numCharsCurrenLine++;
  14727. charWidths[i_1] = 0;
  14728. // Line feed
  14729. if (this._isWhiteSpaceCharVert(char)) {
  14730. lineLengths.push(offset.x);
  14731. charsPerLine.push(numCharsCurrenLine - 1);
  14732. numCharsCurrenLine = 1;
  14733. offset.x = 0;
  14734. if (widthCurrentWord > 0) {
  14735. numWordsPerLine++;
  14736. }
  14737. numWordsPerLine = 0;
  14738. numCharsCurrentWord = 0;
  14739. widthCurrentWord = 0;
  14740. continue;
  14741. }
  14742. var ci = texture.getChar(char);
  14743. var charWidth = 0;
  14744. if (char === "\t") {
  14745. charWidth = tabWidth;
  14746. }
  14747. else {
  14748. charWidth = ci.xAdvance;
  14749. }
  14750. offset.x += charWidth;
  14751. charWidths[i_1] = charWidth;
  14752. if (this._isWhiteSpaceCharHoriz(char)) {
  14753. if (widthCurrentWord > 0) {
  14754. numWordsPerLine++;
  14755. }
  14756. numCharsCurrentWord = 0;
  14757. widthCurrentWord = 0;
  14758. }
  14759. else {
  14760. widthCurrentWord += ci.xAdvance;
  14761. numCharsCurrentWord++;
  14762. }
  14763. if (this._wordWrap && numWordsPerLine > 0 && offset.x > contentAreaWidth) {
  14764. lineLengths.push(offset.x - widthCurrentWord);
  14765. numCharsCurrenLine -= numCharsCurrentWord;
  14766. var j = i_1 - numCharsCurrentWord;
  14767. //skip white space at the end of this line
  14768. while (this._isWhiteSpaceCharHoriz(text[j])) {
  14769. lineLengths[lineLengths.length - 1] -= charWidths[j];
  14770. j--;
  14771. }
  14772. charsPerLine.push(numCharsCurrenLine);
  14773. if (this._isWhiteSpaceCharHoriz(text[i_1])) {
  14774. //skip white space at the beginning of next line
  14775. var numSpaces = 0;
  14776. while (this._isWhiteSpaceCharHoriz(text[i_1 + numSpaces])) {
  14777. numSpaces++;
  14778. charWidths[i_1 + numSpaces] = 0;
  14779. }
  14780. i_1 += numSpaces - 1;
  14781. offset.x = 0;
  14782. numCharsCurrenLine = numSpaces - 1;
  14783. }
  14784. else {
  14785. numCharsCurrenLine = numCharsCurrentWord;
  14786. offset.x = widthCurrentWord;
  14787. }
  14788. numWordsPerLine = 0;
  14789. }
  14790. }
  14791. lineLengths.push(offset.x);
  14792. charsPerLine.push(numCharsCurrenLine);
  14793. //skip white space at the end
  14794. var i = text.length - 1;
  14795. while (this._isWhiteSpaceCharHoriz(text[i])) {
  14796. lineLengths[lineLengths.length - 1] -= charWidths[i];
  14797. i--;
  14798. }
  14799. var charNum = 0;
  14800. var maxLineLen = 0;
  14801. var alignH = this.textAlignmentH;
  14802. var alignV = this.textAlignmentV;
  14803. offset.x = 0;
  14804. if (alignH == Text2D_1.AlignRight || alignH == Text2D_1.AlignCenter) {
  14805. for (var i_2 = 0; i_2 < lineLengths.length; i_2++) {
  14806. if (lineLengths[i_2] > maxLineLen) {
  14807. maxLineLen = lineLengths[i_2];
  14808. }
  14809. }
  14810. }
  14811. var textHeight = lineLengths.length * lh;
  14812. var offsetX = this.padding.leftPixels;
  14813. if (alignH == Text2D_1.AlignRight) {
  14814. offsetX += contentAreaWidth - maxLineLen;
  14815. }
  14816. else if (alignH == Text2D_1.AlignCenter) {
  14817. offsetX += (contentAreaWidth - maxLineLen) * .5;
  14818. }
  14819. offset.x += offsetX;
  14820. offset.y += contentAreaHeight + textHeight - lh;
  14821. offset.y += this.padding.bottomPixels;
  14822. if (alignV == Text2D_1.AlignBottom) {
  14823. offset.y -= contentAreaHeight;
  14824. }
  14825. else if (alignV == Text2D_1.AlignCenter) {
  14826. offset.y -= (contentAreaHeight - textHeight) * .5 + lineLengths.length * lh;
  14827. }
  14828. else {
  14829. offset.y -= lineLengths.length * lh;
  14830. }
  14831. var lineHeight = texture.lineHeight;
  14832. for (var i_3 = 0; i_3 < lineLengths.length; i_3++) {
  14833. var numChars = charsPerLine[i_3];
  14834. var lineLength = lineLengths[i_3];
  14835. if (alignH == Text2D_1.AlignRight) {
  14836. offset.x += maxLineLen - lineLength;
  14837. }
  14838. else if (alignH == Text2D_1.AlignCenter) {
  14839. offset.x += (maxLineLen - lineLength) * .5;
  14840. }
  14841. for (var j = 0; j < numChars; j++) {
  14842. var char = text[charNum];
  14843. var charWidth = charWidths[charNum];
  14844. if (char !== "\t" && !this._isWhiteSpaceCharVert(char)) {
  14845. //make sure space char gets processed here or overlapping can occur when text is set
  14846. var ci = texture.getChar(char);
  14847. this.updateInstanceDataPart(d, new BABYLON.Vector2(offset.x + ci.xOffset, offset.y + ci.yOffset));
  14848. d.topLeftUV = ci.topLeftUV;
  14849. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  14850. d.sizeUV = suv;
  14851. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  14852. d.color = this.defaultFontColor;
  14853. d.superSampleFactor = superSampleFactor;
  14854. ++d.curElement;
  14855. }
  14856. offset.x += charWidth;
  14857. charNum++;
  14858. }
  14859. offset.x = offsetX;
  14860. offset.y -= lineHeight;
  14861. }
  14862. }
  14863. return true;
  14864. };
  14865. Text2D.prototype._isWhiteSpaceCharHoriz = function (char) {
  14866. if (char === " " || char === "\t") {
  14867. return true;
  14868. }
  14869. };
  14870. Text2D.prototype._isWhiteSpaceCharVert = function (char) {
  14871. if (char === "\n" || char === "\r") {
  14872. return true;
  14873. }
  14874. };
  14875. Text2D.prototype._updateCharCount = function () {
  14876. var count = 0;
  14877. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  14878. var char = _a[_i];
  14879. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  14880. continue;
  14881. }
  14882. ++count;
  14883. }
  14884. this._charCount = count;
  14885. };
  14886. Text2D.prototype._setTextAlignmentfromString = function (value) {
  14887. var m = value.trim().split(",");
  14888. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  14889. var v = m_1[_i];
  14890. v = v.toLocaleLowerCase().trim();
  14891. // Horizontal
  14892. var i = v.indexOf("h:");
  14893. if (i === -1) {
  14894. i = v.indexOf("horizontal:");
  14895. }
  14896. if (i !== -1) {
  14897. v = v.substr(v.indexOf(":") + 1);
  14898. this._setTextAlignmentHorizontal(v);
  14899. continue;
  14900. }
  14901. // Vertical
  14902. i = v.indexOf("v:");
  14903. if (i === -1) {
  14904. i = v.indexOf("vertical:");
  14905. }
  14906. if (i !== -1) {
  14907. v = v.substr(v.indexOf(":") + 1);
  14908. this._setTextAlignmentVertical(v);
  14909. continue;
  14910. }
  14911. }
  14912. };
  14913. Text2D.prototype._setTextAlignmentHorizontal = function (text) {
  14914. var v = text.trim().toLocaleLowerCase();
  14915. switch (v) {
  14916. case "left":
  14917. this.textAlignmentH = Text2D_1.AlignLeft;
  14918. return;
  14919. case "right":
  14920. this.textAlignmentH = Text2D_1.AlignRight;
  14921. return;
  14922. case "center":
  14923. this.textAlignmentH = Text2D_1.AlignCenter;
  14924. return;
  14925. }
  14926. };
  14927. Text2D.prototype._setTextAlignmentVertical = function (text) {
  14928. var v = text.trim().toLocaleLowerCase();
  14929. switch (v) {
  14930. case "top":
  14931. this.textAlignmentV = Text2D_1.AlignTop;
  14932. return;
  14933. case "bottom":
  14934. this.textAlignmentV = Text2D_1.AlignBottom;
  14935. return;
  14936. case "center":
  14937. this.textAlignmentV = Text2D_1.AlignCenter;
  14938. return;
  14939. }
  14940. };
  14941. Text2D.prototype._useTextureAlpha = function () {
  14942. return this._fontSDF;
  14943. };
  14944. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  14945. return !this._fontSDF;
  14946. };
  14947. return Text2D;
  14948. }(BABYLON.RenderablePrim2D));
  14949. Text2D.TEXT2D_MAINPARTID = 1;
  14950. Text2D.TEXT2D_CATEGORY_SDF = "SignedDistanceField";
  14951. Text2D.TEXT2D_CATEGORY_FONTTEXTURE = "FontTexture";
  14952. Text2D._AlignLeft = 1;
  14953. Text2D._AlignTop = 1; // Same as left
  14954. Text2D._AlignRight = 2;
  14955. Text2D._AlignBottom = 2; // Same as right
  14956. Text2D._AlignCenter = 3;
  14957. __decorate([
  14958. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D_1.fontProperty = pi; }, false, true)
  14959. ], Text2D.prototype, "fontName", null);
  14960. __decorate([
  14961. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D_1.defaultFontColorProperty = pi; })
  14962. ], Text2D.prototype, "defaultFontColor", null);
  14963. __decorate([
  14964. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D_1.textProperty = pi; }, false, true)
  14965. ], Text2D.prototype, "text", null);
  14966. __decorate([
  14967. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D_1.sizeProperty = pi; })
  14968. ], Text2D.prototype, "size", null);
  14969. __decorate([
  14970. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  14971. ], Text2D.prototype, "fontSuperSample", null);
  14972. __decorate([
  14973. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D_1.fontSignedDistanceFieldProperty = pi; }, false, false)
  14974. ], Text2D.prototype, "fontSignedDistanceField", null);
  14975. __decorate([
  14976. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Text2D_1.textureIsPremulAlphaProperty = pi; })
  14977. ], Text2D.prototype, "textureIsPremulAlpha", null);
  14978. Text2D = Text2D_1 = __decorate([
  14979. BABYLON.className("Text2D", "BABYLON")
  14980. ], Text2D);
  14981. BABYLON.Text2D = Text2D;
  14982. var Text2D_1;
  14983. })(BABYLON || (BABYLON = {}));
  14984. var __extends = (this && this.__extends) || function (d, b) {
  14985. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14986. function __() { this.constructor = d; }
  14987. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14988. };
  14989. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  14990. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  14991. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14992. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  14993. return c > 3 && r && Object.defineProperty(target, key, r), r;
  14994. };
  14995. var BABYLON;
  14996. (function (BABYLON) {
  14997. var Lines2DRenderCache = (function (_super) {
  14998. __extends(Lines2DRenderCache, _super);
  14999. function Lines2DRenderCache(engine, modelKey) {
  15000. var _this = _super.call(this, engine, modelKey) || this;
  15001. _this.effectsReady = false;
  15002. _this.fillVB = null;
  15003. _this.fillIB = null;
  15004. _this.fillIndicesCount = 0;
  15005. _this.instancingFillAttributes = null;
  15006. _this.effectFill = null;
  15007. _this.effectFillInstanced = null;
  15008. _this.borderVB = null;
  15009. _this.borderIB = null;
  15010. _this.borderIndicesCount = 0;
  15011. _this.instancingBorderAttributes = null;
  15012. _this.effectBorder = null;
  15013. _this.effectBorderInstanced = null;
  15014. return _this;
  15015. }
  15016. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  15017. // Do nothing if the shader is still loading/preparing
  15018. if (!this.effectsReady) {
  15019. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  15020. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  15021. return false;
  15022. }
  15023. this.effectsReady = true;
  15024. }
  15025. var canvas = instanceInfo.owner.owner;
  15026. var engine = canvas.engine;
  15027. engine.setState(false, undefined, true);
  15028. var depthFunction = 0;
  15029. if (this.effectFill && this.effectBorder) {
  15030. depthFunction = engine.getDepthFunction();
  15031. engine.setDepthFunctionToLessOrEqual();
  15032. }
  15033. var curAlphaMode = engine.getAlphaMode();
  15034. if (this.effectFill) {
  15035. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  15036. var pid = context.groupInfoPartData[partIndex];
  15037. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  15038. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  15039. }
  15040. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  15041. engine.enableEffect(effect);
  15042. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  15043. if (context.useInstancing) {
  15044. if (!this.instancingFillAttributes) {
  15045. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  15046. }
  15047. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  15048. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  15049. canvas._addDrawCallCount(1, context.renderMode);
  15050. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  15051. engine.draw(true, 0, this.fillIndicesCount, count);
  15052. engine.unbindInstanceAttributes();
  15053. }
  15054. else {
  15055. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  15056. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  15057. this.setupUniforms(effect, partIndex, pid._partData, i);
  15058. engine.draw(true, 0, this.fillIndicesCount);
  15059. }
  15060. }
  15061. }
  15062. if (this.effectBorder) {
  15063. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  15064. var pid = context.groupInfoPartData[partIndex];
  15065. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  15066. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  15067. }
  15068. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  15069. engine.enableEffect(effect);
  15070. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  15071. if (context.useInstancing) {
  15072. if (!this.instancingBorderAttributes) {
  15073. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  15074. }
  15075. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  15076. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  15077. canvas._addDrawCallCount(1, context.renderMode);
  15078. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  15079. engine.draw(true, 0, this.borderIndicesCount, count);
  15080. engine.unbindInstanceAttributes();
  15081. }
  15082. else {
  15083. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  15084. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  15085. this.setupUniforms(effect, partIndex, pid._partData, i);
  15086. engine.draw(true, 0, this.borderIndicesCount);
  15087. }
  15088. }
  15089. }
  15090. engine.setAlphaMode(curAlphaMode, true);
  15091. if (this.effectFill && this.effectBorder) {
  15092. engine.setDepthFunction(depthFunction);
  15093. }
  15094. return true;
  15095. };
  15096. Lines2DRenderCache.prototype.dispose = function () {
  15097. if (!_super.prototype.dispose.call(this)) {
  15098. return false;
  15099. }
  15100. if (this.fillVB) {
  15101. this._engine._releaseBuffer(this.fillVB);
  15102. this.fillVB = null;
  15103. }
  15104. if (this.fillIB) {
  15105. this._engine._releaseBuffer(this.fillIB);
  15106. this.fillIB = null;
  15107. }
  15108. this.effectFill = null;
  15109. this.effectFillInstanced = null;
  15110. this.effectBorder = null;
  15111. this.effectBorderInstanced = null;
  15112. if (this.borderVB) {
  15113. this._engine._releaseBuffer(this.borderVB);
  15114. this.borderVB = null;
  15115. }
  15116. if (this.borderIB) {
  15117. this._engine._releaseBuffer(this.borderIB);
  15118. this.borderIB = null;
  15119. }
  15120. return true;
  15121. };
  15122. return Lines2DRenderCache;
  15123. }(BABYLON.ModelRenderCache));
  15124. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  15125. var Lines2DInstanceData = (function (_super) {
  15126. __extends(Lines2DInstanceData, _super);
  15127. function Lines2DInstanceData(partId) {
  15128. return _super.call(this, partId, 1) || this;
  15129. }
  15130. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  15131. get: function () {
  15132. return null;
  15133. },
  15134. set: function (value) {
  15135. },
  15136. enumerable: true,
  15137. configurable: true
  15138. });
  15139. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  15140. get: function () {
  15141. return null;
  15142. },
  15143. set: function (value) {
  15144. },
  15145. enumerable: true,
  15146. configurable: true
  15147. });
  15148. return Lines2DInstanceData;
  15149. }(BABYLON.Shape2DInstanceData));
  15150. __decorate([
  15151. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  15152. ], Lines2DInstanceData.prototype, "boundingMin", null);
  15153. __decorate([
  15154. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  15155. ], Lines2DInstanceData.prototype, "boundingMax", null);
  15156. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  15157. var Lines2D = Lines2D_1 = (function (_super) {
  15158. __extends(Lines2D, _super);
  15159. /**
  15160. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  15161. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  15162. * @param settings a combination of settings, possible ones are
  15163. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  15164. * - children: an array of direct children
  15165. * - id a text identifier, for information purpose
  15166. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  15167. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  15168. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  15169. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  15170. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  15171. * - zOrder: override the zOrder with the specified value
  15172. * - origin: define the normalized origin point location, default [0.5;0.5]
  15173. * - fillThickness: the thickness of the fill part of the line, can be null to draw nothing (but a border brush must be given), default is 1.
  15174. * - closed: if false the lines are said to be opened, the first point and the latest DON'T connect. if true the lines are said to be closed, the first and last point will be connected by a line. For instance you can define the 4 points of a rectangle, if you set closed to true a 4 edges rectangle will be drawn. If you set false, only three edges will be drawn, the edge formed by the first and last point won't exist. Default is false.
  15175. * - startCap: Draw a cap of the given type at the start of the first line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  15176. * - endCap: Draw a cap of the given type at the end of the last line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  15177. * - fill: the brush used to draw the fill content of the lines, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can be a string value (see Canvas2D.GetBrushFromString)
  15178. * - border: the brush used to draw the border of the lines, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  15179. * - borderThickness: the thickness of the drawn border, default is 1.
  15180. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  15181. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  15182. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  15183. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  15184. * - levelCollision: this primitive is an actor of the Collision Manager and only this level will be used for collision (i.e. not the children). Use deepCollision if you want collision detection on the primitives and its children.
  15185. * - deepCollision: this primitive is an actor of the Collision Manager, this level AND ALSO its children will be used for collision (note: you don't need to set the children as level/deepCollision).
  15186. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  15187. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15188. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15189. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15190. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15191. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  15192. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  15193. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  15194. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  15195. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15196. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15197. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15198. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15199. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  15200. */
  15201. function Lines2D(points, settings) {
  15202. var _this;
  15203. if (!settings) {
  15204. settings = {};
  15205. }
  15206. _this = _super.call(this, settings) || this;
  15207. _this._fillVB = null;
  15208. _this._fillIB = null;
  15209. _this._borderVB = null;
  15210. _this._borderIB = null;
  15211. _this._size = BABYLON.Size.Zero();
  15212. _this._boundingMin = null;
  15213. _this._boundingMax = null;
  15214. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  15215. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  15216. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  15217. var closed = (settings.closed == null) ? false : settings.closed;
  15218. _this.points = points;
  15219. _this.fillThickness = fillThickness;
  15220. _this.startCap = startCap;
  15221. _this.endCap = endCap;
  15222. _this.closed = closed;
  15223. return _this;
  15224. }
  15225. Object.defineProperty(Lines2D, "NoCap", {
  15226. /**
  15227. * No Cap to apply on the extremity
  15228. */
  15229. get: function () { return Lines2D_1._noCap; },
  15230. enumerable: true,
  15231. configurable: true
  15232. });
  15233. Object.defineProperty(Lines2D, "RoundCap", {
  15234. /**
  15235. * A round cap, will use the line thickness as diameter
  15236. */
  15237. get: function () { return Lines2D_1._roundCap; },
  15238. enumerable: true,
  15239. configurable: true
  15240. });
  15241. Object.defineProperty(Lines2D, "TriangleCap", {
  15242. /**
  15243. * Creates a triangle at the extremity.
  15244. */
  15245. get: function () { return Lines2D_1._triangleCap; },
  15246. enumerable: true,
  15247. configurable: true
  15248. });
  15249. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  15250. /**
  15251. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  15252. */
  15253. get: function () { return Lines2D_1._squareAnchorCap; },
  15254. enumerable: true,
  15255. configurable: true
  15256. });
  15257. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  15258. /**
  15259. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  15260. */
  15261. get: function () { return Lines2D_1._roundAnchorCap; },
  15262. enumerable: true,
  15263. configurable: true
  15264. });
  15265. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  15266. /**
  15267. * Creates a diamond anchor at the extremity.
  15268. */
  15269. get: function () { return Lines2D_1._diamondAnchorCap; },
  15270. enumerable: true,
  15271. configurable: true
  15272. });
  15273. Object.defineProperty(Lines2D, "ArrowCap", {
  15274. /**
  15275. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  15276. */
  15277. get: function () { return Lines2D_1._arrowCap; },
  15278. enumerable: true,
  15279. configurable: true
  15280. });
  15281. Object.defineProperty(Lines2D.prototype, "points", {
  15282. get: function () {
  15283. return this._points;
  15284. },
  15285. set: function (value) {
  15286. this._points = value;
  15287. this._primTriArrayDirty = true;
  15288. this._boundingBoxDirty();
  15289. },
  15290. enumerable: true,
  15291. configurable: true
  15292. });
  15293. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  15294. get: function () {
  15295. return this._fillThickness;
  15296. },
  15297. set: function (value) {
  15298. this._fillThickness = value;
  15299. },
  15300. enumerable: true,
  15301. configurable: true
  15302. });
  15303. Object.defineProperty(Lines2D.prototype, "closed", {
  15304. get: function () {
  15305. return this._closed;
  15306. },
  15307. set: function (value) {
  15308. this._closed = value;
  15309. },
  15310. enumerable: true,
  15311. configurable: true
  15312. });
  15313. Object.defineProperty(Lines2D.prototype, "startCap", {
  15314. get: function () {
  15315. return this._startCap;
  15316. },
  15317. set: function (value) {
  15318. this._startCap = value;
  15319. },
  15320. enumerable: true,
  15321. configurable: true
  15322. });
  15323. Object.defineProperty(Lines2D.prototype, "endCap", {
  15324. get: function () {
  15325. return this._endCap;
  15326. },
  15327. set: function (value) {
  15328. this._endCap = value;
  15329. },
  15330. enumerable: true,
  15331. configurable: true
  15332. });
  15333. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  15334. var p = intersectInfo._localPickPosition;
  15335. this.updateTriArray();
  15336. return this._primTriArray.doesContain(p);
  15337. };
  15338. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  15339. get: function () {
  15340. if (!this._boundingMin) {
  15341. this._computeLines2D();
  15342. }
  15343. return this._boundingMin;
  15344. },
  15345. enumerable: true,
  15346. configurable: true
  15347. });
  15348. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  15349. get: function () {
  15350. if (!this._boundingMax) {
  15351. this._computeLines2D();
  15352. }
  15353. return this._boundingMax;
  15354. },
  15355. enumerable: true,
  15356. configurable: true
  15357. });
  15358. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  15359. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  15360. // Remove the BORDER category, we don't use it in the VertexShader
  15361. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  15362. if (i !== -1) {
  15363. res.splice(i, 1);
  15364. }
  15365. return res;
  15366. };
  15367. Lines2D.prototype.updateLevelBoundingInfo = function () {
  15368. if (!this._size) {
  15369. return false;
  15370. }
  15371. if (!this._boundingMin) {
  15372. this._computeLines2D();
  15373. }
  15374. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  15375. return true;
  15376. };
  15377. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  15378. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  15379. return renderCache;
  15380. };
  15381. ///////////////////////////////////////////////////////////////////////////////////
  15382. // Methods for Lines building
  15383. Lines2D.prototype._perp = function (v, res) {
  15384. res.x = v.y;
  15385. res.y = -v.x;
  15386. };
  15387. ;
  15388. Lines2D.prototype._direction = function (a, b, res) {
  15389. a.subtractToRef(b, res);
  15390. res.normalize();
  15391. };
  15392. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  15393. a.addToRef(b, tangent);
  15394. tangent.normalize();
  15395. miter.x = -tangent.y;
  15396. miter.y = tangent.x;
  15397. Lines2D_1._miterTps.x = -a.y;
  15398. Lines2D_1._miterTps.y = a.x;
  15399. return 1 / BABYLON.Vector2.Dot(miter, Lines2D_1._miterTps);
  15400. };
  15401. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  15402. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  15403. if (d === 0)
  15404. return false;
  15405. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  15406. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  15407. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  15408. return false;
  15409. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  15410. return false;
  15411. return true;
  15412. };
  15413. Lines2D.prototype._updateMinMax = function (array, offset) {
  15414. if (offset >= array.length) {
  15415. return;
  15416. }
  15417. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  15418. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  15419. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  15420. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  15421. };
  15422. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  15423. var borderMode = borderThickness != null && !isNaN(borderThickness);
  15424. var off = index * (borderMode ? 8 : 4);
  15425. // Mandatory because we'll be out of bound in case of closed line, for the very last point (which is a duplicate of the first that we don't store in the vb)
  15426. if (off >= array.length) {
  15427. return;
  15428. }
  15429. // Store start/end normal, we need it for the cap construction
  15430. if (index === 0) {
  15431. this._perp(n, Lines2D_1._startDir);
  15432. }
  15433. else if (index === max - 1) {
  15434. this._perp(n, Lines2D_1._endDir);
  15435. Lines2D_1._endDir.x *= -1;
  15436. Lines2D_1._endDir.y *= -1;
  15437. }
  15438. var swap = false;
  15439. array[off + 0] = p.x + n.x * halfThickness;
  15440. array[off + 1] = p.y + n.y * halfThickness;
  15441. array[off + 2] = p.x + n.x * -halfThickness;
  15442. array[off + 3] = p.y + n.y * -halfThickness;
  15443. this._updateMinMax(array, off);
  15444. this._updateMinMax(array, off + 2);
  15445. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  15446. // It should not be the case, they should be parallel, so if they cross, we switch the order of storage to ensure we'll have parallel lines
  15447. if (detectFlip != 0) {
  15448. // Flip if intersect
  15449. var flipOff = detectFlip * (borderMode ? 8 : 4);
  15450. if (this._intersect(array[off + 0], array[off + 1], array[flipOff + 0], array[flipOff + 1], array[off + 2], array[off + 3], array[flipOff + 2], array[flipOff + 3])) {
  15451. swap = true;
  15452. var tps = array[off + 0];
  15453. array[off + 0] = array[off + 2];
  15454. array[off + 2] = tps;
  15455. tps = array[off + 1];
  15456. array[off + 1] = array[off + 3];
  15457. array[off + 3] = tps;
  15458. }
  15459. }
  15460. if (borderMode) {
  15461. var t = halfThickness + borderThickness;
  15462. array[off + 4] = p.x + n.x * (swap ? -t : t);
  15463. array[off + 5] = p.y + n.y * (swap ? -t : t);
  15464. array[off + 6] = p.x + n.x * (swap ? t : -t);
  15465. array[off + 7] = p.y + n.y * (swap ? t : -t);
  15466. this._updateMinMax(array, off + 4);
  15467. this._updateMinMax(array, off + 6);
  15468. }
  15469. if (contour) {
  15470. off += borderMode ? 4 : 0;
  15471. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  15472. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  15473. }
  15474. };
  15475. Lines2D.prototype._getCapSize = function (type, border) {
  15476. if (border === void 0) { border = false; }
  15477. var sd = Lines2D_1._roundCapSubDiv;
  15478. // If no array given, we call this to get the size
  15479. var vbsize = 0, ibsize = 0;
  15480. switch (type) {
  15481. case Lines2D_1.NoCap:
  15482. {
  15483. // If the line is not close and we're computing border, we add the size to generate the edge border
  15484. if (!this.closed && border) {
  15485. vbsize = 4;
  15486. ibsize = 6;
  15487. }
  15488. else {
  15489. vbsize = ibsize = 0;
  15490. }
  15491. break;
  15492. }
  15493. case Lines2D_1.RoundCap:
  15494. {
  15495. if (border) {
  15496. vbsize = sd;
  15497. ibsize = (sd - 2) * 3;
  15498. }
  15499. else {
  15500. vbsize = (sd / 2) + 1;
  15501. ibsize = (sd / 2) * 3;
  15502. }
  15503. break;
  15504. }
  15505. case Lines2D_1.ArrowCap:
  15506. {
  15507. if (border) {
  15508. vbsize = 12;
  15509. ibsize = 24;
  15510. }
  15511. else {
  15512. vbsize = 3;
  15513. ibsize = 3;
  15514. }
  15515. break;
  15516. }
  15517. case Lines2D_1.TriangleCap:
  15518. {
  15519. if (border) {
  15520. vbsize = 6;
  15521. ibsize = 12;
  15522. }
  15523. else {
  15524. vbsize = 3;
  15525. ibsize = 3;
  15526. }
  15527. break;
  15528. }
  15529. case Lines2D_1.DiamondAnchorCap:
  15530. {
  15531. if (border) {
  15532. vbsize = 10;
  15533. ibsize = 24;
  15534. }
  15535. else {
  15536. vbsize = 5;
  15537. ibsize = 9;
  15538. }
  15539. break;
  15540. }
  15541. case Lines2D_1.SquareAnchorCap:
  15542. {
  15543. if (border) {
  15544. vbsize = 12;
  15545. ibsize = 30;
  15546. }
  15547. else {
  15548. vbsize = 4;
  15549. ibsize = 6;
  15550. }
  15551. break;
  15552. }
  15553. case Lines2D_1.RoundAnchorCap:
  15554. {
  15555. if (border) {
  15556. vbsize = sd * 2;
  15557. ibsize = (sd - 1) * 6;
  15558. }
  15559. else {
  15560. vbsize = sd + 1;
  15561. ibsize = (sd + 1) * 3;
  15562. }
  15563. break;
  15564. }
  15565. }
  15566. return { vbsize: vbsize * 2, ibsize: ibsize };
  15567. };
  15568. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  15569. var c = Math.cos(rotation);
  15570. var s = Math.sin(rotation);
  15571. Lines2D_1._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  15572. Lines2D_1._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  15573. var offset = baseOffset + (index * 2);
  15574. vb[offset + 0] = Lines2D_1._tpsV.x;
  15575. vb[offset + 1] = Lines2D_1._tpsV.y;
  15576. if (contour) {
  15577. contour.push(Lines2D_1._tpsV.x);
  15578. contour.push(Lines2D_1._tpsV.y);
  15579. }
  15580. this._updateMinMax(vb, offset);
  15581. return (baseOffset + index * 2) / 2;
  15582. };
  15583. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  15584. ib[baseOffset + index] = vertexIndex;
  15585. };
  15586. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  15587. // Compute the transformation from the direction of the cap to build relative to our default orientation [1;0] (our cap are by default pointing toward right, horizontal
  15588. var sd = Lines2D_1._roundCapSubDiv;
  15589. var dir = new BABYLON.Vector2(1, 0);
  15590. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  15591. var ht = thickness / 2;
  15592. var t = thickness;
  15593. var borderMode = borderThickness != null;
  15594. var bt = borderThickness;
  15595. switch (type) {
  15596. case Lines2D_1.NoCap:
  15597. if (borderMode && !this.closed) {
  15598. var vi = 0;
  15599. var ii = 0;
  15600. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  15601. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  15602. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  15603. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  15604. this._storeIndex(ib, ibi, ii++, v1);
  15605. this._storeIndex(ib, ibi, ii++, v2);
  15606. this._storeIndex(ib, ibi, ii++, v3);
  15607. this._storeIndex(ib, ibi, ii++, v1);
  15608. this._storeIndex(ib, ibi, ii++, v3);
  15609. this._storeIndex(ib, ibi, ii++, v4);
  15610. }
  15611. break;
  15612. case Lines2D_1.ArrowCap:
  15613. ht *= 2;
  15614. case Lines2D_1.TriangleCap:
  15615. {
  15616. if (borderMode) {
  15617. var f = type === Lines2D_1.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  15618. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  15619. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  15620. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  15621. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  15622. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  15623. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  15624. var ii = 0;
  15625. this._storeIndex(ib, ibi, ii++, v1);
  15626. this._storeIndex(ib, ibi, ii++, v4);
  15627. this._storeIndex(ib, ibi, ii++, v5);
  15628. this._storeIndex(ib, ibi, ii++, v1);
  15629. this._storeIndex(ib, ibi, ii++, v5);
  15630. this._storeIndex(ib, ibi, ii++, v2);
  15631. this._storeIndex(ib, ibi, ii++, v6);
  15632. this._storeIndex(ib, ibi, ii++, v3);
  15633. this._storeIndex(ib, ibi, ii++, v2);
  15634. this._storeIndex(ib, ibi, ii++, v6);
  15635. this._storeIndex(ib, ibi, ii++, v2);
  15636. this._storeIndex(ib, ibi, ii++, v5);
  15637. if (type === Lines2D_1.ArrowCap) {
  15638. var rht = thickness / 2;
  15639. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  15640. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  15641. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  15642. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  15643. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  15644. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  15645. this._storeIndex(ib, ibi, ii++, v7);
  15646. this._storeIndex(ib, ibi, ii++, v8);
  15647. this._storeIndex(ib, ibi, ii++, v9);
  15648. this._storeIndex(ib, ibi, ii++, v7);
  15649. this._storeIndex(ib, ibi, ii++, v9);
  15650. this._storeIndex(ib, ibi, ii++, v4);
  15651. this._storeIndex(ib, ibi, ii++, v10);
  15652. this._storeIndex(ib, ibi, ii++, v12);
  15653. this._storeIndex(ib, ibi, ii++, v11);
  15654. this._storeIndex(ib, ibi, ii++, v10);
  15655. this._storeIndex(ib, ibi, ii++, v6);
  15656. this._storeIndex(ib, ibi, ii++, v12);
  15657. }
  15658. }
  15659. else {
  15660. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  15661. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  15662. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  15663. this._storeIndex(ib, ibi, 0, v1);
  15664. this._storeIndex(ib, ibi, 1, v2);
  15665. this._storeIndex(ib, ibi, 2, v3);
  15666. }
  15667. break;
  15668. }
  15669. case Lines2D_1.RoundCap:
  15670. {
  15671. if (borderMode) {
  15672. var curA = -Math.PI / 2;
  15673. var incA = Math.PI / (sd / 2 - 1);
  15674. var ii = 0;
  15675. for (var i = 0; i < (sd / 2); i++) {
  15676. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  15677. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * (ht + bt), Math.sin(curA) * (ht + bt)), contour);
  15678. if (i > 0) {
  15679. this._storeIndex(ib, ibi, ii++, v1 - 2);
  15680. this._storeIndex(ib, ibi, ii++, v2 - 2);
  15681. this._storeIndex(ib, ibi, ii++, v2);
  15682. this._storeIndex(ib, ibi, ii++, v1 - 2);
  15683. this._storeIndex(ib, ibi, ii++, v2);
  15684. this._storeIndex(ib, ibi, ii++, v1);
  15685. }
  15686. curA += incA;
  15687. }
  15688. }
  15689. else {
  15690. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  15691. var curA = -Math.PI / 2;
  15692. var incA = Math.PI / (sd / 2 - 1);
  15693. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  15694. curA += incA;
  15695. for (var i = 1; i < (sd / 2); i++) {
  15696. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  15697. this._storeIndex(ib, ibi, i * 3 + 0, c);
  15698. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  15699. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  15700. curA += incA;
  15701. }
  15702. }
  15703. break;
  15704. }
  15705. case Lines2D_1.SquareAnchorCap:
  15706. {
  15707. var vi = 0;
  15708. var c = borderMode ? null : contour;
  15709. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  15710. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  15711. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  15712. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  15713. if (borderMode) {
  15714. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  15715. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  15716. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  15717. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  15718. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  15719. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  15720. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  15721. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  15722. var ii = 0;
  15723. this._storeIndex(ib, ibi, ii++, v6);
  15724. this._storeIndex(ib, ibi, ii++, v1);
  15725. this._storeIndex(ib, ibi, ii++, v5);
  15726. this._storeIndex(ib, ibi, ii++, v6);
  15727. this._storeIndex(ib, ibi, ii++, v7);
  15728. this._storeIndex(ib, ibi, ii++, v1);
  15729. this._storeIndex(ib, ibi, ii++, v1);
  15730. this._storeIndex(ib, ibi, ii++, v7);
  15731. this._storeIndex(ib, ibi, ii++, v8);
  15732. this._storeIndex(ib, ibi, ii++, v1);
  15733. this._storeIndex(ib, ibi, ii++, v8);
  15734. this._storeIndex(ib, ibi, ii++, v2);
  15735. this._storeIndex(ib, ibi, ii++, v2);
  15736. this._storeIndex(ib, ibi, ii++, v8);
  15737. this._storeIndex(ib, ibi, ii++, v9);
  15738. this._storeIndex(ib, ibi, ii++, v2);
  15739. this._storeIndex(ib, ibi, ii++, v9);
  15740. this._storeIndex(ib, ibi, ii++, v3);
  15741. this._storeIndex(ib, ibi, ii++, v3);
  15742. this._storeIndex(ib, ibi, ii++, v9);
  15743. this._storeIndex(ib, ibi, ii++, v10);
  15744. this._storeIndex(ib, ibi, ii++, v3);
  15745. this._storeIndex(ib, ibi, ii++, v10);
  15746. this._storeIndex(ib, ibi, ii++, v4);
  15747. this._storeIndex(ib, ibi, ii++, v10);
  15748. this._storeIndex(ib, ibi, ii++, v11);
  15749. this._storeIndex(ib, ibi, ii++, v4);
  15750. this._storeIndex(ib, ibi, ii++, v11);
  15751. this._storeIndex(ib, ibi, ii++, v12);
  15752. this._storeIndex(ib, ibi, ii++, v4);
  15753. }
  15754. else {
  15755. this._storeIndex(ib, ibi, 0, v1);
  15756. this._storeIndex(ib, ibi, 1, v2);
  15757. this._storeIndex(ib, ibi, 2, v3);
  15758. this._storeIndex(ib, ibi, 3, v1);
  15759. this._storeIndex(ib, ibi, 4, v3);
  15760. this._storeIndex(ib, ibi, 5, v4);
  15761. }
  15762. break;
  15763. }
  15764. case Lines2D_1.RoundAnchorCap:
  15765. {
  15766. var cpos = Math.sqrt(t * t - ht * ht);
  15767. var center = new BABYLON.Vector2(cpos, 0);
  15768. var curA = BABYLON.Tools.ToRadians(-150);
  15769. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  15770. if (borderMode) {
  15771. var ii = 0;
  15772. for (var i = 0; i < sd; i++) {
  15773. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  15774. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * (t + bt), Math.sin(curA) * (t + bt)), contour);
  15775. if (i > 0) {
  15776. this._storeIndex(ib, ibi, ii++, v1 - 2);
  15777. this._storeIndex(ib, ibi, ii++, v2 - 2);
  15778. this._storeIndex(ib, ibi, ii++, v2);
  15779. this._storeIndex(ib, ibi, ii++, v1 - 2);
  15780. this._storeIndex(ib, ibi, ii++, v2);
  15781. this._storeIndex(ib, ibi, ii++, v1);
  15782. }
  15783. curA += incA;
  15784. }
  15785. }
  15786. else {
  15787. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  15788. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  15789. curA += incA;
  15790. for (var i = 1; i < sd; i++) {
  15791. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  15792. this._storeIndex(ib, ibi, i * 3 + 0, c);
  15793. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  15794. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  15795. curA += incA;
  15796. }
  15797. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  15798. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  15799. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  15800. }
  15801. break;
  15802. }
  15803. case Lines2D_1.DiamondAnchorCap:
  15804. {
  15805. var vi = 0;
  15806. var c = borderMode ? null : contour;
  15807. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  15808. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  15809. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  15810. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  15811. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  15812. if (borderMode) {
  15813. var f = Math.sqrt(bt * bt * 2);
  15814. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  15815. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  15816. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  15817. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  15818. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  15819. var ii = 0;
  15820. this._storeIndex(ib, ibi, ii++, v6);
  15821. this._storeIndex(ib, ibi, ii++, v7);
  15822. this._storeIndex(ib, ibi, ii++, v1);
  15823. this._storeIndex(ib, ibi, ii++, v1);
  15824. this._storeIndex(ib, ibi, ii++, v7);
  15825. this._storeIndex(ib, ibi, ii++, v2);
  15826. this._storeIndex(ib, ibi, ii++, v2);
  15827. this._storeIndex(ib, ibi, ii++, v7);
  15828. this._storeIndex(ib, ibi, ii++, v8);
  15829. this._storeIndex(ib, ibi, ii++, v2);
  15830. this._storeIndex(ib, ibi, ii++, v8);
  15831. this._storeIndex(ib, ibi, ii++, v3);
  15832. this._storeIndex(ib, ibi, ii++, v3);
  15833. this._storeIndex(ib, ibi, ii++, v8);
  15834. this._storeIndex(ib, ibi, ii++, v9);
  15835. this._storeIndex(ib, ibi, ii++, v3);
  15836. this._storeIndex(ib, ibi, ii++, v9);
  15837. this._storeIndex(ib, ibi, ii++, v4);
  15838. this._storeIndex(ib, ibi, ii++, v4);
  15839. this._storeIndex(ib, ibi, ii++, v9);
  15840. this._storeIndex(ib, ibi, ii++, v10);
  15841. this._storeIndex(ib, ibi, ii++, v4);
  15842. this._storeIndex(ib, ibi, ii++, v10);
  15843. this._storeIndex(ib, ibi, ii++, v5);
  15844. }
  15845. else {
  15846. this._storeIndex(ib, ibi, 0, v1);
  15847. this._storeIndex(ib, ibi, 1, v2);
  15848. this._storeIndex(ib, ibi, 2, v3);
  15849. this._storeIndex(ib, ibi, 3, v1);
  15850. this._storeIndex(ib, ibi, 4, v3);
  15851. this._storeIndex(ib, ibi, 5, v5);
  15852. this._storeIndex(ib, ibi, 6, v5);
  15853. this._storeIndex(ib, ibi, 7, v3);
  15854. this._storeIndex(ib, ibi, 8, v4);
  15855. }
  15856. break;
  15857. }
  15858. }
  15859. return null;
  15860. };
  15861. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  15862. var lineA = BABYLON.Vector2.Zero();
  15863. var lineB = BABYLON.Vector2.Zero();
  15864. var tangent = BABYLON.Vector2.Zero();
  15865. var miter = BABYLON.Vector2.Zero();
  15866. var curNormal = null;
  15867. if (this.closed) {
  15868. this.points.push(this.points[0]);
  15869. }
  15870. var total = this.points.length;
  15871. for (var i = 1; i < total; i++) {
  15872. var last = this.points[i - 1];
  15873. var cur = this.points[i];
  15874. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  15875. this._direction(cur, last, lineA);
  15876. if (!curNormal) {
  15877. curNormal = BABYLON.Vector2.Zero();
  15878. this._perp(lineA, curNormal);
  15879. }
  15880. if (i === 1) {
  15881. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  15882. }
  15883. if (!next) {
  15884. this._perp(lineA, curNormal);
  15885. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  15886. }
  15887. else {
  15888. this._direction(next, cur, lineB);
  15889. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  15890. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  15891. }
  15892. }
  15893. if (this.points.length > 2 && this.closed) {
  15894. var last2 = this.points[total - 2];
  15895. var cur2 = this.points[0];
  15896. var next2 = this.points[1];
  15897. this._direction(cur2, last2, lineA);
  15898. this._direction(next2, cur2, lineB);
  15899. this._perp(lineA, curNormal);
  15900. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  15901. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  15902. // Patch contour
  15903. if (contour) {
  15904. var off = (bt == null) ? 0 : 4;
  15905. contour[0].x = vb[off + 0];
  15906. contour[0].y = vb[off + 1];
  15907. contour[1].x = vb[off + 2];
  15908. contour[1].y = vb[off + 3];
  15909. }
  15910. }
  15911. // Remove the point we added at the beginning
  15912. if (this.closed) {
  15913. this.points.splice(total - 1);
  15914. }
  15915. };
  15916. // Methods for Lines building
  15917. ///////////////////////////////////////////////////////////////////////////////////
  15918. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  15919. var renderCache = modelRenderCache;
  15920. var engine = this.owner.engine;
  15921. if (this._fillVB === null) {
  15922. this._computeLines2D();
  15923. }
  15924. // Need to create WebGL resources for fill part?
  15925. if (this.fill) {
  15926. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  15927. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  15928. renderCache.fillIndicesCount = this._fillIB.length;
  15929. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  15930. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  15931. if (ei) {
  15932. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  15933. }
  15934. // Get the non instanced version
  15935. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  15936. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  15937. }
  15938. // Need to create WebGL resources for border part?
  15939. if (this.border) {
  15940. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  15941. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  15942. renderCache.borderIndicesCount = this._borderIB.length;
  15943. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  15944. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  15945. if (ei) {
  15946. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  15947. }
  15948. // Get the non instanced version
  15949. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  15950. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  15951. }
  15952. this._fillVB = null;
  15953. this._fillIB = null;
  15954. this._borderVB = null;
  15955. this._borderIB = null;
  15956. return renderCache;
  15957. };
  15958. Lines2D.prototype.updateTriArray = function () {
  15959. if (this._primTriArrayDirty) {
  15960. this._computeLines2D();
  15961. }
  15962. };
  15963. Lines2D.prototype._computeLines2D = function () {
  15964. var _this = this;
  15965. // Init min/max because their being computed here
  15966. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  15967. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  15968. var contour = new Array();
  15969. var startCapContour = new Array();
  15970. var endCapContour = new Array();
  15971. // Need to create WebGL resources for fill part?
  15972. if (this.fill) {
  15973. var startCapInfo = this._getCapSize(this.startCap);
  15974. var endCapInfo = this._getCapSize(this.endCap);
  15975. var count = this.points.length;
  15976. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  15977. this._fillVB = new Float32Array(vbSize);
  15978. var vb = this._fillVB;
  15979. var ht = this.fillThickness / 2;
  15980. var total = this.points.length;
  15981. this._buildLine(vb, this.border ? null : contour, ht);
  15982. var max = total * 2;
  15983. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  15984. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  15985. var ib = this._fillIB;
  15986. for (var i = 0; i < triCount; i += 2) {
  15987. ib[i * 3 + 0] = i + 0;
  15988. ib[i * 3 + 1] = i + 1;
  15989. ib[i * 3 + 2] = (i + 2) % max;
  15990. ib[i * 3 + 3] = i + 1;
  15991. ib[i * 3 + 4] = (i + 3) % max;
  15992. ib[i * 3 + 5] = (i + 2) % max;
  15993. }
  15994. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D_1._startDir, this.border ? null : startCapContour);
  15995. this._buildCap(vb, (count * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, null, this.endCap, Lines2D_1._endDir, this.border ? null : startCapContour);
  15996. }
  15997. // Need to create WebGL resources for border part?
  15998. if (this.border) {
  15999. var startCapInfo = this._getCapSize(this.startCap, true);
  16000. var endCapInfo = this._getCapSize(this.endCap, true);
  16001. var count = this.points.length;
  16002. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  16003. this._borderVB = new Float32Array(vbSize);
  16004. var vb = this._borderVB;
  16005. var ht = this.fillThickness / 2;
  16006. var bt = this.borderThickness;
  16007. var total = this.points.length;
  16008. this._buildLine(vb, contour, ht, bt);
  16009. var max = total * 2 * 2;
  16010. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  16011. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  16012. var ib = this._borderIB;
  16013. for (var i = 0; i < triCount; i += 4) {
  16014. ib[i * 3 + 0] = i + 0;
  16015. ib[i * 3 + 1] = i + 2;
  16016. ib[i * 3 + 2] = (i + 6) % max;
  16017. ib[i * 3 + 3] = i + 0;
  16018. ib[i * 3 + 4] = (i + 6) % max;
  16019. ib[i * 3 + 5] = (i + 4) % max;
  16020. ib[i * 3 + 6] = i + 3;
  16021. ib[i * 3 + 7] = i + 1;
  16022. ib[i * 3 + 8] = (i + 5) % max;
  16023. ib[i * 3 + 9] = i + 3;
  16024. ib[i * 3 + 10] = (i + 5) % max;
  16025. ib[i * 3 + 11] = (i + 7) % max;
  16026. }
  16027. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D_1._startDir, startCapContour);
  16028. this._buildCap(vb, (count * 2 * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, this.borderThickness, this.endCap, Lines2D_1._endDir, endCapContour);
  16029. }
  16030. var startCapTri;
  16031. if (startCapContour.length > 0) {
  16032. startCapTri = Earcut.earcut(startCapContour, null, 2);
  16033. }
  16034. var endCapTri;
  16035. if (endCapContour.length > 0) {
  16036. endCapTri = Earcut.earcut(endCapContour, null, 2);
  16037. }
  16038. // Build the Tri2DArray using the contour info from the shape and the caps (if any)
  16039. {
  16040. var pl = this.points.length;
  16041. // Count the number of needed triangles
  16042. var count = ((this.closed ? pl : (pl - 1)) * 2) + (startCapTri != null ? ((startCapTri.length + endCapTri.length) / 3) : 0);
  16043. // Init/Clear the TriArray
  16044. if (!this._primTriArray) {
  16045. this._primTriArray = new BABYLON.Tri2DArray(count);
  16046. }
  16047. else {
  16048. this._primTriArray.clear(count);
  16049. }
  16050. var pta_1 = this._primTriArray;
  16051. var l = this.closed ? pl + 1 : pl;
  16052. this.transformPointWithOriginToRef(contour[0], null, Lines2D_1._prevA);
  16053. this.transformPointWithOriginToRef(contour[1], null, Lines2D_1._prevB);
  16054. var si_1 = 0;
  16055. for (var i = 1; i < l; i++) {
  16056. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 0], null, Lines2D_1._curA);
  16057. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 1], null, Lines2D_1._curB);
  16058. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curA);
  16059. pta_1.storeTriangle(si_1++, Lines2D_1._curA, Lines2D_1._prevB, Lines2D_1._curB);
  16060. Lines2D_1._prevA.x = Lines2D_1._curA.x;
  16061. Lines2D_1._prevA.y = Lines2D_1._curA.y;
  16062. Lines2D_1._prevB.x = Lines2D_1._curB.x;
  16063. Lines2D_1._prevB.y = Lines2D_1._curB.y;
  16064. }
  16065. var capIntersect = function (tri, points) {
  16066. var l = tri.length;
  16067. for (var i = 0; i < l; i += 3) {
  16068. Lines2D_1._curA.x = points[tri[i + 0] * 2 + 0];
  16069. Lines2D_1._curA.y = points[tri[i + 0] * 2 + 1];
  16070. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._curB);
  16071. Lines2D_1._curA.x = points[tri[i + 1] * 2 + 0];
  16072. Lines2D_1._curA.y = points[tri[i + 1] * 2 + 1];
  16073. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevA);
  16074. Lines2D_1._curA.x = points[tri[i + 2] * 2 + 0];
  16075. Lines2D_1._curA.y = points[tri[i + 2] * 2 + 1];
  16076. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevB);
  16077. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curB);
  16078. }
  16079. return false;
  16080. };
  16081. if (startCapTri) {
  16082. if (startCapTri) {
  16083. capIntersect(startCapTri, startCapContour);
  16084. }
  16085. if (endCapTri) {
  16086. capIntersect(endCapTri, endCapContour);
  16087. }
  16088. }
  16089. this._primTriArrayDirty = false;
  16090. }
  16091. var bs = this._boundingMax.subtract(this._boundingMin);
  16092. this._size.width = bs.x;
  16093. this._size.height = bs.y;
  16094. };
  16095. Object.defineProperty(Lines2D.prototype, "size", {
  16096. get: function () {
  16097. if (this._size == null) {
  16098. this._computeLines2D();
  16099. }
  16100. return this._size;
  16101. },
  16102. enumerable: true,
  16103. configurable: true
  16104. });
  16105. Lines2D.prototype.createInstanceDataParts = function () {
  16106. var res = new Array();
  16107. if (this.border) {
  16108. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  16109. }
  16110. if (this.fill) {
  16111. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  16112. }
  16113. return res;
  16114. };
  16115. Lines2D.prototype.applyActualScaleOnTransform = function () {
  16116. return true;
  16117. };
  16118. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  16119. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  16120. return false;
  16121. }
  16122. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  16123. var d = part;
  16124. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  16125. d.boundingMin = this.boundingMin;
  16126. d.boundingMax = this.boundingMax;
  16127. }
  16128. }
  16129. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  16130. var d = part;
  16131. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  16132. d.boundingMin = this.boundingMin;
  16133. d.boundingMax = this.boundingMax;
  16134. }
  16135. }
  16136. return true;
  16137. };
  16138. return Lines2D;
  16139. }(BABYLON.Shape2D));
  16140. Lines2D._prevA = BABYLON.Vector2.Zero();
  16141. Lines2D._prevB = BABYLON.Vector2.Zero();
  16142. Lines2D._curA = BABYLON.Vector2.Zero();
  16143. Lines2D._curB = BABYLON.Vector2.Zero();
  16144. Lines2D._miterTps = BABYLON.Vector2.Zero();
  16145. Lines2D._startDir = BABYLON.Vector2.Zero();
  16146. Lines2D._endDir = BABYLON.Vector2.Zero();
  16147. Lines2D._tpsV = BABYLON.Vector2.Zero();
  16148. Lines2D._noCap = 0;
  16149. Lines2D._roundCap = 1;
  16150. Lines2D._triangleCap = 2;
  16151. Lines2D._squareAnchorCap = 3;
  16152. Lines2D._roundAnchorCap = 4;
  16153. Lines2D._diamondAnchorCap = 5;
  16154. Lines2D._arrowCap = 6;
  16155. Lines2D._roundCapSubDiv = 36;
  16156. __decorate([
  16157. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D_1.pointsProperty = pi; })
  16158. ], Lines2D.prototype, "points", null);
  16159. __decorate([
  16160. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D_1.fillThicknessProperty = pi; })
  16161. ], Lines2D.prototype, "fillThickness", null);
  16162. __decorate([
  16163. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D_1.closedProperty = pi; })
  16164. ], Lines2D.prototype, "closed", null);
  16165. __decorate([
  16166. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D_1.startCapProperty = pi; })
  16167. ], Lines2D.prototype, "startCap", null);
  16168. __decorate([
  16169. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D_1.endCapProperty = pi; })
  16170. ], Lines2D.prototype, "endCap", null);
  16171. Lines2D = Lines2D_1 = __decorate([
  16172. BABYLON.className("Lines2D", "BABYLON")
  16173. ], Lines2D);
  16174. BABYLON.Lines2D = Lines2D;
  16175. var Lines2D_1;
  16176. })(BABYLON || (BABYLON = {}));
  16177. var __extends = (this && this.__extends) || function (d, b) {
  16178. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16179. function __() { this.constructor = d; }
  16180. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16181. };
  16182. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  16183. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  16184. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  16185. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  16186. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16187. };
  16188. var BABYLON;
  16189. (function (BABYLON) {
  16190. // This class contains data that lifetime is bounding to the Babylon Engine object
  16191. var Canvas2DEngineBoundData = (function () {
  16192. function Canvas2DEngineBoundData() {
  16193. this._modelCache = new BABYLON.StringDictionary();
  16194. }
  16195. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  16196. return this._modelCache.getOrAddWithFactory(key, factory);
  16197. };
  16198. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  16199. if (!modelRenderCache.isDisposed) {
  16200. return false;
  16201. }
  16202. this._modelCache.remove(modelRenderCache.modelKey);
  16203. return true;
  16204. };
  16205. return Canvas2DEngineBoundData;
  16206. }());
  16207. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  16208. var Canvas2D = Canvas2D_1 = (function (_super) {
  16209. __extends(Canvas2D, _super);
  16210. function Canvas2D(scene, settings) {
  16211. var _this = _super.call(this, settings) || this;
  16212. /**
  16213. * If you set your own WorldSpaceNode to display the Canvas2D you have to provide your own implementation of this method which computes the local position in the Canvas based on the given 3D World one.
  16214. * Beware that you have to take under consideration the origin and unitScaleFactor in your calculations! Good luck!
  16215. */
  16216. _this.worldSpaceToNodeLocal = function (worldPos) {
  16217. var node = _this._worldSpaceNode;
  16218. if (!node) {
  16219. return;
  16220. }
  16221. var mtx = node.getWorldMatrix().clone();
  16222. mtx.invert();
  16223. var usf = _this.unitScaleFactor;
  16224. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  16225. var res = new BABYLON.Vector2(v.x, v.y);
  16226. var size = _this.actualSize;
  16227. res.x += (size.width / usf) * 0.5; // res is centered, make it relative to bottom/left
  16228. res.y += (size.height / usf) * 0.5;
  16229. res.x *= usf; // multiply by the unitScaleFactor, which defines if the canvas is nth time bigger than the original world plane
  16230. res.y *= usf;
  16231. return res;
  16232. };
  16233. /**
  16234. * If you use a custom WorldSpaceCanvasNode you have to override this property to update the UV of your object to reflect the changes due to a resizing of the cached bitmap
  16235. */
  16236. _this.worldSpaceCacheChanged = function () {
  16237. var plane = _this.worldSpaceCanvasNode;
  16238. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  16239. vd.uvs = new Float32Array(8);
  16240. var material = plane.material;
  16241. var tex = _this._renderableData._cacheTexture;
  16242. if (material.diffuseTexture !== tex) {
  16243. material.diffuseTexture = tex;
  16244. tex.hasAlpha = true;
  16245. }
  16246. var nodeuv = _this._renderableData._cacheNodeUVs;
  16247. for (var i = 0; i < 4; i++) {
  16248. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  16249. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  16250. }
  16251. vd.applyToMesh(plane);
  16252. };
  16253. _this._notifDebugMode = false;
  16254. /**
  16255. * Instanced Array will be create if there's at least this number of parts/prim that can fit into it
  16256. */
  16257. _this.minPartCountToUseInstancedArray = 5;
  16258. _this._mapCounter = 0;
  16259. _this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  16260. _this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  16261. _this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  16262. _this._groupRenderCounter = new BABYLON.PerfCounter();
  16263. _this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  16264. _this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  16265. _this._updateCachedStateCounter = new BABYLON.PerfCounter();
  16266. _this._updateLayoutCounter = new BABYLON.PerfCounter();
  16267. _this._updatePositioningCounter = new BABYLON.PerfCounter();
  16268. _this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  16269. _this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  16270. _this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  16271. _this._layoutBoundingInfoUpdateCounter = new BABYLON.PerfCounter();
  16272. _this._cachedCanvasGroup = null;
  16273. _this._renderingGroupObserver = null;
  16274. _this._beforeRenderObserver = null;
  16275. _this._afterRenderObserver = null;
  16276. _this._profileInfoText = null;
  16277. BABYLON.Prim2DBase._isCanvasInit = false;
  16278. if (!settings) {
  16279. settings = {};
  16280. }
  16281. if (_this._cachingStrategy !== Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  16282. _this._background = new BABYLON.Rectangle2D({ parent: _this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  16283. _this._background.zOrder = 1.0;
  16284. _this._background.isPickable = false;
  16285. _this._background.origin = BABYLON.Vector2.Zero();
  16286. _this._background.levelVisible = false;
  16287. if (settings.backgroundRoundRadius != null) {
  16288. _this.backgroundRoundRadius = settings.backgroundRoundRadius;
  16289. }
  16290. if (settings.backgroundBorder != null) {
  16291. if (typeof (settings.backgroundBorder) === "string") {
  16292. _this.backgroundBorder = Canvas2D_1.GetBrushFromString(settings.backgroundBorder);
  16293. }
  16294. else {
  16295. _this.backgroundBorder = settings.backgroundBorder;
  16296. }
  16297. }
  16298. if (settings.backgroundBorderThickNess != null) {
  16299. _this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  16300. }
  16301. if (settings.backgroundFill != null) {
  16302. if (typeof (settings.backgroundFill) === "string") {
  16303. _this.backgroundFill = Canvas2D_1.GetBrushFromString(settings.backgroundFill);
  16304. }
  16305. else {
  16306. _this.backgroundFill = settings.backgroundFill;
  16307. }
  16308. }
  16309. // Put a handler to resize the background whenever the canvas is resizing
  16310. _this.propertyChanged.add(function (e, s) {
  16311. if (e.propertyName === "size") {
  16312. _this._background.size = _this.size;
  16313. }
  16314. }, BABYLON.Group2D.sizeProperty.flagId);
  16315. _this._background._patchHierarchy(_this);
  16316. }
  16317. var engine = scene.getEngine();
  16318. _this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  16319. _this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  16320. _this._capturedPointers = new BABYLON.StringDictionary();
  16321. _this._pickStartingPosition = BABYLON.Vector2.Zero();
  16322. _this._hierarchyLevelMaxSiblingCount = 50;
  16323. _this._hierarchyDepth = 0;
  16324. _this._zOrder = 0;
  16325. _this._zMax = 1;
  16326. _this._scene = scene;
  16327. _this._engine = engine;
  16328. _this._renderingSize = new BABYLON.Size(0, 0);
  16329. _this._curHWScale = 0;
  16330. _this._canvasLevelScale = new BABYLON.Vector3(1, 1, 1);
  16331. _this._designSize = settings.designSize || null;
  16332. _this._designUseHorizAxis = settings.designUseHorizAxis === true;
  16333. if (!_this._trackedGroups) {
  16334. _this._trackedGroups = new Array();
  16335. }
  16336. _this._maxAdaptiveWorldSpaceCanvasSize = null;
  16337. _this._groupCacheMaps = new BABYLON.StringDictionary();
  16338. _this._patchHierarchy(_this);
  16339. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  16340. _this._fitRenderingDevice = !settings.size;
  16341. if (!settings.size) {
  16342. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  16343. }
  16344. // Register scene dispose to also dispose the canvas when it'll happens
  16345. scene.onDisposeObservable.add(function (d, s) {
  16346. _this.dispose();
  16347. });
  16348. if (_this._isScreenSpace) {
  16349. if (settings.renderingPhase) {
  16350. if (!settings.renderingPhase.camera || settings.renderingPhase.renderingGroupID == null) {
  16351. throw Error("You have to specify a valid camera and renderingGroup");
  16352. }
  16353. _this._renderingGroupObserver = _this._scene.onRenderingGroupObservable.add(function (e, s) {
  16354. if ((_this._scene.activeCamera === settings.renderingPhase.camera) && (e.renderStage === BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT)) {
  16355. _this._engine.clear(null, false, true, true);
  16356. _this._render();
  16357. }
  16358. }, Math.pow(2, settings.renderingPhase.renderingGroupID));
  16359. }
  16360. else {
  16361. _this._afterRenderObserver = _this._scene.onAfterRenderObservable.add(function (d, s) {
  16362. _this._engine.clear(null, false, true, true);
  16363. _this._render();
  16364. });
  16365. }
  16366. }
  16367. else {
  16368. _this._beforeRenderObserver = _this._scene.onBeforeRenderObservable.add(function (d, s) {
  16369. _this._render();
  16370. });
  16371. }
  16372. _this._supprtInstancedArray = _this._engine.getCaps().instancedArrays !== null;
  16373. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  16374. // Setup the canvas for interaction (or not)
  16375. _this._setupInteraction(enableInteraction);
  16376. // Initialize the Primitive Collision Manager
  16377. if (settings.enableCollisionManager) {
  16378. var enableBorders = settings.collisionManagerUseBorders;
  16379. _this._primitiveCollisionManager = (settings.customCollisionManager == null) ? BABYLON.PrimitiveCollisionManagerBase.allocBasicPCM(_this, enableBorders) : settings.customCollisionManager(_this, enableBorders);
  16380. }
  16381. // Register this instance
  16382. Canvas2D_1._INSTANCES.push(_this);
  16383. return _this;
  16384. }
  16385. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  16386. get: function () {
  16387. return this._drawCallsOpaqueCounter;
  16388. },
  16389. enumerable: true,
  16390. configurable: true
  16391. });
  16392. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  16393. get: function () {
  16394. return this._drawCallsAlphaTestCounter;
  16395. },
  16396. enumerable: true,
  16397. configurable: true
  16398. });
  16399. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  16400. get: function () {
  16401. return this._drawCallsTransparentCounter;
  16402. },
  16403. enumerable: true,
  16404. configurable: true
  16405. });
  16406. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  16407. get: function () {
  16408. return this._groupRenderCounter;
  16409. },
  16410. enumerable: true,
  16411. configurable: true
  16412. });
  16413. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  16414. get: function () {
  16415. return this._updateTransparentDataCounter;
  16416. },
  16417. enumerable: true,
  16418. configurable: true
  16419. });
  16420. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  16421. get: function () {
  16422. return this._cachedGroupRenderCounter;
  16423. },
  16424. enumerable: true,
  16425. configurable: true
  16426. });
  16427. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  16428. get: function () {
  16429. return this._updateCachedStateCounter;
  16430. },
  16431. enumerable: true,
  16432. configurable: true
  16433. });
  16434. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  16435. get: function () {
  16436. return this._updateLayoutCounter;
  16437. },
  16438. enumerable: true,
  16439. configurable: true
  16440. });
  16441. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  16442. get: function () {
  16443. return this._updatePositioningCounter;
  16444. },
  16445. enumerable: true,
  16446. configurable: true
  16447. });
  16448. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  16449. get: function () {
  16450. return this._updateLocalTransformCounter;
  16451. },
  16452. enumerable: true,
  16453. configurable: true
  16454. });
  16455. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  16456. get: function () {
  16457. return this._updateGlobalTransformCounter;
  16458. },
  16459. enumerable: true,
  16460. configurable: true
  16461. });
  16462. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  16463. get: function () {
  16464. return this._boundingInfoRecomputeCounter;
  16465. },
  16466. enumerable: true,
  16467. configurable: true
  16468. });
  16469. Object.defineProperty(Canvas2D.prototype, "layoutBoundingInfoUpdateCounter", {
  16470. get: function () {
  16471. return this._layoutBoundingInfoUpdateCounter;
  16472. },
  16473. enumerable: true,
  16474. configurable: true
  16475. });
  16476. Object.defineProperty(Canvas2D, "instances", {
  16477. get: function () {
  16478. return Canvas2D_1._INSTANCES;
  16479. },
  16480. enumerable: true,
  16481. configurable: true
  16482. });
  16483. Object.defineProperty(Canvas2D.prototype, "primitiveCollisionManager", {
  16484. get: function () {
  16485. return this._primitiveCollisionManager;
  16486. },
  16487. enumerable: true,
  16488. configurable: true
  16489. });
  16490. Canvas2D.prototype._canvasPreInit = function (settings) {
  16491. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D_1.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  16492. this._cachingStrategy = cachingStrategy;
  16493. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  16494. };
  16495. Canvas2D.prototype._setupInteraction = function (enable) {
  16496. var _this = this;
  16497. // No change detection
  16498. if (enable === this._interactionEnabled) {
  16499. return;
  16500. }
  16501. // Set the new state
  16502. this._interactionEnabled = enable;
  16503. // ScreenSpace mode
  16504. if (this._isScreenSpace) {
  16505. // Disable interaction
  16506. if (!enable) {
  16507. if (this._scenePrePointerObserver) {
  16508. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  16509. this._scenePrePointerObserver = null;
  16510. }
  16511. return;
  16512. }
  16513. // Enable Interaction
  16514. // Register the observable
  16515. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  16516. if (_this.isVisible === false) {
  16517. return;
  16518. }
  16519. var hs = 1 / _this.engine.getHardwareScalingLevel();
  16520. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  16521. _this._handlePointerEventForInteraction(e, localPos, s);
  16522. });
  16523. }
  16524. else {
  16525. var scene = this.scene;
  16526. if (enable) {
  16527. scene.constantlyUpdateMeshUnderPointer = true;
  16528. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  16529. if (_this.isVisible === false) {
  16530. return;
  16531. }
  16532. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  16533. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  16534. _this._handlePointerEventForInteraction(e, localPos, s);
  16535. }
  16536. else if (_this._actualIntersectionList && _this._actualIntersectionList.length > 0) {
  16537. _this._handlePointerEventForInteraction(e, null, s);
  16538. }
  16539. });
  16540. }
  16541. else {
  16542. if (this._scenePointerObserver) {
  16543. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  16544. this._scenePointerObserver = null;
  16545. }
  16546. }
  16547. }
  16548. };
  16549. /**
  16550. * Internal method, you should use the Prim2DBase version instead
  16551. */
  16552. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  16553. if (this.isPointerCaptured(pointerId)) {
  16554. return false;
  16555. }
  16556. // Try to capture the pointer on the HTML side
  16557. try {
  16558. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  16559. }
  16560. catch (e) {
  16561. }
  16562. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  16563. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  16564. this._capturedPointers.add(pointerId.toString(), primitive);
  16565. return true;
  16566. };
  16567. /**
  16568. * Internal method, you should use the Prim2DBase version instead
  16569. */
  16570. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  16571. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  16572. return false;
  16573. }
  16574. // Try to release the pointer on the HTML side
  16575. try {
  16576. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  16577. }
  16578. catch (e) {
  16579. }
  16580. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  16581. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  16582. this._capturedPointers.remove(pointerId.toString());
  16583. return true;
  16584. };
  16585. /**
  16586. * Determine if the given pointer is captured or not
  16587. * @param pointerId the Id of the pointer
  16588. * @return true if it's captured, false otherwise
  16589. */
  16590. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  16591. return this._capturedPointers.contains(pointerId.toString());
  16592. };
  16593. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  16594. // Avoid unnecessary lookup
  16595. if (this._capturedPointers.count === 0) {
  16596. return null;
  16597. }
  16598. return this._capturedPointers.get(pointerId.toString());
  16599. };
  16600. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  16601. // Dispose check
  16602. if (this.isDisposed) {
  16603. return;
  16604. }
  16605. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  16606. if (localPosition) {
  16607. if (!this._updatePointerInfo(eventData, localPosition)) {
  16608. return;
  16609. }
  16610. }
  16611. else {
  16612. this._primPointerInfo.canvasPointerPos = null;
  16613. }
  16614. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  16615. // Make sure the intersection list is up to date, we maintain this list either in response of a mouse event (here) or before rendering the canvas.
  16616. // Why before rendering the canvas? because some primitives may move and get away/under the mouse cursor (which is not moving). So we need to update at both location in order to always have an accurate list, which is needed for the hover state change.
  16617. this._updateIntersectionList(localPosition ? this._primPointerInfo.canvasPointerPos : null, capturedPrim !== null, true);
  16618. // Update the over status, same as above, it's could be done here or during rendering, but will be performed only once per render frame
  16619. this._updateOverStatus(true);
  16620. // Check if we have nothing to raise
  16621. if (!this._actualOverPrimitive && !capturedPrim) {
  16622. return;
  16623. }
  16624. // Update the relatedTarget info with the over primitive or the captured one (if any)
  16625. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  16626. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  16627. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  16628. // Analyze the pointer event type and fire proper events on the primitive
  16629. var skip = false;
  16630. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  16631. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  16632. }
  16633. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16634. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  16635. }
  16636. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16637. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  16638. }
  16639. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  16640. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  16641. }
  16642. eventState.skipNextObservers = skip;
  16643. };
  16644. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  16645. var s = this.scale;
  16646. var pii = this._primPointerInfo;
  16647. pii.cancelBubble = false;
  16648. if (!pii.canvasPointerPos) {
  16649. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  16650. }
  16651. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  16652. if (!camera || !camera.viewport) {
  16653. return false;
  16654. }
  16655. var engine = this._scene.getEngine();
  16656. if (this._isScreenSpace) {
  16657. var cameraViewport = camera.viewport;
  16658. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16659. // Moving coordinates to local viewport world
  16660. var x = localPosition.x - viewport.x;
  16661. var y = localPosition.y - viewport.y;
  16662. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  16663. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  16664. }
  16665. else {
  16666. pii.canvasPointerPos.x = localPosition.x / s;
  16667. pii.canvasPointerPos.y = localPosition.y / s;
  16668. }
  16669. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  16670. pii.mouseWheelDelta = 0;
  16671. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  16672. var event = eventData.event;
  16673. if (event.wheelDelta) {
  16674. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  16675. }
  16676. else if (event.detail) {
  16677. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  16678. }
  16679. }
  16680. else {
  16681. var pe = eventData.event;
  16682. pii.ctrlKey = pe.ctrlKey;
  16683. pii.altKey = pe.altKey;
  16684. pii.shiftKey = pe.shiftKey;
  16685. pii.metaKey = pe.metaKey;
  16686. pii.button = pe.button;
  16687. pii.buttons = pe.buttons;
  16688. pii.pointerId = pe.pointerId;
  16689. pii.width = pe.width;
  16690. pii.height = pe.height;
  16691. pii.presssure = pe.pressure;
  16692. pii.tilt.x = pe.tiltX;
  16693. pii.tilt.y = pe.tiltY;
  16694. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  16695. }
  16696. return true;
  16697. };
  16698. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
  16699. if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
  16700. return;
  16701. }
  16702. var ii = Canvas2D_1._interInfo;
  16703. var outCase = mouseLocalPos == null;
  16704. if (!outCase) {
  16705. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  16706. if (!this._globalTransform) {
  16707. this.updateCachedStates(true);
  16708. }
  16709. ii.pickPosition.x = mouseLocalPos.x;
  16710. ii.pickPosition.y = mouseLocalPos.y;
  16711. ii.findFirstOnly = false;
  16712. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  16713. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  16714. // Reset intersection info as we don't hit anything
  16715. ii.intersectedPrimitives = new Array();
  16716. ii.topMostIntersectedPrimitive = null;
  16717. }
  16718. else {
  16719. // The pointer is inside the Canvas, do an intersection test
  16720. this.intersect(ii);
  16721. // Sort primitives to get them from top to bottom
  16722. ii.intersectedPrimitives = ii.intersectedPrimitives.sort(function (a, b) { return a.prim.actualZOffset - b.prim.actualZOffset; });
  16723. }
  16724. }
  16725. {
  16726. // Update prev/actual intersection info, fire "overPrim" property change if needed
  16727. this._previousIntersectionList = this._actualIntersectionList;
  16728. this._actualIntersectionList = outCase ? new Array() : ii.intersectedPrimitives;
  16729. this._previousOverPrimitive = this._actualOverPrimitive;
  16730. this._actualOverPrimitive = outCase ? null : ii.topMostIntersectedPrimitive;
  16731. var prev = (this._previousOverPrimitive != null) ? this._previousOverPrimitive.prim : null;
  16732. var actual = (this._actualOverPrimitive != null) ? this._actualOverPrimitive.prim : null;
  16733. if (prev !== actual) {
  16734. this.onPropertyChanged("overPrim", this._previousOverPrimitive ? this._previousOverPrimitive.prim : null, this._actualOverPrimitive ? this._actualOverPrimitive.prim : null);
  16735. }
  16736. }
  16737. this._intersectionRenderId = this.scene.getRenderId();
  16738. };
  16739. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  16740. Canvas2D.prototype._updateOverStatus = function (force) {
  16741. if ((!force && (this.scene.getRenderId() === this._hoverStatusRenderId)) || !this._actualIntersectionList) {
  16742. return;
  16743. }
  16744. if (this._previousIntersectionList == null) {
  16745. this._previousIntersectionList = [];
  16746. }
  16747. // Detect a change of over
  16748. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  16749. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  16750. if (prevPrim !== actualPrim) {
  16751. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  16752. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  16753. // See the NOTE section of: https://www.w3.org/TR/pointerevents/#setting-pointer-capture
  16754. if (capturedPrim) {
  16755. if (capturedPrim === prevPrim) {
  16756. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  16757. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  16758. }
  16759. else if (capturedPrim === actualPrim) {
  16760. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  16761. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  16762. }
  16763. }
  16764. else {
  16765. var _loop_1 = function (prev) {
  16766. if (!BABYLON.Tools.first(this_1._actualIntersectionList, function (pii) { return pii.prim === prev.prim; })) {
  16767. this_1._primPointerInfo.updateRelatedTarget(prev.prim, prev.intersectionLocation);
  16768. this_1._bubbleNotifyPrimPointerObserver(prev.prim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  16769. }
  16770. };
  16771. var this_1 = this;
  16772. // Check for Out & Leave
  16773. for (var _i = 0, _a = this._previousIntersectionList; _i < _a.length; _i++) {
  16774. var prev = _a[_i];
  16775. _loop_1(prev);
  16776. }
  16777. var _loop_2 = function (actual) {
  16778. if (!BABYLON.Tools.first(this_2._previousIntersectionList, function (pii) { return pii.prim === actual.prim; })) {
  16779. this_2._primPointerInfo.updateRelatedTarget(actual.prim, actual.intersectionLocation);
  16780. this_2._bubbleNotifyPrimPointerObserver(actual.prim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  16781. }
  16782. };
  16783. var this_2 = this;
  16784. // Check for Over & Enter
  16785. for (var _b = 0, _c = this._actualIntersectionList; _b < _c.length; _b++) {
  16786. var actual = _c[_b];
  16787. _loop_2(actual);
  16788. }
  16789. }
  16790. }
  16791. this._hoverStatusRenderId = this.scene.getRenderId();
  16792. };
  16793. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  16794. if (this._primPointerInfo.isCaptured) {
  16795. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  16796. }
  16797. else {
  16798. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  16799. var pii = _a[_i];
  16800. if (pii.prim === prim) {
  16801. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  16802. return;
  16803. }
  16804. }
  16805. }
  16806. };
  16807. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  16808. if (!this._notifDebugMode) {
  16809. return;
  16810. }
  16811. var debug = "";
  16812. for (var i = 0; i < prim.hierarchyDepth; i++) {
  16813. debug += " ";
  16814. }
  16815. var pii = this._primPointerInfo;
  16816. debug += "[RID:" + this.scene.getRenderId() + "] [" + prim.hierarchyDepth + "] event:" + BABYLON.PrimitivePointerInfo.getEventTypeName(mask) + ", id: " + prim.id + " (" + BABYLON.Tools.getClassName(prim) + "), primPos: " + pii.primitivePointerPos.toString() + ", canvasPos: " + pii.canvasPointerPos.toString() + ", relatedTarget: " + pii.relatedTarget.id;
  16817. console.log(debug);
  16818. };
  16819. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  16820. var ppi = this._primPointerInfo;
  16821. var event = eventData ? eventData.event : null;
  16822. var cur = prim;
  16823. while (cur && !cur.isDisposed) {
  16824. this._updatePrimPointerPos(cur);
  16825. // For the first level we have to fire Enter or Leave for corresponding Over or Out
  16826. if (cur === prim) {
  16827. // Fire the proper notification
  16828. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  16829. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerEnter);
  16830. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  16831. }
  16832. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  16833. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerLeave);
  16834. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  16835. }
  16836. }
  16837. // Exec the observers
  16838. this._debugExecObserver(cur, mask);
  16839. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  16840. eventData.skipOnPointerObservable = true;
  16841. return false;
  16842. }
  16843. this._triggerActionManager(cur, ppi, mask, event);
  16844. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  16845. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  16846. if (ppi.cancelBubble) {
  16847. return false;
  16848. }
  16849. // Loop to the parent
  16850. cur = cur.parent;
  16851. }
  16852. return true;
  16853. };
  16854. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  16855. var _this = this;
  16856. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  16857. if (!this._globalTransform) {
  16858. this.updateCachedStates(true);
  16859. }
  16860. // Process Trigger related to PointerDown
  16861. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  16862. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  16863. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  16864. this._pickStartingTime = new Date().getTime();
  16865. this._pickedDownPrim = null;
  16866. if (prim.actionManager) {
  16867. this._pickedDownPrim = prim;
  16868. if (prim.actionManager.hasPickTriggers) {
  16869. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  16870. switch (eventData.button) {
  16871. case 0:
  16872. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  16873. break;
  16874. case 1:
  16875. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  16876. break;
  16877. case 2:
  16878. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  16879. break;
  16880. }
  16881. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  16882. }
  16883. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16884. window.setTimeout(function () {
  16885. var ppi = _this._primPointerInfo;
  16886. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  16887. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
  16888. _this._updateOverStatus(false);
  16889. var ii = new BABYLON.IntersectInfo2D();
  16890. ii.pickPosition = ppi.canvasPointerPos.clone();
  16891. ii.findFirstOnly = false;
  16892. _this.intersect(ii);
  16893. if (ii.isPrimIntersected(prim) !== null) {
  16894. if (prim.actionManager) {
  16895. if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.ActionManager.DragMovementThreshold)) {
  16896. _this._pickStartingTime = 0;
  16897. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  16898. }
  16899. }
  16900. }
  16901. }, BABYLON.ActionManager.LongPressDelay);
  16902. }
  16903. }
  16904. }
  16905. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  16906. this._pickStartingTime = 0;
  16907. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  16908. if (prim.actionManager) {
  16909. // OnPickUpTrigger
  16910. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  16911. // OnPickTrigger
  16912. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  16913. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  16914. }
  16915. }
  16916. // OnPickOutTrigger
  16917. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  16918. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  16919. }
  16920. }
  16921. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  16922. if (prim.actionManager) {
  16923. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  16924. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  16925. }
  16926. }
  16927. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  16928. if (prim.actionManager) {
  16929. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  16930. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  16931. }
  16932. }
  16933. };
  16934. /**
  16935. * Don't forget to call the dispose method when you're done with the Canvas instance.
  16936. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  16937. */
  16938. Canvas2D.prototype.dispose = function () {
  16939. if (!_super.prototype.dispose.call(this)) {
  16940. return false;
  16941. }
  16942. if (this._profilingCanvas) {
  16943. this._profilingCanvas.dispose();
  16944. this._profilingCanvas = null;
  16945. }
  16946. if (this.interactionEnabled) {
  16947. this._setupInteraction(false);
  16948. }
  16949. if (this._renderingGroupObserver) {
  16950. this._scene.onRenderingGroupObservable.remove(this._renderingGroupObserver);
  16951. this._renderingGroupObserver = null;
  16952. }
  16953. if (this._beforeRenderObserver) {
  16954. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  16955. this._beforeRenderObserver = null;
  16956. }
  16957. if (this._afterRenderObserver) {
  16958. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  16959. this._afterRenderObserver = null;
  16960. }
  16961. if (this._groupCacheMaps) {
  16962. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  16963. this._groupCacheMaps = null;
  16964. }
  16965. // Unregister this instance
  16966. var index = Canvas2D_1._INSTANCES.indexOf(this);
  16967. if (index > -1) {
  16968. Canvas2D_1._INSTANCES.splice(index, 1);
  16969. }
  16970. return true;
  16971. };
  16972. Object.defineProperty(Canvas2D.prototype, "scene", {
  16973. /**
  16974. * Accessor to the Scene that owns the Canvas
  16975. * @returns The instance of the Scene object
  16976. */
  16977. get: function () {
  16978. return this._scene;
  16979. },
  16980. enumerable: true,
  16981. configurable: true
  16982. });
  16983. Object.defineProperty(Canvas2D.prototype, "engine", {
  16984. /**
  16985. * Accessor to the Engine that drives the Scene used by this Canvas
  16986. * @returns The instance of the Engine object
  16987. */
  16988. get: function () {
  16989. return this._engine;
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Object.defineProperty(Canvas2D.prototype, "renderObservable", {
  16995. /**
  16996. * And observable called during the Canvas rendering process.
  16997. * This observable is called twice per render, each time with a different mask:
  16998. * - 1: before render is executed
  16999. * - 2: after render is executed
  17000. */
  17001. get: function () {
  17002. if (!this._renderObservable) {
  17003. this._renderObservable = new BABYLON.Observable();
  17004. }
  17005. return this._renderObservable;
  17006. },
  17007. enumerable: true,
  17008. configurable: true
  17009. });
  17010. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  17011. /**
  17012. * Accessor of the Caching Strategy used by this Canvas.
  17013. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  17014. * @returns the value corresponding to the used strategy.
  17015. */
  17016. get: function () {
  17017. return this._cachingStrategy;
  17018. },
  17019. enumerable: true,
  17020. configurable: true
  17021. });
  17022. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  17023. /**
  17024. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  17025. * @returns {}
  17026. */
  17027. get: function () {
  17028. return this._isScreenSpace;
  17029. },
  17030. enumerable: true,
  17031. configurable: true
  17032. });
  17033. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  17034. /**
  17035. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  17036. */
  17037. get: function () {
  17038. return this._worldSpaceNode;
  17039. },
  17040. set: function (val) {
  17041. this._worldSpaceNode = val;
  17042. },
  17043. enumerable: true,
  17044. configurable: true
  17045. });
  17046. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  17047. /**
  17048. * Check if the WebGL Instanced Array extension is supported or not
  17049. */
  17050. get: function () {
  17051. return this._supprtInstancedArray;
  17052. },
  17053. enumerable: true,
  17054. configurable: true
  17055. });
  17056. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  17057. /**
  17058. * Property that defines the fill object used to draw the background of the Canvas.
  17059. * Note that Canvas with a Caching Strategy of
  17060. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  17061. */
  17062. get: function () {
  17063. if (!this._background || !this._background.isVisible) {
  17064. return null;
  17065. }
  17066. return this._background.fill;
  17067. },
  17068. set: function (value) {
  17069. this.checkBackgroundAvailability();
  17070. if (value === this._background.fill) {
  17071. return;
  17072. }
  17073. this._background.fill = value;
  17074. this._background.levelVisible = true;
  17075. },
  17076. enumerable: true,
  17077. configurable: true
  17078. });
  17079. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  17080. /**
  17081. * Property that defines the border object used to draw the background of the Canvas.
  17082. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  17083. */
  17084. get: function () {
  17085. if (!this._background || !this._background.isVisible) {
  17086. return null;
  17087. }
  17088. return this._background.border;
  17089. },
  17090. set: function (value) {
  17091. this.checkBackgroundAvailability();
  17092. if (value === this._background.border) {
  17093. return;
  17094. }
  17095. this._background.border = value;
  17096. this._background.levelVisible = true;
  17097. },
  17098. enumerable: true,
  17099. configurable: true
  17100. });
  17101. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  17102. /**
  17103. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  17104. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  17105. */
  17106. get: function () {
  17107. if (!this._background || !this._background.isVisible) {
  17108. return null;
  17109. }
  17110. return this._background.borderThickness;
  17111. },
  17112. set: function (value) {
  17113. this.checkBackgroundAvailability();
  17114. if (value === this._background.borderThickness) {
  17115. return;
  17116. }
  17117. this._background.borderThickness = value;
  17118. },
  17119. enumerable: true,
  17120. configurable: true
  17121. });
  17122. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  17123. /**
  17124. * You can set the roundRadius of the background
  17125. * @returns The current roundRadius
  17126. */
  17127. get: function () {
  17128. if (!this._background || !this._background.isVisible) {
  17129. return null;
  17130. }
  17131. return this._background.roundRadius;
  17132. },
  17133. set: function (value) {
  17134. this.checkBackgroundAvailability();
  17135. if (value === this._background.roundRadius) {
  17136. return;
  17137. }
  17138. this._background.roundRadius = value;
  17139. this._background.levelVisible = true;
  17140. },
  17141. enumerable: true,
  17142. configurable: true
  17143. });
  17144. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  17145. /**
  17146. * Enable/Disable interaction for this Canvas
  17147. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  17148. */
  17149. get: function () {
  17150. return this._interactionEnabled;
  17151. },
  17152. set: function (enable) {
  17153. this._setupInteraction(enable);
  17154. },
  17155. enumerable: true,
  17156. configurable: true
  17157. });
  17158. Object.defineProperty(Canvas2D.prototype, "fitRenderingDevice", {
  17159. get: function () {
  17160. return this._fitRenderingDevice;
  17161. },
  17162. enumerable: true,
  17163. configurable: true
  17164. });
  17165. Object.defineProperty(Canvas2D.prototype, "designSize", {
  17166. get: function () {
  17167. return this._designSize;
  17168. },
  17169. enumerable: true,
  17170. configurable: true
  17171. });
  17172. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  17173. get: function () {
  17174. return this._designUseHorizAxis;
  17175. },
  17176. enumerable: true,
  17177. configurable: true
  17178. });
  17179. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizeAxis", {
  17180. set: function (value) {
  17181. this._designUseHorizAxis = value;
  17182. },
  17183. enumerable: true,
  17184. configurable: true
  17185. });
  17186. Object.defineProperty(Canvas2D.prototype, "overPrim", {
  17187. /**
  17188. * Return
  17189. */
  17190. get: function () {
  17191. if (this._actualIntersectionList && this._actualIntersectionList.length > 0) {
  17192. return this._actualIntersectionList[0].prim;
  17193. }
  17194. return null;
  17195. },
  17196. enumerable: true,
  17197. configurable: true
  17198. });
  17199. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  17200. /**
  17201. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  17202. * @returns {}
  17203. */
  17204. get: function () {
  17205. return this.__engineData;
  17206. },
  17207. enumerable: true,
  17208. configurable: true
  17209. });
  17210. Object.defineProperty(Canvas2D.prototype, "unitScaleFactor", {
  17211. get: function () {
  17212. return this._unitScaleFactor;
  17213. },
  17214. enumerable: true,
  17215. configurable: true
  17216. });
  17217. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  17218. if (this._profilingCanvas) {
  17219. return this._profilingCanvas;
  17220. }
  17221. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  17222. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D_1.CACHESTRATEGY_DONTCACHE, children: [
  17223. new BABYLON.Rectangle2D({
  17224. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  17225. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "12pt Lucida Console", fontSignedDistanceField: true })
  17226. ]
  17227. })
  17228. ]
  17229. });
  17230. this._profileInfoText = canvas.findById("ProfileInfoText");
  17231. this._profilingCanvas = canvas;
  17232. return canvas;
  17233. };
  17234. Canvas2D.prototype.checkBackgroundAvailability = function () {
  17235. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  17236. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  17237. }
  17238. };
  17239. Canvas2D.prototype._initPerfMetrics = function () {
  17240. this._drawCallsOpaqueCounter.fetchNewFrame();
  17241. this._drawCallsAlphaTestCounter.fetchNewFrame();
  17242. this._drawCallsTransparentCounter.fetchNewFrame();
  17243. this._groupRenderCounter.fetchNewFrame();
  17244. this._updateTransparentDataCounter.fetchNewFrame();
  17245. this._cachedGroupRenderCounter.fetchNewFrame();
  17246. this._updateCachedStateCounter.fetchNewFrame();
  17247. this._updateLayoutCounter.fetchNewFrame();
  17248. this._updatePositioningCounter.fetchNewFrame();
  17249. this._updateLocalTransformCounter.fetchNewFrame();
  17250. this._updateGlobalTransformCounter.fetchNewFrame();
  17251. this._boundingInfoRecomputeCounter.fetchNewFrame();
  17252. this._layoutBoundingInfoUpdateCounter.fetchNewFrame();
  17253. };
  17254. Canvas2D.prototype._fetchPerfMetrics = function () {
  17255. this._drawCallsOpaqueCounter.addCount(0, true);
  17256. this._drawCallsAlphaTestCounter.addCount(0, true);
  17257. this._drawCallsTransparentCounter.addCount(0, true);
  17258. this._groupRenderCounter.addCount(0, true);
  17259. this._updateTransparentDataCounter.addCount(0, true);
  17260. this._cachedGroupRenderCounter.addCount(0, true);
  17261. this._updateCachedStateCounter.addCount(0, true);
  17262. this._updateLayoutCounter.addCount(0, true);
  17263. this._updatePositioningCounter.addCount(0, true);
  17264. this._updateLocalTransformCounter.addCount(0, true);
  17265. this._updateGlobalTransformCounter.addCount(0, true);
  17266. this._boundingInfoRecomputeCounter.addCount(0, true);
  17267. this._layoutBoundingInfoUpdateCounter.addCount(0, true);
  17268. };
  17269. Canvas2D.prototype._updateProfileCanvas = function () {
  17270. if (this._profileInfoText == null) {
  17271. return;
  17272. }
  17273. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  17274. var p = "Draw Calls:\n" +
  17275. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  17276. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  17277. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  17278. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  17279. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  17280. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  17281. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  17282. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  17283. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  17284. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  17285. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  17286. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n") +
  17287. (" - LayoutBoundingInfo Recompute: " + this.layoutBoundingInfoUpdateCounter.current + ", (avg:" + format(this.layoutBoundingInfoUpdateCounter.lastSecAverage) + ", t:" + format(this.layoutBoundingInfoUpdateCounter.total) + ")");
  17288. this._profileInfoText.text = p;
  17289. };
  17290. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  17291. switch (renderMode) {
  17292. case BABYLON.Render2DContext.RenderModeOpaque:
  17293. this._drawCallsOpaqueCounter.addCount(count, false);
  17294. return;
  17295. case BABYLON.Render2DContext.RenderModeAlphaTest:
  17296. this._drawCallsAlphaTestCounter.addCount(count, false);
  17297. return;
  17298. case BABYLON.Render2DContext.RenderModeTransparent:
  17299. this._drawCallsTransparentCounter.addCount(count, false);
  17300. return;
  17301. }
  17302. };
  17303. Canvas2D.prototype._addGroupRenderCount = function (count) {
  17304. if (this._groupRenderCounter) {
  17305. this._groupRenderCounter.addCount(count, false);
  17306. }
  17307. };
  17308. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  17309. if (this._updateTransparentDataCounter) {
  17310. this._updateTransparentDataCounter.addCount(count, false);
  17311. }
  17312. };
  17313. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  17314. if (this._cachedGroupRenderCounter) {
  17315. this._cachedGroupRenderCounter.addCount(count, false);
  17316. }
  17317. };
  17318. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  17319. if (this._updateCachedStateCounter) {
  17320. this._updateCachedStateCounter.addCount(count, false);
  17321. }
  17322. };
  17323. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  17324. if (this._updateLayoutCounter) {
  17325. this._updateLayoutCounter.addCount(count, false);
  17326. }
  17327. };
  17328. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  17329. if (this._updatePositioningCounter) {
  17330. this._updatePositioningCounter.addCount(count, false);
  17331. }
  17332. };
  17333. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  17334. if (this._updateLocalTransformCounter) {
  17335. this._updateLocalTransformCounter.addCount(count, false);
  17336. }
  17337. };
  17338. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  17339. if (this._updateGlobalTransformCounter) {
  17340. this._updateGlobalTransformCounter.addCount(count, false);
  17341. }
  17342. };
  17343. Canvas2D.prototype.addLayoutBoundingInfoUpdateCounter = function (count) {
  17344. if (this._layoutBoundingInfoUpdateCounter) {
  17345. this._layoutBoundingInfoUpdateCounter.addCount(count, false);
  17346. }
  17347. };
  17348. Canvas2D.prototype._updateTrackedNodes = function () {
  17349. // Get the used camera
  17350. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  17351. // Compute some matrix stuff
  17352. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  17353. var rh = this.engine.getRenderHeight();
  17354. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  17355. var tmpVec3 = Canvas2D_1._tmpVec3;
  17356. var tmpMtx = Canvas2D_1._tmpMtx;
  17357. // Compute the screen position of each group that track a given scene node
  17358. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  17359. var group = _a[_i];
  17360. if (group.isDisposed) {
  17361. continue;
  17362. }
  17363. var node = group.trackedNode;
  17364. var worldMtx = node.getWorldMatrix();
  17365. if (group.trackedNodeOffset) {
  17366. BABYLON.Vector3.TransformCoordinatesToRef(group.trackedNodeOffset, worldMtx, tmpVec3);
  17367. tmpMtx.copyFrom(worldMtx);
  17368. worldMtx = tmpMtx;
  17369. worldMtx.setTranslation(tmpVec3);
  17370. }
  17371. var proj = BABYLON.Vector3.Project(Canvas2D_1._v, worldMtx, Canvas2D_1._m, v);
  17372. // Set the visibility state accordingly, if the position is outside the frustum (well on the Z planes only...) set the group to hidden
  17373. group.levelVisible = proj.z >= 0 && proj.z < 1.0;
  17374. var s = this.scale;
  17375. group.x = Math.round(proj.x / s);
  17376. group.y = Math.round((rh - proj.y) / s);
  17377. }
  17378. // If it's a WorldSpaceCanvas and it's tracking a node, let's update the WSC transformation data
  17379. if (this._trackNode) {
  17380. var rot = null;
  17381. var scale = null;
  17382. var worldmtx = this._trackNode.getWorldMatrix();
  17383. var pos = worldmtx.getTranslation().add(this._trackNodeOffset);
  17384. var wsc = this;
  17385. var wsn = wsc.worldSpaceCanvasNode;
  17386. if (this._trackNodeBillboard) {
  17387. var viewMtx = cam.getViewMatrix().clone().invert();
  17388. viewMtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  17389. rot = Canvas2D_1.tR.clone();
  17390. }
  17391. worldmtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  17392. var mtx = BABYLON.Matrix.Compose(Canvas2D_1.tS, Canvas2D_1.tR, BABYLON.Vector3.Zero());
  17393. pos = worldmtx.getTranslation().add(BABYLON.Vector3.TransformCoordinates(this._trackNodeOffset, mtx));
  17394. if (Canvas2D_1.tS.lengthSquared() !== 1) {
  17395. scale = Canvas2D_1.tS.clone();
  17396. }
  17397. if (!this._trackNodeBillboard) {
  17398. rot = Canvas2D_1.tR.clone();
  17399. }
  17400. if (wsn instanceof BABYLON.AbstractMesh) {
  17401. wsn.position = pos;
  17402. wsn.rotationQuaternion = rot;
  17403. if (scale) {
  17404. wsn.scaling = scale;
  17405. }
  17406. }
  17407. else {
  17408. throw new Error("Can't Track another Scene Node Type than AbstractMesh right now, call me lazy!");
  17409. }
  17410. }
  17411. };
  17412. /**
  17413. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  17414. */
  17415. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  17416. this._updateCanvasState(forceRecompute);
  17417. };
  17418. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  17419. if (this._globalTransformStep < 2) {
  17420. return;
  17421. }
  17422. var n = this.worldSpaceCanvasNode;
  17423. var bi = n.getBoundingInfo().boundingBox;
  17424. var v = bi.vectorsWorld;
  17425. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  17426. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  17427. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  17428. var projPoints = new Array(4);
  17429. for (var i = 0; i < 4; i++) {
  17430. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D_1._mI, Canvas2D_1._m, vp);
  17431. }
  17432. var left = projPoints[3].subtract(projPoints[0]).length();
  17433. var top = projPoints[3].subtract(projPoints[1]).length();
  17434. var right = projPoints[1].subtract(projPoints[2]).length();
  17435. var bottom = projPoints[2].subtract(projPoints[0]).length();
  17436. var w = Math.round(Math.max(top, bottom));
  17437. var h = Math.round(Math.max(right, left));
  17438. var isW = w > h;
  17439. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  17440. var edge = Math.max(w, h);
  17441. if (edge < 256) {
  17442. edge = 256;
  17443. }
  17444. else {
  17445. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  17446. }
  17447. // Clip values if needed
  17448. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  17449. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  17450. if (newScale !== this.scale) {
  17451. var scale = newScale;
  17452. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  17453. this._setRenderingScale(scale);
  17454. }
  17455. };
  17456. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  17457. // Check if the update has already been made for this render Frame
  17458. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  17459. return;
  17460. }
  17461. // Detect a change of HWRendering scale
  17462. var hwsl = this.engine.getHardwareScalingLevel();
  17463. var hwslChanged = this._curHWScale !== hwsl;
  17464. if (hwslChanged) {
  17465. this._curHWScale = hwsl;
  17466. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  17467. var child = _a[_i];
  17468. child._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  17469. }
  17470. this._setLayoutDirty();
  17471. }
  17472. // Detect a change of rendering size
  17473. var renderingSizeChanged = false;
  17474. var newWidth = this.engine.getRenderWidth() * hwsl;
  17475. if (newWidth !== this._renderingSize.width) {
  17476. renderingSizeChanged = true;
  17477. }
  17478. this._renderingSize.width = newWidth;
  17479. var newHeight = this.engine.getRenderHeight() * hwsl;
  17480. if (newHeight !== this._renderingSize.height) {
  17481. renderingSizeChanged = true;
  17482. }
  17483. this._renderingSize.height = newHeight;
  17484. // If the canvas fit the rendering size and it changed, update
  17485. if (renderingSizeChanged && this._fitRenderingDevice) {
  17486. this.size = this._renderingSize.clone();
  17487. if (this._background) {
  17488. this._background.size = this.size;
  17489. }
  17490. // Dirty the Layout at the Canvas level to recompute as the size changed
  17491. this._setLayoutDirty();
  17492. }
  17493. // If there's a design size, update the scale according to the renderingSize
  17494. if (this._designSize) {
  17495. var scale = void 0;
  17496. if (this._designUseHorizAxis) {
  17497. scale = this._renderingSize.width / (this._designSize.width * hwsl);
  17498. }
  17499. else {
  17500. scale = this._renderingSize.height / (this._designSize.height * hwsl);
  17501. }
  17502. this.size = this._designSize.clone();
  17503. this._canvasLevelScale.copyFromFloats(scale, scale, 1);
  17504. }
  17505. else if (this._curHWScale !== 1) {
  17506. var ratio = 1 / this._curHWScale;
  17507. this._canvasLevelScale.copyFromFloats(ratio, ratio, 1);
  17508. }
  17509. var context = new BABYLON.PrepareRender2DContext();
  17510. ++this._globalTransformProcessStep;
  17511. this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  17512. this.updateCachedStates(false);
  17513. this._prepareGroupRender(context);
  17514. this._updateRenderId = this.scene.getRenderId();
  17515. };
  17516. /**
  17517. * Method that renders the Canvas, you should not invoke
  17518. */
  17519. Canvas2D.prototype._render = function () {
  17520. this._initPerfMetrics();
  17521. if (this._renderObservable && this._renderObservable.hasObservers()) {
  17522. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_PRE);
  17523. }
  17524. this._updateCanvasState(false);
  17525. this._updateTrackedNodes();
  17526. // Nothing to do is the Canvas is not visible
  17527. if (this.isVisible === false) {
  17528. return;
  17529. }
  17530. if (!this._isScreenSpace) {
  17531. this._updateAdaptiveSizeWorldCanvas();
  17532. }
  17533. this._updateCanvasState(false);
  17534. if (this._primitiveCollisionManager) {
  17535. this._primitiveCollisionManager._update();
  17536. }
  17537. if (this._primPointerInfo.canvasPointerPos) {
  17538. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
  17539. this._updateOverStatus(false);
  17540. }
  17541. this.engine.setState(false, undefined, true);
  17542. this._groupRender();
  17543. if (!this._isScreenSpace) {
  17544. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  17545. this.worldSpaceCacheChanged();
  17546. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  17547. }
  17548. }
  17549. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  17550. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  17551. this._cachedCanvasGroup._renderCachedCanvas();
  17552. }
  17553. this._fetchPerfMetrics();
  17554. this._updateProfileCanvas();
  17555. if (this._renderObservable && this._renderObservable.hasObservers()) {
  17556. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_POST);
  17557. }
  17558. };
  17559. /**
  17560. * Internal method that allocate a cache for the given group.
  17561. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  17562. * @param group The group to allocate the cache of.
  17563. * @return custom type with the PackedRect instance giving information about the cache location into the texture and also the MapTexture instance that stores the cache.
  17564. */
  17565. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  17566. if (useMipMap === void 0) { useMipMap = false; }
  17567. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  17568. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  17569. var rd = group._renderableData;
  17570. var noResizeScale = rd._noResizeOnScale;
  17571. var isCanvas = parent == null;
  17572. var scale;
  17573. if (noResizeScale) {
  17574. scale = isCanvas ? Canvas2D_1._unS : group.parent.actualScale;
  17575. }
  17576. else {
  17577. scale = group.actualScale;
  17578. }
  17579. // Determine size
  17580. var size = group.actualSize;
  17581. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  17582. var originalSize = size.clone();
  17583. if (minSize) {
  17584. size.width = Math.max(minSize.width, size.width);
  17585. size.height = Math.max(minSize.height, size.height);
  17586. }
  17587. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  17588. // Try to find a spot in one of the cached texture
  17589. var res = null;
  17590. var map;
  17591. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  17592. var _map = mapArray_1[_i];
  17593. map = _map;
  17594. var node = map.allocateRect(size);
  17595. if (node) {
  17596. res = { node: node, texture: map };
  17597. break;
  17598. }
  17599. }
  17600. // Couldn't find a map that could fit the rect, create a new map for it
  17601. if (!res) {
  17602. var mapSize = new BABYLON.Size(Canvas2D_1._groupTextureCacheSize, Canvas2D_1._groupTextureCacheSize);
  17603. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  17604. if (size.width > mapSize.width || size.height > mapSize.height) {
  17605. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  17606. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  17607. }
  17608. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  17609. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  17610. map.hasAlpha = true;
  17611. map.anisotropicFilteringLevel = 4;
  17612. mapArray.splice(0, 0, map);
  17613. var node = map.allocateRect(size);
  17614. res = { node: node, texture: map };
  17615. }
  17616. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  17617. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  17618. if (group !== this || this._isScreenSpace) {
  17619. var node = res.node;
  17620. // Special case if the canvas is entirely cached: create a group that will have a single sprite it will be rendered specifically at the very end of the rendering process
  17621. var sprite = void 0;
  17622. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS) {
  17623. if (this._cachedCanvasGroup) {
  17624. this._cachedCanvasGroup.dispose();
  17625. }
  17626. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  17627. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: originalSize, spriteLocation: node.pos });
  17628. sprite.zOrder = 1;
  17629. sprite.origin = BABYLON.Vector2.Zero();
  17630. }
  17631. else {
  17632. sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: originalSize, spriteLocation: node.pos, dontInheritParentScale: true });
  17633. sprite.origin = group.origin.clone();
  17634. sprite.addExternalData("__cachedGroup__", group);
  17635. sprite.pointerEventObservable.add(function (e, s) {
  17636. if (group.pointerEventObservable !== null) {
  17637. group.pointerEventObservable.notifyObservers(e, s.mask);
  17638. }
  17639. });
  17640. res.sprite = sprite;
  17641. }
  17642. if (sprite && noResizeScale) {
  17643. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  17644. sprite.scaleX = relScale.x;
  17645. sprite.scaleY = relScale.y;
  17646. }
  17647. }
  17648. return res;
  17649. };
  17650. /**
  17651. * Internal method used to register a Scene Node to track position for the given group
  17652. * Do not invoke this method, for internal purpose only.
  17653. * @param group the group to track its associated Scene Node
  17654. */
  17655. Canvas2D.prototype._registerTrackedNode = function (group) {
  17656. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  17657. return;
  17658. }
  17659. if (!this._trackedGroups) {
  17660. this._trackedGroups = new Array();
  17661. }
  17662. this._trackedGroups.push(group);
  17663. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  17664. };
  17665. /**
  17666. * Internal method used to unregister a tracked Scene Node
  17667. * Do not invoke this method, it's for internal purpose only.
  17668. * @param group the group to unregister its tracked Scene Node from.
  17669. */
  17670. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  17671. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  17672. return;
  17673. }
  17674. var i = this._trackedGroups.indexOf(group);
  17675. if (i !== -1) {
  17676. this._trackedGroups.splice(i, 1);
  17677. }
  17678. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  17679. };
  17680. /**
  17681. * Get a Solid Color Brush instance matching the given color.
  17682. * @param color The color to retrieve
  17683. * @return A shared instance of the SolidColorBrush2D class that use the given color
  17684. */
  17685. Canvas2D.GetSolidColorBrush = function (color) {
  17686. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  17687. };
  17688. /**
  17689. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  17690. * @param color The color to retrieve
  17691. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  17692. */
  17693. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  17694. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  17695. };
  17696. /**
  17697. * Get a Gradient Color Brush
  17698. * @param color1 starting color
  17699. * @param color2 engine color
  17700. * @param translation translation vector to apply. default is [0;0]
  17701. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  17702. * @param scale scaling factor to apply. default is 1.
  17703. */
  17704. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  17705. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  17706. if (rotation === void 0) { rotation = 0; }
  17707. if (scale === void 0) { scale = 1; }
  17708. return Canvas2D_1._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  17709. };
  17710. /**
  17711. * Create a solid or gradient brush from a string value.
  17712. * @param brushString should be either
  17713. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  17714. * - "gradient: #FF808080, #FFFFFFF[, [10:20], 180, 1]" for color1, color2, translation, rotation (degree), scale. The last three are optionals, but if specified must be is this order. "gradient:" can be omitted.
  17715. */
  17716. Canvas2D.GetBrushFromString = function (brushString) {
  17717. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  17718. brushString = brushString.trim();
  17719. var split = brushString.split(",");
  17720. // Solid, formatted as: "[solid:]#FF808080"
  17721. if (split.length === 1) {
  17722. var value = null;
  17723. if (brushString.indexOf("solid:") === 0) {
  17724. value = brushString.substr(6).trim();
  17725. }
  17726. else if (brushString.indexOf("#") === 0) {
  17727. value = brushString;
  17728. }
  17729. else {
  17730. return null;
  17731. }
  17732. return Canvas2D_1.GetSolidColorBrushFromHex(value);
  17733. }
  17734. else {
  17735. if (split[0].indexOf("gradient:") === 0) {
  17736. split[0] = split[0].substr(9).trim();
  17737. }
  17738. try {
  17739. var start = BABYLON.Color4.FromHexString(split[0].trim());
  17740. var end = BABYLON.Color4.FromHexString(split[1].trim());
  17741. var t = BABYLON.Vector2.Zero();
  17742. if (split.length > 2) {
  17743. var v = split[2].trim();
  17744. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  17745. return null;
  17746. }
  17747. var sep = v.indexOf(":");
  17748. var x = parseFloat(v.substr(1, sep));
  17749. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  17750. t = new BABYLON.Vector2(x, y);
  17751. }
  17752. var r = 0;
  17753. if (split.length > 3) {
  17754. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  17755. }
  17756. var s = 1;
  17757. if (split.length > 4) {
  17758. s = parseFloat(split[4].trim());
  17759. }
  17760. return Canvas2D_1.GetGradientColorBrush(start, end, t, r, s);
  17761. }
  17762. catch (e) {
  17763. return null;
  17764. }
  17765. }
  17766. };
  17767. return Canvas2D;
  17768. }(BABYLON.Group2D));
  17769. /**
  17770. * In this strategy only the direct children groups of the Canvas will be cached, their whole content (whatever the sub groups they have) into a single bitmap.
  17771. * This strategy doesn't allow primitives added directly as children of the Canvas.
  17772. * You typically want to use this strategy of a screenSpace fullscreen canvas: you don't want a bitmap cache taking the whole screen resolution but still want the main contents (say UI in the topLeft and rightBottom for instance) to be efficiently cached.
  17773. */
  17774. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  17775. /**
  17776. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  17777. * This strategy is typically used if the canvas has some groups that are frequently animated. Unchanged ones will have a steady cache and the others will be refreshed when they change, reducing the redraw operation count to their content only.
  17778. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  17779. * Note that in this mode the Canvas itself is not cached, it only contains the sprites of its direct children group to render, there's no point to cache the whole canvas, sprites will be rendered pretty efficiently, the memory cost would be too great for the value of it.
  17780. */
  17781. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  17782. /**
  17783. * In this strategy the whole canvas is cached into a single bitmap containing every primitives it owns, at the exception of the ones that are owned by a group having the DONTCACHEOVERRIDE behavior (these primitives will be directly drawn to the viewport at each render for screenSpace Canvas or be part of the Canvas cache bitmap for worldSpace Canvas).
  17784. */
  17785. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  17786. /**
  17787. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  17788. * Use this strategy if memory is a concern above rendering performances and/or if the canvas is frequently animated (hence reducing the benefits of caching).
  17789. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  17790. */
  17791. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  17792. /**
  17793. * Observable Mask to be notified before rendering is made
  17794. */
  17795. Canvas2D.RENDEROBSERVABLE_PRE = 1;
  17796. /**
  17797. * Observable Mask to be notified after rendering is made
  17798. */
  17799. Canvas2D.RENDEROBSERVABLE_POST = 2;
  17800. Canvas2D._INSTANCES = [];
  17801. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  17802. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  17803. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  17804. Canvas2D._m = BABYLON.Matrix.Identity();
  17805. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  17806. Canvas2D.tS = BABYLON.Vector3.Zero();
  17807. Canvas2D.tT = BABYLON.Vector3.Zero();
  17808. Canvas2D.tR = BABYLON.Quaternion.Identity();
  17809. Canvas2D._tmpMtx = BABYLON.Matrix.Identity();
  17810. Canvas2D._tmpVec3 = BABYLON.Vector3.Zero();
  17811. /**
  17812. * Define the default size used for both the width and height of a MapTexture to allocate.
  17813. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  17814. */
  17815. Canvas2D._groupTextureCacheSize = 1024;
  17816. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  17817. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  17818. Canvas2D = Canvas2D_1 = __decorate([
  17819. BABYLON.className("Canvas2D", "BABYLON")
  17820. ], Canvas2D);
  17821. BABYLON.Canvas2D = Canvas2D;
  17822. var WorldSpaceCanvas2D = (function (_super) {
  17823. __extends(WorldSpaceCanvas2D, _super);
  17824. /**
  17825. * Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space.
  17826. * This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon.
  17827. * @param scene the Scene that owns the Canvas
  17828. * @param size the dimension of the Canvas in World Space
  17829. * @param settings a combination of settings, possible ones are
  17830. * - children: an array of direct children primitives
  17831. * - id: a text identifier, for information purpose only, default is null.
  17832. * - unitScaleFactor: if specified the created canvas will be with a width of size.width*unitScaleFactor and a height of size.height.unitScaleFactor. If not specified, the unit of 1 is used. You can use this setting when you're dealing with a 3D world with small coordinates and you need a Canvas having bigger coordinates (typically to display text with better quality).
  17833. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  17834. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  17835. * - trackNode: if you want the WorldSpaceCanvas to track the position/rotation/scale of a given Scene Node, use this setting to specify the Node to track
  17836. * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
  17837. * - trackNodeBillboard: if true the WorldSpaceCanvas will always face the screen
  17838. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  17839. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  17840. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is false (the opposite of ScreenSpace).
  17841. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  17842. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  17843. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  17844. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  17845. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  17846. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  17847. * - maxAdaptiveCanvasSize: set the max size (width and height) of the bitmap that will contain the cached version of the WorldSpace Canvas. Default is 1024 or less if it's not supported. In any case the value you give will be clipped by the maximum that WebGL supports on the running device. You can set any size, more than 1024 if you want, but testing proved it's a good max value for non "retina" like screens.
  17848. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  17849. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  17850. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  17851. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  17852. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  17853. */
  17854. function WorldSpaceCanvas2D(scene, size, settings) {
  17855. var _this;
  17856. BABYLON.Prim2DBase._isCanvasInit = true;
  17857. var s = settings;
  17858. s.isScreenSpace = false;
  17859. if (settings.unitScaleFactor != null) {
  17860. s.size = size.multiplyByFloats(settings.unitScaleFactor, settings.unitScaleFactor);
  17861. }
  17862. else {
  17863. s.size = size.clone();
  17864. }
  17865. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  17866. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  17867. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  17868. }
  17869. _this = _super.call(this, scene, settings) || this;
  17870. BABYLON.Prim2DBase._isCanvasInit = false;
  17871. _this._unitScaleFactor = (settings.unitScaleFactor != null) ? settings.unitScaleFactor : 1;
  17872. _this._renderableData._useMipMap = true;
  17873. _this._renderableData._anisotropicLevel = 8;
  17874. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  17875. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  17876. //}
  17877. _this._trackNode = (settings.trackNode != null) ? settings.trackNode : null;
  17878. _this._trackNodeOffset = (settings.trackNodeOffset != null) ? settings.trackNodeOffset : BABYLON.Vector3.Zero();
  17879. _this._trackNodeBillboard = (settings.trackNodeBillboard != null) ? settings.trackNodeBillboard : true;
  17880. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  17881. _this._customWorldSpaceNode = !createWorldSpaceNode;
  17882. var id = settings ? settings.id || null : null;
  17883. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  17884. var capMaxTextSize = _this.engine.getCaps().maxRenderTextureSize;
  17885. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 1K if allowed otherwise the max allowed
  17886. if (settings.maxAdaptiveCanvasSize == null) {
  17887. _this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  17888. }
  17889. else {
  17890. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  17891. _this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  17892. }
  17893. if (createWorldSpaceNode) {
  17894. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, _this);
  17895. var vertexData = BABYLON.VertexData.CreatePlane({
  17896. width: size.width,
  17897. height: size.height,
  17898. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  17899. });
  17900. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  17901. _this.applyCachedTexture(vertexData, mtl);
  17902. vertexData.applyToMesh(plane, true);
  17903. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  17904. mtl.disableLighting = true;
  17905. mtl.useAlphaFromDiffuseTexture = true;
  17906. if (settings && settings.sideOrientation) {
  17907. mtl.backFaceCulling = (settings.sideOrientation === BABYLON.Mesh.DEFAULTSIDE || settings.sideOrientation === BABYLON.Mesh.FRONTSIDE);
  17908. }
  17909. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  17910. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  17911. plane.material = mtl;
  17912. _this._worldSpaceNode = plane;
  17913. }
  17914. else {
  17915. _this._worldSpaceNode = settings.customWorldSpaceNode;
  17916. _this.applyCachedTexture(null, null);
  17917. }
  17918. _this.propertyChanged.add(function (e, st) {
  17919. if (e.propertyName !== "isVisible") {
  17920. return;
  17921. }
  17922. var mesh = _this._worldSpaceNode;
  17923. if (mesh) {
  17924. mesh.isVisible = e.newValue;
  17925. }
  17926. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  17927. return _this;
  17928. }
  17929. WorldSpaceCanvas2D.prototype.dispose = function () {
  17930. if (!_super.prototype.dispose.call(this)) {
  17931. return false;
  17932. }
  17933. if (!this._customWorldSpaceNode && this._worldSpaceNode) {
  17934. this._worldSpaceNode.dispose();
  17935. this._worldSpaceNode = null;
  17936. }
  17937. };
  17938. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNode", {
  17939. get: function () {
  17940. return this._trackNode;
  17941. },
  17942. set: function (value) {
  17943. if (this._trackNode === value) {
  17944. return;
  17945. }
  17946. this._trackNode = value;
  17947. },
  17948. enumerable: true,
  17949. configurable: true
  17950. });
  17951. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeOffset", {
  17952. get: function () {
  17953. return this._trackNodeOffset;
  17954. },
  17955. set: function (value) {
  17956. if (!this._trackNodeOffset) {
  17957. this._trackNodeOffset = value.clone();
  17958. }
  17959. else {
  17960. this._trackNodeOffset.copyFrom(value);
  17961. }
  17962. },
  17963. enumerable: true,
  17964. configurable: true
  17965. });
  17966. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeBillboard", {
  17967. get: function () {
  17968. return this._trackNodeBillboard;
  17969. },
  17970. set: function (value) {
  17971. this._trackNodeBillboard = value;
  17972. },
  17973. enumerable: true,
  17974. configurable: true
  17975. });
  17976. return WorldSpaceCanvas2D;
  17977. }(Canvas2D));
  17978. WorldSpaceCanvas2D = __decorate([
  17979. BABYLON.className("WorldSpaceCanvas2D", "BABYLON")
  17980. ], WorldSpaceCanvas2D);
  17981. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  17982. var ScreenSpaceCanvas2D = (function (_super) {
  17983. __extends(ScreenSpaceCanvas2D, _super);
  17984. /**
  17985. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the bottom/left corner of the screen.
  17986. * ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI.
  17987. * All caching strategies will be available.
  17988. * PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5]
  17989. * @param scene the Scene that owns the Canvas
  17990. * @param settings a combination of settings, possible ones are
  17991. * - children: an array of direct children primitives
  17992. * - id: a text identifier, for information purpose only
  17993. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  17994. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  17995. * - position: the position of the canvas, relative from the bottom/left of the scene's viewport. Alternatively you can set the x and y properties directly. Default value is [0, 0]
  17996. * - width: the width of the Canvas. you can alternatively use the size setting.
  17997. * - height: the height of the Canvas. you can alternatively use the size setting.
  17998. * - size: the Size of the canvas. Alternatively the width and height properties can be set. If null two behaviors depend on the cachingStrategy: if it's CACHESTRATEGY_CACHECANVAS then it will always auto-fit the rendering device, in all the other modes it will fit the content of the Canvas
  17999. * - renderingPhase: you can specify for which camera and which renderGroup this canvas will render to enable interleaving of 3D/2D content through the use of renderinGroup. As a rendering Group is rendered for each camera, you have to specify in the scope of which camera you want the canvas' render to be made. Default behavior will render the Canvas at the very end of the render loop.
  18000. * - designSize: if you want to set the canvas content based on fixed coordinates whatever the final canvas dimension would be, set this. For instance a designSize of 360*640 will give you the possibility to specify all the children element in this frame. The Canvas' true size will be the HTMLCanvas' size: for instance it could be 720*1280, then a uniform scale of 2 will be applied on the Canvas to keep the absolute coordinates working as expecting. If the ratios of the designSize and the true Canvas size are not the same, then the scale is computed following the designUseHorizAxis member by using either the size of the horizontal axis or the vertical axis.
  18001. * - designUseHorizAxis: you can set this member if you use designSize to specify which axis is priority to compute the scale when the ratio of the canvas' size is different from the designSize's one.
  18002. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  18003. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is true.
  18004. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  18005. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  18006. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  18007. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  18008. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  18009. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  18010. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  18011. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  18012. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  18013. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  18014. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  18015. */
  18016. function ScreenSpaceCanvas2D(scene, settings) {
  18017. var _this;
  18018. BABYLON.Prim2DBase._isCanvasInit = true;
  18019. _this = _super.call(this, scene, settings) || this;
  18020. return _this;
  18021. }
  18022. return ScreenSpaceCanvas2D;
  18023. }(Canvas2D));
  18024. ScreenSpaceCanvas2D = __decorate([
  18025. BABYLON.className("ScreenSpaceCanvas2D", "BABYLON")
  18026. ], ScreenSpaceCanvas2D);
  18027. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  18028. var Canvas2D_1;
  18029. })(BABYLON || (BABYLON = {}));
  18030. var __extends = (this && this.__extends) || function (d, b) {
  18031. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18032. function __() { this.constructor = d; }
  18033. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18034. };
  18035. var BABYLON;
  18036. (function (BABYLON) {
  18037. /**
  18038. * This is the class that is used to display a World Space Canvas into a 3D scene
  18039. */
  18040. var WorldSpaceCanvas2DNode = (function (_super) {
  18041. __extends(WorldSpaceCanvas2DNode, _super);
  18042. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  18043. var _this = _super.call(this, name, scene) || this;
  18044. _this._canvas = canvas;
  18045. return _this;
  18046. }
  18047. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  18048. _super.prototype.dispose.call(this);
  18049. if (this._canvas) {
  18050. this._canvas.dispose();
  18051. this._canvas = null;
  18052. }
  18053. };
  18054. return WorldSpaceCanvas2DNode;
  18055. }(BABYLON.Mesh));
  18056. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  18057. })(BABYLON || (BABYLON = {}));
  18058. var __extends = (this && this.__extends) || function (d, b) {
  18059. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18060. function __() { this.constructor = d; }
  18061. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18062. };
  18063. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18064. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18065. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18066. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18067. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18068. };
  18069. var BABYLON;
  18070. (function (BABYLON) {
  18071. var Command = (function () {
  18072. function Command(execute, canExecute) {
  18073. if (!execute) {
  18074. throw Error("At least an execute lambda must be given at Command creation time");
  18075. }
  18076. this._canExecuteChanged = null;
  18077. this._lastCanExecuteResult = null;
  18078. this.execute = execute;
  18079. this.canExecute = canExecute;
  18080. }
  18081. Command.prototype.canExecute = function (parameter) {
  18082. var res = true;
  18083. if (this._canExecute) {
  18084. res = this._canExecute(parameter);
  18085. }
  18086. if (res !== this._lastCanExecuteResult) {
  18087. if (this._canExecuteChanged && this._canExecuteChanged.hasObservers()) {
  18088. this._canExecuteChanged.notifyObservers(null);
  18089. }
  18090. this._lastCanExecuteResult = res;
  18091. }
  18092. return res;
  18093. };
  18094. Command.prototype.execute = function (parameter) {
  18095. this._execute(parameter);
  18096. };
  18097. Object.defineProperty(Command.prototype, "canExecuteChanged", {
  18098. get: function () {
  18099. if (!this._canExecuteChanged) {
  18100. this._canExecuteChanged = new BABYLON.Observable();
  18101. }
  18102. return this._canExecuteChanged;
  18103. },
  18104. enumerable: true,
  18105. configurable: true
  18106. });
  18107. return Command;
  18108. }());
  18109. BABYLON.Command = Command;
  18110. var UIElement = (function (_super) {
  18111. __extends(UIElement, _super);
  18112. function UIElement(settings) {
  18113. var _this = _super.call(this) || this;
  18114. if (!settings) {
  18115. throw Error("A settings object must be passed with at least either a parent or owner parameter");
  18116. }
  18117. var type = BABYLON.Tools.getFullClassName(_this);
  18118. _this._ownerWindow = null;
  18119. _this._parent = null;
  18120. _this._visualPlaceholder = null;
  18121. _this._visualTemplateRoot = null;
  18122. _this._visualChildrenPlaceholder = null;
  18123. _this._hierarchyDepth = 0;
  18124. _this._renderingTemplateName = (settings.templateName != null) ? settings.templateName : GUIManager.DefaultTemplateName;
  18125. _this._style = (settings.styleName != null) ? GUIManager.getStyle(type, settings.styleName) : null;
  18126. _this._flags = 0;
  18127. _this._id = (settings.id != null) ? settings.id : null;
  18128. _this._uid = null;
  18129. _this._width = (settings.width != null) ? settings.width : null;
  18130. _this._height = (settings.height != null) ? settings.height : null;
  18131. _this._minWidth = (settings.minWidth != null) ? settings.minWidth : 0;
  18132. _this._minHeight = (settings.minHeight != null) ? settings.minHeight : 0;
  18133. _this._maxWidth = (settings.maxWidth != null) ? settings.maxWidth : Number.MAX_VALUE;
  18134. _this._maxHeight = (settings.maxHeight != null) ? settings.maxHeight : Number.MAX_VALUE;
  18135. _this._margin = null;
  18136. _this._padding = null;
  18137. _this._marginAlignment = null;
  18138. _this._setFlags(UIElement.flagIsVisible | UIElement.flagIsEnabled);
  18139. // Default Margin Alignment for UIElement is stretch for horizontal/vertical and not left/bottom (which is the default for Canvas2D Primitives)
  18140. //this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  18141. //this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  18142. // Set the layout/margin stuffs
  18143. if (settings.marginTop) {
  18144. _this.margin.setTop(settings.marginTop);
  18145. }
  18146. if (settings.marginLeft) {
  18147. _this.margin.setLeft(settings.marginLeft);
  18148. }
  18149. if (settings.marginRight) {
  18150. _this.margin.setRight(settings.marginRight);
  18151. }
  18152. if (settings.marginBottom) {
  18153. _this.margin.setBottom(settings.marginBottom);
  18154. }
  18155. if (settings.margin) {
  18156. if (typeof settings.margin === "string") {
  18157. _this.margin.fromString(settings.margin);
  18158. }
  18159. else {
  18160. _this.margin.fromUniformPixels(settings.margin);
  18161. }
  18162. }
  18163. if (settings.marginHAlignment) {
  18164. _this.marginAlignment.horizontal = settings.marginHAlignment;
  18165. }
  18166. if (settings.marginVAlignment) {
  18167. _this.marginAlignment.vertical = settings.marginVAlignment;
  18168. }
  18169. if (settings.marginAlignment) {
  18170. _this.marginAlignment.fromString(settings.marginAlignment);
  18171. }
  18172. if (settings.paddingTop) {
  18173. _this.padding.setTop(settings.paddingTop);
  18174. }
  18175. if (settings.paddingLeft) {
  18176. _this.padding.setLeft(settings.paddingLeft);
  18177. }
  18178. if (settings.paddingRight) {
  18179. _this.padding.setRight(settings.paddingRight);
  18180. }
  18181. if (settings.paddingBottom) {
  18182. _this.padding.setBottom(settings.paddingBottom);
  18183. }
  18184. if (settings.padding) {
  18185. _this.padding.fromString(settings.padding);
  18186. }
  18187. if (settings.paddingHAlignment) {
  18188. _this.paddingAlignment.horizontal = settings.paddingHAlignment;
  18189. }
  18190. if (settings.paddingVAlignment) {
  18191. _this.paddingAlignment.vertical = settings.paddingVAlignment;
  18192. }
  18193. if (settings.paddingAlignment) {
  18194. _this.paddingAlignment.fromString(settings.paddingAlignment);
  18195. }
  18196. if (settings.parent != null) {
  18197. _this._parent = settings.parent;
  18198. _this._hierarchyDepth = _this._parent._hierarchyDepth + 1;
  18199. }
  18200. return _this;
  18201. }
  18202. Object.defineProperty(UIElement, "enabledState", {
  18203. get: function () {
  18204. return UIElement._enableState;
  18205. },
  18206. enumerable: true,
  18207. configurable: true
  18208. });
  18209. Object.defineProperty(UIElement, "disabledState", {
  18210. get: function () {
  18211. return UIElement._disabledState;
  18212. },
  18213. enumerable: true,
  18214. configurable: true
  18215. });
  18216. Object.defineProperty(UIElement, "mouseOverState", {
  18217. get: function () {
  18218. return UIElement._mouseOverState;
  18219. },
  18220. enumerable: true,
  18221. configurable: true
  18222. });
  18223. UIElement.prototype.dispose = function () {
  18224. if (this.isDisposed) {
  18225. return false;
  18226. }
  18227. if (this._renderingTemplate) {
  18228. this._renderingTemplate.detach();
  18229. this._renderingTemplate = null;
  18230. }
  18231. _super.prototype.dispose.call(this);
  18232. // Don't set to null, it may upset somebody...
  18233. this.animations.splice(0);
  18234. return true;
  18235. };
  18236. /**
  18237. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  18238. * Look at Sprite2D for more information
  18239. */
  18240. UIElement.prototype.getAnimatables = function () {
  18241. return new Array();
  18242. };
  18243. // TODO
  18244. // PROPERTIES
  18245. // Style
  18246. // Id
  18247. // Parent/Children
  18248. // ActualWidth/Height, MinWidth/Height, MaxWidth/Height,
  18249. // Alignment/Margin
  18250. // Visibility, IsVisible
  18251. // IsEnabled (is false, control is disabled, no interaction and a specific render state)
  18252. // CacheMode of Visual Elements
  18253. // Focusable/IsFocused
  18254. // IsPointerCaptured, CapturePointer, IsPointerDirectlyOver, IsPointerOver. De-correlate mouse, stylus, touch?
  18255. // ContextMenu
  18256. // Cursor
  18257. // DesiredSize
  18258. // IsInputEnable ?
  18259. // Opacity, OpacityMask ?
  18260. // SnapToDevicePixels
  18261. // Tag
  18262. // ToolTip
  18263. // METHODS
  18264. // BringIntoView (for scrollable content, to move the scroll to bring the given element visible in the parent's area)
  18265. // Capture/ReleaseCapture (mouse, touch, stylus)
  18266. // Focus
  18267. // PointFrom/ToScreen to translate coordinates
  18268. // EVENTS
  18269. // ContextMenuOpening/Closing/Changed
  18270. // DragEnter/LeaveOver, Drop
  18271. // Got/LostFocus
  18272. // IsEnabledChanged
  18273. // IsPointerOver/DirectlyOverChanged
  18274. // IsVisibleChanged
  18275. // KeyDown/Up
  18276. // LayoutUpdated ?
  18277. // Pointer related events
  18278. // SizeChanged
  18279. // ToolTipOpening/Closing
  18280. UIElement.prototype.findById = function (id) {
  18281. if (this._id === id) {
  18282. return this;
  18283. }
  18284. var children = this._getChildren();
  18285. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18286. var child = children_1[_i];
  18287. var r = child.findById(id);
  18288. if (r != null) {
  18289. return r;
  18290. }
  18291. }
  18292. };
  18293. Object.defineProperty(UIElement.prototype, "ownerWindow", {
  18294. get: function () {
  18295. return this._ownerWindow;
  18296. },
  18297. enumerable: true,
  18298. configurable: true
  18299. });
  18300. Object.defineProperty(UIElement.prototype, "style", {
  18301. get: function () {
  18302. if (!this.style) {
  18303. return GUIManager.DefaultStyleName;
  18304. }
  18305. return this._style.name;
  18306. },
  18307. set: function (value) {
  18308. if (this._style && (this._style.name === value)) {
  18309. return;
  18310. }
  18311. var newStyle = null;
  18312. if (value) {
  18313. newStyle = GUIManager.getStyle(BABYLON.Tools.getFullClassName(this), value);
  18314. if (!newStyle) {
  18315. throw Error("Couldn't find Style " + value + " for UIElement " + BABYLON.Tools.getFullClassName(this));
  18316. }
  18317. }
  18318. if (this._style) {
  18319. this._style.removeStyle(this);
  18320. }
  18321. if (newStyle) {
  18322. newStyle.applyStyle(this);
  18323. }
  18324. this._style = newStyle;
  18325. },
  18326. enumerable: true,
  18327. configurable: true
  18328. });
  18329. Object.defineProperty(UIElement.prototype, "id", {
  18330. /**
  18331. * A string that identifies the UIElement.
  18332. * The id is optional and there's possible collision with other UIElement's id as the uniqueness is not supported.
  18333. */
  18334. get: function () {
  18335. return this._id;
  18336. },
  18337. set: function (value) {
  18338. if (this._id === value) {
  18339. return;
  18340. }
  18341. this._id = value;
  18342. },
  18343. enumerable: true,
  18344. configurable: true
  18345. });
  18346. Object.defineProperty(UIElement.prototype, "uid", {
  18347. /**
  18348. * Return a unique id automatically generated.
  18349. * This property is mainly used for serialization to ensure a perfect way of identifying a UIElement
  18350. */
  18351. get: function () {
  18352. if (!this._uid) {
  18353. this._uid = BABYLON.Tools.RandomId();
  18354. }
  18355. return this._uid;
  18356. },
  18357. enumerable: true,
  18358. configurable: true
  18359. });
  18360. Object.defineProperty(UIElement.prototype, "hierarchyDepth", {
  18361. get: function () {
  18362. return this._hierarchyDepth;
  18363. },
  18364. enumerable: true,
  18365. configurable: true
  18366. });
  18367. Object.defineProperty(UIElement.prototype, "parent", {
  18368. get: function () {
  18369. return this._parent;
  18370. },
  18371. set: function (value) {
  18372. this._parent = value;
  18373. },
  18374. enumerable: true,
  18375. configurable: true
  18376. });
  18377. Object.defineProperty(UIElement.prototype, "width", {
  18378. get: function () {
  18379. return this._width;
  18380. },
  18381. set: function (value) {
  18382. this._width = value;
  18383. },
  18384. enumerable: true,
  18385. configurable: true
  18386. });
  18387. Object.defineProperty(UIElement.prototype, "height", {
  18388. get: function () {
  18389. return this._height;
  18390. },
  18391. set: function (value) {
  18392. this._height = value;
  18393. },
  18394. enumerable: true,
  18395. configurable: true
  18396. });
  18397. Object.defineProperty(UIElement.prototype, "minWidth", {
  18398. get: function () {
  18399. return this._minWidth;
  18400. },
  18401. set: function (value) {
  18402. this._minWidth = value;
  18403. },
  18404. enumerable: true,
  18405. configurable: true
  18406. });
  18407. Object.defineProperty(UIElement.prototype, "minHheight", {
  18408. get: function () {
  18409. return this._minHeight;
  18410. },
  18411. enumerable: true,
  18412. configurable: true
  18413. });
  18414. Object.defineProperty(UIElement.prototype, "minHeight", {
  18415. set: function (value) {
  18416. this._minHeight = value;
  18417. },
  18418. enumerable: true,
  18419. configurable: true
  18420. });
  18421. Object.defineProperty(UIElement.prototype, "maxWidth", {
  18422. get: function () {
  18423. return this._maxWidth;
  18424. },
  18425. set: function (value) {
  18426. this._maxWidth = value;
  18427. },
  18428. enumerable: true,
  18429. configurable: true
  18430. });
  18431. Object.defineProperty(UIElement.prototype, "maxHeight", {
  18432. get: function () {
  18433. return this._maxHeight;
  18434. },
  18435. set: function (value) {
  18436. this._maxHeight = value;
  18437. },
  18438. enumerable: true,
  18439. configurable: true
  18440. });
  18441. Object.defineProperty(UIElement.prototype, "actualWidth", {
  18442. get: function () {
  18443. return this._actualWidth;
  18444. },
  18445. set: function (value) {
  18446. this._actualWidth = value;
  18447. },
  18448. enumerable: true,
  18449. configurable: true
  18450. });
  18451. Object.defineProperty(UIElement.prototype, "actualHeight", {
  18452. get: function () {
  18453. return this._actualHeight;
  18454. },
  18455. set: function (value) {
  18456. this._actualHeight = value;
  18457. },
  18458. enumerable: true,
  18459. configurable: true
  18460. });
  18461. Object.defineProperty(UIElement.prototype, "margin", {
  18462. get: function () {
  18463. var _this = this;
  18464. if (!this._margin) {
  18465. this._margin = new BABYLON.PrimitiveThickness(function () {
  18466. if (!_this.parent) {
  18467. return null;
  18468. }
  18469. return _this.parent.margin;
  18470. });
  18471. }
  18472. return this._margin;
  18473. },
  18474. set: function (value) {
  18475. this.margin.copyFrom(value);
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. Object.defineProperty(UIElement.prototype, "_hasMargin", {
  18481. get: function () {
  18482. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  18483. },
  18484. enumerable: true,
  18485. configurable: true
  18486. });
  18487. Object.defineProperty(UIElement.prototype, "padding", {
  18488. get: function () {
  18489. var _this = this;
  18490. if (!this._padding) {
  18491. this._padding = new BABYLON.PrimitiveThickness(function () {
  18492. if (!_this.parent) {
  18493. return null;
  18494. }
  18495. return _this.parent.padding;
  18496. });
  18497. }
  18498. return this._padding;
  18499. },
  18500. set: function (value) {
  18501. this.padding.copyFrom(value);
  18502. },
  18503. enumerable: true,
  18504. configurable: true
  18505. });
  18506. Object.defineProperty(UIElement.prototype, "_hasPadding", {
  18507. get: function () {
  18508. return this._padding !== null && !this._padding.isDefault;
  18509. },
  18510. enumerable: true,
  18511. configurable: true
  18512. });
  18513. Object.defineProperty(UIElement.prototype, "marginAlignment", {
  18514. get: function () {
  18515. if (!this._marginAlignment) {
  18516. this._marginAlignment = new BABYLON.PrimitiveAlignment();
  18517. }
  18518. return this._marginAlignment;
  18519. },
  18520. set: function (value) {
  18521. this.marginAlignment.copyFrom(value);
  18522. },
  18523. enumerable: true,
  18524. configurable: true
  18525. });
  18526. Object.defineProperty(UIElement.prototype, "_hasMarginAlignment", {
  18527. /**
  18528. * Check if there a marginAlignment specified (non null and not default)
  18529. */
  18530. get: function () {
  18531. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(UIElement.prototype, "paddingAlignment", {
  18537. get: function () {
  18538. if (!this._paddingAlignment) {
  18539. this._paddingAlignment = new BABYLON.PrimitiveAlignment();
  18540. }
  18541. return this._paddingAlignment;
  18542. },
  18543. set: function (value) {
  18544. this.paddingAlignment.copyFrom(value);
  18545. },
  18546. enumerable: true,
  18547. configurable: true
  18548. });
  18549. Object.defineProperty(UIElement.prototype, "_hasPaddingAlignment", {
  18550. /**
  18551. * Check if there a marginAlignment specified (non null and not default)
  18552. */
  18553. get: function () {
  18554. return (this._paddingAlignment !== null && !this._paddingAlignment.isDefault);
  18555. },
  18556. enumerable: true,
  18557. configurable: true
  18558. });
  18559. Object.defineProperty(UIElement.prototype, "isVisible", {
  18560. get: function () {
  18561. return this._isFlagSet(UIElement.flagIsVisible);
  18562. },
  18563. set: function (value) {
  18564. if (this.isVisible === value) {
  18565. return;
  18566. }
  18567. this._visualPlaceholder.levelVisible = value;
  18568. this._changeFlags(UIElement.flagIsVisible, value);
  18569. },
  18570. enumerable: true,
  18571. configurable: true
  18572. });
  18573. Object.defineProperty(UIElement.prototype, "isEnabled", {
  18574. get: function () {
  18575. return this._isFlagSet(UIElement.flagIsEnabled);
  18576. },
  18577. set: function (value) {
  18578. this._changeFlags(UIElement.flagIsEnabled, value);
  18579. },
  18580. enumerable: true,
  18581. configurable: true
  18582. });
  18583. Object.defineProperty(UIElement.prototype, "isFocused", {
  18584. get: function () {
  18585. return this._isFlagSet(UIElement.flagIsFocus);
  18586. },
  18587. set: function (value) {
  18588. // If the UIElement doesn't accept focus, set it on its parent
  18589. if (!this.isFocusable) {
  18590. var p = this.parent;
  18591. if (!p) {
  18592. return;
  18593. }
  18594. p.isFocused = value;
  18595. }
  18596. // If the focus is being set, notify the Focus Manager
  18597. if (value) {
  18598. this.ownerWindow.focusManager.setFocusOn(this, this.getFocusScope());
  18599. }
  18600. this._changeFlags(UIElement.flagIsFocus, value);
  18601. },
  18602. enumerable: true,
  18603. configurable: true
  18604. });
  18605. Object.defineProperty(UIElement.prototype, "isMouseOver", {
  18606. get: function () {
  18607. return this._isFlagSet(UIElement.flagIsMouseOver);
  18608. },
  18609. set: function (value) {
  18610. this._changeFlags(UIElement.flagIsMouseOver, value);
  18611. },
  18612. enumerable: true,
  18613. configurable: true
  18614. });
  18615. Object.defineProperty(UIElement.prototype, "isFocusScope", {
  18616. get: function () {
  18617. return this._isFlagSet(UIElement.flagIsFocusScope);
  18618. },
  18619. set: function (value) {
  18620. this._changeFlags(UIElement.flagIsFocusScope, value);
  18621. },
  18622. enumerable: true,
  18623. configurable: true
  18624. });
  18625. Object.defineProperty(UIElement.prototype, "isFocusable", {
  18626. get: function () {
  18627. return this._isFlagSet(UIElement.flagIsFocusable);
  18628. },
  18629. set: function (value) {
  18630. this._changeFlags(UIElement.flagIsFocusable, value);
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. // Look for the nearest parent which is the focus scope. Should always return something as the Window UIElement which is the root of all UI Tree is focus scope (unless the user disable it)
  18636. UIElement.prototype.getFocusScope = function () {
  18637. if (this.isFocusScope) {
  18638. return this;
  18639. }
  18640. var p = this.parent;
  18641. if (!p) {
  18642. return null;
  18643. }
  18644. return p.getFocusScope();
  18645. };
  18646. /**
  18647. * Check if a given flag is set
  18648. * @param flag the flag value
  18649. * @return true if set, false otherwise
  18650. */
  18651. UIElement.prototype._isFlagSet = function (flag) {
  18652. return (this._flags & flag) !== 0;
  18653. };
  18654. /**
  18655. * Check if all given flags are set
  18656. * @param flags the flags ORed
  18657. * @return true if all the flags are set, false otherwise
  18658. */
  18659. UIElement.prototype._areAllFlagsSet = function (flags) {
  18660. return (this._flags & flags) === flags;
  18661. };
  18662. /**
  18663. * Check if at least one flag of the given flags is set
  18664. * @param flags the flags ORed
  18665. * @return true if at least one flag is set, false otherwise
  18666. */
  18667. UIElement.prototype._areSomeFlagsSet = function (flags) {
  18668. return (this._flags & flags) !== 0;
  18669. };
  18670. /**
  18671. * Clear the given flags
  18672. * @param flags the flags to clear
  18673. */
  18674. UIElement.prototype._clearFlags = function (flags) {
  18675. this._flags &= ~flags;
  18676. };
  18677. /**
  18678. * Set the given flags to true state
  18679. * @param flags the flags ORed to set
  18680. * @return the flags state before this call
  18681. */
  18682. UIElement.prototype._setFlags = function (flags) {
  18683. var cur = this._flags;
  18684. this._flags |= flags;
  18685. return cur;
  18686. };
  18687. /**
  18688. * Change the state of the given flags
  18689. * @param flags the flags ORed to change
  18690. * @param state true to set them, false to clear them
  18691. */
  18692. UIElement.prototype._changeFlags = function (flags, state) {
  18693. if (state) {
  18694. this._flags |= flags;
  18695. }
  18696. else {
  18697. this._flags &= ~flags;
  18698. }
  18699. };
  18700. UIElement.prototype._assignTemplate = function (templateName) {
  18701. if (!templateName) {
  18702. templateName = GUIManager.DefaultTemplateName;
  18703. }
  18704. var className = BABYLON.Tools.getFullClassName(this);
  18705. if (!className) {
  18706. throw Error("Couldn't access class name of this UIElement, you have to decorate the type with the className decorator");
  18707. }
  18708. var factory = GUIManager.getRenderingTemplate(className, templateName);
  18709. if (!factory) {
  18710. throw Error("Couldn't get the renderingTemplate " + templateName + " of class " + className);
  18711. }
  18712. this._renderingTemplateName = templateName;
  18713. this._renderingTemplate = factory();
  18714. this._renderingTemplate.attach(this);
  18715. };
  18716. UIElement.prototype._createVisualTree = function () {
  18717. var parentPrim = this.ownerWindow.canvas;
  18718. if (this.parent) {
  18719. parentPrim = this.parent.visualChildrenPlaceholder;
  18720. }
  18721. if (!this._renderingTemplate) {
  18722. this._assignTemplate(this._renderingTemplateName);
  18723. }
  18724. this._visualPlaceholder = new BABYLON.Group2D({ parent: parentPrim, id: "GUI " + BABYLON.Tools.getClassName(this) + " RootGroup of " + this.id });
  18725. var p = this._visualPlaceholder;
  18726. p.addExternalData("_GUIOwnerElement_", this);
  18727. p.dataSource = this;
  18728. p.createSimpleDataBinding(BABYLON.Prim2DBase.widthProperty, "width", BABYLON.DataBinding.MODE_ONEWAY);
  18729. p.createSimpleDataBinding(BABYLON.Prim2DBase.heightProperty, "height", BABYLON.DataBinding.MODE_ONEWAY);
  18730. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualWidthProperty, "actualWidth", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  18731. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualHeightProperty, "actualHeight", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  18732. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "margin", BABYLON.DataBinding.MODE_ONEWAY);
  18733. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "marginAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  18734. this.createVisualTree();
  18735. };
  18736. UIElement.prototype._patchUIElement = function (ownerWindow, parent) {
  18737. if (ownerWindow) {
  18738. if (!this._ownerWindow) {
  18739. ownerWindow._registerVisualToBuild(this);
  18740. }
  18741. this._ownerWindow = ownerWindow;
  18742. }
  18743. this._parent = parent;
  18744. if (parent) {
  18745. this._hierarchyDepth = parent.hierarchyDepth + 1;
  18746. }
  18747. var children = this._getChildren();
  18748. if (children) {
  18749. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  18750. var curChild = children_2[_i];
  18751. curChild._patchUIElement(ownerWindow, this);
  18752. }
  18753. }
  18754. };
  18755. // Overload the SmartPropertyBase's method to provide the additional logic of returning the parent's dataSource if there's no dataSource specified at this level.
  18756. UIElement.prototype._getDataSource = function () {
  18757. var levelDS = _super.prototype._getDataSource.call(this);
  18758. if (levelDS != null) {
  18759. return levelDS;
  18760. }
  18761. var p = this.parent;
  18762. if (p != null) {
  18763. return p.dataSource;
  18764. }
  18765. return null;
  18766. };
  18767. UIElement.prototype.createVisualTree = function () {
  18768. var res = this._renderingTemplate.createVisualTree(this, this._visualPlaceholder);
  18769. this._visualTemplateRoot = res.root;
  18770. this._visualChildrenPlaceholder = res.contentPlaceholder;
  18771. };
  18772. Object.defineProperty(UIElement.prototype, "visualPlaceholder", {
  18773. get: function () {
  18774. return this._visualPlaceholder;
  18775. },
  18776. enumerable: true,
  18777. configurable: true
  18778. });
  18779. Object.defineProperty(UIElement.prototype, "visualTemplateRoot", {
  18780. get: function () {
  18781. return this._visualTemplateRoot;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. Object.defineProperty(UIElement.prototype, "visualChildrenPlaceholder", {
  18787. get: function () {
  18788. return this._visualChildrenPlaceholder;
  18789. },
  18790. enumerable: true,
  18791. configurable: true
  18792. });
  18793. Object.defineProperty(UIElement.prototype, "_position", {
  18794. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  18795. ,
  18796. enumerable: true,
  18797. configurable: true
  18798. });
  18799. return UIElement;
  18800. }(BABYLON.SmartPropertyBase));
  18801. UIElement.UIELEMENT_PROPCOUNT = 16;
  18802. UIElement.flagVisualToBuild = 0x0000001;
  18803. UIElement.flagIsVisible = 0x0000002;
  18804. UIElement.flagIsFocus = 0x0000004;
  18805. UIElement.flagIsFocusScope = 0x0000008;
  18806. UIElement.flagIsFocusable = 0x0000010;
  18807. UIElement.flagIsEnabled = 0x0000020;
  18808. UIElement.flagIsMouseOver = 0x0000040;
  18809. UIElement._enableState = "Enabled";
  18810. UIElement._disabledState = "Disabled";
  18811. UIElement._mouseOverState = "MouseOver";
  18812. __decorate([
  18813. BABYLON.dependencyProperty(0, function (pi) { return UIElement.parentProperty = pi; })
  18814. ], UIElement.prototype, "parent", null);
  18815. __decorate([
  18816. BABYLON.dependencyProperty(1, function (pi) { return UIElement.widthProperty = pi; })
  18817. ], UIElement.prototype, "width", null);
  18818. __decorate([
  18819. BABYLON.dependencyProperty(2, function (pi) { return UIElement.heightProperty = pi; })
  18820. ], UIElement.prototype, "height", null);
  18821. __decorate([
  18822. BABYLON.dependencyProperty(3, function (pi) { return UIElement.minWidthProperty = pi; })
  18823. ], UIElement.prototype, "minWidth", null);
  18824. __decorate([
  18825. BABYLON.dependencyProperty(4, function (pi) { return UIElement.minHeightProperty = pi; })
  18826. ], UIElement.prototype, "minHheight", null);
  18827. __decorate([
  18828. BABYLON.dependencyProperty(5, function (pi) { return UIElement.maxWidthProperty = pi; })
  18829. ], UIElement.prototype, "maxWidth", null);
  18830. __decorate([
  18831. BABYLON.dependencyProperty(6, function (pi) { return UIElement.maxHeightProperty = pi; })
  18832. ], UIElement.prototype, "maxHeight", null);
  18833. __decorate([
  18834. BABYLON.dependencyProperty(7, function (pi) { return UIElement.actualWidthProperty = pi; })
  18835. ], UIElement.prototype, "actualWidth", null);
  18836. __decorate([
  18837. BABYLON.dependencyProperty(8, function (pi) { return UIElement.actualHeightProperty = pi; })
  18838. ], UIElement.prototype, "actualHeight", null);
  18839. __decorate([
  18840. BABYLON.dynamicLevelProperty(9, function (pi) { return UIElement.marginProperty = pi; })
  18841. ], UIElement.prototype, "margin", null);
  18842. __decorate([
  18843. BABYLON.dynamicLevelProperty(10, function (pi) { return UIElement.paddingProperty = pi; })
  18844. ], UIElement.prototype, "padding", null);
  18845. __decorate([
  18846. BABYLON.dynamicLevelProperty(11, function (pi) { return UIElement.marginAlignmentProperty = pi; })
  18847. ], UIElement.prototype, "marginAlignment", null);
  18848. __decorate([
  18849. BABYLON.dynamicLevelProperty(12, function (pi) { return UIElement.paddingAlignmentProperty = pi; })
  18850. ], UIElement.prototype, "paddingAlignment", null);
  18851. __decorate([
  18852. BABYLON.dynamicLevelProperty(13, function (pi) { return UIElement.isEnabledProperty = pi; })
  18853. ], UIElement.prototype, "isEnabled", null);
  18854. __decorate([
  18855. BABYLON.dynamicLevelProperty(14, function (pi) { return UIElement.isFocusedProperty = pi; })
  18856. ], UIElement.prototype, "isFocused", null);
  18857. __decorate([
  18858. BABYLON.dynamicLevelProperty(15, function (pi) { return UIElement.isMouseOverProperty = pi; })
  18859. ], UIElement.prototype, "isMouseOver", null);
  18860. BABYLON.UIElement = UIElement;
  18861. var UIElementStyle = (function () {
  18862. function UIElementStyle() {
  18863. }
  18864. Object.defineProperty(UIElementStyle.prototype, "name", {
  18865. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  18866. ,
  18867. enumerable: true,
  18868. configurable: true
  18869. });
  18870. return UIElementStyle;
  18871. }());
  18872. BABYLON.UIElementStyle = UIElementStyle;
  18873. var GUIManager = (function () {
  18874. function GUIManager() {
  18875. }
  18876. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18877. // DATA TEMPLATE MANAGER
  18878. GUIManager.registerDataTemplate = function (className, factory) {
  18879. };
  18880. // DATA TEMPLATE MANAGER
  18881. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18882. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18883. // STYLE MANAGER
  18884. GUIManager.getStyle = function (uiElType, styleName) {
  18885. var styles = GUIManager.stylesByUIElement.get(uiElType);
  18886. if (!styles) {
  18887. throw Error("The type " + uiElType + " is unknown, no style were registered for it.");
  18888. }
  18889. var style = styles.get(styleName);
  18890. if (!style) {
  18891. throw Error("Couldn't find Template " + styleName + " of UIElement type " + uiElType);
  18892. }
  18893. return style;
  18894. };
  18895. GUIManager.registerStyle = function (uiElType, templateName, style) {
  18896. var templates = GUIManager.stylesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  18897. if (templates.contains(templateName)) {
  18898. templates[templateName] = style;
  18899. }
  18900. else {
  18901. templates.add(templateName, style);
  18902. }
  18903. };
  18904. Object.defineProperty(GUIManager, "DefaultStyleName", {
  18905. get: function () {
  18906. return GUIManager._defaultStyleName;
  18907. },
  18908. set: function (value) {
  18909. GUIManager._defaultStyleName = value;
  18910. },
  18911. enumerable: true,
  18912. configurable: true
  18913. });
  18914. // STYLE MANAGER
  18915. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18916. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18917. // RENDERING TEMPLATE MANAGER
  18918. GUIManager.getRenderingTemplate = function (uiElType, templateName) {
  18919. var templates = GUIManager.renderingTemplatesByUIElement.get(uiElType);
  18920. if (!templates) {
  18921. throw Error("The type " + uiElType + " is unknown, no Rendering Template were registered for it.");
  18922. }
  18923. var templateFactory = templates.get(templateName);
  18924. if (!templateFactory) {
  18925. throw Error("Couldn't find Template " + templateName + " of UI Element type " + uiElType);
  18926. }
  18927. return templateFactory;
  18928. };
  18929. GUIManager.registerRenderingTemplate = function (uiElType, templateName, factory) {
  18930. var templates = GUIManager.renderingTemplatesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  18931. if (templates.contains(templateName)) {
  18932. templates[templateName] = factory;
  18933. }
  18934. else {
  18935. templates.add(templateName, factory);
  18936. }
  18937. };
  18938. Object.defineProperty(GUIManager, "DefaultTemplateName", {
  18939. get: function () {
  18940. return GUIManager._defaultTemplateName;
  18941. },
  18942. set: function (value) {
  18943. GUIManager._defaultTemplateName = value;
  18944. },
  18945. enumerable: true,
  18946. configurable: true
  18947. });
  18948. return GUIManager;
  18949. }());
  18950. GUIManager.stylesByUIElement = new BABYLON.StringDictionary();
  18951. GUIManager.renderingTemplatesByUIElement = new BABYLON.StringDictionary();
  18952. // RENDERING TEMPLATE MANAGER
  18953. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18954. GUIManager._defaultTemplateName = "Default";
  18955. GUIManager._defaultStyleName = "Default";
  18956. BABYLON.GUIManager = GUIManager;
  18957. var UIElementRenderingTemplateBase = (function () {
  18958. function UIElementRenderingTemplateBase() {
  18959. }
  18960. UIElementRenderingTemplateBase.prototype.attach = function (owner) {
  18961. this._owner = owner;
  18962. };
  18963. UIElementRenderingTemplateBase.prototype.detach = function () {
  18964. };
  18965. Object.defineProperty(UIElementRenderingTemplateBase.prototype, "owner", {
  18966. get: function () {
  18967. return this._owner;
  18968. },
  18969. enumerable: true,
  18970. configurable: true
  18971. });
  18972. return UIElementRenderingTemplateBase;
  18973. }());
  18974. BABYLON.UIElementRenderingTemplateBase = UIElementRenderingTemplateBase;
  18975. function registerWindowRenderingTemplate(uiElType, templateName, factory) {
  18976. return function () {
  18977. GUIManager.registerRenderingTemplate(uiElType, templateName, factory);
  18978. };
  18979. }
  18980. BABYLON.registerWindowRenderingTemplate = registerWindowRenderingTemplate;
  18981. })(BABYLON || (BABYLON = {}));
  18982. var __extends = (this && this.__extends) || function (d, b) {
  18983. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18984. function __() { this.constructor = d; }
  18985. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18986. };
  18987. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18988. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18989. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18990. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  18991. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18992. };
  18993. var BABYLON;
  18994. (function (BABYLON) {
  18995. var StackPanel = StackPanel_1 = (function (_super) {
  18996. __extends(StackPanel, _super);
  18997. function StackPanel(settings) {
  18998. var _this;
  18999. if (!settings) {
  19000. settings = {};
  19001. }
  19002. _this = _super.call(this, settings) || this;
  19003. _this.isOrientationHorizontal = (settings.isOrientationHorizontal == null) ? true : settings.isOrientationHorizontal;
  19004. _this._children = new Array();
  19005. if (settings.children != null) {
  19006. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  19007. var child = _a[_i];
  19008. _this._children.push(child);
  19009. }
  19010. }
  19011. return _this;
  19012. }
  19013. Object.defineProperty(StackPanel.prototype, "isOrientationHorizontal", {
  19014. get: function () {
  19015. return this._isOrientationHorizontal;
  19016. },
  19017. set: function (value) {
  19018. this._isOrientationHorizontal = value;
  19019. },
  19020. enumerable: true,
  19021. configurable: true
  19022. });
  19023. StackPanel.prototype.createVisualTree = function () {
  19024. _super.prototype.createVisualTree.call(this);
  19025. // A StackPanel Control has a Group2D, child of the visualPlaceHolder, which is the Children placeholder.
  19026. // The Children UIElement Tree will be create inside this placeholder.
  19027. this._childrenPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "StackPanel Children Placeholder of " + this.id });
  19028. var p = this._childrenPlaceholder;
  19029. p.layoutEngine = this.isOrientationHorizontal ? BABYLON.StackPanelLayoutEngine.Horizontal : BABYLON.StackPanelLayoutEngine.Vertical;
  19030. // The UIElement padding properties (padding and paddingAlignment) are bound to the Group2D Children placeholder, we bound to the Margin properties as the Group2D acts as an inner element already, so margin of inner is padding.
  19031. p.dataSource = this;
  19032. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  19033. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  19034. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  19035. // But it's not the case for a StackPanel, the placeholder of UIElement Children (the content)
  19036. this._visualChildrenPlaceholder = this._childrenPlaceholder;
  19037. };
  19038. Object.defineProperty(StackPanel.prototype, "children", {
  19039. get: function () {
  19040. return this._children;
  19041. },
  19042. enumerable: true,
  19043. configurable: true
  19044. });
  19045. StackPanel.prototype._getChildren = function () {
  19046. return this.children;
  19047. };
  19048. return StackPanel;
  19049. }(BABYLON.UIElement));
  19050. StackPanel.STACKPANEL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3;
  19051. __decorate([
  19052. BABYLON.dependencyProperty(StackPanel_1.STACKPANEL_PROPCOUNT + 0, function (pi) { return StackPanel_1.orientationHorizontalProperty = pi; })
  19053. ], StackPanel.prototype, "isOrientationHorizontal", null);
  19054. StackPanel = StackPanel_1 = __decorate([
  19055. BABYLON.className("StackPanel", "BABYLON")
  19056. ], StackPanel);
  19057. BABYLON.StackPanel = StackPanel;
  19058. var DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = (function (_super) {
  19059. __extends(DefaultStackPanelRenderingTemplate, _super);
  19060. function DefaultStackPanelRenderingTemplate() {
  19061. return _super.apply(this, arguments) || this;
  19062. }
  19063. DefaultStackPanelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19064. return { root: visualPlaceholder, contentPlaceholder: visualPlaceholder };
  19065. };
  19066. DefaultStackPanelRenderingTemplate.prototype.attach = function (owner) {
  19067. _super.prototype.attach.call(this, owner);
  19068. };
  19069. return DefaultStackPanelRenderingTemplate;
  19070. }(BABYLON.UIElementRenderingTemplateBase));
  19071. DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = __decorate([
  19072. BABYLON.registerWindowRenderingTemplate("BABYLON.StackPanel", "Default", function () { return new DefaultStackPanelRenderingTemplate_1(); })
  19073. ], DefaultStackPanelRenderingTemplate);
  19074. BABYLON.DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate;
  19075. var StackPanel_1, DefaultStackPanelRenderingTemplate_1;
  19076. })(BABYLON || (BABYLON = {}));
  19077. var __extends = (this && this.__extends) || function (d, b) {
  19078. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19079. function __() { this.constructor = d; }
  19080. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19081. };
  19082. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19083. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19084. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19085. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19086. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19087. };
  19088. var BABYLON;
  19089. (function (BABYLON) {
  19090. var Control = Control_1 = (function (_super) {
  19091. __extends(Control, _super);
  19092. function Control(settings) {
  19093. return _super.call(this, settings) || this;
  19094. }
  19095. Object.defineProperty(Control.prototype, "background", {
  19096. get: function () {
  19097. if (!this._background) {
  19098. this._background = new BABYLON.ObservableStringDictionary(false);
  19099. }
  19100. return this._background;
  19101. },
  19102. set: function (value) {
  19103. this.background.copyFrom(value);
  19104. },
  19105. enumerable: true,
  19106. configurable: true
  19107. });
  19108. Object.defineProperty(Control.prototype, "border", {
  19109. get: function () {
  19110. return this._border;
  19111. },
  19112. set: function (value) {
  19113. this._border = value;
  19114. },
  19115. enumerable: true,
  19116. configurable: true
  19117. });
  19118. Object.defineProperty(Control.prototype, "borderThickness", {
  19119. get: function () {
  19120. return this._borderThickness;
  19121. },
  19122. set: function (value) {
  19123. this._borderThickness = value;
  19124. },
  19125. enumerable: true,
  19126. configurable: true
  19127. });
  19128. Object.defineProperty(Control.prototype, "fontName", {
  19129. get: function () {
  19130. return this._fontName;
  19131. },
  19132. set: function (value) {
  19133. this._fontName = value;
  19134. },
  19135. enumerable: true,
  19136. configurable: true
  19137. });
  19138. Object.defineProperty(Control.prototype, "foreground", {
  19139. get: function () {
  19140. return this._foreground;
  19141. },
  19142. set: function (value) {
  19143. this._foreground = value;
  19144. },
  19145. enumerable: true,
  19146. configurable: true
  19147. });
  19148. return Control;
  19149. }(BABYLON.UIElement));
  19150. Control.CONTROL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 5;
  19151. __decorate([
  19152. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 0, function (pi) { return Control_1.backgroundProperty = pi; })
  19153. ], Control.prototype, "background", null);
  19154. __decorate([
  19155. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 1, function (pi) { return Control_1.borderProperty = pi; })
  19156. ], Control.prototype, "border", null);
  19157. __decorate([
  19158. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 2, function (pi) { return Control_1.borderThicknessProperty = pi; })
  19159. ], Control.prototype, "borderThickness", null);
  19160. __decorate([
  19161. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3, function (pi) { return Control_1.fontNameProperty = pi; })
  19162. ], Control.prototype, "fontName", null);
  19163. __decorate([
  19164. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 4, function (pi) { return Control_1.foregroundProperty = pi; })
  19165. ], Control.prototype, "foreground", null);
  19166. Control = Control_1 = __decorate([
  19167. BABYLON.className("Control", "BABYLON")
  19168. ], Control);
  19169. BABYLON.Control = Control;
  19170. var Control_1;
  19171. })(BABYLON || (BABYLON = {}));
  19172. var __extends = (this && this.__extends) || function (d, b) {
  19173. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19174. function __() { this.constructor = d; }
  19175. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19176. };
  19177. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19178. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19179. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19180. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19181. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19182. };
  19183. var BABYLON;
  19184. (function (BABYLON) {
  19185. var ContentControl = ContentControl_1 = (function (_super) {
  19186. __extends(ContentControl, _super);
  19187. function ContentControl(settings) {
  19188. var _this;
  19189. if (!settings) {
  19190. settings = {};
  19191. }
  19192. _this = _super.call(this, settings) || this;
  19193. if (settings.content != null) {
  19194. _this._content = settings.content;
  19195. }
  19196. return _this;
  19197. }
  19198. ContentControl.prototype.dispose = function () {
  19199. if (this.isDisposed) {
  19200. return false;
  19201. }
  19202. if (this.content && this.content.dispose) {
  19203. this.content.dispose();
  19204. this.content = null;
  19205. }
  19206. if (this.__contentUIElement) {
  19207. this.__contentUIElement.dispose();
  19208. this.__contentUIElement = null;
  19209. }
  19210. _super.prototype.dispose.call(this);
  19211. return true;
  19212. };
  19213. Object.defineProperty(ContentControl.prototype, "content", {
  19214. get: function () {
  19215. return this._content;
  19216. },
  19217. set: function (value) {
  19218. this._content = value;
  19219. },
  19220. enumerable: true,
  19221. configurable: true
  19222. });
  19223. Object.defineProperty(ContentControl.prototype, "_contentUIElement", {
  19224. get: function () {
  19225. if (!this.__contentUIElement) {
  19226. this._buildContentUIElement();
  19227. }
  19228. return this.__contentUIElement;
  19229. },
  19230. enumerable: true,
  19231. configurable: true
  19232. });
  19233. ContentControl.prototype._createVisualTree = function () {
  19234. // Base implementation will create the Group2D for the Visual Placeholder and its Visual Tree
  19235. _super.prototype._createVisualTree.call(this);
  19236. // A Content Control has a Group2D, child of the visualPlaceHolder, which is the Content placeholder.
  19237. // The Content UIElement Tree will be create inside this placeholder.
  19238. this._contentPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "ContentControl Content Placeholder of " + this.id });
  19239. var p = this._contentPlaceholder;
  19240. // The UIElement padding properties (padding and paddingAlignment) are bound to the Group2D Content placeholder, we bound to the Margin properties as the Group2D acts as an inner element already, so margin of inner is padding.
  19241. p.dataSource = this;
  19242. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  19243. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  19244. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  19245. // But it's not the case for a ContentControl, the placeholder of UIElement Children (the content)
  19246. this._visualChildrenPlaceholder = this._contentPlaceholder;
  19247. };
  19248. ContentControl.prototype._buildContentUIElement = function () {
  19249. var c = this._content;
  19250. this.__contentUIElement = null;
  19251. // Already a UIElement
  19252. if (c instanceof BABYLON.UIElement) {
  19253. this.__contentUIElement = c;
  19254. }
  19255. else if ((typeof c === "string") || (typeof c === "boolean") || (typeof c === "number")) {
  19256. var l = new BABYLON.Label({ parent: this, id: "Content of " + this.id });
  19257. var binding = new BABYLON.DataBinding();
  19258. binding.propertyPathName = "content";
  19259. binding.stringFormat = function (v) { return "" + v; };
  19260. binding.dataSource = this;
  19261. l.createDataBinding(BABYLON.Label.textProperty, binding);
  19262. this.__contentUIElement = l;
  19263. }
  19264. else {
  19265. }
  19266. if (this.__contentUIElement) {
  19267. this.__contentUIElement._patchUIElement(this.ownerWindow, this);
  19268. }
  19269. };
  19270. ContentControl.prototype._getChildren = function () {
  19271. var children = new Array();
  19272. if (this.content) {
  19273. children.push(this._contentUIElement);
  19274. }
  19275. return children;
  19276. };
  19277. return ContentControl;
  19278. }(BABYLON.Control));
  19279. ContentControl.CONTENTCONTROL_PROPCOUNT = BABYLON.Control.CONTROL_PROPCOUNT + 2;
  19280. __decorate([
  19281. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return ContentControl_1.contentProperty = pi; })
  19282. ], ContentControl.prototype, "content", null);
  19283. ContentControl = ContentControl_1 = __decorate([
  19284. BABYLON.className("ContentControl", "BABYLON")
  19285. ], ContentControl);
  19286. BABYLON.ContentControl = ContentControl;
  19287. var ContentControl_1;
  19288. })(BABYLON || (BABYLON = {}));
  19289. var __extends = (this && this.__extends) || function (d, b) {
  19290. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19291. function __() { this.constructor = d; }
  19292. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19293. };
  19294. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19295. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19296. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19297. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19298. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19299. };
  19300. var BABYLON;
  19301. (function (BABYLON) {
  19302. var FocusScopeData = (function () {
  19303. function FocusScopeData(focusScope) {
  19304. this.focusScope = focusScope;
  19305. this.focusedElement = null;
  19306. }
  19307. return FocusScopeData;
  19308. }());
  19309. var FocusManager = (function () {
  19310. function FocusManager() {
  19311. this._focusScopes = new BABYLON.StringDictionary();
  19312. this._rootScope = new FocusScopeData(null);
  19313. this._activeScope = null;
  19314. }
  19315. FocusManager.prototype.setFocusOn = function (el, focusScope) {
  19316. var fsd = (focusScope != null) ? this._focusScopes.getOrAddWithFactory(focusScope.uid, function (k) { return new FocusScopeData(focusScope); }) : this._rootScope;
  19317. if (fsd.focusedElement !== el) {
  19318. // Remove focus from current
  19319. if (fsd.focusedElement) {
  19320. fsd.focusedElement.isFocused = false;
  19321. }
  19322. fsd.focusedElement = el;
  19323. }
  19324. if (this._activeScope !== fsd) {
  19325. this._activeScope = fsd;
  19326. }
  19327. };
  19328. return FocusManager;
  19329. }());
  19330. BABYLON.FocusManager = FocusManager;
  19331. var GUISceneData = (function () {
  19332. function GUISceneData(scene) {
  19333. this.scene = scene;
  19334. this.screenSpaceCanvas = new BABYLON.ScreenSpaceCanvas2D(scene, { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE });
  19335. this.focusManager = new FocusManager();
  19336. }
  19337. return GUISceneData;
  19338. }());
  19339. var Window = Window_1 = (function (_super) {
  19340. __extends(Window, _super);
  19341. function Window(scene, settings) {
  19342. var _this;
  19343. if (!settings) {
  19344. settings = {};
  19345. }
  19346. _this = _super.call(this, settings) || this;
  19347. // Per default a Window is focus scope
  19348. _this.isFocusScope = true;
  19349. _this.isActive = false;
  19350. if (!_this._UIElementVisualToBuildList) {
  19351. _this._UIElementVisualToBuildList = new Array();
  19352. }
  19353. // Patch the owner and also the parent property through the whole tree
  19354. _this._patchUIElement(_this, null);
  19355. // Screen Space UI
  19356. if (!settings.worldPosition && !settings.worldRotation) {
  19357. _this._sceneData = Window_1.getSceneData(scene);
  19358. _this._canvas = _this._sceneData.screenSpaceCanvas;
  19359. _this._isWorldSpaceCanvas = false;
  19360. _this._left = (settings.left != null) ? settings.left : 0;
  19361. _this._bottom = (settings.bottom != null) ? settings.bottom : 0;
  19362. }
  19363. else {
  19364. var w = (settings.width == null) ? 100 : settings.width;
  19365. var h = (settings.height == null) ? 100 : settings.height;
  19366. var wpos = (settings.worldPosition == null) ? BABYLON.Vector3.Zero() : settings.worldPosition;
  19367. var wrot = (settings.worldRotation == null) ? BABYLON.Quaternion.Identity() : settings.worldRotation;
  19368. _this._canvas = new BABYLON.WorldSpaceCanvas2D(scene, new BABYLON.Size(w, h), { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE, worldPosition: wpos, worldRotation: wrot });
  19369. _this._isWorldSpaceCanvas = true;
  19370. }
  19371. _this._renderObserver = _this._canvas.renderObservable.add(function (e, s) { return _this._canvasPreRender(); }, BABYLON.Canvas2D.RENDEROBSERVABLE_PRE);
  19372. _this._disposeObserver = _this._canvas.disposeObservable.add(function (e, s) { return _this._canvasDisposed(); });
  19373. _this._canvas.propertyChanged.add(function (e, s) {
  19374. if (e.propertyName === "overPrim") {
  19375. _this._overPrimChanged(e.oldValue, e.newValue);
  19376. }
  19377. });
  19378. _this._mouseOverUIElement = null;
  19379. return _this;
  19380. }
  19381. Object.defineProperty(Window.prototype, "canvas", {
  19382. get: function () {
  19383. return this._canvas;
  19384. },
  19385. enumerable: true,
  19386. configurable: true
  19387. });
  19388. Object.defineProperty(Window.prototype, "left", {
  19389. get: function () {
  19390. return this._left;
  19391. },
  19392. set: function (value) {
  19393. var old = new BABYLON.Vector2(this._left, this._bottom);
  19394. this._left = value;
  19395. this.onPropertyChanged("_position", old, this._position);
  19396. },
  19397. enumerable: true,
  19398. configurable: true
  19399. });
  19400. Object.defineProperty(Window.prototype, "bottom", {
  19401. get: function () {
  19402. return this._bottom;
  19403. },
  19404. set: function (value) {
  19405. var old = new BABYLON.Vector2(this._left, this._bottom);
  19406. this._bottom = value;
  19407. this.onPropertyChanged("_position", old, this._position);
  19408. },
  19409. enumerable: true,
  19410. configurable: true
  19411. });
  19412. Object.defineProperty(Window.prototype, "position", {
  19413. get: function () {
  19414. return this._position;
  19415. },
  19416. set: function (value) {
  19417. this._left = value.x;
  19418. this._bottom = value.y;
  19419. },
  19420. enumerable: true,
  19421. configurable: true
  19422. });
  19423. Object.defineProperty(Window.prototype, "isActive", {
  19424. get: function () {
  19425. return this._isActive;
  19426. },
  19427. set: function (value) {
  19428. this._isActive = value;
  19429. },
  19430. enumerable: true,
  19431. configurable: true
  19432. });
  19433. Object.defineProperty(Window.prototype, "focusManager", {
  19434. get: function () {
  19435. return this._sceneData.focusManager;
  19436. },
  19437. enumerable: true,
  19438. configurable: true
  19439. });
  19440. Object.defineProperty(Window.prototype, "_position", {
  19441. get: function () {
  19442. return new BABYLON.Vector2(this.left, this.bottom);
  19443. },
  19444. enumerable: true,
  19445. configurable: true
  19446. });
  19447. Window.prototype.createVisualTree = function () {
  19448. _super.prototype.createVisualTree.call(this);
  19449. var p = this._visualPlaceholder;
  19450. p.createSimpleDataBinding(BABYLON.Group2D.positionProperty, "position");
  19451. };
  19452. Window.prototype._registerVisualToBuild = function (uiel) {
  19453. if (uiel._isFlagSet(BABYLON.UIElement.flagVisualToBuild)) {
  19454. return;
  19455. }
  19456. if (!this._UIElementVisualToBuildList) {
  19457. this._UIElementVisualToBuildList = new Array();
  19458. }
  19459. this._UIElementVisualToBuildList.push(uiel);
  19460. uiel._setFlags(BABYLON.UIElement.flagVisualToBuild);
  19461. };
  19462. Window.prototype._overPrimChanged = function (oldPrim, newPrim) {
  19463. var curOverEl = this._mouseOverUIElement;
  19464. var newOverEl = null;
  19465. var curGroup = newPrim ? newPrim.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  19466. while (curGroup) {
  19467. var uiel = curGroup.getExternalData("_GUIOwnerElement_");
  19468. if (uiel) {
  19469. newOverEl = uiel;
  19470. break;
  19471. }
  19472. curGroup = curGroup.parent ? curGroup.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  19473. }
  19474. if (curOverEl === newOverEl) {
  19475. return;
  19476. }
  19477. if (curOverEl) {
  19478. curOverEl.isMouseOver = false;
  19479. }
  19480. if (newOverEl) {
  19481. newOverEl.isMouseOver = true;
  19482. }
  19483. this._mouseOverUIElement = newOverEl;
  19484. };
  19485. Window.prototype._canvasPreRender = function () {
  19486. // Check if we have visual to create
  19487. if (this._UIElementVisualToBuildList.length > 0) {
  19488. // Sort the UI Element to get the highest (so lowest hierarchy depth) in the hierarchy tree first
  19489. var sortedElementList = this._UIElementVisualToBuildList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  19490. for (var _i = 0, sortedElementList_1 = sortedElementList; _i < sortedElementList_1.length; _i++) {
  19491. var el = sortedElementList_1[_i];
  19492. el._createVisualTree();
  19493. }
  19494. this._UIElementVisualToBuildList.splice(0);
  19495. }
  19496. };
  19497. Window.prototype._canvasDisposed = function () {
  19498. this._canvas.disposeObservable.remove(this._disposeObserver);
  19499. this._canvas.renderObservable.remove(this._renderObserver);
  19500. };
  19501. Window.getSceneData = function (scene) {
  19502. return Window_1._sceneData.getOrAddWithFactory(scene.uid, function (k) { return new GUISceneData(scene); });
  19503. };
  19504. return Window;
  19505. }(BABYLON.ContentControl));
  19506. Window.WINDOW_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 4;
  19507. Window._sceneData = new BABYLON.StringDictionary();
  19508. __decorate([
  19509. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 0, function (pi) { return Window_1.leftProperty = pi; })
  19510. ], Window.prototype, "left", null);
  19511. __decorate([
  19512. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 1, function (pi) { return Window_1.bottomProperty = pi; })
  19513. ], Window.prototype, "bottom", null);
  19514. __decorate([
  19515. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 2, function (pi) { return Window_1.positionProperty = pi; })
  19516. ], Window.prototype, "position", null);
  19517. __decorate([
  19518. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3, function (pi) { return Window_1.isActiveProperty = pi; })
  19519. ], Window.prototype, "isActive", null);
  19520. Window = Window_1 = __decorate([
  19521. BABYLON.className("Window", "BABYLON")
  19522. ], Window);
  19523. BABYLON.Window = Window;
  19524. var DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = (function (_super) {
  19525. __extends(DefaultWindowRenderingTemplate, _super);
  19526. function DefaultWindowRenderingTemplate() {
  19527. return _super.apply(this, arguments) || this;
  19528. }
  19529. DefaultWindowRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19530. var r = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#808080FF" });
  19531. return { root: r, contentPlaceholder: r };
  19532. };
  19533. return DefaultWindowRenderingTemplate;
  19534. }(BABYLON.UIElementRenderingTemplateBase));
  19535. DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = __decorate([
  19536. BABYLON.registerWindowRenderingTemplate("BABYLON.Window", "Default", function () { return new DefaultWindowRenderingTemplate_1(); })
  19537. ], DefaultWindowRenderingTemplate);
  19538. BABYLON.DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate;
  19539. var Window_1, DefaultWindowRenderingTemplate_1;
  19540. })(BABYLON || (BABYLON = {}));
  19541. var __extends = (this && this.__extends) || function (d, b) {
  19542. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19543. function __() { this.constructor = d; }
  19544. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19545. };
  19546. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19547. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19548. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19549. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19550. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19551. };
  19552. var BABYLON;
  19553. (function (BABYLON) {
  19554. var Label = Label_1 = (function (_super) {
  19555. __extends(Label, _super);
  19556. function Label(settings) {
  19557. var _this;
  19558. if (!settings) {
  19559. settings = {};
  19560. }
  19561. _this = _super.call(this, settings) || this;
  19562. if (settings.text != null) {
  19563. _this.text = settings.text;
  19564. }
  19565. return _this;
  19566. }
  19567. Object.defineProperty(Label.prototype, "_position", {
  19568. get: function () {
  19569. return BABYLON.Vector2.Zero();
  19570. },
  19571. enumerable: true,
  19572. configurable: true
  19573. });
  19574. Label.prototype._getChildren = function () {
  19575. return Label_1._emptyArray;
  19576. };
  19577. Label.prototype.createVisualTree = function () {
  19578. _super.prototype.createVisualTree.call(this);
  19579. var p = this._visualChildrenPlaceholder;
  19580. };
  19581. Object.defineProperty(Label.prototype, "text", {
  19582. get: function () {
  19583. return this._text;
  19584. },
  19585. set: function (value) {
  19586. this._text = value;
  19587. },
  19588. enumerable: true,
  19589. configurable: true
  19590. });
  19591. return Label;
  19592. }(BABYLON.Control));
  19593. Label._emptyArray = new Array();
  19594. __decorate([
  19595. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return Label_1.textProperty = pi; })
  19596. ], Label.prototype, "text", null);
  19597. Label = Label_1 = __decorate([
  19598. BABYLON.className("Label", "BABYLON")
  19599. ], Label);
  19600. BABYLON.Label = Label;
  19601. var DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = (function (_super) {
  19602. __extends(DefaultLabelRenderingTemplate, _super);
  19603. function DefaultLabelRenderingTemplate() {
  19604. return _super.apply(this, arguments) || this;
  19605. }
  19606. DefaultLabelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19607. var r = new BABYLON.Text2D("", { parent: visualPlaceholder });
  19608. r.createSimpleDataBinding(BABYLON.Text2D.textProperty, "text");
  19609. r.dataSource = owner;
  19610. return { root: r, contentPlaceholder: r };
  19611. };
  19612. return DefaultLabelRenderingTemplate;
  19613. }(BABYLON.UIElementRenderingTemplateBase));
  19614. DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = __decorate([
  19615. BABYLON.registerWindowRenderingTemplate("BABYLON.Label", "Default", function () { return new DefaultLabelRenderingTemplate_1(); })
  19616. ], DefaultLabelRenderingTemplate);
  19617. BABYLON.DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate;
  19618. var Label_1, DefaultLabelRenderingTemplate_1;
  19619. })(BABYLON || (BABYLON = {}));
  19620. var __extends = (this && this.__extends) || function (d, b) {
  19621. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19622. function __() { this.constructor = d; }
  19623. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19624. };
  19625. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19626. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19627. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19628. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  19629. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19630. };
  19631. var BABYLON;
  19632. (function (BABYLON) {
  19633. var Button = Button_1 = (function (_super) {
  19634. __extends(Button, _super);
  19635. function Button(settings) {
  19636. var _this;
  19637. if (!settings) {
  19638. settings = {};
  19639. }
  19640. _this = _super.call(this, settings) || this;
  19641. if (settings.paddingAlignment == null) {
  19642. _this.paddingAlignment.horizontal = BABYLON.PrimitiveAlignment.AlignCenter;
  19643. _this.paddingAlignment.vertical = BABYLON.PrimitiveAlignment.AlignCenter;
  19644. }
  19645. _this._normalStateBackground = new BABYLON.ObservableStringDictionary(false);
  19646. _this._normalStateBorder = new BABYLON.ObservableStringDictionary(false);
  19647. _this._defaultStateBackground = new BABYLON.ObservableStringDictionary(false);
  19648. _this._defaultStateBorder = new BABYLON.ObservableStringDictionary(false);
  19649. _this._normalStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#337AB7FF"));
  19650. _this._normalStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#7BA9D0FF"));
  19651. _this._normalStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#286090FF"));
  19652. _this._normalStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#1E496EFF"));
  19653. _this._normalStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E6DA4FF"));
  19654. _this._normalStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#77A0C4FF"));
  19655. _this._normalStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#204D74FF"));
  19656. _this._normalStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E5D9EFF"));
  19657. _this._defaultStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  19658. _this._defaultStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  19659. _this._defaultStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#E6E6E6FF"));
  19660. _this._defaultStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#D4D4D4FF"));
  19661. _this._defaultStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#CCCCCCFF"));
  19662. _this._defaultStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#DEDEDEFF"));
  19663. _this._defaultStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#ADADADFF"));
  19664. _this._defaultStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#6C8EC5FF"));
  19665. return _this;
  19666. }
  19667. Object.defineProperty(Button, "pushedState", {
  19668. get: function () {
  19669. return Button_1._pushedState;
  19670. },
  19671. enumerable: true,
  19672. configurable: true
  19673. });
  19674. Object.defineProperty(Button.prototype, "isPushed", {
  19675. get: function () {
  19676. return this._isPushed;
  19677. },
  19678. set: function (value) {
  19679. this._isPushed = value;
  19680. },
  19681. enumerable: true,
  19682. configurable: true
  19683. });
  19684. Object.defineProperty(Button.prototype, "isDefault", {
  19685. get: function () {
  19686. return this._isDefault;
  19687. },
  19688. set: function (value) {
  19689. this._isDefault = value;
  19690. },
  19691. enumerable: true,
  19692. configurable: true
  19693. });
  19694. Object.defineProperty(Button.prototype, "isOutline", {
  19695. get: function () {
  19696. return this._isOutline;
  19697. },
  19698. set: function (value) {
  19699. this._isOutline = value;
  19700. },
  19701. enumerable: true,
  19702. configurable: true
  19703. });
  19704. Object.defineProperty(Button.prototype, "clickObservable", {
  19705. get: function () {
  19706. if (!this._clickObservable) {
  19707. this._clickObservable = new BABYLON.Observable();
  19708. }
  19709. return this._clickObservable;
  19710. },
  19711. enumerable: true,
  19712. configurable: true
  19713. });
  19714. Button.prototype._raiseClick = function () {
  19715. if (this._clickObservable && this._clickObservable.hasObservers()) {
  19716. this._clickObservable.notifyObservers(this);
  19717. }
  19718. };
  19719. Button.prototype.createVisualTree = function () {
  19720. var _this = this;
  19721. _super.prototype.createVisualTree.call(this);
  19722. var p = this._visualPlaceholder;
  19723. p.pointerEventObservable.add(function (e, s) {
  19724. // check if input must be discarded
  19725. if (!_this.isVisible || !_this.isEnabled) {
  19726. return;
  19727. }
  19728. // We reject an event coming from the placeholder because it means it's on an empty spot, so it's not valid.
  19729. if (e.relatedTarget === _this._visualPlaceholder) {
  19730. return;
  19731. }
  19732. if (s.mask === BABYLON.PrimitivePointerInfo.PointerUp) {
  19733. _this._raiseClick();
  19734. _this.isPushed = false;
  19735. }
  19736. else if (s.mask === BABYLON.PrimitivePointerInfo.PointerDown) {
  19737. _this.isPushed = true;
  19738. _this.isFocused = true;
  19739. }
  19740. }, BABYLON.PrimitivePointerInfo.PointerUp | BABYLON.PrimitivePointerInfo.PointerDown);
  19741. };
  19742. Object.defineProperty(Button.prototype, "normalStateBackground", {
  19743. get: function () {
  19744. return this._normalStateBackground;
  19745. },
  19746. enumerable: true,
  19747. configurable: true
  19748. });
  19749. Object.defineProperty(Button.prototype, "defaultStateBackground", {
  19750. get: function () {
  19751. return this._defaultStateBackground;
  19752. },
  19753. enumerable: true,
  19754. configurable: true
  19755. });
  19756. Object.defineProperty(Button.prototype, "normalStateBorder", {
  19757. get: function () {
  19758. return this._normalStateBorder;
  19759. },
  19760. enumerable: true,
  19761. configurable: true
  19762. });
  19763. Object.defineProperty(Button.prototype, "defaultStateBorder", {
  19764. get: function () {
  19765. return this._defaultStateBorder;
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. return Button;
  19771. }(BABYLON.ContentControl));
  19772. Button.BUTTON_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3;
  19773. Button._pushedState = "Pushed";
  19774. __decorate([
  19775. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 0, function (pi) { return Button_1.isPushedProperty = pi; })
  19776. ], Button.prototype, "isPushed", null);
  19777. __decorate([
  19778. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 1, function (pi) { return Button_1.isDefaultProperty = pi; })
  19779. ], Button.prototype, "isDefault", null);
  19780. __decorate([
  19781. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 2, function (pi) { return Button_1.isOutlineProperty = pi; })
  19782. ], Button.prototype, "isOutline", null);
  19783. Button = Button_1 = __decorate([
  19784. BABYLON.className("Button", "BABYLON")
  19785. ], Button);
  19786. BABYLON.Button = Button;
  19787. var DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = (function (_super) {
  19788. __extends(DefaultButtonRenderingTemplate, _super);
  19789. function DefaultButtonRenderingTemplate() {
  19790. return _super.apply(this, arguments) || this;
  19791. }
  19792. DefaultButtonRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19793. this._rect = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#FF8080FF", border: "#FF8080FF", roundRadius: 10, borderThickness: 2 });
  19794. this.stateChange();
  19795. return { root: this._rect, contentPlaceholder: this._rect };
  19796. };
  19797. DefaultButtonRenderingTemplate.prototype.attach = function (owner) {
  19798. var _this = this;
  19799. _super.prototype.attach.call(this, owner);
  19800. this.owner.propertyChanged.add(function (e, s) { return _this.stateChange(); }, BABYLON.UIElement.isEnabledProperty.flagId |
  19801. BABYLON.UIElement.isFocusedProperty.flagId |
  19802. BABYLON.UIElement.isMouseOverProperty.flagId |
  19803. Button.isDefaultProperty.flagId |
  19804. Button.isOutlineProperty.flagId |
  19805. Button.isPushedProperty.flagId);
  19806. // Register for brush change and update the Visual
  19807. var button = owner;
  19808. button.normalStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  19809. button.normalStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  19810. button.defaultStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  19811. button.defaultStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  19812. };
  19813. DefaultButtonRenderingTemplate.prototype.stateChange = function () {
  19814. //console.log("state changed");
  19815. var b = this.owner;
  19816. var state = BABYLON.UIElement.enabledState;
  19817. var bg = b.isDefault ? b.defaultStateBackground.get(state) : b.normalStateBackground.get(state);
  19818. var bd = b.isDefault ? b.defaultStateBorder.get(state) : b.normalStateBorder.get(state);
  19819. if (b.isPushed) {
  19820. state = Button.pushedState;
  19821. if (b.isDefault) {
  19822. bg = b.defaultStateBackground.get(state);
  19823. bd = b.defaultStateBorder.get(state);
  19824. }
  19825. else {
  19826. bg = b.normalStateBackground.get(state);
  19827. bd = b.normalStateBorder.get(state);
  19828. }
  19829. }
  19830. else if (b.isMouseOver) {
  19831. state = BABYLON.UIElement.mouseOverState;
  19832. if (b.isDefault) {
  19833. bg = b.defaultStateBackground.get(state);
  19834. bd = b.defaultStateBorder.get(state);
  19835. }
  19836. else {
  19837. bg = b.normalStateBackground.get(state);
  19838. bd = b.normalStateBorder.get(state);
  19839. }
  19840. }
  19841. else if (!b.isEnabled) {
  19842. state = BABYLON.UIElement.disabledState;
  19843. if (b.isDefault) {
  19844. bg = b.defaultStateBackground.get(state);
  19845. bd = b.defaultStateBorder.get(state);
  19846. }
  19847. else {
  19848. bg = b.normalStateBackground.get(state);
  19849. bd = b.normalStateBorder.get(state);
  19850. }
  19851. }
  19852. this._rect.fill = bg;
  19853. this._rect.border = bd;
  19854. };
  19855. return DefaultButtonRenderingTemplate;
  19856. }(BABYLON.UIElementRenderingTemplateBase));
  19857. DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = __decorate([
  19858. BABYLON.registerWindowRenderingTemplate("BABYLON.Button", "Default", function () { return new DefaultButtonRenderingTemplate_1(); })
  19859. ], DefaultButtonRenderingTemplate);
  19860. BABYLON.DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate;
  19861. var Button_1, DefaultButtonRenderingTemplate_1;
  19862. })(BABYLON || (BABYLON = {}));