babylon.canvas2d.js 908 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497
  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);\ngl_FragColor=color*vColor;\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. var Tri2DInfo = (function () {
  16. /**
  17. * 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
  18. */
  19. function Tri2DInfo(a, b, c) {
  20. if (a === null && b === null && c === null) {
  21. this.a = BABYLON.Vector2.Zero();
  22. this.b = BABYLON.Vector2.Zero();
  23. this.c = BABYLON.Vector2.Zero();
  24. this.center = BABYLON.Vector2.Zero();
  25. this.radius = 0;
  26. return;
  27. }
  28. this.a = a.clone();
  29. this.b = b.clone();
  30. this.c = c.clone();
  31. this._updateCenterRadius();
  32. }
  33. Tri2DInfo.Zero = function () {
  34. return new Tri2DInfo(null, null, null);
  35. };
  36. Tri2DInfo.prototype.set = function (a, b, c) {
  37. this.a.copyFrom(a);
  38. this.b.copyFrom(b);
  39. this.c.copyFrom(c);
  40. this._updateCenterRadius();
  41. };
  42. Tri2DInfo.prototype.transformInPlace = function (transform) {
  43. BABYLON.Vector2.TransformToRef(this.a, transform, this.a);
  44. BABYLON.Vector2.TransformToRef(this.b, transform, this.b);
  45. BABYLON.Vector2.TransformToRef(this.c, transform, this.c);
  46. this._updateCenterRadius();
  47. };
  48. Tri2DInfo.prototype.doesContain = function (p) {
  49. return BABYLON.Vector2.PointInTriangle(p, this.a, this.b, this.c);
  50. };
  51. Tri2DInfo.prototype._updateCenterRadius = function () {
  52. this.center.x = (this.a.x + this.b.x + this.c.x) / 3;
  53. this.center.y = (this.a.y + this.b.y + this.c.y) / 3;
  54. var la = BABYLON.Vector2.DistanceSquared(this.a, this.center);
  55. var lb = BABYLON.Vector2.DistanceSquared(this.b, this.center);
  56. var lc = BABYLON.Vector2.DistanceSquared(this.c, this.center);
  57. var rs = Math.max(Math.max(la, lb), lc);
  58. this.radius = Math.sqrt(rs);
  59. };
  60. return Tri2DInfo;
  61. }());
  62. BABYLON.Tri2DInfo = Tri2DInfo;
  63. var Tri2DArray = (function () {
  64. function Tri2DArray(count) {
  65. this._count = count;
  66. this._array = new Float32Array(9 * count);
  67. }
  68. Tri2DArray.prototype.clear = function (count) {
  69. if (this._count === count) {
  70. return;
  71. }
  72. this._count = count;
  73. this._array = new Float32Array(9 * count);
  74. };
  75. Tri2DArray.prototype.storeTriangle = function (index, a, b, c) {
  76. var center = new BABYLON.Vector2((a.x + b.x + c.x) / 3, (a.y + b.y + c.y) / 3);
  77. var la = BABYLON.Vector2.DistanceSquared(a, center);
  78. var lb = BABYLON.Vector2.DistanceSquared(b, center);
  79. var lc = BABYLON.Vector2.DistanceSquared(c, center);
  80. var rs = Math.max(Math.max(la, lb), lc);
  81. var radius = Math.sqrt(rs);
  82. var offset = index * 9;
  83. this._array[offset + 0] = a.x;
  84. this._array[offset + 1] = a.y;
  85. this._array[offset + 2] = b.x;
  86. this._array[offset + 3] = b.y;
  87. this._array[offset + 4] = c.x;
  88. this._array[offset + 5] = c.y;
  89. this._array[offset + 6] = center.x;
  90. this._array[offset + 7] = center.y;
  91. this._array[offset + 8] = radius;
  92. };
  93. /**
  94. * Store a triangle in a Tri2DInfo object
  95. * @param index the index of the triangle to store
  96. * @param tri2dInfo the instance that will contain the data, it must be already allocated with its inner object also allocated
  97. */
  98. Tri2DArray.prototype.storeToTri2DInfo = function (index, tri2dInfo) {
  99. if (index >= this._count) {
  100. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  101. }
  102. var offset = index * 9;
  103. tri2dInfo.a.x = this._array[offset + 0];
  104. tri2dInfo.a.y = this._array[offset + 1];
  105. tri2dInfo.b.x = this._array[offset + 2];
  106. tri2dInfo.b.y = this._array[offset + 3];
  107. tri2dInfo.c.x = this._array[offset + 4];
  108. tri2dInfo.c.y = this._array[offset + 5];
  109. tri2dInfo.center.x = this._array[offset + 6];
  110. tri2dInfo.center.y = this._array[offset + 7];
  111. tri2dInfo.radius = this._array[offset + 8];
  112. };
  113. Tri2DArray.prototype.transformAndStoreToTri2DInfo = function (index, tri2dInfo, transform) {
  114. if (index >= this._count) {
  115. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  116. }
  117. var offset = index * 9;
  118. tri2dInfo.a.x = this._array[offset + 0];
  119. tri2dInfo.a.y = this._array[offset + 1];
  120. tri2dInfo.b.x = this._array[offset + 2];
  121. tri2dInfo.b.y = this._array[offset + 3];
  122. tri2dInfo.c.x = this._array[offset + 4];
  123. tri2dInfo.c.y = this._array[offset + 5];
  124. tri2dInfo.transformInPlace(transform);
  125. };
  126. Object.defineProperty(Tri2DArray.prototype, "count", {
  127. get: function () {
  128. return this._count;
  129. },
  130. enumerable: true,
  131. configurable: true
  132. });
  133. Tri2DArray.prototype.doesContain = function (p) {
  134. Tri2DArray._checkInitStatics();
  135. var a = Tri2DArray.tempT[0];
  136. for (var i = 0; i < this.count; i++) {
  137. this.storeToTri2DInfo(i, a);
  138. if (a.doesContain(p)) {
  139. return true;
  140. }
  141. }
  142. return false;
  143. };
  144. Tri2DArray.doesIntersect = function (setA, setB, bToATransform) {
  145. Tri2DArray._checkInitStatics();
  146. var a = Tri2DArray.tempT[0];
  147. var b = Tri2DArray.tempT[1];
  148. var v0 = Tri2DArray.tempV[0];
  149. for (var curB = 0; curB < setB.count; curB++) {
  150. setB.transformAndStoreToTri2DInfo(curB, b, bToATransform);
  151. for (var curA = 0; curA < setA.count; curA++) {
  152. setA.storeToTri2DInfo(curA, a);
  153. // Fast rejection first
  154. v0.x = a.center.x - b.center.x;
  155. v0.y = a.center.y - b.center.y;
  156. if (v0.lengthSquared() > ((a.radius * a.radius) + (b.radius * b.radius))) {
  157. continue;
  158. }
  159. // Actual intersection test
  160. if (Math2D.TriangleTriangleDosIntersect(a.a, a.b, a.c, b.a, b.b, b.c)) {
  161. return true;
  162. }
  163. }
  164. }
  165. return false;
  166. };
  167. Tri2DArray._checkInitStatics = function () {
  168. if (Tri2DArray.tempT !== null) {
  169. return;
  170. }
  171. Tri2DArray.tempT = new Array(2);
  172. Tri2DArray.tempT[0] = new Tri2DInfo(null, null, null);
  173. Tri2DArray.tempT[1] = new Tri2DInfo(null, null, null);
  174. Tri2DArray.tempV = new Array(6);
  175. for (var i = 0; i < 6; i++) {
  176. Tri2DArray.tempV[i] = BABYLON.Vector2.Zero();
  177. }
  178. };
  179. return Tri2DArray;
  180. }());
  181. Tri2DArray.tempV = null;
  182. Tri2DArray.tempT = null;
  183. BABYLON.Tri2DArray = Tri2DArray;
  184. var Math2D = (function () {
  185. function Math2D() {
  186. }
  187. Math2D.Dot = function (a, b) {
  188. return a.x * b.x + a.y * b.y;
  189. };
  190. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  191. // 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/
  192. Math2D.LineLineDoesIntersect = function (segA1, segA2, segB1, segB2) {
  193. var s1_x = segA2.x - segA1.x;
  194. var s1_y = segA2.y - segA1.y;
  195. var s2_x = segB2.x - segB1.x;
  196. var s2_y = segB2.y - segB1.y;
  197. var s = (-s1_y * (segA1.x - segB1.x) + s1_x * (segA1.y - segB1.y)) / (-s2_x * s1_y + s1_x * s2_y);
  198. var t = (s2_x * (segA1.y - segB1.y) - s2_y * (segA1.x - segB1.x)) / (-s2_x * s1_y + s1_x * s2_y);
  199. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  200. return true;
  201. }
  202. return false;
  203. };
  204. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  205. Math2D.LineLineIntersection = function (p0, p1, p2, p3) {
  206. var s1_x = p1.x - p0.x;
  207. var s1_y = p1.y - p0.y;
  208. var s2_x = p3.x - p2.x;
  209. var s2_y = p3.y - p2.y;
  210. var s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y);
  211. var t = (s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y);
  212. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  213. return { res: true, xr: p0.x + (t * s1_x), yr: p0.y + (t * s1_y) };
  214. }
  215. return { res: false, xr: 0, yr: 0 };
  216. };
  217. // Tell me that it's slow and I'll answer: yes it is!
  218. // If you fancy to implement the SAT (Separating Axis Theorem) version: BE MY VERY WELCOMED GUEST!
  219. Math2D.TriangleTriangleDosIntersect = function (tri1A, tri1B, tri1C, tri2A, tri2B, tri2C) {
  220. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2B))
  221. return true;
  222. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2C))
  223. return true;
  224. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2B, tri2C))
  225. return true;
  226. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2B))
  227. return true;
  228. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2C))
  229. return true;
  230. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2B, tri2C))
  231. return true;
  232. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2B))
  233. return true;
  234. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2C))
  235. return true;
  236. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2B, tri2C))
  237. return true;
  238. if (BABYLON.Vector2.PointInTriangle(tri2A, tri1A, tri1B, tri1C) &&
  239. BABYLON.Vector2.PointInTriangle(tri2B, tri1A, tri1B, tri1C) &&
  240. BABYLON.Vector2.PointInTriangle(tri2C, tri1A, tri1B, tri1C))
  241. return true;
  242. if (BABYLON.Vector2.PointInTriangle(tri1A, tri2A, tri2B, tri2C) &&
  243. BABYLON.Vector2.PointInTriangle(tri1B, tri2A, tri2B, tri2C) &&
  244. BABYLON.Vector2.PointInTriangle(tri1C, tri2A, tri2B, tri2C))
  245. return true;
  246. return false;
  247. };
  248. return Math2D;
  249. }());
  250. Math2D.v0 = BABYLON.Vector2.Zero();
  251. Math2D.v1 = BABYLON.Vector2.Zero();
  252. Math2D.v2 = BABYLON.Vector2.Zero();
  253. })(BABYLON || (BABYLON = {}));
  254. //# sourceMappingURL=babylon.math2D.js.map
  255. var BABYLON;
  256. (function (BABYLON) {
  257. var PropertyChangedInfo = (function () {
  258. function PropertyChangedInfo() {
  259. }
  260. return PropertyChangedInfo;
  261. }());
  262. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  263. /**
  264. * The purpose of this class is to provide a base implementation of the IPropertyChanged interface for the user to avoid rewriting a code needlessly.
  265. * 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.
  266. * 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)
  267. */
  268. var PropertyChangedBase = (function () {
  269. function PropertyChangedBase() {
  270. this._propertyChanged = null;
  271. }
  272. /**
  273. * Protected method to call when there's a change of value in a property set
  274. * @param propName the name of the concerned property
  275. * @param oldValue its old value
  276. * @param newValue its new value
  277. * @param mask an optional observable mask
  278. */
  279. PropertyChangedBase.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  280. if (this.propertyChanged.hasObservers()) {
  281. var pci = PropertyChangedBase.calling ? new PropertyChangedInfo() : PropertyChangedBase.pci;
  282. pci.oldValue = oldValue;
  283. pci.newValue = newValue;
  284. pci.propertyName = propName;
  285. try {
  286. PropertyChangedBase.calling = true;
  287. this.propertyChanged.notifyObservers(pci, mask);
  288. }
  289. finally {
  290. PropertyChangedBase.calling = false;
  291. }
  292. }
  293. };
  294. Object.defineProperty(PropertyChangedBase.prototype, "propertyChanged", {
  295. /**
  296. * An observable that is triggered when a property (using of the XXXXLevelProperty decorator) has its value changing.
  297. * 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)
  298. */
  299. get: function () {
  300. if (!this._propertyChanged) {
  301. this._propertyChanged = new BABYLON.Observable();
  302. }
  303. return this._propertyChanged;
  304. },
  305. enumerable: true,
  306. configurable: true
  307. });
  308. return PropertyChangedBase;
  309. }());
  310. PropertyChangedBase.pci = new PropertyChangedInfo();
  311. PropertyChangedBase.calling = false;
  312. BABYLON.PropertyChangedBase = PropertyChangedBase;
  313. })(BABYLON || (BABYLON = {}));
  314. //# sourceMappingURL=babylon.IPropertyChanged.js.map
  315. var __extends = (this && this.__extends) || function (d, b) {
  316. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  317. function __() { this.constructor = d; }
  318. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  319. };
  320. var BABYLON;
  321. (function (BABYLON) {
  322. /**
  323. * Class for the ObservableArray.onArrayChanged observable
  324. */
  325. var ArrayChanged = (function () {
  326. function ArrayChanged() {
  327. this.action = 0;
  328. this.newItems = new Array();
  329. this.removedItems = new Array();
  330. this.changedItems = new Array();
  331. this.newStartingIndex = -1;
  332. this.removedStartingIndex = -1;
  333. }
  334. Object.defineProperty(ArrayChanged, "clearAction", {
  335. /**
  336. * The content of the array was totally cleared
  337. */
  338. get: function () {
  339. return ArrayChanged._clearAction;
  340. },
  341. enumerable: true,
  342. configurable: true
  343. });
  344. Object.defineProperty(ArrayChanged, "newItemsAction", {
  345. /**
  346. * A new item was added, the newItems field contains the key/value pairs
  347. */
  348. get: function () {
  349. return ArrayChanged._newItemsAction;
  350. },
  351. enumerable: true,
  352. configurable: true
  353. });
  354. Object.defineProperty(ArrayChanged, "removedItemsAction", {
  355. /**
  356. * An existing item was removed, the removedKey field contains its key
  357. */
  358. get: function () {
  359. return ArrayChanged._removedItemsAction;
  360. },
  361. enumerable: true,
  362. configurable: true
  363. });
  364. Object.defineProperty(ArrayChanged, "changedItemAction", {
  365. /**
  366. * One or many items in the array were changed, the
  367. */
  368. get: function () {
  369. return ArrayChanged._changedItemAction;
  370. },
  371. enumerable: true,
  372. configurable: true
  373. });
  374. Object.defineProperty(ArrayChanged, "replacedArrayAction", {
  375. /**
  376. * The array's content was totally changed
  377. * Depending on the method that used this mode the ChangedArray object may contains more information
  378. */
  379. get: function () {
  380. return ArrayChanged._replacedArrayAction;
  381. },
  382. enumerable: true,
  383. configurable: true
  384. });
  385. Object.defineProperty(ArrayChanged, "lengthChangedAction", {
  386. /**
  387. * The length of the array changed
  388. */
  389. get: function () {
  390. return ArrayChanged._lengthChangedAction;
  391. },
  392. enumerable: true,
  393. configurable: true
  394. });
  395. ArrayChanged.prototype.clear = function () {
  396. this.action = 0;
  397. this.newItems.splice(0);
  398. this.removedItems.splice(0);
  399. this.changedItems.splice(0);
  400. this.removedStartingIndex = this.removedStartingIndex = this.changedStartingIndex = 0;
  401. };
  402. return ArrayChanged;
  403. }());
  404. ArrayChanged._clearAction = 0x1;
  405. ArrayChanged._newItemsAction = 0x2;
  406. ArrayChanged._removedItemsAction = 0x4;
  407. ArrayChanged._replacedArrayAction = 0x8;
  408. ArrayChanged._lengthChangedAction = 0x10;
  409. ArrayChanged._changedItemAction = 0x20;
  410. BABYLON.ArrayChanged = ArrayChanged;
  411. var OAWatchedObjectChangedInfo = (function () {
  412. function OAWatchedObjectChangedInfo() {
  413. }
  414. return OAWatchedObjectChangedInfo;
  415. }());
  416. BABYLON.OAWatchedObjectChangedInfo = OAWatchedObjectChangedInfo;
  417. /**
  418. * This class mimics the Javascript Array and TypeScript Array<T> classes, adding new features concerning the Observable pattern.
  419. *
  420. */
  421. var ObservableArray = (function (_super) {
  422. __extends(ObservableArray, _super);
  423. /**
  424. * Create an Observable Array.
  425. * @param watchObjectsPropertyChange
  426. * @param array and optional array that will be encapsulated by this ObservableArray instance. That's right, it's NOT a copy!
  427. */
  428. function ObservableArray(watchObjectsPropertyChange, array) {
  429. var _this = _super.call(this) || this;
  430. _this.dci = new ArrayChanged();
  431. _this._callingArrayChanged = false;
  432. _this._array = (array != null) ? array : new Array();
  433. _this.dci = new ArrayChanged();
  434. _this._callingArrayChanged = false;
  435. _this._arrayChanged = null;
  436. _this._callingWatchedObjectChanged = false;
  437. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  438. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  439. _this._woci = new OAWatchedObjectChangedInfo();
  440. return _this;
  441. }
  442. Object.defineProperty(ObservableArray.prototype, "length", {
  443. /**
  444. * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
  445. */
  446. get: function () {
  447. return this._array.length;
  448. },
  449. set: function (value) {
  450. if (value === this._array.length) {
  451. return;
  452. }
  453. var oldLength = this._array.length;
  454. this._array.length = value;
  455. this.onPropertyChanged("length", oldLength, this._array.length);
  456. },
  457. enumerable: true,
  458. configurable: true
  459. });
  460. ObservableArray.prototype.getAt = function (index) {
  461. return this._array[index];
  462. };
  463. ObservableArray.prototype.setAt = function (index, value) {
  464. if (index < 0) {
  465. return false;
  466. }
  467. var insertion = (index >= this._array.length) || this._array[index] === undefined;
  468. var oldLength = 0;
  469. if (insertion) {
  470. oldLength = this._array.length;
  471. }
  472. else if (this._watchObjectsPropertyChange) {
  473. this._removeWatchedElement(this._array[index]);
  474. }
  475. this._array[index] = value;
  476. if (this._watchObjectsPropertyChange) {
  477. this._addWatchedElement(value);
  478. }
  479. if (insertion) {
  480. this.onPropertyChanged("length", oldLength, this._array.length);
  481. }
  482. var ac = this.getArrayChangedObject();
  483. if (ac) {
  484. ac.action = insertion ? ArrayChanged.newItemsAction : ArrayChanged.changedItemAction;
  485. if (insertion) {
  486. ac.newItems.splice(0, ac.newItems.length, { index: index, value: value });
  487. ac.newStartingIndex = index;
  488. ac.changedItems.splice(0);
  489. }
  490. else {
  491. ac.newItems.splice(0);
  492. ac.changedStartingIndex = index;
  493. ac.changedItems.splice(0, ac.changedItems.length, { index: index, value: value });
  494. }
  495. ac.removedItems.splice(0);
  496. ac.removedStartingIndex = -1;
  497. this.callArrayChanged(ac);
  498. }
  499. };
  500. /**
  501. * Returns a string representation of an array.
  502. */
  503. ObservableArray.prototype.toString = function () {
  504. return this._array.toString();
  505. };
  506. ObservableArray.prototype.toLocaleString = function () {
  507. return this._array.toLocaleString();
  508. };
  509. /**
  510. * Appends new elements to an array, and returns the new length of the array.
  511. * @param items New elements of the Array.
  512. */
  513. ObservableArray.prototype.push = function () {
  514. var items = [];
  515. for (var _i = 0; _i < arguments.length; _i++) {
  516. items[_i] = arguments[_i];
  517. }
  518. var oldLength = this._array.length;
  519. var n = (_a = this._array).push.apply(_a, items);
  520. if (this._watchObjectsPropertyChange) {
  521. this._addWatchedElement.apply(this, items);
  522. }
  523. this.onPropertyChanged("length", oldLength, this._array.length);
  524. var ac = this.getArrayChangedObject();
  525. if (ac) {
  526. ac.action = ArrayChanged.newItemsAction;
  527. ac.newStartingIndex = oldLength;
  528. this.feedNotifArray.apply(this, [ac.newItems, oldLength].concat(items));
  529. this.callArrayChanged(ac);
  530. }
  531. return n;
  532. var _a;
  533. };
  534. /**
  535. * Removes the last element from an array and returns it.
  536. */
  537. ObservableArray.prototype.pop = function () {
  538. var firstRemove = this._array.length - 1;
  539. var res = this._array.pop();
  540. if (res && this._watchObjectsPropertyChange) {
  541. this._removeWatchedElement(res);
  542. }
  543. if (firstRemove !== -1) {
  544. this.onPropertyChanged("length", this._array.length + 1, this._array.length);
  545. var ac = this.getArrayChangedObject();
  546. if (ac) {
  547. ac.action = ArrayChanged.removedItemsAction;
  548. ac.removedStartingIndex = firstRemove;
  549. this.feedNotifArray(ac.removedItems, firstRemove, res);
  550. }
  551. }
  552. return res;
  553. };
  554. /**
  555. * Combines two or more arrays.
  556. * @param items Additional items to add to the end of array1.
  557. */
  558. ObservableArray.prototype.concat = function () {
  559. var items = [];
  560. for (var _i = 0; _i < arguments.length; _i++) {
  561. items[_i] = arguments[_i];
  562. }
  563. return new ObservableArray(this._watchObjectsPropertyChange, (_a = this._array).concat.apply(_a, items));
  564. var _a;
  565. };
  566. /**
  567. * Adds all the elements of an array separated by the specified separator string.
  568. * @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.
  569. */
  570. ObservableArray.prototype.join = function (separator) {
  571. return this._array.join(separator);
  572. };
  573. /**
  574. * Reverses the elements in an Array.
  575. * The arrayChanged action is
  576. */
  577. ObservableArray.prototype.reverse = function () {
  578. var res = this._array.reverse();
  579. var ac = this.getArrayChangedObject();
  580. ac.action = ArrayChanged.replacedArrayAction;
  581. return res;
  582. };
  583. /**
  584. * Removes the first element from an array and returns it, shift all subsequents element one element before.
  585. * The ArrayChange action is replacedArrayAction, the whole array changes and must be reevaluate as such, the removed element is in removedItems.
  586. *
  587. */
  588. ObservableArray.prototype.shift = function () {
  589. var oldLength = this._array.length;
  590. var res = this._array.shift();
  591. if (this._watchedObjectChanged && res != null) {
  592. this._removeWatchedElement(res);
  593. }
  594. if (oldLength !== 0) {
  595. this.onPropertyChanged("length", oldLength, this._array.length);
  596. var ac = this.getArrayChangedObject();
  597. if (ac) {
  598. ac.action = ArrayChanged.replacedArrayAction;
  599. ac.removedItems.splice(0, ac.removedItems.length, { index: 0, value: res });
  600. ac.newItems.splice(0);
  601. ac.changedItems.splice(0);
  602. ac.removedStartingIndex = 0;
  603. this.callArrayChanged(ac);
  604. }
  605. }
  606. return res;
  607. };
  608. /**
  609. * Returns a section of an array.
  610. * @param start The beginning of the specified portion of the array.
  611. * @param end The end of the specified portion of the array.
  612. */
  613. ObservableArray.prototype.slice = function (start, end) {
  614. return new ObservableArray(this._watchObjectsPropertyChange, this._array.slice(start, end));
  615. };
  616. /**
  617. * Sorts an array.
  618. * @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.
  619. * On the contrary of the Javascript Array's implementation, this method returns nothing
  620. */
  621. ObservableArray.prototype.sort = function (compareFn) {
  622. var oldLength = this._array.length;
  623. this._array.sort(compareFn);
  624. if (oldLength !== 0) {
  625. var ac = this.getArrayChangedObject();
  626. if (ac) {
  627. ac.clear();
  628. ac.action = ArrayChanged.replacedArrayAction;
  629. this.callArrayChanged(ac);
  630. }
  631. }
  632. };
  633. /**
  634. * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
  635. * @param start The zero-based location in the array from which to start removing elements.
  636. * @param deleteCount The number of elements to remove.
  637. * @param items Elements to insert into the array in place of the deleted elements.
  638. */
  639. ObservableArray.prototype.splice = function (start, deleteCount) {
  640. var items = [];
  641. for (var _i = 2; _i < arguments.length; _i++) {
  642. items[_i - 2] = arguments[_i];
  643. }
  644. var oldLength = this._array.length;
  645. if (this._watchObjectsPropertyChange) {
  646. for (var i = start; i < start + deleteCount; i++) {
  647. var val = this._array[i];
  648. if (this._watchObjectsPropertyChange && val != null) {
  649. this._removeWatchedElement(val);
  650. }
  651. }
  652. }
  653. var res = (_a = this._array).splice.apply(_a, [start, deleteCount].concat(items));
  654. if (this._watchObjectsPropertyChange) {
  655. this._addWatchedElement.apply(this, items);
  656. }
  657. if (oldLength !== this._array.length) {
  658. this.onPropertyChanged("length", oldLength, this._array.length);
  659. }
  660. var ac = this.getArrayChangedObject();
  661. if (ac) {
  662. ac.clear();
  663. ac.action = ArrayChanged.replacedArrayAction;
  664. this.callArrayChanged(ac);
  665. }
  666. return res;
  667. var _a;
  668. };
  669. /**
  670. * Inserts new elements at the start of an array.
  671. * @param items Elements to insert at the start of the Array.
  672. * The ChangedArray action is replacedArrayAction, newItems contains the list of the added items
  673. */
  674. ObservableArray.prototype.unshift = function () {
  675. var items = [];
  676. for (var _i = 0; _i < arguments.length; _i++) {
  677. items[_i] = arguments[_i];
  678. }
  679. var oldLength = this._array.length;
  680. var res = (_a = this._array).unshift.apply(_a, items);
  681. if (this._watchObjectsPropertyChange) {
  682. this._addWatchedElement.apply(this, items);
  683. }
  684. this.onPropertyChanged("length", oldLength, this._array.length);
  685. var ac = this.getArrayChangedObject();
  686. if (ac) {
  687. ac.clear();
  688. ac.action = ArrayChanged.replacedArrayAction;
  689. ac.newStartingIndex = 0, this.feedNotifArray.apply(this, [ac.newItems, 0].concat(items));
  690. this.callArrayChanged(ac);
  691. }
  692. return res;
  693. var _a;
  694. };
  695. /**
  696. * Returns the index of the first occurrence of a value in an array.
  697. * @param searchElement The value to locate in the array.
  698. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
  699. */
  700. ObservableArray.prototype.indexOf = function (searchElement, fromIndex) {
  701. return this._array.indexOf(searchElement, fromIndex);
  702. };
  703. /**
  704. * Returns the index of the last occurrence of a specified value in an array.
  705. * @param searchElement The value to locate in the array.
  706. * @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.
  707. */
  708. ObservableArray.prototype.lastIndexOf = function (searchElement, fromIndex) {
  709. return this._array.lastIndexOf(searchElement, fromIndex);
  710. };
  711. /**
  712. * Determines whether all the members of an array satisfy the specified test.
  713. * @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.
  714. * @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.
  715. */
  716. ObservableArray.prototype.every = function (callbackfn, thisArg) {
  717. return this._array.every(callbackfn, thisArg);
  718. };
  719. /**
  720. * Determines whether the specified callback function returns true for any element of an array.
  721. * @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.
  722. * @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.
  723. */
  724. ObservableArray.prototype.some = function (callbackfn, thisArg) {
  725. return this._array.some(callbackfn, thisArg);
  726. };
  727. /**
  728. * Performs the specified action for each element in an array.
  729. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
  730. * @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.
  731. */
  732. ObservableArray.prototype.forEach = function (callbackfn, thisArg) {
  733. return this._array.forEach(callbackfn, thisArg);
  734. };
  735. /**
  736. * Calls a defined callback function on each element of an array, and returns an array that contains the results.
  737. * @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.
  738. * @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.
  739. */
  740. ObservableArray.prototype.map = function (callbackfn, thisArg) {
  741. return this._array.map(callbackfn, thisArg);
  742. };
  743. /**
  744. * Returns the elements of an array that meet the condition specified in a callback function.
  745. * @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.
  746. * @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.
  747. */
  748. ObservableArray.prototype.filter = function (callbackfn, thisArg) {
  749. return this._array.filter(callbackfn, thisArg);
  750. };
  751. /**
  752. * 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.
  753. * @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.
  754. * @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.
  755. */
  756. ObservableArray.prototype.reduce = function (callbackfn, initialValue) {
  757. return this._array.reduce(callbackfn);
  758. };
  759. /**
  760. * 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.
  761. * @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.
  762. * @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.
  763. */
  764. ObservableArray.prototype.reduceRight = function (callbackfn, initialValue) {
  765. return this._array.reduceRight(callbackfn);
  766. };
  767. Object.defineProperty(ObservableArray.prototype, "arrayChanged", {
  768. get: function () {
  769. if (!this._arrayChanged) {
  770. this._arrayChanged = new BABYLON.Observable();
  771. }
  772. return this._arrayChanged;
  773. },
  774. enumerable: true,
  775. configurable: true
  776. });
  777. ObservableArray.prototype.getArrayChangedObject = function () {
  778. if (this._arrayChanged && this._arrayChanged.hasObservers()) {
  779. var ac = this._callingArrayChanged ? new ArrayChanged() : this.dci;
  780. return ac;
  781. }
  782. return null;
  783. };
  784. ObservableArray.prototype.feedNotifArray = function (array, startindIndex) {
  785. var items = [];
  786. for (var _i = 2; _i < arguments.length; _i++) {
  787. items[_i - 2] = arguments[_i];
  788. }
  789. array.splice(0);
  790. for (var i = 0; i < items.length; i++) {
  791. var value = this._array[i + startindIndex];
  792. if (value !== undefined) {
  793. array.push({ index: i + startindIndex, value: value });
  794. }
  795. }
  796. };
  797. ObservableArray.prototype.callArrayChanged = function (ac) {
  798. try {
  799. this._callingArrayChanged = true;
  800. this.arrayChanged.notifyObservers(ac, ac.action);
  801. }
  802. finally {
  803. this._callingArrayChanged = false;
  804. }
  805. };
  806. Object.defineProperty(ObservableArray.prototype, "watchedObjectChanged", {
  807. get: function () {
  808. if (!this._watchedObjectChanged) {
  809. this._watchedObjectChanged = new BABYLON.Observable();
  810. }
  811. return this._watchedObjectChanged;
  812. },
  813. enumerable: true,
  814. configurable: true
  815. });
  816. ObservableArray.prototype._addWatchedElement = function () {
  817. var _this = this;
  818. var items = [];
  819. for (var _i = 0; _i < arguments.length; _i++) {
  820. items[_i] = arguments[_i];
  821. }
  822. var _loop_1 = function (curItem) {
  823. if (curItem["propertyChanged"]) {
  824. var key_1 = curItem["__ObsArrayObjID__"];
  825. // The object may already be part of another ObsArray, so there already be a valid ID
  826. if (!key_1) {
  827. key_1 = BABYLON.Tools.RandomId();
  828. curItem["__ObsArrayObjID__"] = key_1;
  829. }
  830. this_1._watchedObjectList.add(key_1, curItem.propertyChanged.add(function (e, d) {
  831. _this.onWatchedObjectChanged(key_1, curItem, e);
  832. }));
  833. }
  834. };
  835. var this_1 = this;
  836. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  837. var curItem = items_1[_a];
  838. _loop_1(curItem);
  839. }
  840. };
  841. ObservableArray.prototype._removeWatchedElement = function () {
  842. var items = [];
  843. for (var _i = 0; _i < arguments.length; _i++) {
  844. items[_i] = arguments[_i];
  845. }
  846. for (var _a = 0, items_2 = items; _a < items_2.length; _a++) {
  847. var curItem = items_2[_a];
  848. var key = curItem["__ObsArrayObjID__"];
  849. if (key != null) {
  850. var observer = this._watchedObjectList.getAndRemove(key);
  851. curItem.propertyChanged.remove(observer);
  852. }
  853. }
  854. };
  855. ObservableArray.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  856. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  857. var woci = this._callingWatchedObjectChanged ? new OAWatchedObjectChangedInfo() : this._woci;
  858. woci.object = object;
  859. woci.propertyChanged = propChanged;
  860. try {
  861. this._callingWatchedObjectChanged = true;
  862. this.watchedObjectChanged.notifyObservers(woci);
  863. }
  864. finally {
  865. this._callingWatchedObjectChanged = false;
  866. }
  867. }
  868. };
  869. return ObservableArray;
  870. }(BABYLON.PropertyChangedBase));
  871. BABYLON.ObservableArray = ObservableArray;
  872. })(BABYLON || (BABYLON = {}));
  873. //# sourceMappingURL=babylon.observableArray.js.map
  874. var __extends = (this && this.__extends) || function (d, b) {
  875. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  876. function __() { this.constructor = d; }
  877. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  878. };
  879. var BABYLON;
  880. (function (BABYLON) {
  881. /**
  882. * Class for the ObservableStringDictionary.onDictionaryChanged observable
  883. */
  884. var DictionaryChanged = (function () {
  885. function DictionaryChanged() {
  886. }
  887. Object.defineProperty(DictionaryChanged, "clearAction", {
  888. /**
  889. * The content of the dictionary was totally cleared
  890. */
  891. get: function () {
  892. return DictionaryChanged._clearAction;
  893. },
  894. enumerable: true,
  895. configurable: true
  896. });
  897. Object.defineProperty(DictionaryChanged, "newItemAction", {
  898. /**
  899. * A new item was added, the newItem field contains the key/value pair
  900. */
  901. get: function () {
  902. return DictionaryChanged._newItemAction;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. Object.defineProperty(DictionaryChanged, "removedItemAction", {
  908. /**
  909. * An existing item was removed, the removedKey field contains its key
  910. */
  911. get: function () {
  912. return DictionaryChanged._removedItemAction;
  913. },
  914. enumerable: true,
  915. configurable: true
  916. });
  917. Object.defineProperty(DictionaryChanged, "itemValueChangedAction", {
  918. /**
  919. * An existing item had a value change, the changedItem field contains the key/value
  920. */
  921. get: function () {
  922. return DictionaryChanged._itemValueChangedAction;
  923. },
  924. enumerable: true,
  925. configurable: true
  926. });
  927. Object.defineProperty(DictionaryChanged, "replacedAction", {
  928. /**
  929. * The dictionary's content was reset and replaced by the content of another dictionary.
  930. * DictionaryChanged<T> contains no further information about this action
  931. */
  932. get: function () {
  933. return DictionaryChanged._replacedAction;
  934. },
  935. enumerable: true,
  936. configurable: true
  937. });
  938. return DictionaryChanged;
  939. }());
  940. DictionaryChanged._clearAction = 0x1;
  941. DictionaryChanged._newItemAction = 0x2;
  942. DictionaryChanged._removedItemAction = 0x4;
  943. DictionaryChanged._itemValueChangedAction = 0x8;
  944. DictionaryChanged._replacedAction = 0x10;
  945. BABYLON.DictionaryChanged = DictionaryChanged;
  946. var OSDWatchedObjectChangedInfo = (function () {
  947. function OSDWatchedObjectChangedInfo() {
  948. }
  949. return OSDWatchedObjectChangedInfo;
  950. }());
  951. BABYLON.OSDWatchedObjectChangedInfo = OSDWatchedObjectChangedInfo;
  952. var ObservableStringDictionary = (function (_super) {
  953. __extends(ObservableStringDictionary, _super);
  954. function ObservableStringDictionary(watchObjectsPropertyChange) {
  955. var _this = _super.call(this) || this;
  956. _this._propertyChanged = null;
  957. _this._dictionaryChanged = null;
  958. _this.dci = new DictionaryChanged();
  959. _this._callingDicChanged = false;
  960. _this._watchedObjectChanged = null;
  961. _this._callingWatchedObjectChanged = false;
  962. _this._woci = new OSDWatchedObjectChangedInfo();
  963. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  964. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  965. return _this;
  966. }
  967. /**
  968. * This will clear this dictionary and copy the content from the 'source' one.
  969. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  970. * @param source the dictionary to take the content from and copy to this dictionary
  971. */
  972. ObservableStringDictionary.prototype.copyFrom = function (source) {
  973. var _this = this;
  974. var oldCount = this.count;
  975. // Don't rely on this class' implementation for clear/add otherwise tons of notification will be thrown
  976. _super.prototype.clear.call(this);
  977. source.forEach(function (t, v) { return _this._add(t, v, false, _this._watchObjectsPropertyChange); });
  978. this.onDictionaryChanged(DictionaryChanged.replacedAction, null, null, null);
  979. this.onPropertyChanged("count", oldCount, this.count);
  980. };
  981. /**
  982. * Get a value from its key or add it if it doesn't exist.
  983. * This method will ensure you that a given key/data will be present in the dictionary.
  984. * @param key the given key to get the matching value from
  985. * @param factory the factory that will create the value if the key is not present in the dictionary.
  986. * The factory will only be invoked if there's no data for the given key.
  987. * @return the value corresponding to the key.
  988. */
  989. ObservableStringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  990. var _this = this;
  991. var val = _super.prototype.getOrAddWithFactory.call(this, key, function (k) {
  992. var v = factory(key);
  993. _this._add(key, v, true, _this._watchObjectsPropertyChange);
  994. return v;
  995. });
  996. return val;
  997. };
  998. /**
  999. * Add a new key and its corresponding value
  1000. * @param key the key to add
  1001. * @param value the value corresponding to the key
  1002. * @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
  1003. */
  1004. ObservableStringDictionary.prototype.add = function (key, value) {
  1005. return this._add(key, value, true, this._watchObjectsPropertyChange);
  1006. };
  1007. ObservableStringDictionary.prototype.getAndRemove = function (key) {
  1008. var val = _super.prototype.get.call(this, key);
  1009. this._remove(key, true, val);
  1010. return val;
  1011. };
  1012. ObservableStringDictionary.prototype._add = function (key, value, fireNotif, registerWatcher) {
  1013. if (_super.prototype.add.call(this, key, value)) {
  1014. if (fireNotif) {
  1015. this.onDictionaryChanged(DictionaryChanged.newItemAction, { key: key, value: value }, null, null);
  1016. this.onPropertyChanged("count", this.count - 1, this.count);
  1017. }
  1018. if (registerWatcher) {
  1019. this._addWatchedElement(key, value);
  1020. }
  1021. return true;
  1022. }
  1023. return false;
  1024. };
  1025. ObservableStringDictionary.prototype._addWatchedElement = function (key, el) {
  1026. var _this = this;
  1027. if (el["propertyChanged"]) {
  1028. this._watchedObjectList.add(key, el.propertyChanged.add(function (e, d) {
  1029. _this.onWatchedObjectChanged(key, el, e);
  1030. }));
  1031. }
  1032. };
  1033. ObservableStringDictionary.prototype._removeWatchedElement = function (key, el) {
  1034. var observer = this._watchedObjectList.getAndRemove(key);
  1035. if (el["propertyChanged"]) {
  1036. el.propertyChanged.remove(observer);
  1037. }
  1038. };
  1039. ObservableStringDictionary.prototype.set = function (key, value) {
  1040. var oldValue = this.get(key);
  1041. if (this._watchObjectsPropertyChange) {
  1042. this._removeWatchedElement(key, oldValue);
  1043. }
  1044. if (_super.prototype.set.call(this, key, value)) {
  1045. this.onDictionaryChanged(DictionaryChanged.itemValueChangedAction, null, null, { key: key, oldValue: oldValue, newValue: value });
  1046. this._addWatchedElement(key, value);
  1047. return true;
  1048. }
  1049. return false;
  1050. };
  1051. /**
  1052. * Remove a key/value from the dictionary.
  1053. * @param key the key to remove
  1054. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  1055. */
  1056. ObservableStringDictionary.prototype.remove = function (key) {
  1057. return this._remove(key, true);
  1058. };
  1059. ObservableStringDictionary.prototype._remove = function (key, fireNotif, element) {
  1060. if (!element) {
  1061. element = this.get(key);
  1062. }
  1063. if (!element) {
  1064. return false;
  1065. }
  1066. if (_super.prototype.remove.call(this, key) === undefined) {
  1067. return false;
  1068. }
  1069. this.onDictionaryChanged(DictionaryChanged.removedItemAction, null, key, null);
  1070. this.onPropertyChanged("count", this.count + 1, this.count);
  1071. if (this._watchObjectsPropertyChange) {
  1072. this._removeWatchedElement(key, element);
  1073. }
  1074. return true;
  1075. };
  1076. /**
  1077. * Clear the whole content of the dictionary
  1078. */
  1079. ObservableStringDictionary.prototype.clear = function () {
  1080. var _this = this;
  1081. if (this._watchedObjectList) {
  1082. this._watchedObjectList.forEach(function (k, v) {
  1083. var el = _this.get(k);
  1084. _this._removeWatchedElement(k, el);
  1085. });
  1086. this._watchedObjectList.clear();
  1087. }
  1088. var oldCount = this.count;
  1089. _super.prototype.clear.call(this);
  1090. this.onDictionaryChanged(DictionaryChanged.clearAction, null, null, null);
  1091. this.onPropertyChanged("count", oldCount, 0);
  1092. };
  1093. Object.defineProperty(ObservableStringDictionary.prototype, "propertyChanged", {
  1094. get: function () {
  1095. if (!this._propertyChanged) {
  1096. this._propertyChanged = new BABYLON.Observable();
  1097. }
  1098. return this._propertyChanged;
  1099. },
  1100. enumerable: true,
  1101. configurable: true
  1102. });
  1103. ObservableStringDictionary.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  1104. if (this._propertyChanged && this._propertyChanged.hasObservers()) {
  1105. var pci = ObservableStringDictionary.callingPropChanged ? new BABYLON.PropertyChangedInfo() : ObservableStringDictionary.pci;
  1106. pci.oldValue = oldValue;
  1107. pci.newValue = newValue;
  1108. pci.propertyName = propName;
  1109. try {
  1110. ObservableStringDictionary.callingPropChanged = true;
  1111. this.propertyChanged.notifyObservers(pci, mask);
  1112. }
  1113. finally {
  1114. ObservableStringDictionary.callingPropChanged = false;
  1115. }
  1116. }
  1117. };
  1118. Object.defineProperty(ObservableStringDictionary.prototype, "dictionaryChanged", {
  1119. get: function () {
  1120. if (!this._dictionaryChanged) {
  1121. this._dictionaryChanged = new BABYLON.Observable();
  1122. }
  1123. return this._dictionaryChanged;
  1124. },
  1125. enumerable: true,
  1126. configurable: true
  1127. });
  1128. ObservableStringDictionary.prototype.onDictionaryChanged = function (action, newItem, removedKey, changedItem) {
  1129. if (this._dictionaryChanged && this._dictionaryChanged.hasObservers()) {
  1130. var dci = this._callingDicChanged ? new DictionaryChanged() : this.dci;
  1131. dci.action = action;
  1132. dci.newItem = newItem;
  1133. dci.removedKey = removedKey;
  1134. dci.changedItem = changedItem;
  1135. try {
  1136. this._callingDicChanged = true;
  1137. this.dictionaryChanged.notifyObservers(dci, action);
  1138. }
  1139. finally {
  1140. this._callingDicChanged = false;
  1141. }
  1142. }
  1143. };
  1144. Object.defineProperty(ObservableStringDictionary.prototype, "watchedObjectChanged", {
  1145. get: function () {
  1146. if (!this._watchedObjectChanged) {
  1147. this._watchedObjectChanged = new BABYLON.Observable();
  1148. }
  1149. return this._watchedObjectChanged;
  1150. },
  1151. enumerable: true,
  1152. configurable: true
  1153. });
  1154. ObservableStringDictionary.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  1155. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  1156. var woci = this._callingWatchedObjectChanged ? new OSDWatchedObjectChangedInfo() : this._woci;
  1157. woci.key = key;
  1158. woci.object = object;
  1159. woci.propertyChanged = propChanged;
  1160. try {
  1161. this._callingWatchedObjectChanged = true;
  1162. this.watchedObjectChanged.notifyObservers(woci);
  1163. }
  1164. finally {
  1165. this._callingWatchedObjectChanged = false;
  1166. }
  1167. }
  1168. };
  1169. return ObservableStringDictionary;
  1170. }(BABYLON.StringDictionary));
  1171. ObservableStringDictionary.pci = new BABYLON.PropertyChangedInfo();
  1172. ObservableStringDictionary.callingPropChanged = false;
  1173. BABYLON.ObservableStringDictionary = ObservableStringDictionary;
  1174. })(BABYLON || (BABYLON = {}));
  1175. //# sourceMappingURL=babylon.observableStringDictionary.js.map
  1176. var __extends = (this && this.__extends) || function (d, b) {
  1177. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1178. function __() { this.constructor = d; }
  1179. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1180. };
  1181. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  1182. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  1183. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  1184. 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;
  1185. return c > 3 && r && Object.defineProperty(target, key, r), r;
  1186. };
  1187. var BABYLON;
  1188. (function (BABYLON) {
  1189. /**
  1190. * This class given information about a given character.
  1191. */
  1192. var CharInfo = (function () {
  1193. function CharInfo() {
  1194. }
  1195. return CharInfo;
  1196. }());
  1197. BABYLON.CharInfo = CharInfo;
  1198. /**
  1199. * This is an abstract base class to hold a Texture that will contain a FontMap
  1200. */
  1201. var BaseFontTexture = (function (_super) {
  1202. __extends(BaseFontTexture, _super);
  1203. function BaseFontTexture(url, scene, noMipmap, invertY, samplingMode) {
  1204. if (noMipmap === void 0) { noMipmap = false; }
  1205. if (invertY === void 0) { invertY = true; }
  1206. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1207. var _this = _super.call(this, url, scene, noMipmap, invertY, samplingMode) || this;
  1208. _this._cachedFontId = null;
  1209. _this._charInfos = new BABYLON.StringDictionary();
  1210. return _this;
  1211. }
  1212. Object.defineProperty(BaseFontTexture.prototype, "isSuperSampled", {
  1213. /**
  1214. * Is the Font is using Super Sampling (each font texel is doubled).
  1215. */
  1216. get: function () {
  1217. return this._superSample;
  1218. },
  1219. enumerable: true,
  1220. configurable: true
  1221. });
  1222. Object.defineProperty(BaseFontTexture.prototype, "isSignedDistanceField", {
  1223. /**
  1224. * Is the Font was rendered using the Signed Distance Field algorithm
  1225. * @returns {}
  1226. */
  1227. get: function () {
  1228. return this._signedDistanceField;
  1229. },
  1230. enumerable: true,
  1231. configurable: true
  1232. });
  1233. Object.defineProperty(BaseFontTexture.prototype, "spaceWidth", {
  1234. /**
  1235. * Get the Width (in pixel) of the Space character
  1236. */
  1237. get: function () {
  1238. return this._spaceWidth;
  1239. },
  1240. enumerable: true,
  1241. configurable: true
  1242. });
  1243. Object.defineProperty(BaseFontTexture.prototype, "lineHeight", {
  1244. /**
  1245. * Get the Line height (in pixel)
  1246. */
  1247. get: function () {
  1248. return this._lineHeight;
  1249. },
  1250. enumerable: true,
  1251. configurable: true
  1252. });
  1253. /**
  1254. * Measure the width/height that will take a given text
  1255. * @param text the text to measure
  1256. * @param tabulationSize the size (in space character) of the tabulation character, default value must be 4
  1257. */
  1258. BaseFontTexture.prototype.measureText = function (text, tabulationSize) {
  1259. var maxWidth = 0;
  1260. var curWidth = 0;
  1261. var lineCount = 1;
  1262. var charxpos = 0;
  1263. // Parse each char of the string
  1264. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  1265. var char = text_1[_i];
  1266. // Next line feed?
  1267. if (char === "\n") {
  1268. maxWidth = Math.max(maxWidth, curWidth);
  1269. charxpos = 0;
  1270. curWidth = 0;
  1271. ++lineCount;
  1272. continue;
  1273. }
  1274. // Tabulation ?
  1275. if (char === "\t") {
  1276. var nextPos = charxpos + tabulationSize;
  1277. nextPos = nextPos - (nextPos % tabulationSize);
  1278. curWidth += (nextPos - charxpos) * this.spaceWidth;
  1279. charxpos = nextPos;
  1280. continue;
  1281. }
  1282. if (char < " ") {
  1283. continue;
  1284. }
  1285. var ci = this.getChar(char);
  1286. if (!ci) {
  1287. throw new Error("Character " + char + " is not supported by FontTexture " + this.name);
  1288. }
  1289. curWidth += ci.charWidth;
  1290. ++charxpos;
  1291. }
  1292. maxWidth = Math.max(maxWidth, curWidth);
  1293. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  1294. };
  1295. return BaseFontTexture;
  1296. }(BABYLON.Texture));
  1297. BABYLON.BaseFontTexture = BaseFontTexture;
  1298. var BitmapFontInfo = (function () {
  1299. function BitmapFontInfo() {
  1300. this.kerningDic = new BABYLON.StringDictionary();
  1301. this.charDic = new BABYLON.StringDictionary();
  1302. }
  1303. return BitmapFontInfo;
  1304. }());
  1305. BABYLON.BitmapFontInfo = BitmapFontInfo;
  1306. var BitmapFontTexture = (function (_super) {
  1307. __extends(BitmapFontTexture, _super);
  1308. function BitmapFontTexture(scene, bmFontUrl, textureUrl, noMipmap, invertY, samplingMode, onLoad, onError) {
  1309. if (textureUrl === void 0) { textureUrl = null; }
  1310. if (noMipmap === void 0) { noMipmap = false; }
  1311. if (invertY === void 0) { invertY = true; }
  1312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1313. if (onLoad === void 0) { onLoad = null; }
  1314. if (onError === void 0) { onError = null; }
  1315. var _this = _super.call(this, null, scene, noMipmap, invertY, samplingMode) || this;
  1316. _this._usedCounter = 1;
  1317. var xhr = new XMLHttpRequest();
  1318. xhr.onreadystatechange = function () {
  1319. if (xhr.readyState === XMLHttpRequest.DONE) {
  1320. if (xhr.status === 200) {
  1321. var ext = bmFontUrl.split('.').pop().split(/\#|\?/)[0];
  1322. var plugins = BitmapFontTexture.plugins.get(ext.toLocaleLowerCase());
  1323. if (!plugins) {
  1324. if (onError) {
  1325. onError("couldn't find a plugin for this file extension", -1);
  1326. }
  1327. return;
  1328. }
  1329. var _loop_1 = function (p) {
  1330. var ret = p.loadFont(xhr.response, scene, invertY);
  1331. if (ret) {
  1332. var bfi = ret.bfi;
  1333. if (textureUrl != null) {
  1334. bfi.textureUrl = textureUrl;
  1335. }
  1336. else {
  1337. var baseUrl = bmFontUrl.substr(0, bmFontUrl.lastIndexOf("/") + 1);
  1338. bfi.textureUrl = baseUrl + bfi.textureFile;
  1339. }
  1340. _this._texture = scene.getEngine().createTexture(bfi.textureUrl, noMipmap, invertY, scene, samplingMode, function () {
  1341. if (ret.bfi && onLoad) {
  1342. onLoad();
  1343. }
  1344. });
  1345. _this._lineHeight = bfi.lineHeight;
  1346. _this._charInfos.copyFrom(bfi.charDic);
  1347. var ci = _this.getChar(" ");
  1348. if (ci) {
  1349. _this._spaceWidth = ci.charWidth;
  1350. }
  1351. else {
  1352. _this._charInfos.first(function (k, v) { return _this._spaceWidth = v.charWidth; });
  1353. }
  1354. if (!ret.bfi && onError) {
  1355. onError(ret.errorMsg, ret.errorCode);
  1356. }
  1357. return { value: void 0 };
  1358. }
  1359. };
  1360. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  1361. var p = plugins_1[_i];
  1362. var state_1 = _loop_1(p);
  1363. if (typeof state_1 === "object")
  1364. return state_1.value;
  1365. }
  1366. if (onError) {
  1367. onError("No plugin to load this BMFont file format", -1);
  1368. }
  1369. }
  1370. else {
  1371. if (onError) {
  1372. onError("Couldn't load file through HTTP Request, HTTP Status " + xhr.status, xhr.status);
  1373. }
  1374. }
  1375. }
  1376. };
  1377. xhr.open("GET", bmFontUrl, true);
  1378. xhr.send();
  1379. return _this;
  1380. }
  1381. BitmapFontTexture.GetCachedFontTexture = function (scene, fontTexture) {
  1382. var dic = scene.getOrAddExternalDataWithFactory("BitmapFontTextureCache", function () { return new BABYLON.StringDictionary(); });
  1383. var ft = dic.get(fontTexture.uid);
  1384. if (ft) {
  1385. ++ft._usedCounter;
  1386. return ft;
  1387. }
  1388. dic.add(fontTexture.uid, fontTexture);
  1389. return ft;
  1390. };
  1391. BitmapFontTexture.ReleaseCachedFontTexture = function (scene, fontTexture) {
  1392. var dic = scene.getExternalData("BitmapFontTextureCache");
  1393. if (!dic) {
  1394. return;
  1395. }
  1396. var font = dic.get(fontTexture.uid);
  1397. if (--font._usedCounter === 0) {
  1398. dic.remove(fontTexture.uid);
  1399. font.dispose();
  1400. }
  1401. };
  1402. Object.defineProperty(BitmapFontTexture.prototype, "isDynamicFontTexture", {
  1403. /**
  1404. * 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()
  1405. */
  1406. get: function () {
  1407. return false;
  1408. },
  1409. enumerable: true,
  1410. configurable: true
  1411. });
  1412. /**
  1413. * This method does nothing for a BitmapFontTexture object as it's a static texture
  1414. */
  1415. BitmapFontTexture.prototype.update = function () {
  1416. };
  1417. /**
  1418. * Retrieve the CharInfo object for a given character
  1419. * @param char the character to retrieve the CharInfo object from (e.g.: "A", "a", etc.)
  1420. */
  1421. BitmapFontTexture.prototype.getChar = function (char) {
  1422. return this._charInfos.get(char);
  1423. };
  1424. /**
  1425. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  1426. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  1427. */
  1428. BitmapFontTexture.prototype.incCachedFontTextureCounter = function () {
  1429. ++this._usedCounter;
  1430. };
  1431. /**
  1432. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  1433. */
  1434. BitmapFontTexture.prototype.decCachedFontTextureCounter = function () {
  1435. var dic = this.getScene().getExternalData("BitmapFontTextureCache");
  1436. if (!dic) {
  1437. return;
  1438. }
  1439. if (--this._usedCounter === 0) {
  1440. dic.remove(this._cachedFontId);
  1441. this.dispose();
  1442. }
  1443. };
  1444. BitmapFontTexture.addLoader = function (fileExtension, plugin) {
  1445. var a = BitmapFontTexture.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  1446. a.push(plugin);
  1447. };
  1448. return BitmapFontTexture;
  1449. }(BaseFontTexture));
  1450. BitmapFontTexture.plugins = new BABYLON.StringDictionary();
  1451. BABYLON.BitmapFontTexture = BitmapFontTexture;
  1452. /**
  1453. * This class is a special kind of texture which generates on the fly characters of a given css style "fontName".
  1454. * The generated texture will be updated when new characters will be retrieved using the getChar() method, but you have
  1455. * to call the update() method for the texture to fetch these changes, you can harmlessly call update any time you want, if no
  1456. * change were made, nothing will happen.
  1457. * The Font Texture can be rendered in three modes: normal size, super sampled size (x2) or using Signed Distance Field rendering.
  1458. * 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).
  1459. * 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.
  1460. */
  1461. var FontTexture = (function (_super) {
  1462. __extends(FontTexture, _super);
  1463. /**
  1464. * Create a new instance of the FontTexture class
  1465. * @param name the name of the texture
  1466. * @param font the font to use, use the W3C CSS notation
  1467. * @param scene the scene that owns the texture
  1468. * @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
  1469. * @param samplingMode the texture sampling mode
  1470. * @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.
  1471. */
  1472. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  1473. if (maxCharCount === void 0) { maxCharCount = 200; }
  1474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1475. if (superSample === void 0) { superSample = false; }
  1476. if (signedDistanceField === void 0) { signedDistanceField = false; }
  1477. var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
  1478. _this._curCharCount = 0;
  1479. _this._lastUpdateCharCount = -1;
  1480. _this._usedCounter = 1;
  1481. _this.name = name;
  1482. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  1483. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  1484. _this._sdfScale = 8;
  1485. _this._signedDistanceField = signedDistanceField;
  1486. _this._superSample = false;
  1487. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  1488. if (superSample || signedDistanceField) {
  1489. var sfont = _this.getSuperSampleFont(font);
  1490. if (sfont) {
  1491. _this._superSample = true;
  1492. font = sfont;
  1493. }
  1494. }
  1495. // First canvas creation to determine the size of the texture to create
  1496. _this._canvas = document.createElement("canvas");
  1497. _this._context = _this._canvas.getContext("2d");
  1498. _this._context.font = font;
  1499. _this._context.fillStyle = "white";
  1500. _this._context.textBaseline = "top";
  1501. var res = _this.getFontHeight(font);
  1502. _this._lineHeightSuper = res.height; //+4;
  1503. _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
  1504. _this._offset = res.offset - 1;
  1505. _this._xMargin = 1 + Math.ceil(_this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  1506. _this._yMargin = _this._xMargin;
  1507. var maxCharWidth = _this._context.measureText("W").width;
  1508. _this._spaceWidthSuper = _this._context.measureText(" ").width;
  1509. _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
  1510. // This is an approximate size, but should always be able to fit at least the maxCharCount
  1511. var totalEstSurface = (_this._lineHeightSuper + _this._yMargin) * (maxCharWidth + _this._xMargin) * maxCharCount;
  1512. var edge = Math.sqrt(totalEstSurface);
  1513. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  1514. // Create the texture that will store the font characters
  1515. _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  1516. var textureSize = _this.getSize();
  1517. _this.hasAlpha = _this._signedDistanceField === false;
  1518. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  1519. _this._canvas = document.createElement("canvas");
  1520. _this._canvas.width = textureSize.width;
  1521. _this._canvas.height = textureSize.height;
  1522. _this._context = _this._canvas.getContext("2d");
  1523. _this._context.textBaseline = "top";
  1524. _this._context.font = font;
  1525. _this._context.fillStyle = "white";
  1526. _this._context.imageSmoothingEnabled = false;
  1527. _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  1528. // 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
  1529. // 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)
  1530. // So you can see this context as an intermediate one, because it is.
  1531. if (_this._signedDistanceField) {
  1532. var sdfC = document.createElement("canvas");
  1533. var s = _this._sdfScale;
  1534. sdfC.width = maxCharWidth * s;
  1535. sdfC.height = _this._lineHeightSuper * s;
  1536. var sdfCtx = sdfC.getContext("2d");
  1537. sdfCtx.scale(s, s);
  1538. sdfCtx.textBaseline = "top";
  1539. sdfCtx.font = font;
  1540. sdfCtx.fillStyle = "white";
  1541. sdfCtx.imageSmoothingEnabled = false;
  1542. _this._sdfCanvas = sdfC;
  1543. _this._sdfContext = sdfCtx;
  1544. }
  1545. _this._currentFreePosition = BABYLON.Vector2.Zero();
  1546. // Add the basic ASCII based characters
  1547. for (var i = 0x20; i < 0x7F; i++) {
  1548. var c = String.fromCharCode(i);
  1549. _this.getChar(c);
  1550. }
  1551. _this.update();
  1552. return _this;
  1553. }
  1554. Object.defineProperty(FontTexture.prototype, "isDynamicFontTexture", {
  1555. get: function () {
  1556. return true;
  1557. },
  1558. enumerable: true,
  1559. configurable: true
  1560. });
  1561. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  1562. if (supersample === void 0) { supersample = false; }
  1563. if (signedDistanceField === void 0) { signedDistanceField = false; }
  1564. var dic = scene.getOrAddExternalDataWithFactory("FontTextureCache", function () { return new BABYLON.StringDictionary(); });
  1565. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  1566. var ft = dic.get(lfn);
  1567. if (ft) {
  1568. ++ft._usedCounter;
  1569. return ft;
  1570. }
  1571. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  1572. ft._cachedFontId = lfn;
  1573. dic.add(lfn, ft);
  1574. return ft;
  1575. };
  1576. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  1577. if (supersample === void 0) { supersample = false; }
  1578. if (signedDistanceField === void 0) { signedDistanceField = false; }
  1579. var dic = scene.getExternalData("FontTextureCache");
  1580. if (!dic) {
  1581. return;
  1582. }
  1583. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  1584. var font = dic.get(lfn);
  1585. if (--font._usedCounter === 0) {
  1586. dic.remove(lfn);
  1587. font.dispose();
  1588. }
  1589. };
  1590. /**
  1591. * Make sure the given char is present in the font map.
  1592. * @param char the character to get or add
  1593. * @return the CharInfo instance corresponding to the given character
  1594. */
  1595. FontTexture.prototype.getChar = function (char) {
  1596. if (char.length !== 1) {
  1597. return null;
  1598. }
  1599. var info = this._charInfos.get(char);
  1600. if (info) {
  1601. return info;
  1602. }
  1603. info = new CharInfo();
  1604. var measure = this._context.measureText(char);
  1605. var textureSize = this.getSize();
  1606. // we reached the end of the current line?
  1607. var width = Math.round(measure.width);
  1608. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  1609. this._currentFreePosition.x = 0;
  1610. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  1611. // No more room?
  1612. if (this._currentFreePosition.y > textureSize.height) {
  1613. return this.getChar("!");
  1614. }
  1615. }
  1616. // 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)
  1617. if (this._signedDistanceField) {
  1618. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  1619. this._sdfContext.fillText(char, 0, -this._offset);
  1620. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  1621. var res = this._computeSDFChar(data);
  1622. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  1623. }
  1624. else {
  1625. // Draw the character in the HTML canvas
  1626. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  1627. }
  1628. // Fill the CharInfo object
  1629. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  1630. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  1631. if (this._signedDistanceField) {
  1632. var off = 1 / textureSize.width;
  1633. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  1634. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  1635. }
  1636. info.charWidth = this._superSample ? (width / 2) : width;
  1637. // Add the info structure
  1638. this._charInfos.add(char, info);
  1639. this._curCharCount++;
  1640. // Set the next position
  1641. this._currentFreePosition.x += width + this._xMargin;
  1642. return info;
  1643. };
  1644. FontTexture.prototype._computeSDFChar = function (source) {
  1645. var scl = this._sdfScale;
  1646. var sw = source.width;
  1647. var sh = source.height;
  1648. var dw = sw / scl;
  1649. var dh = sh / scl;
  1650. var roffx = 0;
  1651. var roffy = 0;
  1652. // We shouldn't look beyond half of the biggest between width and height
  1653. var radius = scl;
  1654. var br = radius - 1;
  1655. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  1656. var sx = dx * scl;
  1657. var sy = dy * scl;
  1658. // Looking out of the area? return true to make the test going on
  1659. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  1660. return true;
  1661. }
  1662. // Get the pixel we want
  1663. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  1664. var res = (val > 0) === lookVis;
  1665. if (!res) {
  1666. roffx = offX;
  1667. roffy = offY;
  1668. }
  1669. return res;
  1670. };
  1671. var lookupArea = function (dx, dy, lookVis) {
  1672. // 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
  1673. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  1674. lookupSrc(dx, dy, 0, -br, lookVis) &&
  1675. lookupSrc(dx, dy, -br, 0, lookVis) &&
  1676. lookupSrc(dx, dy, br, 0, lookVis)) {
  1677. return 0;
  1678. }
  1679. for (var i = 1; i <= radius; i++) {
  1680. // Quick test N, S, W, E
  1681. 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)) {
  1682. return i * i; // Squared Distance is simple to compute in this case
  1683. }
  1684. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  1685. for (var j = 1; j <= i; j++) {
  1686. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  1687. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  1688. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  1689. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  1690. // We found the nearest texel having and opposite state, store the squared length
  1691. var res_1 = (i * i) + (j * j);
  1692. var count = 1;
  1693. // 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
  1694. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  1695. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  1696. ++count;
  1697. }
  1698. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  1699. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  1700. ++count;
  1701. }
  1702. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  1703. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  1704. ++count;
  1705. }
  1706. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  1707. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  1708. ++count;
  1709. }
  1710. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  1711. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  1712. ++count;
  1713. }
  1714. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  1715. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  1716. ++count;
  1717. }
  1718. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  1719. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  1720. ++count;
  1721. }
  1722. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  1723. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  1724. ++count;
  1725. }
  1726. // Compute the average based on the accumulated distance
  1727. return res_1 / count;
  1728. }
  1729. }
  1730. }
  1731. return 0;
  1732. };
  1733. var tmp = new Array(dw * dh);
  1734. for (var y = 0; y < dh; y++) {
  1735. for (var x = 0; x < dw; x++) {
  1736. var curState = lookupSrc(x, y, 0, 0, true);
  1737. var d = lookupArea(x, y, curState);
  1738. if (d === 0) {
  1739. d = radius * radius * 2;
  1740. }
  1741. tmp[(y * dw) + x] = curState ? d : -d;
  1742. }
  1743. }
  1744. var res = this._context.createImageData(dw, dh);
  1745. var size = dw * dh;
  1746. for (var j = 0; j < size; j++) {
  1747. var d = tmp[j];
  1748. var sign = (d < 0) ? -1 : 1;
  1749. d = Math.sqrt(Math.abs(d)) * sign;
  1750. d *= 127.5 / radius;
  1751. d += 127.5;
  1752. if (d < 0) {
  1753. d = 0;
  1754. }
  1755. else if (d > 255) {
  1756. d = 255;
  1757. }
  1758. d += 0.5;
  1759. res.data[j * 4 + 0] = d;
  1760. res.data[j * 4 + 1] = d;
  1761. res.data[j * 4 + 2] = d;
  1762. res.data[j * 4 + 3] = 255;
  1763. }
  1764. return res;
  1765. };
  1766. FontTexture.prototype.getSuperSampleFont = function (font) {
  1767. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  1768. 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*$/;
  1769. var res = font.toLocaleLowerCase().match(regex);
  1770. if (res == null) {
  1771. return null;
  1772. }
  1773. var size = parseInt(res[4]);
  1774. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  1775. var newFont = "";
  1776. for (var j = 1; j < res.length; j++) {
  1777. if (res[j] != null) {
  1778. newFont += res[j] + " ";
  1779. }
  1780. }
  1781. return newFont;
  1782. };
  1783. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  1784. FontTexture.prototype.getFontHeight = function (font) {
  1785. var fontDraw = document.createElement("canvas");
  1786. fontDraw.width = 600;
  1787. fontDraw.height = 600;
  1788. var ctx = fontDraw.getContext('2d');
  1789. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  1790. ctx.textBaseline = 'top';
  1791. ctx.fillStyle = 'white';
  1792. ctx.font = font;
  1793. ctx.fillText('jH|', 0, 0);
  1794. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  1795. var start = -1;
  1796. var end = -1;
  1797. for (var row = 0; row < fontDraw.height; row++) {
  1798. for (var column = 0; column < fontDraw.width; column++) {
  1799. var index = (row * fontDraw.width + column) * 4;
  1800. if (pixels[index] === 0) {
  1801. if (column === fontDraw.width - 1 && start !== -1) {
  1802. end = row;
  1803. row = fontDraw.height;
  1804. break;
  1805. }
  1806. continue;
  1807. }
  1808. else {
  1809. if (start === -1) {
  1810. start = row;
  1811. }
  1812. break;
  1813. }
  1814. }
  1815. }
  1816. return { height: (end - start) + 1, offset: start - 1 };
  1817. };
  1818. Object.defineProperty(FontTexture.prototype, "canRescale", {
  1819. get: function () {
  1820. return false;
  1821. },
  1822. enumerable: true,
  1823. configurable: true
  1824. });
  1825. FontTexture.prototype.getContext = function () {
  1826. return this._context;
  1827. };
  1828. /**
  1829. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  1830. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  1831. */
  1832. FontTexture.prototype.update = function () {
  1833. // Update only if there's new char added since the previous update
  1834. if (this._lastUpdateCharCount < this._curCharCount) {
  1835. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  1836. this._lastUpdateCharCount = this._curCharCount;
  1837. }
  1838. };
  1839. // cloning should be prohibited, there's no point to duplicate this texture at all
  1840. FontTexture.prototype.clone = function () {
  1841. return null;
  1842. };
  1843. /**
  1844. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  1845. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  1846. */
  1847. FontTexture.prototype.incCachedFontTextureCounter = function () {
  1848. ++this._usedCounter;
  1849. };
  1850. /**
  1851. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  1852. */
  1853. FontTexture.prototype.decCachedFontTextureCounter = function () {
  1854. var dic = this.getScene().getExternalData("FontTextureCache");
  1855. if (!dic) {
  1856. return;
  1857. }
  1858. if (--this._usedCounter === 0) {
  1859. dic.remove(this._cachedFontId);
  1860. this.dispose();
  1861. }
  1862. };
  1863. return FontTexture;
  1864. }(BaseFontTexture));
  1865. BABYLON.FontTexture = FontTexture;
  1866. /**
  1867. * Orginial code from cocos2d-js, converted to TypeScript by Nockawa
  1868. * Load the Text version of the BMFont format, no XML or binary supported, just plain old text
  1869. */
  1870. var BMFontLoaderTxt = BMFontLoaderTxt_1 = (function () {
  1871. function BMFontLoaderTxt() {
  1872. }
  1873. BMFontLoaderTxt.prototype._parseStrToObj = function (str) {
  1874. var arr = str.match(BMFontLoaderTxt_1.ITEM_EXP);
  1875. if (!arr) {
  1876. return null;
  1877. }
  1878. var obj = {};
  1879. for (var i = 0, li = arr.length; i < li; i++) {
  1880. var tempStr = arr[i];
  1881. var index = tempStr.indexOf("=");
  1882. var key = tempStr.substring(0, index);
  1883. var value = tempStr.substring(index + 1);
  1884. if (value.match(BMFontLoaderTxt_1.INT_EXP))
  1885. value = parseInt(value);
  1886. else if (value[0] === '"')
  1887. value = value.substring(1, value.length - 1);
  1888. obj[key] = value;
  1889. }
  1890. return obj;
  1891. };
  1892. BMFontLoaderTxt.prototype._buildCharInfo = function (initialLine, obj, textureSize, invertY, chars) {
  1893. var char = null;
  1894. var x = null;
  1895. var y = null;
  1896. var xadv = null;
  1897. var width = null;
  1898. var height = null;
  1899. var ci = new CharInfo();
  1900. for (var key in obj) {
  1901. var value = obj[key];
  1902. switch (key) {
  1903. case "id":
  1904. char = String.fromCharCode(value);
  1905. break;
  1906. case "x":
  1907. x = value;
  1908. break;
  1909. case "y":
  1910. y = value;
  1911. break;
  1912. case "width":
  1913. width = value;
  1914. break;
  1915. case "height":
  1916. height = value;
  1917. break;
  1918. case "xadvance":
  1919. xadv = value;
  1920. break;
  1921. }
  1922. }
  1923. if (x != null && y != null && width != null && height != null && char != null) {
  1924. if (xadv) {
  1925. width = xadv;
  1926. }
  1927. if (invertY) {
  1928. ci.topLeftUV = new BABYLON.Vector2(1 - (x / textureSize.width), 1 - (y / textureSize.height));
  1929. ci.bottomRightUV = new BABYLON.Vector2(1 - ((x + width) / textureSize.width), 1 - ((y + height) / textureSize.height));
  1930. }
  1931. else {
  1932. ci.topLeftUV = new BABYLON.Vector2(x / textureSize.width, y / textureSize.height);
  1933. ci.bottomRightUV = new BABYLON.Vector2((x + width) / textureSize.width, (y + height) / textureSize.height);
  1934. }
  1935. ci.charWidth = width;
  1936. chars.add(char, ci);
  1937. }
  1938. else {
  1939. console.log("Error while parsing line " + initialLine);
  1940. }
  1941. };
  1942. BMFontLoaderTxt.prototype.loadFont = function (fontContent, scene, invertY) {
  1943. var fontStr = fontContent;
  1944. var bfi = new BitmapFontInfo();
  1945. var errorCode = 0;
  1946. var errorMsg = "OK";
  1947. //padding
  1948. var info = fontStr.match(BMFontLoaderTxt_1.INFO_EXP);
  1949. var infoObj = this._parseStrToObj(info[0]);
  1950. if (!infoObj) {
  1951. return null;
  1952. }
  1953. var paddingArr = infoObj["padding"].split(",");
  1954. bfi.padding = new BABYLON.Vector4(parseInt(paddingArr[0]), parseInt(paddingArr[1]), parseInt(paddingArr[2]), parseInt(paddingArr[3]));
  1955. //common
  1956. var commonObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.COMMON_EXP)[0]);
  1957. bfi.lineHeight = commonObj["lineHeight"];
  1958. bfi.textureSize = new BABYLON.Size(commonObj["scaleW"], commonObj["scaleH"]);
  1959. var maxTextureSize = scene.getEngine()._gl.getParameter(0xd33);
  1960. if (commonObj["scaleW"] > maxTextureSize.width || commonObj["scaleH"] > maxTextureSize.height) {
  1961. errorMsg = "FontMap texture's size is bigger than what WebGL supports";
  1962. errorCode = -1;
  1963. }
  1964. else {
  1965. if (commonObj["pages"] !== 1) {
  1966. errorMsg = "FontMap must contain one page only.";
  1967. errorCode = -1;
  1968. }
  1969. else {
  1970. //page
  1971. var pageObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.PAGE_EXP)[0]);
  1972. if (pageObj["id"] !== 0) {
  1973. errorMsg = "Only one page of ID 0 is supported";
  1974. errorCode = -1;
  1975. }
  1976. else {
  1977. bfi.textureFile = pageObj["file"];
  1978. //char
  1979. var charLines = fontStr.match(BMFontLoaderTxt_1.CHAR_EXP);
  1980. for (var i = 0, li = charLines.length; i < li; i++) {
  1981. var charObj = this._parseStrToObj(charLines[i]);
  1982. this._buildCharInfo(charLines[i], charObj, bfi.textureSize, invertY, bfi.charDic);
  1983. }
  1984. //kerning
  1985. var kerningLines = fontStr.match(BMFontLoaderTxt_1.KERNING_EXP);
  1986. if (kerningLines) {
  1987. for (var i = 0, li = kerningLines.length; i < li; i++) {
  1988. var kerningObj = this._parseStrToObj(kerningLines[i]);
  1989. bfi.kerningDic.add(((kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)).toString(), kerningObj["amount"]);
  1990. }
  1991. }
  1992. }
  1993. }
  1994. }
  1995. return { bfi: bfi, errorCode: errorCode, errorMsg: errorMsg };
  1996. };
  1997. return BMFontLoaderTxt;
  1998. }());
  1999. BMFontLoaderTxt.INFO_EXP = /info [^\r\n]*(\r\n|$)/gi;
  2000. BMFontLoaderTxt.COMMON_EXP = /common [^\n]*(\n|$)/gi;
  2001. BMFontLoaderTxt.PAGE_EXP = /page [^\n]*(\n|$)/gi;
  2002. BMFontLoaderTxt.CHAR_EXP = /char [^\n]*(\n|$)/gi;
  2003. BMFontLoaderTxt.KERNING_EXP = /kerning [^\n]*(\n|$)/gi;
  2004. BMFontLoaderTxt.ITEM_EXP = /\w+=[^ \r\n]+/gi;
  2005. BMFontLoaderTxt.INT_EXP = /^[\-]?\d+$/;
  2006. BMFontLoaderTxt = BMFontLoaderTxt_1 = __decorate([
  2007. BitmapFontLoaderPlugin("fnt", new BMFontLoaderTxt_1())
  2008. ], BMFontLoaderTxt);
  2009. ;
  2010. function BitmapFontLoaderPlugin(fileExtension, plugin) {
  2011. return function () {
  2012. BitmapFontTexture.addLoader(fileExtension, plugin);
  2013. };
  2014. }
  2015. BABYLON.BitmapFontLoaderPlugin = BitmapFontLoaderPlugin;
  2016. var BMFontLoaderTxt_1;
  2017. })(BABYLON || (BABYLON = {}));
  2018. //# sourceMappingURL=babylon.fontTexture.js.map
  2019. var BABYLON;
  2020. (function (BABYLON) {
  2021. /**
  2022. * Stores 2D Bounding Information.
  2023. * This class handles a circle area and a bounding rectangle one.
  2024. */
  2025. var BoundingInfo2D = (function () {
  2026. function BoundingInfo2D() {
  2027. this.radius = 0;
  2028. this.center = BABYLON.Vector2.Zero();
  2029. this.extent = BABYLON.Vector2.Zero();
  2030. this._worldAABBDirty = false;
  2031. this._worldAABBDirtyObservable = null;
  2032. this._worldAABB = BABYLON.Vector4.Zero();
  2033. }
  2034. /**
  2035. * Create a BoundingInfo2D object from a given size
  2036. * @param size the size that will be used to set the extend, radius will be computed from it.
  2037. */
  2038. BoundingInfo2D.CreateFromSize = function (size) {
  2039. var r = new BoundingInfo2D();
  2040. BoundingInfo2D.CreateFromSizeToRef(size, r);
  2041. return r;
  2042. };
  2043. /**
  2044. * Create a BoundingInfo2D object from a given radius
  2045. * @param radius the radius to use, the extent will be computed from it.
  2046. */
  2047. BoundingInfo2D.CreateFromRadius = function (radius) {
  2048. var r = new BoundingInfo2D();
  2049. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  2050. return r;
  2051. };
  2052. /**
  2053. * Create a BoundingInfo2D object from a list of points.
  2054. * The resulted object will be the smallest bounding area that includes all the given points.
  2055. * @param points an array of points to compute the bounding object from.
  2056. */
  2057. BoundingInfo2D.CreateFromPoints = function (points) {
  2058. var r = new BoundingInfo2D();
  2059. BoundingInfo2D.CreateFromPointsToRef(points, r);
  2060. return r;
  2061. };
  2062. /**
  2063. * Update a BoundingInfo2D object using the given Size as input
  2064. * @param size the bounding data will be computed from this size.
  2065. * @param b must be a valid/allocated object, it will contain the result of the operation
  2066. */
  2067. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  2068. if (!size) {
  2069. size = BABYLON.Size.Zero();
  2070. }
  2071. b.center.x = +size.width / 2;
  2072. b.center.y = +size.height / 2;
  2073. b.extent.x = b.center.x;
  2074. b.extent.y = b.center.y;
  2075. b.radius = b.extent.length();
  2076. b._worldAABBDirty = true;
  2077. };
  2078. /**
  2079. * Update a BoundingInfo2D object using the given radius as input
  2080. * @param radius the bounding data will be computed from this radius
  2081. * @param b must be a valid/allocated object, it will contain the result of the operation
  2082. */
  2083. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  2084. b.center.x = b.center.y = 0;
  2085. var r = +radius;
  2086. b.extent.x = r;
  2087. b.extent.y = r;
  2088. b.radius = r;
  2089. b._worldAABBDirty = true;
  2090. };
  2091. /**
  2092. * Update a BoundingInfo2D object using the given points array as input
  2093. * @param points the point array to use to update the bounding data
  2094. * @param b must be a valid/allocated object, it will contain the result of the operation
  2095. */
  2096. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  2097. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  2098. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  2099. var p = points_1[_i];
  2100. xmin = Math.min(p.x, xmin);
  2101. xmax = Math.max(p.x, xmax);
  2102. ymin = Math.min(p.y, ymin);
  2103. ymax = Math.max(p.y, ymax);
  2104. }
  2105. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  2106. };
  2107. /**
  2108. * Update a BoundingInfo2D object using the given min/max values as input
  2109. * @param xmin the smallest x coordinate
  2110. * @param xmax the biggest x coordinate
  2111. * @param ymin the smallest y coordinate
  2112. * @param ymax the buggest y coordinate
  2113. * @param b must be a valid/allocated object, it will contain the result of the operation
  2114. */
  2115. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  2116. var w = xmax - xmin;
  2117. var h = ymax - ymin;
  2118. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  2119. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  2120. b.radius = b.extent.length();
  2121. b._worldAABBDirty = true;
  2122. };
  2123. /**
  2124. * Duplicate this instance and return a new one
  2125. * @return the duplicated instance
  2126. */
  2127. BoundingInfo2D.prototype.clone = function () {
  2128. var r = new BoundingInfo2D();
  2129. r.center = this.center.clone();
  2130. r.radius = this.radius;
  2131. r.extent = this.extent.clone();
  2132. return r;
  2133. };
  2134. BoundingInfo2D.prototype.clear = function () {
  2135. this.center.copyFromFloats(0, 0);
  2136. this.radius = 0;
  2137. this.extent.copyFromFloats(0, 0);
  2138. this._worldAABBDirty = true;
  2139. };
  2140. BoundingInfo2D.prototype.copyFrom = function (src) {
  2141. this.center.copyFrom(src.center);
  2142. this.radius = src.radius;
  2143. this.extent.copyFrom(src.extent);
  2144. this._worldAABBDirty = true;
  2145. };
  2146. /**
  2147. * return the max extend of the bounding info
  2148. */
  2149. BoundingInfo2D.prototype.max = function () {
  2150. var r = BABYLON.Vector2.Zero();
  2151. this.maxToRef(r);
  2152. return r;
  2153. };
  2154. /**
  2155. * return the min/max extend of the bounding info.
  2156. * x, y, z, w are left, bottom, right and top
  2157. */
  2158. BoundingInfo2D.prototype.minMax = function () {
  2159. var r = BABYLON.Vector4.Zero();
  2160. this.minMaxToRef(r);
  2161. return r;
  2162. };
  2163. /**
  2164. * Update a vector2 with the max extend of the bounding info
  2165. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  2166. */
  2167. BoundingInfo2D.prototype.maxToRef = function (result) {
  2168. result.x = this.center.x + this.extent.x;
  2169. result.y = this.center.y + this.extent.y;
  2170. };
  2171. /**
  2172. * Update a vector4 with the min/max extend of the bounding info
  2173. * x, y, z, w are left, bottom, right and top
  2174. * @param result must be a valid/allocated vector4 that will contain the result of the operation
  2175. */
  2176. BoundingInfo2D.prototype.minMaxToRef = function (result) {
  2177. result.x = this.center.x - this.extent.x;
  2178. result.y = this.center.y - this.extent.y;
  2179. result.z = this.center.x + this.extent.x;
  2180. result.w = this.center.y + this.extent.y;
  2181. };
  2182. /**
  2183. * Return the size of the boundingInfo rect surface
  2184. */
  2185. BoundingInfo2D.prototype.size = function () {
  2186. var r = BABYLON.Size.Zero();
  2187. this.sizeToRef(r);
  2188. return r;
  2189. };
  2190. /**
  2191. * Stores in the result object the size of the boundingInfo rect surface
  2192. * @param result
  2193. */
  2194. BoundingInfo2D.prototype.sizeToRef = function (result) {
  2195. result.width = this.extent.x * 2;
  2196. result.height = this.extent.y * 2;
  2197. };
  2198. /**
  2199. * Inflate the boundingInfo with the given vector
  2200. * @param offset the extent will be incremented with offset and the radius will be computed again
  2201. */
  2202. BoundingInfo2D.prototype.inflate = function (offset) {
  2203. this.extent.addInPlace(offset);
  2204. this.radius = this.extent.length();
  2205. };
  2206. /**
  2207. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  2208. * @param matrix the transformation matrix to apply
  2209. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  2210. */
  2211. BoundingInfo2D.prototype.transform = function (matrix) {
  2212. var r = new BoundingInfo2D();
  2213. this.transformToRef(matrix, r);
  2214. return r;
  2215. };
  2216. /**
  2217. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  2218. * @param other the second BoundingInfo2D to compute the union with this one
  2219. * @return a new instance containing the result of the union
  2220. */
  2221. BoundingInfo2D.prototype.union = function (other) {
  2222. var r = new BoundingInfo2D();
  2223. this.unionToRef(other, r);
  2224. return r;
  2225. };
  2226. BoundingInfo2D.prototype.worldAABBIntersectionTest = function (other) {
  2227. var a = this.worldAABB;
  2228. var b = other.worldAABB;
  2229. return b.z >= a.x && b.x <= a.z && b.w >= a.y && b.y <= a.w;
  2230. };
  2231. /**
  2232. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  2233. * 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.
  2234. * @param matrix The matrix to use to compute the transformation
  2235. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  2236. */
  2237. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  2238. // Construct a bounding box based on the extent values
  2239. var p = BoundingInfo2D._transform;
  2240. p[0].x = this.center.x + this.extent.x;
  2241. p[0].y = this.center.y + this.extent.y;
  2242. p[1].x = this.center.x + this.extent.x;
  2243. p[1].y = this.center.y - this.extent.y;
  2244. p[2].x = this.center.x - this.extent.x;
  2245. p[2].y = this.center.y - this.extent.y;
  2246. p[3].x = this.center.x - this.extent.x;
  2247. p[3].y = this.center.y + this.extent.y;
  2248. // Transform the four points of the bounding box with the matrix
  2249. for (var i = 0; i < 4; i++) {
  2250. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  2251. }
  2252. BoundingInfo2D.CreateFromPointsToRef(p, result);
  2253. };
  2254. BoundingInfo2D.prototype._updateWorldAABB = function (worldMatrix) {
  2255. // Construct a bounding box based on the extent values
  2256. var p = BoundingInfo2D._transform;
  2257. p[0].x = this.center.x + this.extent.x;
  2258. p[0].y = this.center.y + this.extent.y;
  2259. p[1].x = this.center.x + this.extent.x;
  2260. p[1].y = this.center.y - this.extent.y;
  2261. p[2].x = this.center.x - this.extent.x;
  2262. p[2].y = this.center.y - this.extent.y;
  2263. p[3].x = this.center.x - this.extent.x;
  2264. p[3].y = this.center.y + this.extent.y;
  2265. // Transform the four points of the bounding box with the matrix
  2266. for (var i = 0; i < 4; i++) {
  2267. BABYLON.Vector2.TransformToRef(p[i], worldMatrix, p[i]);
  2268. }
  2269. this._worldAABB.x = Math.min(Math.min(p[0].x, p[1].x), Math.min(p[2].x, p[3].x));
  2270. this._worldAABB.y = Math.min(Math.min(p[0].y, p[1].y), Math.min(p[2].y, p[3].y));
  2271. this._worldAABB.z = Math.max(Math.max(p[0].x, p[1].x), Math.max(p[2].x, p[3].x));
  2272. this._worldAABB.w = Math.max(Math.max(p[0].y, p[1].y), Math.max(p[2].y, p[3].y));
  2273. };
  2274. Object.defineProperty(BoundingInfo2D.prototype, "worldAABBDirtyObservable", {
  2275. get: function () {
  2276. if (!this._worldAABBDirtyObservable) {
  2277. this._worldAABBDirtyObservable = new BABYLON.Observable();
  2278. }
  2279. return this._worldAABBDirtyObservable;
  2280. },
  2281. enumerable: true,
  2282. configurable: true
  2283. });
  2284. Object.defineProperty(BoundingInfo2D.prototype, "isWorldAABBDirty", {
  2285. get: function () {
  2286. return this._worldAABBDirty;
  2287. },
  2288. enumerable: true,
  2289. configurable: true
  2290. });
  2291. BoundingInfo2D.prototype.dirtyWorldAABB = function () {
  2292. if (this._worldAABBDirty) {
  2293. return;
  2294. }
  2295. this._worldAABBDirty = true;
  2296. if (this._worldAABBDirtyObservable && this._worldAABBDirtyObservable.hasObservers()) {
  2297. this._worldAABBDirtyObservable.notifyObservers(this);
  2298. }
  2299. };
  2300. Object.defineProperty(BoundingInfo2D.prototype, "worldAABB", {
  2301. /**
  2302. * Retrieve the world AABB, the Vector4's data is x=xmin, y=ymin, z=xmax, w=ymax
  2303. */
  2304. get: function () {
  2305. if (this._worldAABBDirty) {
  2306. if (!this.worldMatrixAccess) {
  2307. throw new Error("you must set the worldMatrixAccess function first");
  2308. }
  2309. this._updateWorldAABB(this.worldMatrixAccess());
  2310. this._worldAABBDirty = false;
  2311. }
  2312. return this._worldAABB;
  2313. },
  2314. enumerable: true,
  2315. configurable: true
  2316. });
  2317. /**
  2318. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  2319. * 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.
  2320. * @param other the second object used to compute the union
  2321. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  2322. */
  2323. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  2324. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  2325. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  2326. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  2327. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  2328. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  2329. };
  2330. /**
  2331. * Check if the given point is inside the BoundingInfo.
  2332. * The test is first made on the radius, then inside the rectangle described by the extent
  2333. * @param pickPosition the position to test
  2334. * @return true if the point is inside, false otherwise
  2335. */
  2336. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  2337. // is it inside the radius?
  2338. var pickLocal = pickPosition.subtract(this.center);
  2339. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  2340. // is it inside the rectangle?
  2341. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  2342. }
  2343. return false;
  2344. };
  2345. return BoundingInfo2D;
  2346. }());
  2347. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  2348. BABYLON.BoundingInfo2D = BoundingInfo2D;
  2349. })(BABYLON || (BABYLON = {}));
  2350. //# sourceMappingURL=babylon.bounding2d.js.map
  2351. var __extends = (this && this.__extends) || function (d, b) {
  2352. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  2353. function __() { this.constructor = d; }
  2354. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2355. };
  2356. var BABYLON;
  2357. (function (BABYLON) {
  2358. /**
  2359. * The base class for all implementation of a Primitive Collision Manager
  2360. */
  2361. var PrimitiveCollisionManagerBase = (function () {
  2362. function PrimitiveCollisionManagerBase(owner) {
  2363. this._owner = owner;
  2364. }
  2365. PrimitiveCollisionManagerBase.allocBasicPCM = function (owner, enableBorders) {
  2366. return new BasicPrimitiveCollisionManager(owner, enableBorders);
  2367. };
  2368. return PrimitiveCollisionManagerBase;
  2369. }());
  2370. BABYLON.PrimitiveCollisionManagerBase = PrimitiveCollisionManagerBase;
  2371. /**
  2372. * Base class of an Actor
  2373. */
  2374. var ActorInfoBase = (function () {
  2375. function ActorInfoBase() {
  2376. }
  2377. return ActorInfoBase;
  2378. }());
  2379. BABYLON.ActorInfoBase = ActorInfoBase;
  2380. var ActorInfo = (function (_super) {
  2381. __extends(ActorInfo, _super);
  2382. function ActorInfo(owner, actor, deep) {
  2383. var _this = _super.call(this) || this;
  2384. _this.owner = owner;
  2385. _this.prim = actor;
  2386. _this.flags = 0;
  2387. _this.presentInClusters = new BABYLON.StringDictionary();
  2388. _this.intersectWith = new BABYLON.ObservableStringDictionary(false);
  2389. _this.setFlags((deep ? ActorInfo.flagDeep : 0) | ActorInfo.flagDirty);
  2390. var bi = (deep ? actor.boundingInfo : actor.levelBoundingInfo);
  2391. // Dirty Actor if its WorldAABB changed
  2392. bi.worldAABBDirtyObservable.add(function (e, d) {
  2393. _this.owner.actorDirty(_this);
  2394. });
  2395. // Dirty Actor if it's getting enabled/disabled
  2396. actor.propertyChanged.add(function (e, d) {
  2397. if (d.mask === -1) {
  2398. return;
  2399. }
  2400. _this.setFlagsValue(ActorInfo.flagEnabled, e.newValue === true);
  2401. _this.owner.actorDirty(_this);
  2402. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  2403. return _this;
  2404. }
  2405. ActorInfo.prototype.setFlags = function (flags) {
  2406. this.flags |= flags;
  2407. };
  2408. ActorInfo.prototype.clearFlags = function (flags) {
  2409. this.flags &= ~flags;
  2410. };
  2411. ActorInfo.prototype.isAllFlagsSet = function (flags) {
  2412. return (this.flags & flags) === flags;
  2413. };
  2414. ActorInfo.prototype.isSomeFlagsSet = function (flags) {
  2415. return (this.flags & flags) !== 0;
  2416. };
  2417. ActorInfo.prototype.setFlagsValue = function (flags, value) {
  2418. if (value) {
  2419. this.flags |= flags;
  2420. }
  2421. else {
  2422. this.flags &= ~flags;
  2423. }
  2424. };
  2425. Object.defineProperty(ActorInfo.prototype, "worldAABB", {
  2426. get: function () {
  2427. return (this.isSomeFlagsSet(ActorInfo.flagDeep) ? this.prim.boundingInfo : this.prim.levelBoundingInfo).worldAABB;
  2428. },
  2429. enumerable: true,
  2430. configurable: true
  2431. });
  2432. Object.defineProperty(ActorInfo.prototype, "isEnabled", {
  2433. get: function () {
  2434. return this.isSomeFlagsSet(ActorInfo.flagEnabled);
  2435. },
  2436. enumerable: true,
  2437. configurable: true
  2438. });
  2439. Object.defineProperty(ActorInfo.prototype, "isDeep", {
  2440. get: function () {
  2441. return this.isSomeFlagsSet(ActorInfo.flagDeep);
  2442. },
  2443. enumerable: true,
  2444. configurable: true
  2445. });
  2446. Object.defineProperty(ActorInfo.prototype, "isDirty", {
  2447. get: function () {
  2448. return this.isSomeFlagsSet(ActorInfo.flagDirty);
  2449. },
  2450. enumerable: true,
  2451. configurable: true
  2452. });
  2453. Object.defineProperty(ActorInfo.prototype, "isRemoved", {
  2454. get: function () {
  2455. return this.isSomeFlagsSet(ActorInfo.flagRemoved);
  2456. },
  2457. enumerable: true,
  2458. configurable: true
  2459. });
  2460. return ActorInfo;
  2461. }(ActorInfoBase));
  2462. ActorInfo.flagDeep = 0x0001; // set if the actor boundingInfo must be used instead of the levelBoundingInfo
  2463. ActorInfo.flagEnabled = 0x0002; // set if the actor is enabled and should be considered for intersection tests
  2464. ActorInfo.flagDirty = 0x0004; // set if the actor's AABB is dirty
  2465. ActorInfo.flagRemoved = 0x0008; // set if the actor was removed from the PCM
  2466. var ClusterInfo = (function () {
  2467. function ClusterInfo() {
  2468. this.actors = new BABYLON.StringDictionary();
  2469. }
  2470. ClusterInfo.prototype.clear = function () {
  2471. this.actors.clear();
  2472. };
  2473. return ClusterInfo;
  2474. }());
  2475. var BasicPrimitiveCollisionManager = (function (_super) {
  2476. __extends(BasicPrimitiveCollisionManager, _super);
  2477. function BasicPrimitiveCollisionManager(owner, enableBorders) {
  2478. var _this = _super.call(this, owner) || this;
  2479. _this._actors = new BABYLON.StringDictionary();
  2480. _this._dirtyActors = new BABYLON.StringDictionary();
  2481. _this._clusters = null;
  2482. _this._maxActorByCluster = 0;
  2483. _this._AABBRenderPrim = null;
  2484. _this._canvasSize = BABYLON.Size.Zero();
  2485. _this._ClusterRenderPrim = null;
  2486. _this._debugTextBackground = null;
  2487. _this._clusterDirty = true;
  2488. _this._clusterSize = new BABYLON.Size(2, 2);
  2489. _this._clusterStep = BABYLON.Vector2.Zero();
  2490. _this._lastClusterResizeCounter = 0;
  2491. _this._freeClusters = new Array();
  2492. _this._enableBorder = enableBorders;
  2493. _this._debugUpdateOpCount = new BABYLON.PerfCounter();
  2494. _this._debugUpdateTime = new BABYLON.PerfCounter();
  2495. _this._intersectedActors = new BABYLON.ObservableStringDictionary(false);
  2496. _this._borderIntersecteddActors = new Array(4);
  2497. for (var j = 0; j < 4; j++) {
  2498. _this._borderIntersecteddActors[j] = new BABYLON.ObservableStringDictionary(false);
  2499. }
  2500. var flagId = BABYLON.Canvas2D.actualSizeProperty.flagId;
  2501. if (!BasicPrimitiveCollisionManager.WAABBCorners) {
  2502. BasicPrimitiveCollisionManager.WAABBCorners = new Array(4);
  2503. for (var i = 0; i < 4; i++) {
  2504. BasicPrimitiveCollisionManager.WAABBCorners[i] = BABYLON.Vector2.Zero();
  2505. }
  2506. BasicPrimitiveCollisionManager.WAABBCornersCluster = new Array(4);
  2507. for (var i = 0; i < 4; i++) {
  2508. BasicPrimitiveCollisionManager.WAABBCornersCluster[i] = BABYLON.Vector2.Zero();
  2509. }
  2510. }
  2511. owner.propertyChanged.add(function (e, d) {
  2512. if (d.mask === -1) {
  2513. return;
  2514. }
  2515. _this._clusterDirty = true;
  2516. console.log("canvas size changed");
  2517. }, flagId);
  2518. _this.debugRenderAABB = false;
  2519. _this.debugRenderClusters = false;
  2520. _this.debugStats = false;
  2521. return _this;
  2522. }
  2523. BasicPrimitiveCollisionManager.prototype._addActor = function (actor, deep) {
  2524. var _this = this;
  2525. return this._actors.getOrAddWithFactory(actor.uid, function () {
  2526. var ai = new ActorInfo(_this, actor, deep);
  2527. _this.actorDirty(ai);
  2528. return ai;
  2529. });
  2530. };
  2531. BasicPrimitiveCollisionManager.prototype._removeActor = function (actor) {
  2532. var ai = this._actors.getAndRemove(actor.uid);
  2533. ai.setFlags(ActorInfo.flagRemoved);
  2534. this.actorDirty(ai);
  2535. };
  2536. BasicPrimitiveCollisionManager.prototype.actorDirty = function (actor) {
  2537. actor.setFlags(ActorInfo.flagDirty);
  2538. this._dirtyActors.add(actor.prim.uid, actor);
  2539. };
  2540. BasicPrimitiveCollisionManager.prototype._update = function () {
  2541. this._canvasSize.copyFrom(this._owner.actualSize);
  2542. // Should we update the WireFrame2D Primitive that displays the WorldAABB ?
  2543. if (this.debugRenderAABB) {
  2544. if (this._dirtyActors.count > 0 || this._debugRenderAABBDirty) {
  2545. this._updateAABBDisplay();
  2546. }
  2547. }
  2548. if (this._AABBRenderPrim) {
  2549. this._AABBRenderPrim.levelVisible = this.debugRenderAABB;
  2550. }
  2551. var cw = this._clusterSize.width;
  2552. var ch = this._clusterSize.height;
  2553. // Check for Cluster resize
  2554. if (((this._clusterSize.width < 16 && this._clusterSize.height < 16 && this._maxActorByCluster >= 10) ||
  2555. (this._clusterSize.width > 2 && this._clusterSize.height > 2 && this._maxActorByCluster <= 7)) &&
  2556. this._lastClusterResizeCounter > 100) {
  2557. if (this._maxActorByCluster >= 10) {
  2558. ++cw;
  2559. ++ch;
  2560. }
  2561. else {
  2562. --cw;
  2563. --ch;
  2564. }
  2565. console.log("Change cluster size to " + cw + ":" + ch + ", max actor " + this._maxActorByCluster);
  2566. this._clusterDirty = true;
  2567. }
  2568. // Should we update the WireFrame2D Primitive that displays the clusters
  2569. if (this.debugRenderClusters && this._clusterDirty) {
  2570. this._updateClusterDisplay(cw, ch);
  2571. }
  2572. if (this._ClusterRenderPrim) {
  2573. this._ClusterRenderPrim.levelVisible = this.debugRenderClusters;
  2574. }
  2575. var updateStats = this.debugStats && (this._dirtyActors.count > 0 || this._clusterDirty);
  2576. this._debugUpdateTime.beginMonitoring();
  2577. // If the Cluster Size changed: rebuild it and add all actors. Otherwise add only new (dirty) actors
  2578. if (this._clusterDirty) {
  2579. this._initializeCluster(cw, ch);
  2580. this._rebuildAllActors();
  2581. }
  2582. else {
  2583. this._rebuildDirtyActors();
  2584. ++this._lastClusterResizeCounter;
  2585. }
  2586. // Proceed to the collision detection between primitives
  2587. this._collisionDetection();
  2588. this._debugUpdateTime.endMonitoring();
  2589. if (updateStats) {
  2590. this._updateDebugStats();
  2591. }
  2592. if (this._debugTextBackground) {
  2593. this._debugTextBackground.levelVisible = updateStats;
  2594. }
  2595. // Reset the dirty actor list: everything is processed
  2596. this._dirtyActors.clear();
  2597. };
  2598. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "debugRenderAABB", {
  2599. /**
  2600. * Renders the World AABB of all Actors
  2601. */
  2602. get: function () {
  2603. return this._debugRenderAABB;
  2604. },
  2605. set: function (val) {
  2606. if (this._debugRenderAABB === val) {
  2607. return;
  2608. }
  2609. this._debugRenderAABB = val;
  2610. this._debugRenderAABBDirty = true;
  2611. },
  2612. enumerable: true,
  2613. configurable: true
  2614. });
  2615. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "intersectedActors", {
  2616. get: function () {
  2617. return this._intersectedActors;
  2618. },
  2619. enumerable: true,
  2620. configurable: true
  2621. });
  2622. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "leftBorderIntersectedActors", {
  2623. get: function () {
  2624. return this._borderIntersecteddActors[0];
  2625. },
  2626. enumerable: true,
  2627. configurable: true
  2628. });
  2629. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "bottomBorderIntersectedActors", {
  2630. get: function () {
  2631. return this._borderIntersecteddActors[1];
  2632. },
  2633. enumerable: true,
  2634. configurable: true
  2635. });
  2636. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "rightBorderIntersectedActors", {
  2637. get: function () {
  2638. return this._borderIntersecteddActors[2];
  2639. },
  2640. enumerable: true,
  2641. configurable: true
  2642. });
  2643. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "topBorderIntersectedActors", {
  2644. get: function () {
  2645. return this._borderIntersecteddActors[3];
  2646. },
  2647. enumerable: true,
  2648. configurable: true
  2649. });
  2650. BasicPrimitiveCollisionManager.prototype._initializeCluster = function (countW, countH) {
  2651. // Check for free
  2652. if (this._clusters) {
  2653. for (var w = 0; w < this._clusterSize.height; w++) {
  2654. for (var h = 0; h < this._clusterSize.width; h++) {
  2655. this._freeClusterInfo(this._clusters[w][h]);
  2656. }
  2657. }
  2658. }
  2659. // Allocate
  2660. this._clusterSize.copyFromFloats(countW, countH);
  2661. this._clusters = [];
  2662. for (var w = 0; w < this._clusterSize.height; w++) {
  2663. this._clusters[w] = [];
  2664. for (var h = 0; h < this._clusterSize.width; h++) {
  2665. var ci = this._allocClusterInfo();
  2666. this._clusters[w][h] = ci;
  2667. }
  2668. }
  2669. this._clusterStep.copyFromFloats(this._owner.actualWidth / countW, this._owner.actualHeight / countH);
  2670. this._maxActorByCluster = 0;
  2671. this._lastClusterResizeCounter = 0;
  2672. this._clusterDirty = false;
  2673. };
  2674. BasicPrimitiveCollisionManager.prototype._rebuildAllActors = function () {
  2675. var _this = this;
  2676. this._actors.forEach(function (k, ai) {
  2677. _this._processActor(ai);
  2678. });
  2679. };
  2680. BasicPrimitiveCollisionManager.prototype._rebuildDirtyActors = function () {
  2681. var _this = this;
  2682. this._dirtyActors.forEach(function (k, ai) {
  2683. _this._processActor(ai);
  2684. });
  2685. };
  2686. BasicPrimitiveCollisionManager.prototype._processActor = function (actor) {
  2687. var _this = this;
  2688. // Check if the actor is being disabled or removed
  2689. if (!actor.isEnabled || actor.isRemoved) {
  2690. actor.presentInClusters.forEach(function (k, ci) {
  2691. ci.actors.remove(actor.prim.uid);
  2692. });
  2693. actor.presentInClusters.clear();
  2694. return;
  2695. }
  2696. var wab = actor.worldAABB;
  2697. // Build the worldAABB corners
  2698. var wac = BasicPrimitiveCollisionManager.WAABBCorners;
  2699. wac[0].copyFromFloats(wab.x, wab.y); // Bottom/Left
  2700. wac[1].copyFromFloats(wab.z, wab.y); // Bottom/Right
  2701. wac[2].copyFromFloats(wab.z, wab.w); // Top/Right
  2702. wac[3].copyFromFloats(wab.x, wab.w); // Top/Left
  2703. var cs = this._clusterStep;
  2704. var wacc = BasicPrimitiveCollisionManager.WAABBCornersCluster;
  2705. for (var i = 0; i < 4; i++) {
  2706. var p = wac[i];
  2707. var cx = (p.x - (p.x % cs.x)) / cs.x;
  2708. var cy = (p.y - (p.y % cs.y)) / cs.y;
  2709. wacc[i].copyFromFloats(Math.floor(cx), Math.floor(cy));
  2710. }
  2711. var opCount = 0;
  2712. var totalClusters = 0;
  2713. var newCI = new Array();
  2714. var sx = Math.max(0, wacc[0].x); // Start Cluster X
  2715. var sy = Math.max(0, wacc[0].y); // Start Cluster Y
  2716. var ex = Math.min(this._clusterSize.width - 1, wacc[2].x); // End Cluster X
  2717. var ey = Math.min(this._clusterSize.height - 1, wacc[2].y); // End Cluster Y
  2718. if (this._enableBorder) {
  2719. if (wac[0].x < 0) {
  2720. this._borderIntersecteddActors[0].add(actor.prim.uid, actor.prim);
  2721. }
  2722. else {
  2723. this._borderIntersecteddActors[0].remove(actor.prim.uid);
  2724. }
  2725. if (wac[0].y < 0) {
  2726. this._borderIntersecteddActors[1].add(actor.prim.uid, actor.prim);
  2727. }
  2728. else {
  2729. this._borderIntersecteddActors[1].remove(actor.prim.uid);
  2730. }
  2731. if (wac[2].x >= this._canvasSize.width) {
  2732. this._borderIntersecteddActors[2].add(actor.prim.uid, actor.prim);
  2733. }
  2734. else {
  2735. this._borderIntersecteddActors[2].remove(actor.prim.uid);
  2736. }
  2737. if (wac[2].y >= this._canvasSize.height) {
  2738. this._borderIntersecteddActors[3].add(actor.prim.uid, actor.prim);
  2739. }
  2740. else {
  2741. this._borderIntersecteddActors[3].remove(actor.prim.uid);
  2742. }
  2743. }
  2744. for (var y = sy; y <= ey; y++) {
  2745. var _loop_1 = function (x) {
  2746. var k = x + ":" + y;
  2747. var cx = x, cy = y;
  2748. var ci = actor.presentInClusters.getOrAddWithFactory(k, function (k) {
  2749. var nci = _this._getCluster(cx, cy);
  2750. nci.actors.add(actor.prim.uid, actor);
  2751. _this._maxActorByCluster = Math.max(_this._maxActorByCluster, nci.actors.count);
  2752. ++opCount;
  2753. ++totalClusters;
  2754. return nci;
  2755. });
  2756. newCI.push(ci);
  2757. };
  2758. for (var x = sx; x <= ex; x++) {
  2759. _loop_1(x);
  2760. }
  2761. }
  2762. // Check if there were no change
  2763. if (opCount === 0 && actor.presentInClusters.count === totalClusters) {
  2764. return;
  2765. }
  2766. // Build the array of the cluster where the actor is no longer in
  2767. var clusterToRemove = new Array();
  2768. actor.presentInClusters.forEach(function (k, ci) {
  2769. if (newCI.indexOf(ci) === -1) {
  2770. clusterToRemove.push(k);
  2771. // remove the primitive from the Cluster Info object
  2772. ci.actors.remove(actor.prim.uid);
  2773. }
  2774. });
  2775. // Remove these clusters from the actor's dictionary
  2776. for (var _i = 0, clusterToRemove_1 = clusterToRemove; _i < clusterToRemove_1.length; _i++) {
  2777. var key = clusterToRemove_1[_i];
  2778. actor.presentInClusters.remove(key);
  2779. }
  2780. };
  2781. // 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.
  2782. // Then for a given Actor that is dirty we evaluate the intersection with all the other actors present in the same Cluster(s)
  2783. // So it's basically O(n²), BUT only inside a Cluster and only for dirty Actors.
  2784. BasicPrimitiveCollisionManager.prototype._collisionDetection = function () {
  2785. var _this = this;
  2786. var hash = BasicPrimitiveCollisionManager.CandidatesActors;
  2787. var prev = BasicPrimitiveCollisionManager.PreviousIntersections;
  2788. var opCount = 0;
  2789. this._dirtyActors.forEach(function (k1, ai1) {
  2790. ++opCount;
  2791. // Build the list of candidates
  2792. hash.clear();
  2793. ai1.presentInClusters.forEach(function (k, ci) {
  2794. ++opCount;
  2795. ci.actors.forEach(function (k, v) { return hash.add(k, v); });
  2796. });
  2797. var wab1 = ai1.worldAABB;
  2798. // Save the previous intersections
  2799. prev.clear();
  2800. prev.copyFrom(ai1.intersectWith);
  2801. ai1.intersectWith.clear();
  2802. // For each candidate
  2803. hash.forEach(function (k2, ai2) {
  2804. ++opCount;
  2805. // Check if we're testing against itself
  2806. if (k1 === k2) {
  2807. return;
  2808. }
  2809. var wab2 = ai2.worldAABB;
  2810. if (wab2.z >= wab1.x && wab2.x <= wab1.z && wab2.w >= wab1.y && wab2.y <= wab1.w) {
  2811. if (ai1.prim.intersectOtherPrim(ai2.prim)) {
  2812. ++opCount;
  2813. ai1.intersectWith.add(k2, ai2);
  2814. if (k1 < k2) {
  2815. _this._intersectedActors.add(k1 + ";" + k2, { a: ai1.prim, b: ai2.prim });
  2816. }
  2817. else {
  2818. _this._intersectedActors.add(k2 + ";" + k1, { a: ai2.prim, b: ai1.prim });
  2819. }
  2820. }
  2821. }
  2822. });
  2823. // Check and remove the associations that no longer exist in the main intersection list
  2824. prev.forEach(function (k, ai) {
  2825. if (!ai1.intersectWith.contains(k)) {
  2826. ++opCount;
  2827. _this._intersectedActors.remove((k < k1 ? k : k1) + ";" + (k < k1 ? k1 : k));
  2828. }
  2829. });
  2830. });
  2831. this._debugUpdateOpCount.fetchNewFrame();
  2832. this._debugUpdateOpCount.addCount(opCount, true);
  2833. };
  2834. BasicPrimitiveCollisionManager.prototype._getCluster = function (x, y) {
  2835. return this._clusters[x][y];
  2836. };
  2837. BasicPrimitiveCollisionManager.prototype._updateDebugStats = function () {
  2838. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  2839. var txt = "Primitive Collision Stats\n" +
  2840. (" - PCM Execution Time: " + format(this._debugUpdateTime.lastSecAverage) + "ms\n") +
  2841. (" - Operation Count: " + format(this._debugUpdateOpCount.current) + ", (avg:" + format(this._debugUpdateOpCount.lastSecAverage) + ", t:" + format(this._debugUpdateOpCount.total) + ")\n") +
  2842. (" - Max Actor per Cluster: " + this._maxActorByCluster + "\n") +
  2843. (" - Intersections count: " + this.intersectedActors.count);
  2844. if (!this._debugTextBackground) {
  2845. this._debugTextBackground = new BABYLON.Rectangle2D({
  2846. id: "###DEBUG PMC STATS###", parent: this._owner, marginAlignment: "h: left, v: top", fill: "#C0404080", padding: "10", margin: "10", roundRadius: 10, children: [
  2847. new BABYLON.Text2D(txt, { id: "###DEBUG PMC TEXT###", fontName: "12pt Lucida Console" })
  2848. ]
  2849. });
  2850. }
  2851. else {
  2852. this._debugTextBackground.levelVisible = true;
  2853. var text2d = this._debugTextBackground.children[0];
  2854. text2d.text = txt;
  2855. }
  2856. };
  2857. BasicPrimitiveCollisionManager.prototype._updateAABBDisplay = function () {
  2858. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.5, 0.8, 1.0, 1.0));
  2859. var v = BABYLON.Vector2.Zero();
  2860. this._actors.forEach(function (k, ai) {
  2861. if (ai.isEnabled) {
  2862. var ab = ai.worldAABB;
  2863. v.x = ab.x;
  2864. v.y = ab.y;
  2865. g.startLineStrip(v);
  2866. v.x = ab.z;
  2867. g.pushVertex(v);
  2868. v.y = ab.w;
  2869. g.pushVertex(v);
  2870. v.x = ab.x;
  2871. g.pushVertex(v);
  2872. v.y = ab.y;
  2873. g.endLineStrip(v);
  2874. }
  2875. });
  2876. if (!this._AABBRenderPrim) {
  2877. this._AABBRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: false, id: "###DEBUG PCM AABB###" });
  2878. }
  2879. else {
  2880. this._AABBRenderPrim.wireFrameGroups.set("main", g);
  2881. this._AABBRenderPrim.wireFrameGroupsDirty();
  2882. }
  2883. this._debugRenderAABBDirty = false;
  2884. };
  2885. BasicPrimitiveCollisionManager.prototype._updateClusterDisplay = function (cw, ch) {
  2886. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.8, 0.1, 0.5, 1.0));
  2887. var v1 = BABYLON.Vector2.Zero();
  2888. var v2 = BABYLON.Vector2.Zero();
  2889. // Vertical lines
  2890. var step = (this._owner.actualWidth - 1) / cw;
  2891. v1.y = 0;
  2892. v2.y = this._owner.actualHeight;
  2893. for (var x = 0; x <= cw; x++) {
  2894. g.pushVertex(v1);
  2895. g.pushVertex(v2);
  2896. v1.x += step;
  2897. v2.x += step;
  2898. }
  2899. // Horizontal lines
  2900. step = (this._owner.actualHeight - 1) / ch;
  2901. v1.x = v1.y = v2.y = 0;
  2902. v2.x = this._owner.actualWidth;
  2903. for (var y = 0; y <= ch; y++) {
  2904. g.pushVertex(v1);
  2905. g.pushVertex(v2);
  2906. v1.y += step;
  2907. v2.y += step;
  2908. }
  2909. if (!this._ClusterRenderPrim) {
  2910. this._ClusterRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: true, id: "###DEBUG PCM Clusters###" });
  2911. }
  2912. else {
  2913. this._ClusterRenderPrim.wireFrameGroups.set("main", g);
  2914. this._ClusterRenderPrim.wireFrameGroupsDirty();
  2915. }
  2916. };
  2917. // 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
  2918. // ClusterInfo object and we have two method to allocate/free them. This way we always deal with the same objects.
  2919. // The free array never shrink, always grows...For the better...and the worst!
  2920. BasicPrimitiveCollisionManager.prototype._allocClusterInfo = function () {
  2921. if (this._freeClusters.length === 0) {
  2922. for (var i = 0; i < 8; i++) {
  2923. this._freeClusters.push(new ClusterInfo());
  2924. }
  2925. }
  2926. return this._freeClusters.pop();
  2927. };
  2928. BasicPrimitiveCollisionManager.prototype._freeClusterInfo = function (ci) {
  2929. ci.clear();
  2930. this._freeClusters.push(ci);
  2931. };
  2932. return BasicPrimitiveCollisionManager;
  2933. }(PrimitiveCollisionManagerBase));
  2934. BasicPrimitiveCollisionManager.WAABBCorners = null;
  2935. BasicPrimitiveCollisionManager.WAABBCornersCluster = null;
  2936. BasicPrimitiveCollisionManager.CandidatesActors = new BABYLON.StringDictionary();
  2937. BasicPrimitiveCollisionManager.PreviousIntersections = new BABYLON.StringDictionary();
  2938. })(BABYLON || (BABYLON = {}));
  2939. //# sourceMappingURL=babylon.primitiveCollisionManager.js.map
  2940. var __extends = (this && this.__extends) || function (d, b) {
  2941. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  2942. function __() { this.constructor = d; }
  2943. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2944. };
  2945. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2946. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  2947. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  2948. 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;
  2949. return c > 3 && r && Object.defineProperty(target, key, r), r;
  2950. };
  2951. var BABYLON;
  2952. (function (BABYLON) {
  2953. var LayoutEngineBase = (function () {
  2954. function LayoutEngineBase() {
  2955. this.layoutDirtyOnPropertyChangedMask = 0;
  2956. }
  2957. LayoutEngineBase.prototype.newChild = function (child, data) {
  2958. };
  2959. LayoutEngineBase.prototype.updateLayout = function (prim) {
  2960. };
  2961. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  2962. get: function () {
  2963. return false;
  2964. },
  2965. enumerable: true,
  2966. configurable: true
  2967. });
  2968. LayoutEngineBase.prototype.isLocked = function () {
  2969. return this._isLocked;
  2970. };
  2971. LayoutEngineBase.prototype.lock = function () {
  2972. if (this._isLocked) {
  2973. return false;
  2974. }
  2975. this._isLocked = true;
  2976. return true;
  2977. };
  2978. return LayoutEngineBase;
  2979. }());
  2980. LayoutEngineBase = __decorate([
  2981. BABYLON.className("LayoutEngineBase", "BABYLON")
  2982. ], LayoutEngineBase);
  2983. BABYLON.LayoutEngineBase = LayoutEngineBase;
  2984. var CanvasLayoutEngine = CanvasLayoutEngine_1 = (function (_super) {
  2985. __extends(CanvasLayoutEngine, _super);
  2986. function CanvasLayoutEngine() {
  2987. var _this = _super.call(this) || this;
  2988. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  2989. return _this;
  2990. }
  2991. Object.defineProperty(CanvasLayoutEngine, "Singleton", {
  2992. get: function () {
  2993. if (!CanvasLayoutEngine_1._singleton) {
  2994. CanvasLayoutEngine_1._singleton = new CanvasLayoutEngine_1();
  2995. }
  2996. return CanvasLayoutEngine_1._singleton;
  2997. },
  2998. enumerable: true,
  2999. configurable: true
  3000. });
  3001. // A very simple (no) layout computing...
  3002. // The Canvas and its direct children gets the Canvas' size as Layout Area
  3003. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  3004. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  3005. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  3006. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3007. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3008. var child = _a[_i];
  3009. this._doUpdate(child);
  3010. }
  3011. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3012. }
  3013. };
  3014. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  3015. // Canvas ?
  3016. if (prim instanceof BABYLON.Canvas2D) {
  3017. prim.layoutArea = prim.actualSize; //.multiplyByFloats(prim.scaleX, prim.scaleY);
  3018. }
  3019. else if (prim.parent instanceof BABYLON.Canvas2D) {
  3020. prim.layoutArea = prim.owner.actualSize; //.multiplyByFloats(prim.owner.scaleX, prim.owner.scaleY);
  3021. }
  3022. else {
  3023. prim.layoutArea = prim.parent.contentArea;
  3024. }
  3025. };
  3026. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  3027. get: function () {
  3028. return true;
  3029. },
  3030. enumerable: true,
  3031. configurable: true
  3032. });
  3033. return CanvasLayoutEngine;
  3034. }(LayoutEngineBase));
  3035. CanvasLayoutEngine._singleton = null;
  3036. CanvasLayoutEngine = CanvasLayoutEngine_1 = __decorate([
  3037. BABYLON.className("CanvasLayoutEngine", "BABYLON")
  3038. ], CanvasLayoutEngine);
  3039. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  3040. var StackPanelLayoutEngine = StackPanelLayoutEngine_1 = (function (_super) {
  3041. __extends(StackPanelLayoutEngine, _super);
  3042. function StackPanelLayoutEngine() {
  3043. var _this = _super.call(this) || this;
  3044. _this._isHorizontal = true;
  3045. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  3046. return _this;
  3047. }
  3048. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  3049. get: function () {
  3050. if (!StackPanelLayoutEngine_1._horizontal) {
  3051. StackPanelLayoutEngine_1._horizontal = new StackPanelLayoutEngine_1();
  3052. StackPanelLayoutEngine_1._horizontal.isHorizontal = true;
  3053. StackPanelLayoutEngine_1._horizontal.lock();
  3054. }
  3055. return StackPanelLayoutEngine_1._horizontal;
  3056. },
  3057. enumerable: true,
  3058. configurable: true
  3059. });
  3060. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  3061. get: function () {
  3062. if (!StackPanelLayoutEngine_1._vertical) {
  3063. StackPanelLayoutEngine_1._vertical = new StackPanelLayoutEngine_1();
  3064. StackPanelLayoutEngine_1._vertical.isHorizontal = false;
  3065. StackPanelLayoutEngine_1._vertical.lock();
  3066. }
  3067. return StackPanelLayoutEngine_1._vertical;
  3068. },
  3069. enumerable: true,
  3070. configurable: true
  3071. });
  3072. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  3073. get: function () {
  3074. return this._isHorizontal;
  3075. },
  3076. set: function (val) {
  3077. if (this.isLocked()) {
  3078. return;
  3079. }
  3080. this._isHorizontal = val;
  3081. },
  3082. enumerable: true,
  3083. configurable: true
  3084. });
  3085. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  3086. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3087. var x = 0;
  3088. var y = 0;
  3089. var h = this.isHorizontal;
  3090. var max = 0;
  3091. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3092. var child = _a[_i];
  3093. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3094. continue;
  3095. }
  3096. var layoutArea = void 0;
  3097. if (child._hasMargin) {
  3098. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, child.actualScale, StackPanelLayoutEngine_1.dstOffset, StackPanelLayoutEngine_1.dstArea, true);
  3099. layoutArea = StackPanelLayoutEngine_1.dstArea.clone();
  3100. child.layoutArea = layoutArea;
  3101. }
  3102. else {
  3103. layoutArea = child.layoutArea;
  3104. child.margin.computeArea(child.actualSize, layoutArea);
  3105. }
  3106. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  3107. }
  3108. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  3109. var child = _c[_b];
  3110. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3111. continue;
  3112. }
  3113. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  3114. var layoutArea = child.layoutArea;
  3115. if (h) {
  3116. x += layoutArea.width;
  3117. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  3118. }
  3119. else {
  3120. y += layoutArea.height;
  3121. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  3122. }
  3123. }
  3124. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3125. }
  3126. };
  3127. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  3128. get: function () {
  3129. return false;
  3130. },
  3131. enumerable: true,
  3132. configurable: true
  3133. });
  3134. return StackPanelLayoutEngine;
  3135. }(LayoutEngineBase));
  3136. StackPanelLayoutEngine._horizontal = null;
  3137. StackPanelLayoutEngine._vertical = null;
  3138. StackPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  3139. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  3140. StackPanelLayoutEngine = StackPanelLayoutEngine_1 = __decorate([
  3141. BABYLON.className("StackPanelLayoutEngine", "BABYLON")
  3142. ], StackPanelLayoutEngine);
  3143. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  3144. var CanvasLayoutEngine_1, StackPanelLayoutEngine_1;
  3145. })(BABYLON || (BABYLON = {}));
  3146. //# sourceMappingURL=babylon.canvas2dLayoutEngine.js.map
  3147. var __extends = (this && this.__extends) || function (d, b) {
  3148. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3149. function __() { this.constructor = d; }
  3150. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3151. };
  3152. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3153. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3154. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  3155. 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;
  3156. return c > 3 && r && Object.defineProperty(target, key, r), r;
  3157. };
  3158. var BABYLON;
  3159. (function (BABYLON) {
  3160. /**
  3161. * Base class implementing the ILocable interface.
  3162. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  3163. */
  3164. var LockableBase = (function () {
  3165. function LockableBase() {
  3166. }
  3167. LockableBase.prototype.isLocked = function () {
  3168. return this._isLocked;
  3169. };
  3170. LockableBase.prototype.lock = function () {
  3171. if (this._isLocked) {
  3172. return true;
  3173. }
  3174. this.onLock();
  3175. this._isLocked = true;
  3176. return false;
  3177. };
  3178. /**
  3179. * Protected handler that will be called when the instance is about to be locked.
  3180. */
  3181. LockableBase.prototype.onLock = function () {
  3182. };
  3183. return LockableBase;
  3184. }());
  3185. BABYLON.LockableBase = LockableBase;
  3186. var SolidColorBrush2D = (function (_super) {
  3187. __extends(SolidColorBrush2D, _super);
  3188. function SolidColorBrush2D(color, lock) {
  3189. if (lock === void 0) { lock = false; }
  3190. var _this = _super.call(this) || this;
  3191. _this._color = color;
  3192. if (lock) {
  3193. {
  3194. _this.lock();
  3195. }
  3196. }
  3197. return _this;
  3198. }
  3199. /**
  3200. * Return true if the brush is transparent, false if it's totally opaque
  3201. */
  3202. SolidColorBrush2D.prototype.isTransparent = function () {
  3203. return this._color && this._color.a < 1.0;
  3204. };
  3205. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  3206. /**
  3207. * The color used by this instance to render
  3208. * @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.
  3209. */
  3210. get: function () {
  3211. return this._color;
  3212. },
  3213. set: function (value) {
  3214. if (this.isLocked()) {
  3215. return;
  3216. }
  3217. this._color = value;
  3218. },
  3219. enumerable: true,
  3220. configurable: true
  3221. });
  3222. /**
  3223. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  3224. */
  3225. SolidColorBrush2D.prototype.toString = function () {
  3226. return this._color.toHexString();
  3227. };
  3228. return SolidColorBrush2D;
  3229. }(LockableBase));
  3230. SolidColorBrush2D = __decorate([
  3231. BABYLON.className("SolidColorBrush2D", "BABYLON")
  3232. ], SolidColorBrush2D);
  3233. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  3234. var GradientColorBrush2D = (function (_super) {
  3235. __extends(GradientColorBrush2D, _super);
  3236. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  3237. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  3238. if (rotation === void 0) { rotation = 0; }
  3239. if (scale === void 0) { scale = 1; }
  3240. if (lock === void 0) { lock = false; }
  3241. var _this = _super.call(this) || this;
  3242. _this._color1 = color1;
  3243. _this._color2 = color2;
  3244. _this._translation = translation;
  3245. _this._rotation = rotation;
  3246. _this._scale = scale;
  3247. if (lock) {
  3248. _this.lock();
  3249. }
  3250. return _this;
  3251. }
  3252. /**
  3253. * Return true if the brush is transparent, false if it's totally opaque
  3254. */
  3255. GradientColorBrush2D.prototype.isTransparent = function () {
  3256. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  3257. };
  3258. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  3259. /**
  3260. * First color, the blend will start from this color
  3261. */
  3262. get: function () {
  3263. return this._color1;
  3264. },
  3265. set: function (value) {
  3266. if (this.isLocked()) {
  3267. return;
  3268. }
  3269. this._color1 = value;
  3270. },
  3271. enumerable: true,
  3272. configurable: true
  3273. });
  3274. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  3275. /**
  3276. * Second color, the blend will end to this color
  3277. */
  3278. get: function () {
  3279. return this._color2;
  3280. },
  3281. set: function (value) {
  3282. if (this.isLocked()) {
  3283. return;
  3284. }
  3285. this._color2 = value;
  3286. },
  3287. enumerable: true,
  3288. configurable: true
  3289. });
  3290. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  3291. /**
  3292. * Translation vector to apply on the blend
  3293. * Default is [0;0]
  3294. */
  3295. get: function () {
  3296. return this._translation;
  3297. },
  3298. set: function (value) {
  3299. if (this.isLocked()) {
  3300. return;
  3301. }
  3302. this._translation = value;
  3303. },
  3304. enumerable: true,
  3305. configurable: true
  3306. });
  3307. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  3308. /**
  3309. * Rotation in radian to apply to the brush
  3310. * Default direction of the brush is vertical, you can change this using this property.
  3311. * Default is 0.
  3312. */
  3313. get: function () {
  3314. return this._rotation;
  3315. },
  3316. set: function (value) {
  3317. if (this.isLocked()) {
  3318. return;
  3319. }
  3320. this._rotation = value;
  3321. },
  3322. enumerable: true,
  3323. configurable: true
  3324. });
  3325. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  3326. /**
  3327. * Scale factor to apply to the gradient.
  3328. * Default is 1: no scale.
  3329. */
  3330. get: function () {
  3331. return this._scale;
  3332. },
  3333. set: function (value) {
  3334. if (this.isLocked()) {
  3335. return;
  3336. }
  3337. this._scale = value;
  3338. },
  3339. enumerable: true,
  3340. configurable: true
  3341. });
  3342. /**
  3343. * Return a string describing the brush
  3344. */
  3345. GradientColorBrush2D.prototype.toString = function () {
  3346. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  3347. };
  3348. /**
  3349. * Build a unique key string for the given parameters
  3350. */
  3351. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  3352. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  3353. };
  3354. return GradientColorBrush2D;
  3355. }(LockableBase));
  3356. GradientColorBrush2D = __decorate([
  3357. BABYLON.className("GradientColorBrush2D", "BABYLON")
  3358. ], GradientColorBrush2D);
  3359. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  3360. })(BABYLON || (BABYLON = {}));
  3361. //# sourceMappingURL=babylon.brushes2d.js.map
  3362. var __extends = (this && this.__extends) || function (d, b) {
  3363. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3364. function __() { this.constructor = d; }
  3365. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3366. };
  3367. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3368. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3369. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  3370. 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;
  3371. return c > 3 && r && Object.defineProperty(target, key, r), r;
  3372. };
  3373. var BABYLON;
  3374. (function (BABYLON) {
  3375. var Prim2DClassInfo = (function () {
  3376. function Prim2DClassInfo() {
  3377. }
  3378. return Prim2DClassInfo;
  3379. }());
  3380. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  3381. var Prim2DPropInfo = (function () {
  3382. function Prim2DPropInfo() {
  3383. }
  3384. return Prim2DPropInfo;
  3385. }());
  3386. Prim2DPropInfo.PROPKIND_MODEL = 1;
  3387. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  3388. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  3389. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  3390. var ClassTreeInfo = (function () {
  3391. function ClassTreeInfo(baseClass, type, classContentFactory) {
  3392. this._baseClass = baseClass;
  3393. this._type = type;
  3394. this._subClasses = new Array();
  3395. this._levelContent = new BABYLON.StringDictionary();
  3396. this._classContentFactory = classContentFactory;
  3397. }
  3398. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  3399. get: function () {
  3400. if (!this._classContent) {
  3401. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  3402. }
  3403. return this._classContent;
  3404. },
  3405. enumerable: true,
  3406. configurable: true
  3407. });
  3408. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  3409. get: function () {
  3410. return this._type;
  3411. },
  3412. enumerable: true,
  3413. configurable: true
  3414. });
  3415. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  3416. get: function () {
  3417. return this._levelContent;
  3418. },
  3419. enumerable: true,
  3420. configurable: true
  3421. });
  3422. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  3423. get: function () {
  3424. if (!this._fullContent) {
  3425. var dic_1 = new BABYLON.StringDictionary();
  3426. var curLevel = this;
  3427. while (curLevel) {
  3428. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  3429. curLevel = curLevel._baseClass;
  3430. }
  3431. this._fullContent = dic_1;
  3432. }
  3433. return this._fullContent;
  3434. },
  3435. enumerable: true,
  3436. configurable: true
  3437. });
  3438. ClassTreeInfo.prototype.getLevelOf = function (type) {
  3439. // Are we already there?
  3440. if (type === this._type) {
  3441. return this;
  3442. }
  3443. var baseProto = Object.getPrototypeOf(type);
  3444. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  3445. if (!curProtoContent) {
  3446. this.getLevelOf(baseProto);
  3447. }
  3448. return this.getOrAddType(baseProto, type);
  3449. };
  3450. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  3451. // Are we at the level corresponding to the baseType?
  3452. // If so, get or add the level we're looking for
  3453. if (baseType === this._type) {
  3454. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  3455. var subType = _a[_i];
  3456. if (subType.type === type) {
  3457. return subType.node;
  3458. }
  3459. }
  3460. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  3461. var info = { type: type, node: node };
  3462. this._subClasses.push(info);
  3463. return info.node;
  3464. }
  3465. // Recurse down to keep looking for the node corresponding to the baseTypeName
  3466. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  3467. var subType = _c[_b];
  3468. var info = subType.node.getOrAddType(baseType, type);
  3469. if (info) {
  3470. return info;
  3471. }
  3472. }
  3473. return null;
  3474. };
  3475. ClassTreeInfo.get = function (type) {
  3476. var dic = type["__classTreeInfo"];
  3477. if (!dic) {
  3478. return null;
  3479. }
  3480. return dic.getLevelOf(type);
  3481. };
  3482. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  3483. var dic = type["__classTreeInfo"];
  3484. if (!dic) {
  3485. dic = new ClassTreeInfo(null, type, classContentFactory);
  3486. type["__classTreeInfo"] = dic;
  3487. }
  3488. return dic;
  3489. };
  3490. return ClassTreeInfo;
  3491. }());
  3492. BABYLON.ClassTreeInfo = ClassTreeInfo;
  3493. var DataBinding = DataBinding_1 = (function () {
  3494. function DataBinding() {
  3495. this._converter = null;
  3496. this._mode = DataBinding_1.MODE_DEFAULT;
  3497. this._uiElementId = null;
  3498. this._dataSource = null;
  3499. this._currentDataSource = null;
  3500. this._propertyPathName = null;
  3501. this._stringFormat = null;
  3502. this._updateSourceTrigger = DataBinding_1.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  3503. this._boundTo = null;
  3504. this._owner = null;
  3505. this._updateCounter = 0;
  3506. }
  3507. Object.defineProperty(DataBinding.prototype, "converter", {
  3508. /**
  3509. * Provide a callback that will convert the value obtained by the Data Binding to the type of the SmartProperty it's bound to.
  3510. * If no value are set, then it's assumed that the sourceValue is of the same type as the SmartProperty's one.
  3511. * 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.
  3512. * @param sourceValue the source object retrieve by the Data Binding mechanism
  3513. * @returns the object of a compatible type with the SmartProperty it's bound to
  3514. */
  3515. get: function () {
  3516. return this._converter;
  3517. },
  3518. set: function (value) {
  3519. if (this._converter === value) {
  3520. return;
  3521. }
  3522. this._converter = value;
  3523. },
  3524. enumerable: true,
  3525. configurable: true
  3526. });
  3527. Object.defineProperty(DataBinding.prototype, "mode", {
  3528. /**
  3529. * 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
  3530. */
  3531. get: function () {
  3532. if (this._mode === DataBinding_1.MODE_DEFAULT) {
  3533. return this._boundTo.bindingMode;
  3534. }
  3535. return this._mode;
  3536. },
  3537. set: function (value) {
  3538. if (this._mode === value) {
  3539. return;
  3540. }
  3541. this._mode = value;
  3542. },
  3543. enumerable: true,
  3544. configurable: true
  3545. });
  3546. Object.defineProperty(DataBinding.prototype, "uiElementId", {
  3547. /**
  3548. * You can override the Data Source object with this member which is the Id of a uiElement existing in the UI Logical tree.
  3549. * If not set and source no set too, then the dataSource property will be used.
  3550. */
  3551. get: function () {
  3552. return this._uiElementId;
  3553. },
  3554. set: function (value) {
  3555. if (this._uiElementId === value) {
  3556. return;
  3557. }
  3558. this._uiElementId = value;
  3559. },
  3560. enumerable: true,
  3561. configurable: true
  3562. });
  3563. Object.defineProperty(DataBinding.prototype, "dataSource", {
  3564. /**
  3565. * You can override the Data Source object with this member which is the source object to use directly.
  3566. * If not set and uiElement no set too, then the dataSource property of the SmartPropertyBase object will be used.
  3567. */
  3568. get: function () {
  3569. return this._dataSource;
  3570. },
  3571. set: function (value) {
  3572. if (this._dataSource === value) {
  3573. return;
  3574. }
  3575. this._dataSource = value;
  3576. },
  3577. enumerable: true,
  3578. configurable: true
  3579. });
  3580. Object.defineProperty(DataBinding.prototype, "propertyPathName", {
  3581. /**
  3582. * The path & name of the property to get from the source object.
  3583. * 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.
  3584. * If nothing is set then the source object will be used.
  3585. * 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.
  3586. * 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.
  3587. */
  3588. get: function () {
  3589. return this._propertyPathName;
  3590. },
  3591. set: function (value) {
  3592. if (this._propertyPathName === value) {
  3593. return;
  3594. }
  3595. if (this._owner) {
  3596. }
  3597. this._propertyPathName = value;
  3598. if (this._owner) {
  3599. }
  3600. },
  3601. enumerable: true,
  3602. configurable: true
  3603. });
  3604. Object.defineProperty(DataBinding.prototype, "stringFormat", {
  3605. /**
  3606. * 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}`
  3607. */
  3608. get: function () {
  3609. return this._stringFormat;
  3610. },
  3611. set: function (value) {
  3612. if (this._stringFormat === value) {
  3613. return;
  3614. }
  3615. this._stringFormat = value;
  3616. },
  3617. enumerable: true,
  3618. configurable: true
  3619. });
  3620. Object.defineProperty(DataBinding.prototype, "updateSourceTrigger", {
  3621. /**
  3622. * 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.
  3623. */
  3624. get: function () {
  3625. return this._updateSourceTrigger;
  3626. },
  3627. set: function (value) {
  3628. if (this._updateSourceTrigger === value) {
  3629. return;
  3630. }
  3631. this._updateSourceTrigger = value;
  3632. },
  3633. enumerable: true,
  3634. configurable: true
  3635. });
  3636. DataBinding.prototype.canUpdateTarget = function (resetUpdateCounter) {
  3637. if (resetUpdateCounter) {
  3638. this._updateCounter = 0;
  3639. }
  3640. var mode = this.mode;
  3641. if (mode === DataBinding_1.MODE_ONETIME) {
  3642. return this._updateCounter === 0;
  3643. }
  3644. if (mode === DataBinding_1.MODE_ONEWAYTOSOURCE) {
  3645. return false;
  3646. }
  3647. return true;
  3648. };
  3649. DataBinding.prototype.updateTarget = function () {
  3650. var value = this._getActualDataSource();
  3651. var properties = this.propertyPathName.split(".");
  3652. for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
  3653. var propertyName = properties_1[_i];
  3654. value = value[propertyName];
  3655. }
  3656. this._storeBoundValue(this._owner, value);
  3657. };
  3658. DataBinding.prototype._storeBoundValue = function (watcher, value) {
  3659. if ((++this._updateCounter > 1) && (this.mode === DataBinding_1.MODE_ONETIME)) {
  3660. return;
  3661. }
  3662. var newValue = value;
  3663. if (this._converter) {
  3664. newValue = this._converter(value);
  3665. }
  3666. if (this._stringFormat) {
  3667. newValue = this._stringFormat(newValue);
  3668. }
  3669. watcher[this._boundTo.name] = newValue;
  3670. };
  3671. DataBinding.prototype._getActualDataSource = function () {
  3672. if (this.dataSource) {
  3673. return this.dataSource;
  3674. }
  3675. if (this.uiElementId) {
  3676. // TODO Find UIElement
  3677. return null;
  3678. }
  3679. return this._owner.dataSource;
  3680. };
  3681. DataBinding.prototype._registerDataSource = function (updateTarget) {
  3682. var ds = this._getActualDataSource();
  3683. if (ds === this._currentDataSource) {
  3684. return;
  3685. }
  3686. if (this._currentDataSource) {
  3687. BindingHelper.unregisterDataSource(this._currentDataSource, this, 0);
  3688. }
  3689. if (ds) {
  3690. BindingHelper.registerDataSource(ds, this);
  3691. if (updateTarget && this.canUpdateTarget(true)) {
  3692. this.updateTarget();
  3693. }
  3694. }
  3695. this._currentDataSource = ds;
  3696. };
  3697. DataBinding.prototype._unregisterDataSource = function () {
  3698. var ds = this._getActualDataSource();
  3699. if (ds) {
  3700. BindingHelper.unregisterDataSource(ds, this, 0);
  3701. }
  3702. };
  3703. return DataBinding;
  3704. }());
  3705. /**
  3706. * Use the mode specified in the SmartProperty declaration
  3707. */
  3708. DataBinding.MODE_DEFAULT = 1;
  3709. /**
  3710. * Update the binding target only once when the Smart Property's value is first accessed
  3711. */
  3712. DataBinding.MODE_ONETIME = 2;
  3713. /**
  3714. * Update the smart property when the source changes.
  3715. * The source won't be updated if the smart property value is set.
  3716. */
  3717. DataBinding.MODE_ONEWAY = 3;
  3718. /**
  3719. * Only update the source when the target's data is changing.
  3720. */
  3721. DataBinding.MODE_ONEWAYTOSOURCE = 4;
  3722. /**
  3723. * Update the bind target when the source changes and update the source when the Smart Property value is set.
  3724. */
  3725. DataBinding.MODE_TWOWAY = 5;
  3726. /**
  3727. * Use the Update Source Trigger defined in the SmartProperty declaration
  3728. */
  3729. DataBinding.UPDATESOURCETRIGGER_DEFAULT = 1;
  3730. /**
  3731. * Update the source as soon as the Smart Property has a value change
  3732. */
  3733. DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED = 2;
  3734. /**
  3735. * Update the source when the binding target loses focus
  3736. */
  3737. DataBinding.UPDATESOURCETRIGGER_LOSTFOCUS = 3;
  3738. /**
  3739. * Update the source will be made by explicitly calling the UpdateFromDataSource method
  3740. */
  3741. DataBinding.UPDATESOURCETRIGGER_EXPLICIT = 4;
  3742. DataBinding = DataBinding_1 = __decorate([
  3743. BABYLON.className("DataBinding", "BABYLON")
  3744. ], DataBinding);
  3745. BABYLON.DataBinding = DataBinding;
  3746. var SmartPropertyBase = SmartPropertyBase_1 = (function (_super) {
  3747. __extends(SmartPropertyBase, _super);
  3748. function SmartPropertyBase() {
  3749. var _this = _super.call(this) || this;
  3750. _this._dataSource = null;
  3751. _this._dataSourceObserver = null;
  3752. _this._instanceDirtyFlags = 0;
  3753. _this._isDisposed = false;
  3754. _this._bindings = null;
  3755. _this._hasBinding = 0;
  3756. _this._bindingSourceChanged = 0;
  3757. _this._disposeObservable = null;
  3758. return _this;
  3759. }
  3760. Object.defineProperty(SmartPropertyBase.prototype, "disposeObservable", {
  3761. get: function () {
  3762. if (!this._disposeObservable) {
  3763. this._disposeObservable = new BABYLON.Observable();
  3764. }
  3765. return this._disposeObservable;
  3766. },
  3767. enumerable: true,
  3768. configurable: true
  3769. });
  3770. Object.defineProperty(SmartPropertyBase.prototype, "isDisposed", {
  3771. /**
  3772. * Check if the object is disposed or not.
  3773. * @returns true if the object is dispose, false otherwise.
  3774. */
  3775. get: function () {
  3776. return this._isDisposed;
  3777. },
  3778. enumerable: true,
  3779. configurable: true
  3780. });
  3781. /**
  3782. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  3783. * @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.
  3784. */
  3785. SmartPropertyBase.prototype.dispose = function () {
  3786. if (this.isDisposed) {
  3787. return false;
  3788. }
  3789. if (this._disposeObservable && this._disposeObservable.hasObservers()) {
  3790. this._disposeObservable.notifyObservers(this);
  3791. }
  3792. this._isDisposed = true;
  3793. return true;
  3794. };
  3795. /**
  3796. * Check if a given set of properties are dirty or not.
  3797. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  3798. * @return true if at least one property is dirty, false if none of them are.
  3799. */
  3800. SmartPropertyBase.prototype.checkPropertiesDirty = function (flags) {
  3801. return (this._instanceDirtyFlags & flags) !== 0;
  3802. };
  3803. /**
  3804. * Clear a given set of properties.
  3805. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  3806. * @return the new set of property still marked as dirty
  3807. */
  3808. SmartPropertyBase.prototype.clearPropertiesDirty = function (flags) {
  3809. this._instanceDirtyFlags &= ~flags;
  3810. return this._instanceDirtyFlags;
  3811. };
  3812. SmartPropertyBase.prototype._resetPropertiesDirty = function () {
  3813. this._instanceDirtyFlags = 0;
  3814. };
  3815. /**
  3816. * Add an externally attached data from its key.
  3817. * This method call will fail and return false, if such key already exists.
  3818. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3819. * @param key the unique key that identifies the data
  3820. * @param data the data object to associate to the key for this Engine instance
  3821. * @return true if no such key were already present and the data was added successfully, false otherwise
  3822. */
  3823. SmartPropertyBase.prototype.addExternalData = function (key, data) {
  3824. if (!this._externalData) {
  3825. this._externalData = new BABYLON.StringDictionary();
  3826. }
  3827. return this._externalData.add(key, data);
  3828. };
  3829. /**
  3830. * Get an externally attached data from its key
  3831. * @param key the unique key that identifies the data
  3832. * @return the associated data, if present (can be null), or undefined if not present
  3833. */
  3834. SmartPropertyBase.prototype.getExternalData = function (key) {
  3835. if (!this._externalData) {
  3836. return null;
  3837. }
  3838. return this._externalData.get(key);
  3839. };
  3840. /**
  3841. * Get an externally attached data from its key, create it using a factory if it's not already present
  3842. * @param key the unique key that identifies the data
  3843. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3844. * @return the associated data, can be null if the factory returned null.
  3845. */
  3846. SmartPropertyBase.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  3847. if (!this._externalData) {
  3848. this._externalData = new BABYLON.StringDictionary();
  3849. }
  3850. return this._externalData.getOrAddWithFactory(key, factory);
  3851. };
  3852. /**
  3853. * Remove an externally attached data from the Engine instance
  3854. * @param key the unique key that identifies the data
  3855. * @return true if the data was successfully removed, false if it doesn't exist
  3856. */
  3857. SmartPropertyBase.prototype.removeExternalData = function (key) {
  3858. if (!this._externalData) {
  3859. return false;
  3860. }
  3861. return this._externalData.remove(key);
  3862. };
  3863. SmartPropertyBase._hookProperty = function (propId, piStore, kind, settings) {
  3864. return function (target, propName, descriptor) {
  3865. if (!settings) {
  3866. settings = {};
  3867. }
  3868. var propInfo = SmartPropertyBase_1._createPropInfo(target, propName, propId, kind, settings);
  3869. if (piStore) {
  3870. piStore(propInfo);
  3871. }
  3872. var getter = descriptor.get, setter = descriptor.set;
  3873. var typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  3874. // Overload the property setter implementation to add our own logic
  3875. descriptor.set = function (val) {
  3876. if (!setter) {
  3877. throw Error("Property '" + propInfo.name + "' of type '" + BABYLON.Tools.getFullClassName(this) + "' has no setter defined but was invoked as if it had one.");
  3878. }
  3879. // check for disposed first, do nothing
  3880. if (this.isDisposed) {
  3881. return;
  3882. }
  3883. var curVal = getter.call(this);
  3884. if (SmartPropertyBase_1._checkUnchanged(curVal, val)) {
  3885. return;
  3886. }
  3887. // Cast the object we're working one
  3888. var prim = this;
  3889. // Change the value
  3890. setter.call(this, val);
  3891. // Notify change, dirty flags update
  3892. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  3893. };
  3894. };
  3895. };
  3896. SmartPropertyBase._createPropInfo = function (target, propName, propId, kind, settings) {
  3897. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  3898. var node = dic.getLevelOf(target);
  3899. var propInfo = node.levelContent.get(propId.toString());
  3900. if (propInfo) {
  3901. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  3902. }
  3903. // Create, setup and add the PropInfo object to our prop dictionary
  3904. propInfo = new Prim2DPropInfo();
  3905. propInfo.id = propId;
  3906. propInfo.flagId = Math.pow(2, propId);
  3907. propInfo.kind = kind;
  3908. propInfo.name = propName;
  3909. propInfo.bindingMode = (settings.bindingMode !== undefined) ? settings.bindingMode : DataBinding.MODE_TWOWAY;
  3910. propInfo.bindingUpdateSourceTrigger = (settings.bindingUpdateSourceTrigger !== undefined) ? settings.bindingUpdateSourceTrigger : DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  3911. propInfo.dirtyBoundingInfo = (settings.dirtyBoundingInfo !== undefined) ? settings.dirtyBoundingInfo : false;
  3912. propInfo.dirtyParentBoundingInfo = (settings.dirtyParentBoundingBox !== undefined) ? settings.dirtyParentBoundingBox : false;
  3913. propInfo.typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  3914. node.levelContent.add(propName, propInfo);
  3915. return propInfo;
  3916. };
  3917. Object.defineProperty(SmartPropertyBase.prototype, "propDic", {
  3918. /**
  3919. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  3920. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  3921. */
  3922. get: function () {
  3923. if (!this._propInfo) {
  3924. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  3925. if (!cti) {
  3926. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  3927. }
  3928. this._propInfo = cti.fullContent;
  3929. }
  3930. return this._propInfo;
  3931. },
  3932. enumerable: true,
  3933. configurable: true
  3934. });
  3935. SmartPropertyBase._checkUnchanged = function (curValue, newValue) {
  3936. // Nothing to nothing: nothing to do!
  3937. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  3938. return true;
  3939. }
  3940. // Check value unchanged
  3941. if ((curValue != null) && (newValue != null)) {
  3942. if (typeof (curValue.equals) == "function") {
  3943. if (curValue.equals(newValue)) {
  3944. return true;
  3945. }
  3946. }
  3947. else {
  3948. if (curValue === newValue) {
  3949. return true;
  3950. }
  3951. }
  3952. }
  3953. return false;
  3954. };
  3955. SmartPropertyBase.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  3956. // Trigger property changed
  3957. var info = SmartPropertyBase_1.propChangeGuarding ? new BABYLON.PropertyChangedInfo() : SmartPropertyPrim.propChangedInfo;
  3958. info.oldValue = curValue;
  3959. info.newValue = newValue;
  3960. info.propertyName = propName;
  3961. var propMask = propInfo ? propInfo.flagId : -1;
  3962. try {
  3963. SmartPropertyBase_1.propChangeGuarding = true;
  3964. this.propertyChanged.notifyObservers(info, propMask);
  3965. }
  3966. finally {
  3967. SmartPropertyBase_1.propChangeGuarding = false;
  3968. }
  3969. };
  3970. SmartPropertyBase.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  3971. if (this.isDisposed) {
  3972. return;
  3973. }
  3974. if (!propInfo) {
  3975. return;
  3976. }
  3977. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  3978. };
  3979. Object.defineProperty(SmartPropertyBase.prototype, "dataSource", {
  3980. /**
  3981. * Set the object from which Smart Properties using Binding will take/update their data from/to.
  3982. * 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.
  3983. */
  3984. get: function () {
  3985. // Don't access to _dataSource directly but via a call to the _getDataSource method which can be overloaded in inherited classes
  3986. return this._getDataSource();
  3987. },
  3988. set: function (value) {
  3989. if (this._dataSource === value) {
  3990. return;
  3991. }
  3992. var oldValue = this._dataSource;
  3993. this._dataSource = value;
  3994. if (this._bindings && value != null) {
  3995. // Register the bindings
  3996. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  3997. var binding = _a[_i];
  3998. if (binding != null) {
  3999. binding._registerDataSource(true);
  4000. }
  4001. }
  4002. }
  4003. this.onPropertyChanged("dataSource", oldValue, value);
  4004. },
  4005. enumerable: true,
  4006. configurable: true
  4007. });
  4008. // Inheriting classes can overload this method to provides additional logic for dataSource access
  4009. SmartPropertyBase.prototype._getDataSource = function () {
  4010. return this._dataSource;
  4011. };
  4012. SmartPropertyBase.prototype.createSimpleDataBinding = function (propInfo, propertyPathName, mode) {
  4013. if (mode === void 0) { mode = DataBinding.MODE_DEFAULT; }
  4014. var binding = new DataBinding();
  4015. binding.propertyPathName = propertyPathName;
  4016. binding.mode = mode;
  4017. return this.createDataBinding(propInfo, binding);
  4018. };
  4019. SmartPropertyBase.prototype.createDataBinding = function (propInfo, binding) {
  4020. if (!this._bindings) {
  4021. this._bindings = new Array();
  4022. }
  4023. if (!binding || binding._owner != null) {
  4024. throw Error("A valid/unused Binding must be passed.");
  4025. }
  4026. // Unregister a potentially existing binding for this property
  4027. this.removeDataBinding(propInfo);
  4028. // register the binding
  4029. binding._owner = this;
  4030. binding._boundTo = propInfo;
  4031. this._bindings[propInfo.id] = binding;
  4032. this._hasBinding |= propInfo.flagId;
  4033. binding._registerDataSource(true);
  4034. return binding;
  4035. };
  4036. SmartPropertyBase.prototype.removeDataBinding = function (propInfo) {
  4037. if ((this._hasBinding & propInfo.flagId) === 0) {
  4038. return false;
  4039. }
  4040. var curBinding = this._bindings[propInfo.id];
  4041. curBinding._unregisterDataSource();
  4042. this._bindings[propInfo.id] = null;
  4043. this._hasBinding &= ~propInfo.flagId;
  4044. return true;
  4045. };
  4046. SmartPropertyBase.prototype.updateFromDataSource = function () {
  4047. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  4048. var binding = _a[_i];
  4049. if (binding) {
  4050. }
  4051. }
  4052. };
  4053. return SmartPropertyBase;
  4054. }(BABYLON.PropertyChangedBase));
  4055. SmartPropertyBase.propChangedInfo = new BABYLON.PropertyChangedInfo();
  4056. SmartPropertyBase.propChangeGuarding = false;
  4057. SmartPropertyBase = SmartPropertyBase_1 = __decorate([
  4058. BABYLON.className("SmartPropertyBase", "BABYLON")
  4059. ], SmartPropertyBase);
  4060. BABYLON.SmartPropertyBase = SmartPropertyBase;
  4061. var BindingInfo = (function () {
  4062. function BindingInfo(binding, level, isLast) {
  4063. this.binding = binding;
  4064. this.level = level;
  4065. this.isLast = isLast;
  4066. }
  4067. return BindingInfo;
  4068. }());
  4069. var MonitoredObjectData = (function () {
  4070. function MonitoredObjectData(monitoredObject) {
  4071. var _this = this;
  4072. this.monitoredObject = monitoredObject;
  4073. this.monitoredIntermediateProperties = new BABYLON.StringDictionary();
  4074. this.observer = this.monitoredObject.propertyChanged.add(function (e, s) { _this.propertyChangedHandler(e.propertyName, e.oldValue, e.newValue); });
  4075. this.boundProperties = new BABYLON.StringDictionary();
  4076. this.monitoredIntermediateMask = 0;
  4077. this.boundPropertiesMask = 0;
  4078. }
  4079. MonitoredObjectData.prototype.propertyChangedHandler = function (propName, oldValue, newValue) {
  4080. var propId = BindingHelper._getPropertyID(this.monitoredObject, propName);
  4081. var propIdStr = propId.toString();
  4082. // Loop through all the registered bindings for this property that had a value change
  4083. if ((this.boundPropertiesMask & propId) !== 0) {
  4084. var bindingInfos = this.boundProperties.get(propIdStr);
  4085. for (var _i = 0, bindingInfos_1 = bindingInfos; _i < bindingInfos_1.length; _i++) {
  4086. var bi = bindingInfos_1[_i];
  4087. if (!bi.isLast) {
  4088. BindingHelper.unregisterDataSource(this.monitoredObject, bi.binding, bi.level);
  4089. BindingHelper.registerDataSource(bi.binding._currentDataSource, bi.binding);
  4090. }
  4091. if (bi.binding.canUpdateTarget(false)) {
  4092. bi.binding.updateTarget();
  4093. }
  4094. }
  4095. }
  4096. };
  4097. return MonitoredObjectData;
  4098. }());
  4099. var BindingHelper = (function () {
  4100. function BindingHelper() {
  4101. }
  4102. BindingHelper.registerDataSource = function (dataSource, binding) {
  4103. var properties = binding.propertyPathName.split(".");
  4104. var ownerMod = null;
  4105. var ownerInterPropId = 0;
  4106. var propertyOwner = dataSource;
  4107. var _loop_1 = function (i) {
  4108. var propName = properties[i];
  4109. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  4110. var propIdStr = propId.toString();
  4111. var mod = void 0;
  4112. if (ownerMod) {
  4113. var o_1 = ownerMod;
  4114. var po_1 = propertyOwner;
  4115. var oii_1 = ownerInterPropId;
  4116. mod = ownerMod.monitoredIntermediateProperties.getOrAddWithFactory(oii_1.toString(), function (k) {
  4117. o_1.monitoredIntermediateMask |= oii_1;
  4118. return BindingHelper._getMonitoredObjectData(po_1);
  4119. });
  4120. }
  4121. else {
  4122. mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  4123. }
  4124. var m = mod;
  4125. var bindingInfos = mod.boundProperties.getOrAddWithFactory(propIdStr, function (k) {
  4126. m.boundPropertiesMask |= propId;
  4127. return new Array();
  4128. });
  4129. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  4130. if (!bi) {
  4131. bindingInfos.push(new BindingInfo(binding, i, (i + 1) === properties.length));
  4132. }
  4133. ownerMod = mod;
  4134. ownerInterPropId = propId;
  4135. propertyOwner = propertyOwner[propName];
  4136. };
  4137. for (var i = 0; i < properties.length; i++) {
  4138. _loop_1(i);
  4139. }
  4140. };
  4141. BindingHelper.unregisterDataSource = function (dataSource, binding, level) {
  4142. var properties = binding.propertyPathName.split(".");
  4143. var propertyOwner = dataSource;
  4144. var mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  4145. for (var i = 0; i < properties.length; i++) {
  4146. var propName = properties[i];
  4147. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  4148. var propIdStr = propId.toString();
  4149. if (i >= level) {
  4150. mod = BindingHelper._unregisterBinding(mod, propId, binding);
  4151. }
  4152. else {
  4153. mod = mod.monitoredIntermediateProperties.get(propIdStr);
  4154. }
  4155. propertyOwner = propertyOwner[propName];
  4156. }
  4157. };
  4158. BindingHelper._unregisterBinding = function (mod, propertyID, binding) {
  4159. var propertyIDStr = propertyID.toString();
  4160. var res = null;
  4161. // Check if the property is registered as an intermediate and remove it
  4162. if ((mod.monitoredIntermediateMask & propertyID) !== 0) {
  4163. res = mod.monitoredIntermediateProperties.get(propertyIDStr);
  4164. mod.monitoredIntermediateProperties.remove(propertyIDStr);
  4165. // Update the mask
  4166. mod.monitoredIntermediateMask &= ~propertyID;
  4167. }
  4168. // Check if the property is registered as a final property and remove it
  4169. if ((mod.boundPropertiesMask & propertyID) !== 0) {
  4170. var bindingInfos = mod.boundProperties.get(propertyIDStr);
  4171. // Find the binding and remove it
  4172. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  4173. if (bi) {
  4174. var bii = bindingInfos.indexOf(bi);
  4175. bindingInfos.splice(bii, 1);
  4176. }
  4177. // If the array is empty, update the mask
  4178. if (bindingInfos.length === 0) {
  4179. mod.boundPropertiesMask &= ~propertyID;
  4180. }
  4181. }
  4182. // Check if the MOD is empty and unregister the observer and remove it from the list of MODs
  4183. if (mod.boundPropertiesMask === 0 && mod.monitoredIntermediateMask === 0) {
  4184. // Unregister the observer on Property Change
  4185. mod.monitoredObject.propertyChanged.remove(mod.observer);
  4186. // Remove the MOD from the dic
  4187. var objectId = BindingHelper._getObjectId(mod.monitoredObject);
  4188. BindingHelper._monitoredObjects.remove(objectId);
  4189. }
  4190. return res;
  4191. };
  4192. BindingHelper._getMonitoredObjectData = function (object) {
  4193. var objectId = BindingHelper._getObjectId(object);
  4194. var mod = BindingHelper._monitoredObjects.getOrAddWithFactory(objectId, function (k) { return new MonitoredObjectData(object); });
  4195. return mod;
  4196. };
  4197. BindingHelper._getObjectId = function (obj) {
  4198. var id = obj["__bindingHelperObjectId__"];
  4199. if (id == null) {
  4200. id = BABYLON.Tools.RandomId();
  4201. obj["__bindingHelperObjectId__"] = id;
  4202. return id;
  4203. }
  4204. return id;
  4205. };
  4206. BindingHelper._getObjectTypePropertyIDs = function (obj) {
  4207. var fullName = BABYLON.Tools.getFullClassName(obj);
  4208. if (!fullName) {
  4209. throw Error("Types involved in Data Binding must be decorated with the @className decorator");
  4210. }
  4211. var d = BindingHelper._propertiesID.getOrAddWithFactory(fullName, function () { return new BABYLON.StringDictionary(); });
  4212. return d;
  4213. };
  4214. BindingHelper._getPropertyID = function (object, propName) {
  4215. var otd = BindingHelper._getObjectTypePropertyIDs(object);
  4216. // Make sure we have a WatchedPropertyData for this property of this object type. This will contains the flagIg of the watched property.
  4217. // We use this flagId to flag for each watched instance which properties are watched, as final or intermediate and which directions are used
  4218. var propData = otd.getOrAddWithFactory(propName, function (k) { return 1 << otd.count; });
  4219. return propData;
  4220. };
  4221. return BindingHelper;
  4222. }());
  4223. BindingHelper._propertiesID = new BABYLON.StringDictionary();
  4224. BindingHelper._monitoredObjects = new BABYLON.StringDictionary();
  4225. var SmartPropertyPrim = SmartPropertyPrim_1 = (function (_super) {
  4226. __extends(SmartPropertyPrim, _super);
  4227. function SmartPropertyPrim() {
  4228. var _this = _super.call(this) || this;
  4229. _this._flags = 0;
  4230. _this._uid = null;
  4231. _this._modelKey = null;
  4232. _this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  4233. _this._boundingInfo = new BABYLON.BoundingInfo2D();
  4234. _this.animations = new Array();
  4235. return _this;
  4236. }
  4237. /**
  4238. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  4239. * @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.
  4240. */
  4241. SmartPropertyPrim.prototype.dispose = function () {
  4242. if (this.isDisposed) {
  4243. return false;
  4244. }
  4245. _super.prototype.dispose.call(this);
  4246. // Don't set to null, it may upset somebody...
  4247. this.animations.splice(0);
  4248. return true;
  4249. };
  4250. Object.defineProperty(SmartPropertyPrim.prototype, "uid", {
  4251. /**
  4252. * return a unique identifier for the Canvas2D
  4253. */
  4254. get: function () {
  4255. if (!this._uid) {
  4256. this._uid = BABYLON.Tools.RandomId();
  4257. }
  4258. return this._uid;
  4259. },
  4260. enumerable: true,
  4261. configurable: true
  4262. });
  4263. /**
  4264. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  4265. * Look at Sprite2D for more information
  4266. */
  4267. SmartPropertyPrim.prototype.getAnimatables = function () {
  4268. return new Array();
  4269. };
  4270. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  4271. /**
  4272. * Property giving the Model Key associated to the property.
  4273. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  4274. * @returns the model key string.
  4275. */
  4276. get: function () {
  4277. var _this = this;
  4278. // No need to compute it?
  4279. if (!this._isFlagSet(SmartPropertyPrim_1.flagModelDirty) && this._modelKey) {
  4280. return this._modelKey;
  4281. }
  4282. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  4283. var propDic = this.propDic;
  4284. propDic.forEach(function (k, v) {
  4285. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  4286. var propVal = _this[v.name];
  4287. // 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
  4288. if (propVal && propVal.constructor === Array) {
  4289. var firstVal = propVal[0];
  4290. if (!firstVal) {
  4291. propVal = 0;
  4292. }
  4293. else {
  4294. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  4295. }
  4296. }
  4297. var value = "[null]";
  4298. if (propVal != null) {
  4299. if (v.typeLevelCompare) {
  4300. value = BABYLON.Tools.getClassName(propVal);
  4301. }
  4302. else {
  4303. // String Dictionaries' content are too complex, with use a Random GUID to make the model unique
  4304. if (propVal instanceof BABYLON.StringDictionary) {
  4305. value = BABYLON.Tools.RandomId();
  4306. }
  4307. else if (propVal instanceof BABYLON.BaseTexture) {
  4308. value = propVal.uid;
  4309. }
  4310. else {
  4311. value = propVal.toString();
  4312. }
  4313. }
  4314. }
  4315. modelKey += v.name + ":" + value + ";";
  4316. }
  4317. });
  4318. this._clearFlags(SmartPropertyPrim_1.flagModelDirty);
  4319. this._modelKey = modelKey;
  4320. return modelKey;
  4321. },
  4322. enumerable: true,
  4323. configurable: true
  4324. });
  4325. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  4326. /**
  4327. * States if the Primitive is dirty and should be rendered again next time.
  4328. * @returns true is dirty, false otherwise
  4329. */
  4330. get: function () {
  4331. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim_1.flagModelDirty | SmartPropertyPrim_1.flagModelUpdate | SmartPropertyPrim_1.flagPositioningDirty | SmartPropertyPrim_1.flagLayoutDirty);
  4332. },
  4333. enumerable: true,
  4334. configurable: true
  4335. });
  4336. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  4337. this._setFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  4338. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  4339. if (this instanceof BABYLON.Prim2DBase) {
  4340. var curprim = this;
  4341. while (curprim) {
  4342. curprim._setFlags(SmartPropertyPrim_1.flagBoundingInfoDirty);
  4343. if (curprim.isSizeAuto) {
  4344. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  4345. curprim._setFlags(SmartPropertyPrim_1.flagPositioningDirty);
  4346. }
  4347. if (curprim instanceof BABYLON.Group2D) {
  4348. if (curprim.isRenderableGroup) {
  4349. break;
  4350. }
  4351. }
  4352. curprim = curprim.parent;
  4353. }
  4354. }
  4355. };
  4356. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  4357. _super.prototype._handlePropChanged.call(this, curValue, newValue, propName, propInfo, typeLevelCompare);
  4358. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  4359. if (propInfo.dirtyBoundingInfo) {
  4360. this._boundingBoxDirty();
  4361. }
  4362. else if (propInfo.dirtyParentBoundingInfo) {
  4363. var p = this._parent;
  4364. if (p != null) {
  4365. p._boundingBoxDirty();
  4366. }
  4367. }
  4368. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  4369. if (this instanceof BABYLON.Group2D && this._renderableData) {
  4370. this.handleGroupChanged(propInfo);
  4371. }
  4372. // Check for parent layout dirty
  4373. if (this instanceof BABYLON.Prim2DBase) {
  4374. var p = this._parent;
  4375. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  4376. p._setLayoutDirty();
  4377. }
  4378. var that = this;
  4379. if (that.layoutEngine && (that.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  4380. this._setLayoutDirty();
  4381. }
  4382. }
  4383. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  4384. var instanceDirty = false;
  4385. if (typeLevelCompare && curValue != null && newValue != null) {
  4386. var cvProto = curValue.__proto__;
  4387. var nvProto = newValue.__proto__;
  4388. instanceDirty = (cvProto === nvProto);
  4389. }
  4390. // Set the dirty flags
  4391. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  4392. if (!this.isDirty) {
  4393. this._setFlags(SmartPropertyPrim_1.flagModelDirty);
  4394. }
  4395. }
  4396. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  4397. var propMask = propInfo.flagId;
  4398. this.onPrimitivePropertyDirty(propMask);
  4399. }
  4400. };
  4401. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  4402. this.onPrimBecomesDirty();
  4403. this._instanceDirtyFlags |= propFlagId;
  4404. };
  4405. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  4406. };
  4407. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  4408. _super.prototype._resetPropertiesDirty.call(this);
  4409. this._clearFlags(SmartPropertyPrim_1.flagPrimInDirtyList | SmartPropertyPrim_1.flagNeedRefresh);
  4410. };
  4411. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  4412. /**
  4413. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  4414. */
  4415. get: function () {
  4416. if (this._isFlagSet(SmartPropertyPrim_1.flagLevelBoundingInfoDirty)) {
  4417. if (this.updateLevelBoundingInfo()) {
  4418. this._boundingInfo.dirtyWorldAABB();
  4419. this._clearFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  4420. }
  4421. else {
  4422. this._levelBoundingInfo.clear();
  4423. }
  4424. }
  4425. return this._levelBoundingInfo;
  4426. },
  4427. enumerable: true,
  4428. configurable: true
  4429. });
  4430. /**
  4431. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  4432. */
  4433. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  4434. return false;
  4435. };
  4436. /**
  4437. * Property method called when the Primitive becomes dirty
  4438. */
  4439. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  4440. };
  4441. /**
  4442. * Check if a given flag is set
  4443. * @param flag the flag value
  4444. * @return true if set, false otherwise
  4445. */
  4446. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  4447. return (this._flags & flag) !== 0;
  4448. };
  4449. /**
  4450. * Check if all given flags are set
  4451. * @param flags the flags ORed
  4452. * @return true if all the flags are set, false otherwise
  4453. */
  4454. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  4455. return (this._flags & flags) === flags;
  4456. };
  4457. /**
  4458. * Check if at least one flag of the given flags is set
  4459. * @param flags the flags ORed
  4460. * @return true if at least one flag is set, false otherwise
  4461. */
  4462. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  4463. return (this._flags & flags) !== 0;
  4464. };
  4465. /**
  4466. * Clear the given flags
  4467. * @param flags the flags to clear
  4468. */
  4469. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  4470. this._flags &= ~flags;
  4471. };
  4472. /**
  4473. * Set the given flags to true state
  4474. * @param flags the flags ORed to set
  4475. * @return the flags state before this call
  4476. */
  4477. SmartPropertyPrim.prototype._setFlags = function (flags) {
  4478. var cur = this._flags;
  4479. this._flags |= flags;
  4480. return cur;
  4481. };
  4482. /**
  4483. * Change the state of the given flags
  4484. * @param flags the flags ORed to change
  4485. * @param state true to set them, false to clear them
  4486. */
  4487. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  4488. if (state) {
  4489. this._flags |= flags;
  4490. }
  4491. else {
  4492. this._flags &= ~flags;
  4493. }
  4494. };
  4495. return SmartPropertyPrim;
  4496. }(SmartPropertyBase));
  4497. SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT = 0;
  4498. SmartPropertyPrim.flagNoPartOfLayout = 0x0000001; // set if the primitive's position/size must not be computed by Layout Engine
  4499. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  4500. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  4501. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  4502. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  4503. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  4504. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  4505. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  4506. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  4507. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  4508. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  4509. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  4510. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  4511. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  4512. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  4513. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  4514. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  4515. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  4516. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  4517. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  4518. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  4519. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0200000; // set if the layout bounding info is dirty
  4520. SmartPropertyPrim.flagCollisionActor = 0x0400000; // set if the primitive is part of the collision engine
  4521. SmartPropertyPrim.flagModelUpdate = 0x0800000; // set if the primitive's model data is to update
  4522. SmartPropertyPrim = SmartPropertyPrim_1 = __decorate([
  4523. BABYLON.className("SmartPropertyPrim", "BABYLON")
  4524. ], SmartPropertyPrim);
  4525. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  4526. function dependencyProperty(propId, piStore, mode, updateSourceTrigger) {
  4527. if (mode === void 0) { mode = DataBinding.MODE_TWOWAY; }
  4528. if (updateSourceTrigger === void 0) { updateSourceTrigger = DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED; }
  4529. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { bindingMode: mode, bindingUpdateSourceTrigger: updateSourceTrigger });
  4530. }
  4531. BABYLON.dependencyProperty = dependencyProperty;
  4532. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  4533. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  4534. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  4535. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  4536. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_MODEL, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  4537. }
  4538. BABYLON.modelLevelProperty = modelLevelProperty;
  4539. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  4540. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  4541. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  4542. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  4543. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_INSTANCE, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  4544. }
  4545. BABYLON.instanceLevelProperty = instanceLevelProperty;
  4546. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  4547. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  4548. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  4549. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  4550. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  4551. }
  4552. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  4553. var DataBinding_1, SmartPropertyBase_1, SmartPropertyPrim_1;
  4554. })(BABYLON || (BABYLON = {}));
  4555. //# sourceMappingURL=babylon.smartPropertyPrim.js.map
  4556. var __extends = (this && this.__extends) || function (d, b) {
  4557. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4558. function __() { this.constructor = d; }
  4559. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4560. };
  4561. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4562. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4563. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4564. 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;
  4565. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4566. };
  4567. var BABYLON;
  4568. (function (BABYLON) {
  4569. var PrepareRender2DContext = (function () {
  4570. function PrepareRender2DContext() {
  4571. this.forceRefreshPrimitive = false;
  4572. }
  4573. return PrepareRender2DContext;
  4574. }());
  4575. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  4576. var Render2DContext = (function () {
  4577. function Render2DContext(renderMode) {
  4578. this._renderMode = renderMode;
  4579. this.useInstancing = false;
  4580. this.groupInfoPartData = null;
  4581. this.partDataStartIndex = this.partDataEndIndex = null;
  4582. this.instancedBuffers = null;
  4583. }
  4584. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  4585. /**
  4586. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  4587. */
  4588. get: function () {
  4589. return this._renderMode;
  4590. },
  4591. enumerable: true,
  4592. configurable: true
  4593. });
  4594. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  4595. /**
  4596. * The set of primitives to render is opaque.
  4597. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  4598. */
  4599. get: function () {
  4600. return Render2DContext._renderModeOpaque;
  4601. },
  4602. enumerable: true,
  4603. configurable: true
  4604. });
  4605. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  4606. /**
  4607. * The set of primitives to render is using Alpha Test (aka masking).
  4608. * 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.
  4609. */
  4610. get: function () {
  4611. return Render2DContext._renderModeAlphaTest;
  4612. },
  4613. enumerable: true,
  4614. configurable: true
  4615. });
  4616. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  4617. /**
  4618. * The set of primitives to render is transparent.
  4619. * 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.
  4620. */
  4621. get: function () {
  4622. return Render2DContext._renderModeTransparent;
  4623. },
  4624. enumerable: true,
  4625. configurable: true
  4626. });
  4627. return Render2DContext;
  4628. }());
  4629. Render2DContext._renderModeOpaque = 1;
  4630. Render2DContext._renderModeAlphaTest = 2;
  4631. Render2DContext._renderModeTransparent = 3;
  4632. BABYLON.Render2DContext = Render2DContext;
  4633. /**
  4634. * This class store information for the pointerEventObservable Observable.
  4635. * 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.
  4636. */
  4637. var PrimitivePointerInfo = (function () {
  4638. function PrimitivePointerInfo() {
  4639. this.primitivePointerPos = BABYLON.Vector2.Zero();
  4640. this.tilt = BABYLON.Vector2.Zero();
  4641. this.cancelBubble = false;
  4642. }
  4643. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  4644. // 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.
  4645. /**
  4646. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  4647. * Bubbles: yes
  4648. */
  4649. get: function () {
  4650. return PrimitivePointerInfo._pointerOver;
  4651. },
  4652. enumerable: true,
  4653. configurable: true
  4654. });
  4655. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  4656. /**
  4657. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  4658. * Bubbles: no
  4659. */
  4660. get: function () {
  4661. return PrimitivePointerInfo._pointerEnter;
  4662. },
  4663. enumerable: true,
  4664. configurable: true
  4665. });
  4666. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  4667. /**
  4668. * 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.
  4669. * Bubbles: yes
  4670. */
  4671. get: function () {
  4672. return PrimitivePointerInfo._pointerDown;
  4673. },
  4674. enumerable: true,
  4675. configurable: true
  4676. });
  4677. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  4678. /**
  4679. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  4680. * Bubbles: yes
  4681. */
  4682. get: function () {
  4683. return PrimitivePointerInfo._pointerMouseWheel;
  4684. },
  4685. enumerable: true,
  4686. configurable: true
  4687. });
  4688. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  4689. /**
  4690. * 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.
  4691. * Bubbles: yes
  4692. */
  4693. get: function () {
  4694. return PrimitivePointerInfo._pointerMove;
  4695. },
  4696. enumerable: true,
  4697. configurable: true
  4698. });
  4699. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  4700. /**
  4701. * 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.
  4702. * Bubbles: yes
  4703. */
  4704. get: function () {
  4705. return PrimitivePointerInfo._pointerUp;
  4706. },
  4707. enumerable: true,
  4708. configurable: true
  4709. });
  4710. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  4711. /**
  4712. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  4713. * Bubbles: yes
  4714. */
  4715. get: function () {
  4716. return PrimitivePointerInfo._pointerOut;
  4717. },
  4718. enumerable: true,
  4719. configurable: true
  4720. });
  4721. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  4722. /**
  4723. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  4724. * Bubbles: no
  4725. */
  4726. get: function () {
  4727. return PrimitivePointerInfo._pointerLeave;
  4728. },
  4729. enumerable: true,
  4730. configurable: true
  4731. });
  4732. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  4733. /**
  4734. * 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.
  4735. * Bubbles: yes
  4736. */
  4737. get: function () {
  4738. return PrimitivePointerInfo._pointerGotCapture;
  4739. },
  4740. enumerable: true,
  4741. configurable: true
  4742. });
  4743. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  4744. /**
  4745. * This event type is raised after pointer capture is released for a pointer.
  4746. * Bubbles: yes
  4747. */
  4748. get: function () {
  4749. return PrimitivePointerInfo._pointerLostCapture;
  4750. },
  4751. enumerable: true,
  4752. configurable: true
  4753. });
  4754. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  4755. get: function () {
  4756. return PrimitivePointerInfo._mouseWheelPrecision;
  4757. },
  4758. enumerable: true,
  4759. configurable: true
  4760. });
  4761. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  4762. this.relatedTarget = prim;
  4763. this.relatedTargetPointerPos = primPointerPos;
  4764. };
  4765. PrimitivePointerInfo.getEventTypeName = function (mask) {
  4766. switch (mask) {
  4767. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  4768. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  4769. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  4770. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  4771. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  4772. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  4773. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  4774. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  4775. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  4776. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  4777. }
  4778. };
  4779. return PrimitivePointerInfo;
  4780. }());
  4781. PrimitivePointerInfo._pointerOver = 0x0001;
  4782. PrimitivePointerInfo._pointerEnter = 0x0002;
  4783. PrimitivePointerInfo._pointerDown = 0x0004;
  4784. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  4785. PrimitivePointerInfo._pointerMove = 0x0010;
  4786. PrimitivePointerInfo._pointerUp = 0x0020;
  4787. PrimitivePointerInfo._pointerOut = 0x0040;
  4788. PrimitivePointerInfo._pointerLeave = 0x0080;
  4789. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  4790. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  4791. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  4792. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  4793. /**
  4794. * Defines the horizontal and vertical alignment information for a Primitive.
  4795. */
  4796. var PrimitiveAlignment = PrimitiveAlignment_1 = (function () {
  4797. function PrimitiveAlignment(changeCallback) {
  4798. this._changedCallback = changeCallback;
  4799. this._horizontal = PrimitiveAlignment_1.AlignLeft;
  4800. this._vertical = PrimitiveAlignment_1.AlignBottom;
  4801. }
  4802. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  4803. /**
  4804. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  4805. */
  4806. get: function () { return PrimitiveAlignment_1._AlignLeft; },
  4807. enumerable: true,
  4808. configurable: true
  4809. });
  4810. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  4811. /**
  4812. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  4813. */
  4814. get: function () { return PrimitiveAlignment_1._AlignTop; },
  4815. enumerable: true,
  4816. configurable: true
  4817. });
  4818. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  4819. /**
  4820. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  4821. */
  4822. get: function () { return PrimitiveAlignment_1._AlignRight; },
  4823. enumerable: true,
  4824. configurable: true
  4825. });
  4826. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  4827. /**
  4828. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  4829. */
  4830. get: function () { return PrimitiveAlignment_1._AlignBottom; },
  4831. enumerable: true,
  4832. configurable: true
  4833. });
  4834. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  4835. /**
  4836. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  4837. */
  4838. get: function () { return PrimitiveAlignment_1._AlignCenter; },
  4839. enumerable: true,
  4840. configurable: true
  4841. });
  4842. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  4843. /**
  4844. * The content is stretched toward the opposite edges of the Primitive
  4845. */
  4846. get: function () { return PrimitiveAlignment_1._AlignStretch; },
  4847. enumerable: true,
  4848. configurable: true
  4849. });
  4850. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  4851. /**
  4852. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  4853. */
  4854. get: function () {
  4855. return this._horizontal;
  4856. },
  4857. set: function (value) {
  4858. if (this._horizontal === value) {
  4859. return;
  4860. }
  4861. this._horizontal = value;
  4862. this.onChangeCallback();
  4863. },
  4864. enumerable: true,
  4865. configurable: true
  4866. });
  4867. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  4868. /**
  4869. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  4870. */
  4871. get: function () {
  4872. return this._vertical;
  4873. },
  4874. set: function (value) {
  4875. if (this._vertical === value) {
  4876. return;
  4877. }
  4878. this._vertical = value;
  4879. this.onChangeCallback();
  4880. },
  4881. enumerable: true,
  4882. configurable: true
  4883. });
  4884. PrimitiveAlignment.prototype.onChangeCallback = function () {
  4885. if (this._changedCallback) {
  4886. this._changedCallback();
  4887. }
  4888. };
  4889. /**
  4890. * Set the horizontal alignment from a string value.
  4891. * @param text can be either: 'left','right','center','stretch'
  4892. */
  4893. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  4894. var v = text.trim().toLocaleLowerCase();
  4895. switch (v) {
  4896. case "left":
  4897. this.horizontal = PrimitiveAlignment_1.AlignLeft;
  4898. return;
  4899. case "right":
  4900. this.horizontal = PrimitiveAlignment_1.AlignRight;
  4901. return;
  4902. case "center":
  4903. this.horizontal = PrimitiveAlignment_1.AlignCenter;
  4904. return;
  4905. case "stretch":
  4906. this.horizontal = PrimitiveAlignment_1.AlignStretch;
  4907. return;
  4908. }
  4909. };
  4910. /**
  4911. * Set the vertical alignment from a string value.
  4912. * @param text can be either: 'top','bottom','center','stretch'
  4913. */
  4914. PrimitiveAlignment.prototype.setVertical = function (text) {
  4915. var v = text.trim().toLocaleLowerCase();
  4916. switch (v) {
  4917. case "top":
  4918. this.vertical = PrimitiveAlignment_1.AlignTop;
  4919. return;
  4920. case "bottom":
  4921. this.vertical = PrimitiveAlignment_1.AlignBottom;
  4922. return;
  4923. case "center":
  4924. this.vertical = PrimitiveAlignment_1.AlignCenter;
  4925. return;
  4926. case "stretch":
  4927. this.vertical = PrimitiveAlignment_1.AlignStretch;
  4928. return;
  4929. }
  4930. };
  4931. /**
  4932. * Set the horizontal and or vertical alignments from a string value.
  4933. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  4934. */
  4935. PrimitiveAlignment.prototype.fromString = function (value) {
  4936. var m = value.trim().split(",");
  4937. if (m.length === 1) {
  4938. this.setHorizontal(m[0]);
  4939. this.setVertical(m[0]);
  4940. }
  4941. else {
  4942. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  4943. var v = m_1[_i];
  4944. v = v.toLocaleLowerCase().trim();
  4945. // Horizontal
  4946. var i = v.indexOf("h:");
  4947. if (i === -1) {
  4948. i = v.indexOf("horizontal:");
  4949. }
  4950. if (i !== -1) {
  4951. v = v.substr(v.indexOf(":") + 1);
  4952. this.setHorizontal(v);
  4953. continue;
  4954. }
  4955. // Vertical
  4956. i = v.indexOf("v:");
  4957. if (i === -1) {
  4958. i = v.indexOf("vertical:");
  4959. }
  4960. if (i !== -1) {
  4961. v = v.substr(v.indexOf(":") + 1);
  4962. this.setVertical(v);
  4963. continue;
  4964. }
  4965. }
  4966. }
  4967. };
  4968. PrimitiveAlignment.prototype.copyFrom = function (pa) {
  4969. this._horizontal = pa._horizontal;
  4970. this._vertical = pa._vertical;
  4971. this.onChangeCallback();
  4972. };
  4973. Object.defineProperty(PrimitiveAlignment.prototype, "isDefault", {
  4974. get: function () {
  4975. return this.horizontal === PrimitiveAlignment_1.AlignLeft && this.vertical === PrimitiveAlignment_1.AlignBottom;
  4976. },
  4977. enumerable: true,
  4978. configurable: true
  4979. });
  4980. return PrimitiveAlignment;
  4981. }());
  4982. PrimitiveAlignment._AlignLeft = 1;
  4983. PrimitiveAlignment._AlignTop = 1; // Same as left
  4984. PrimitiveAlignment._AlignRight = 2;
  4985. PrimitiveAlignment._AlignBottom = 2; // Same as right
  4986. PrimitiveAlignment._AlignCenter = 3;
  4987. PrimitiveAlignment._AlignStretch = 4;
  4988. PrimitiveAlignment = PrimitiveAlignment_1 = __decorate([
  4989. BABYLON.className("PrimitiveAlignment", "BABYLON")
  4990. ], PrimitiveAlignment);
  4991. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  4992. /**
  4993. * Stores information about a Primitive that was intersected
  4994. */
  4995. var PrimitiveIntersectedInfo = (function () {
  4996. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  4997. this.prim = prim;
  4998. this.intersectionLocation = intersectionLocation;
  4999. }
  5000. return PrimitiveIntersectedInfo;
  5001. }());
  5002. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  5003. /**
  5004. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  5005. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  5006. */
  5007. var PrimitiveThickness = PrimitiveThickness_1 = (function () {
  5008. function PrimitiveThickness(parentAccess, changedCallback) {
  5009. this._parentAccess = parentAccess;
  5010. this._changedCallback = changedCallback;
  5011. this._pixels = new Array(4);
  5012. this._percentages = new Array(4);
  5013. this._setType(0, PrimitiveThickness_1.Auto);
  5014. this._setType(1, PrimitiveThickness_1.Auto);
  5015. this._setType(2, PrimitiveThickness_1.Auto);
  5016. this._setType(3, PrimitiveThickness_1.Auto);
  5017. this._pixels[0] = 0;
  5018. this._pixels[1] = 0;
  5019. this._pixels[2] = 0;
  5020. this._pixels[3] = 0;
  5021. }
  5022. /**
  5023. * Set the thickness from a string value
  5024. * @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.
  5025. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5026. */
  5027. PrimitiveThickness.prototype.fromString = function (thickness) {
  5028. this._clear();
  5029. var m = thickness.trim().split(",");
  5030. // Special case, one value to apply to all edges
  5031. if (m.length === 1 && thickness.indexOf(":") === -1) {
  5032. this._setStringValue(m[0], 0, false);
  5033. this._setStringValue(m[0], 1, false);
  5034. this._setStringValue(m[0], 2, false);
  5035. this._setStringValue(m[0], 3, false);
  5036. this.onChangeCallback();
  5037. return;
  5038. }
  5039. var res = false;
  5040. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  5041. var cm = m_2[_i];
  5042. res = this._extractString(cm, false) || res;
  5043. }
  5044. if (!res) {
  5045. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  5046. }
  5047. // Check the margin that weren't set and set them in auto
  5048. if ((this._flags & 0x000F) === 0)
  5049. this._flags |= PrimitiveThickness_1.Pixel << 0;
  5050. if ((this._flags & 0x00F0) === 0)
  5051. this._flags |= PrimitiveThickness_1.Pixel << 4;
  5052. if ((this._flags & 0x0F00) === 0)
  5053. this._flags |= PrimitiveThickness_1.Pixel << 8;
  5054. if ((this._flags & 0xF000) === 0)
  5055. this._flags |= PrimitiveThickness_1.Pixel << 12;
  5056. this.onChangeCallback();
  5057. };
  5058. /**
  5059. * Set the thickness from multiple string
  5060. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5061. * @param top the top thickness to set
  5062. * @param left the left thickness to set
  5063. * @param right the right thickness to set
  5064. * @param bottom the bottom thickness to set
  5065. */
  5066. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  5067. this._clear();
  5068. this._setStringValue(top, 0, false);
  5069. this._setStringValue(left, 1, false);
  5070. this._setStringValue(right, 2, false);
  5071. this._setStringValue(bottom, 3, false);
  5072. this.onChangeCallback();
  5073. return this;
  5074. };
  5075. /**
  5076. * Set the thickness from pixel values
  5077. * @param top the top thickness in pixels to set
  5078. * @param left the left thickness in pixels to set
  5079. * @param right the right thickness in pixels to set
  5080. * @param bottom the bottom thickness in pixels to set
  5081. */
  5082. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  5083. this._clear();
  5084. this._pixels[0] = top;
  5085. this._pixels[1] = left;
  5086. this._pixels[2] = right;
  5087. this._pixels[3] = bottom;
  5088. this.onChangeCallback();
  5089. return this;
  5090. };
  5091. /**
  5092. * Apply the same pixel value to all edges
  5093. * @param margin the value to set, in pixels.
  5094. */
  5095. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  5096. this._clear();
  5097. this._pixels[0] = margin;
  5098. this._pixels[1] = margin;
  5099. this._pixels[2] = margin;
  5100. this._pixels[3] = margin;
  5101. this.onChangeCallback();
  5102. return this;
  5103. };
  5104. PrimitiveThickness.prototype.copyFrom = function (pt) {
  5105. this._clear();
  5106. for (var i = 0; i < 4; i++) {
  5107. this._pixels[i] = pt._pixels[i];
  5108. this._percentages[i] = pt._percentages[i];
  5109. }
  5110. this._flags = pt._flags;
  5111. this.onChangeCallback();
  5112. };
  5113. /**
  5114. * Set all edges in auto
  5115. */
  5116. PrimitiveThickness.prototype.auto = function () {
  5117. this._clear();
  5118. this._flags = (PrimitiveThickness_1.Auto << 0) | (PrimitiveThickness_1.Auto << 4) | (PrimitiveThickness_1.Auto << 8) | (PrimitiveThickness_1.Auto << 12);
  5119. this._pixels[0] = 0;
  5120. this._pixels[1] = 0;
  5121. this._pixels[2] = 0;
  5122. this._pixels[3] = 0;
  5123. this.onChangeCallback();
  5124. return this;
  5125. };
  5126. PrimitiveThickness.prototype._clear = function () {
  5127. this._flags = 0;
  5128. this._pixels[0] = 0;
  5129. this._pixels[1] = 0;
  5130. this._pixels[2] = 0;
  5131. this._pixels[3] = 0;
  5132. this._percentages[0] = null;
  5133. this._percentages[1] = null;
  5134. this._percentages[2] = null;
  5135. this._percentages[3] = null;
  5136. };
  5137. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  5138. var v = value.trim().toLocaleLowerCase();
  5139. if (v.indexOf("top:") === 0) {
  5140. v = v.substr(4).trim();
  5141. return this._setStringValue(v, 0, emitChanged);
  5142. }
  5143. if (v.indexOf("left:") === 0) {
  5144. v = v.substr(5).trim();
  5145. return this._setStringValue(v, 1, emitChanged);
  5146. }
  5147. if (v.indexOf("right:") === 0) {
  5148. v = v.substr(6).trim();
  5149. return this._setStringValue(v, 2, emitChanged);
  5150. }
  5151. if (v.indexOf("bottom:") === 0) {
  5152. v = v.substr(7).trim();
  5153. return this._setStringValue(v, 3, emitChanged);
  5154. }
  5155. return false;
  5156. };
  5157. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  5158. // Check for auto
  5159. var v = value.trim().toLocaleLowerCase();
  5160. if (v === "auto") {
  5161. if (this._isType(index, PrimitiveThickness_1.Auto)) {
  5162. return true;
  5163. }
  5164. this._setType(index, PrimitiveThickness_1.Auto);
  5165. this._pixels[index] = 0;
  5166. if (emitChanged) {
  5167. this.onChangeCallback();
  5168. }
  5169. }
  5170. else if (v === "inherit") {
  5171. if (this._isType(index, PrimitiveThickness_1.Inherit)) {
  5172. return true;
  5173. }
  5174. this._setType(index, PrimitiveThickness_1.Inherit);
  5175. this._pixels[index] = null;
  5176. if (emitChanged) {
  5177. this.onChangeCallback();
  5178. }
  5179. }
  5180. else {
  5181. var pI = v.indexOf("%");
  5182. // Check for percentage
  5183. if (pI !== -1) {
  5184. var n_1 = v.substr(0, pI);
  5185. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  5186. if (this._isType(index, PrimitiveThickness_1.Percentage) && (this._percentages[index] === number_1)) {
  5187. return true;
  5188. }
  5189. this._setType(index, PrimitiveThickness_1.Percentage);
  5190. if (isNaN(number_1)) {
  5191. return false;
  5192. }
  5193. this._percentages[index] = number_1;
  5194. if (emitChanged) {
  5195. this.onChangeCallback();
  5196. }
  5197. return true;
  5198. }
  5199. // Check for pixel
  5200. var n = void 0;
  5201. pI = v.indexOf("px");
  5202. if (pI !== -1) {
  5203. n = v.substr(0, pI).trim();
  5204. }
  5205. else {
  5206. n = v;
  5207. }
  5208. var number = Number(n);
  5209. if (this._isType(index, PrimitiveThickness_1.Pixel) && (this._pixels[index] === number)) {
  5210. return true;
  5211. }
  5212. if (isNaN(number)) {
  5213. return false;
  5214. }
  5215. this._pixels[index] = number;
  5216. this._setType(index, PrimitiveThickness_1.Pixel);
  5217. if (emitChanged) {
  5218. this.onChangeCallback();
  5219. }
  5220. return true;
  5221. }
  5222. };
  5223. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  5224. // 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
  5225. value = Math.round(value);
  5226. if (this._isType(index, PrimitiveThickness_1.Pixel) && this._pixels[index] === value) {
  5227. return;
  5228. }
  5229. this._setType(index, PrimitiveThickness_1.Pixel);
  5230. this._pixels[index] = value;
  5231. if (emitChanged) {
  5232. this.onChangeCallback();
  5233. }
  5234. };
  5235. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  5236. // Clip Value to bounds
  5237. value = Math.min(1, value);
  5238. value = Math.max(0, value);
  5239. value = Math.round(value * 100) / 100; // 0.01 precision
  5240. if (this._isType(index, PrimitiveThickness_1.Percentage) && this._percentages[index] === value) {
  5241. return;
  5242. }
  5243. this._setType(index, PrimitiveThickness_1.Percentage);
  5244. this._percentages[index] = value;
  5245. if (emitChanged) {
  5246. this.onChangeCallback();
  5247. }
  5248. };
  5249. PrimitiveThickness.prototype._getStringValue = function (index) {
  5250. var f = (this._flags >> (index * 4)) & 0xF;
  5251. switch (f) {
  5252. case PrimitiveThickness_1.Auto:
  5253. return "auto";
  5254. case PrimitiveThickness_1.Pixel:
  5255. return this._pixels[index] + "px";
  5256. case PrimitiveThickness_1.Percentage:
  5257. return this._percentages[index] * 100 + "%";
  5258. case PrimitiveThickness_1.Inherit:
  5259. return "inherit";
  5260. }
  5261. return "";
  5262. };
  5263. PrimitiveThickness.prototype._isType = function (index, type) {
  5264. var f = (this._flags >> (index * 4)) & 0xF;
  5265. return f === type;
  5266. };
  5267. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  5268. var t = (this._flags >> (index * 4)) & 0xF;
  5269. if (processInherit && (t === PrimitiveThickness_1.Inherit)) {
  5270. var p = this._parentAccess();
  5271. if (p) {
  5272. return p._getType(index, true);
  5273. }
  5274. return PrimitiveThickness_1.Auto;
  5275. }
  5276. return t;
  5277. };
  5278. PrimitiveThickness.prototype._setType = function (index, type) {
  5279. this._flags &= ~(0xF << (index * 4));
  5280. this._flags |= type << (index * 4);
  5281. };
  5282. PrimitiveThickness.prototype.setTop = function (value) {
  5283. if (typeof value === "string") {
  5284. this._setStringValue(value, 0, true);
  5285. }
  5286. else {
  5287. this.topPixels = value;
  5288. }
  5289. };
  5290. PrimitiveThickness.prototype.setLeft = function (value) {
  5291. if (typeof value === "string") {
  5292. this._setStringValue(value, 1, true);
  5293. }
  5294. else {
  5295. this.leftPixels = value;
  5296. }
  5297. };
  5298. PrimitiveThickness.prototype.setRight = function (value) {
  5299. if (typeof value === "string") {
  5300. this._setStringValue(value, 2, true);
  5301. }
  5302. else {
  5303. this.rightPixels = value;
  5304. }
  5305. };
  5306. PrimitiveThickness.prototype.setBottom = function (value) {
  5307. if (typeof value === "string") {
  5308. this._setStringValue(value, 3, true);
  5309. }
  5310. else {
  5311. this.bottomPixels = value;
  5312. }
  5313. };
  5314. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  5315. /**
  5316. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5317. */
  5318. get: function () {
  5319. return this._getStringValue(0);
  5320. },
  5321. set: function (value) {
  5322. this._setStringValue(value, 0, true);
  5323. },
  5324. enumerable: true,
  5325. configurable: true
  5326. });
  5327. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  5328. /**
  5329. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5330. */
  5331. get: function () {
  5332. return this._getStringValue(1);
  5333. },
  5334. set: function (value) {
  5335. this._setStringValue(value, 1, true);
  5336. },
  5337. enumerable: true,
  5338. configurable: true
  5339. });
  5340. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  5341. /**
  5342. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5343. */
  5344. get: function () {
  5345. return this._getStringValue(2);
  5346. },
  5347. set: function (value) {
  5348. this._setStringValue(value, 2, true);
  5349. },
  5350. enumerable: true,
  5351. configurable: true
  5352. });
  5353. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  5354. /**
  5355. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5356. */
  5357. get: function () {
  5358. return this._getStringValue(3);
  5359. },
  5360. set: function (value) {
  5361. this._setStringValue(value, 3, true);
  5362. },
  5363. enumerable: true,
  5364. configurable: true
  5365. });
  5366. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  5367. /**
  5368. * Get/set the top thickness in pixel.
  5369. */
  5370. get: function () {
  5371. return this._pixels[0];
  5372. },
  5373. set: function (value) {
  5374. this._setPixels(value, 0, true);
  5375. },
  5376. enumerable: true,
  5377. configurable: true
  5378. });
  5379. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  5380. /**
  5381. * Get/set the left thickness in pixel.
  5382. */
  5383. get: function () {
  5384. return this._pixels[1];
  5385. },
  5386. set: function (value) {
  5387. this._setPixels(value, 1, true);
  5388. },
  5389. enumerable: true,
  5390. configurable: true
  5391. });
  5392. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  5393. /**
  5394. * Get/set the right thickness in pixel.
  5395. */
  5396. get: function () {
  5397. return this._pixels[2];
  5398. },
  5399. set: function (value) {
  5400. this._setPixels(value, 2, true);
  5401. },
  5402. enumerable: true,
  5403. configurable: true
  5404. });
  5405. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  5406. /**
  5407. * Get/set the bottom thickness in pixel.
  5408. */
  5409. get: function () {
  5410. return this._pixels[3];
  5411. },
  5412. set: function (value) {
  5413. this._setPixels(value, 3, true);
  5414. },
  5415. enumerable: true,
  5416. configurable: true
  5417. });
  5418. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  5419. /**
  5420. * Get/set the top thickness in percentage.
  5421. * The get will return a valid value only if the edge type is percentage.
  5422. * The Set will change the edge mode if needed
  5423. */
  5424. get: function () {
  5425. return this._percentages[0];
  5426. },
  5427. set: function (value) {
  5428. this._setPercentage(value, 0, true);
  5429. },
  5430. enumerable: true,
  5431. configurable: true
  5432. });
  5433. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  5434. /**
  5435. * Get/set the left thickness in percentage.
  5436. * The get will return a valid value only if the edge mode is percentage.
  5437. * The Set will change the edge mode if needed
  5438. */
  5439. get: function () {
  5440. return this._percentages[1];
  5441. },
  5442. set: function (value) {
  5443. this._setPercentage(value, 1, true);
  5444. },
  5445. enumerable: true,
  5446. configurable: true
  5447. });
  5448. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  5449. /**
  5450. * Get/set the right thickness in percentage.
  5451. * The get will return a valid value only if the edge mode is percentage.
  5452. * The Set will change the edge mode if needed
  5453. */
  5454. get: function () {
  5455. return this._percentages[2];
  5456. },
  5457. set: function (value) {
  5458. this._setPercentage(value, 2, true);
  5459. },
  5460. enumerable: true,
  5461. configurable: true
  5462. });
  5463. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  5464. /**
  5465. * Get/set the bottom thickness in percentage.
  5466. * The get will return a valid value only if the edge mode is percentage.
  5467. * The Set will change the edge mode if needed
  5468. */
  5469. get: function () {
  5470. return this._percentages[3];
  5471. },
  5472. set: function (value) {
  5473. this._setPercentage(value, 3, true);
  5474. },
  5475. enumerable: true,
  5476. configurable: true
  5477. });
  5478. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  5479. /**
  5480. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  5481. */
  5482. get: function () {
  5483. return this._getType(0, false);
  5484. },
  5485. set: function (mode) {
  5486. this._setType(0, mode);
  5487. },
  5488. enumerable: true,
  5489. configurable: true
  5490. });
  5491. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  5492. /**
  5493. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  5494. */
  5495. get: function () {
  5496. return this._getType(1, false);
  5497. },
  5498. set: function (mode) {
  5499. this._setType(1, mode);
  5500. },
  5501. enumerable: true,
  5502. configurable: true
  5503. });
  5504. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  5505. /**
  5506. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  5507. */
  5508. get: function () {
  5509. return this._getType(2, false);
  5510. },
  5511. set: function (mode) {
  5512. this._setType(2, mode);
  5513. },
  5514. enumerable: true,
  5515. configurable: true
  5516. });
  5517. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  5518. /**
  5519. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  5520. */
  5521. get: function () {
  5522. return this._getType(3, false);
  5523. },
  5524. set: function (mode) {
  5525. this._setType(3, mode);
  5526. },
  5527. enumerable: true,
  5528. configurable: true
  5529. });
  5530. Object.defineProperty(PrimitiveThickness.prototype, "isDefault", {
  5531. get: function () {
  5532. return this._flags === 0x1111;
  5533. },
  5534. enumerable: true,
  5535. configurable: true
  5536. });
  5537. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  5538. var type = this._getType(index, false);
  5539. if (type === PrimitiveThickness_1.Inherit) {
  5540. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  5541. return;
  5542. }
  5543. if (type !== PrimitiveThickness_1.Percentage) {
  5544. return;
  5545. }
  5546. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  5547. this._pixels[index] = pixels;
  5548. if (emitChanged) {
  5549. this.onChangeCallback();
  5550. }
  5551. };
  5552. PrimitiveThickness.prototype.onChangeCallback = function () {
  5553. if (this._changedCallback) {
  5554. this._changedCallback();
  5555. }
  5556. };
  5557. /**
  5558. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  5559. * @param sourceArea the source area where the content must be sized/positioned
  5560. * @param contentSize the content size to position/resize
  5561. * @param alignment the alignment setting
  5562. * @param dstOffset the position of the content, x, y, z, w are left, bottom, right, top
  5563. * @param dstArea the new size of the content
  5564. */
  5565. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, contentScale, dstOffset, dstArea, computeLayoutArea) {
  5566. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  5567. // Fetch some data
  5568. var topType = this._getType(0, true);
  5569. var leftType = this._getType(1, true);
  5570. var rightType = this._getType(2, true);
  5571. var bottomType = this._getType(3, true);
  5572. var hasWidth = contentSize && (contentSize.width != null);
  5573. var hasHeight = contentSize && (contentSize.height != null);
  5574. var sx = contentScale.x;
  5575. var sy = contentScale.y;
  5576. var width = hasWidth ? contentSize.width : 0;
  5577. var height = hasHeight ? contentSize.height : 0;
  5578. var isTopAuto = topType === PrimitiveThickness_1.Auto;
  5579. var isLeftAuto = leftType === PrimitiveThickness_1.Auto;
  5580. var isRightAuto = rightType === PrimitiveThickness_1.Auto;
  5581. var isBottomAuto = bottomType === PrimitiveThickness_1.Auto;
  5582. switch (alignment.horizontal) {
  5583. case PrimitiveAlignment.AlignLeft:
  5584. {
  5585. if (isLeftAuto) {
  5586. dstOffset.x = 0;
  5587. }
  5588. else {
  5589. this._computePixels(1, sourceArea, true);
  5590. dstOffset.x = this.leftPixels;
  5591. }
  5592. dstArea.width = width;
  5593. if (computeLayoutArea) {
  5594. dstArea.width += this.leftPixels;
  5595. }
  5596. dstOffset.z = sourceArea.width - (dstOffset.x + (width * sx));
  5597. break;
  5598. }
  5599. case PrimitiveAlignment.AlignRight:
  5600. {
  5601. if (isRightAuto) {
  5602. dstOffset.x = Math.round(sourceArea.width - (width * sx));
  5603. }
  5604. else {
  5605. this._computePixels(2, sourceArea, true);
  5606. dstOffset.x = Math.round(sourceArea.width - ((width * sx) + this.rightPixels));
  5607. }
  5608. dstArea.width = width;
  5609. if (computeLayoutArea) {
  5610. dstArea.width += this.rightPixels;
  5611. }
  5612. dstOffset.z = this.rightPixels;
  5613. break;
  5614. }
  5615. case PrimitiveAlignment.AlignStretch:
  5616. {
  5617. if (isLeftAuto) {
  5618. dstOffset.x = 0;
  5619. }
  5620. else {
  5621. this._computePixels(1, sourceArea, true);
  5622. dstOffset.x = this.leftPixels;
  5623. }
  5624. var right = 0;
  5625. if (!isRightAuto) {
  5626. this._computePixels(2, sourceArea, true);
  5627. right = this.rightPixels;
  5628. }
  5629. dstArea.width = sourceArea.width - (dstOffset.x + right);
  5630. dstOffset.z = this.rightPixels;
  5631. break;
  5632. }
  5633. case PrimitiveAlignment.AlignCenter:
  5634. {
  5635. if (!isLeftAuto) {
  5636. this._computePixels(1, sourceArea, true);
  5637. }
  5638. if (!isRightAuto) {
  5639. this._computePixels(2, sourceArea, true);
  5640. }
  5641. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  5642. dstOffset.x = Math.round(((sourceArea.width - (width * sx)) / 2) + offset);
  5643. dstArea.width = width;
  5644. dstOffset.z = sourceArea.width - (dstOffset.x + (width * sx));
  5645. break;
  5646. }
  5647. }
  5648. switch (alignment.vertical) {
  5649. case PrimitiveAlignment.AlignTop:
  5650. {
  5651. if (isTopAuto) {
  5652. dstOffset.y = sourceArea.height - (height * sy);
  5653. }
  5654. else {
  5655. this._computePixels(0, sourceArea, true);
  5656. dstOffset.y = Math.round(sourceArea.height - ((height * sy) + this.topPixels));
  5657. }
  5658. dstArea.height = height;
  5659. if (computeLayoutArea) {
  5660. dstArea.height += this.topPixels;
  5661. }
  5662. dstOffset.w = this.topPixels;
  5663. break;
  5664. }
  5665. case PrimitiveAlignment.AlignBottom:
  5666. {
  5667. if (isBottomAuto) {
  5668. dstOffset.y = 0;
  5669. }
  5670. else {
  5671. this._computePixels(3, sourceArea, true);
  5672. dstOffset.y = this.bottomPixels;
  5673. }
  5674. dstArea.height = height;
  5675. if (computeLayoutArea) {
  5676. dstArea.height += this.bottomPixels;
  5677. }
  5678. dstOffset.w = sourceArea.height - (dstOffset.y + (height * sy));
  5679. break;
  5680. }
  5681. case PrimitiveAlignment.AlignStretch:
  5682. {
  5683. if (isBottomAuto) {
  5684. dstOffset.y = 0;
  5685. }
  5686. else {
  5687. this._computePixels(3, sourceArea, true);
  5688. dstOffset.y = this.bottomPixels;
  5689. }
  5690. var top_1 = 0;
  5691. if (!isTopAuto) {
  5692. this._computePixels(0, sourceArea, true);
  5693. top_1 = this.topPixels;
  5694. }
  5695. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  5696. dstOffset.w = this.topPixels;
  5697. break;
  5698. }
  5699. case PrimitiveAlignment.AlignCenter:
  5700. {
  5701. if (!isTopAuto) {
  5702. this._computePixels(0, sourceArea, true);
  5703. }
  5704. if (!isBottomAuto) {
  5705. this._computePixels(3, sourceArea, true);
  5706. }
  5707. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  5708. dstOffset.y = Math.round(((sourceArea.height - (height * sy)) / 2) + offset);
  5709. dstArea.height = height;
  5710. dstOffset.w = sourceArea.height - (dstOffset.y + (height * sy));
  5711. break;
  5712. }
  5713. }
  5714. };
  5715. /**
  5716. * Compute an area and its position considering this thickness properties based on a given source area
  5717. * @param sourceArea the source area
  5718. * @param dstOffset the position of the resulting area
  5719. * @param dstArea the size of the resulting area
  5720. */
  5721. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  5722. this._computePixels(0, sourceArea, true);
  5723. this._computePixels(1, sourceArea, true);
  5724. this._computePixels(2, sourceArea, true);
  5725. this._computePixels(3, sourceArea, true);
  5726. dstOffset.x = this.leftPixels;
  5727. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  5728. dstOffset.y = this.bottomPixels;
  5729. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  5730. dstOffset.z = this.rightPixels;
  5731. dstOffset.w = this.topPixels;
  5732. };
  5733. /**
  5734. * Compute an area considering this thickness properties based on a given source area
  5735. * @param sourceArea the source area
  5736. * @param result the resulting area
  5737. */
  5738. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  5739. this._computePixels(0, sourceArea, true);
  5740. this._computePixels(1, sourceArea, true);
  5741. this._computePixels(2, sourceArea, true);
  5742. this._computePixels(3, sourceArea, true);
  5743. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  5744. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  5745. };
  5746. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  5747. this._computePixels(0, sourceArea, true);
  5748. this._computePixels(1, sourceArea, true);
  5749. this._computePixels(2, sourceArea, true);
  5750. this._computePixels(3, sourceArea, true);
  5751. dstOffset.x = this.leftPixels;
  5752. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  5753. dstOffset.y = this.bottomPixels;
  5754. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  5755. dstOffset.z = this.rightPixels;
  5756. dstOffset.w = this.topPixels;
  5757. };
  5758. return PrimitiveThickness;
  5759. }());
  5760. PrimitiveThickness.Auto = 0x1;
  5761. PrimitiveThickness.Inherit = 0x2;
  5762. PrimitiveThickness.Percentage = 0x4;
  5763. PrimitiveThickness.Pixel = 0x8;
  5764. PrimitiveThickness = PrimitiveThickness_1 = __decorate([
  5765. BABYLON.className("PrimitiveThickness", "BABYLON")
  5766. ], PrimitiveThickness);
  5767. BABYLON.PrimitiveThickness = PrimitiveThickness;
  5768. /**
  5769. * Main class used for the Primitive Intersection API
  5770. */
  5771. var IntersectInfo2D = (function () {
  5772. function IntersectInfo2D() {
  5773. this.findFirstOnly = false;
  5774. this.intersectHidden = false;
  5775. this.pickPosition = BABYLON.Vector2.Zero();
  5776. }
  5777. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  5778. /**
  5779. * true if at least one primitive intersected during the test
  5780. */
  5781. get: function () {
  5782. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  5783. },
  5784. enumerable: true,
  5785. configurable: true
  5786. });
  5787. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  5788. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  5789. var cur = _a[_i];
  5790. if (cur.prim === prim) {
  5791. return cur.intersectionLocation;
  5792. }
  5793. }
  5794. return null;
  5795. };
  5796. // Internals, don't use
  5797. IntersectInfo2D.prototype._exit = function (firstLevel) {
  5798. if (firstLevel) {
  5799. this._globalPickPosition = null;
  5800. }
  5801. };
  5802. return IntersectInfo2D;
  5803. }());
  5804. BABYLON.IntersectInfo2D = IntersectInfo2D;
  5805. var Prim2DBase = Prim2DBase_1 = (function (_super) {
  5806. __extends(Prim2DBase, _super);
  5807. function Prim2DBase(settings) {
  5808. var _this = this;
  5809. // Avoid checking every time if the object exists
  5810. if (settings == null) {
  5811. settings = {};
  5812. }
  5813. // BASE CLASS CALL
  5814. _this = _super.call(this) || this;
  5815. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  5816. var owner;
  5817. var parent;
  5818. if (Prim2DBase_1._isCanvasInit) {
  5819. owner = _this;
  5820. parent = null;
  5821. _this._canvasPreInit(settings);
  5822. }
  5823. else {
  5824. if (settings.parent != null) {
  5825. parent = settings.parent;
  5826. owner = settings.parent.owner;
  5827. if (!owner) {
  5828. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  5829. }
  5830. 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)) {
  5831. 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");
  5832. }
  5833. }
  5834. }
  5835. // Fields initialization
  5836. _this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  5837. _this._size = null; //Size.Zero();
  5838. _this._scale = new BABYLON.Vector2(1, 1);
  5839. _this._actualSize = null;
  5840. _this._boundingSize = BABYLON.Size.Zero();
  5841. _this._layoutArea = BABYLON.Size.Zero();
  5842. _this._layoutAreaPos = null;
  5843. _this._layoutBoundingInfo = null;
  5844. _this._marginOffset = BABYLON.Vector4.Zero();
  5845. _this._paddingOffset = BABYLON.Vector4.Zero();
  5846. _this._parentPaddingOffset = BABYLON.Vector2.Zero();
  5847. _this._parentContentArea = BABYLON.Size.Zero();
  5848. _this._lastAutoSizeArea = BABYLON.Size.Zero();
  5849. _this._contentArea = new BABYLON.Size(null, null);
  5850. _this._pointerEventObservable = new BABYLON.Observable();
  5851. _this._owner = owner;
  5852. _this._parent = null;
  5853. _this._margin = null;
  5854. _this._padding = null;
  5855. _this._marginAlignment = null;
  5856. _this._id = settings.id;
  5857. _this._children = new Array();
  5858. _this._localTransform = new BABYLON.Matrix();
  5859. _this._globalTransform = null;
  5860. _this._invGlobalTransform = null;
  5861. _this._globalTransformProcessStep = 0;
  5862. _this._globalTransformStep = 0;
  5863. _this._renderGroup = null;
  5864. _this._primLinearPosition = 0;
  5865. _this._manualZOrder = null;
  5866. _this._zOrder = 0;
  5867. _this._zMax = 0;
  5868. _this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  5869. _this._actualOpacity = 0;
  5870. _this._actualScale = BABYLON.Vector2.Zero();
  5871. _this._displayDebugAreas = false;
  5872. _this._debugAreaGroup = null;
  5873. _this._primTriArray = null;
  5874. _this._primTriArrayDirty = true;
  5875. _this._levelBoundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  5876. _this._boundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  5877. var isPickable = true;
  5878. var isContainer = true;
  5879. if (settings.isPickable !== undefined) {
  5880. isPickable = settings.isPickable;
  5881. }
  5882. if (settings.isContainer !== undefined) {
  5883. isContainer = settings.isContainer;
  5884. }
  5885. if (settings.dontInheritParentScale) {
  5886. _this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  5887. }
  5888. _this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  5889. if (settings.opacity != null) {
  5890. _this._opacity = settings.opacity;
  5891. }
  5892. else {
  5893. _this._opacity = 1;
  5894. }
  5895. _this._updateRenderMode();
  5896. if (settings.childrenFlatZOrder) {
  5897. _this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  5898. }
  5899. // If the parent is given, initialize the hierarchy/owner related data
  5900. if (parent != null) {
  5901. parent.addChild(_this);
  5902. _this._hierarchyDepth = parent._hierarchyDepth + 1;
  5903. _this._patchHierarchy(parent.owner);
  5904. }
  5905. // If it's a group, detect its own states
  5906. if (_this.owner && _this instanceof BABYLON.Group2D) {
  5907. var group = _this;
  5908. group.detectGroupStates();
  5909. }
  5910. // Time to insert children if some are specified
  5911. if (settings.children != null) {
  5912. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  5913. var child = _a[_i];
  5914. _this.addChild(child);
  5915. // Good time to patch the hierarchy, it won't go very far if there's no need to
  5916. if (_this.owner != null && _this._hierarchyDepth != null) {
  5917. child._patchHierarchy(_this.owner);
  5918. }
  5919. }
  5920. }
  5921. if (settings.zOrder != null) {
  5922. _this.zOrder = settings.zOrder;
  5923. }
  5924. // Set the model related properties
  5925. if (settings.position != null) {
  5926. _this.position = settings.position;
  5927. }
  5928. else if (settings.x != null || settings.y != null) {
  5929. _this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  5930. }
  5931. else {
  5932. _this._position = null;
  5933. }
  5934. _this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  5935. if (settings.scale != null) {
  5936. _this.scale = settings.scale;
  5937. }
  5938. else {
  5939. if (settings.scaleX != null) {
  5940. _this.scaleX = settings.scaleX;
  5941. }
  5942. if (settings.scaleY != null) {
  5943. _this.scaleY = settings.scaleY;
  5944. }
  5945. }
  5946. _this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  5947. _this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  5948. // Layout Engine
  5949. if (settings.layoutEngine != null) {
  5950. if (typeof settings.layoutEngine === "string") {
  5951. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  5952. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  5953. _this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  5954. }
  5955. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  5956. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  5957. }
  5958. else if (name_1.indexOf("verticalstackpanel") === 0) {
  5959. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  5960. }
  5961. }
  5962. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  5963. _this.layoutEngine = settings.layoutEngine;
  5964. }
  5965. }
  5966. // Set the layout/margin stuffs
  5967. if (settings.marginTop) {
  5968. _this.margin.setTop(settings.marginTop);
  5969. }
  5970. if (settings.marginLeft) {
  5971. _this.margin.setLeft(settings.marginLeft);
  5972. }
  5973. if (settings.marginRight) {
  5974. _this.margin.setRight(settings.marginRight);
  5975. }
  5976. if (settings.marginBottom) {
  5977. _this.margin.setBottom(settings.marginBottom);
  5978. }
  5979. if (settings.margin) {
  5980. if (typeof settings.margin === "string") {
  5981. _this.margin.fromString(settings.margin);
  5982. }
  5983. else {
  5984. _this.margin.fromUniformPixels(settings.margin);
  5985. }
  5986. }
  5987. if (settings.marginHAlignment) {
  5988. _this.marginAlignment.horizontal = settings.marginHAlignment;
  5989. }
  5990. if (settings.marginVAlignment) {
  5991. _this.marginAlignment.vertical = settings.marginVAlignment;
  5992. }
  5993. if (settings.marginAlignment) {
  5994. _this.marginAlignment.fromString(settings.marginAlignment);
  5995. }
  5996. if (settings.paddingTop) {
  5997. _this.padding.setTop(settings.paddingTop);
  5998. }
  5999. if (settings.paddingLeft) {
  6000. _this.padding.setLeft(settings.paddingLeft);
  6001. }
  6002. if (settings.paddingRight) {
  6003. _this.padding.setRight(settings.paddingRight);
  6004. }
  6005. if (settings.paddingBottom) {
  6006. _this.padding.setBottom(settings.paddingBottom);
  6007. }
  6008. if (settings.padding) {
  6009. _this.padding.fromString(settings.padding);
  6010. }
  6011. if (settings.layoutData) {
  6012. var p = _this.parent;
  6013. if (p && p.layoutEngine) {
  6014. p.layoutEngine.newChild(_this, settings.layoutData);
  6015. }
  6016. }
  6017. // Dirty layout and positioning
  6018. _this._parentLayoutDirty();
  6019. _this._positioningDirty();
  6020. // Add in the PCM
  6021. if (settings.levelCollision || settings.deepCollision) {
  6022. _this._actorInfo = _this.owner._primitiveCollisionManager._addActor(_this, settings.deepCollision === true);
  6023. _this._setFlags(BABYLON.SmartPropertyPrim.flagCollisionActor);
  6024. }
  6025. else {
  6026. _this._actorInfo = null;
  6027. }
  6028. return _this;
  6029. }
  6030. Object.defineProperty(Prim2DBase.prototype, "intersectWithObservable", {
  6031. /**
  6032. * Return the ChangedDictionary observable of the StringDictionary containing the primitives intersecting with this one
  6033. */
  6034. get: function () {
  6035. if (!this._actorInfo) {
  6036. return null;
  6037. }
  6038. return this._actorInfo.intersectWith.dictionaryChanged;
  6039. },
  6040. enumerable: true,
  6041. configurable: true
  6042. });
  6043. Object.defineProperty(Prim2DBase.prototype, "intersectWith", {
  6044. /**
  6045. * Return the ObservableStringDictionary containing all the primitives intersecting with this one.
  6046. * The key is the primitive uid, the value is the ActorInfo object
  6047. * @returns {}
  6048. */
  6049. get: function () {
  6050. if (!this._actorInfo) {
  6051. return null;
  6052. }
  6053. return this._actorInfo.intersectWith;
  6054. },
  6055. enumerable: true,
  6056. configurable: true
  6057. });
  6058. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  6059. get: function () {
  6060. if (!this._actionManager) {
  6061. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  6062. }
  6063. return this._actionManager;
  6064. },
  6065. enumerable: true,
  6066. configurable: true
  6067. });
  6068. /**
  6069. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  6070. * @param predicate the predicate to test on each parent
  6071. * @return the first primitive where the predicate was successful
  6072. */
  6073. Prim2DBase.prototype.traverseUp = function (predicate) {
  6074. var p = this;
  6075. while (p != null) {
  6076. if (predicate(p)) {
  6077. return p;
  6078. }
  6079. p = p._parent;
  6080. }
  6081. return null;
  6082. };
  6083. Object.defineProperty(Prim2DBase.prototype, "owner", {
  6084. /**
  6085. * Retrieve the owner Canvas2D
  6086. */
  6087. get: function () {
  6088. return this._owner;
  6089. },
  6090. enumerable: true,
  6091. configurable: true
  6092. });
  6093. Object.defineProperty(Prim2DBase.prototype, "parent", {
  6094. /**
  6095. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  6096. */
  6097. get: function () {
  6098. return this._parent;
  6099. },
  6100. enumerable: true,
  6101. configurable: true
  6102. });
  6103. Object.defineProperty(Prim2DBase.prototype, "children", {
  6104. /**
  6105. * The array of direct children primitives
  6106. */
  6107. get: function () {
  6108. return this._children;
  6109. },
  6110. enumerable: true,
  6111. configurable: true
  6112. });
  6113. Object.defineProperty(Prim2DBase.prototype, "id", {
  6114. /**
  6115. * The identifier of this primitive, may not be unique, it's for information purpose only
  6116. */
  6117. get: function () {
  6118. return this._id;
  6119. },
  6120. set: function (value) {
  6121. if (this._id === value) {
  6122. return;
  6123. }
  6124. var oldValue = this._id;
  6125. this.onPropertyChanged("id", oldValue, this._id);
  6126. },
  6127. enumerable: true,
  6128. configurable: true
  6129. });
  6130. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  6131. get: function () {
  6132. if (this._actualPosition != null) {
  6133. return this._actualPosition;
  6134. }
  6135. if (this._position != null) {
  6136. return this._position;
  6137. }
  6138. // At least return 0,0, we can't return null on actualPosition
  6139. return Prim2DBase_1._nullPosition;
  6140. },
  6141. /**
  6142. * DO NOT INVOKE for internal purpose only
  6143. */
  6144. set: function (val) {
  6145. if (!this._actualPosition) {
  6146. this._actualPosition = val.clone();
  6147. }
  6148. else {
  6149. this._actualPosition.copyFrom(val);
  6150. }
  6151. },
  6152. enumerable: true,
  6153. configurable: true
  6154. });
  6155. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  6156. /**
  6157. * Shortcut to actualPosition.x
  6158. */
  6159. get: function () {
  6160. return this.actualPosition.x;
  6161. },
  6162. set: function (val) {
  6163. this._actualPosition.x = val;
  6164. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  6165. },
  6166. enumerable: true,
  6167. configurable: true
  6168. });
  6169. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  6170. /**
  6171. * Shortcut to actualPosition.y
  6172. */
  6173. get: function () {
  6174. return this.actualPosition.y;
  6175. },
  6176. set: function (val) {
  6177. this._actualPosition.y = val;
  6178. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  6179. },
  6180. enumerable: true,
  6181. configurable: true
  6182. });
  6183. Object.defineProperty(Prim2DBase.prototype, "position", {
  6184. /**
  6185. * Position of the primitive, relative to its parent.
  6186. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  6187. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  6188. * Setting this property may have no effect is specific alignment are in effect.
  6189. */
  6190. get: function () {
  6191. if (!this._position) {
  6192. this._position = BABYLON.Vector2.Zero();
  6193. }
  6194. return this._position;
  6195. },
  6196. set: function (value) {
  6197. if (!this._checkPositionChange()) {
  6198. return;
  6199. }
  6200. if (!this._position) {
  6201. this._position = value.clone();
  6202. }
  6203. else {
  6204. this._position.copyFrom(value);
  6205. }
  6206. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  6207. },
  6208. enumerable: true,
  6209. configurable: true
  6210. });
  6211. Object.defineProperty(Prim2DBase.prototype, "x", {
  6212. /**
  6213. * Direct access to the position.x value of the primitive
  6214. * Use this property when you only want to change one component of the position property
  6215. */
  6216. get: function () {
  6217. if (!this._position) {
  6218. return null;
  6219. }
  6220. return this._position.x;
  6221. },
  6222. set: function (value) {
  6223. if (!this._checkPositionChange()) {
  6224. return;
  6225. }
  6226. if (!this._position) {
  6227. this._position = BABYLON.Vector2.Zero();
  6228. }
  6229. if (this._position.x === value) {
  6230. return;
  6231. }
  6232. this._position.x = value;
  6233. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  6234. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  6235. },
  6236. enumerable: true,
  6237. configurable: true
  6238. });
  6239. Object.defineProperty(Prim2DBase.prototype, "y", {
  6240. /**
  6241. * Direct access to the position.y value of the primitive
  6242. * Use this property when you only want to change one component of the position property
  6243. */
  6244. get: function () {
  6245. if (!this._position) {
  6246. return null;
  6247. }
  6248. return this._position.y;
  6249. },
  6250. set: function (value) {
  6251. if (!this._checkPositionChange()) {
  6252. return;
  6253. }
  6254. if (!this._position) {
  6255. this._position = BABYLON.Vector2.Zero();
  6256. }
  6257. if (this._position.y === value) {
  6258. return;
  6259. }
  6260. this._position.y = value;
  6261. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  6262. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  6263. },
  6264. enumerable: true,
  6265. configurable: true
  6266. });
  6267. Object.defineProperty(Prim2DBase.prototype, "size", {
  6268. /**
  6269. * Size of the primitive or its bounding area
  6270. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  6271. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  6272. */
  6273. get: function () {
  6274. return this.internalGetSize();
  6275. },
  6276. set: function (value) {
  6277. this.internalSetSize(value);
  6278. },
  6279. enumerable: true,
  6280. configurable: true
  6281. });
  6282. Prim2DBase.prototype.internalGetSize = function () {
  6283. if (!this._size || this._size.width == null || this._size.height == null) {
  6284. if (Prim2DBase_1.boundinbBoxReentrency) {
  6285. return Prim2DBase_1.nullSize;
  6286. }
  6287. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  6288. return this._boundingSize;
  6289. }
  6290. Prim2DBase_1.boundinbBoxReentrency = true;
  6291. var b = this.boundingInfo;
  6292. Prim2DBase_1.boundinbBoxReentrency = false;
  6293. return this._boundingSize;
  6294. }
  6295. return this._size;
  6296. };
  6297. Prim2DBase.prototype.internalSetSize = function (value) {
  6298. if (!this._size) {
  6299. this._size = (value != null) ? value.clone() : null;
  6300. }
  6301. else {
  6302. this._size.copyFrom(value);
  6303. }
  6304. };
  6305. Object.defineProperty(Prim2DBase.prototype, "width", {
  6306. /**
  6307. * Direct access to the size.width value of the primitive
  6308. * Use this property when you only want to change one component of the size property
  6309. */
  6310. get: function () {
  6311. if (!this.size) {
  6312. return null;
  6313. }
  6314. return this.size.width;
  6315. },
  6316. set: function (value) {
  6317. if (this.size && this.size.width === value) {
  6318. return;
  6319. }
  6320. if (!this.size) {
  6321. this.size = new BABYLON.Size(value, 0);
  6322. }
  6323. else {
  6324. this.size.width = value;
  6325. }
  6326. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  6327. this._positioningDirty();
  6328. },
  6329. enumerable: true,
  6330. configurable: true
  6331. });
  6332. Object.defineProperty(Prim2DBase.prototype, "height", {
  6333. /**
  6334. * Direct access to the size.height value of the primitive
  6335. * Use this property when you only want to change one component of the size property
  6336. */
  6337. get: function () {
  6338. if (!this.size) {
  6339. return null;
  6340. }
  6341. return this.size.height;
  6342. },
  6343. set: function (value) {
  6344. if (this.size && this.size.height === value) {
  6345. return;
  6346. }
  6347. if (!this.size) {
  6348. this.size = new BABYLON.Size(0, value);
  6349. }
  6350. else {
  6351. this.size.height = value;
  6352. }
  6353. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  6354. this._positioningDirty();
  6355. },
  6356. enumerable: true,
  6357. configurable: true
  6358. });
  6359. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  6360. get: function () {
  6361. return this._rotation;
  6362. },
  6363. set: function (value) {
  6364. this._rotation = value;
  6365. },
  6366. enumerable: true,
  6367. configurable: true
  6368. });
  6369. Object.defineProperty(Prim2DBase.prototype, "scale", {
  6370. get: function () {
  6371. return this._scale.x;
  6372. },
  6373. set: function (value) {
  6374. this._scale.x = this._scale.y = value;
  6375. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6376. this._spreadActualScaleDirty();
  6377. },
  6378. enumerable: true,
  6379. configurable: true
  6380. });
  6381. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  6382. /**
  6383. * Return the size of the primitive as it's being rendered into the target.
  6384. * 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.
  6385. * BEWARE: don't use the setter, it's for internal purpose only
  6386. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  6387. */
  6388. get: function () {
  6389. if (this._actualSize) {
  6390. return this._actualSize;
  6391. }
  6392. return this._size;
  6393. },
  6394. set: function (value) {
  6395. if (this._actualSize.equals(value)) {
  6396. return;
  6397. }
  6398. if (!this._actualSize) {
  6399. this._actualSize = value.clone();
  6400. }
  6401. else {
  6402. this._actualSize.copyFrom(value);
  6403. }
  6404. },
  6405. enumerable: true,
  6406. configurable: true
  6407. });
  6408. Object.defineProperty(Prim2DBase.prototype, "actualWidth", {
  6409. /**
  6410. * Shortcut to actualSize.width
  6411. */
  6412. get: function () {
  6413. return this.actualSize.width;
  6414. },
  6415. set: function (val) {
  6416. this._actualSize.width = val;
  6417. this._triggerPropertyChanged(Prim2DBase_1.actualSizeProperty, this._actualSize);
  6418. },
  6419. enumerable: true,
  6420. configurable: true
  6421. });
  6422. Object.defineProperty(Prim2DBase.prototype, "actualHeight", {
  6423. /**
  6424. * Shortcut to actualPosition.height
  6425. */
  6426. get: function () {
  6427. return this.actualSize.height;
  6428. },
  6429. set: function (val) {
  6430. this._actualSize.height = val;
  6431. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualSize);
  6432. },
  6433. enumerable: true,
  6434. configurable: true
  6435. });
  6436. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  6437. get: function () {
  6438. if (this._manualZOrder != null) {
  6439. return this._manualZOrder;
  6440. }
  6441. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  6442. this._updateZOrder();
  6443. }
  6444. return (1 - this._zOrder);
  6445. },
  6446. enumerable: true,
  6447. configurable: true
  6448. });
  6449. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  6450. /**
  6451. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  6452. * The Primitive's size won't be less than specified.
  6453. * The default value depends of the Primitive type
  6454. */
  6455. get: function () {
  6456. return this._minSize;
  6457. },
  6458. set: function (value) {
  6459. if (this._minSize && value && this._minSize.equals(value)) {
  6460. return;
  6461. }
  6462. if (!this._minSize) {
  6463. this._minSize = value.clone();
  6464. }
  6465. else {
  6466. this._minSize.copyFrom(value);
  6467. }
  6468. this._parentLayoutDirty();
  6469. },
  6470. enumerable: true,
  6471. configurable: true
  6472. });
  6473. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  6474. /**
  6475. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  6476. * The Primitive's size won't be more than specified.
  6477. * The default value depends of the Primitive type
  6478. */
  6479. get: function () {
  6480. return this._maxSize;
  6481. },
  6482. set: function (value) {
  6483. if (this._maxSize && value && this._maxSize.equals(value)) {
  6484. return;
  6485. }
  6486. if (!this._maxSize) {
  6487. this._maxSize = value.clone();
  6488. }
  6489. else {
  6490. this._maxSize.copyFrom(value);
  6491. }
  6492. this._parentLayoutDirty();
  6493. },
  6494. enumerable: true,
  6495. configurable: true
  6496. });
  6497. Object.defineProperty(Prim2DBase.prototype, "origin", {
  6498. /**
  6499. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  6500. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  6501. * For instance:
  6502. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  6503. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  6504. * 0,1 means the center is top/left
  6505. * @returns The normalized center.
  6506. */
  6507. get: function () {
  6508. return this._origin;
  6509. },
  6510. set: function (value) {
  6511. if (!this._origin) {
  6512. this._origin = value.clone();
  6513. }
  6514. else {
  6515. this._origin.copyFrom(value);
  6516. }
  6517. },
  6518. enumerable: true,
  6519. configurable: true
  6520. });
  6521. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  6522. get: function () {
  6523. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  6524. },
  6525. set: function (value) {
  6526. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  6527. },
  6528. enumerable: true,
  6529. configurable: true
  6530. });
  6531. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  6532. get: function () {
  6533. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  6534. },
  6535. set: function (value) {
  6536. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  6537. },
  6538. enumerable: true,
  6539. configurable: true
  6540. });
  6541. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  6542. get: function () {
  6543. return this._manualZOrder;
  6544. },
  6545. set: function (value) {
  6546. if (this._manualZOrder === value) {
  6547. return;
  6548. }
  6549. this._manualZOrder = value;
  6550. this.onZOrderChanged();
  6551. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  6552. this._actualZOrderChangedObservable.notifyObservers(value);
  6553. }
  6554. },
  6555. enumerable: true,
  6556. configurable: true
  6557. });
  6558. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  6559. get: function () {
  6560. return this._manualZOrder != null;
  6561. },
  6562. enumerable: true,
  6563. configurable: true
  6564. });
  6565. Object.defineProperty(Prim2DBase.prototype, "margin", {
  6566. get: function () {
  6567. var _this = this;
  6568. if (!this._margin) {
  6569. this._margin = new PrimitiveThickness(function () {
  6570. if (!_this.parent) {
  6571. return null;
  6572. }
  6573. return _this.parent.margin;
  6574. }, function () { return _this._positioningDirty(); });
  6575. }
  6576. return this._margin;
  6577. },
  6578. set: function (value) {
  6579. this.margin.copyFrom(value);
  6580. },
  6581. enumerable: true,
  6582. configurable: true
  6583. });
  6584. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  6585. /**
  6586. * Check for both margin and marginAlignment, return true if at least one of them is specified with a non default value
  6587. */
  6588. get: function () {
  6589. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  6590. },
  6591. enumerable: true,
  6592. configurable: true
  6593. });
  6594. Object.defineProperty(Prim2DBase.prototype, "padding", {
  6595. get: function () {
  6596. var _this = this;
  6597. if (!this._padding) {
  6598. this._padding = new PrimitiveThickness(function () {
  6599. if (!_this.parent) {
  6600. return null;
  6601. }
  6602. return _this.parent.padding;
  6603. }, function () { return _this._positioningDirty(); });
  6604. }
  6605. return this._padding;
  6606. },
  6607. set: function (value) {
  6608. this.padding.copyFrom(value);
  6609. },
  6610. enumerable: true,
  6611. configurable: true
  6612. });
  6613. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  6614. get: function () {
  6615. return this._padding !== null && !this._padding.isDefault;
  6616. },
  6617. enumerable: true,
  6618. configurable: true
  6619. });
  6620. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  6621. get: function () {
  6622. var _this = this;
  6623. if (!this._marginAlignment) {
  6624. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  6625. }
  6626. return this._marginAlignment;
  6627. },
  6628. set: function (value) {
  6629. this.marginAlignment.copyFrom(value);
  6630. },
  6631. enumerable: true,
  6632. configurable: true
  6633. });
  6634. Object.defineProperty(Prim2DBase.prototype, "_hasMarginAlignment", {
  6635. /**
  6636. * Check if there a marginAlignment specified (non null and not default)
  6637. */
  6638. get: function () {
  6639. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  6640. },
  6641. enumerable: true,
  6642. configurable: true
  6643. });
  6644. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  6645. get: function () {
  6646. return this._opacity;
  6647. },
  6648. set: function (value) {
  6649. if (value < 0) {
  6650. value = 0;
  6651. }
  6652. else if (value > 1) {
  6653. value = 1;
  6654. }
  6655. if (this._opacity === value) {
  6656. return;
  6657. }
  6658. this._opacity = value;
  6659. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  6660. this._spreadActualOpacityChanged();
  6661. this._updateRenderMode();
  6662. },
  6663. enumerable: true,
  6664. configurable: true
  6665. });
  6666. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  6667. get: function () {
  6668. return this._scale.x;
  6669. },
  6670. set: function (value) {
  6671. this._scale.x = value;
  6672. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6673. this._spreadActualScaleDirty();
  6674. },
  6675. enumerable: true,
  6676. configurable: true
  6677. });
  6678. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  6679. get: function () {
  6680. return this._scale.y;
  6681. },
  6682. set: function (value) {
  6683. this._scale.y = value;
  6684. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6685. this._spreadActualScaleDirty();
  6686. },
  6687. enumerable: true,
  6688. configurable: true
  6689. });
  6690. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  6691. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  6692. var child = _a[_i];
  6693. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6694. child._spreadActualScaleDirty();
  6695. }
  6696. };
  6697. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  6698. /**
  6699. * 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
  6700. */
  6701. get: function () {
  6702. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  6703. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  6704. var sx = this.scaleX;
  6705. var sy = this.scaleY;
  6706. while (cur) {
  6707. sx *= cur.scaleX;
  6708. sy *= cur.scaleY;
  6709. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  6710. }
  6711. this._actualScale.copyFromFloats(sx, sy);
  6712. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6713. }
  6714. return this._actualScale;
  6715. },
  6716. enumerable: true,
  6717. configurable: true
  6718. });
  6719. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  6720. /**
  6721. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  6722. */
  6723. get: function () {
  6724. return this.actualScale.x;
  6725. },
  6726. enumerable: true,
  6727. configurable: true
  6728. });
  6729. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  6730. /**
  6731. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  6732. */
  6733. get: function () {
  6734. return this.actualScale.y;
  6735. },
  6736. enumerable: true,
  6737. configurable: true
  6738. });
  6739. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  6740. /**
  6741. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  6742. */
  6743. get: function () {
  6744. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  6745. var cur = this.parent;
  6746. var op = this.opacity;
  6747. while (cur) {
  6748. op *= cur.opacity;
  6749. cur = cur.parent;
  6750. }
  6751. this._actualOpacity = op;
  6752. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  6753. }
  6754. return this._actualOpacity;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  6760. /**
  6761. * Get/set the layout engine to use for this primitive.
  6762. * The default layout engine is the CanvasLayoutEngine.
  6763. */
  6764. get: function () {
  6765. if (!this._layoutEngine) {
  6766. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  6767. }
  6768. return this._layoutEngine;
  6769. },
  6770. set: function (value) {
  6771. if (this._layoutEngine === value) {
  6772. return;
  6773. }
  6774. this._changeLayoutEngine(value);
  6775. },
  6776. enumerable: true,
  6777. configurable: true
  6778. });
  6779. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  6780. /**
  6781. * Get/set the layout are of this primitive.
  6782. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  6783. * The setter should only be called by a Layout Engine class.
  6784. */
  6785. get: function () {
  6786. return this._layoutArea;
  6787. },
  6788. set: function (val) {
  6789. if (this._layoutArea.equals(val)) {
  6790. return;
  6791. }
  6792. this._positioningDirty();
  6793. if (this.parent) {
  6794. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  6795. }
  6796. this._layoutArea.copyFrom(val);
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  6802. /**
  6803. * Get/set the layout area position (relative to the parent primitive).
  6804. * The setter should only be called by a Layout Engine class.
  6805. */
  6806. get: function () {
  6807. if (!this._layoutAreaPos) {
  6808. this._layoutAreaPos = BABYLON.Vector2.Zero();
  6809. }
  6810. return this._layoutAreaPos;
  6811. },
  6812. set: function (val) {
  6813. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  6814. return;
  6815. }
  6816. if (this.parent) {
  6817. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  6818. }
  6819. this._positioningDirty();
  6820. if (!this._layoutAreaPos) {
  6821. this._layoutAreaPos = val.clone();
  6822. }
  6823. else {
  6824. this._layoutAreaPos.copyFrom(val);
  6825. }
  6826. },
  6827. enumerable: true,
  6828. configurable: true
  6829. });
  6830. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  6831. /**
  6832. * Define if the Primitive can be subject to intersection test or not (default is true)
  6833. */
  6834. get: function () {
  6835. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  6836. },
  6837. set: function (value) {
  6838. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  6839. },
  6840. enumerable: true,
  6841. configurable: true
  6842. });
  6843. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  6844. /**
  6845. * Define if the Primitive acts as a container or not
  6846. * A container will encapsulate its children for interaction event.
  6847. * If it's not a container events will be process down to children if the primitive is not pickable.
  6848. * Default value is true
  6849. */
  6850. get: function () {
  6851. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  6852. },
  6853. set: function (value) {
  6854. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  6855. },
  6856. enumerable: true,
  6857. configurable: true
  6858. });
  6859. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  6860. /**
  6861. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  6862. */
  6863. get: function () {
  6864. return this._hierarchyDepth;
  6865. },
  6866. enumerable: true,
  6867. configurable: true
  6868. });
  6869. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  6870. /**
  6871. * Retrieve the Group that is responsible to render this primitive
  6872. */
  6873. get: function () {
  6874. return this._renderGroup;
  6875. },
  6876. enumerable: true,
  6877. configurable: true
  6878. });
  6879. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  6880. /**
  6881. * Get the global transformation matrix of the primitive
  6882. */
  6883. get: function () {
  6884. if (this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  6885. this.updateCachedStates(false);
  6886. }
  6887. return this._globalTransform;
  6888. },
  6889. enumerable: true,
  6890. configurable: true
  6891. });
  6892. /**
  6893. * return the global position of the primitive, relative to its canvas
  6894. */
  6895. Prim2DBase.prototype.getGlobalPosition = function () {
  6896. var v = new BABYLON.Vector2(0, 0);
  6897. this.getGlobalPositionByRef(v);
  6898. return v;
  6899. };
  6900. /**
  6901. * return the global position of the primitive, relative to its canvas
  6902. * @param v the valid Vector2 object where the global position will be stored
  6903. */
  6904. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  6905. v.x = this.globalTransform.m[12];
  6906. v.y = this.globalTransform.m[13];
  6907. };
  6908. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  6909. /**
  6910. * Get invert of the global transformation matrix of the primitive
  6911. */
  6912. get: function () {
  6913. this._updateLocalTransform();
  6914. return this._invGlobalTransform;
  6915. },
  6916. enumerable: true,
  6917. configurable: true
  6918. });
  6919. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  6920. /**
  6921. * Get the local transformation of the primitive
  6922. */
  6923. get: function () {
  6924. this._updateLocalTransform();
  6925. return this._localTransform;
  6926. },
  6927. enumerable: true,
  6928. configurable: true
  6929. });
  6930. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  6931. /**
  6932. * Get the boundingInfo associated to the primitive and its children.
  6933. * The value is supposed to be always up to date
  6934. */
  6935. get: function () {
  6936. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  6937. if (this.owner) {
  6938. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  6939. }
  6940. var sizedByContent = this.isSizedByContent;
  6941. if (sizedByContent) {
  6942. this._boundingInfo.clear();
  6943. }
  6944. else {
  6945. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  6946. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  6947. return this._boundingInfo;
  6948. }
  6949. }
  6950. var bi = this._boundingInfo;
  6951. var tps = new BABYLON.BoundingInfo2D();
  6952. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  6953. var curChild = _a[_i];
  6954. var bb = curChild.boundingInfo;
  6955. bb.transformToRef(curChild.localTransform, tps);
  6956. bi.unionToRef(tps, bi);
  6957. }
  6958. // If the size is determined by the content we have to update the contentArea
  6959. // and compute the size considering the padding (if any)
  6960. if (sizedByContent) {
  6961. bi.maxToRef(Prim2DBase_1._bMax);
  6962. this._contentArea.width = Prim2DBase_1._bMax.x;
  6963. this._contentArea.height = Prim2DBase_1._bMax.y;
  6964. if (this._hasPadding) {
  6965. var padding = this.padding;
  6966. var mm = Prim2DBase_1._bMinMax;
  6967. bi.minMaxToRef(mm);
  6968. mm.z += padding.leftPixels + padding.rightPixels;
  6969. mm.w += padding.bottomPixels + padding.topPixels;
  6970. this._paddingOffset.copyFromFloats(padding.leftPixels, padding.bottomPixels, padding.rightPixels, padding.topPixels);
  6971. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(mm.x, mm.z, mm.y, mm.w, bi);
  6972. }
  6973. }
  6974. this._boundingInfo.sizeToRef(Prim2DBase_1._bSize);
  6975. this._boundingSize.copyFromFloats((!this._size || this._size.width == null) ? Math.ceil(Prim2DBase_1._bSize.width) : this._size.width, (!this._size || this._size.height == null) ? Math.ceil(Prim2DBase_1._bSize.height) : this._size.height);
  6976. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  6977. }
  6978. return this._boundingInfo;
  6979. },
  6980. enumerable: true,
  6981. configurable: true
  6982. });
  6983. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  6984. /**
  6985. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  6986. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  6987. */
  6988. get: function () {
  6989. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  6990. if (!this._layoutBoundingInfo) {
  6991. this._layoutBoundingInfo = new BABYLON.BoundingInfo2D();
  6992. }
  6993. if (this.isSizedByContent) {
  6994. this._layoutBoundingInfo.clear();
  6995. }
  6996. else {
  6997. this._layoutBoundingInfo.copyFrom(this.levelBoundingInfo);
  6998. }
  6999. var bi = this._layoutBoundingInfo;
  7000. var tps = new BABYLON.BoundingInfo2D();
  7001. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7002. var curChild = _a[_i];
  7003. var bb = void 0;
  7004. if (curChild._layoutAreaPos) {
  7005. var s = curChild._layoutArea;
  7006. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(0, s.width, 0, s.height, Prim2DBase_1._tpsBB);
  7007. bb = Prim2DBase_1._tpsBB;
  7008. }
  7009. else {
  7010. bb = curChild.boundingInfo;
  7011. }
  7012. bb.transformToRef(curChild.localTransform, tps);
  7013. bi.unionToRef(tps, bi);
  7014. }
  7015. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  7016. }
  7017. return this._layoutBoundingInfo;
  7018. },
  7019. enumerable: true,
  7020. configurable: true
  7021. });
  7022. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  7023. /**
  7024. * Determine if the size is automatically computed or fixed because manually specified.
  7025. * Use the actualSize property to get the final/real size of the primitive
  7026. * @returns true if the size is automatically computed, false if it were manually specified.
  7027. */
  7028. get: function () {
  7029. return this._size == null;
  7030. },
  7031. enumerable: true,
  7032. configurable: true
  7033. });
  7034. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  7035. /**
  7036. * Return true if this prim has an auto size which is set by the children's global bounding box
  7037. */
  7038. get: function () {
  7039. return (this._size == null) && (this._children.length > 0);
  7040. },
  7041. enumerable: true,
  7042. configurable: true
  7043. });
  7044. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  7045. /**
  7046. * Determine if the position is automatically computed or fixed because manually specified.
  7047. * Use the actualPosition property to get the final/real position of the primitive
  7048. * @returns true if the position is automatically computed, false if it were manually specified.
  7049. */
  7050. get: function () {
  7051. return this._position == null;
  7052. },
  7053. enumerable: true,
  7054. configurable: true
  7055. });
  7056. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  7057. /**
  7058. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  7059. */
  7060. get: function () {
  7061. return this._pointerEventObservable;
  7062. },
  7063. enumerable: true,
  7064. configurable: true
  7065. });
  7066. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  7067. get: function () {
  7068. if (!this._actualZOrderChangedObservable) {
  7069. this._actualZOrderChangedObservable = new BABYLON.Observable();
  7070. }
  7071. return this._actualZOrderChangedObservable;
  7072. },
  7073. enumerable: true,
  7074. configurable: true
  7075. });
  7076. Object.defineProperty(Prim2DBase.prototype, "displayDebugAreas", {
  7077. get: function () {
  7078. return this._displayDebugAreas;
  7079. },
  7080. set: function (value) {
  7081. if (this._displayDebugAreas === value) {
  7082. return;
  7083. }
  7084. if (value === false) {
  7085. this._debugAreaGroup.dispose();
  7086. this._debugAreaGroup = null;
  7087. }
  7088. else {
  7089. var layoutFill = "#F0808040"; // Red - Layout area
  7090. var layoutBorder = "#F08080FF";
  7091. var marginFill = "#F0F04040"; // Yellow - Margin area
  7092. var marginBorder = "#F0F040FF";
  7093. var paddingFill = "#F040F040"; // Magenta - Padding Area
  7094. var paddingBorder = "#F040F0FF";
  7095. var contentFill = "#40F0F040"; // Cyan - Content area
  7096. var contentBorder = "#40F0F0FF";
  7097. var s = new BABYLON.Size(10, 10);
  7098. var p = BABYLON.Vector2.Zero();
  7099. this._debugAreaGroup = new BABYLON.Group2D({ dontInheritParentScale: true,
  7100. parent: (this.parent != null) ? this.parent : this, id: "###DEBUG AREA GROUP###", children: [
  7101. new BABYLON.Group2D({
  7102. id: "###Layout Area###", position: p, size: s, children: [
  7103. new BABYLON.Rectangle2D({ id: "###Layout Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: layoutBorder }),
  7104. new BABYLON.Rectangle2D({ id: "###Layout Top###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  7105. new BABYLON.Rectangle2D({ id: "###Layout Left###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  7106. new BABYLON.Rectangle2D({ id: "###Layout Right###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  7107. new BABYLON.Rectangle2D({ id: "###Layout Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill })
  7108. ]
  7109. }),
  7110. new BABYLON.Group2D({
  7111. id: "###Margin Area###", position: p, size: s, children: [
  7112. new BABYLON.Rectangle2D({ id: "###Margin Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: marginBorder }),
  7113. new BABYLON.Rectangle2D({ id: "###Margin Top###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  7114. new BABYLON.Rectangle2D({ id: "###Margin Left###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  7115. new BABYLON.Rectangle2D({ id: "###Margin Right###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  7116. new BABYLON.Rectangle2D({ id: "###Margin Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill })
  7117. ]
  7118. }),
  7119. new BABYLON.Group2D({
  7120. id: "###Padding Area###", position: p, size: s, children: [
  7121. new BABYLON.Rectangle2D({ id: "###Padding Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: paddingBorder }),
  7122. new BABYLON.Rectangle2D({ id: "###Padding Top###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  7123. new BABYLON.Rectangle2D({ id: "###Padding Left###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  7124. new BABYLON.Rectangle2D({ id: "###Padding Right###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  7125. new BABYLON.Rectangle2D({ id: "###Padding Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill })
  7126. ]
  7127. }),
  7128. new BABYLON.Group2D({
  7129. id: "###Content Area###", position: p, size: s, children: [
  7130. new BABYLON.Rectangle2D({ id: "###Content Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: contentBorder }),
  7131. new BABYLON.Rectangle2D({ id: "###Content Top###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  7132. new BABYLON.Rectangle2D({ id: "###Content Left###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  7133. new BABYLON.Rectangle2D({ id: "###Content Right###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  7134. new BABYLON.Rectangle2D({ id: "###Content Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill })
  7135. ]
  7136. })
  7137. ]
  7138. });
  7139. this._debugAreaGroup._setFlags(BABYLON.SmartPropertyPrim.flagNoPartOfLayout);
  7140. this._updateDebugArea();
  7141. }
  7142. this._displayDebugAreas = value;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Prim2DBase.prototype._updateDebugArea = function () {
  7148. var areaNames = ["Layout", "Margin", "Padding", "Content"];
  7149. var areaZones = ["Area", "Frame", "Top", "Left", "Right", "Bottom"];
  7150. var prims = new Array(4);
  7151. // Get all the primitives used to display the areas
  7152. for (var i = 0; i < 4; i++) {
  7153. prims[i] = new Array(6);
  7154. for (var j = 0; j < 6; j++) {
  7155. prims[i][j] = this._debugAreaGroup.findById("###" + areaNames[i] + " " + areaZones[j] + "###");
  7156. if (j > 1) {
  7157. prims[i][j].levelVisible = false;
  7158. }
  7159. }
  7160. }
  7161. // Update the visibility status of layout/margin/padding
  7162. var hasLayout = this._layoutAreaPos != null;
  7163. var hasPos = (this.actualPosition.x !== 0) || (this.actualPosition.y !== 0);
  7164. var hasMargin = this._hasMargin;
  7165. var hasPadding = this._hasPadding;
  7166. prims[0][0].levelVisible = hasLayout;
  7167. prims[1][0].levelVisible = hasMargin;
  7168. prims[2][0].levelVisible = hasPadding;
  7169. prims[3][0].levelVisible = true;
  7170. // Current offset
  7171. var curOffset = BABYLON.Vector2.Zero();
  7172. // Store the area info of the layout area
  7173. var curAreaIndex = 0;
  7174. // Store data about each area
  7175. var areaInfo = new Array(4);
  7176. var storeAreaInfo = function (pos, size) {
  7177. var min = pos.clone();
  7178. var max = pos.clone();
  7179. if (size.width > 0) {
  7180. max.x += size.width;
  7181. }
  7182. if (size.height > 0) {
  7183. max.y += size.height;
  7184. }
  7185. areaInfo[curAreaIndex++] = { off: pos, size: size, min: min, max: max };
  7186. };
  7187. var isCanvas = this instanceof BABYLON.Canvas2D;
  7188. var marginH = this._marginOffset.x + this._marginOffset.z;
  7189. var marginV = this._marginOffset.y + this._marginOffset.w;
  7190. var actualSize = this.actualSize.multiplyByFloats(isCanvas ? 1 : this.scaleX, isCanvas ? 1 : this.scaleY);
  7191. var w = hasLayout ? (this.layoutAreaPos.x + this.layoutArea.width) : (marginH + actualSize.width);
  7192. var h = hasLayout ? (this.layoutAreaPos.y + this.layoutArea.height) : (marginV + actualSize.height);
  7193. var pos = (!hasLayout && !hasMargin && !hasPadding && hasPos) ? this.actualPosition : BABYLON.Vector2.Zero();
  7194. storeAreaInfo(pos, new BABYLON.Size(w, h));
  7195. // Compute the layout related data
  7196. if (hasLayout) {
  7197. var layoutOffset = this.layoutAreaPos.clone();
  7198. storeAreaInfo(layoutOffset, (hasMargin || hasPadding) ? this.layoutArea.clone() : actualSize.clone());
  7199. curOffset = layoutOffset.clone();
  7200. }
  7201. // Compute margin data
  7202. if (hasMargin) {
  7203. var marginOffset = curOffset.clone();
  7204. marginOffset.x += this._marginOffset.x;
  7205. marginOffset.y += this._marginOffset.y;
  7206. var marginArea = actualSize;
  7207. storeAreaInfo(marginOffset, marginArea);
  7208. curOffset = marginOffset.clone();
  7209. }
  7210. if (hasPadding) {
  7211. var contentOffset = curOffset.clone();
  7212. contentOffset.x += this._paddingOffset.x;
  7213. contentOffset.y += this._paddingOffset.y;
  7214. var contentArea = this.contentArea;
  7215. storeAreaInfo(contentOffset, contentArea);
  7216. curOffset = curOffset.add(contentOffset);
  7217. }
  7218. // Helper function that set the pos and size of a given prim
  7219. var setArea = function (i, j, pos, size) {
  7220. prims[i][j].position = pos;
  7221. prims[i][j].size = size;
  7222. };
  7223. var setFullRect = function (i, pos, size) {
  7224. var plist = prims[i];
  7225. plist[2].levelVisible = true;
  7226. plist[3].levelVisible = false;
  7227. plist[4].levelVisible = false;
  7228. plist[5].levelVisible = false;
  7229. setArea(i, 1, pos, size);
  7230. setArea(i, 2, pos, size);
  7231. };
  7232. var setQuadRect = function (i, areaIndex) {
  7233. var plist = prims[i];
  7234. plist[2].levelVisible = true;
  7235. plist[3].levelVisible = true;
  7236. plist[4].levelVisible = true;
  7237. plist[5].levelVisible = true;
  7238. var ca = areaInfo[areaIndex];
  7239. var na = areaInfo[areaIndex + 1];
  7240. var tp = new BABYLON.Vector2(ca.min.x, na.max.y);
  7241. var ts = new BABYLON.Size(ca.size.width, ca.max.y - tp.y);
  7242. var lp = new BABYLON.Vector2(ca.min.x, na.min.y);
  7243. var ls = new BABYLON.Size(na.min.x - ca.min.x, na.max.y - na.min.y);
  7244. var rp = new BABYLON.Vector2(na.max.x, na.min.y);
  7245. var rs = new BABYLON.Size(ca.max.x - na.max.x, na.max.y - na.min.y);
  7246. var bp = new BABYLON.Vector2(ca.min.x, ca.min.y);
  7247. var bs = new BABYLON.Size(ca.size.width, na.min.y - ca.min.y);
  7248. // Frame
  7249. plist[1].position = ca.off;
  7250. plist[1].size = ca.size;
  7251. // Top rect
  7252. plist[2].position = tp;
  7253. plist[2].size = ts;
  7254. // Left rect
  7255. plist[3].position = lp;
  7256. plist[3].size = ls;
  7257. // Right rect
  7258. plist[4].position = rp;
  7259. plist[4].size = rs;
  7260. // Bottom rect
  7261. plist[5].position = bp;
  7262. plist[5].size = bs;
  7263. };
  7264. var areaCount = curAreaIndex;
  7265. curAreaIndex = 0;
  7266. // Available zones
  7267. var availableZones = [false, hasLayout, hasMargin, hasPadding, true];
  7268. for (var k = 1; k < 5; k++) {
  7269. if (availableZones[k]) {
  7270. var ai = areaInfo[curAreaIndex];
  7271. setArea(k - 1, 0, BABYLON.Vector2.Zero(), ai.size);
  7272. // setArea(k-1, 1, Vector2.Zero(), ai.size);
  7273. if (k === 4) {
  7274. setFullRect(k - 1, ai.off, ai.size);
  7275. }
  7276. else {
  7277. setQuadRect(k - 1, curAreaIndex);
  7278. }
  7279. ++curAreaIndex;
  7280. }
  7281. }
  7282. };
  7283. Prim2DBase.prototype.findById = function (id) {
  7284. if (this._id === id) {
  7285. return this;
  7286. }
  7287. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7288. var child = _a[_i];
  7289. var r = child.findById(id);
  7290. if (r != null) {
  7291. return r;
  7292. }
  7293. }
  7294. };
  7295. Prim2DBase.prototype.onZOrderChanged = function () {
  7296. };
  7297. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  7298. return false;
  7299. };
  7300. /**
  7301. * Capture all the Events of the given PointerId for this primitive.
  7302. * Don't forget to call releasePointerEventsCapture when done.
  7303. * @param pointerId the Id of the pointer to capture the events from.
  7304. */
  7305. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  7306. return this.owner._setPointerCapture(pointerId, this);
  7307. };
  7308. /**
  7309. * Release a captured pointer made with setPointerEventCapture.
  7310. * @param pointerId the Id of the pointer to release the capture from.
  7311. */
  7312. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  7313. return this.owner._releasePointerCapture(pointerId, this);
  7314. };
  7315. /**
  7316. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  7317. * @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.
  7318. */
  7319. Prim2DBase.prototype.intersect = function (intersectInfo) {
  7320. if (!intersectInfo) {
  7321. return false;
  7322. }
  7323. // If this is null it means this method is call for the first level, initialize stuffs
  7324. var firstLevel = !intersectInfo._globalPickPosition;
  7325. if (firstLevel) {
  7326. // 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).
  7327. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  7328. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  7329. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  7330. intersectInfo.intersectedPrimitives = new Array();
  7331. intersectInfo.topMostIntersectedPrimitive = null;
  7332. }
  7333. if (!Prim2DBase_1._bypassGroup2DExclusion && this instanceof BABYLON.Group2D && this.isCachedGroup && !this.isRenderableGroup) {
  7334. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7335. intersectInfo._exit(firstLevel);
  7336. return false;
  7337. }
  7338. if (!intersectInfo.intersectHidden && !this.isVisible) {
  7339. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7340. intersectInfo._exit(firstLevel);
  7341. return false;
  7342. }
  7343. var id = this.id;
  7344. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  7345. try {
  7346. Prim2DBase_1._bypassGroup2DExclusion = true;
  7347. var ownerGroup = this.getExternalData("__cachedGroup__");
  7348. return ownerGroup.intersect(intersectInfo);
  7349. }
  7350. finally {
  7351. Prim2DBase_1._bypassGroup2DExclusion = false;
  7352. }
  7353. }
  7354. // 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).
  7355. var isIntersectionTest = false;
  7356. if (this instanceof BABYLON.Group2D) {
  7357. var g = this;
  7358. isIntersectionTest = g.isCachedGroup;
  7359. }
  7360. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  7361. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7362. intersectInfo._exit(firstLevel);
  7363. return false;
  7364. }
  7365. // Fast rejection test with boundingInfo
  7366. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  7367. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7368. intersectInfo._exit(firstLevel);
  7369. return false;
  7370. }
  7371. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  7372. var levelIntersectRes = false;
  7373. if (this.isPickable) {
  7374. levelIntersectRes = this.levelIntersect(intersectInfo);
  7375. if (levelIntersectRes) {
  7376. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  7377. intersectInfo.intersectedPrimitives.push(pii);
  7378. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  7379. intersectInfo.topMostIntersectedPrimitive = pii;
  7380. }
  7381. // If we must stop at the first intersection, we're done, quit!
  7382. if (intersectInfo.findFirstOnly) {
  7383. intersectInfo._exit(firstLevel);
  7384. return true;
  7385. }
  7386. }
  7387. }
  7388. // Recurse to children if needed
  7389. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  7390. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7391. var curChild = _a[_i];
  7392. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  7393. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  7394. continue;
  7395. }
  7396. // Must compute the localPickLocation for the children level
  7397. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  7398. // If we got an intersection with the child and we only need to find the first one, quit!
  7399. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  7400. intersectInfo._exit(firstLevel);
  7401. return true;
  7402. }
  7403. }
  7404. }
  7405. intersectInfo._exit(firstLevel);
  7406. return intersectInfo.isIntersected;
  7407. };
  7408. Prim2DBase.prototype.intersectOtherPrim = function (other) {
  7409. var setA = this.triList;
  7410. var setB = other.triList;
  7411. return BABYLON.Tri2DArray.doesIntersect(setA, setB, other.globalTransform.multiply(this.globalTransform.clone().invert()));
  7412. };
  7413. Object.defineProperty(Prim2DBase.prototype, "triList", {
  7414. get: function () {
  7415. if (this._primTriArrayDirty) {
  7416. this.updateTriArray();
  7417. this._primTriArrayDirty = false;
  7418. }
  7419. return this._primTriArray;
  7420. },
  7421. enumerable: true,
  7422. configurable: true
  7423. });
  7424. // 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
  7425. Prim2DBase.prototype.updateTriArray = function () {
  7426. if (this._primTriArray == null) {
  7427. this._primTriArray = new BABYLON.Tri2DArray(2);
  7428. }
  7429. else {
  7430. this._primTriArray.clear(2);
  7431. }
  7432. var size = this.actualSize;
  7433. var lb = new BABYLON.Vector2(0, 0);
  7434. var rt = new BABYLON.Vector2(size.width, size.height);
  7435. var lt = new BABYLON.Vector2(0, size.height);
  7436. var rb = new BABYLON.Vector2(size.width, 0);
  7437. this._primTriArray.storeTriangle(0, lb, lt, rt);
  7438. this._primTriArray.storeTriangle(1, lb, rt, rb);
  7439. };
  7440. /**
  7441. * Move a child object into a new position regarding its siblings to change its rendering order.
  7442. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  7443. * @param child the object to move
  7444. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  7445. */
  7446. Prim2DBase.prototype.moveChild = function (child, previous) {
  7447. if (child.parent !== this) {
  7448. return false;
  7449. }
  7450. var childIndex = this._children.indexOf(child);
  7451. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  7452. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  7453. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7454. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  7455. }
  7456. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  7457. return true;
  7458. };
  7459. /**
  7460. * Move the given child so it's displayed on the top of all its siblings
  7461. * @param child the primitive to move to the top
  7462. */
  7463. Prim2DBase.prototype.moveChildToTop = function (child) {
  7464. return this.moveChild(child, this._children[this._children.length - 1]);
  7465. };
  7466. /**
  7467. * Move the given child so it's displayed on the bottom of all its siblings
  7468. * @param child the primitive to move to the top
  7469. */
  7470. Prim2DBase.prototype.moveChildToBottom = function (child) {
  7471. return this.moveChild(child, null);
  7472. };
  7473. /**
  7474. * Move this primitive to be at the top among all its sibling
  7475. */
  7476. Prim2DBase.prototype.moveToTop = function () {
  7477. if (this.parent == null) {
  7478. return false;
  7479. }
  7480. return this.parent.moveChildToTop(this);
  7481. };
  7482. /**
  7483. * Move this primitive to be at the bottom among all its sibling
  7484. */
  7485. Prim2DBase.prototype.moveToBottom = function () {
  7486. if (this.parent == null) {
  7487. return false;
  7488. }
  7489. return this.parent.moveChildToBottom(this);
  7490. };
  7491. Prim2DBase.prototype.addChild = function (child) {
  7492. child._parent = this;
  7493. this._boundingBoxDirty();
  7494. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7495. if (flat) {
  7496. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7497. child._setZOrder(this._zOrder, true);
  7498. child._zMax = this._zOrder;
  7499. }
  7500. else {
  7501. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7502. }
  7503. var length = this._children.push(child);
  7504. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  7505. };
  7506. /**
  7507. * Dispose the primitive, remove it from its parent.
  7508. */
  7509. Prim2DBase.prototype.dispose = function () {
  7510. if (!_super.prototype.dispose.call(this)) {
  7511. return false;
  7512. }
  7513. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagCollisionActor)) {
  7514. this.owner._primitiveCollisionManager._removeActor(this);
  7515. this._actorInfo = null;
  7516. }
  7517. if (this._pointerEventObservable) {
  7518. this._pointerEventObservable.clear();
  7519. this._pointerEventObservable = null;
  7520. }
  7521. if (this._actionManager) {
  7522. this._actionManager.dispose();
  7523. this._actionManager = null;
  7524. }
  7525. this.owner.scene.stopAnimation(this);
  7526. // If there's a parent, remove this object from its parent list
  7527. if (this._parent) {
  7528. if (this instanceof BABYLON.Group2D) {
  7529. var g = this;
  7530. if (g.isRenderableGroup) {
  7531. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  7532. if (parentRenderable != null) {
  7533. var l = parentRenderable._renderableData._childrenRenderableGroups;
  7534. var i_1 = l.indexOf(g);
  7535. if (i_1 !== -1) {
  7536. l.splice(i_1, 1);
  7537. }
  7538. }
  7539. }
  7540. }
  7541. var i = this._parent._children.indexOf(this);
  7542. if (i !== undefined) {
  7543. this._parent._children.splice(i, 1);
  7544. }
  7545. this._parent = null;
  7546. }
  7547. // Recurse dispose to children
  7548. if (this._children) {
  7549. while (this._children.length > 0) {
  7550. this._children[this._children.length - 1].dispose();
  7551. }
  7552. }
  7553. return true;
  7554. };
  7555. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  7556. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  7557. this._renderGroup._addPrimToDirtyList(this);
  7558. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  7559. }
  7560. };
  7561. Prim2DBase.prototype._needPrepare = function () {
  7562. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagModelUpdate | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  7563. };
  7564. Prim2DBase.prototype._prepareRender = function (context) {
  7565. this._prepareRenderPre(context);
  7566. this._prepareRenderPost(context);
  7567. };
  7568. Prim2DBase.prototype._prepareRenderPre = function (context) {
  7569. };
  7570. Prim2DBase.prototype._prepareRenderPost = function (context) {
  7571. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  7572. if (this instanceof BABYLON.Group2D) {
  7573. var self = this;
  7574. if (self.isRenderableGroup) {
  7575. return;
  7576. }
  7577. }
  7578. // Check if we need to recurse the prepare to children primitives
  7579. // - must have children
  7580. // - the global transform of this level have changed, or
  7581. // - the visible state of primitive has changed
  7582. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  7583. this.checkPropertiesDirty(Prim2DBase_1.isVisibleProperty.flagId))) {
  7584. this._children.forEach(function (c) {
  7585. // As usual stop the recursion if we meet a renderable group
  7586. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  7587. c._prepareRender(context);
  7588. }
  7589. });
  7590. }
  7591. // Finally reset the dirty flags as we've processed everything
  7592. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  7593. this._instanceDirtyFlags = 0;
  7594. };
  7595. Prim2DBase.prototype._canvasPreInit = function (settings) {
  7596. };
  7597. Prim2DBase.CheckParent = function (parent) {
  7598. //if (!Prim2DBase._isCanvasInit && !parent) {
  7599. // 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)");
  7600. //}
  7601. };
  7602. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  7603. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  7604. var cur = list_1[_i];
  7605. cur.updateCachedStates(recurse);
  7606. }
  7607. };
  7608. Prim2DBase.prototype._parentLayoutDirty = function () {
  7609. if (!this._parent || this._parent.isDisposed) {
  7610. return;
  7611. }
  7612. this._parent._setLayoutDirty();
  7613. };
  7614. Prim2DBase.prototype._setLayoutDirty = function () {
  7615. this.onPrimBecomesDirty();
  7616. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  7617. };
  7618. Prim2DBase.prototype._checkPositionChange = function () {
  7619. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  7620. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  7621. return false;
  7622. }
  7623. return true;
  7624. };
  7625. Prim2DBase.prototype._positioningDirty = function () {
  7626. this.onPrimBecomesDirty();
  7627. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7628. };
  7629. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  7630. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7631. var child = _a[_i];
  7632. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  7633. child._updateRenderMode();
  7634. child.onPrimBecomesDirty();
  7635. child._spreadActualOpacityChanged();
  7636. }
  7637. };
  7638. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  7639. this._layoutEngine = engine;
  7640. };
  7641. Prim2DBase.prototype._updateLocalTransform = function () {
  7642. 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;
  7643. if (this.checkPropertiesDirty(tflags)) {
  7644. if (this.owner) {
  7645. this.owner.addupdateLocalTransformCounter(1);
  7646. }
  7647. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  7648. var local;
  7649. var pos = this._position ? this.position : this.layoutAreaPos;
  7650. if (this._origin.x === 0 && this._origin.y === 0) {
  7651. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0));
  7652. this._localTransform = local;
  7653. }
  7654. else {
  7655. // -Origin offset
  7656. var as = this.actualSize;
  7657. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase_1._t0);
  7658. // -Origin * rotation
  7659. rot.toRotationMatrix(Prim2DBase_1._t1);
  7660. Prim2DBase_1._t0.multiplyToRef(Prim2DBase_1._t1, Prim2DBase_1._t2);
  7661. // -Origin * rotation * scale
  7662. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase_1._t0);
  7663. Prim2DBase_1._t2.multiplyToRef(Prim2DBase_1._t0, Prim2DBase_1._t1);
  7664. // -Origin * rotation * scale * (Origin + Position)
  7665. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x + this._marginOffset.x, (as.height * this._origin.y) + pos.y + this._marginOffset.y, 0, Prim2DBase_1._t2);
  7666. Prim2DBase_1._t1.multiplyToRef(Prim2DBase_1._t2, this._localTransform);
  7667. }
  7668. this.clearPropertiesDirty(tflags);
  7669. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7670. return true;
  7671. }
  7672. return false;
  7673. };
  7674. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  7675. if (this.isDisposed) {
  7676. return;
  7677. }
  7678. this.owner.addCachedGroupRenderCounter(1);
  7679. // Check if the parent is synced
  7680. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  7681. this._parent.updateCachedStates(false);
  7682. }
  7683. // Update Z-Order if needed
  7684. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7685. this._updateZOrder();
  7686. }
  7687. // Update actualSize only if there' not positioning to recompute and the size changed
  7688. // Otherwise positioning will take care of it.
  7689. var sizeDirty = this.checkPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  7690. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  7691. var size = this.size;
  7692. if (size) {
  7693. if (this.size.width != null) {
  7694. this.actualSize.width = this.size.width;
  7695. }
  7696. if (this.size.height != null) {
  7697. this.actualSize.height = this.size.height;
  7698. }
  7699. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  7700. }
  7701. }
  7702. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7703. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7704. // Check for layout update
  7705. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  7706. this.owner.addUpdateLayoutCounter(1);
  7707. this._layoutEngine.updateLayout(this);
  7708. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  7709. }
  7710. var autoContentChanged = false;
  7711. if (this.isSizeAuto) {
  7712. if (!this._lastAutoSizeArea) {
  7713. autoContentChanged = this.actualSize !== null;
  7714. }
  7715. else {
  7716. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  7717. }
  7718. }
  7719. // Check for positioning update
  7720. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  7721. this._updatePositioning();
  7722. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7723. if (sizeDirty) {
  7724. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  7725. }
  7726. positioningComputed = true;
  7727. }
  7728. if (positioningComputed && this._parent) {
  7729. this._parentContentArea.copyFrom(this._parent.contentArea);
  7730. }
  7731. // Check if we must update this prim
  7732. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  7733. this.owner.addUpdateGlobalTransformCounter(1);
  7734. var curVisibleState = this.isVisible;
  7735. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  7736. // Detect a change of visibility
  7737. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  7738. // Get/compute the localTransform
  7739. var localDirty = this._updateLocalTransform();
  7740. var parentPaddingChanged = false;
  7741. var parentPaddingOffset = Prim2DBase_1._v0;
  7742. if (this._parent) {
  7743. parentPaddingOffset = new BABYLON.Vector2(this._parent._paddingOffset.x, this._parent._paddingOffset.y);
  7744. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  7745. }
  7746. // Check if there are changes in the parent that will force us to update the global matrix
  7747. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  7748. // Check if we have to update the globalTransform
  7749. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  7750. var globalTransform = this._parent ? this._parent._globalTransform : null;
  7751. var localTransform = void 0;
  7752. Prim2DBase_1._transMtx.copyFrom(this._localTransform);
  7753. Prim2DBase_1._transMtx.m[12] += parentPaddingOffset.x;
  7754. Prim2DBase_1._transMtx.m[13] += parentPaddingOffset.y;
  7755. localTransform = Prim2DBase_1._transMtx;
  7756. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  7757. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  7758. this._levelBoundingInfo.dirtyWorldAABB();
  7759. this._boundingInfo.dirtyWorldAABB();
  7760. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  7761. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  7762. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7763. }
  7764. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  7765. }
  7766. if (recurse) {
  7767. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7768. var child = _a[_i];
  7769. // Stop the recursion if we meet a renderable group
  7770. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  7771. }
  7772. }
  7773. };
  7774. Prim2DBase.prototype._updatePositioning = function () {
  7775. if (this.owner) {
  7776. this.owner.addUpdatePositioningCounter(1);
  7777. }
  7778. // From this point we assume that the primitive layoutArea is computed and up to date.
  7779. // We know have to :
  7780. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  7781. // 2. Determine the contentArea based on the padding property.
  7782. var isSizeAuto = this.isSizeAuto;
  7783. // 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
  7784. if (!this._hasMarginAlignment && (isSizeAuto || (this.actualSize.width == null || this.actualSize.height == null))) {
  7785. if (isSizeAuto || this.actualSize.width == null) {
  7786. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  7787. }
  7788. if (isSizeAuto || this.actualSize.height == null) {
  7789. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  7790. }
  7791. }
  7792. // Apply margin
  7793. if (this._hasMargin) {
  7794. var contentSize = this.size || this.actualSize;
  7795. this.margin.computeWithAlignment(this.layoutArea, contentSize, this.marginAlignment, this.actualScale, this._marginOffset, Prim2DBase_1._size);
  7796. }
  7797. if (this._hasPadding) {
  7798. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so we resize the primitive itself
  7799. if (isSizeAuto) {
  7800. // Changing the padding has resize the prim, which forces us to recompute margin again
  7801. if (this._hasMargin) {
  7802. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase_1._size, this.marginAlignment, this.actualScale, this._marginOffset, Prim2DBase_1._size);
  7803. }
  7804. }
  7805. else {
  7806. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase_1._icZone, Prim2DBase_1._icArea);
  7807. Prim2DBase_1._icArea.width = Math.max(0, Prim2DBase_1._icArea.width);
  7808. Prim2DBase_1._icArea.height = Math.max(0, Prim2DBase_1._icArea.height);
  7809. this.padding.compute(Prim2DBase_1._icArea, this._paddingOffset, Prim2DBase_1._size);
  7810. this._paddingOffset.x += Prim2DBase_1._icZone.x;
  7811. this._paddingOffset.y += Prim2DBase_1._icZone.y;
  7812. this._paddingOffset.z -= Prim2DBase_1._icZone.z;
  7813. this._paddingOffset.w -= Prim2DBase_1._icZone.w;
  7814. this._contentArea.copyFrom(Prim2DBase_1._size);
  7815. }
  7816. }
  7817. else {
  7818. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase_1._icZone, Prim2DBase_1._icArea);
  7819. Prim2DBase_1._icArea.width = Math.max(0, Prim2DBase_1._icArea.width);
  7820. Prim2DBase_1._icArea.height = Math.max(0, Prim2DBase_1._icArea.height);
  7821. this._paddingOffset.x = Prim2DBase_1._icZone.x;
  7822. this._paddingOffset.y = Prim2DBase_1._icZone.y;
  7823. this._paddingOffset.z = Prim2DBase_1._icZone.z;
  7824. this._paddingOffset.w = Prim2DBase_1._icZone.w;
  7825. this._contentArea.copyFrom(Prim2DBase_1._icArea);
  7826. }
  7827. if (!this._position) {
  7828. var aPos = new BABYLON.Vector2(this.layoutAreaPos.x + this._marginOffset.x, this.layoutAreaPos.y + this._marginOffset.y);
  7829. this.actualPosition = aPos;
  7830. }
  7831. if (isSizeAuto) {
  7832. this._lastAutoSizeArea = this.actualSize;
  7833. }
  7834. if (this.displayDebugAreas) {
  7835. this._updateDebugArea();
  7836. }
  7837. };
  7838. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  7839. /**
  7840. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  7841. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  7842. */
  7843. get: function () {
  7844. if (!this._size || this._size.width == null || this._size.height == null) {
  7845. if (Prim2DBase_1.boundinbBoxReentrency) {
  7846. return Prim2DBase_1.nullSize;
  7847. }
  7848. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  7849. return this._contentArea;
  7850. }
  7851. Prim2DBase_1.boundinbBoxReentrency = true;
  7852. var b = this.boundingInfo;
  7853. Prim2DBase_1.boundinbBoxReentrency = false;
  7854. return this._contentArea;
  7855. }
  7856. else
  7857. // Check for positioning update
  7858. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  7859. this._updatePositioning();
  7860. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7861. }
  7862. return this._contentArea;
  7863. },
  7864. enumerable: true,
  7865. configurable: true
  7866. });
  7867. Prim2DBase.prototype._patchHierarchy = function (owner) {
  7868. this._owner = owner;
  7869. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  7870. if (this._renderGroup != null) {
  7871. return;
  7872. }
  7873. if (this instanceof BABYLON.Group2D) {
  7874. var group = this;
  7875. group.detectGroupStates();
  7876. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  7877. group.owner._registerTrackedNode(this);
  7878. }
  7879. }
  7880. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  7881. if (this._parent) {
  7882. this._parentLayoutDirty();
  7883. }
  7884. // Make sure the prim is in the dirtyList if it should be
  7885. if (this._renderGroup && this.isDirty) {
  7886. var list = this._renderGroup._renderableData._primDirtyList;
  7887. var i = list.indexOf(this);
  7888. if (i === -1) {
  7889. list.push(this);
  7890. }
  7891. }
  7892. // Recurse
  7893. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7894. var child = _a[_i];
  7895. child._hierarchyDepth = this._hierarchyDepth + 1;
  7896. child._patchHierarchy(owner);
  7897. }
  7898. };
  7899. Prim2DBase.prototype._updateZOrder = function () {
  7900. var prevLinPos = this._primLinearPosition;
  7901. var startI = 0;
  7902. var startZ = this._zOrder;
  7903. // 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
  7904. var childrenCount = this._children.length;
  7905. if (this._firstZDirtyIndex > 0) {
  7906. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  7907. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  7908. prevLinPos = prevPrim._primLinearPosition;
  7909. startI = this._firstZDirtyIndex - 1;
  7910. startZ = prevPrim._zOrder;
  7911. }
  7912. }
  7913. var startPos = prevLinPos;
  7914. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  7915. Prim2DBase_1._totalCount = 0;
  7916. for (var i = startI; i < childrenCount; i++) {
  7917. var child = this._children[i];
  7918. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  7919. }
  7920. // Compute the new Z-Order for all the primitives
  7921. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  7922. var zDelta = (this._zMax - startZ) / (Prim2DBase_1._totalCount * (Prim2DBase_1._zRebuildReentrency ? 1 : 1.2));
  7923. // 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.
  7924. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  7925. // 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...
  7926. if (Prim2DBase_1._zRebuildReentrency) {
  7927. var p = this._parent;
  7928. if (p == null) {
  7929. // 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...)
  7930. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  7931. Prim2DBase_1._zRebuildReentrency = false;
  7932. return;
  7933. }
  7934. p._firstZDirtyIndex = 0;
  7935. return p._updateZOrder();
  7936. }
  7937. Prim2DBase_1._zRebuildReentrency = true;
  7938. this._firstZDirtyIndex = 0;
  7939. this._updateZOrder();
  7940. Prim2DBase_1._zRebuildReentrency = false;
  7941. }
  7942. for (var i = startI; i < childrenCount; i++) {
  7943. var child = this._children[i];
  7944. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  7945. }
  7946. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  7947. for (var _i = 0, _a = Prim2DBase_1._zOrderChangedNotifList; _i < _a.length; _i++) {
  7948. var p = _a[_i];
  7949. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  7950. }
  7951. Prim2DBase_1._zOrderChangedNotifList.splice(0);
  7952. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  7953. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7954. };
  7955. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  7956. if (this.isManualZOrder) {
  7957. return prevLinPos;
  7958. }
  7959. this._primLinearPosition = ++prevLinPos;
  7960. Prim2DBase_1._totalCount++;
  7961. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  7962. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  7963. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7964. var child = _a[_i];
  7965. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  7966. }
  7967. }
  7968. return prevLinPos;
  7969. };
  7970. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  7971. if (this.isManualZOrder) {
  7972. return null;
  7973. }
  7974. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  7975. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7976. this._setZOrder(newZ, false);
  7977. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7978. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  7979. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7980. }
  7981. var curZ = newZ;
  7982. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  7983. if (isFlat) {
  7984. if (this._children.length > 0) {
  7985. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  7986. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7987. var child = _a[_i];
  7988. child._updatePrimitiveFlatZOrder(this._zOrder);
  7989. }
  7990. }
  7991. }
  7992. else {
  7993. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  7994. var child = _c[_b];
  7995. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  7996. if (r != null) {
  7997. curZ = r;
  7998. }
  7999. }
  8000. }
  8001. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  8002. return curZ;
  8003. };
  8004. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  8005. if (this.isManualZOrder) {
  8006. return;
  8007. }
  8008. this._setZOrder(newZ, false);
  8009. this._zMax = newZ;
  8010. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  8011. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  8012. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  8013. }
  8014. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8015. var child = _a[_i];
  8016. child._updatePrimitiveFlatZOrder(newZ);
  8017. }
  8018. };
  8019. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  8020. if (newZ !== this._zOrder) {
  8021. this._zOrder = newZ;
  8022. this.onPrimBecomesDirty();
  8023. this.onZOrderChanged();
  8024. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  8025. if (directEmit) {
  8026. this._actualZOrderChangedObservable.notifyObservers(newZ);
  8027. }
  8028. else {
  8029. Prim2DBase_1._zOrderChangedNotifList.push(this);
  8030. }
  8031. }
  8032. }
  8033. };
  8034. Prim2DBase.prototype._updateRenderMode = function () {
  8035. };
  8036. /**
  8037. * This method is used to alter the contentArea of the Primitive before margin is applied.
  8038. * 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.
  8039. * @param primSize the current size of the primitive
  8040. * @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
  8041. * @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!
  8042. */
  8043. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  8044. initialContentArea.copyFrom(primSize);
  8045. initialContentPosition.x = initialContentPosition.y = initialContentPosition.z = initialContentPosition.w = 0;
  8046. };
  8047. /**
  8048. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  8049. * Check the Rectangle2D implementation for a concrete application.
  8050. * @param primSize the current size of the primitive
  8051. * @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!
  8052. */
  8053. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  8054. newPrimSize.copyFrom(primSize);
  8055. };
  8056. return Prim2DBase;
  8057. }(BABYLON.SmartPropertyPrim));
  8058. Prim2DBase.PRIM2DBASE_PROPCOUNT = 25;
  8059. Prim2DBase._bigInt = Math.pow(2, 30);
  8060. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  8061. Prim2DBase.boundinbBoxReentrency = false;
  8062. Prim2DBase.nullSize = BABYLON.Size.Zero();
  8063. Prim2DBase._bMinMax = BABYLON.Vector4.Zero();
  8064. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  8065. Prim2DBase._bSize = BABYLON.Size.Zero();
  8066. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  8067. Prim2DBase._bypassGroup2DExclusion = false;
  8068. Prim2DBase._isCanvasInit = false;
  8069. Prim2DBase._t0 = new BABYLON.Matrix();
  8070. Prim2DBase._t1 = new BABYLON.Matrix();
  8071. Prim2DBase._t2 = new BABYLON.Matrix();
  8072. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  8073. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  8074. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  8075. Prim2DBase._icZone = BABYLON.Vector4.Zero();
  8076. Prim2DBase._icArea = BABYLON.Size.Zero();
  8077. Prim2DBase._size = BABYLON.Size.Zero();
  8078. Prim2DBase._zOrderChangedNotifList = new Array();
  8079. Prim2DBase._zRebuildReentrency = false;
  8080. Prim2DBase._totalCount = 0;
  8081. __decorate([
  8082. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase_1.actualPositionProperty = pi; }, false, false, true)
  8083. ], Prim2DBase.prototype, "actualPosition", null);
  8084. __decorate([
  8085. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 1, function (pi) { return Prim2DBase_1.actualXProperty = pi; }, false, false, true)
  8086. ], Prim2DBase.prototype, "actualX", null);
  8087. __decorate([
  8088. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 2, function (pi) { return Prim2DBase_1.actualYProperty = pi; }, false, false, true)
  8089. ], Prim2DBase.prototype, "actualY", null);
  8090. __decorate([
  8091. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 3, function (pi) { return Prim2DBase_1.positionProperty = pi; }, false, false, true)
  8092. ], Prim2DBase.prototype, "position", null);
  8093. __decorate([
  8094. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 4, function (pi) { return Prim2DBase_1.xProperty = pi; }, false, false, true)
  8095. ], Prim2DBase.prototype, "x", null);
  8096. __decorate([
  8097. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 5, function (pi) { return Prim2DBase_1.yProperty = pi; }, false, false, true)
  8098. ], Prim2DBase.prototype, "y", null);
  8099. __decorate([
  8100. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 6, function (pi) { return Prim2DBase_1.sizeProperty = pi; }, false, true)
  8101. ], Prim2DBase.prototype, "size", null);
  8102. __decorate([
  8103. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 7, function (pi) { return Prim2DBase_1.widthProperty = pi; }, false, true)
  8104. ], Prim2DBase.prototype, "width", null);
  8105. __decorate([
  8106. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 8, function (pi) { return Prim2DBase_1.heightProperty = pi; }, false, true)
  8107. ], Prim2DBase.prototype, "height", null);
  8108. __decorate([
  8109. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 9, function (pi) { return Prim2DBase_1.rotationProperty = pi; }, false, true)
  8110. ], Prim2DBase.prototype, "rotation", null);
  8111. __decorate([
  8112. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 10, function (pi) { return Prim2DBase_1.scaleProperty = pi; }, false, true)
  8113. ], Prim2DBase.prototype, "scale", null);
  8114. __decorate([
  8115. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 11, function (pi) { return Prim2DBase_1.actualSizeProperty = pi; }, false, true)
  8116. ], Prim2DBase.prototype, "actualSize", null);
  8117. __decorate([
  8118. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 12, function (pi) { return Prim2DBase_1.actualWidthProperty = pi; }, false, true)
  8119. ], Prim2DBase.prototype, "actualWidth", null);
  8120. __decorate([
  8121. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 13, function (pi) { return Prim2DBase_1.actualHeightProperty = pi; }, false, true)
  8122. ], Prim2DBase.prototype, "actualHeight", null);
  8123. __decorate([
  8124. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 14, function (pi) { return Prim2DBase_1.originProperty = pi; }, false, true)
  8125. ], Prim2DBase.prototype, "origin", null);
  8126. __decorate([
  8127. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 15, function (pi) { return Prim2DBase_1.levelVisibleProperty = pi; })
  8128. ], Prim2DBase.prototype, "levelVisible", null);
  8129. __decorate([
  8130. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 16, function (pi) { return Prim2DBase_1.isVisibleProperty = pi; })
  8131. ], Prim2DBase.prototype, "isVisible", null);
  8132. __decorate([
  8133. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 17, function (pi) { return Prim2DBase_1.zOrderProperty = pi; })
  8134. ], Prim2DBase.prototype, "zOrder", null);
  8135. __decorate([
  8136. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 18, function (pi) { return Prim2DBase_1.marginProperty = pi; })
  8137. ], Prim2DBase.prototype, "margin", null);
  8138. __decorate([
  8139. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 19, function (pi) { return Prim2DBase_1.paddingProperty = pi; })
  8140. ], Prim2DBase.prototype, "padding", null);
  8141. __decorate([
  8142. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 20, function (pi) { return Prim2DBase_1.marginAlignmentProperty = pi; })
  8143. ], Prim2DBase.prototype, "marginAlignment", null);
  8144. __decorate([
  8145. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 21, function (pi) { return Prim2DBase_1.opacityProperty = pi; })
  8146. ], Prim2DBase.prototype, "opacity", null);
  8147. __decorate([
  8148. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 22, function (pi) { return Prim2DBase_1.scaleXProperty = pi; }, false, true)
  8149. ], Prim2DBase.prototype, "scaleX", null);
  8150. __decorate([
  8151. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 23, function (pi) { return Prim2DBase_1.scaleYProperty = pi; }, false, true)
  8152. ], Prim2DBase.prototype, "scaleY", null);
  8153. __decorate([
  8154. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 24, function (pi) { return Prim2DBase_1.actualScaleProperty = pi; }, false, true)
  8155. ], Prim2DBase.prototype, "actualScale", null);
  8156. Prim2DBase = Prim2DBase_1 = __decorate([
  8157. BABYLON.className("Prim2DBase", "BABYLON")
  8158. ], Prim2DBase);
  8159. BABYLON.Prim2DBase = Prim2DBase;
  8160. var PrimitiveAlignment_1, PrimitiveThickness_1, Prim2DBase_1;
  8161. })(BABYLON || (BABYLON = {}));
  8162. //# sourceMappingURL=babylon.prim2dBase.js.map
  8163. var __extends = (this && this.__extends) || function (d, b) {
  8164. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8165. function __() { this.constructor = d; }
  8166. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  8167. };
  8168. var BABYLON;
  8169. (function (BABYLON) {
  8170. var GroupInstanceInfo = (function () {
  8171. function GroupInstanceInfo(owner, mrc, partCount) {
  8172. this._partCount = partCount;
  8173. this.owner = owner;
  8174. this.modelRenderCache = mrc;
  8175. this.modelRenderCache.addRef();
  8176. this.partIndexFromId = new BABYLON.StringDictionary();
  8177. this._usedShaderCategories = new Array(partCount);
  8178. this._strides = new Array(partCount);
  8179. this._opaqueData = null;
  8180. this._alphaTestData = null;
  8181. this._transparentData = null;
  8182. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  8183. }
  8184. GroupInstanceInfo.prototype.dispose = function () {
  8185. if (this._isDisposed) {
  8186. return false;
  8187. }
  8188. if (this.modelRenderCache) {
  8189. this.modelRenderCache.dispose();
  8190. this.modelRenderCache = null;
  8191. }
  8192. var engine = this.owner.owner.engine;
  8193. if (this._opaqueData) {
  8194. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  8195. this._opaqueData = null;
  8196. }
  8197. if (this._alphaTestData) {
  8198. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  8199. this._alphaTestData = null;
  8200. }
  8201. if (this._transparentData) {
  8202. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  8203. this._transparentData = null;
  8204. }
  8205. this.partIndexFromId = null;
  8206. this._isDisposed = true;
  8207. return true;
  8208. };
  8209. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  8210. get: function () {
  8211. return this._opaqueData != null;
  8212. },
  8213. enumerable: true,
  8214. configurable: true
  8215. });
  8216. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  8217. get: function () {
  8218. return this._alphaTestData != null;
  8219. },
  8220. enumerable: true,
  8221. configurable: true
  8222. });
  8223. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  8224. get: function () {
  8225. return this._transparentData != null;
  8226. },
  8227. enumerable: true,
  8228. configurable: true
  8229. });
  8230. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  8231. get: function () {
  8232. if (!this._opaqueData) {
  8233. this._opaqueData = new Array(this._partCount);
  8234. for (var i = 0; i < this._partCount; i++) {
  8235. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  8236. }
  8237. }
  8238. return this._opaqueData;
  8239. },
  8240. enumerable: true,
  8241. configurable: true
  8242. });
  8243. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  8244. get: function () {
  8245. if (!this._alphaTestData) {
  8246. this._alphaTestData = new Array(this._partCount);
  8247. for (var i = 0; i < this._partCount; i++) {
  8248. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  8249. }
  8250. }
  8251. return this._alphaTestData;
  8252. },
  8253. enumerable: true,
  8254. configurable: true
  8255. });
  8256. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  8257. get: function () {
  8258. if (!this._transparentData) {
  8259. this._transparentData = new Array(this._partCount);
  8260. for (var i = 0; i < this._partCount; i++) {
  8261. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  8262. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  8263. }
  8264. }
  8265. return this._transparentData;
  8266. },
  8267. enumerable: true,
  8268. configurable: true
  8269. });
  8270. GroupInstanceInfo.prototype.sortTransparentData = function () {
  8271. if (!this.transparentOrderDirty) {
  8272. return;
  8273. }
  8274. for (var i = 0; i < this._transparentData.length; i++) {
  8275. var td = this._transparentData[i];
  8276. td._partData.sort();
  8277. }
  8278. this.transparentOrderDirty = false;
  8279. };
  8280. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  8281. get: function () {
  8282. return this._usedShaderCategories;
  8283. },
  8284. enumerable: true,
  8285. configurable: true
  8286. });
  8287. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  8288. get: function () {
  8289. return this._strides;
  8290. },
  8291. enumerable: true,
  8292. configurable: true
  8293. });
  8294. return GroupInstanceInfo;
  8295. }());
  8296. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  8297. var TransparentSegment = (function () {
  8298. function TransparentSegment() {
  8299. this.groupInsanceInfo = null;
  8300. this.startZ = 0;
  8301. this.endZ = 0;
  8302. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  8303. this.endDataIndex = 0;
  8304. this.partBuffers = null;
  8305. }
  8306. TransparentSegment.prototype.dispose = function (engine) {
  8307. if (this.partBuffers) {
  8308. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  8309. this.partBuffers.splice(0);
  8310. this.partBuffers = null;
  8311. }
  8312. };
  8313. return TransparentSegment;
  8314. }());
  8315. BABYLON.TransparentSegment = TransparentSegment;
  8316. var GroupInfoPartData = (function () {
  8317. function GroupInfoPartData(stride) {
  8318. this._partData = null;
  8319. this._partBuffer = null;
  8320. this._partBufferSize = 0;
  8321. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  8322. this._isDisposed = false;
  8323. }
  8324. GroupInfoPartData.prototype.dispose = function (engine) {
  8325. if (this._isDisposed) {
  8326. return false;
  8327. }
  8328. if (this._partBuffer) {
  8329. engine._releaseBuffer(this._partBuffer);
  8330. this._partBuffer = null;
  8331. }
  8332. this._partData = null;
  8333. this._isDisposed = true;
  8334. };
  8335. return GroupInfoPartData;
  8336. }());
  8337. BABYLON.GroupInfoPartData = GroupInfoPartData;
  8338. var TransparentGroupInfoPartData = (function (_super) {
  8339. __extends(TransparentGroupInfoPartData, _super);
  8340. function TransparentGroupInfoPartData(stride, zoff) {
  8341. var _this = _super.call(this, stride) || this;
  8342. _this._partData.compareValueOffset = zoff;
  8343. _this._partData.sortingAscending = false;
  8344. return _this;
  8345. }
  8346. return TransparentGroupInfoPartData;
  8347. }(GroupInfoPartData));
  8348. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  8349. var ModelRenderCache = (function () {
  8350. function ModelRenderCache(engine, modelKey) {
  8351. this._engine = engine;
  8352. this._modelKey = modelKey;
  8353. this._nextKey = 1;
  8354. this._refCounter = 1;
  8355. this._partData = null;
  8356. }
  8357. ModelRenderCache.prototype.dispose = function () {
  8358. if (--this._refCounter !== 0) {
  8359. return false;
  8360. }
  8361. // Remove the Model Render Cache from the global dictionary
  8362. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  8363. if (edata) {
  8364. edata.DisposeModelRenderCache(this);
  8365. }
  8366. return true;
  8367. };
  8368. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  8369. get: function () {
  8370. return this._refCounter <= 0;
  8371. },
  8372. enumerable: true,
  8373. configurable: true
  8374. });
  8375. ModelRenderCache.prototype.addRef = function () {
  8376. return ++this._refCounter;
  8377. };
  8378. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  8379. get: function () {
  8380. return this._modelKey;
  8381. },
  8382. enumerable: true,
  8383. configurable: true
  8384. });
  8385. ModelRenderCache.prototype.updateModelRenderCache = function (prim) {
  8386. return false;
  8387. };
  8388. /**
  8389. * Render the model instances
  8390. * @param instanceInfo
  8391. * @param context
  8392. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  8393. */
  8394. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  8395. return true;
  8396. };
  8397. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  8398. for (var i = 0; i < this._partData.length; i++) {
  8399. if (this._partData[i]._partId === partId) {
  8400. return i;
  8401. }
  8402. }
  8403. return null;
  8404. };
  8405. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  8406. var i = this.getPartIndexFromId(partId);
  8407. if (i === null) {
  8408. return null;
  8409. }
  8410. var ci = this._partsClassInfo[i];
  8411. var categories = this._partData[i]._partUsedCategories;
  8412. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  8413. return res;
  8414. };
  8415. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  8416. var pd = this._partData[partIndex];
  8417. var offset = (pd._partDataStride / 4) * elementCount;
  8418. var pci = this._partsClassInfo[partIndex];
  8419. var self = this;
  8420. pci.fullContent.forEach(function (k, v) {
  8421. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  8422. switch (v.dataType) {
  8423. case 4 /* float */:
  8424. {
  8425. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8426. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  8427. break;
  8428. }
  8429. case 0 /* Vector2 */:
  8430. {
  8431. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8432. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  8433. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  8434. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  8435. break;
  8436. }
  8437. case 5 /* Color3 */:
  8438. case 1 /* Vector3 */:
  8439. {
  8440. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8441. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  8442. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  8443. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  8444. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  8445. break;
  8446. }
  8447. case 6 /* Color4 */:
  8448. case 2 /* Vector4 */:
  8449. {
  8450. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8451. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  8452. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  8453. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  8454. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  8455. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  8456. break;
  8457. }
  8458. default:
  8459. }
  8460. }
  8461. });
  8462. };
  8463. return ModelRenderCache;
  8464. }());
  8465. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  8466. // let i = this.getPartIndexFromId(partId);
  8467. // if (i === null) {
  8468. // return null;
  8469. // }
  8470. // let pci = this._partsClassInfo[i];
  8471. // pci.fullContent.forEach((k, v) => {
  8472. // if (uniforms.indexOf(v.attributeName) !== -1) {
  8473. // v.uniformLocation = effect.getUniform(v.attributeName);
  8474. // }
  8475. // });
  8476. //}
  8477. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  8478. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  8479. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  8480. BABYLON.ModelRenderCache = ModelRenderCache;
  8481. var ModelRenderCachePartData = (function () {
  8482. function ModelRenderCachePartData() {
  8483. }
  8484. return ModelRenderCachePartData;
  8485. }());
  8486. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  8487. })(BABYLON || (BABYLON = {}));
  8488. //# sourceMappingURL=babylon.modelRenderCache.js.map
  8489. var __extends = (this && this.__extends) || function (d, b) {
  8490. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8491. function __() { this.constructor = d; }
  8492. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  8493. };
  8494. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  8495. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  8496. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8497. 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;
  8498. return c > 3 && r && Object.defineProperty(target, key, r), r;
  8499. };
  8500. var BABYLON;
  8501. (function (BABYLON) {
  8502. var InstanceClassInfo = (function () {
  8503. function InstanceClassInfo(base) {
  8504. this._baseInfo = base;
  8505. this._nextOffset = new BABYLON.StringDictionary();
  8506. this._attributes = new Array();
  8507. }
  8508. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  8509. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  8510. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  8511. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  8512. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  8513. if (push) {
  8514. this._attributes.push(propInfo);
  8515. }
  8516. };
  8517. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  8518. var catInline = ";" + categories.join(";") + ";";
  8519. var res = new Array();
  8520. var curInfo = this;
  8521. while (curInfo) {
  8522. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  8523. var attrib = _a[_i];
  8524. // 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
  8525. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  8526. var index = effect.getAttributeLocationByName(attrib.attributeName);
  8527. if (index === -1) {
  8528. throw new Error("Attribute " + attrib.attributeName + " was not found in Effect: " + effect.name + ". It's certainly no longer used in the Effect's Shaders");
  8529. }
  8530. var iai = new BABYLON.InstancingAttributeInfo();
  8531. iai.index = index;
  8532. 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)
  8533. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  8534. iai.attributeName = attrib.attributeName;
  8535. res.push(iai);
  8536. }
  8537. }
  8538. curInfo = curInfo._baseInfo;
  8539. }
  8540. return res;
  8541. };
  8542. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  8543. var res = new Array();
  8544. var curInfo = this;
  8545. while (curInfo) {
  8546. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  8547. var attrib = _a[_i];
  8548. // 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
  8549. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  8550. res.push(attrib.attributeName);
  8551. }
  8552. }
  8553. curInfo = curInfo._baseInfo;
  8554. }
  8555. return res;
  8556. };
  8557. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  8558. var curOffset = 0;
  8559. var curBase = this._baseInfo;
  8560. while (curBase) {
  8561. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  8562. curBase = curBase._baseInfo;
  8563. }
  8564. return curOffset;
  8565. };
  8566. return InstanceClassInfo;
  8567. }());
  8568. BABYLON.InstanceClassInfo = InstanceClassInfo;
  8569. var InstancePropInfo = (function () {
  8570. function InstancePropInfo() {
  8571. this.instanceOffset = new BABYLON.StringDictionary();
  8572. }
  8573. InstancePropInfo.prototype.setSize = function (val) {
  8574. if (val instanceof BABYLON.Vector2) {
  8575. this.size = 8;
  8576. this.dataType = 0 /* Vector2 */;
  8577. return;
  8578. }
  8579. if (val instanceof BABYLON.Vector3) {
  8580. this.size = 12;
  8581. this.dataType = 1 /* Vector3 */;
  8582. return;
  8583. }
  8584. if (val instanceof BABYLON.Vector4) {
  8585. this.size = 16;
  8586. this.dataType = 2 /* Vector4 */;
  8587. return;
  8588. }
  8589. if (val instanceof BABYLON.Matrix) {
  8590. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  8591. }
  8592. if (typeof (val) === "number") {
  8593. this.size = 4;
  8594. this.dataType = 4 /* float */;
  8595. return;
  8596. }
  8597. if (val instanceof BABYLON.Color3) {
  8598. this.size = 12;
  8599. this.dataType = 5 /* Color3 */;
  8600. return;
  8601. }
  8602. if (val instanceof BABYLON.Color4) {
  8603. this.size = 16;
  8604. this.dataType = 6 /* Color4 */;
  8605. return;
  8606. }
  8607. if (val instanceof BABYLON.Size) {
  8608. this.size = 8;
  8609. this.dataType = 7 /* Size */;
  8610. return;
  8611. }
  8612. return;
  8613. };
  8614. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  8615. switch (this.dataType) {
  8616. case 0 /* Vector2 */:
  8617. {
  8618. var v = val;
  8619. array[offset + 0] = v.x;
  8620. array[offset + 1] = v.y;
  8621. break;
  8622. }
  8623. case 1 /* Vector3 */:
  8624. {
  8625. var v = val;
  8626. array[offset + 0] = v.x;
  8627. array[offset + 1] = v.y;
  8628. array[offset + 2] = v.z;
  8629. break;
  8630. }
  8631. case 2 /* Vector4 */:
  8632. {
  8633. var v = val;
  8634. array[offset + 0] = v.x;
  8635. array[offset + 1] = v.y;
  8636. array[offset + 2] = v.z;
  8637. array[offset + 3] = v.w;
  8638. break;
  8639. }
  8640. case 5 /* Color3 */:
  8641. {
  8642. var v = val;
  8643. array[offset + 0] = v.r;
  8644. array[offset + 1] = v.g;
  8645. array[offset + 2] = v.b;
  8646. break;
  8647. }
  8648. case 6 /* Color4 */:
  8649. {
  8650. var v = val;
  8651. array[offset + 0] = v.r;
  8652. array[offset + 1] = v.g;
  8653. array[offset + 2] = v.b;
  8654. array[offset + 3] = v.a;
  8655. break;
  8656. }
  8657. case 4 /* float */:
  8658. {
  8659. var v = val;
  8660. array[offset] = v;
  8661. break;
  8662. }
  8663. case 3 /* Matrix */:
  8664. {
  8665. var v = val;
  8666. for (var i = 0; i < 16; i++) {
  8667. array[offset + i] = v.m[i];
  8668. }
  8669. break;
  8670. }
  8671. case 7 /* Size */:
  8672. {
  8673. var s = val;
  8674. array[offset + 0] = s.width;
  8675. array[offset + 1] = s.height;
  8676. break;
  8677. }
  8678. }
  8679. };
  8680. return InstancePropInfo;
  8681. }());
  8682. BABYLON.InstancePropInfo = InstancePropInfo;
  8683. function instanceData(category, shaderAttributeName) {
  8684. return function (target, propName, descriptor) {
  8685. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  8686. var node = dic.getLevelOf(target);
  8687. var instanceDataName = propName;
  8688. shaderAttributeName = shaderAttributeName || instanceDataName;
  8689. var info = node.levelContent.get(instanceDataName);
  8690. if (info) {
  8691. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  8692. }
  8693. info = new InstancePropInfo();
  8694. info.attributeName = shaderAttributeName;
  8695. info.category = category || null;
  8696. if (info.category) {
  8697. info.delimitedCategory = ";" + info.category + ";";
  8698. }
  8699. node.levelContent.add(instanceDataName, info);
  8700. descriptor.get = function () {
  8701. return null;
  8702. };
  8703. descriptor.set = function (val) {
  8704. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  8705. // Quit if it's the case, otherwise we could overwrite data somewhere...
  8706. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  8707. return;
  8708. }
  8709. if (!info.size) {
  8710. info.setSize(val);
  8711. node.classContent.mapProperty(info, true);
  8712. }
  8713. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  8714. node.classContent.mapProperty(info, false);
  8715. }
  8716. var obj = this;
  8717. if (obj.dataBuffer && obj.dataElements) {
  8718. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  8719. info.writeData(obj.dataBuffer.buffer, offset, val);
  8720. }
  8721. };
  8722. };
  8723. }
  8724. BABYLON.instanceData = instanceData;
  8725. var InstanceDataBase = (function () {
  8726. function InstanceDataBase(partId, dataElementCount) {
  8727. this.id = partId;
  8728. this.curElement = 0;
  8729. this._dataElementCount = dataElementCount;
  8730. this.renderMode = 0;
  8731. this.arrayLengthChanged = false;
  8732. }
  8733. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  8734. get: function () {
  8735. return null;
  8736. },
  8737. set: function (value) {
  8738. },
  8739. enumerable: true,
  8740. configurable: true
  8741. });
  8742. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  8743. get: function () {
  8744. return null;
  8745. },
  8746. set: function (value) {
  8747. },
  8748. enumerable: true,
  8749. configurable: true
  8750. });
  8751. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  8752. get: function () {
  8753. return null;
  8754. },
  8755. set: function (value) {
  8756. },
  8757. enumerable: true,
  8758. configurable: true
  8759. });
  8760. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  8761. get: function () {
  8762. return null;
  8763. },
  8764. set: function (value) {
  8765. },
  8766. enumerable: true,
  8767. configurable: true
  8768. });
  8769. InstanceDataBase.prototype.getClassTreeInfo = function () {
  8770. if (!this.typeInfo) {
  8771. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  8772. }
  8773. return this.typeInfo;
  8774. };
  8775. InstanceDataBase.prototype.allocElements = function () {
  8776. if (!this.dataBuffer || this.dataElements) {
  8777. return;
  8778. }
  8779. var res = new Array(this.dataElementCount);
  8780. for (var i = 0; i < this.dataElementCount; i++) {
  8781. res[i] = this.dataBuffer.allocElement();
  8782. }
  8783. this.dataElements = res;
  8784. };
  8785. InstanceDataBase.prototype.freeElements = function () {
  8786. if (!this.dataElements) {
  8787. return;
  8788. }
  8789. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  8790. var ei = _a[_i];
  8791. this.dataBuffer.freeElement(ei);
  8792. }
  8793. this.dataElements = null;
  8794. };
  8795. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  8796. get: function () {
  8797. return this._dataElementCount;
  8798. },
  8799. set: function (value) {
  8800. if (value === this._dataElementCount) {
  8801. return;
  8802. }
  8803. this.arrayLengthChanged = true;
  8804. this.freeElements();
  8805. this._dataElementCount = value;
  8806. this.allocElements();
  8807. },
  8808. enumerable: true,
  8809. configurable: true
  8810. });
  8811. return InstanceDataBase;
  8812. }());
  8813. __decorate([
  8814. instanceData()
  8815. ], InstanceDataBase.prototype, "zBias", null);
  8816. __decorate([
  8817. instanceData()
  8818. ], InstanceDataBase.prototype, "transformX", null);
  8819. __decorate([
  8820. instanceData()
  8821. ], InstanceDataBase.prototype, "transformY", null);
  8822. __decorate([
  8823. instanceData()
  8824. ], InstanceDataBase.prototype, "opacity", null);
  8825. BABYLON.InstanceDataBase = InstanceDataBase;
  8826. var RenderablePrim2D = RenderablePrim2D_1 = (function (_super) {
  8827. __extends(RenderablePrim2D, _super);
  8828. function RenderablePrim2D(settings) {
  8829. var _this = _super.call(this, settings) || this;
  8830. _this._transparentPrimitiveInfo = null;
  8831. return _this;
  8832. }
  8833. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  8834. get: function () {
  8835. return this._useTextureAlpha() || this._isPrimAlphaTest();
  8836. },
  8837. enumerable: true,
  8838. configurable: true
  8839. });
  8840. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  8841. get: function () {
  8842. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  8843. },
  8844. enumerable: true,
  8845. configurable: true
  8846. });
  8847. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  8848. get: function () {
  8849. return this._renderMode;
  8850. },
  8851. enumerable: true,
  8852. configurable: true
  8853. });
  8854. /**
  8855. * Dispose the primitive and its resources, remove it from its parent
  8856. */
  8857. RenderablePrim2D.prototype.dispose = function () {
  8858. if (!_super.prototype.dispose.call(this)) {
  8859. return false;
  8860. }
  8861. if (this.renderGroup) {
  8862. this.renderGroup._setCacheGroupDirty();
  8863. }
  8864. if (this._transparentPrimitiveInfo) {
  8865. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  8866. this._transparentPrimitiveInfo = null;
  8867. }
  8868. if (this._instanceDataParts) {
  8869. this._cleanupInstanceDataParts();
  8870. }
  8871. if (this._modelRenderCache) {
  8872. this._modelRenderCache.dispose();
  8873. this._modelRenderCache = null;
  8874. }
  8875. if (this._instanceDataParts) {
  8876. this._instanceDataParts.forEach(function (p) {
  8877. p.freeElements();
  8878. });
  8879. this._instanceDataParts = null;
  8880. }
  8881. return true;
  8882. };
  8883. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  8884. var gii = null;
  8885. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  8886. var part = _a[_i];
  8887. part.freeElements();
  8888. gii = part.groupInstanceInfo;
  8889. }
  8890. if (gii) {
  8891. var usedCount = 0;
  8892. if (gii.hasOpaqueData) {
  8893. var od = gii.opaqueData[0];
  8894. usedCount += od._partData.usedElementCount;
  8895. gii.opaqueDirty = true;
  8896. }
  8897. if (gii.hasAlphaTestData) {
  8898. var atd = gii.alphaTestData[0];
  8899. usedCount += atd._partData.usedElementCount;
  8900. gii.alphaTestDirty = true;
  8901. }
  8902. if (gii.hasTransparentData) {
  8903. var td = gii.transparentData[0];
  8904. usedCount += td._partData.usedElementCount;
  8905. gii.transparentDirty = true;
  8906. }
  8907. if (usedCount === 0 && gii.modelRenderCache != null) {
  8908. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  8909. gii.dispose();
  8910. }
  8911. if (this._modelRenderCache) {
  8912. this._modelRenderCache.dispose();
  8913. this._modelRenderCache = null;
  8914. }
  8915. }
  8916. this._instanceDataParts = null;
  8917. };
  8918. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  8919. _super.prototype._prepareRenderPre.call(this, context);
  8920. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  8921. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  8922. this._cleanupInstanceDataParts();
  8923. }
  8924. // Need to create the model?
  8925. var setupModelRenderCache = false;
  8926. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  8927. setupModelRenderCache = this._createModelRenderCache();
  8928. }
  8929. var gii = null;
  8930. var newInstance = false;
  8931. // Need to create the instance data parts?
  8932. if (!this._instanceDataParts) {
  8933. // Yes, flag it for later, more processing will have to be done
  8934. newInstance = true;
  8935. gii = this._createModelDataParts();
  8936. }
  8937. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  8938. if (setupModelRenderCache) {
  8939. this.setupModelRenderCache(this._modelRenderCache);
  8940. }
  8941. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelUpdate)) {
  8942. if (this._modelRenderCache.updateModelRenderCache(this)) {
  8943. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  8944. }
  8945. }
  8946. // 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.
  8947. // 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.
  8948. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  8949. this._updateInstanceDataParts(gii);
  8950. }
  8951. };
  8952. RenderablePrim2D.prototype._createModelRenderCache = function () {
  8953. var _this = this;
  8954. var setupModelRenderCache = false;
  8955. if (this._modelRenderCache) {
  8956. this._modelRenderCache.dispose();
  8957. }
  8958. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  8959. var mrc = _this.createModelRenderCache(key);
  8960. setupModelRenderCache = true;
  8961. return mrc;
  8962. });
  8963. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  8964. // if this is still false it means the MRC already exists, so we add a reference to it
  8965. if (!setupModelRenderCache) {
  8966. this._modelRenderCache.addRef();
  8967. }
  8968. return setupModelRenderCache;
  8969. };
  8970. RenderablePrim2D.prototype._createModelDataParts = function () {
  8971. var _this = this;
  8972. // Create the instance data parts of the primitive and store them
  8973. var parts = this.createInstanceDataParts();
  8974. this._instanceDataParts = parts;
  8975. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  8976. if (!this._modelRenderCache._partData) {
  8977. this._setupModelRenderCache(parts);
  8978. }
  8979. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  8980. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  8981. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  8982. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  8983. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  8984. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  8985. var part = _this._instanceDataParts[j];
  8986. res.partIndexFromId.add(part.id.toString(), j);
  8987. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  8988. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  8989. }
  8990. return res;
  8991. });
  8992. // Get the GroupInfoDataPart corresponding to the render category of the part
  8993. var rm = 0;
  8994. var gipd = null;
  8995. if (this.isTransparent) {
  8996. gipd = gii.transparentData;
  8997. rm = BABYLON.Render2DContext.RenderModeTransparent;
  8998. }
  8999. else if (this.isAlphaTest) {
  9000. gipd = gii.alphaTestData;
  9001. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  9002. }
  9003. else {
  9004. gipd = gii.opaqueData;
  9005. rm = BABYLON.Render2DContext.RenderModeOpaque;
  9006. }
  9007. // For each instance data part of the primitive, allocate the instanced element it needs for render
  9008. for (var i = 0; i < parts.length; i++) {
  9009. var part = parts[i];
  9010. part.dataBuffer = gipd[i]._partData;
  9011. part.allocElements();
  9012. part.renderMode = rm;
  9013. part.groupInstanceInfo = gii;
  9014. }
  9015. return gii;
  9016. };
  9017. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  9018. var ctiArray = new Array();
  9019. this._modelRenderCache._partData = new Array();
  9020. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  9021. var dataPart = parts_1[_i];
  9022. var pd = new BABYLON.ModelRenderCachePartData();
  9023. this._modelRenderCache._partData.push(pd);
  9024. var cat = this.getUsedShaderCategories(dataPart);
  9025. var cti = dataPart.getClassTreeInfo();
  9026. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  9027. var curVisible = this.isVisible;
  9028. this.isVisible = true;
  9029. // 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.
  9030. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  9031. var joinCat = ";" + cat.join(";") + ";";
  9032. pd._partJoinedUsedCategories = joinCat;
  9033. InstanceClassInfo._CurCategories = joinCat;
  9034. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  9035. if (!this.refreshInstanceDataPart(dataPart)) {
  9036. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  9037. }
  9038. this.afterRefreshForLayoutConstruction(dataPart, obj);
  9039. this.isVisible = curVisible;
  9040. var size = 0;
  9041. cti.fullContent.forEach(function (k, v) {
  9042. if (!v.category || cat.indexOf(v.category) !== -1) {
  9043. if (v.attributeName === "zBias") {
  9044. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  9045. }
  9046. if (!v.size) {
  9047. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  9048. }
  9049. else {
  9050. size += v.size;
  9051. }
  9052. }
  9053. });
  9054. pd._partDataStride = size;
  9055. pd._partUsedCategories = cat;
  9056. pd._partId = dataPart.id;
  9057. ctiArray.push(cti);
  9058. }
  9059. this._modelRenderCache._partsClassInfo = ctiArray;
  9060. };
  9061. RenderablePrim2D.prototype.onZOrderChanged = function () {
  9062. if (this.isTransparent && this._transparentPrimitiveInfo) {
  9063. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  9064. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  9065. // Flag the transparentData dirty has will have to sort it again
  9066. gii.transparentOrderDirty = true;
  9067. }
  9068. };
  9069. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  9070. return false;
  9071. };
  9072. RenderablePrim2D.prototype._useTextureAlpha = function () {
  9073. return false;
  9074. };
  9075. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  9076. return false;
  9077. };
  9078. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  9079. return false;
  9080. };
  9081. RenderablePrim2D.prototype._isPrimTransparent = function () {
  9082. return false;
  9083. };
  9084. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  9085. // Fetch the GroupInstanceInfo if we don't already have it
  9086. var rd = this.renderGroup._renderableData;
  9087. if (!gii) {
  9088. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  9089. }
  9090. var isTransparent = this.isTransparent;
  9091. var isAlphaTest = this.isAlphaTest;
  9092. var wereTransparent = false;
  9093. // Check a render mode change
  9094. var rmChanged = false;
  9095. if (this._instanceDataParts.length > 0) {
  9096. var firstPart = this._instanceDataParts[0];
  9097. var partRM = firstPart.renderMode;
  9098. var curRM = this.renderMode;
  9099. if (partRM !== curRM) {
  9100. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  9101. rmChanged = true;
  9102. var gipd = void 0;
  9103. switch (curRM) {
  9104. case BABYLON.Render2DContext.RenderModeTransparent:
  9105. gipd = gii.transparentData;
  9106. break;
  9107. case BABYLON.Render2DContext.RenderModeAlphaTest:
  9108. gipd = gii.alphaTestData;
  9109. break;
  9110. default:
  9111. gipd = gii.opaqueData;
  9112. }
  9113. for (var i = 0; i < this._instanceDataParts.length; i++) {
  9114. var part = this._instanceDataParts[i];
  9115. part.freeElements();
  9116. part.dataBuffer = gipd[i]._partData;
  9117. part.renderMode = curRM;
  9118. }
  9119. }
  9120. }
  9121. // Handle changes related to ZOffset
  9122. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  9123. if (isTransparent || wereTransparent) {
  9124. // Handle visibility change, which is also triggered when the primitive just got created
  9125. if (visChanged || rmChanged) {
  9126. if (this.isVisible && !wereTransparent) {
  9127. if (!this._transparentPrimitiveInfo) {
  9128. // Add the primitive to the list of transparent ones in the group that render is
  9129. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  9130. }
  9131. }
  9132. else {
  9133. if (this._transparentPrimitiveInfo) {
  9134. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  9135. this._transparentPrimitiveInfo = null;
  9136. }
  9137. }
  9138. gii.transparentOrderDirty = true;
  9139. }
  9140. }
  9141. var rebuildTrans = false;
  9142. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  9143. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  9144. var part = _a[_i];
  9145. var justAllocated = false;
  9146. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  9147. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  9148. part.allocElements();
  9149. justAllocated = true;
  9150. }
  9151. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  9152. // Will return false if the instance should not be rendered (not visible or other any reasons)
  9153. part.arrayLengthChanged = false;
  9154. if (!this.refreshInstanceDataPart(part)) {
  9155. // Free the data element
  9156. if (part.dataElements) {
  9157. part.freeElements();
  9158. }
  9159. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  9160. if (this.isVisible) {
  9161. rd._primNewDirtyList.push(this);
  9162. }
  9163. }
  9164. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  9165. }
  9166. this._instanceDirtyFlags = 0;
  9167. // Make the appropriate data dirty
  9168. if (isTransparent) {
  9169. gii.transparentDirty = true;
  9170. if (rebuildTrans) {
  9171. rd._transparentListChanged = true;
  9172. }
  9173. }
  9174. else if (isAlphaTest) {
  9175. gii.alphaTestDirty = true;
  9176. }
  9177. else {
  9178. gii.opaqueDirty = true;
  9179. }
  9180. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  9181. };
  9182. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  9183. var minOff = BABYLON.Prim2DBase._bigInt;
  9184. var maxOff = 0;
  9185. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  9186. var part = _a[_i];
  9187. if (part && part.dataElements) {
  9188. part.dataBuffer.pack();
  9189. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  9190. var el = _c[_b];
  9191. minOff = Math.min(minOff, el.offset);
  9192. maxOff = Math.max(maxOff, el.offset);
  9193. }
  9194. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  9195. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  9196. }
  9197. }
  9198. };
  9199. // This internal method is mainly used for transparency processing
  9200. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  9201. var length = this._instanceDataParts.length;
  9202. for (var i = 0; i < length; i++) {
  9203. var part = this._instanceDataParts[i];
  9204. if (part) {
  9205. var stride = part.dataBuffer.stride;
  9206. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  9207. // check if it's the last in the DFA
  9208. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  9209. return null;
  9210. }
  9211. // Return the Z of the next primitive that lies in the DFA
  9212. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  9213. }
  9214. }
  9215. return null;
  9216. };
  9217. // This internal method is mainly used for transparency processing
  9218. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  9219. var length = this._instanceDataParts.length;
  9220. for (var i = 0; i < length; i++) {
  9221. var part = this._instanceDataParts[i];
  9222. if (part) {
  9223. var stride = part.dataBuffer.stride;
  9224. var firstElementOffset = part.dataElements[0].offset;
  9225. // check if it's the first in the DFA
  9226. if (firstElementOffset === 0) {
  9227. return null;
  9228. }
  9229. // Return the Z of the previous primitive that lies in the DFA
  9230. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  9231. }
  9232. }
  9233. return null;
  9234. };
  9235. /**
  9236. * Transform a given point using the Primitive's origin setting.
  9237. * This method requires the Primitive's actualSize to be accurate
  9238. * @param p the point to transform
  9239. * @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.
  9240. * @param res an allocated Vector2 that will receive the transformed content
  9241. */
  9242. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  9243. var actualSize = this.actualSize;
  9244. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  9245. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  9246. };
  9247. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  9248. this.transformPointWithOriginByRef(p, originOffset, res);
  9249. return res;
  9250. };
  9251. /**
  9252. * Get the info for a given effect based on the dataPart metadata
  9253. * @param dataPartId partId in part list to get the info
  9254. * @param vertexBufferAttributes vertex buffer attributes to manually add
  9255. * @param uniforms uniforms to manually add
  9256. * @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
  9257. */
  9258. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  9259. if (uniforms === void 0) { uniforms = null; }
  9260. if (useInstanced === void 0) { useInstanced = null; }
  9261. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  9262. if (!dataPart) {
  9263. return null;
  9264. }
  9265. var instancedArray = this.owner.supportInstancedArray;
  9266. if (useInstanced != null) {
  9267. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  9268. if (useInstanced && instancedArray === false) {
  9269. return null;
  9270. }
  9271. // Use the caller's setting
  9272. instancedArray = useInstanced;
  9273. }
  9274. var cti = dataPart.getClassTreeInfo();
  9275. var categories = this.getUsedShaderCategories(dataPart);
  9276. var att = cti.classContent.getShaderAttributes(categories);
  9277. var defines = "";
  9278. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  9279. if (instancedArray) {
  9280. defines += "#define Instanced\n";
  9281. }
  9282. return {
  9283. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  9284. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  9285. defines: defines
  9286. };
  9287. };
  9288. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  9289. get: function () {
  9290. return this._modelRenderCache;
  9291. },
  9292. enumerable: true,
  9293. configurable: true
  9294. });
  9295. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  9296. return null;
  9297. };
  9298. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  9299. };
  9300. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  9301. return null;
  9302. };
  9303. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  9304. return [];
  9305. };
  9306. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  9307. };
  9308. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  9309. };
  9310. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  9311. return true;
  9312. };
  9313. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  9314. if (!this.isVisible) {
  9315. return false;
  9316. }
  9317. part.isVisible = this.isVisible;
  9318. // 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)
  9319. if (part.dataElementCount === 1) {
  9320. part.curElement = 0;
  9321. this.updateInstanceDataPart(part);
  9322. }
  9323. return true;
  9324. };
  9325. /**
  9326. * Update the instanceDataBase level properties of a part
  9327. * @param part the part to update
  9328. * @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).
  9329. */
  9330. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  9331. if (positionOffset === void 0) { positionOffset = null; }
  9332. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  9333. var rgScale = this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? RenderablePrim2D_1._uV : this.renderGroup.actualScale; // We still need to apply the scale of the renderGroup to our rendering, so get it.
  9334. var size = this.renderGroup.viewportSize;
  9335. var zBias = this.actualZOffset;
  9336. var offX = 0;
  9337. var offY = 0;
  9338. // If there's an offset, apply the global transformation matrix on it to get a global offset
  9339. if (positionOffset) {
  9340. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  9341. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  9342. }
  9343. // 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
  9344. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  9345. // So for X:
  9346. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  9347. // - 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].
  9348. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  9349. var w = size.width;
  9350. var h = size.height;
  9351. var invZBias = 1 / zBias;
  9352. var tx = new BABYLON.Vector4(t.m[0] * rgScale.x * 2 /* / w*/, t.m[4] * rgScale.x * 2 /* / w*/, 0 /*t.m[8]*/, ((t.m[12] + offX) * rgScale.x * 2 / w) - 1);
  9353. var ty = new BABYLON.Vector4(t.m[1] * rgScale.y * 2 /* / h*/, t.m[5] * rgScale.y * 2 /* / h*/, 0 /*t.m[9]*/, ((t.m[13] + offY) * rgScale.y * 2 / h) - 1);
  9354. if (!this.applyActualScaleOnTransform()) {
  9355. t.m[0] = tx.x, t.m[4] = tx.y, t.m[12] = tx.w;
  9356. t.m[1] = ty.x, t.m[5] = ty.y, t.m[13] = ty.w;
  9357. var las = this.actualScale;
  9358. t.decompose(RenderablePrim2D_1._s, RenderablePrim2D_1._r, RenderablePrim2D_1._t);
  9359. var scale = new BABYLON.Vector3(RenderablePrim2D_1._s.x / las.x, RenderablePrim2D_1._s.y / las.y, 1);
  9360. t = BABYLON.Matrix.Compose(scale, RenderablePrim2D_1._r, RenderablePrim2D_1._t);
  9361. tx = new BABYLON.Vector4(t.m[0], t.m[4], 0, t.m[12]);
  9362. ty = new BABYLON.Vector4(t.m[1], t.m[5], 0, t.m[13]);
  9363. }
  9364. tx.x /= w;
  9365. tx.y /= w;
  9366. ty.x /= h;
  9367. ty.y /= h;
  9368. part.transformX = tx;
  9369. part.transformY = ty;
  9370. part.opacity = this.actualOpacity;
  9371. // 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)
  9372. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  9373. };
  9374. RenderablePrim2D.prototype._updateRenderMode = function () {
  9375. if (this.isTransparent) {
  9376. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  9377. }
  9378. else if (this.isAlphaTest) {
  9379. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  9380. }
  9381. else {
  9382. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  9383. }
  9384. };
  9385. return RenderablePrim2D;
  9386. }(BABYLON.Prim2DBase));
  9387. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  9388. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  9389. RenderablePrim2D._s = BABYLON.Vector3.Zero();
  9390. RenderablePrim2D._r = BABYLON.Quaternion.Identity();
  9391. RenderablePrim2D._t = BABYLON.Vector3.Zero();
  9392. RenderablePrim2D._uV3 = new BABYLON.Vector3(1, 1, 1);
  9393. __decorate([
  9394. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D_1.isAlphaTestProperty = pi; })
  9395. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  9396. __decorate([
  9397. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D_1.isTransparentProperty = pi; })
  9398. ], RenderablePrim2D.prototype, "isTransparent", null);
  9399. RenderablePrim2D = RenderablePrim2D_1 = __decorate([
  9400. BABYLON.className("RenderablePrim2D", "BABYLON")
  9401. ], RenderablePrim2D);
  9402. BABYLON.RenderablePrim2D = RenderablePrim2D;
  9403. var RenderablePrim2D_1;
  9404. })(BABYLON || (BABYLON = {}));
  9405. //# sourceMappingURL=babylon.renderablePrim2d.js.map
  9406. var __extends = (this && this.__extends) || function (d, b) {
  9407. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9408. function __() { this.constructor = d; }
  9409. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9410. };
  9411. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  9412. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  9413. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9414. 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;
  9415. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9416. };
  9417. var BABYLON;
  9418. (function (BABYLON) {
  9419. var Shape2D = Shape2D_1 = (function (_super) {
  9420. __extends(Shape2D, _super);
  9421. function Shape2D(settings) {
  9422. var _this = _super.call(this, settings) || this;
  9423. if (!settings) {
  9424. settings = {};
  9425. }
  9426. var borderBrush = null;
  9427. if (settings.border) {
  9428. if (typeof (settings.border) === "string") {
  9429. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  9430. }
  9431. else {
  9432. borderBrush = settings.border;
  9433. }
  9434. }
  9435. var fillBrush = null;
  9436. if (settings.fill) {
  9437. if (typeof (settings.fill) === "string") {
  9438. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  9439. }
  9440. else {
  9441. fillBrush = settings.fill;
  9442. }
  9443. }
  9444. _this._isTransparent = false;
  9445. _this._oldTransparent = false;
  9446. _this.border = borderBrush;
  9447. _this.fill = fillBrush;
  9448. _this._updateTransparencyStatus();
  9449. _this.borderThickness = settings.borderThickness;
  9450. return _this;
  9451. }
  9452. Object.defineProperty(Shape2D.prototype, "border", {
  9453. get: function () {
  9454. return this._border;
  9455. },
  9456. set: function (value) {
  9457. this._border = value;
  9458. this._updateTransparencyStatus();
  9459. },
  9460. enumerable: true,
  9461. configurable: true
  9462. });
  9463. Object.defineProperty(Shape2D.prototype, "fill", {
  9464. /**
  9465. * Get/set the brush to render the Fill part of the Primitive
  9466. */
  9467. get: function () {
  9468. return this._fill;
  9469. },
  9470. set: function (value) {
  9471. this._fill = value;
  9472. this._updateTransparencyStatus();
  9473. },
  9474. enumerable: true,
  9475. configurable: true
  9476. });
  9477. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  9478. get: function () {
  9479. return this._borderThickness;
  9480. },
  9481. set: function (value) {
  9482. this._borderThickness = value;
  9483. },
  9484. enumerable: true,
  9485. configurable: true
  9486. });
  9487. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  9488. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  9489. // Fill Part
  9490. if (dataPart.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  9491. var fill = this.fill;
  9492. if (fill instanceof BABYLON.SolidColorBrush2D) {
  9493. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLSOLID);
  9494. }
  9495. if (fill instanceof BABYLON.GradientColorBrush2D) {
  9496. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLGRADIENT);
  9497. }
  9498. }
  9499. // Border Part
  9500. if (dataPart.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  9501. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDER);
  9502. var border = this.border;
  9503. if (border instanceof BABYLON.SolidColorBrush2D) {
  9504. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERSOLID);
  9505. }
  9506. if (border instanceof BABYLON.GradientColorBrush2D) {
  9507. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERGRADIENT);
  9508. }
  9509. }
  9510. return cat;
  9511. };
  9512. Shape2D.prototype.applyActualScaleOnTransform = function () {
  9513. return false;
  9514. };
  9515. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  9516. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  9517. return false;
  9518. }
  9519. // Fill Part
  9520. if (part.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  9521. var d = part;
  9522. if (this.fill) {
  9523. var fill = this.fill;
  9524. if (fill instanceof BABYLON.SolidColorBrush2D) {
  9525. d.fillSolidColor = fill.color;
  9526. }
  9527. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  9528. d.fillGradientColor1 = fill.color1;
  9529. d.fillGradientColor2 = fill.color2;
  9530. 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));
  9531. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  9532. d.fillGradientTY = ty;
  9533. }
  9534. }
  9535. }
  9536. else if (part.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  9537. var d = part;
  9538. if (this.border) {
  9539. d.borderThickness = this.borderThickness;
  9540. var border = this.border;
  9541. if (border instanceof BABYLON.SolidColorBrush2D) {
  9542. d.borderSolidColor = border.color;
  9543. }
  9544. else if (border instanceof BABYLON.GradientColorBrush2D) {
  9545. d.borderGradientColor1 = border.color1;
  9546. d.borderGradientColor2 = border.color2;
  9547. 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));
  9548. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  9549. d.borderGradientTY = ty;
  9550. }
  9551. }
  9552. }
  9553. return true;
  9554. };
  9555. Shape2D.prototype._updateTransparencyStatus = function () {
  9556. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  9557. if (this._isTransparent !== this._oldTransparent) {
  9558. this._oldTransparent = this._isTransparent;
  9559. this._updateRenderMode();
  9560. }
  9561. };
  9562. Shape2D.prototype._mustUpdateInstance = function () {
  9563. var res = this._oldTransparent !== this._isTransparent;
  9564. if (res) {
  9565. this._updateRenderMode();
  9566. this._oldTransparent = this._isTransparent;
  9567. }
  9568. return res;
  9569. };
  9570. Shape2D.prototype._isPrimTransparent = function () {
  9571. return this._isTransparent;
  9572. };
  9573. return Shape2D;
  9574. }(BABYLON.RenderablePrim2D));
  9575. Shape2D.SHAPE2D_BORDERPARTID = 1;
  9576. Shape2D.SHAPE2D_FILLPARTID = 2;
  9577. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  9578. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  9579. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  9580. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  9581. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  9582. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  9583. __decorate([
  9584. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D_1.borderProperty = pi; }, true)
  9585. ], Shape2D.prototype, "border", null);
  9586. __decorate([
  9587. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D_1.fillProperty = pi; }, true)
  9588. ], Shape2D.prototype, "fill", null);
  9589. __decorate([
  9590. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D_1.borderThicknessProperty = pi; })
  9591. ], Shape2D.prototype, "borderThickness", null);
  9592. Shape2D = Shape2D_1 = __decorate([
  9593. BABYLON.className("Shape2D", "BABYLON")
  9594. ], Shape2D);
  9595. BABYLON.Shape2D = Shape2D;
  9596. var Shape2DInstanceData = (function (_super) {
  9597. __extends(Shape2DInstanceData, _super);
  9598. function Shape2DInstanceData() {
  9599. return _super !== null && _super.apply(this, arguments) || this;
  9600. }
  9601. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  9602. // FILL ATTRIBUTES
  9603. get: function () {
  9604. return null;
  9605. },
  9606. set: function (value) {
  9607. },
  9608. enumerable: true,
  9609. configurable: true
  9610. });
  9611. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  9612. get: function () {
  9613. return null;
  9614. },
  9615. set: function (value) {
  9616. },
  9617. enumerable: true,
  9618. configurable: true
  9619. });
  9620. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  9621. get: function () {
  9622. return null;
  9623. },
  9624. set: function (value) {
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  9630. get: function () {
  9631. return null;
  9632. },
  9633. set: function (value) {
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  9639. // BORDER ATTRIBUTES
  9640. get: function () {
  9641. return null;
  9642. },
  9643. set: function (value) {
  9644. },
  9645. enumerable: true,
  9646. configurable: true
  9647. });
  9648. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  9649. get: function () {
  9650. return null;
  9651. },
  9652. set: function (value) {
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  9658. get: function () {
  9659. return null;
  9660. },
  9661. set: function (value) {
  9662. },
  9663. enumerable: true,
  9664. configurable: true
  9665. });
  9666. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  9667. get: function () {
  9668. return null;
  9669. },
  9670. set: function (value) {
  9671. },
  9672. enumerable: true,
  9673. configurable: true
  9674. });
  9675. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  9676. get: function () {
  9677. return null;
  9678. },
  9679. set: function (value) {
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. return Shape2DInstanceData;
  9685. }(BABYLON.InstanceDataBase));
  9686. __decorate([
  9687. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  9688. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  9689. __decorate([
  9690. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  9691. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  9692. __decorate([
  9693. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  9694. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  9695. __decorate([
  9696. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  9697. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  9698. __decorate([
  9699. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  9700. ], Shape2DInstanceData.prototype, "borderThickness", null);
  9701. __decorate([
  9702. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  9703. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  9704. __decorate([
  9705. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  9706. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  9707. __decorate([
  9708. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  9709. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  9710. __decorate([
  9711. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  9712. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  9713. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  9714. var Shape2D_1;
  9715. })(BABYLON || (BABYLON = {}));
  9716. //# sourceMappingURL=babylon.shape2d.js.map
  9717. var __extends = (this && this.__extends) || function (d, b) {
  9718. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9719. function __() { this.constructor = d; }
  9720. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9721. };
  9722. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  9723. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  9724. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9725. 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;
  9726. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9727. };
  9728. var BABYLON;
  9729. (function (BABYLON) {
  9730. var Group2D = Group2D_1 = (function (_super) {
  9731. __extends(Group2D, _super);
  9732. /**
  9733. * Create an Logical or Renderable Group.
  9734. * @param settings a combination of settings, possible ones are
  9735. * - 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)
  9736. * - children: an array of direct children
  9737. * - id a text identifier, for information purpose
  9738. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  9739. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  9740. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  9741. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  9742. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  9743. * - zOrder: override the zOrder with the specified value
  9744. * - origin: define the normalized origin point location, default [0.5;0.5]
  9745. * - 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.
  9746. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  9747. * - 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).
  9748. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  9749. * - 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.
  9750. * - 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.
  9751. * - 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!
  9752. * - 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.
  9753. * - 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).
  9754. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  9755. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9756. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9757. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9758. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9759. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  9760. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  9761. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  9762. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  9763. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9764. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9765. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9766. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9767. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  9768. */
  9769. function Group2D(settings) {
  9770. var _this = this;
  9771. if (settings == null) {
  9772. settings = {};
  9773. }
  9774. if (settings.origin == null) {
  9775. settings.origin = new BABYLON.Vector2(0, 0);
  9776. }
  9777. _this = _super.call(this, settings) || this;
  9778. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  9779. _this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  9780. if (_this._trackedNode && _this.owner) {
  9781. _this.owner._registerTrackedNode(_this);
  9782. }
  9783. _this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  9784. var rd = _this._renderableData;
  9785. if (rd) {
  9786. rd._noResizeOnScale = (_this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  9787. }
  9788. _this.size = size;
  9789. _this._viewportPosition = BABYLON.Vector2.Zero();
  9790. _this._viewportSize = BABYLON.Size.Zero();
  9791. return _this;
  9792. }
  9793. Group2D._createCachedCanvasGroup = function (owner) {
  9794. 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 });
  9795. return g;
  9796. };
  9797. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  9798. this._bindCacheTarget();
  9799. if (vertexData) {
  9800. var uv = vertexData.uvs;
  9801. var nodeuv = this._renderableData._cacheNodeUVs;
  9802. for (var i = 0; i < 4; i++) {
  9803. uv[i * 2 + 0] = nodeuv[i].x;
  9804. uv[i * 2 + 1] = nodeuv[i].y;
  9805. }
  9806. }
  9807. if (material) {
  9808. material.diffuseTexture = this._renderableData._cacheTexture;
  9809. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  9810. }
  9811. this._renderableData._cacheTexture.hasAlpha = true;
  9812. this._unbindCacheTarget();
  9813. };
  9814. Object.defineProperty(Group2D.prototype, "cachedRect", {
  9815. /**
  9816. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  9817. * 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.
  9818. */
  9819. get: function () {
  9820. if (!this._renderableData) {
  9821. return null;
  9822. }
  9823. return this._renderableData._cacheNode;
  9824. },
  9825. enumerable: true,
  9826. configurable: true
  9827. });
  9828. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  9829. /**
  9830. * The UVs into the MapTexture that map the cached group
  9831. */
  9832. get: function () {
  9833. if (!this._renderableData) {
  9834. return null;
  9835. }
  9836. return this._renderableData._cacheNodeUVs;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  9842. get: function () {
  9843. if (!this._renderableData) {
  9844. return null;
  9845. }
  9846. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  9847. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  9848. }
  9849. return this._renderableData._cacheNodeUVsChangedObservable;
  9850. },
  9851. enumerable: true,
  9852. configurable: true
  9853. });
  9854. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  9855. /**
  9856. * Access the texture that maintains a cached version of the Group2D.
  9857. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  9858. */
  9859. get: function () {
  9860. if (!this._renderableData) {
  9861. return null;
  9862. }
  9863. return this._renderableData._cacheTexture;
  9864. },
  9865. enumerable: true,
  9866. configurable: true
  9867. });
  9868. /**
  9869. * Call this method to remove this Group and its children from the Canvas
  9870. */
  9871. Group2D.prototype.dispose = function () {
  9872. if (!_super.prototype.dispose.call(this)) {
  9873. return false;
  9874. }
  9875. if (this._trackedNode != null) {
  9876. this.owner._unregisterTrackedNode(this);
  9877. this._trackedNode = null;
  9878. }
  9879. if (this._renderableData) {
  9880. this._renderableData.dispose(this.owner);
  9881. this._renderableData = null;
  9882. }
  9883. return true;
  9884. };
  9885. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  9886. /**
  9887. * @returns Returns true if the Group render content, false if it's a logical group only
  9888. */
  9889. get: function () {
  9890. return this._isRenderableGroup;
  9891. },
  9892. enumerable: true,
  9893. configurable: true
  9894. });
  9895. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  9896. /**
  9897. * @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
  9898. */
  9899. get: function () {
  9900. return this._isCachedGroup;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(Group2D.prototype, "size", {
  9906. get: function () {
  9907. return this._size;
  9908. },
  9909. /**
  9910. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  9911. * 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.
  9912. */
  9913. set: function (val) {
  9914. this.internalSetSize(val);
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(Group2D.prototype, "viewportSize", {
  9920. get: function () {
  9921. return this._viewportSize;
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. Object.defineProperty(Group2D.prototype, "actualSize", {
  9927. get: function () {
  9928. // The computed size will be floor on both width and height
  9929. var actualSize;
  9930. // Return the actualSize if set
  9931. if (this._actualSize) {
  9932. return this._actualSize;
  9933. }
  9934. // Return the size if set by the user
  9935. if (this._size) {
  9936. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  9937. }
  9938. else {
  9939. var m = this.layoutBoundingInfo.max();
  9940. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  9941. }
  9942. // Compare the size with the one we previously had, if it differs we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  9943. if (!actualSize.equals(this._actualSize)) {
  9944. this.onPrimitivePropertyDirty(Group2D_1.actualSizeProperty.flagId);
  9945. this._actualSize = actualSize;
  9946. this.handleGroupChanged(Group2D_1.actualSizeProperty);
  9947. }
  9948. return actualSize;
  9949. },
  9950. set: function (value) {
  9951. if (!this._actualSize) {
  9952. this._actualSize = value.clone();
  9953. }
  9954. else {
  9955. this._actualSize.copyFrom(value);
  9956. }
  9957. },
  9958. enumerable: true,
  9959. configurable: true
  9960. });
  9961. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  9962. /**
  9963. * 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.
  9964. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  9965. * 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.
  9966. */
  9967. get: function () {
  9968. return this._cacheBehavior;
  9969. },
  9970. enumerable: true,
  9971. configurable: true
  9972. });
  9973. Group2D.prototype._addPrimToDirtyList = function (prim) {
  9974. this._renderableData._primDirtyList.push(prim);
  9975. };
  9976. Group2D.prototype._renderCachedCanvas = function () {
  9977. this.owner._addGroupRenderCount(1);
  9978. this.updateCachedStates(true);
  9979. var context = new BABYLON.PrepareRender2DContext();
  9980. this._prepareGroupRender(context);
  9981. this._groupRender();
  9982. };
  9983. Object.defineProperty(Group2D.prototype, "trackedNode", {
  9984. /**
  9985. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  9986. */
  9987. get: function () {
  9988. return this._trackedNode;
  9989. },
  9990. set: function (val) {
  9991. if (val != null) {
  9992. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  9993. this.owner._registerTrackedNode(this);
  9994. }
  9995. this._trackedNode = val;
  9996. }
  9997. else {
  9998. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  9999. this.owner._unregisterTrackedNode(this);
  10000. }
  10001. this._trackedNode = null;
  10002. }
  10003. },
  10004. enumerable: true,
  10005. configurable: true
  10006. });
  10007. Group2D.prototype.levelIntersect = function (intersectInfo) {
  10008. // 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
  10009. return true;
  10010. };
  10011. Group2D.prototype.updateLevelBoundingInfo = function () {
  10012. var size;
  10013. // If the size is set by the user, the boundingInfo is computed from this value
  10014. if (this.size) {
  10015. size = this.size;
  10016. }
  10017. else {
  10018. size = new BABYLON.Size(0, 0);
  10019. }
  10020. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  10021. return true;
  10022. };
  10023. // Method called only on renderable groups to prepare the rendering
  10024. Group2D.prototype._prepareGroupRender = function (context) {
  10025. var sortedDirtyList = null;
  10026. // Update the Global Transformation and visibility status of the changed primitives
  10027. var rd = this._renderableData;
  10028. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  10029. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  10030. this.updateCachedStatesOf(sortedDirtyList, true);
  10031. }
  10032. var s = this.actualSize;
  10033. var a = this.actualScale;
  10034. var sw = Math.ceil(s.width * a.x);
  10035. var sh = Math.ceil(s.height * a.y);
  10036. // 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.
  10037. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  10038. if ((this instanceof BABYLON.Canvas2D || this.id === "__cachedCanvasGroup__") && this.owner.designSize != null) {
  10039. sw = this.owner.engine.getRenderWidth();
  10040. sh = this.owner.engine.getRenderHeight();
  10041. }
  10042. // Setup the size of the rendering viewport
  10043. // 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
  10044. if (!this._isCachedGroup) {
  10045. // Compute the WebGL viewport's location/size
  10046. var t = this._globalTransform.getTranslation();
  10047. var rs = this.owner._renderingSize;
  10048. sh = Math.min(sh, rs.height - t.y);
  10049. sw = Math.min(sw, rs.width - t.x);
  10050. var x = t.x;
  10051. var y = t.y;
  10052. // 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
  10053. this._viewportPosition.x = x;
  10054. this._viewportPosition.y = y;
  10055. }
  10056. // 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.
  10057. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  10058. context.forceRefreshPrimitive = true;
  10059. this._viewportSize.width = sw;
  10060. this._viewportSize.height = sh;
  10061. }
  10062. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  10063. // If the group is cached, set the dirty flag to true because of the incoming changes
  10064. this._cacheGroupDirty = this._isCachedGroup;
  10065. rd._primNewDirtyList.splice(0);
  10066. // If it's a force refresh, prepare all the children
  10067. if (context.forceRefreshPrimitive) {
  10068. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10069. var p = _a[_i];
  10070. p._prepareRender(context);
  10071. }
  10072. }
  10073. else {
  10074. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  10075. // the hierarchyDepth in order to prepare primitives from top to bottom
  10076. if (!sortedDirtyList) {
  10077. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  10078. }
  10079. sortedDirtyList.forEach(function (p) {
  10080. // 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.
  10081. // 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.
  10082. if (!p.isDisposed && p._needPrepare()) {
  10083. p._prepareRender(context);
  10084. }
  10085. });
  10086. }
  10087. // Everything is updated, clear the dirty list
  10088. rd._primDirtyList.forEach(function (p) {
  10089. if (rd._primNewDirtyList.indexOf(p) === -1) {
  10090. p._resetPropertiesDirty();
  10091. }
  10092. else {
  10093. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  10094. }
  10095. });
  10096. rd._primDirtyList.splice(0);
  10097. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  10098. }
  10099. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  10100. rd._childrenRenderableGroups.forEach(function (g) {
  10101. g._prepareGroupRender(context);
  10102. });
  10103. };
  10104. Group2D.prototype._groupRender = function () {
  10105. var _this = this;
  10106. var engine = this.owner.engine;
  10107. var failedCount = 0;
  10108. // First recurse to children render group to render them (in their cache or on screen)
  10109. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  10110. var childGroup = _a[_i];
  10111. childGroup._groupRender();
  10112. }
  10113. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  10114. if (!this.isCachedGroup || this._cacheGroupDirty) {
  10115. this.owner._addGroupRenderCount(1);
  10116. if (this.isCachedGroup) {
  10117. this._bindCacheTarget();
  10118. }
  10119. else {
  10120. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  10121. }
  10122. var curAlphaTest = engine.getAlphaTesting() === true;
  10123. var curDepthWrite = engine.getDepthWrite() === true;
  10124. // ===================================================================
  10125. // First pass, update the InstancedArray and render Opaque primitives
  10126. // Disable Alpha Testing, Enable Depth Write
  10127. engine.setAlphaTesting(false);
  10128. engine.setDepthWrite(true);
  10129. // For each different model of primitive to render
  10130. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  10131. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  10132. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  10133. var renderCount = _this._prepareContext(engine, context_1, v);
  10134. // If null is returned, there's no opaque data to render
  10135. if (renderCount === null) {
  10136. return;
  10137. }
  10138. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  10139. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  10140. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  10141. var renderFailed = !v.modelRenderCache.render(v, context_1);
  10142. // Update dirty flag/related
  10143. v.opaqueDirty = renderFailed;
  10144. failedCount += renderFailed ? 1 : 0;
  10145. }
  10146. });
  10147. // =======================================================================
  10148. // Second pass, update the InstancedArray and render AlphaTest primitives
  10149. // Enable Alpha Testing, Enable Depth Write
  10150. engine.setAlphaTesting(true);
  10151. engine.setDepthWrite(true);
  10152. // For each different model of primitive to render
  10153. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  10154. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  10155. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  10156. var renderCount = _this._prepareContext(engine, context_1, v);
  10157. // If null is returned, there's no opaque data to render
  10158. if (renderCount === null) {
  10159. return;
  10160. }
  10161. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  10162. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  10163. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  10164. var renderFailed = !v.modelRenderCache.render(v, context_1);
  10165. // Update dirty flag/related
  10166. v.opaqueDirty = renderFailed;
  10167. failedCount += renderFailed ? 1 : 0;
  10168. }
  10169. });
  10170. // =======================================================================
  10171. // Third pass, transparent primitive rendering
  10172. // Enable Alpha Testing, Disable Depth Write
  10173. engine.setAlphaTesting(true);
  10174. engine.setDepthWrite(false);
  10175. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  10176. if (this._renderableData._transparentListChanged) {
  10177. this._updateTransparentData();
  10178. }
  10179. // From this point on we have up to date data to render, so let's go
  10180. failedCount += this._renderTransparentData();
  10181. // =======================================================================
  10182. // Unbind target/restore viewport setting, clear dirty flag, and quit
  10183. // The group's content is no longer dirty
  10184. this._cacheGroupDirty = failedCount !== 0;
  10185. if (this.isCachedGroup) {
  10186. this._unbindCacheTarget();
  10187. }
  10188. else {
  10189. if (curVP) {
  10190. engine.setViewport(curVP);
  10191. }
  10192. }
  10193. // Restore saved states
  10194. engine.setAlphaTesting(curAlphaTest);
  10195. engine.setDepthWrite(curDepthWrite);
  10196. }
  10197. };
  10198. Group2D.prototype._setCacheGroupDirty = function () {
  10199. this._cacheGroupDirty = true;
  10200. };
  10201. Group2D.prototype._updateTransparentData = function () {
  10202. this.owner._addUpdateTransparentDataCount(1);
  10203. var rd = this._renderableData;
  10204. // Sort all the primitive from their depth, max (bottom) to min (top)
  10205. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  10206. var checkAndAddPrimInSegment = function (seg, tpiI) {
  10207. var tpi = rd._transparentPrimitives[tpiI];
  10208. // Fast rejection: if gii are different
  10209. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  10210. return false;
  10211. }
  10212. //let tpiZ = tpi._primitive.actualZOffset;
  10213. // We've made it so far, the tpi can be part of the segment, add it
  10214. tpi._transparentSegment = seg;
  10215. tpi._primitive._updateTransparentSegmentIndices(seg);
  10216. return true;
  10217. };
  10218. // Free the existing TransparentSegments
  10219. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  10220. var ts = _a[_i];
  10221. ts.dispose(this.owner.engine);
  10222. }
  10223. rd._transparentSegments.splice(0);
  10224. var prevSeg = null;
  10225. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  10226. var tpi = rd._transparentPrimitives[tpiI];
  10227. // Check if the Data in which the primitive is stored is not sorted properly
  10228. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  10229. tpi._groupInstanceInfo.sortTransparentData();
  10230. }
  10231. // Reset the segment, we have to create/rebuild it
  10232. tpi._transparentSegment = null;
  10233. // If there's a previous valid segment, check if this prim can be part of it
  10234. if (prevSeg) {
  10235. checkAndAddPrimInSegment(prevSeg, tpiI);
  10236. }
  10237. // If we couldn't insert in the adjacent segments, he have to create one
  10238. if (!tpi._transparentSegment) {
  10239. var ts = new BABYLON.TransparentSegment();
  10240. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  10241. var prim = tpi._primitive;
  10242. ts.startZ = prim.actualZOffset;
  10243. prim._updateTransparentSegmentIndices(ts);
  10244. ts.endZ = ts.startZ;
  10245. tpi._transparentSegment = ts;
  10246. rd._transparentSegments.push(ts);
  10247. }
  10248. // Update prevSeg
  10249. prevSeg = tpi._transparentSegment;
  10250. }
  10251. //rd._firstChangedPrim = null;
  10252. rd._transparentListChanged = false;
  10253. };
  10254. Group2D.prototype._renderTransparentData = function () {
  10255. var failedCount = 0;
  10256. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  10257. var rd = this._renderableData;
  10258. var useInstanced = this.owner.supportInstancedArray;
  10259. var length = rd._transparentSegments.length;
  10260. for (var i = 0; i < length; i++) {
  10261. context.instancedBuffers = null;
  10262. var ts = rd._transparentSegments[i];
  10263. var gii = ts.groupInsanceInfo;
  10264. var mrc = gii.modelRenderCache;
  10265. var engine = this.owner.engine;
  10266. var count = ts.endDataIndex - ts.startDataIndex;
  10267. // Use Instanced Array if it's supported and if there's at least minPartCountToUseInstancedArray prims to draw.
  10268. // We don't want to create an Instanced Buffer for less that minPartCountToUseInstancedArray prims
  10269. if (useInstanced && count >= this.owner.minPartCountToUseInstancedArray) {
  10270. if (!ts.partBuffers) {
  10271. var buffers = new Array();
  10272. for (var j = 0; j < gii.transparentData.length; j++) {
  10273. var gitd = gii.transparentData[j];
  10274. var dfa = gitd._partData;
  10275. var data = dfa.pack();
  10276. var stride = dfa.stride;
  10277. var neededSize = count * stride * 4;
  10278. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  10279. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  10280. engine.updateArrayBuffer(segData);
  10281. buffers.push(buffer);
  10282. }
  10283. ts.partBuffers = buffers;
  10284. }
  10285. else if (gii.transparentDirty) {
  10286. for (var j = 0; j < gii.transparentData.length; j++) {
  10287. var gitd = gii.transparentData[j];
  10288. var dfa = gitd._partData;
  10289. var data = dfa.pack();
  10290. var stride = dfa.stride;
  10291. var buffer = ts.partBuffers[j];
  10292. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  10293. engine.bindArrayBuffer(buffer);
  10294. engine.updateArrayBuffer(segData);
  10295. }
  10296. }
  10297. context.useInstancing = true;
  10298. context.instancesCount = count;
  10299. context.instancedBuffers = ts.partBuffers;
  10300. context.groupInfoPartData = gii.transparentData;
  10301. var renderFailed = !mrc.render(gii, context);
  10302. failedCount += renderFailed ? 1 : 0;
  10303. }
  10304. else {
  10305. context.useInstancing = false;
  10306. context.partDataStartIndex = ts.startDataIndex;
  10307. context.partDataEndIndex = ts.endDataIndex;
  10308. context.groupInfoPartData = gii.transparentData;
  10309. var renderFailed = !mrc.render(gii, context);
  10310. failedCount += renderFailed ? 1 : 0;
  10311. }
  10312. }
  10313. return failedCount;
  10314. };
  10315. Group2D.prototype._prepareContext = function (engine, context, gii) {
  10316. var gipd = null;
  10317. var setDirty;
  10318. var getDirty;
  10319. // Render Mode specifics
  10320. switch (context.renderMode) {
  10321. case BABYLON.Render2DContext.RenderModeOpaque:
  10322. {
  10323. if (!gii.hasOpaqueData) {
  10324. return null;
  10325. }
  10326. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  10327. getDirty = function () { return gii.opaqueDirty; };
  10328. context.groupInfoPartData = gii.opaqueData;
  10329. gipd = gii.opaqueData;
  10330. break;
  10331. }
  10332. case BABYLON.Render2DContext.RenderModeAlphaTest:
  10333. {
  10334. if (!gii.hasAlphaTestData) {
  10335. return null;
  10336. }
  10337. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  10338. getDirty = function () { return gii.alphaTestDirty; };
  10339. context.groupInfoPartData = gii.alphaTestData;
  10340. gipd = gii.alphaTestData;
  10341. break;
  10342. }
  10343. default:
  10344. throw new Error("_prepareContext is only for opaque or alphaTest");
  10345. }
  10346. var renderCount = 0;
  10347. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  10348. // Skip it if instanced arrays are not supported
  10349. if (this.owner.supportInstancedArray) {
  10350. // Flag for instancing
  10351. context.useInstancing = true;
  10352. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  10353. for (var i = 0; i < gipd.length; i++) {
  10354. var pid = gipd[i];
  10355. // If the instances of the model was changed, pack the data
  10356. var array = pid._partData;
  10357. var instanceData_1 = array.pack();
  10358. renderCount += array.usedElementCount;
  10359. // Compute the size the instance buffer should have
  10360. var neededSize = array.usedElementCount * array.stride * 4;
  10361. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  10362. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  10363. if (pid._partBuffer) {
  10364. engine.deleteInstancesBuffer(pid._partBuffer);
  10365. }
  10366. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  10367. pid._partBufferSize = neededSize;
  10368. setDirty(false);
  10369. // Update the WebGL buffer to match the new content of the instances data
  10370. engine.updateArrayBuffer(instanceData_1);
  10371. }
  10372. else if (getDirty()) {
  10373. // Update the WebGL buffer to match the new content of the instances data
  10374. engine.bindArrayBuffer(pid._partBuffer);
  10375. engine.updateArrayBuffer(instanceData_1);
  10376. }
  10377. }
  10378. setDirty(false);
  10379. }
  10380. else {
  10381. context.partDataStartIndex = 0;
  10382. // Find the first valid object to get the count
  10383. if (context.groupInfoPartData.length > 0) {
  10384. var i = 0;
  10385. while (!context.groupInfoPartData[i]) {
  10386. i++;
  10387. }
  10388. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  10389. }
  10390. }
  10391. return renderCount;
  10392. };
  10393. Group2D.prototype._setRenderingScale = function (scale) {
  10394. if (this._renderableData._renderingScale === scale) {
  10395. return;
  10396. }
  10397. this._renderableData._renderingScale = scale;
  10398. };
  10399. Group2D.prototype._bindCacheTarget = function () {
  10400. var curWidth;
  10401. var curHeight;
  10402. var rd = this._renderableData;
  10403. var rs = rd._renderingScale;
  10404. var noResizeScale = rd._noResizeOnScale;
  10405. var isCanvas = this.parent == null;
  10406. var scale;
  10407. if (noResizeScale) {
  10408. scale = isCanvas ? Group2D_1._uV : this.parent.actualScale;
  10409. }
  10410. else {
  10411. scale = this.actualScale;
  10412. }
  10413. if (isCanvas && this.owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS && this.owner.isScreenSpace) {
  10414. if (this.owner.designSize || this.owner.fitRenderingDevice) {
  10415. Group2D_1._s.width = this.owner.engine.getRenderWidth();
  10416. Group2D_1._s.height = this.owner.engine.getRenderHeight();
  10417. }
  10418. else {
  10419. Group2D_1._s.copyFrom(this.owner.size);
  10420. }
  10421. }
  10422. else {
  10423. Group2D_1._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  10424. Group2D_1._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  10425. }
  10426. var sizeChanged = !Group2D_1._s.equals(rd._cacheSize);
  10427. if (rd._cacheNode) {
  10428. var size = rd._cacheNode.contentSize;
  10429. // Check if we have to deallocate because the size is too small
  10430. if ((size.width < Group2D_1._s.width) || (size.height < Group2D_1._s.height)) {
  10431. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  10432. // For World space: no over-provisioning
  10433. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  10434. curWidth = Math.floor(Group2D_1._s.width * overprovisioning);
  10435. curHeight = Math.floor(Group2D_1._s.height * overprovisioning);
  10436. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  10437. rd._cacheTexture.freeRect(rd._cacheNode);
  10438. rd._cacheNode = null;
  10439. }
  10440. }
  10441. if (!rd._cacheNode) {
  10442. // Check if we have to allocate a rendering zone in the global cache texture
  10443. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  10444. rd._cacheNode = res.node;
  10445. rd._cacheTexture = res.texture;
  10446. if (rd._cacheRenderSprite) {
  10447. rd._cacheRenderSprite.dispose();
  10448. }
  10449. rd._cacheRenderSprite = res.sprite;
  10450. sizeChanged = true;
  10451. }
  10452. if (sizeChanged) {
  10453. rd._cacheSize.copyFrom(Group2D_1._s);
  10454. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  10455. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  10456. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  10457. }
  10458. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  10459. }
  10460. var n = rd._cacheNode;
  10461. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D_1._s, true);
  10462. };
  10463. Group2D.prototype._unbindCacheTarget = function () {
  10464. if (this._renderableData._cacheTexture) {
  10465. this._renderableData._cacheTexture.unbindTexture();
  10466. }
  10467. };
  10468. Group2D.prototype._spreadActualScaleDirty = function () {
  10469. if (this._renderableData && this._renderableData._cacheRenderSprite) {
  10470. this.handleGroupChanged(BABYLON.Prim2DBase.actualScaleProperty);
  10471. }
  10472. _super.prototype._spreadActualScaleDirty.call(this);
  10473. };
  10474. Group2D.prototype.handleGroupChanged = function (prop) {
  10475. // This method is only for cachedGroup
  10476. var rd = this._renderableData;
  10477. if (!rd) {
  10478. return;
  10479. }
  10480. var cachedSprite = rd._cacheRenderSprite;
  10481. if (!this.isCachedGroup || !cachedSprite) {
  10482. return;
  10483. }
  10484. // For now we only support these property changes
  10485. // TODO: add more! :)
  10486. switch (prop.id) {
  10487. case BABYLON.Prim2DBase.actualPositionProperty.id:
  10488. cachedSprite.actualPosition = this.actualPosition.clone();
  10489. if (cachedSprite.position != null) {
  10490. cachedSprite.position = cachedSprite.actualPosition.clone();
  10491. }
  10492. break;
  10493. case BABYLON.Prim2DBase.rotationProperty.id:
  10494. cachedSprite.rotation = this.rotation;
  10495. break;
  10496. case BABYLON.Prim2DBase.scaleProperty.id:
  10497. cachedSprite.scale = this.scale;
  10498. break;
  10499. case BABYLON.Prim2DBase.originProperty.id:
  10500. cachedSprite.origin = this.origin.clone();
  10501. break;
  10502. case Group2D_1.actualSizeProperty.id:
  10503. cachedSprite.size = this.actualSize.clone();
  10504. break;
  10505. }
  10506. };
  10507. Group2D.prototype.detectGroupStates = function () {
  10508. var isCanvas = this instanceof BABYLON.Canvas2D;
  10509. var canvasStrat = this.owner.cachingStrategy;
  10510. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  10511. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  10512. this._isRenderableGroup = isCanvas;
  10513. this._isCachedGroup = false;
  10514. }
  10515. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  10516. if (isCanvas) {
  10517. this._isRenderableGroup = true;
  10518. this._isCachedGroup = true;
  10519. }
  10520. else {
  10521. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  10522. this._isCachedGroup = false;
  10523. }
  10524. }
  10525. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  10526. if (isCanvas) {
  10527. this._isRenderableGroup = true;
  10528. this._isCachedGroup = false;
  10529. }
  10530. else {
  10531. if (this.hierarchyDepth === 1) {
  10532. this._isRenderableGroup = true;
  10533. this._isCachedGroup = true;
  10534. }
  10535. else {
  10536. this._isRenderableGroup = false;
  10537. this._isCachedGroup = false;
  10538. }
  10539. }
  10540. }
  10541. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  10542. if (isCanvas) {
  10543. this._isRenderableGroup = true;
  10544. this._isCachedGroup = false;
  10545. }
  10546. else {
  10547. var gcb = this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_OPTIONMASK;
  10548. if ((gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D_1.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  10549. this._isRenderableGroup = gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  10550. this._isCachedGroup = false;
  10551. }
  10552. if (gcb === Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  10553. this._isRenderableGroup = true;
  10554. this._isCachedGroup = true;
  10555. }
  10556. }
  10557. }
  10558. if (this._isRenderableGroup) {
  10559. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  10560. if (!this._renderableData) {
  10561. this._renderableData = new RenderableGroupData();
  10562. }
  10563. }
  10564. // If the group is tagged as renderable we add it to the renderable tree
  10565. if (this._isCachedGroup) {
  10566. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  10567. var cur = this.parent;
  10568. while (cur) {
  10569. if (cur instanceof Group2D_1 && cur._isRenderableGroup) {
  10570. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  10571. cur._renderableData._childrenRenderableGroups.push(this);
  10572. }
  10573. break;
  10574. }
  10575. cur = cur.parent;
  10576. }
  10577. }
  10578. };
  10579. Object.defineProperty(Group2D.prototype, "_cachedTexture", {
  10580. get: function () {
  10581. if (this._renderableData) {
  10582. return this._renderableData._cacheTexture;
  10583. }
  10584. return null;
  10585. },
  10586. enumerable: true,
  10587. configurable: true
  10588. });
  10589. return Group2D;
  10590. }(BABYLON.Prim2DBase));
  10591. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  10592. /**
  10593. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  10594. */
  10595. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  10596. /**
  10597. * When used, this group's content won't be cached, no matter which strategy used.
  10598. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  10599. */
  10600. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  10601. /**
  10602. * When used, the group's content will be cached in the nearest cached parent group/canvas
  10603. */
  10604. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  10605. /**
  10606. * 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
  10607. */
  10608. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  10609. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  10610. Group2D._uV = new BABYLON.Vector2(1, 1);
  10611. Group2D._s = BABYLON.Size.Zero();
  10612. Group2D._unS = new BABYLON.Vector2(1, 1);
  10613. __decorate([
  10614. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D_1.sizeProperty = pi; }, false, true)
  10615. ], Group2D.prototype, "size", null);
  10616. __decorate([
  10617. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D_1.actualSizeProperty = pi; })
  10618. ], Group2D.prototype, "actualSize", null);
  10619. Group2D = Group2D_1 = __decorate([
  10620. BABYLON.className("Group2D", "BABYLON")
  10621. ], Group2D);
  10622. BABYLON.Group2D = Group2D;
  10623. var RenderableGroupData = (function () {
  10624. function RenderableGroupData() {
  10625. this._primDirtyList = new Array();
  10626. this._primNewDirtyList = new Array();
  10627. this._childrenRenderableGroups = new Array();
  10628. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  10629. this._transparentPrimitives = new Array();
  10630. this._transparentSegments = new Array();
  10631. this._transparentListChanged = false;
  10632. this._cacheNode = null;
  10633. this._cacheTexture = null;
  10634. this._cacheRenderSprite = null;
  10635. this._renderingScale = 1;
  10636. this._cacheNodeUVs = null;
  10637. this._cacheNodeUVsChangedObservable = null;
  10638. this._cacheSize = BABYLON.Size.Zero();
  10639. this._useMipMap = false;
  10640. this._anisotropicLevel = 1;
  10641. this._noResizeOnScale = false;
  10642. }
  10643. RenderableGroupData.prototype.dispose = function (owner) {
  10644. var engine = owner.engine;
  10645. if (this._cacheRenderSprite) {
  10646. this._cacheRenderSprite.dispose();
  10647. this._cacheRenderSprite = null;
  10648. }
  10649. if (this._cacheTexture && this._cacheNode) {
  10650. this._cacheTexture.freeRect(this._cacheNode);
  10651. this._cacheTexture = null;
  10652. this._cacheNode = null;
  10653. }
  10654. if (this._primDirtyList) {
  10655. this._primDirtyList.splice(0);
  10656. this._primDirtyList = null;
  10657. }
  10658. if (this._renderGroupInstancesInfo) {
  10659. this._renderGroupInstancesInfo.forEach(function (k, v) {
  10660. v.dispose();
  10661. });
  10662. this._renderGroupInstancesInfo = null;
  10663. }
  10664. if (this._cacheNodeUVsChangedObservable) {
  10665. this._cacheNodeUVsChangedObservable.clear();
  10666. this._cacheNodeUVsChangedObservable = null;
  10667. }
  10668. if (this._transparentSegments) {
  10669. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  10670. var ts = _a[_i];
  10671. ts.dispose(engine);
  10672. }
  10673. this._transparentSegments.splice(0);
  10674. this._transparentSegments = null;
  10675. }
  10676. };
  10677. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  10678. var tpi = new TransparentPrimitiveInfo();
  10679. tpi._primitive = prim;
  10680. tpi._groupInstanceInfo = gii;
  10681. tpi._transparentSegment = null;
  10682. this._transparentPrimitives.push(tpi);
  10683. this._transparentListChanged = true;
  10684. return tpi;
  10685. };
  10686. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  10687. var index = this._transparentPrimitives.indexOf(tpi);
  10688. if (index !== -1) {
  10689. this._transparentPrimitives.splice(index, 1);
  10690. this._transparentListChanged = true;
  10691. }
  10692. };
  10693. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  10694. this._transparentListChanged = true;
  10695. //this.updateSmallestZChangedPrim(tpi);
  10696. };
  10697. return RenderableGroupData;
  10698. }());
  10699. BABYLON.RenderableGroupData = RenderableGroupData;
  10700. var TransparentPrimitiveInfo = (function () {
  10701. function TransparentPrimitiveInfo() {
  10702. }
  10703. return TransparentPrimitiveInfo;
  10704. }());
  10705. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  10706. var Group2D_1;
  10707. })(BABYLON || (BABYLON = {}));
  10708. //# sourceMappingURL=babylon.group2d.js.map
  10709. var __extends = (this && this.__extends) || function (d, b) {
  10710. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10711. function __() { this.constructor = d; }
  10712. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  10713. };
  10714. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  10715. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  10716. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  10717. 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;
  10718. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10719. };
  10720. var BABYLON;
  10721. (function (BABYLON) {
  10722. var WireFrame2DRenderCache = (function (_super) {
  10723. __extends(WireFrame2DRenderCache, _super);
  10724. function WireFrame2DRenderCache() {
  10725. var _this = _super !== null && _super.apply(this, arguments) || this;
  10726. _this.effectsReady = false;
  10727. _this.vb = null;
  10728. _this.vtxCount = 0;
  10729. _this.instancingAttributes = null;
  10730. _this.effect = null;
  10731. _this.effectInstanced = null;
  10732. return _this;
  10733. }
  10734. WireFrame2DRenderCache.prototype.render = function (instanceInfo, context) {
  10735. // Do nothing if the shader is still loading/preparing
  10736. if (!this.effectsReady) {
  10737. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  10738. return false;
  10739. }
  10740. this.effectsReady = true;
  10741. }
  10742. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  10743. var canvas = instanceInfo.owner.owner;
  10744. var engine = canvas.engine;
  10745. var cur = engine.getAlphaMode();
  10746. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  10747. engine.enableEffect(effect);
  10748. engine.bindBuffersDirectly(this.vb, null, [2, 4], 24, effect);
  10749. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  10750. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  10751. }
  10752. var pid = context.groupInfoPartData[0];
  10753. if (context.useInstancing) {
  10754. if (!this.instancingAttributes) {
  10755. this.instancingAttributes = this.loadInstancingAttributes(WireFrame2D.WIREFRAME2D_MAINPARTID, effect);
  10756. }
  10757. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  10758. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  10759. canvas._addDrawCallCount(1, context.renderMode);
  10760. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  10761. engine.drawUnIndexed(false, 0, this.vtxCount, count);
  10762. // engine.draw(true, 0, 6, count);
  10763. engine.unbindInstanceAttributes();
  10764. }
  10765. else {
  10766. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  10767. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  10768. this.setupUniforms(effect, 0, pid._partData, i);
  10769. engine.drawUnIndexed(false, 0, this.vtxCount);
  10770. }
  10771. }
  10772. engine.setAlphaMode(cur, true);
  10773. return true;
  10774. };
  10775. WireFrame2DRenderCache.prototype.updateModelRenderCache = function (prim) {
  10776. var w = prim;
  10777. w._updateVertexBuffer(this);
  10778. return true;
  10779. };
  10780. WireFrame2DRenderCache.prototype.dispose = function () {
  10781. if (!_super.prototype.dispose.call(this)) {
  10782. return false;
  10783. }
  10784. if (this.vb) {
  10785. this._engine._releaseBuffer(this.vb);
  10786. this.vb = null;
  10787. }
  10788. this.effect = null;
  10789. this.effectInstanced = null;
  10790. return true;
  10791. };
  10792. return WireFrame2DRenderCache;
  10793. }(BABYLON.ModelRenderCache));
  10794. BABYLON.WireFrame2DRenderCache = WireFrame2DRenderCache;
  10795. var WireFrameVertex2D = (function () {
  10796. function WireFrameVertex2D(p, c) {
  10797. if (c === void 0) { c = null; }
  10798. this.fromVector2(p);
  10799. if (c != null) {
  10800. this.fromColor4(c);
  10801. }
  10802. else {
  10803. this.r = this.g = this.b = this.a = 1;
  10804. }
  10805. }
  10806. WireFrameVertex2D.prototype.fromVector2 = function (p) {
  10807. this.x = p.x;
  10808. this.y = p.y;
  10809. };
  10810. WireFrameVertex2D.prototype.fromColor3 = function (c) {
  10811. this.r = c.r;
  10812. this.g = c.g;
  10813. this.b = c.b;
  10814. this.a = 1;
  10815. };
  10816. WireFrameVertex2D.prototype.fromColor4 = function (c) {
  10817. this.r = c.r;
  10818. this.g = c.g;
  10819. this.b = c.b;
  10820. this.a = c.a;
  10821. };
  10822. return WireFrameVertex2D;
  10823. }());
  10824. WireFrameVertex2D = __decorate([
  10825. BABYLON.className("WireFrameVertex2D", "BABYLON")
  10826. ], WireFrameVertex2D);
  10827. BABYLON.WireFrameVertex2D = WireFrameVertex2D;
  10828. var WireFrameGroup2D = (function () {
  10829. /**
  10830. * Construct a WireFrameGroup2D object
  10831. * @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.
  10832. * @param defaultColor specify the default color that will be used when a vertex is pushed, white will be used if not specified.
  10833. */
  10834. function WireFrameGroup2D(id, defaultColor) {
  10835. if (id === void 0) { id = null; }
  10836. if (defaultColor === void 0) { defaultColor = null; }
  10837. this._id = (id == null) ? BABYLON.Tools.RandomId() : id;
  10838. this._uid = BABYLON.Tools.RandomId();
  10839. this._defaultColor = (defaultColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : defaultColor;
  10840. this._buildingStrip = false;
  10841. this._vertices = new Array();
  10842. }
  10843. Object.defineProperty(WireFrameGroup2D.prototype, "uid", {
  10844. get: function () {
  10845. return this._uid;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(WireFrameGroup2D.prototype, "id", {
  10851. /**
  10852. * Retrieve the ID of the group
  10853. */
  10854. get: function () {
  10855. return this._id;
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. /**
  10861. * Push a vertex in the array of vertices.
  10862. * 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.
  10863. * @param p Position of the vertex
  10864. * @param c Color of the vertex, if null the default color of the group will be used
  10865. */
  10866. WireFrameGroup2D.prototype.pushVertex = function (p, c) {
  10867. if (c === void 0) { c = null; }
  10868. var v = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  10869. this._vertices.push(v);
  10870. if (this._buildingStrip) {
  10871. var v2 = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  10872. this._vertices.push(v2);
  10873. }
  10874. };
  10875. /**
  10876. * 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!!!
  10877. * @param p Position of the vertex
  10878. * @param c Color of the vertex, if null the default color of the group will be used
  10879. */
  10880. WireFrameGroup2D.prototype.startLineStrip = function (p, c) {
  10881. if (c === void 0) { c = null; }
  10882. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  10883. this._buildingStrip = true;
  10884. };
  10885. /**
  10886. * Close the Strip by storing a last vertex
  10887. * @param p Position of the vertex
  10888. * @param c Color of the vertex, if null the default color of the group will be used
  10889. */
  10890. WireFrameGroup2D.prototype.endLineStrip = function (p, c) {
  10891. if (c === void 0) { c = null; }
  10892. this._buildingStrip = false;
  10893. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  10894. };
  10895. Object.defineProperty(WireFrameGroup2D.prototype, "vertices", {
  10896. /**
  10897. * Access to the array of Vertices, you can manipulate its content but BEWARE of what you're doing!
  10898. */
  10899. get: function () {
  10900. return this._vertices;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. return WireFrameGroup2D;
  10906. }());
  10907. WireFrameGroup2D = __decorate([
  10908. BABYLON.className("WireFrameGroup2D", "BABYLON")
  10909. ], WireFrameGroup2D);
  10910. BABYLON.WireFrameGroup2D = WireFrameGroup2D;
  10911. var WireFrame2D = WireFrame2D_1 = (function (_super) {
  10912. __extends(WireFrame2D, _super);
  10913. /**
  10914. * Create an WireFrame 2D primitive
  10915. * @param wireFrameGroups an array of WireFrameGroup.
  10916. * @param settings a combination of settings, possible ones are
  10917. * - 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)
  10918. * - children: an array of direct children
  10919. * - id a text identifier, for information purpose
  10920. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  10921. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  10922. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  10923. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  10924. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  10925. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  10926. * - zOrder: override the zOrder with the specified value
  10927. * - origin: define the normalized origin point location, default [0.5;0.5]
  10928. * - alignToPixel: the rendered lines will be aligned to the rendering device' pixels
  10929. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  10930. * - 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.
  10931. * - 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.
  10932. * - 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!
  10933. * - 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.
  10934. * - 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).
  10935. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  10936. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10937. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10938. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10939. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10940. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  10941. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  10942. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  10943. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  10944. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10945. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10946. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10947. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10948. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  10949. */
  10950. function WireFrame2D(wireFrameGroups, settings) {
  10951. var _this = this;
  10952. if (!settings) {
  10953. settings = {};
  10954. }
  10955. _this = _super.call(this, settings) || this;
  10956. _this._wireFrameGroups = new BABYLON.StringDictionary();
  10957. for (var _i = 0, wireFrameGroups_1 = wireFrameGroups; _i < wireFrameGroups_1.length; _i++) {
  10958. var wfg = wireFrameGroups_1[_i];
  10959. _this._wireFrameGroups.add(wfg.id, wfg);
  10960. }
  10961. _this._vtxTransparent = false;
  10962. if (settings.size != null) {
  10963. _this.size = settings.size;
  10964. }
  10965. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  10966. return _this;
  10967. }
  10968. Object.defineProperty(WireFrame2D.prototype, "wireFrameGroups", {
  10969. get: function () {
  10970. return this._wireFrameGroups;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. /**
  10976. * If you change the content of the wireFrameGroups you MUST call this method for the changes to be reflected during rendering
  10977. */
  10978. WireFrame2D.prototype.wireFrameGroupsDirty = function () {
  10979. this._setFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  10980. this.onPrimBecomesDirty();
  10981. };
  10982. Object.defineProperty(WireFrame2D.prototype, "size", {
  10983. get: function () {
  10984. if (this._size == null) {
  10985. this._computeMinMaxTrans();
  10986. }
  10987. return this._size;
  10988. },
  10989. set: function (value) {
  10990. this.internalSetSize(value);
  10991. },
  10992. enumerable: true,
  10993. configurable: true
  10994. });
  10995. Object.defineProperty(WireFrame2D.prototype, "actualSize", {
  10996. get: function () {
  10997. if (this._actualSize) {
  10998. return this._actualSize;
  10999. }
  11000. return this.size;
  11001. },
  11002. set: function (value) {
  11003. if (!this._actualSize) {
  11004. this._actualSize.clone();
  11005. }
  11006. else {
  11007. this._actualSize.copyFrom(value);
  11008. }
  11009. },
  11010. enumerable: true,
  11011. configurable: true
  11012. });
  11013. WireFrame2D.prototype.updateLevelBoundingInfo = function () {
  11014. var v = this._computeMinMaxTrans();
  11015. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(v.x, v.z, v.y, v.w, this._levelBoundingInfo);
  11016. return true;
  11017. };
  11018. WireFrame2D.prototype.levelIntersect = function (intersectInfo) {
  11019. // TODO !
  11020. return true;
  11021. };
  11022. Object.defineProperty(WireFrame2D.prototype, "alignToPixel", {
  11023. /**
  11024. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  11025. */
  11026. get: function () {
  11027. return this._alignToPixel;
  11028. },
  11029. set: function (value) {
  11030. this._alignToPixel = value;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. WireFrame2D.prototype.createModelRenderCache = function (modelKey) {
  11036. var renderCache = new WireFrame2DRenderCache(this.owner.engine, modelKey);
  11037. return renderCache;
  11038. };
  11039. WireFrame2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  11040. var renderCache = modelRenderCache;
  11041. var engine = this.owner.engine;
  11042. // Create the VertexBuffer
  11043. this._updateVertexBuffer(renderCache);
  11044. // 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
  11045. var ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], true);
  11046. if (ei) {
  11047. renderCache.effectInstanced = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11048. }
  11049. ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], false);
  11050. renderCache.effect = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11051. return renderCache;
  11052. };
  11053. WireFrame2D.prototype._updateVertexBuffer = function (mrc) {
  11054. var engine = this.owner.engine;
  11055. if (mrc.vb != null) {
  11056. engine._releaseBuffer(mrc.vb);
  11057. }
  11058. var vtxCount = 0;
  11059. this._wireFrameGroups.forEach(function (k, v) { return vtxCount += v.vertices.length; });
  11060. var vb = new Float32Array(vtxCount * 6);
  11061. var i = 0;
  11062. this._wireFrameGroups.forEach(function (k, v) {
  11063. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  11064. var vtx = _a[_i];
  11065. vb[i++] = vtx.x;
  11066. vb[i++] = vtx.y;
  11067. vb[i++] = vtx.r;
  11068. vb[i++] = vtx.g;
  11069. vb[i++] = vtx.b;
  11070. vb[i++] = vtx.a;
  11071. }
  11072. });
  11073. mrc.vb = engine.createVertexBuffer(vb);
  11074. mrc.vtxCount = vtxCount;
  11075. };
  11076. WireFrame2D.prototype.refreshInstanceDataPart = function (part) {
  11077. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  11078. return false;
  11079. }
  11080. if (part.id === WireFrame2D_1.WIREFRAME2D_MAINPARTID) {
  11081. var d = this._instanceDataParts[0];
  11082. d.properties = new BABYLON.Vector3(this.alignToPixel ? 1 : 0, 2 / this.renderGroup.actualWidth, 2 / this.renderGroup.actualHeight);
  11083. }
  11084. return true;
  11085. };
  11086. WireFrame2D.prototype._computeMinMaxTrans = function () {
  11087. var xmin = Number.MAX_VALUE;
  11088. var xmax = Number.MIN_VALUE;
  11089. var ymin = Number.MAX_VALUE;
  11090. var ymax = Number.MIN_VALUE;
  11091. var transparent = false;
  11092. this._wireFrameGroups.forEach(function (k, v) {
  11093. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  11094. var vtx = _a[_i];
  11095. xmin = Math.min(xmin, vtx.x);
  11096. xmax = Math.max(xmax, vtx.x);
  11097. ymin = Math.min(ymin, vtx.y);
  11098. ymax = Math.max(ymax, vtx.y);
  11099. if (vtx.a < 1) {
  11100. transparent = true;
  11101. }
  11102. }
  11103. });
  11104. this._vtxTransparent = transparent;
  11105. this._size = new BABYLON.Size(xmax - xmin, ymax - ymin);
  11106. return new BABYLON.Vector4(xmin, ymin, xmax, ymax);
  11107. };
  11108. WireFrame2D.prototype.createInstanceDataParts = function () {
  11109. return [new WireFrame2DInstanceData(WireFrame2D_1.WIREFRAME2D_MAINPARTID)];
  11110. };
  11111. return WireFrame2D;
  11112. }(BABYLON.RenderablePrim2D));
  11113. WireFrame2D.WIREFRAME2D_MAINPARTID = 1;
  11114. __decorate([
  11115. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return WireFrame2D_1.wireFrameGroupsProperty = pi; })
  11116. ], WireFrame2D.prototype, "wireFrameGroups", null);
  11117. __decorate([
  11118. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return WireFrame2D_1.actualSizeProperty = pi; }, false, true)
  11119. ], WireFrame2D.prototype, "actualSize", null);
  11120. WireFrame2D = WireFrame2D_1 = __decorate([
  11121. BABYLON.className("WireFrame2D", "BABYLON")
  11122. ], WireFrame2D);
  11123. BABYLON.WireFrame2D = WireFrame2D;
  11124. var WireFrame2DInstanceData = (function (_super) {
  11125. __extends(WireFrame2DInstanceData, _super);
  11126. function WireFrame2DInstanceData(partId) {
  11127. return _super.call(this, partId, 1) || this;
  11128. }
  11129. Object.defineProperty(WireFrame2DInstanceData.prototype, "properties", {
  11130. // the properties is for now the alignedToPixel value
  11131. get: function () {
  11132. return null;
  11133. },
  11134. set: function (value) {
  11135. },
  11136. enumerable: true,
  11137. configurable: true
  11138. });
  11139. return WireFrame2DInstanceData;
  11140. }(BABYLON.InstanceDataBase));
  11141. __decorate([
  11142. BABYLON.instanceData()
  11143. ], WireFrame2DInstanceData.prototype, "properties", null);
  11144. BABYLON.WireFrame2DInstanceData = WireFrame2DInstanceData;
  11145. var WireFrame2D_1;
  11146. })(BABYLON || (BABYLON = {}));
  11147. //# sourceMappingURL=babylon.wireFrame2d.js.map
  11148. var __extends = (this && this.__extends) || function (d, b) {
  11149. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11150. function __() { this.constructor = d; }
  11151. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11152. };
  11153. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11154. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11155. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11156. 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;
  11157. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11158. };
  11159. var BABYLON;
  11160. (function (BABYLON) {
  11161. var Rectangle2DRenderCache = (function (_super) {
  11162. __extends(Rectangle2DRenderCache, _super);
  11163. function Rectangle2DRenderCache(engine, modelKey) {
  11164. var _this = _super.call(this, engine, modelKey) || this;
  11165. _this.effectsReady = false;
  11166. _this.fillVB = null;
  11167. _this.fillIB = null;
  11168. _this.fillIndicesCount = 0;
  11169. _this.instancingFillAttributes = null;
  11170. _this.effectFill = null;
  11171. _this.effectFillInstanced = null;
  11172. _this.borderVB = null;
  11173. _this.borderIB = null;
  11174. _this.borderIndicesCount = 0;
  11175. _this.instancingBorderAttributes = null;
  11176. _this.effectBorder = null;
  11177. _this.effectBorderInstanced = null;
  11178. return _this;
  11179. }
  11180. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  11181. // Do nothing if the shader is still loading/preparing
  11182. if (!this.effectsReady) {
  11183. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  11184. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  11185. return false;
  11186. }
  11187. this.effectsReady = true;
  11188. }
  11189. var canvas = instanceInfo.owner.owner;
  11190. var engine = canvas.engine;
  11191. var depthFunction = 0;
  11192. if (this.effectFill && this.effectBorder) {
  11193. depthFunction = engine.getDepthFunction();
  11194. engine.setDepthFunctionToLessOrEqual();
  11195. }
  11196. var curAlphaMode = engine.getAlphaMode();
  11197. if (this.effectFill) {
  11198. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  11199. var pid = context.groupInfoPartData[partIndex];
  11200. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11201. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11202. }
  11203. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  11204. engine.enableEffect(effect);
  11205. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  11206. if (context.useInstancing) {
  11207. if (!this.instancingFillAttributes) {
  11208. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  11209. }
  11210. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11211. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11212. canvas._addDrawCallCount(1, context.renderMode);
  11213. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  11214. engine.draw(true, 0, this.fillIndicesCount, count);
  11215. engine.unbindInstanceAttributes();
  11216. }
  11217. else {
  11218. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11219. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11220. this.setupUniforms(effect, partIndex, pid._partData, i);
  11221. engine.draw(true, 0, this.fillIndicesCount);
  11222. }
  11223. }
  11224. }
  11225. if (this.effectBorder) {
  11226. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  11227. var pid = context.groupInfoPartData[partIndex];
  11228. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11229. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11230. }
  11231. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  11232. engine.enableEffect(effect);
  11233. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  11234. if (context.useInstancing) {
  11235. if (!this.instancingBorderAttributes) {
  11236. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  11237. }
  11238. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11239. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11240. canvas._addDrawCallCount(1, context.renderMode);
  11241. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  11242. engine.draw(true, 0, this.borderIndicesCount, count);
  11243. engine.unbindInstanceAttributes();
  11244. }
  11245. else {
  11246. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11247. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11248. this.setupUniforms(effect, partIndex, pid._partData, i);
  11249. engine.draw(true, 0, this.borderIndicesCount);
  11250. }
  11251. }
  11252. }
  11253. engine.setAlphaMode(curAlphaMode, true);
  11254. if (this.effectFill && this.effectBorder) {
  11255. engine.setDepthFunction(depthFunction);
  11256. }
  11257. return true;
  11258. };
  11259. Rectangle2DRenderCache.prototype.dispose = function () {
  11260. if (!_super.prototype.dispose.call(this)) {
  11261. return false;
  11262. }
  11263. if (this.fillVB) {
  11264. this._engine._releaseBuffer(this.fillVB);
  11265. this.fillVB = null;
  11266. }
  11267. if (this.fillIB) {
  11268. this._engine._releaseBuffer(this.fillIB);
  11269. this.fillIB = null;
  11270. }
  11271. this.effectFill = null;
  11272. this.effectFillInstanced = null;
  11273. this.effectBorder = null;
  11274. this.effectBorderInstanced = null;
  11275. if (this.borderVB) {
  11276. this._engine._releaseBuffer(this.borderVB);
  11277. this.borderVB = null;
  11278. }
  11279. if (this.borderIB) {
  11280. this._engine._releaseBuffer(this.borderIB);
  11281. this.borderIB = null;
  11282. }
  11283. return true;
  11284. };
  11285. return Rectangle2DRenderCache;
  11286. }(BABYLON.ModelRenderCache));
  11287. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  11288. var Rectangle2DInstanceData = (function (_super) {
  11289. __extends(Rectangle2DInstanceData, _super);
  11290. function Rectangle2DInstanceData(partId) {
  11291. return _super.call(this, partId, 1) || this;
  11292. }
  11293. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  11294. get: function () {
  11295. return null;
  11296. },
  11297. set: function (value) {
  11298. },
  11299. enumerable: true,
  11300. configurable: true
  11301. });
  11302. return Rectangle2DInstanceData;
  11303. }(BABYLON.Shape2DInstanceData));
  11304. __decorate([
  11305. BABYLON.instanceData()
  11306. ], Rectangle2DInstanceData.prototype, "properties", null);
  11307. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  11308. var Rectangle2D = Rectangle2D_1 = (function (_super) {
  11309. __extends(Rectangle2D, _super);
  11310. /**
  11311. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  11312. * @param settings a combination of settings, possible ones are
  11313. * - 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)
  11314. * - children: an array of direct children
  11315. * - id a text identifier, for information purpose
  11316. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  11317. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  11318. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  11319. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  11320. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  11321. * - zOrder: override the zOrder with the specified value
  11322. * - origin: define the normalized origin point location, default [0.5;0.5]
  11323. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  11324. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  11325. * - 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)
  11326. * - 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)
  11327. * - borderThickness: the thickness of the drawn border, default is 1.
  11328. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  11329. * - 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.
  11330. * - 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.
  11331. * - 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!
  11332. * - 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.
  11333. * - 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).
  11334. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  11335. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11336. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11337. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11338. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11339. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  11340. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  11341. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  11342. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  11343. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11344. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11345. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11346. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11347. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  11348. */
  11349. function Rectangle2D(settings) {
  11350. var _this = this;
  11351. // Avoid checking every time if the object exists
  11352. if (settings == null) {
  11353. settings = {};
  11354. }
  11355. _this = _super.call(this, settings) || this;
  11356. if (settings.size != null) {
  11357. _this.size = settings.size;
  11358. }
  11359. else if (settings.width || settings.height) {
  11360. var size = new BABYLON.Size(settings.width, settings.height);
  11361. _this.size = size;
  11362. }
  11363. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  11364. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  11365. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  11366. //this.size = size;
  11367. _this.roundRadius = roundRadius;
  11368. _this.borderThickness = borderThickness;
  11369. return _this;
  11370. }
  11371. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  11372. get: function () {
  11373. if (this._actualSize) {
  11374. return this._actualSize;
  11375. }
  11376. return this.size;
  11377. },
  11378. set: function (value) {
  11379. if (!this._actualSize) {
  11380. this._actualSize = value.clone();
  11381. }
  11382. else {
  11383. this._actualSize.copyFrom(value);
  11384. }
  11385. },
  11386. enumerable: true,
  11387. configurable: true
  11388. });
  11389. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  11390. get: function () {
  11391. return this._notRounded;
  11392. },
  11393. set: function (value) {
  11394. this._notRounded = value;
  11395. },
  11396. enumerable: true,
  11397. configurable: true
  11398. });
  11399. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  11400. get: function () {
  11401. return this._roundRadius;
  11402. },
  11403. set: function (value) {
  11404. this._roundRadius = value;
  11405. this.notRounded = value === 0;
  11406. this._positioningDirty();
  11407. },
  11408. enumerable: true,
  11409. configurable: true
  11410. });
  11411. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  11412. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  11413. if (this.notRounded) {
  11414. return true;
  11415. }
  11416. // 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.
  11417. // 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)
  11418. // 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.
  11419. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  11420. var size = this.size;
  11421. Rectangle2D_1._i0.x = intersectInfo._localPickPosition.x;
  11422. Rectangle2D_1._i0.y = intersectInfo._localPickPosition.y;
  11423. var rr = this.roundRadius;
  11424. var rrs = rr * rr;
  11425. // Check if the point is in the bottom/left quarter area
  11426. Rectangle2D_1._i1.x = rr;
  11427. Rectangle2D_1._i1.y = rr;
  11428. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  11429. // Compute the intersection point in the quarter local space
  11430. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11431. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11432. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11433. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11434. }
  11435. // Check if the point is in the top/left quarter area
  11436. Rectangle2D_1._i1.x = rr;
  11437. Rectangle2D_1._i1.y = size.height - rr;
  11438. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  11439. // Compute the intersection point in the quarter local space
  11440. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11441. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11442. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11443. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11444. }
  11445. // Check if the point is in the top/right quarter area
  11446. Rectangle2D_1._i1.x = size.width - rr;
  11447. Rectangle2D_1._i1.y = size.height - rr;
  11448. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  11449. // Compute the intersection point in the quarter local space
  11450. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11451. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11452. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11453. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11454. }
  11455. // Check if the point is in the bottom/right quarter area
  11456. Rectangle2D_1._i1.x = size.width - rr;
  11457. Rectangle2D_1._i1.y = rr;
  11458. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  11459. // Compute the intersection point in the quarter local space
  11460. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11461. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11462. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11463. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11464. }
  11465. // At any other locations the point is guarantied to be inside
  11466. return true;
  11467. };
  11468. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  11469. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  11470. return true;
  11471. };
  11472. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  11473. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  11474. return renderCache;
  11475. };
  11476. Rectangle2D.prototype.updateTriArray = function () {
  11477. // Not Rounded = sharp edge rect, the default implementation is the right one!
  11478. if (this.notRounded) {
  11479. _super.prototype.updateTriArray.call(this);
  11480. return;
  11481. }
  11482. // Rounded Corner? It's more complicated! :)
  11483. var subDiv = Rectangle2D_1.roundSubdivisions * 4;
  11484. if (this._primTriArray == null) {
  11485. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  11486. }
  11487. else {
  11488. this._primTriArray.clear(subDiv);
  11489. }
  11490. var size = this.actualSize;
  11491. var w = size.width;
  11492. var h = size.height;
  11493. var r = this.roundRadius;
  11494. var rsub0 = subDiv * 0.25;
  11495. var rsub1 = subDiv * 0.50;
  11496. var rsub2 = subDiv * 0.75;
  11497. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  11498. var twopi = Math.PI * 2;
  11499. var nru = r / w;
  11500. var nrv = r / h;
  11501. var computePos = function (index, p) {
  11502. // right/bottom
  11503. if (index < rsub0) {
  11504. p.x = 1.0 - nru;
  11505. p.y = nrv;
  11506. }
  11507. else if (index < rsub1) {
  11508. p.x = nru;
  11509. p.y = nrv;
  11510. }
  11511. else if (index < rsub2) {
  11512. p.x = nru;
  11513. p.y = 1.0 - nrv;
  11514. }
  11515. else {
  11516. p.x = 1.0 - nru;
  11517. p.y = 1.0 - nrv;
  11518. }
  11519. var angle = twopi - (index * twopi / (subDiv - 0.5));
  11520. p.x += Math.cos(angle) * nru;
  11521. p.y += Math.sin(angle) * nrv;
  11522. p.x *= w;
  11523. p.y *= h;
  11524. };
  11525. console.log("Genetre TriList for " + this.id);
  11526. var first = BABYLON.Vector2.Zero();
  11527. var cur = BABYLON.Vector2.Zero();
  11528. computePos(0, first);
  11529. var prev = first.clone();
  11530. for (var index = 1; index < subDiv; index++) {
  11531. computePos(index, cur);
  11532. this._primTriArray.storeTriangle(index - 1, center, prev, cur);
  11533. console.log(index - 1 + ", " + center + ", " + prev + ", " + cur);
  11534. prev.copyFrom(cur);
  11535. }
  11536. this._primTriArray.storeTriangle(subDiv - 1, center, first, prev);
  11537. console.log(subDiv - 1 + ", " + center + ", " + prev + ", " + first);
  11538. };
  11539. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  11540. var renderCache = modelRenderCache;
  11541. var engine = this.owner.engine;
  11542. // Need to create WebGL resources for fill part?
  11543. if (this.fill) {
  11544. var vbSize = ((this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4) + 1;
  11545. var vb = new Float32Array(vbSize);
  11546. for (var i = 0; i < vbSize; i++) {
  11547. vb[i] = i;
  11548. }
  11549. renderCache.fillVB = engine.createVertexBuffer(vb);
  11550. var triCount = vbSize - 1;
  11551. var ib = new Float32Array(triCount * 3);
  11552. for (var i = 0; i < triCount; i++) {
  11553. ib[i * 3 + 0] = 0;
  11554. ib[i * 3 + 2] = i + 1;
  11555. ib[i * 3 + 1] = i + 2;
  11556. }
  11557. ib[triCount * 3 - 2] = 1;
  11558. renderCache.fillIB = engine.createIndexBuffer(ib);
  11559. renderCache.fillIndicesCount = triCount * 3;
  11560. // 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
  11561. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  11562. if (ei) {
  11563. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11564. }
  11565. // Get the non instanced version
  11566. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  11567. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11568. }
  11569. // Need to create WebGL resource for border part?
  11570. if (this.border) {
  11571. var vbSize = (this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4 * 2;
  11572. var vb = new Float32Array(vbSize);
  11573. for (var i = 0; i < vbSize; i++) {
  11574. vb[i] = i;
  11575. }
  11576. renderCache.borderVB = engine.createVertexBuffer(vb);
  11577. var triCount = vbSize;
  11578. var rs = triCount / 2;
  11579. var ib = new Float32Array(triCount * 3);
  11580. for (var i = 0; i < rs; i++) {
  11581. var r0 = i;
  11582. var r1 = (i + 1) % rs;
  11583. ib[i * 6 + 0] = rs + r1;
  11584. ib[i * 6 + 1] = rs + r0;
  11585. ib[i * 6 + 2] = r0;
  11586. ib[i * 6 + 3] = r1;
  11587. ib[i * 6 + 4] = rs + r1;
  11588. ib[i * 6 + 5] = r0;
  11589. }
  11590. renderCache.borderIB = engine.createIndexBuffer(ib);
  11591. renderCache.borderIndicesCount = triCount * 3;
  11592. // 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
  11593. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  11594. if (ei) {
  11595. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11596. }
  11597. // Get the non instanced version
  11598. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  11599. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11600. }
  11601. return renderCache;
  11602. };
  11603. // 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
  11604. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  11605. // Fall back to default implementation if there's no round Radius
  11606. if (this._notRounded) {
  11607. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  11608. }
  11609. else {
  11610. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  11611. initialContentPosition.x = initialContentPosition.y = rr;
  11612. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  11613. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  11614. initialContentPosition.z = primSize.width - (initialContentPosition.x + initialContentArea.width);
  11615. initialContentPosition.w = primSize.height - (initialContentPosition.y + initialContentArea.height);
  11616. }
  11617. };
  11618. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  11619. // Fall back to default implementation if there's no round Radius
  11620. if (this._notRounded) {
  11621. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  11622. }
  11623. else {
  11624. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  11625. newPrimSize.copyFrom(primSize);
  11626. newPrimSize.width += rr * 2;
  11627. newPrimSize.height += rr * 2;
  11628. }
  11629. };
  11630. Rectangle2D.prototype.createInstanceDataParts = function () {
  11631. var res = new Array();
  11632. if (this.border) {
  11633. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  11634. }
  11635. if (this.fill) {
  11636. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  11637. }
  11638. return res;
  11639. };
  11640. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  11641. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  11642. return false;
  11643. }
  11644. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  11645. var d = part;
  11646. var size = this.actualSize;
  11647. var s = this.actualScale;
  11648. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  11649. }
  11650. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  11651. var d = part;
  11652. var size = this.actualSize;
  11653. var s = this.actualScale;
  11654. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  11655. }
  11656. return true;
  11657. };
  11658. return Rectangle2D;
  11659. }(BABYLON.Shape2D));
  11660. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  11661. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  11662. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  11663. Rectangle2D.roundSubdivisions = 16;
  11664. __decorate([
  11665. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D_1.actualSizeProperty = pi; }, false, true)
  11666. ], Rectangle2D.prototype, "actualSize", null);
  11667. __decorate([
  11668. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D_1.notRoundedProperty = pi; })
  11669. ], Rectangle2D.prototype, "notRounded", null);
  11670. __decorate([
  11671. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D_1.roundRadiusProperty = pi; })
  11672. ], Rectangle2D.prototype, "roundRadius", null);
  11673. Rectangle2D = Rectangle2D_1 = __decorate([
  11674. BABYLON.className("Rectangle2D", "BABYLON")
  11675. ], Rectangle2D);
  11676. BABYLON.Rectangle2D = Rectangle2D;
  11677. var Rectangle2D_1;
  11678. })(BABYLON || (BABYLON = {}));
  11679. var __extends = (this && this.__extends) || function (d, b) {
  11680. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11681. function __() { this.constructor = d; }
  11682. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11683. };
  11684. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11685. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11686. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11687. 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;
  11688. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11689. };
  11690. var BABYLON;
  11691. (function (BABYLON) {
  11692. var Ellipse2DRenderCache = (function (_super) {
  11693. __extends(Ellipse2DRenderCache, _super);
  11694. function Ellipse2DRenderCache(engine, modelKey) {
  11695. var _this = _super.call(this, engine, modelKey) || this;
  11696. _this.effectsReady = false;
  11697. _this.fillVB = null;
  11698. _this.fillIB = null;
  11699. _this.fillIndicesCount = 0;
  11700. _this.instancingFillAttributes = null;
  11701. _this.effectFillInstanced = null;
  11702. _this.effectFill = null;
  11703. _this.borderVB = null;
  11704. _this.borderIB = null;
  11705. _this.borderIndicesCount = 0;
  11706. _this.instancingBorderAttributes = null;
  11707. _this.effectBorderInstanced = null;
  11708. _this.effectBorder = null;
  11709. return _this;
  11710. }
  11711. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  11712. // Do nothing if the shader is still loading/preparing
  11713. if (!this.effectsReady) {
  11714. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  11715. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  11716. return false;
  11717. }
  11718. this.effectsReady = true;
  11719. }
  11720. var canvas = instanceInfo.owner.owner;
  11721. var engine = canvas.engine;
  11722. var depthFunction = 0;
  11723. if (this.effectFill && this.effectBorder) {
  11724. depthFunction = engine.getDepthFunction();
  11725. engine.setDepthFunctionToLessOrEqual();
  11726. }
  11727. var curAlphaMode = engine.getAlphaMode();
  11728. if (this.effectFill) {
  11729. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  11730. var pid = context.groupInfoPartData[partIndex];
  11731. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11732. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11733. }
  11734. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  11735. engine.enableEffect(effect);
  11736. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  11737. if (context.useInstancing) {
  11738. if (!this.instancingFillAttributes) {
  11739. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  11740. }
  11741. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11742. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11743. canvas._addDrawCallCount(1, context.renderMode);
  11744. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  11745. engine.draw(true, 0, this.fillIndicesCount, count);
  11746. engine.unbindInstanceAttributes();
  11747. }
  11748. else {
  11749. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11750. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11751. this.setupUniforms(effect, partIndex, pid._partData, i);
  11752. engine.draw(true, 0, this.fillIndicesCount);
  11753. }
  11754. }
  11755. }
  11756. if (this.effectBorder) {
  11757. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  11758. var pid = context.groupInfoPartData[partIndex];
  11759. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11760. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11761. }
  11762. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  11763. engine.enableEffect(effect);
  11764. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  11765. if (context.useInstancing) {
  11766. if (!this.instancingBorderAttributes) {
  11767. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  11768. }
  11769. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11770. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11771. canvas._addDrawCallCount(1, context.renderMode);
  11772. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  11773. engine.draw(true, 0, this.borderIndicesCount, count);
  11774. engine.unbindInstanceAttributes();
  11775. }
  11776. else {
  11777. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11778. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11779. this.setupUniforms(effect, partIndex, pid._partData, i);
  11780. engine.draw(true, 0, this.borderIndicesCount);
  11781. }
  11782. }
  11783. }
  11784. engine.setAlphaMode(curAlphaMode, true);
  11785. if (this.effectFill && this.effectBorder) {
  11786. engine.setDepthFunction(depthFunction);
  11787. }
  11788. return true;
  11789. };
  11790. Ellipse2DRenderCache.prototype.dispose = function () {
  11791. if (!_super.prototype.dispose.call(this)) {
  11792. return false;
  11793. }
  11794. if (this.fillVB) {
  11795. this._engine._releaseBuffer(this.fillVB);
  11796. this.fillVB = null;
  11797. }
  11798. if (this.fillIB) {
  11799. this._engine._releaseBuffer(this.fillIB);
  11800. this.fillIB = null;
  11801. }
  11802. this.effectFill = null;
  11803. this.effectFillInstanced = null;
  11804. this.effectBorder = null;
  11805. this.effectBorderInstanced = null;
  11806. if (this.borderVB) {
  11807. this._engine._releaseBuffer(this.borderVB);
  11808. this.borderVB = null;
  11809. }
  11810. if (this.borderIB) {
  11811. this._engine._releaseBuffer(this.borderIB);
  11812. this.borderIB = null;
  11813. }
  11814. return true;
  11815. };
  11816. return Ellipse2DRenderCache;
  11817. }(BABYLON.ModelRenderCache));
  11818. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  11819. var Ellipse2DInstanceData = (function (_super) {
  11820. __extends(Ellipse2DInstanceData, _super);
  11821. function Ellipse2DInstanceData(partId) {
  11822. return _super.call(this, partId, 1) || this;
  11823. }
  11824. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  11825. get: function () {
  11826. return null;
  11827. },
  11828. set: function (value) {
  11829. },
  11830. enumerable: true,
  11831. configurable: true
  11832. });
  11833. return Ellipse2DInstanceData;
  11834. }(BABYLON.Shape2DInstanceData));
  11835. __decorate([
  11836. BABYLON.instanceData()
  11837. ], Ellipse2DInstanceData.prototype, "properties", null);
  11838. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  11839. var Ellipse2D = Ellipse2D_1 = (function (_super) {
  11840. __extends(Ellipse2D, _super);
  11841. /**
  11842. * Create an Ellipse 2D Shape primitive
  11843. * @param settings a combination of settings, possible ones are
  11844. * - 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)
  11845. * - children: an array of direct children
  11846. * - id: a text identifier, for information purpose
  11847. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  11848. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  11849. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  11850. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  11851. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  11852. * - zOrder: override the zOrder with the specified value
  11853. * - origin: define the normalized origin point location, default [0.5;0.5]
  11854. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  11855. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  11856. * - 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)
  11857. * - 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)
  11858. * - borderThickness: the thickness of the drawn border, default is 1.
  11859. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  11860. * - 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.
  11861. * - 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.
  11862. * - 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!
  11863. * - 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.
  11864. * - 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).
  11865. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  11866. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11867. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11868. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11869. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11870. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  11871. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  11872. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  11873. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  11874. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11875. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11876. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11877. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11878. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  11879. */
  11880. function Ellipse2D(settings) {
  11881. var _this = this;
  11882. // Avoid checking every time if the object exists
  11883. if (settings == null) {
  11884. settings = {};
  11885. }
  11886. _this = _super.call(this, settings) || this;
  11887. if (settings.size != null) {
  11888. _this.size = settings.size;
  11889. }
  11890. else if (settings.width || settings.height) {
  11891. var size = new BABYLON.Size(settings.width, settings.height);
  11892. _this.size = size;
  11893. }
  11894. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  11895. _this.subdivisions = sub;
  11896. return _this;
  11897. }
  11898. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  11899. get: function () {
  11900. if (this._actualSize) {
  11901. return this._actualSize;
  11902. }
  11903. return this.size;
  11904. },
  11905. set: function (value) {
  11906. this._actualSize = value;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  11912. get: function () {
  11913. return this._subdivisions;
  11914. },
  11915. set: function (value) {
  11916. this._subdivisions = value;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  11922. var w = this.size.width / 2;
  11923. var h = this.size.height / 2;
  11924. var x = intersectInfo._localPickPosition.x - w;
  11925. var y = intersectInfo._localPickPosition.y - h;
  11926. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  11927. };
  11928. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  11929. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  11930. return true;
  11931. };
  11932. Ellipse2D.prototype.updateTriArray = function () {
  11933. var subDiv = this._subdivisions;
  11934. if (this._primTriArray == null) {
  11935. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  11936. }
  11937. else {
  11938. this._primTriArray.clear(subDiv);
  11939. }
  11940. var size = this.actualSize;
  11941. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  11942. var v1 = BABYLON.Vector2.Zero();
  11943. var v2 = BABYLON.Vector2.Zero();
  11944. for (var i = 0; i < subDiv; i++) {
  11945. var angle1 = Math.PI * 2 * (i - 1) / subDiv;
  11946. var angle2 = Math.PI * 2 * i / subDiv;
  11947. v1.x = ((Math.cos(angle1) / 2.0) + 0.5) * size.width;
  11948. v1.y = ((Math.sin(angle1) / 2.0) + 0.5) * size.height;
  11949. v2.x = ((Math.cos(angle2) / 2.0) + 0.5) * size.width;
  11950. v2.y = ((Math.sin(angle2) / 2.0) + 0.5) * size.height;
  11951. this._primTriArray.storeTriangle(i, center, v1, v2);
  11952. }
  11953. };
  11954. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  11955. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  11956. return renderCache;
  11957. };
  11958. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  11959. var renderCache = modelRenderCache;
  11960. var engine = this.owner.engine;
  11961. // Need to create WebGL resources for fill part?
  11962. if (this.fill) {
  11963. var vbSize = this.subdivisions + 1;
  11964. var vb = new Float32Array(vbSize);
  11965. for (var i = 0; i < vbSize; i++) {
  11966. vb[i] = i;
  11967. }
  11968. renderCache.fillVB = engine.createVertexBuffer(vb);
  11969. var triCount = vbSize - 1;
  11970. var ib = new Float32Array(triCount * 3);
  11971. for (var i = 0; i < triCount; i++) {
  11972. ib[i * 3 + 0] = 0;
  11973. ib[i * 3 + 2] = i + 2;
  11974. ib[i * 3 + 1] = i + 1;
  11975. }
  11976. ib[triCount * 3 - 1] = 1;
  11977. renderCache.fillIB = engine.createIndexBuffer(ib);
  11978. renderCache.fillIndicesCount = triCount * 3;
  11979. // 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
  11980. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  11981. if (ei) {
  11982. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  11983. }
  11984. // Get the non instanced version
  11985. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  11986. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  11987. }
  11988. // Need to create WebGL resource for border part?
  11989. if (this.border) {
  11990. var vbSize = this.subdivisions * 2;
  11991. var vb = new Float32Array(vbSize);
  11992. for (var i = 0; i < vbSize; i++) {
  11993. vb[i] = i;
  11994. }
  11995. renderCache.borderVB = engine.createVertexBuffer(vb);
  11996. var triCount = vbSize;
  11997. var rs = triCount / 2;
  11998. var ib = new Float32Array(triCount * 3);
  11999. for (var i = 0; i < rs; i++) {
  12000. var r0 = i;
  12001. var r1 = (i + 1) % rs;
  12002. ib[i * 6 + 0] = rs + r1;
  12003. ib[i * 6 + 1] = rs + r0;
  12004. ib[i * 6 + 2] = r0;
  12005. ib[i * 6 + 3] = r1;
  12006. ib[i * 6 + 4] = rs + r1;
  12007. ib[i * 6 + 5] = r0;
  12008. }
  12009. renderCache.borderIB = engine.createIndexBuffer(ib);
  12010. renderCache.borderIndicesCount = (triCount * 3);
  12011. // 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
  12012. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  12013. if (ei) {
  12014. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12015. }
  12016. // Get the non instanced version
  12017. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  12018. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12019. }
  12020. return renderCache;
  12021. };
  12022. Ellipse2D.prototype.createInstanceDataParts = function () {
  12023. var res = new Array();
  12024. if (this.border) {
  12025. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  12026. }
  12027. if (this.fill) {
  12028. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  12029. }
  12030. return res;
  12031. };
  12032. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  12033. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  12034. return false;
  12035. }
  12036. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  12037. var d = part;
  12038. var size = this.actualSize;
  12039. var s = this.actualScale;
  12040. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  12041. }
  12042. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  12043. var d = part;
  12044. var size = this.actualSize;
  12045. var s = this.actualScale;
  12046. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  12047. }
  12048. return true;
  12049. };
  12050. return Ellipse2D;
  12051. }(BABYLON.Shape2D));
  12052. __decorate([
  12053. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D_1.acutalSizeProperty = pi; }, false, true)
  12054. ], Ellipse2D.prototype, "actualSize", null);
  12055. __decorate([
  12056. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D_1.subdivisionsProperty = pi; })
  12057. ], Ellipse2D.prototype, "subdivisions", null);
  12058. Ellipse2D = Ellipse2D_1 = __decorate([
  12059. BABYLON.className("Ellipse2D", "BABYLON")
  12060. ], Ellipse2D);
  12061. BABYLON.Ellipse2D = Ellipse2D;
  12062. var Ellipse2D_1;
  12063. })(BABYLON || (BABYLON = {}));
  12064. var __extends = (this && this.__extends) || function (d, b) {
  12065. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12066. function __() { this.constructor = d; }
  12067. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12068. };
  12069. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12070. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12071. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12072. 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;
  12073. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12074. };
  12075. var BABYLON;
  12076. (function (BABYLON) {
  12077. var Sprite2DRenderCache = (function (_super) {
  12078. __extends(Sprite2DRenderCache, _super);
  12079. function Sprite2DRenderCache() {
  12080. var _this = _super !== null && _super.apply(this, arguments) || this;
  12081. _this.effectsReady = false;
  12082. _this.vb = null;
  12083. _this.ib = null;
  12084. _this.instancingAttributes = null;
  12085. _this.texture = null;
  12086. _this.effect = null;
  12087. _this.effectInstanced = null;
  12088. return _this;
  12089. }
  12090. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  12091. // Do nothing if the shader is still loading/preparing
  12092. if (!this.effectsReady) {
  12093. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  12094. return false;
  12095. }
  12096. this.effectsReady = true;
  12097. }
  12098. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  12099. var canvas = instanceInfo.owner.owner;
  12100. var engine = canvas.engine;
  12101. var cur = engine.getAlphaMode();
  12102. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  12103. engine.enableEffect(effect);
  12104. effect.setTexture("diffuseSampler", this.texture);
  12105. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  12106. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12107. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12108. }
  12109. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  12110. var pid = context.groupInfoPartData[0];
  12111. if (context.useInstancing) {
  12112. if (!this.instancingAttributes) {
  12113. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  12114. }
  12115. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  12116. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12117. canvas._addDrawCallCount(1, context.renderMode);
  12118. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  12119. engine.draw(true, 0, 6, count);
  12120. engine.unbindInstanceAttributes();
  12121. }
  12122. else {
  12123. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12124. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12125. this.setupUniforms(effect, 0, pid._partData, i);
  12126. engine.draw(true, 0, 6);
  12127. }
  12128. }
  12129. engine.setAlphaMode(cur, true);
  12130. return true;
  12131. };
  12132. Sprite2DRenderCache.prototype.dispose = function () {
  12133. if (!_super.prototype.dispose.call(this)) {
  12134. return false;
  12135. }
  12136. if (this.vb) {
  12137. this._engine._releaseBuffer(this.vb);
  12138. this.vb = null;
  12139. }
  12140. if (this.ib) {
  12141. this._engine._releaseBuffer(this.ib);
  12142. this.ib = null;
  12143. }
  12144. //if (this.texture) {
  12145. // this.texture.dispose();
  12146. // this.texture = null;
  12147. //}
  12148. this.effect = null;
  12149. this.effectInstanced = null;
  12150. return true;
  12151. };
  12152. return Sprite2DRenderCache;
  12153. }(BABYLON.ModelRenderCache));
  12154. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  12155. var Sprite2D = Sprite2D_1 = (function (_super) {
  12156. __extends(Sprite2D, _super);
  12157. /**
  12158. * Create an 2D Sprite primitive
  12159. * @param texture the texture that stores the sprite to render
  12160. * @param settings a combination of settings, possible ones are
  12161. * - 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)
  12162. * - children: an array of direct children
  12163. * - id a text identifier, for information purpose
  12164. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  12165. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12166. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12167. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  12168. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12169. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12170. * - zOrder: override the zOrder with the specified value
  12171. * - origin: define the normalized origin point location, default [0.5;0.5]
  12172. * - 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.
  12173. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  12174. * - 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.
  12175. * - 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
  12176. * - invertY: if true the texture Y will be inverted, default is false.
  12177. * - 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.
  12178. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  12179. * - 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.
  12180. * - 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.
  12181. * - 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!
  12182. * - 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.
  12183. * - 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).
  12184. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12185. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12186. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12187. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12188. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12189. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12190. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12191. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12192. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12193. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12194. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12195. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12196. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12197. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12198. */
  12199. function Sprite2D(texture, settings) {
  12200. var _this = this;
  12201. if (!settings) {
  12202. settings = {};
  12203. }
  12204. _this = _super.call(this, settings) || this;
  12205. _this.texture = texture;
  12206. _this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12207. _this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12208. _this._useSize = false;
  12209. _this._spriteSize = (settings.spriteSize != null) ? settings.spriteSize.clone() : null;
  12210. _this._spriteLocation = (settings.spriteLocation != null) ? settings.spriteLocation.clone() : new BABYLON.Vector2(0, 0);
  12211. if (settings.size != null) {
  12212. _this.size = settings.size;
  12213. }
  12214. _this.spriteFrame = 0;
  12215. _this.invertY = (settings.invertY == null) ? false : settings.invertY;
  12216. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  12217. _this.useAlphaFromTexture = true;
  12218. _this._scale9 = (settings.scale9 != null) ? settings.scale9.clone() : null;
  12219. // 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.
  12220. // The fucking delayed texture sprite bug is fixed!
  12221. if (settings.spriteSize == null) {
  12222. _this.spriteSize = new BABYLON.Size(10, 10);
  12223. }
  12224. if (settings.spriteSize == null || !texture.isReady()) {
  12225. if (texture.isReady()) {
  12226. var s = texture.getBaseSize();
  12227. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  12228. _this._updateSpriteScaleFactor();
  12229. }
  12230. else {
  12231. texture.onLoadObservable.add(function () {
  12232. if (settings.spriteSize == null) {
  12233. var s = texture.getBaseSize();
  12234. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  12235. }
  12236. _this._updateSpriteScaleFactor();
  12237. _this._positioningDirty();
  12238. _this._setLayoutDirty();
  12239. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D_1.textureProperty.flagId; // To make sure the sprite is issued again for render
  12240. });
  12241. }
  12242. }
  12243. return _this;
  12244. }
  12245. Object.defineProperty(Sprite2D.prototype, "texture", {
  12246. get: function () {
  12247. return this._texture;
  12248. },
  12249. set: function (value) {
  12250. this._texture = value;
  12251. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  12252. },
  12253. enumerable: true,
  12254. configurable: true
  12255. });
  12256. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  12257. get: function () {
  12258. return this._useAlphaFromTexture;
  12259. },
  12260. set: function (value) {
  12261. if (this._useAlphaFromTexture === value) {
  12262. return;
  12263. }
  12264. this._useAlphaFromTexture = value;
  12265. this._updateRenderMode();
  12266. },
  12267. enumerable: true,
  12268. configurable: true
  12269. });
  12270. Object.defineProperty(Sprite2D.prototype, "size", {
  12271. get: function () {
  12272. if (this._size == null) {
  12273. return this.spriteSize;
  12274. }
  12275. return this.internalGetSize();
  12276. },
  12277. set: function (value) {
  12278. this._useSize = value != null;
  12279. this.internalSetSize(value);
  12280. this._updateSpriteScaleFactor();
  12281. },
  12282. enumerable: true,
  12283. configurable: true
  12284. });
  12285. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  12286. get: function () {
  12287. if (this._actualSize) {
  12288. return this._actualSize;
  12289. }
  12290. return this.size;
  12291. },
  12292. set: function (value) {
  12293. if (!this._actualSize) {
  12294. this._actualSize = value.clone();
  12295. }
  12296. else {
  12297. this._actualSize.copyFrom(value);
  12298. }
  12299. },
  12300. enumerable: true,
  12301. configurable: true
  12302. });
  12303. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  12304. get: function () {
  12305. return this._spriteSize;
  12306. },
  12307. set: function (value) {
  12308. if (!this._spriteSize) {
  12309. this._spriteSize = value.clone();
  12310. }
  12311. else {
  12312. this._spriteSize.copyFrom(value);
  12313. }
  12314. this._updateSpriteScaleFactor();
  12315. },
  12316. enumerable: true,
  12317. configurable: true
  12318. });
  12319. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  12320. get: function () {
  12321. return this._spriteLocation;
  12322. },
  12323. set: function (value) {
  12324. if (!this._spriteLocation) {
  12325. this._spriteLocation = value.clone();
  12326. }
  12327. else {
  12328. this._spriteLocation.copyFrom(value);
  12329. }
  12330. },
  12331. enumerable: true,
  12332. configurable: true
  12333. });
  12334. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  12335. get: function () {
  12336. return this._spriteFrame;
  12337. },
  12338. set: function (value) {
  12339. this._spriteFrame = value;
  12340. },
  12341. enumerable: true,
  12342. configurable: true
  12343. });
  12344. Object.defineProperty(Sprite2D.prototype, "invertY", {
  12345. get: function () {
  12346. return this._invertY;
  12347. },
  12348. set: function (value) {
  12349. this._invertY = value;
  12350. },
  12351. enumerable: true,
  12352. configurable: true
  12353. });
  12354. Object.defineProperty(Sprite2D.prototype, "isScale9", {
  12355. get: function () {
  12356. return this._scale9 !== null;
  12357. },
  12358. enumerable: true,
  12359. configurable: true
  12360. });
  12361. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  12362. //@instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, pi => Sprite2D.spriteScaleFactorProperty = pi)
  12363. ///**
  12364. // * Get/set the sprite location (in pixels) in the texture
  12365. // */
  12366. //public get spriteScaleFactor(): Vector2 {
  12367. // return this._spriteScaleFactor;
  12368. //}
  12369. //public set spriteScaleFactor(value: Vector2) {
  12370. // this._spriteScaleFactor = value;
  12371. //}
  12372. /**
  12373. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  12374. */
  12375. get: function () {
  12376. return this._alignToPixel;
  12377. },
  12378. set: function (value) {
  12379. this._alignToPixel = value;
  12380. },
  12381. enumerable: true,
  12382. configurable: true
  12383. });
  12384. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  12385. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  12386. return true;
  12387. };
  12388. /**
  12389. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  12390. */
  12391. Sprite2D.prototype.getAnimatables = function () {
  12392. var res = new Array();
  12393. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  12394. res.push(this.texture);
  12395. }
  12396. return res;
  12397. };
  12398. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  12399. // 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
  12400. return true;
  12401. };
  12402. Object.defineProperty(Sprite2D.prototype, "isSizeAuto", {
  12403. get: function () {
  12404. return this.size == null;
  12405. },
  12406. enumerable: true,
  12407. configurable: true
  12408. });
  12409. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  12410. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  12411. return renderCache;
  12412. };
  12413. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  12414. var renderCache = modelRenderCache;
  12415. var engine = this.owner.engine;
  12416. var vb = new Float32Array(4);
  12417. for (var i = 0; i < 4; i++) {
  12418. vb[i] = i;
  12419. }
  12420. renderCache.vb = engine.createVertexBuffer(vb);
  12421. var ib = new Float32Array(6);
  12422. ib[0] = 0;
  12423. ib[1] = 2;
  12424. ib[2] = 1;
  12425. ib[3] = 0;
  12426. ib[4] = 3;
  12427. ib[5] = 2;
  12428. renderCache.ib = engine.createIndexBuffer(ib);
  12429. renderCache.texture = this.texture;
  12430. // 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
  12431. var ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  12432. if (ei) {
  12433. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  12434. }
  12435. ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  12436. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  12437. return renderCache;
  12438. };
  12439. Sprite2D.prototype.getUsedShaderCategories = function (dataPart) {
  12440. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  12441. if (dataPart.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  12442. var useScale9 = this._scale9 != null;
  12443. if (useScale9) {
  12444. cat.push(Sprite2D_1.SHAPE2D_CATEGORY_SCALE9);
  12445. }
  12446. }
  12447. return cat;
  12448. };
  12449. Sprite2D.prototype.createInstanceDataParts = function () {
  12450. return [new Sprite2DInstanceData(Sprite2D_1.SPRITE2D_MAINPARTID)];
  12451. };
  12452. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  12453. Sprite2D_1.layoutConstructMode = true;
  12454. };
  12455. // if obj contains something, we restore the _text property
  12456. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  12457. Sprite2D_1.layoutConstructMode = false;
  12458. };
  12459. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  12460. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  12461. return false;
  12462. }
  12463. if (!this.texture.isReady() && !Sprite2D_1.layoutConstructMode) {
  12464. return false;
  12465. }
  12466. if (part.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  12467. var d = this._instanceDataParts[0];
  12468. if (Sprite2D_1.layoutConstructMode) {
  12469. d.topLeftUV = BABYLON.Vector2.Zero();
  12470. d.sizeUV = BABYLON.Vector2.Zero();
  12471. d.properties = BABYLON.Vector3.Zero();
  12472. d.textureSize = BABYLON.Vector2.Zero();
  12473. d.scaleFactor = BABYLON.Vector2.Zero();
  12474. if (this.isScale9) {
  12475. d.scale9 = BABYLON.Vector4.Zero();
  12476. }
  12477. }
  12478. else {
  12479. var ts = this.texture.getBaseSize();
  12480. var ss = this.spriteSize;
  12481. var sl = this.spriteLocation;
  12482. var ssf = this.actualScale;
  12483. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  12484. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  12485. d.sizeUV = suv;
  12486. d.scaleFactor = ssf;
  12487. Sprite2D_1._prop.x = this.spriteFrame;
  12488. Sprite2D_1._prop.y = this.invertY ? 1 : 0;
  12489. Sprite2D_1._prop.z = this.alignToPixel ? 1 : 0;
  12490. d.properties = Sprite2D_1._prop;
  12491. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  12492. var scale9 = this._scale9;
  12493. if (scale9 != null) {
  12494. 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);
  12495. d.scale9 = normalizedScale9;
  12496. }
  12497. }
  12498. }
  12499. return true;
  12500. };
  12501. Sprite2D.prototype._mustUpdateInstance = function () {
  12502. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  12503. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  12504. if (res) {
  12505. this._updateRenderMode();
  12506. }
  12507. return res;
  12508. };
  12509. Sprite2D.prototype._useTextureAlpha = function () {
  12510. return this.texture != null && this.texture.hasAlpha;
  12511. };
  12512. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  12513. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  12514. };
  12515. Sprite2D.prototype._updateSpriteScaleFactor = function () {
  12516. if (!this._useSize) {
  12517. return;
  12518. }
  12519. var sS = this.spriteSize;
  12520. var s = this.size;
  12521. if (s == null || sS == null) {
  12522. return;
  12523. }
  12524. this.scaleX = s.width / sS.width;
  12525. this.scaleY = s.height / sS.height;
  12526. };
  12527. return Sprite2D;
  12528. }(BABYLON.RenderablePrim2D));
  12529. Sprite2D.SPRITE2D_MAINPARTID = 1;
  12530. Sprite2D.SHAPE2D_CATEGORY_SCALE9 = "Scale9";
  12531. Sprite2D._prop = BABYLON.Vector3.Zero();
  12532. Sprite2D.layoutConstructMode = false;
  12533. __decorate([
  12534. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D_1.textureProperty = pi; })
  12535. ], Sprite2D.prototype, "texture", null);
  12536. __decorate([
  12537. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D_1.useAlphaFromTextureProperty = pi; })
  12538. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  12539. __decorate([
  12540. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D_1.actualSizeProperty = pi; }, false, true)
  12541. ], Sprite2D.prototype, "actualSize", null);
  12542. __decorate([
  12543. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D_1.spriteSizeProperty = pi; })
  12544. ], Sprite2D.prototype, "spriteSize", null);
  12545. __decorate([
  12546. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D_1.spriteLocationProperty = pi; })
  12547. ], Sprite2D.prototype, "spriteLocation", null);
  12548. __decorate([
  12549. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D_1.spriteFrameProperty = pi; })
  12550. ], Sprite2D.prototype, "spriteFrame", null);
  12551. __decorate([
  12552. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D_1.invertYProperty = pi; })
  12553. ], Sprite2D.prototype, "invertY", null);
  12554. __decorate([
  12555. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 8, function (pi) { return Sprite2D_1.spriteScale9Property = pi; })
  12556. ], Sprite2D.prototype, "isScale9", null);
  12557. Sprite2D = Sprite2D_1 = __decorate([
  12558. BABYLON.className("Sprite2D", "BABYLON")
  12559. ], Sprite2D);
  12560. BABYLON.Sprite2D = Sprite2D;
  12561. var Sprite2DInstanceData = (function (_super) {
  12562. __extends(Sprite2DInstanceData, _super);
  12563. function Sprite2DInstanceData(partId) {
  12564. return _super.call(this, partId, 1) || this;
  12565. }
  12566. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  12567. get: function () {
  12568. return null;
  12569. },
  12570. set: function (value) {
  12571. },
  12572. enumerable: true,
  12573. configurable: true
  12574. });
  12575. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  12576. get: function () {
  12577. return null;
  12578. },
  12579. set: function (value) {
  12580. },
  12581. enumerable: true,
  12582. configurable: true
  12583. });
  12584. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  12585. get: function () {
  12586. return null;
  12587. },
  12588. set: function (value) {
  12589. },
  12590. enumerable: true,
  12591. configurable: true
  12592. });
  12593. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  12594. get: function () {
  12595. return null;
  12596. },
  12597. set: function (value) {
  12598. },
  12599. enumerable: true,
  12600. configurable: true
  12601. });
  12602. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  12603. // 3 floats being:
  12604. // - x: frame number to display
  12605. // - y: invertY setting
  12606. // - z: alignToPixel setting
  12607. get: function () {
  12608. return null;
  12609. },
  12610. set: function (value) {
  12611. },
  12612. enumerable: true,
  12613. configurable: true
  12614. });
  12615. Object.defineProperty(Sprite2DInstanceData.prototype, "scale9", {
  12616. get: function () {
  12617. return null;
  12618. },
  12619. set: function (value) {
  12620. },
  12621. enumerable: true,
  12622. configurable: true
  12623. });
  12624. return Sprite2DInstanceData;
  12625. }(BABYLON.InstanceDataBase));
  12626. __decorate([
  12627. BABYLON.instanceData()
  12628. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  12629. __decorate([
  12630. BABYLON.instanceData()
  12631. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  12632. __decorate([
  12633. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  12634. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  12635. __decorate([
  12636. BABYLON.instanceData()
  12637. ], Sprite2DInstanceData.prototype, "textureSize", null);
  12638. __decorate([
  12639. BABYLON.instanceData()
  12640. ], Sprite2DInstanceData.prototype, "properties", null);
  12641. __decorate([
  12642. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  12643. ], Sprite2DInstanceData.prototype, "scale9", null);
  12644. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  12645. var Sprite2D_1;
  12646. })(BABYLON || (BABYLON = {}));
  12647. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12648. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12649. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12650. 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;
  12651. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12652. };
  12653. var BABYLON;
  12654. (function (BABYLON) {
  12655. /**
  12656. * This class will contains information about a sub picture present in an Atlas Picture.
  12657. */
  12658. var AtlasSubPictureInfo = (function () {
  12659. function AtlasSubPictureInfo() {
  12660. }
  12661. return AtlasSubPictureInfo;
  12662. }());
  12663. BABYLON.AtlasSubPictureInfo = AtlasSubPictureInfo;
  12664. /**
  12665. * This class represent an Atlas Picture, it contains the information of all the sub pictures and the Texture that stores the bitmap.
  12666. * You get an instance of this class using methods of the AtlasPictureInfoFactory
  12667. */
  12668. var AtlasPictureInfo = (function () {
  12669. function AtlasPictureInfo() {
  12670. }
  12671. /**
  12672. * Creates many sprite from the Atlas Picture
  12673. * @param filterCallback a predicate if true is returned then the corresponding sub picture will be used to create a sprite.
  12674. * The Predicate has many parameters:
  12675. * - index: just an index incremented at each sub picture submitted for Sprite creation
  12676. * - name: the sub picture's name
  12677. * - aspi: the AtlasSubPictureInfo corresponding to the submitted sub picture
  12678. * - settings: the Sprite2D creation settings, you can alter this JSON object but BEWARE, the alterations will be kept for subsequent Sprite2D creations!
  12679. * @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.
  12680. */
  12681. AtlasPictureInfo.prototype.createSprites = function (filterCallback, spriteSettings) {
  12682. var _this = this;
  12683. var res = new Array();
  12684. var index = 0;
  12685. this.subPictures.forEach(function (k, v) {
  12686. if (!filterCallback || filterCallback(index++, k, v, spriteSettings)) {
  12687. var s = _this.createSprite(k, spriteSettings);
  12688. if (s) {
  12689. res.push(s);
  12690. }
  12691. }
  12692. });
  12693. return res;
  12694. };
  12695. /**
  12696. * Create one Sprite from a sub picture
  12697. * @param subPictureName the name of the sub picture to use
  12698. * @param spriteSettings the Sprite2D settings to use for the Sprite instance creation
  12699. */
  12700. AtlasPictureInfo.prototype.createSprite = function (subPictureName, spriteSettings) {
  12701. var spi = this.subPictures.get(subPictureName);
  12702. if (!spi) {
  12703. return null;
  12704. }
  12705. if (!spriteSettings) {
  12706. spriteSettings = {};
  12707. }
  12708. var s = spriteSettings;
  12709. s.id = subPictureName;
  12710. s.spriteLocation = spi.location;
  12711. s.spriteSize = spi.size;
  12712. var sprite = new BABYLON.Sprite2D(this.texture, spriteSettings);
  12713. return sprite;
  12714. };
  12715. return AtlasPictureInfo;
  12716. }());
  12717. BABYLON.AtlasPictureInfo = AtlasPictureInfo;
  12718. /**
  12719. * This if the Factory class containing static method to create Atlas Pictures Info objects or add new loaders
  12720. */
  12721. var AtlasPictureInfoFactory = (function () {
  12722. function AtlasPictureInfoFactory() {
  12723. }
  12724. /**
  12725. * Add a custom loader
  12726. * @param fileExtension must be the file extension (without the dot) of the file that is loaded by this loader (e.g.: json)
  12727. * @param plugin the instance of the loader
  12728. */
  12729. AtlasPictureInfoFactory.addLoader = function (fileExtension, plugin) {
  12730. var a = AtlasPictureInfoFactory.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  12731. a.push(plugin);
  12732. };
  12733. /**
  12734. * Load an Atlas Picture Info object from a data file at a given url and with a given texture
  12735. * @param texture the texture containing the atlas bitmap
  12736. * @param url the URL of the Atlas Info data file
  12737. * @param onLoad a callback that will be called when the AtlasPictureInfo object will be loaded and ready
  12738. * @param onError a callback that will be called in case of error
  12739. */
  12740. AtlasPictureInfoFactory.loadFromUrl = function (texture, url, onLoad, onError) {
  12741. if (onError === void 0) { onError = null; }
  12742. var xhr = new XMLHttpRequest();
  12743. xhr.onreadystatechange = function () {
  12744. if (xhr.readyState === XMLHttpRequest.DONE) {
  12745. if (xhr.status === 200) {
  12746. var ext = url.split('.').pop().split(/\#|\?/)[0];
  12747. var plugins = AtlasPictureInfoFactory.plugins.get(ext.toLocaleLowerCase());
  12748. if (!plugins) {
  12749. if (onError) {
  12750. onError("couldn't find a plugin for this file extension", -1);
  12751. }
  12752. return;
  12753. }
  12754. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  12755. var p = plugins_1[_i];
  12756. var ret = p.loadFile(xhr.response);
  12757. if (ret) {
  12758. if (ret.api) {
  12759. ret.api.texture = texture;
  12760. if (onLoad) {
  12761. onLoad(ret.api);
  12762. }
  12763. }
  12764. else if (onError) {
  12765. onError(ret.errorMsg, ret.errorCode);
  12766. }
  12767. return;
  12768. }
  12769. }
  12770. if (onError) {
  12771. onError("No plugin to load this Atlas Data file format", -1);
  12772. }
  12773. }
  12774. else {
  12775. if (onError) {
  12776. onError("Couldn't load file through HTTP Request, HTTP Status " + xhr.status, xhr.status);
  12777. }
  12778. }
  12779. }
  12780. };
  12781. xhr.open("GET", url, true);
  12782. xhr.send();
  12783. return null;
  12784. };
  12785. return AtlasPictureInfoFactory;
  12786. }());
  12787. AtlasPictureInfoFactory.plugins = new BABYLON.StringDictionary();
  12788. BABYLON.AtlasPictureInfoFactory = AtlasPictureInfoFactory;
  12789. // Loader class for the TexturePacker's JSON Array data format
  12790. var JSONArrayLoader = JSONArrayLoader_1 = (function () {
  12791. function JSONArrayLoader() {
  12792. }
  12793. JSONArrayLoader.prototype.loadFile = function (content) {
  12794. var errorMsg = null;
  12795. var errorCode = 0;
  12796. var root = null;
  12797. var api = null;
  12798. try {
  12799. var frames_1;
  12800. var meta = void 0;
  12801. try {
  12802. root = JSON.parse(content);
  12803. frames_1 = root.frames;
  12804. meta = root.meta;
  12805. if (!frames_1 || !meta) {
  12806. throw Error("Not a JSON Array file format");
  12807. }
  12808. }
  12809. catch (ex1) {
  12810. return null;
  12811. }
  12812. api = new AtlasPictureInfo();
  12813. api.atlasSize = new BABYLON.Size(meta.size.w, meta.size.h);
  12814. api.subPictures = new BABYLON.StringDictionary();
  12815. for (var _i = 0, frames_2 = frames_1; _i < frames_2.length; _i++) {
  12816. var f = frames_2[_i];
  12817. var aspi = new AtlasSubPictureInfo();
  12818. aspi.name = f.filename;
  12819. aspi.location = new BABYLON.Vector2(f.frame.x, api.atlasSize.height - (f.frame.y + f.frame.h));
  12820. aspi.size = new BABYLON.Size(f.frame.w, f.frame.h);
  12821. api.subPictures.add(aspi.name, aspi);
  12822. }
  12823. }
  12824. catch (ex2) {
  12825. errorMsg = "Unknown Exception: " + ex2;
  12826. errorCode = -2;
  12827. }
  12828. return { api: api, errorMsg: errorMsg, errorCode: errorCode };
  12829. };
  12830. return JSONArrayLoader;
  12831. }());
  12832. JSONArrayLoader = JSONArrayLoader_1 = __decorate([
  12833. AtlasLoaderPlugin("json", new JSONArrayLoader_1())
  12834. ], JSONArrayLoader);
  12835. /**
  12836. * Use this decorator when you declare an Atlas Loader Class for the loader to register itself automatically.
  12837. * @param fileExtension the extension of the file that the plugin is loading (there can be many plugin for the same extension)
  12838. * @param plugin an instance of the plugin class to add to the AtlasPictureInfoFactory
  12839. */
  12840. function AtlasLoaderPlugin(fileExtension, plugin) {
  12841. return function () {
  12842. AtlasPictureInfoFactory.addLoader(fileExtension, plugin);
  12843. };
  12844. }
  12845. BABYLON.AtlasLoaderPlugin = AtlasLoaderPlugin;
  12846. var JSONArrayLoader_1;
  12847. })(BABYLON || (BABYLON = {}));
  12848. var __extends = (this && this.__extends) || function (d, b) {
  12849. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12850. function __() { this.constructor = d; }
  12851. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12852. };
  12853. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12854. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12855. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12856. 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;
  12857. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12858. };
  12859. var BABYLON;
  12860. (function (BABYLON) {
  12861. var Text2DRenderCache = (function (_super) {
  12862. __extends(Text2DRenderCache, _super);
  12863. function Text2DRenderCache() {
  12864. var _this = _super !== null && _super.apply(this, arguments) || this;
  12865. _this.effectsReady = false;
  12866. _this.vb = null;
  12867. _this.ib = null;
  12868. _this.instancingAttributes = null;
  12869. _this.fontTexture = null;
  12870. _this.effect = null;
  12871. _this.effectInstanced = null;
  12872. return _this;
  12873. }
  12874. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  12875. // Do nothing if the shader is still loading/preparing
  12876. if (!this.effectsReady) {
  12877. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  12878. return false;
  12879. }
  12880. this.effectsReady = true;
  12881. }
  12882. var canvas = instanceInfo.owner.owner;
  12883. var engine = canvas.engine;
  12884. this.fontTexture.update();
  12885. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  12886. engine.enableEffect(effect);
  12887. effect.setTexture("diffuseSampler", this.fontTexture);
  12888. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  12889. var sdf = this.fontTexture.isSignedDistanceField;
  12890. // Enable alpha mode only if the texture is not using SDF, SDF is rendered in AlphaTest mode, which mean no alpha blend
  12891. var curAlphaMode;
  12892. if (!sdf) {
  12893. curAlphaMode = engine.getAlphaMode();
  12894. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12895. }
  12896. var pid = context.groupInfoPartData[0];
  12897. if (context.useInstancing) {
  12898. if (!this.instancingAttributes) {
  12899. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  12900. }
  12901. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  12902. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12903. canvas._addDrawCallCount(1, context.renderMode);
  12904. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  12905. engine.draw(true, 0, 6, count);
  12906. engine.unbindInstanceAttributes();
  12907. }
  12908. else {
  12909. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12910. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12911. this.setupUniforms(effect, 0, pid._partData, i);
  12912. engine.draw(true, 0, 6);
  12913. }
  12914. }
  12915. if (!sdf) {
  12916. engine.setAlphaMode(curAlphaMode, true);
  12917. }
  12918. return true;
  12919. };
  12920. Text2DRenderCache.prototype.dispose = function () {
  12921. if (!_super.prototype.dispose.call(this)) {
  12922. return false;
  12923. }
  12924. if (this.vb) {
  12925. this._engine._releaseBuffer(this.vb);
  12926. this.vb = null;
  12927. }
  12928. if (this.ib) {
  12929. this._engine._releaseBuffer(this.ib);
  12930. this.ib = null;
  12931. }
  12932. if (this.fontTexture) {
  12933. this.fontTexture.decCachedFontTextureCounter();
  12934. this.fontTexture = null;
  12935. }
  12936. this.effect = null;
  12937. this.effectInstanced = null;
  12938. return true;
  12939. };
  12940. return Text2DRenderCache;
  12941. }(BABYLON.ModelRenderCache));
  12942. BABYLON.Text2DRenderCache = Text2DRenderCache;
  12943. var Text2DInstanceData = (function (_super) {
  12944. __extends(Text2DInstanceData, _super);
  12945. function Text2DInstanceData(partId, dataElementCount) {
  12946. return _super.call(this, partId, dataElementCount) || this;
  12947. }
  12948. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  12949. get: function () {
  12950. return null;
  12951. },
  12952. set: function (value) {
  12953. },
  12954. enumerable: true,
  12955. configurable: true
  12956. });
  12957. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  12958. get: function () {
  12959. return null;
  12960. },
  12961. set: function (value) {
  12962. },
  12963. enumerable: true,
  12964. configurable: true
  12965. });
  12966. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  12967. get: function () {
  12968. return null;
  12969. },
  12970. set: function (value) {
  12971. },
  12972. enumerable: true,
  12973. configurable: true
  12974. });
  12975. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  12976. get: function () {
  12977. return null;
  12978. },
  12979. set: function (value) {
  12980. },
  12981. enumerable: true,
  12982. configurable: true
  12983. });
  12984. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  12985. get: function () {
  12986. return null;
  12987. },
  12988. set: function (value) {
  12989. },
  12990. enumerable: true,
  12991. configurable: true
  12992. });
  12993. return Text2DInstanceData;
  12994. }(BABYLON.InstanceDataBase));
  12995. __decorate([
  12996. BABYLON.instanceData()
  12997. ], Text2DInstanceData.prototype, "topLeftUV", null);
  12998. __decorate([
  12999. BABYLON.instanceData()
  13000. ], Text2DInstanceData.prototype, "sizeUV", null);
  13001. __decorate([
  13002. BABYLON.instanceData()
  13003. ], Text2DInstanceData.prototype, "textureSize", null);
  13004. __decorate([
  13005. BABYLON.instanceData()
  13006. ], Text2DInstanceData.prototype, "color", null);
  13007. __decorate([
  13008. BABYLON.instanceData()
  13009. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  13010. BABYLON.Text2DInstanceData = Text2DInstanceData;
  13011. var Text2D = Text2D_1 = (function (_super) {
  13012. __extends(Text2D, _super);
  13013. /**
  13014. * Create a Text primitive
  13015. * @param text the text to display
  13016. * @param settings a combination of settings, possible ones are
  13017. * - 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)
  13018. * - children: an array of direct children
  13019. * - id a text identifier, for information purpose
  13020. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13021. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13022. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13023. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13024. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13025. * - zOrder: override the zOrder with the specified value
  13026. * - origin: define the normalized origin point location, default [0.5;0.5]
  13027. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  13028. * - 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.
  13029. * - 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.
  13030. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  13031. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  13032. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  13033. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  13034. * - 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.
  13035. * - 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.
  13036. * - 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!
  13037. * - 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.
  13038. * - 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).
  13039. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13040. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13041. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13042. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13043. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13044. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13045. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13046. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13047. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13048. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13049. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13050. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13051. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13052. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13053. * - textAlignmentH: align text horizontally (Text2D.AlignLeft, Text2D.AlignCenter, Text2D.AlignRight)
  13054. * - textAlignmentV: align text vertically (Text2D.AlignTop, Text2D.AlignCenter, Text2D.AlignBottom)
  13055. * - textAlignment: a string defining the text alignment, text can be: [<h:|horizontal:><left|right|center>], [<v:|vertical:><top|bottom|center>]
  13056. * - wordWrap: if true the text will wrap inside content area
  13057. */
  13058. function Text2D(text, settings) {
  13059. var _this = this;
  13060. if (!settings) {
  13061. settings = {};
  13062. }
  13063. _this = _super.call(this, settings) || this;
  13064. if (settings.bitmapFontTexture != null) {
  13065. _this._fontTexture = settings.bitmapFontTexture;
  13066. _this._fontName = null;
  13067. _this._fontSuperSample = false;
  13068. _this._fontSDF = false;
  13069. }
  13070. else {
  13071. _this._fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  13072. _this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  13073. _this._fontSDF = (settings.fontSignedDistanceField != null && settings.fontSignedDistanceField);
  13074. }
  13075. _this._defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor.clone();
  13076. _this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  13077. _this._textSize = null;
  13078. _this.text = text;
  13079. _this.size = (settings.size == null) ? null : settings.size;
  13080. _this.textAlignmentH = (settings.textAlignmentH == null) ? Text2D_1.AlignLeft : settings.textAlignmentH;
  13081. _this.textAlignmentV = (settings.textAlignmentV == null) ? Text2D_1.AlignTop : settings.textAlignmentV;
  13082. _this.textAlignment = (settings.textAlignment == null) ? "" : settings.textAlignment;
  13083. _this._wordWrap = (settings.wordWrap == null) ? false : settings.wordWrap;
  13084. _this._updateRenderMode();
  13085. return _this;
  13086. }
  13087. Object.defineProperty(Text2D, "AlignLeft", {
  13088. /**
  13089. * Alignment is made relative to the left edge of the Content Area. Valid for horizontal alignment only.
  13090. */
  13091. get: function () { return Text2D_1._AlignLeft; },
  13092. enumerable: true,
  13093. configurable: true
  13094. });
  13095. Object.defineProperty(Text2D, "AlignTop", {
  13096. /**
  13097. * Alignment is made relative to the top edge of the Content Area. Valid for vertical alignment only.
  13098. */
  13099. get: function () { return Text2D_1._AlignTop; },
  13100. enumerable: true,
  13101. configurable: true
  13102. });
  13103. Object.defineProperty(Text2D, "AlignRight", {
  13104. /**
  13105. * Alignment is made relative to the right edge of the Content Area. Valid for horizontal alignment only.
  13106. */
  13107. get: function () { return Text2D_1._AlignRight; },
  13108. enumerable: true,
  13109. configurable: true
  13110. });
  13111. Object.defineProperty(Text2D, "AlignBottom", {
  13112. /**
  13113. * Alignment is made relative to the bottom edge of the Content Area. Valid for vertical alignment only.
  13114. */
  13115. get: function () { return Text2D_1._AlignBottom; },
  13116. enumerable: true,
  13117. configurable: true
  13118. });
  13119. Object.defineProperty(Text2D, "AlignCenter", {
  13120. /**
  13121. * Alignment is made to center the text from equal distance to the opposite edges of the Content Area
  13122. */
  13123. get: function () { return Text2D_1._AlignCenter; },
  13124. enumerable: true,
  13125. configurable: true
  13126. });
  13127. Object.defineProperty(Text2D.prototype, "fontName", {
  13128. get: function () {
  13129. return this._fontName;
  13130. },
  13131. set: function (value) {
  13132. if (this._fontName) {
  13133. throw new Error("Font Name change is not supported right now.");
  13134. }
  13135. this._fontName = value;
  13136. },
  13137. enumerable: true,
  13138. configurable: true
  13139. });
  13140. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  13141. get: function () {
  13142. return this._defaultFontColor;
  13143. },
  13144. set: function (value) {
  13145. if (!this._defaultFontColor) {
  13146. this._defaultFontColor = value.clone();
  13147. }
  13148. else {
  13149. this._defaultFontColor.copyFrom(value);
  13150. }
  13151. },
  13152. enumerable: true,
  13153. configurable: true
  13154. });
  13155. Object.defineProperty(Text2D.prototype, "text", {
  13156. get: function () {
  13157. return this._text;
  13158. },
  13159. set: function (value) {
  13160. if (!value) {
  13161. value = "";
  13162. }
  13163. this._text = value;
  13164. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  13165. this._size = null;
  13166. this._updateCharCount();
  13167. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  13168. var s = this.textSize;
  13169. },
  13170. enumerable: true,
  13171. configurable: true
  13172. });
  13173. Object.defineProperty(Text2D.prototype, "size", {
  13174. get: function () {
  13175. if (this._size != null) {
  13176. return this._size;
  13177. }
  13178. return this.textSize;
  13179. },
  13180. set: function (value) {
  13181. this.internalSetSize(value);
  13182. },
  13183. enumerable: true,
  13184. configurable: true
  13185. });
  13186. Object.defineProperty(Text2D.prototype, "fontSuperSample", {
  13187. get: function () {
  13188. return this._fontTexture && this._fontTexture.isSuperSampled;
  13189. },
  13190. enumerable: true,
  13191. configurable: true
  13192. });
  13193. Object.defineProperty(Text2D.prototype, "fontSignedDistanceField", {
  13194. get: function () {
  13195. return this._fontTexture && this._fontTexture.isSignedDistanceField;
  13196. },
  13197. enumerable: true,
  13198. configurable: true
  13199. });
  13200. Object.defineProperty(Text2D.prototype, "isSizeAuto", {
  13201. get: function () {
  13202. return false;
  13203. },
  13204. enumerable: true,
  13205. configurable: true
  13206. });
  13207. Object.defineProperty(Text2D.prototype, "actualSize", {
  13208. /**
  13209. * Get the actual size of the Text2D primitive
  13210. */
  13211. get: function () {
  13212. if (this._actualSize) {
  13213. return this._actualSize;
  13214. }
  13215. return this.size;
  13216. },
  13217. enumerable: true,
  13218. configurable: true
  13219. });
  13220. Object.defineProperty(Text2D.prototype, "textSize", {
  13221. /**
  13222. * Get the area that bounds the text associated to the primitive
  13223. */
  13224. get: function () {
  13225. if (!this._textSize) {
  13226. if (this.owner && this._text) {
  13227. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  13228. if (!newSize.equals(this._textSize)) {
  13229. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  13230. this._positioningDirty();
  13231. }
  13232. this._textSize = newSize;
  13233. }
  13234. else {
  13235. return Text2D_1.nullSize;
  13236. }
  13237. }
  13238. return this._textSize;
  13239. },
  13240. enumerable: true,
  13241. configurable: true
  13242. });
  13243. Object.defineProperty(Text2D.prototype, "fontTexture", {
  13244. get: function () {
  13245. if (this._fontTexture) {
  13246. return this._fontTexture;
  13247. }
  13248. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  13249. return null;
  13250. }
  13251. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  13252. return this._fontTexture;
  13253. },
  13254. enumerable: true,
  13255. configurable: true
  13256. });
  13257. /**
  13258. * Dispose the primitive, remove it from its parent
  13259. */
  13260. Text2D.prototype.dispose = function () {
  13261. if (!_super.prototype.dispose.call(this)) {
  13262. return false;
  13263. }
  13264. if (this._fontTexture) {
  13265. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  13266. this._fontTexture = null;
  13267. }
  13268. return true;
  13269. };
  13270. Text2D.prototype.updateLevelBoundingInfo = function () {
  13271. if (!this.owner || !this._text) {
  13272. return false;
  13273. }
  13274. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  13275. return true;
  13276. };
  13277. Object.defineProperty(Text2D.prototype, "textAlignment", {
  13278. /**
  13279. * You can get/set the text alignment through this property
  13280. */
  13281. get: function () {
  13282. return this._textAlignment;
  13283. },
  13284. set: function (value) {
  13285. this._textAlignment = value;
  13286. this._setTextAlignmentfromString(value);
  13287. },
  13288. enumerable: true,
  13289. configurable: true
  13290. });
  13291. Text2D.prototype.levelIntersect = function (intersectInfo) {
  13292. // 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...
  13293. return true;
  13294. };
  13295. Text2D.prototype.createModelRenderCache = function (modelKey) {
  13296. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  13297. return renderCache;
  13298. };
  13299. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  13300. var renderCache = modelRenderCache;
  13301. var engine = this.owner.engine;
  13302. renderCache.fontTexture = this.fontTexture;
  13303. renderCache.fontTexture.incCachedFontTextureCounter();
  13304. var vb = new Float32Array(4);
  13305. for (var i = 0; i < 4; i++) {
  13306. vb[i] = i;
  13307. }
  13308. renderCache.vb = engine.createVertexBuffer(vb);
  13309. var ib = new Float32Array(6);
  13310. ib[0] = 0;
  13311. ib[1] = 2;
  13312. ib[2] = 1;
  13313. ib[3] = 0;
  13314. ib[4] = 3;
  13315. ib[5] = 2;
  13316. renderCache.ib = engine.createIndexBuffer(ib);
  13317. // 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
  13318. var ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, true);
  13319. if (ei) {
  13320. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13321. }
  13322. ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, false);
  13323. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13324. return renderCache;
  13325. };
  13326. Text2D.prototype.createInstanceDataParts = function () {
  13327. return [new Text2DInstanceData(Text2D_1.TEXT2D_MAINPARTID, this._charCount)];
  13328. };
  13329. // Looks like a hack!? Yes! Because that's what it is!
  13330. // 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
  13331. // 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)
  13332. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  13333. if (!this._charCount) {
  13334. var curText = this._text;
  13335. this.text = "A";
  13336. return curText;
  13337. }
  13338. };
  13339. // if obj contains something, we restore the _text property
  13340. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  13341. if (obj !== undefined) {
  13342. this.text = obj;
  13343. }
  13344. };
  13345. Text2D.prototype.getUsedShaderCategories = function (dataPart) {
  13346. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  13347. if (this._fontSDF) {
  13348. cat.push(Text2D_1.TEXT2D_CATEGORY_SDF);
  13349. }
  13350. return cat;
  13351. };
  13352. Text2D.prototype.refreshInstanceDataPart = function (part) {
  13353. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  13354. return false;
  13355. }
  13356. if (part.id === Text2D_1.TEXT2D_MAINPARTID) {
  13357. var d = part;
  13358. var texture = this.fontTexture;
  13359. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  13360. var ts = texture.getSize();
  13361. var offset = BABYLON.Vector2.Zero();
  13362. var lh = this.fontTexture.lineHeight;
  13363. d.dataElementCount = this._charCount;
  13364. d.curElement = 0;
  13365. var lineLengths = [];
  13366. var charWidths = [];
  13367. var charsPerLine = [];
  13368. var numCharsCurrenLine = 0;
  13369. var contentAreaWidth = this.contentArea.width;
  13370. var contentAreaHeight = this.contentArea.height;
  13371. var numCharsCurrentWord = 0;
  13372. var widthCurrentWord = 0;
  13373. var numWordsPerLine = 0;
  13374. var text = this.text;
  13375. var tabWidth = this._tabulationSize * texture.spaceWidth;
  13376. for (var i_1 = 0; i_1 < text.length; i_1++) {
  13377. var char = text[i_1];
  13378. numCharsCurrenLine++;
  13379. charWidths[i_1] = 0;
  13380. // Line feed
  13381. if (this._isWhiteSpaceCharVert(char)) {
  13382. lineLengths.push(offset.x);
  13383. charsPerLine.push(numCharsCurrenLine - 1);
  13384. numCharsCurrenLine = 1;
  13385. offset.x = 0;
  13386. if (widthCurrentWord > 0) {
  13387. numWordsPerLine++;
  13388. }
  13389. numWordsPerLine = 0;
  13390. numCharsCurrentWord = 0;
  13391. widthCurrentWord = 0;
  13392. continue;
  13393. }
  13394. var ci = texture.getChar(char);
  13395. var charWidth = 0;
  13396. if (char === "\t") {
  13397. charWidth = tabWidth;
  13398. }
  13399. else {
  13400. charWidth = ci.charWidth;
  13401. }
  13402. offset.x += charWidth;
  13403. charWidths[i_1] = charWidth;
  13404. if (this._isWhiteSpaceCharHoriz(char)) {
  13405. if (widthCurrentWord > 0) {
  13406. numWordsPerLine++;
  13407. }
  13408. numCharsCurrentWord = 0;
  13409. widthCurrentWord = 0;
  13410. }
  13411. else {
  13412. widthCurrentWord += ci.charWidth;
  13413. numCharsCurrentWord++;
  13414. }
  13415. if (this._wordWrap && numWordsPerLine > 0 && offset.x > contentAreaWidth) {
  13416. lineLengths.push(offset.x - widthCurrentWord);
  13417. numCharsCurrenLine -= numCharsCurrentWord;
  13418. var j = i_1 - numCharsCurrentWord;
  13419. //skip white space at the end of this line
  13420. while (this._isWhiteSpaceCharHoriz(text[j])) {
  13421. lineLengths[lineLengths.length - 1] -= charWidths[j];
  13422. j--;
  13423. }
  13424. charsPerLine.push(numCharsCurrenLine);
  13425. if (this._isWhiteSpaceCharHoriz(text[i_1])) {
  13426. //skip white space at the beginning of next line
  13427. var numSpaces = 0;
  13428. while (this._isWhiteSpaceCharHoriz(text[i_1 + numSpaces])) {
  13429. numSpaces++;
  13430. charWidths[i_1 + numSpaces] = 0;
  13431. }
  13432. i_1 += numSpaces - 1;
  13433. offset.x = 0;
  13434. numCharsCurrenLine = numSpaces - 1;
  13435. }
  13436. else {
  13437. numCharsCurrenLine = numCharsCurrentWord;
  13438. offset.x = widthCurrentWord;
  13439. }
  13440. numWordsPerLine = 0;
  13441. }
  13442. }
  13443. lineLengths.push(offset.x);
  13444. charsPerLine.push(numCharsCurrenLine);
  13445. //skip white space at the end
  13446. var i = text.length - 1;
  13447. while (this._isWhiteSpaceCharHoriz(text[i])) {
  13448. lineLengths[lineLengths.length - 1] -= charWidths[i];
  13449. i--;
  13450. }
  13451. var charNum = 0;
  13452. var maxLineLen = 0;
  13453. var alignH = this.textAlignmentH;
  13454. var alignV = this.textAlignmentV;
  13455. offset.x = 0;
  13456. if (alignH == Text2D_1.AlignRight || alignH == Text2D_1.AlignCenter) {
  13457. for (var i_2 = 0; i_2 < lineLengths.length; i_2++) {
  13458. if (lineLengths[i_2] > maxLineLen) {
  13459. maxLineLen = lineLengths[i_2];
  13460. }
  13461. }
  13462. }
  13463. var textHeight = lineLengths.length * lh;
  13464. var offsetX = this.padding.leftPixels;
  13465. if (alignH == Text2D_1.AlignRight) {
  13466. offsetX += contentAreaWidth - maxLineLen;
  13467. }
  13468. else if (alignH == Text2D_1.AlignCenter) {
  13469. offsetX += (contentAreaWidth - maxLineLen) * .5;
  13470. }
  13471. offset.x += offsetX;
  13472. offset.y += contentAreaHeight + textHeight - lh;
  13473. offset.y += this.padding.bottomPixels;
  13474. if (alignV == Text2D_1.AlignBottom) {
  13475. offset.y -= contentAreaHeight;
  13476. }
  13477. else if (alignV == Text2D_1.AlignCenter) {
  13478. offset.y -= (contentAreaHeight - textHeight) * .5 + lineLengths.length * lh;
  13479. }
  13480. else {
  13481. offset.y -= lineLengths.length * lh;
  13482. }
  13483. for (var i_3 = 0; i_3 < lineLengths.length; i_3++) {
  13484. var numChars = charsPerLine[i_3];
  13485. var lineLength = lineLengths[i_3];
  13486. if (alignH == Text2D_1.AlignRight) {
  13487. offset.x += maxLineLen - lineLength;
  13488. }
  13489. else if (alignH == Text2D_1.AlignCenter) {
  13490. offset.x += (maxLineLen - lineLength) * .5;
  13491. }
  13492. for (var j = 0; j < numChars; j++) {
  13493. var char = text[charNum];
  13494. var charWidth = charWidths[charNum];
  13495. if (!this._isWhiteSpaceCharHoriz(char) && !this._isWhiteSpaceCharVert(char)) {
  13496. this.updateInstanceDataPart(d, offset);
  13497. var ci = texture.getChar(char);
  13498. d.topLeftUV = ci.topLeftUV;
  13499. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  13500. d.sizeUV = suv;
  13501. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  13502. d.color = this.defaultFontColor;
  13503. d.superSampleFactor = superSampleFactor;
  13504. ++d.curElement;
  13505. }
  13506. offset.x += charWidth;
  13507. charNum++;
  13508. }
  13509. offset.x = offsetX;
  13510. offset.y -= texture.lineHeight;
  13511. }
  13512. }
  13513. return true;
  13514. };
  13515. Text2D.prototype._isWhiteSpaceCharHoriz = function (char) {
  13516. if (char === " " || char === "\t") {
  13517. return true;
  13518. }
  13519. };
  13520. Text2D.prototype._isWhiteSpaceCharVert = function (char) {
  13521. if (char === "\n" || char === "\r") {
  13522. return true;
  13523. }
  13524. };
  13525. Text2D.prototype._updateCharCount = function () {
  13526. var count = 0;
  13527. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  13528. var char = _a[_i];
  13529. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  13530. continue;
  13531. }
  13532. ++count;
  13533. }
  13534. this._charCount = count;
  13535. };
  13536. Text2D.prototype._setTextAlignmentfromString = function (value) {
  13537. var m = value.trim().split(",");
  13538. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  13539. var v = m_1[_i];
  13540. v = v.toLocaleLowerCase().trim();
  13541. // Horizontal
  13542. var i = v.indexOf("h:");
  13543. if (i === -1) {
  13544. i = v.indexOf("horizontal:");
  13545. }
  13546. if (i !== -1) {
  13547. v = v.substr(v.indexOf(":") + 1);
  13548. this._setTextAlignmentHorizontal(v);
  13549. continue;
  13550. }
  13551. // Vertical
  13552. i = v.indexOf("v:");
  13553. if (i === -1) {
  13554. i = v.indexOf("vertical:");
  13555. }
  13556. if (i !== -1) {
  13557. v = v.substr(v.indexOf(":") + 1);
  13558. this._setTextAlignmentVertical(v);
  13559. continue;
  13560. }
  13561. }
  13562. };
  13563. Text2D.prototype._setTextAlignmentHorizontal = function (text) {
  13564. var v = text.trim().toLocaleLowerCase();
  13565. switch (v) {
  13566. case "left":
  13567. this.textAlignmentH = Text2D_1.AlignLeft;
  13568. return;
  13569. case "right":
  13570. this.textAlignmentH = Text2D_1.AlignRight;
  13571. return;
  13572. case "center":
  13573. this.textAlignmentH = Text2D_1.AlignCenter;
  13574. return;
  13575. }
  13576. };
  13577. Text2D.prototype._setTextAlignmentVertical = function (text) {
  13578. var v = text.trim().toLocaleLowerCase();
  13579. switch (v) {
  13580. case "top":
  13581. this.textAlignmentV = Text2D_1.AlignTop;
  13582. return;
  13583. case "bottom":
  13584. this.textAlignmentV = Text2D_1.AlignBottom;
  13585. return;
  13586. case "center":
  13587. this.textAlignmentV = Text2D_1.AlignCenter;
  13588. return;
  13589. }
  13590. };
  13591. Text2D.prototype._useTextureAlpha = function () {
  13592. return this._fontSDF;
  13593. };
  13594. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  13595. return !this._fontSDF;
  13596. };
  13597. return Text2D;
  13598. }(BABYLON.RenderablePrim2D));
  13599. Text2D.TEXT2D_MAINPARTID = 1;
  13600. Text2D.TEXT2D_CATEGORY_SDF = "SignedDistanceField";
  13601. Text2D._AlignLeft = 1;
  13602. Text2D._AlignTop = 1; // Same as left
  13603. Text2D._AlignRight = 2;
  13604. Text2D._AlignBottom = 2; // Same as right
  13605. Text2D._AlignCenter = 3;
  13606. __decorate([
  13607. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D_1.fontProperty = pi; }, false, true)
  13608. ], Text2D.prototype, "fontName", null);
  13609. __decorate([
  13610. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D_1.defaultFontColorProperty = pi; })
  13611. ], Text2D.prototype, "defaultFontColor", null);
  13612. __decorate([
  13613. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D_1.textProperty = pi; }, false, true)
  13614. ], Text2D.prototype, "text", null);
  13615. __decorate([
  13616. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D_1.sizeProperty = pi; })
  13617. ], Text2D.prototype, "size", null);
  13618. __decorate([
  13619. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  13620. ], Text2D.prototype, "fontSuperSample", null);
  13621. __decorate([
  13622. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  13623. ], Text2D.prototype, "fontSignedDistanceField", null);
  13624. Text2D = Text2D_1 = __decorate([
  13625. BABYLON.className("Text2D", "BABYLON")
  13626. ], Text2D);
  13627. BABYLON.Text2D = Text2D;
  13628. var Text2D_1;
  13629. })(BABYLON || (BABYLON = {}));
  13630. var __extends = (this && this.__extends) || function (d, b) {
  13631. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13632. function __() { this.constructor = d; }
  13633. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13634. };
  13635. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13636. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13637. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13638. 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;
  13639. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13640. };
  13641. var BABYLON;
  13642. (function (BABYLON) {
  13643. var Lines2DRenderCache = (function (_super) {
  13644. __extends(Lines2DRenderCache, _super);
  13645. function Lines2DRenderCache(engine, modelKey) {
  13646. var _this = _super.call(this, engine, modelKey) || this;
  13647. _this.effectsReady = false;
  13648. _this.fillVB = null;
  13649. _this.fillIB = null;
  13650. _this.fillIndicesCount = 0;
  13651. _this.instancingFillAttributes = null;
  13652. _this.effectFill = null;
  13653. _this.effectFillInstanced = null;
  13654. _this.borderVB = null;
  13655. _this.borderIB = null;
  13656. _this.borderIndicesCount = 0;
  13657. _this.instancingBorderAttributes = null;
  13658. _this.effectBorder = null;
  13659. _this.effectBorderInstanced = null;
  13660. return _this;
  13661. }
  13662. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  13663. // Do nothing if the shader is still loading/preparing
  13664. if (!this.effectsReady) {
  13665. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  13666. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  13667. return false;
  13668. }
  13669. this.effectsReady = true;
  13670. }
  13671. var canvas = instanceInfo.owner.owner;
  13672. var engine = canvas.engine;
  13673. engine.setState(false, undefined, true);
  13674. var depthFunction = 0;
  13675. if (this.effectFill && this.effectBorder) {
  13676. depthFunction = engine.getDepthFunction();
  13677. engine.setDepthFunctionToLessOrEqual();
  13678. }
  13679. var curAlphaMode = engine.getAlphaMode();
  13680. if (this.effectFill) {
  13681. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  13682. var pid = context.groupInfoPartData[partIndex];
  13683. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13684. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13685. }
  13686. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  13687. engine.enableEffect(effect);
  13688. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  13689. if (context.useInstancing) {
  13690. if (!this.instancingFillAttributes) {
  13691. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  13692. }
  13693. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13694. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13695. canvas._addDrawCallCount(1, context.renderMode);
  13696. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  13697. engine.draw(true, 0, this.fillIndicesCount, count);
  13698. engine.unbindInstanceAttributes();
  13699. }
  13700. else {
  13701. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13702. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13703. this.setupUniforms(effect, partIndex, pid._partData, i);
  13704. engine.draw(true, 0, this.fillIndicesCount);
  13705. }
  13706. }
  13707. }
  13708. if (this.effectBorder) {
  13709. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  13710. var pid = context.groupInfoPartData[partIndex];
  13711. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13712. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13713. }
  13714. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  13715. engine.enableEffect(effect);
  13716. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  13717. if (context.useInstancing) {
  13718. if (!this.instancingBorderAttributes) {
  13719. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  13720. }
  13721. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13722. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13723. canvas._addDrawCallCount(1, context.renderMode);
  13724. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  13725. engine.draw(true, 0, this.borderIndicesCount, count);
  13726. engine.unbindInstanceAttributes();
  13727. }
  13728. else {
  13729. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13730. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13731. this.setupUniforms(effect, partIndex, pid._partData, i);
  13732. engine.draw(true, 0, this.borderIndicesCount);
  13733. }
  13734. }
  13735. }
  13736. engine.setAlphaMode(curAlphaMode, true);
  13737. if (this.effectFill && this.effectBorder) {
  13738. engine.setDepthFunction(depthFunction);
  13739. }
  13740. return true;
  13741. };
  13742. Lines2DRenderCache.prototype.dispose = function () {
  13743. if (!_super.prototype.dispose.call(this)) {
  13744. return false;
  13745. }
  13746. if (this.fillVB) {
  13747. this._engine._releaseBuffer(this.fillVB);
  13748. this.fillVB = null;
  13749. }
  13750. if (this.fillIB) {
  13751. this._engine._releaseBuffer(this.fillIB);
  13752. this.fillIB = null;
  13753. }
  13754. this.effectFill = null;
  13755. this.effectFillInstanced = null;
  13756. this.effectBorder = null;
  13757. this.effectBorderInstanced = null;
  13758. if (this.borderVB) {
  13759. this._engine._releaseBuffer(this.borderVB);
  13760. this.borderVB = null;
  13761. }
  13762. if (this.borderIB) {
  13763. this._engine._releaseBuffer(this.borderIB);
  13764. this.borderIB = null;
  13765. }
  13766. return true;
  13767. };
  13768. return Lines2DRenderCache;
  13769. }(BABYLON.ModelRenderCache));
  13770. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  13771. var Lines2DInstanceData = (function (_super) {
  13772. __extends(Lines2DInstanceData, _super);
  13773. function Lines2DInstanceData(partId) {
  13774. return _super.call(this, partId, 1) || this;
  13775. }
  13776. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  13777. get: function () {
  13778. return null;
  13779. },
  13780. set: function (value) {
  13781. },
  13782. enumerable: true,
  13783. configurable: true
  13784. });
  13785. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  13786. get: function () {
  13787. return null;
  13788. },
  13789. set: function (value) {
  13790. },
  13791. enumerable: true,
  13792. configurable: true
  13793. });
  13794. return Lines2DInstanceData;
  13795. }(BABYLON.Shape2DInstanceData));
  13796. __decorate([
  13797. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  13798. ], Lines2DInstanceData.prototype, "boundingMin", null);
  13799. __decorate([
  13800. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  13801. ], Lines2DInstanceData.prototype, "boundingMax", null);
  13802. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  13803. var Lines2D = Lines2D_1 = (function (_super) {
  13804. __extends(Lines2D, _super);
  13805. /**
  13806. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  13807. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  13808. * @param settings a combination of settings, possible ones are
  13809. * - 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)
  13810. * - children: an array of direct children
  13811. * - id a text identifier, for information purpose
  13812. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13813. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13814. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13815. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13816. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13817. * - zOrder: override the zOrder with the specified value
  13818. * - origin: define the normalized origin point location, default [0.5;0.5]
  13819. * - 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.
  13820. * - 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.
  13821. * - 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.
  13822. * - 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.
  13823. * - 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)
  13824. * - 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)
  13825. * - borderThickness: the thickness of the drawn border, default is 1.
  13826. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  13827. * - 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.
  13828. * - 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.
  13829. * - 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!
  13830. * - 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.
  13831. * - 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).
  13832. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13833. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13834. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13835. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13836. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13837. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13838. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13839. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13840. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13841. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13842. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13843. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13844. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13845. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13846. */
  13847. function Lines2D(points, settings) {
  13848. var _this = this;
  13849. if (!settings) {
  13850. settings = {};
  13851. }
  13852. _this = _super.call(this, settings) || this;
  13853. _this._fillVB = null;
  13854. _this._fillIB = null;
  13855. _this._borderVB = null;
  13856. _this._borderIB = null;
  13857. _this._size = BABYLON.Size.Zero();
  13858. _this._boundingMin = null;
  13859. _this._boundingMax = null;
  13860. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  13861. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  13862. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  13863. var closed = (settings.closed == null) ? false : settings.closed;
  13864. _this.points = points;
  13865. _this.fillThickness = fillThickness;
  13866. _this.startCap = startCap;
  13867. _this.endCap = endCap;
  13868. _this.closed = closed;
  13869. return _this;
  13870. }
  13871. Object.defineProperty(Lines2D, "NoCap", {
  13872. /**
  13873. * No Cap to apply on the extremity
  13874. */
  13875. get: function () { return Lines2D_1._noCap; },
  13876. enumerable: true,
  13877. configurable: true
  13878. });
  13879. Object.defineProperty(Lines2D, "RoundCap", {
  13880. /**
  13881. * A round cap, will use the line thickness as diameter
  13882. */
  13883. get: function () { return Lines2D_1._roundCap; },
  13884. enumerable: true,
  13885. configurable: true
  13886. });
  13887. Object.defineProperty(Lines2D, "TriangleCap", {
  13888. /**
  13889. * Creates a triangle at the extremity.
  13890. */
  13891. get: function () { return Lines2D_1._triangleCap; },
  13892. enumerable: true,
  13893. configurable: true
  13894. });
  13895. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  13896. /**
  13897. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  13898. */
  13899. get: function () { return Lines2D_1._squareAnchorCap; },
  13900. enumerable: true,
  13901. configurable: true
  13902. });
  13903. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  13904. /**
  13905. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  13906. */
  13907. get: function () { return Lines2D_1._roundAnchorCap; },
  13908. enumerable: true,
  13909. configurable: true
  13910. });
  13911. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  13912. /**
  13913. * Creates a diamond anchor at the extremity.
  13914. */
  13915. get: function () { return Lines2D_1._diamondAnchorCap; },
  13916. enumerable: true,
  13917. configurable: true
  13918. });
  13919. Object.defineProperty(Lines2D, "ArrowCap", {
  13920. /**
  13921. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  13922. */
  13923. get: function () { return Lines2D_1._arrowCap; },
  13924. enumerable: true,
  13925. configurable: true
  13926. });
  13927. Object.defineProperty(Lines2D.prototype, "points", {
  13928. get: function () {
  13929. return this._points;
  13930. },
  13931. set: function (value) {
  13932. this._points = value;
  13933. this._primTriArrayDirty = true;
  13934. this._boundingBoxDirty();
  13935. },
  13936. enumerable: true,
  13937. configurable: true
  13938. });
  13939. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  13940. get: function () {
  13941. return this._fillThickness;
  13942. },
  13943. set: function (value) {
  13944. this._fillThickness = value;
  13945. },
  13946. enumerable: true,
  13947. configurable: true
  13948. });
  13949. Object.defineProperty(Lines2D.prototype, "closed", {
  13950. get: function () {
  13951. return this._closed;
  13952. },
  13953. set: function (value) {
  13954. this._closed = value;
  13955. },
  13956. enumerable: true,
  13957. configurable: true
  13958. });
  13959. Object.defineProperty(Lines2D.prototype, "startCap", {
  13960. get: function () {
  13961. return this._startCap;
  13962. },
  13963. set: function (value) {
  13964. this._startCap = value;
  13965. },
  13966. enumerable: true,
  13967. configurable: true
  13968. });
  13969. Object.defineProperty(Lines2D.prototype, "endCap", {
  13970. get: function () {
  13971. return this._endCap;
  13972. },
  13973. set: function (value) {
  13974. this._endCap = value;
  13975. },
  13976. enumerable: true,
  13977. configurable: true
  13978. });
  13979. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  13980. var p = intersectInfo._localPickPosition;
  13981. this.updateTriArray();
  13982. return this._primTriArray.doesContain(p);
  13983. };
  13984. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  13985. get: function () {
  13986. if (!this._boundingMin) {
  13987. this._computeLines2D();
  13988. }
  13989. return this._boundingMin;
  13990. },
  13991. enumerable: true,
  13992. configurable: true
  13993. });
  13994. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  13995. get: function () {
  13996. if (!this._boundingMax) {
  13997. this._computeLines2D();
  13998. }
  13999. return this._boundingMax;
  14000. },
  14001. enumerable: true,
  14002. configurable: true
  14003. });
  14004. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  14005. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  14006. // Remove the BORDER category, we don't use it in the VertexShader
  14007. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  14008. if (i !== -1) {
  14009. res.splice(i, 1);
  14010. }
  14011. return res;
  14012. };
  14013. Lines2D.prototype.updateLevelBoundingInfo = function () {
  14014. if (!this._size) {
  14015. return false;
  14016. }
  14017. if (!this._boundingMin) {
  14018. this._computeLines2D();
  14019. }
  14020. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  14021. return true;
  14022. };
  14023. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  14024. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  14025. return renderCache;
  14026. };
  14027. ///////////////////////////////////////////////////////////////////////////////////
  14028. // Methods for Lines building
  14029. Lines2D.prototype._perp = function (v, res) {
  14030. res.x = v.y;
  14031. res.y = -v.x;
  14032. };
  14033. ;
  14034. Lines2D.prototype._direction = function (a, b, res) {
  14035. a.subtractToRef(b, res);
  14036. res.normalize();
  14037. };
  14038. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  14039. a.addToRef(b, tangent);
  14040. tangent.normalize();
  14041. miter.x = -tangent.y;
  14042. miter.y = tangent.x;
  14043. Lines2D_1._miterTps.x = -a.y;
  14044. Lines2D_1._miterTps.y = a.x;
  14045. return 1 / BABYLON.Vector2.Dot(miter, Lines2D_1._miterTps);
  14046. };
  14047. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  14048. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  14049. if (d === 0)
  14050. return false;
  14051. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  14052. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  14053. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  14054. return false;
  14055. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  14056. return false;
  14057. return true;
  14058. };
  14059. Lines2D.prototype._updateMinMax = function (array, offset) {
  14060. if (offset >= array.length) {
  14061. return;
  14062. }
  14063. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  14064. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  14065. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  14066. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  14067. };
  14068. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  14069. var borderMode = borderThickness != null && !isNaN(borderThickness);
  14070. var off = index * (borderMode ? 8 : 4);
  14071. // 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)
  14072. if (off >= array.length) {
  14073. return;
  14074. }
  14075. // Store start/end normal, we need it for the cap construction
  14076. if (index === 0) {
  14077. this._perp(n, Lines2D_1._startDir);
  14078. }
  14079. else if (index === max - 1) {
  14080. this._perp(n, Lines2D_1._endDir);
  14081. Lines2D_1._endDir.x *= -1;
  14082. Lines2D_1._endDir.y *= -1;
  14083. }
  14084. var swap = false;
  14085. array[off + 0] = p.x + n.x * halfThickness;
  14086. array[off + 1] = p.y + n.y * halfThickness;
  14087. array[off + 2] = p.x + n.x * -halfThickness;
  14088. array[off + 3] = p.y + n.y * -halfThickness;
  14089. this._updateMinMax(array, off);
  14090. this._updateMinMax(array, off + 2);
  14091. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  14092. // 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
  14093. if (detectFlip != 0) {
  14094. // Flip if intersect
  14095. var flipOff = detectFlip * (borderMode ? 8 : 4);
  14096. 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])) {
  14097. swap = true;
  14098. var tps = array[off + 0];
  14099. array[off + 0] = array[off + 2];
  14100. array[off + 2] = tps;
  14101. tps = array[off + 1];
  14102. array[off + 1] = array[off + 3];
  14103. array[off + 3] = tps;
  14104. }
  14105. }
  14106. if (borderMode) {
  14107. var t = halfThickness + borderThickness;
  14108. array[off + 4] = p.x + n.x * (swap ? -t : t);
  14109. array[off + 5] = p.y + n.y * (swap ? -t : t);
  14110. array[off + 6] = p.x + n.x * (swap ? t : -t);
  14111. array[off + 7] = p.y + n.y * (swap ? t : -t);
  14112. this._updateMinMax(array, off + 4);
  14113. this._updateMinMax(array, off + 6);
  14114. }
  14115. if (contour) {
  14116. off += borderMode ? 4 : 0;
  14117. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  14118. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  14119. }
  14120. };
  14121. Lines2D.prototype._getCapSize = function (type, border) {
  14122. if (border === void 0) { border = false; }
  14123. var sd = Lines2D_1._roundCapSubDiv;
  14124. // If no array given, we call this to get the size
  14125. var vbsize = 0, ibsize = 0;
  14126. switch (type) {
  14127. case Lines2D_1.NoCap:
  14128. {
  14129. // If the line is not close and we're computing border, we add the size to generate the edge border
  14130. if (!this.closed && border) {
  14131. vbsize = 4;
  14132. ibsize = 6;
  14133. }
  14134. else {
  14135. vbsize = ibsize = 0;
  14136. }
  14137. break;
  14138. }
  14139. case Lines2D_1.RoundCap:
  14140. {
  14141. if (border) {
  14142. vbsize = sd;
  14143. ibsize = (sd - 2) * 3;
  14144. }
  14145. else {
  14146. vbsize = (sd / 2) + 1;
  14147. ibsize = (sd / 2) * 3;
  14148. }
  14149. break;
  14150. }
  14151. case Lines2D_1.ArrowCap:
  14152. {
  14153. if (border) {
  14154. vbsize = 12;
  14155. ibsize = 24;
  14156. }
  14157. else {
  14158. vbsize = 3;
  14159. ibsize = 3;
  14160. }
  14161. break;
  14162. }
  14163. case Lines2D_1.TriangleCap:
  14164. {
  14165. if (border) {
  14166. vbsize = 6;
  14167. ibsize = 12;
  14168. }
  14169. else {
  14170. vbsize = 3;
  14171. ibsize = 3;
  14172. }
  14173. break;
  14174. }
  14175. case Lines2D_1.DiamondAnchorCap:
  14176. {
  14177. if (border) {
  14178. vbsize = 10;
  14179. ibsize = 24;
  14180. }
  14181. else {
  14182. vbsize = 5;
  14183. ibsize = 9;
  14184. }
  14185. break;
  14186. }
  14187. case Lines2D_1.SquareAnchorCap:
  14188. {
  14189. if (border) {
  14190. vbsize = 12;
  14191. ibsize = 30;
  14192. }
  14193. else {
  14194. vbsize = 4;
  14195. ibsize = 6;
  14196. }
  14197. break;
  14198. }
  14199. case Lines2D_1.RoundAnchorCap:
  14200. {
  14201. if (border) {
  14202. vbsize = sd * 2;
  14203. ibsize = (sd - 1) * 6;
  14204. }
  14205. else {
  14206. vbsize = sd + 1;
  14207. ibsize = (sd + 1) * 3;
  14208. }
  14209. break;
  14210. }
  14211. }
  14212. return { vbsize: vbsize * 2, ibsize: ibsize };
  14213. };
  14214. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  14215. var c = Math.cos(rotation);
  14216. var s = Math.sin(rotation);
  14217. Lines2D_1._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  14218. Lines2D_1._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  14219. var offset = baseOffset + (index * 2);
  14220. vb[offset + 0] = Lines2D_1._tpsV.x;
  14221. vb[offset + 1] = Lines2D_1._tpsV.y;
  14222. if (contour) {
  14223. contour.push(Lines2D_1._tpsV.x);
  14224. contour.push(Lines2D_1._tpsV.y);
  14225. }
  14226. this._updateMinMax(vb, offset);
  14227. return (baseOffset + index * 2) / 2;
  14228. };
  14229. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  14230. ib[baseOffset + index] = vertexIndex;
  14231. };
  14232. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  14233. // 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
  14234. var sd = Lines2D_1._roundCapSubDiv;
  14235. var dir = new BABYLON.Vector2(1, 0);
  14236. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  14237. var ht = thickness / 2;
  14238. var t = thickness;
  14239. var borderMode = borderThickness != null;
  14240. var bt = borderThickness;
  14241. switch (type) {
  14242. case Lines2D_1.NoCap:
  14243. if (borderMode && !this.closed) {
  14244. var vi = 0;
  14245. var ii = 0;
  14246. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  14247. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  14248. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  14249. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  14250. this._storeIndex(ib, ibi, ii++, v1);
  14251. this._storeIndex(ib, ibi, ii++, v2);
  14252. this._storeIndex(ib, ibi, ii++, v3);
  14253. this._storeIndex(ib, ibi, ii++, v1);
  14254. this._storeIndex(ib, ibi, ii++, v3);
  14255. this._storeIndex(ib, ibi, ii++, v4);
  14256. }
  14257. break;
  14258. case Lines2D_1.ArrowCap:
  14259. ht *= 2;
  14260. case Lines2D_1.TriangleCap:
  14261. {
  14262. if (borderMode) {
  14263. var f = type === Lines2D_1.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  14264. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  14265. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  14266. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  14267. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  14268. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  14269. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  14270. var ii = 0;
  14271. this._storeIndex(ib, ibi, ii++, v1);
  14272. this._storeIndex(ib, ibi, ii++, v4);
  14273. this._storeIndex(ib, ibi, ii++, v5);
  14274. this._storeIndex(ib, ibi, ii++, v1);
  14275. this._storeIndex(ib, ibi, ii++, v5);
  14276. this._storeIndex(ib, ibi, ii++, v2);
  14277. this._storeIndex(ib, ibi, ii++, v6);
  14278. this._storeIndex(ib, ibi, ii++, v3);
  14279. this._storeIndex(ib, ibi, ii++, v2);
  14280. this._storeIndex(ib, ibi, ii++, v6);
  14281. this._storeIndex(ib, ibi, ii++, v2);
  14282. this._storeIndex(ib, ibi, ii++, v5);
  14283. if (type === Lines2D_1.ArrowCap) {
  14284. var rht = thickness / 2;
  14285. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  14286. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  14287. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  14288. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  14289. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  14290. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  14291. this._storeIndex(ib, ibi, ii++, v7);
  14292. this._storeIndex(ib, ibi, ii++, v8);
  14293. this._storeIndex(ib, ibi, ii++, v9);
  14294. this._storeIndex(ib, ibi, ii++, v7);
  14295. this._storeIndex(ib, ibi, ii++, v9);
  14296. this._storeIndex(ib, ibi, ii++, v4);
  14297. this._storeIndex(ib, ibi, ii++, v10);
  14298. this._storeIndex(ib, ibi, ii++, v12);
  14299. this._storeIndex(ib, ibi, ii++, v11);
  14300. this._storeIndex(ib, ibi, ii++, v10);
  14301. this._storeIndex(ib, ibi, ii++, v6);
  14302. this._storeIndex(ib, ibi, ii++, v12);
  14303. }
  14304. }
  14305. else {
  14306. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  14307. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  14308. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  14309. this._storeIndex(ib, ibi, 0, v1);
  14310. this._storeIndex(ib, ibi, 1, v2);
  14311. this._storeIndex(ib, ibi, 2, v3);
  14312. }
  14313. break;
  14314. }
  14315. case Lines2D_1.RoundCap:
  14316. {
  14317. if (borderMode) {
  14318. var curA = -Math.PI / 2;
  14319. var incA = Math.PI / (sd / 2 - 1);
  14320. var ii = 0;
  14321. for (var i = 0; i < (sd / 2); i++) {
  14322. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  14323. 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);
  14324. if (i > 0) {
  14325. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14326. this._storeIndex(ib, ibi, ii++, v2 - 2);
  14327. this._storeIndex(ib, ibi, ii++, v2);
  14328. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14329. this._storeIndex(ib, ibi, ii++, v2);
  14330. this._storeIndex(ib, ibi, ii++, v1);
  14331. }
  14332. curA += incA;
  14333. }
  14334. }
  14335. else {
  14336. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  14337. var curA = -Math.PI / 2;
  14338. var incA = Math.PI / (sd / 2 - 1);
  14339. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  14340. curA += incA;
  14341. for (var i = 1; i < (sd / 2); i++) {
  14342. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  14343. this._storeIndex(ib, ibi, i * 3 + 0, c);
  14344. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  14345. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  14346. curA += incA;
  14347. }
  14348. }
  14349. break;
  14350. }
  14351. case Lines2D_1.SquareAnchorCap:
  14352. {
  14353. var vi = 0;
  14354. var c = borderMode ? null : contour;
  14355. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  14356. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  14357. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  14358. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  14359. if (borderMode) {
  14360. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  14361. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  14362. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  14363. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  14364. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  14365. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  14366. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  14367. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  14368. var ii = 0;
  14369. this._storeIndex(ib, ibi, ii++, v6);
  14370. this._storeIndex(ib, ibi, ii++, v1);
  14371. this._storeIndex(ib, ibi, ii++, v5);
  14372. this._storeIndex(ib, ibi, ii++, v6);
  14373. this._storeIndex(ib, ibi, ii++, v7);
  14374. this._storeIndex(ib, ibi, ii++, v1);
  14375. this._storeIndex(ib, ibi, ii++, v1);
  14376. this._storeIndex(ib, ibi, ii++, v7);
  14377. this._storeIndex(ib, ibi, ii++, v8);
  14378. this._storeIndex(ib, ibi, ii++, v1);
  14379. this._storeIndex(ib, ibi, ii++, v8);
  14380. this._storeIndex(ib, ibi, ii++, v2);
  14381. this._storeIndex(ib, ibi, ii++, v2);
  14382. this._storeIndex(ib, ibi, ii++, v8);
  14383. this._storeIndex(ib, ibi, ii++, v9);
  14384. this._storeIndex(ib, ibi, ii++, v2);
  14385. this._storeIndex(ib, ibi, ii++, v9);
  14386. this._storeIndex(ib, ibi, ii++, v3);
  14387. this._storeIndex(ib, ibi, ii++, v3);
  14388. this._storeIndex(ib, ibi, ii++, v9);
  14389. this._storeIndex(ib, ibi, ii++, v10);
  14390. this._storeIndex(ib, ibi, ii++, v3);
  14391. this._storeIndex(ib, ibi, ii++, v10);
  14392. this._storeIndex(ib, ibi, ii++, v4);
  14393. this._storeIndex(ib, ibi, ii++, v10);
  14394. this._storeIndex(ib, ibi, ii++, v11);
  14395. this._storeIndex(ib, ibi, ii++, v4);
  14396. this._storeIndex(ib, ibi, ii++, v11);
  14397. this._storeIndex(ib, ibi, ii++, v12);
  14398. this._storeIndex(ib, ibi, ii++, v4);
  14399. }
  14400. else {
  14401. this._storeIndex(ib, ibi, 0, v1);
  14402. this._storeIndex(ib, ibi, 1, v2);
  14403. this._storeIndex(ib, ibi, 2, v3);
  14404. this._storeIndex(ib, ibi, 3, v1);
  14405. this._storeIndex(ib, ibi, 4, v3);
  14406. this._storeIndex(ib, ibi, 5, v4);
  14407. }
  14408. break;
  14409. }
  14410. case Lines2D_1.RoundAnchorCap:
  14411. {
  14412. var cpos = Math.sqrt(t * t - ht * ht);
  14413. var center = new BABYLON.Vector2(cpos, 0);
  14414. var curA = BABYLON.Tools.ToRadians(-150);
  14415. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  14416. if (borderMode) {
  14417. var ii = 0;
  14418. for (var i = 0; i < sd; i++) {
  14419. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  14420. 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);
  14421. if (i > 0) {
  14422. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14423. this._storeIndex(ib, ibi, ii++, v2 - 2);
  14424. this._storeIndex(ib, ibi, ii++, v2);
  14425. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14426. this._storeIndex(ib, ibi, ii++, v2);
  14427. this._storeIndex(ib, ibi, ii++, v1);
  14428. }
  14429. curA += incA;
  14430. }
  14431. }
  14432. else {
  14433. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  14434. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  14435. curA += incA;
  14436. for (var i = 1; i < sd; i++) {
  14437. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  14438. this._storeIndex(ib, ibi, i * 3 + 0, c);
  14439. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  14440. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  14441. curA += incA;
  14442. }
  14443. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  14444. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  14445. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  14446. }
  14447. break;
  14448. }
  14449. case Lines2D_1.DiamondAnchorCap:
  14450. {
  14451. var vi = 0;
  14452. var c = borderMode ? null : contour;
  14453. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  14454. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  14455. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  14456. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  14457. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  14458. if (borderMode) {
  14459. var f = Math.sqrt(bt * bt * 2);
  14460. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  14461. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  14462. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  14463. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  14464. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  14465. var ii = 0;
  14466. this._storeIndex(ib, ibi, ii++, v6);
  14467. this._storeIndex(ib, ibi, ii++, v7);
  14468. this._storeIndex(ib, ibi, ii++, v1);
  14469. this._storeIndex(ib, ibi, ii++, v1);
  14470. this._storeIndex(ib, ibi, ii++, v7);
  14471. this._storeIndex(ib, ibi, ii++, v2);
  14472. this._storeIndex(ib, ibi, ii++, v2);
  14473. this._storeIndex(ib, ibi, ii++, v7);
  14474. this._storeIndex(ib, ibi, ii++, v8);
  14475. this._storeIndex(ib, ibi, ii++, v2);
  14476. this._storeIndex(ib, ibi, ii++, v8);
  14477. this._storeIndex(ib, ibi, ii++, v3);
  14478. this._storeIndex(ib, ibi, ii++, v3);
  14479. this._storeIndex(ib, ibi, ii++, v8);
  14480. this._storeIndex(ib, ibi, ii++, v9);
  14481. this._storeIndex(ib, ibi, ii++, v3);
  14482. this._storeIndex(ib, ibi, ii++, v9);
  14483. this._storeIndex(ib, ibi, ii++, v4);
  14484. this._storeIndex(ib, ibi, ii++, v4);
  14485. this._storeIndex(ib, ibi, ii++, v9);
  14486. this._storeIndex(ib, ibi, ii++, v10);
  14487. this._storeIndex(ib, ibi, ii++, v4);
  14488. this._storeIndex(ib, ibi, ii++, v10);
  14489. this._storeIndex(ib, ibi, ii++, v5);
  14490. }
  14491. else {
  14492. this._storeIndex(ib, ibi, 0, v1);
  14493. this._storeIndex(ib, ibi, 1, v2);
  14494. this._storeIndex(ib, ibi, 2, v3);
  14495. this._storeIndex(ib, ibi, 3, v1);
  14496. this._storeIndex(ib, ibi, 4, v3);
  14497. this._storeIndex(ib, ibi, 5, v5);
  14498. this._storeIndex(ib, ibi, 6, v5);
  14499. this._storeIndex(ib, ibi, 7, v3);
  14500. this._storeIndex(ib, ibi, 8, v4);
  14501. }
  14502. break;
  14503. }
  14504. }
  14505. return null;
  14506. };
  14507. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  14508. var lineA = BABYLON.Vector2.Zero();
  14509. var lineB = BABYLON.Vector2.Zero();
  14510. var tangent = BABYLON.Vector2.Zero();
  14511. var miter = BABYLON.Vector2.Zero();
  14512. var curNormal = null;
  14513. if (this.closed) {
  14514. this.points.push(this.points[0]);
  14515. }
  14516. var total = this.points.length;
  14517. for (var i = 1; i < total; i++) {
  14518. var last = this.points[i - 1];
  14519. var cur = this.points[i];
  14520. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  14521. this._direction(cur, last, lineA);
  14522. if (!curNormal) {
  14523. curNormal = BABYLON.Vector2.Zero();
  14524. this._perp(lineA, curNormal);
  14525. }
  14526. if (i === 1) {
  14527. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  14528. }
  14529. if (!next) {
  14530. this._perp(lineA, curNormal);
  14531. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  14532. }
  14533. else {
  14534. this._direction(next, cur, lineB);
  14535. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  14536. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  14537. }
  14538. }
  14539. if (this.points.length > 2 && this.closed) {
  14540. var last2 = this.points[total - 2];
  14541. var cur2 = this.points[0];
  14542. var next2 = this.points[1];
  14543. this._direction(cur2, last2, lineA);
  14544. this._direction(next2, cur2, lineB);
  14545. this._perp(lineA, curNormal);
  14546. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  14547. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  14548. // Patch contour
  14549. if (contour) {
  14550. var off = (bt == null) ? 0 : 4;
  14551. contour[0].x = vb[off + 0];
  14552. contour[0].y = vb[off + 1];
  14553. contour[1].x = vb[off + 2];
  14554. contour[1].y = vb[off + 3];
  14555. }
  14556. }
  14557. // Remove the point we added at the beginning
  14558. if (this.closed) {
  14559. this.points.splice(total - 1);
  14560. }
  14561. };
  14562. // Methods for Lines building
  14563. ///////////////////////////////////////////////////////////////////////////////////
  14564. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  14565. var renderCache = modelRenderCache;
  14566. var engine = this.owner.engine;
  14567. if (this._fillVB === null) {
  14568. this._computeLines2D();
  14569. }
  14570. // Need to create WebGL resources for fill part?
  14571. if (this.fill) {
  14572. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  14573. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  14574. renderCache.fillIndicesCount = this._fillIB.length;
  14575. // 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
  14576. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  14577. if (ei) {
  14578. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  14579. }
  14580. // Get the non instanced version
  14581. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  14582. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  14583. }
  14584. // Need to create WebGL resources for border part?
  14585. if (this.border) {
  14586. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  14587. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  14588. renderCache.borderIndicesCount = this._borderIB.length;
  14589. // 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
  14590. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  14591. if (ei) {
  14592. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  14593. }
  14594. // Get the non instanced version
  14595. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  14596. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  14597. }
  14598. this._fillVB = null;
  14599. this._fillIB = null;
  14600. this._borderVB = null;
  14601. this._borderIB = null;
  14602. return renderCache;
  14603. };
  14604. Lines2D.prototype.updateTriArray = function () {
  14605. if (this._primTriArrayDirty) {
  14606. this._computeLines2D();
  14607. }
  14608. };
  14609. Lines2D.prototype._computeLines2D = function () {
  14610. var _this = this;
  14611. // Init min/max because their being computed here
  14612. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  14613. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  14614. var contour = new Array();
  14615. var startCapContour = new Array();
  14616. var endCapContour = new Array();
  14617. // Need to create WebGL resources for fill part?
  14618. if (this.fill) {
  14619. var startCapInfo = this._getCapSize(this.startCap);
  14620. var endCapInfo = this._getCapSize(this.endCap);
  14621. var count = this.points.length;
  14622. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  14623. this._fillVB = new Float32Array(vbSize);
  14624. var vb = this._fillVB;
  14625. var ht = this.fillThickness / 2;
  14626. var total = this.points.length;
  14627. this._buildLine(vb, this.border ? null : contour, ht);
  14628. var max = total * 2;
  14629. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  14630. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  14631. var ib = this._fillIB;
  14632. for (var i = 0; i < triCount; i += 2) {
  14633. ib[i * 3 + 0] = i + 0;
  14634. ib[i * 3 + 1] = i + 1;
  14635. ib[i * 3 + 2] = (i + 2) % max;
  14636. ib[i * 3 + 3] = i + 1;
  14637. ib[i * 3 + 4] = (i + 3) % max;
  14638. ib[i * 3 + 5] = (i + 2) % max;
  14639. }
  14640. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D_1._startDir, this.border ? null : startCapContour);
  14641. 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);
  14642. }
  14643. // Need to create WebGL resources for border part?
  14644. if (this.border) {
  14645. var startCapInfo = this._getCapSize(this.startCap, true);
  14646. var endCapInfo = this._getCapSize(this.endCap, true);
  14647. var count = this.points.length;
  14648. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  14649. this._borderVB = new Float32Array(vbSize);
  14650. var vb = this._borderVB;
  14651. var ht = this.fillThickness / 2;
  14652. var bt = this.borderThickness;
  14653. var total = this.points.length;
  14654. this._buildLine(vb, contour, ht, bt);
  14655. var max = total * 2 * 2;
  14656. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  14657. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  14658. var ib = this._borderIB;
  14659. for (var i = 0; i < triCount; i += 4) {
  14660. ib[i * 3 + 0] = i + 0;
  14661. ib[i * 3 + 1] = i + 2;
  14662. ib[i * 3 + 2] = (i + 6) % max;
  14663. ib[i * 3 + 3] = i + 0;
  14664. ib[i * 3 + 4] = (i + 6) % max;
  14665. ib[i * 3 + 5] = (i + 4) % max;
  14666. ib[i * 3 + 6] = i + 3;
  14667. ib[i * 3 + 7] = i + 1;
  14668. ib[i * 3 + 8] = (i + 5) % max;
  14669. ib[i * 3 + 9] = i + 3;
  14670. ib[i * 3 + 10] = (i + 5) % max;
  14671. ib[i * 3 + 11] = (i + 7) % max;
  14672. }
  14673. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D_1._startDir, startCapContour);
  14674. 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);
  14675. }
  14676. var startCapTri;
  14677. if (startCapContour.length > 0) {
  14678. startCapTri = Earcut.earcut(startCapContour, null, 2);
  14679. }
  14680. var endCapTri;
  14681. if (endCapContour.length > 0) {
  14682. endCapTri = Earcut.earcut(endCapContour, null, 2);
  14683. }
  14684. // Build the Tri2DArray using the contour info from the shape and the caps (if any)
  14685. {
  14686. var pl = this.points.length;
  14687. // Count the number of needed triangles
  14688. var count = ((this.closed ? pl : (pl - 1)) * 2) + (startCapTri != null ? ((startCapTri.length + endCapTri.length) / 3) : 0);
  14689. // Init/Clear the TriArray
  14690. if (!this._primTriArray) {
  14691. this._primTriArray = new BABYLON.Tri2DArray(count);
  14692. }
  14693. else {
  14694. this._primTriArray.clear(count);
  14695. }
  14696. var pta_1 = this._primTriArray;
  14697. var l = this.closed ? pl + 1 : pl;
  14698. this.transformPointWithOriginToRef(contour[0], null, Lines2D_1._prevA);
  14699. this.transformPointWithOriginToRef(contour[1], null, Lines2D_1._prevB);
  14700. var si_1 = 0;
  14701. for (var i = 1; i < l; i++) {
  14702. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 0], null, Lines2D_1._curA);
  14703. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 1], null, Lines2D_1._curB);
  14704. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curA);
  14705. pta_1.storeTriangle(si_1++, Lines2D_1._curA, Lines2D_1._prevB, Lines2D_1._curB);
  14706. Lines2D_1._prevA.x = Lines2D_1._curA.x;
  14707. Lines2D_1._prevA.y = Lines2D_1._curA.y;
  14708. Lines2D_1._prevB.x = Lines2D_1._curB.x;
  14709. Lines2D_1._prevB.y = Lines2D_1._curB.y;
  14710. }
  14711. var capIntersect = function (tri, points) {
  14712. var l = tri.length;
  14713. for (var i = 0; i < l; i += 3) {
  14714. Lines2D_1._curA.x = points[tri[i + 0] * 2 + 0];
  14715. Lines2D_1._curA.y = points[tri[i + 0] * 2 + 1];
  14716. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._curB);
  14717. Lines2D_1._curA.x = points[tri[i + 1] * 2 + 0];
  14718. Lines2D_1._curA.y = points[tri[i + 1] * 2 + 1];
  14719. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevA);
  14720. Lines2D_1._curA.x = points[tri[i + 2] * 2 + 0];
  14721. Lines2D_1._curA.y = points[tri[i + 2] * 2 + 1];
  14722. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevB);
  14723. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curB);
  14724. }
  14725. return false;
  14726. };
  14727. if (startCapTri) {
  14728. if (startCapTri) {
  14729. capIntersect(startCapTri, startCapContour);
  14730. }
  14731. if (endCapTri) {
  14732. capIntersect(endCapTri, endCapContour);
  14733. }
  14734. }
  14735. this._primTriArrayDirty = false;
  14736. }
  14737. var bs = this._boundingMax.subtract(this._boundingMin);
  14738. this._size.width = bs.x;
  14739. this._size.height = bs.y;
  14740. };
  14741. Object.defineProperty(Lines2D.prototype, "size", {
  14742. get: function () {
  14743. if (this._size == null) {
  14744. this._computeLines2D();
  14745. }
  14746. return this._size;
  14747. },
  14748. enumerable: true,
  14749. configurable: true
  14750. });
  14751. Lines2D.prototype.createInstanceDataParts = function () {
  14752. var res = new Array();
  14753. if (this.border) {
  14754. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  14755. }
  14756. if (this.fill) {
  14757. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  14758. }
  14759. return res;
  14760. };
  14761. Lines2D.prototype.applyActualScaleOnTransform = function () {
  14762. return true;
  14763. };
  14764. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  14765. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  14766. return false;
  14767. }
  14768. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  14769. var d = part;
  14770. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  14771. d.boundingMin = this.boundingMin;
  14772. d.boundingMax = this.boundingMax;
  14773. }
  14774. }
  14775. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  14776. var d = part;
  14777. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  14778. d.boundingMin = this.boundingMin;
  14779. d.boundingMax = this.boundingMax;
  14780. }
  14781. }
  14782. return true;
  14783. };
  14784. return Lines2D;
  14785. }(BABYLON.Shape2D));
  14786. Lines2D._prevA = BABYLON.Vector2.Zero();
  14787. Lines2D._prevB = BABYLON.Vector2.Zero();
  14788. Lines2D._curA = BABYLON.Vector2.Zero();
  14789. Lines2D._curB = BABYLON.Vector2.Zero();
  14790. Lines2D._miterTps = BABYLON.Vector2.Zero();
  14791. Lines2D._startDir = BABYLON.Vector2.Zero();
  14792. Lines2D._endDir = BABYLON.Vector2.Zero();
  14793. Lines2D._tpsV = BABYLON.Vector2.Zero();
  14794. Lines2D._noCap = 0;
  14795. Lines2D._roundCap = 1;
  14796. Lines2D._triangleCap = 2;
  14797. Lines2D._squareAnchorCap = 3;
  14798. Lines2D._roundAnchorCap = 4;
  14799. Lines2D._diamondAnchorCap = 5;
  14800. Lines2D._arrowCap = 6;
  14801. Lines2D._roundCapSubDiv = 36;
  14802. __decorate([
  14803. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D_1.pointsProperty = pi; })
  14804. ], Lines2D.prototype, "points", null);
  14805. __decorate([
  14806. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D_1.fillThicknessProperty = pi; })
  14807. ], Lines2D.prototype, "fillThickness", null);
  14808. __decorate([
  14809. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D_1.closedProperty = pi; })
  14810. ], Lines2D.prototype, "closed", null);
  14811. __decorate([
  14812. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D_1.startCapProperty = pi; })
  14813. ], Lines2D.prototype, "startCap", null);
  14814. __decorate([
  14815. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D_1.endCapProperty = pi; })
  14816. ], Lines2D.prototype, "endCap", null);
  14817. Lines2D = Lines2D_1 = __decorate([
  14818. BABYLON.className("Lines2D", "BABYLON")
  14819. ], Lines2D);
  14820. BABYLON.Lines2D = Lines2D;
  14821. var Lines2D_1;
  14822. })(BABYLON || (BABYLON = {}));
  14823. var __extends = (this && this.__extends) || function (d, b) {
  14824. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14825. function __() { this.constructor = d; }
  14826. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14827. };
  14828. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  14829. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  14830. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14831. 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;
  14832. return c > 3 && r && Object.defineProperty(target, key, r), r;
  14833. };
  14834. var BABYLON;
  14835. (function (BABYLON) {
  14836. // This class contains data that lifetime is bounding to the Babylon Engine object
  14837. var Canvas2DEngineBoundData = (function () {
  14838. function Canvas2DEngineBoundData() {
  14839. this._modelCache = new BABYLON.StringDictionary();
  14840. }
  14841. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  14842. return this._modelCache.getOrAddWithFactory(key, factory);
  14843. };
  14844. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  14845. if (!modelRenderCache.isDisposed) {
  14846. return false;
  14847. }
  14848. this._modelCache.remove(modelRenderCache.modelKey);
  14849. return true;
  14850. };
  14851. return Canvas2DEngineBoundData;
  14852. }());
  14853. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  14854. var Canvas2D = Canvas2D_1 = (function (_super) {
  14855. __extends(Canvas2D, _super);
  14856. function Canvas2D(scene, settings) {
  14857. var _this = _super.call(this, settings) || this;
  14858. /**
  14859. * 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.
  14860. * Beware that you have to take under consideration the origin and unitScaleFactor in your calculations! Good luck!
  14861. */
  14862. _this.worldSpaceToNodeLocal = function (worldPos) {
  14863. var node = _this._worldSpaceNode;
  14864. if (!node) {
  14865. return;
  14866. }
  14867. var mtx = node.getWorldMatrix().clone();
  14868. mtx.invert();
  14869. var usf = _this.unitScaleFactor;
  14870. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  14871. var res = new BABYLON.Vector2(v.x, v.y);
  14872. var size = _this.actualSize;
  14873. res.x += (size.width / usf) * 0.5; // res is centered, make it relative to bottom/left
  14874. res.y += (size.height / usf) * 0.5;
  14875. res.x *= usf; // multiply by the unitScaleFactor, which defines if the canvas is nth time bigger than the original world plane
  14876. res.y *= usf;
  14877. return res;
  14878. };
  14879. /**
  14880. * 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
  14881. */
  14882. _this.worldSpaceCacheChanged = function () {
  14883. var plane = _this.worldSpaceCanvasNode;
  14884. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  14885. vd.uvs = new Float32Array(8);
  14886. var material = plane.material;
  14887. var tex = _this._renderableData._cacheTexture;
  14888. if (material.diffuseTexture !== tex) {
  14889. material.diffuseTexture = tex;
  14890. tex.hasAlpha = true;
  14891. }
  14892. var nodeuv = _this._renderableData._cacheNodeUVs;
  14893. for (var i = 0; i < 4; i++) {
  14894. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  14895. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  14896. }
  14897. vd.applyToMesh(plane);
  14898. };
  14899. _this._notifDebugMode = false;
  14900. /**
  14901. * Instanced Array will be create if there's at least this number of parts/prim that can fit into it
  14902. */
  14903. _this.minPartCountToUseInstancedArray = 5;
  14904. _this._mapCounter = 0;
  14905. _this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  14906. _this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  14907. _this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  14908. _this._groupRenderCounter = new BABYLON.PerfCounter();
  14909. _this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  14910. _this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  14911. _this._updateCachedStateCounter = new BABYLON.PerfCounter();
  14912. _this._updateLayoutCounter = new BABYLON.PerfCounter();
  14913. _this._updatePositioningCounter = new BABYLON.PerfCounter();
  14914. _this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  14915. _this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  14916. _this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  14917. _this._cachedCanvasGroup = null;
  14918. _this._renderingGroupObserver = null;
  14919. _this._beforeRenderObserver = null;
  14920. _this._afterRenderObserver = null;
  14921. _this._profileInfoText = null;
  14922. BABYLON.Prim2DBase._isCanvasInit = false;
  14923. if (!settings) {
  14924. settings = {};
  14925. }
  14926. if (_this._cachingStrategy !== Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  14927. _this._background = new BABYLON.Rectangle2D({ parent: _this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  14928. _this._background.zOrder = 1.0;
  14929. _this._background.isPickable = false;
  14930. _this._background.origin = BABYLON.Vector2.Zero();
  14931. _this._background.levelVisible = false;
  14932. if (settings.backgroundRoundRadius != null) {
  14933. _this.backgroundRoundRadius = settings.backgroundRoundRadius;
  14934. }
  14935. if (settings.backgroundBorder != null) {
  14936. if (typeof (settings.backgroundBorder) === "string") {
  14937. _this.backgroundBorder = Canvas2D_1.GetBrushFromString(settings.backgroundBorder);
  14938. }
  14939. else {
  14940. _this.backgroundBorder = settings.backgroundBorder;
  14941. }
  14942. }
  14943. if (settings.backgroundBorderThickNess != null) {
  14944. _this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  14945. }
  14946. if (settings.backgroundFill != null) {
  14947. if (typeof (settings.backgroundFill) === "string") {
  14948. _this.backgroundFill = Canvas2D_1.GetBrushFromString(settings.backgroundFill);
  14949. }
  14950. else {
  14951. _this.backgroundFill = settings.backgroundFill;
  14952. }
  14953. }
  14954. // Put a handler to resize the background whenever the canvas is resizing
  14955. _this.propertyChanged.add(function (e, s) {
  14956. if (e.propertyName === "size") {
  14957. _this._background.size = _this.size;
  14958. }
  14959. }, BABYLON.Group2D.sizeProperty.flagId);
  14960. _this._background._patchHierarchy(_this);
  14961. }
  14962. var engine = scene.getEngine();
  14963. _this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  14964. _this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  14965. _this._capturedPointers = new BABYLON.StringDictionary();
  14966. _this._pickStartingPosition = BABYLON.Vector2.Zero();
  14967. _this._hierarchyLevelMaxSiblingCount = 50;
  14968. _this._hierarchyDepth = 0;
  14969. _this._zOrder = 0;
  14970. _this._zMax = 1;
  14971. _this._scene = scene;
  14972. _this._engine = engine;
  14973. _this._renderingSize = new BABYLON.Size(0, 0);
  14974. _this._designSize = settings.designSize || null;
  14975. _this._designUseHorizAxis = settings.designUseHorizAxis === true;
  14976. if (!_this._trackedGroups) {
  14977. _this._trackedGroups = new Array();
  14978. }
  14979. _this._maxAdaptiveWorldSpaceCanvasSize = null;
  14980. _this._groupCacheMaps = new BABYLON.StringDictionary();
  14981. _this._patchHierarchy(_this);
  14982. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  14983. _this._fitRenderingDevice = !settings.size;
  14984. if (!settings.size) {
  14985. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  14986. }
  14987. // Register scene dispose to also dispose the canvas when it'll happens
  14988. scene.onDisposeObservable.add(function (d, s) {
  14989. _this.dispose();
  14990. });
  14991. if (_this._isScreenSpace) {
  14992. if (settings.renderingPhase) {
  14993. if (!settings.renderingPhase.camera || settings.renderingPhase.renderingGroupID == null) {
  14994. throw Error("You have to specify a valid camera and renderingGroup");
  14995. }
  14996. _this._renderingGroupObserver = _this._scene.onRenderingGroupObservable.add(function (e, s) {
  14997. if ((_this._scene.activeCamera === settings.renderingPhase.camera) && (e.renderStage === BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT)) {
  14998. _this._engine.clear(null, false, true, true);
  14999. _this._render();
  15000. }
  15001. }, Math.pow(2, settings.renderingPhase.renderingGroupID));
  15002. }
  15003. else {
  15004. _this._afterRenderObserver = _this._scene.onAfterRenderObservable.add(function (d, s) {
  15005. _this._engine.clear(null, false, true, true);
  15006. _this._render();
  15007. });
  15008. }
  15009. }
  15010. else {
  15011. _this._beforeRenderObserver = _this._scene.onBeforeRenderObservable.add(function (d, s) {
  15012. _this._render();
  15013. });
  15014. }
  15015. _this._supprtInstancedArray = _this._engine.getCaps().instancedArrays !== null;
  15016. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  15017. // Setup the canvas for interaction (or not)
  15018. _this._setupInteraction(enableInteraction);
  15019. // Initialize the Primitive Collision Manager
  15020. if (settings.enableCollisionManager) {
  15021. var enableBorders = settings.collisionManagerUseBorders;
  15022. _this._primitiveCollisionManager = (settings.customCollisionManager == null) ? BABYLON.PrimitiveCollisionManagerBase.allocBasicPCM(_this, enableBorders) : settings.customCollisionManager(_this, enableBorders);
  15023. }
  15024. // Register this instance
  15025. Canvas2D_1._INSTANCES.push(_this);
  15026. return _this;
  15027. }
  15028. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  15029. get: function () {
  15030. return this._drawCallsOpaqueCounter;
  15031. },
  15032. enumerable: true,
  15033. configurable: true
  15034. });
  15035. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  15036. get: function () {
  15037. return this._drawCallsAlphaTestCounter;
  15038. },
  15039. enumerable: true,
  15040. configurable: true
  15041. });
  15042. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  15043. get: function () {
  15044. return this._drawCallsTransparentCounter;
  15045. },
  15046. enumerable: true,
  15047. configurable: true
  15048. });
  15049. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  15050. get: function () {
  15051. return this._groupRenderCounter;
  15052. },
  15053. enumerable: true,
  15054. configurable: true
  15055. });
  15056. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  15057. get: function () {
  15058. return this._updateTransparentDataCounter;
  15059. },
  15060. enumerable: true,
  15061. configurable: true
  15062. });
  15063. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  15064. get: function () {
  15065. return this._cachedGroupRenderCounter;
  15066. },
  15067. enumerable: true,
  15068. configurable: true
  15069. });
  15070. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  15071. get: function () {
  15072. return this._updateCachedStateCounter;
  15073. },
  15074. enumerable: true,
  15075. configurable: true
  15076. });
  15077. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  15078. get: function () {
  15079. return this._updateLayoutCounter;
  15080. },
  15081. enumerable: true,
  15082. configurable: true
  15083. });
  15084. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  15085. get: function () {
  15086. return this._updatePositioningCounter;
  15087. },
  15088. enumerable: true,
  15089. configurable: true
  15090. });
  15091. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  15092. get: function () {
  15093. return this._updateLocalTransformCounter;
  15094. },
  15095. enumerable: true,
  15096. configurable: true
  15097. });
  15098. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  15099. get: function () {
  15100. return this._updateGlobalTransformCounter;
  15101. },
  15102. enumerable: true,
  15103. configurable: true
  15104. });
  15105. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  15106. get: function () {
  15107. return this._boundingInfoRecomputeCounter;
  15108. },
  15109. enumerable: true,
  15110. configurable: true
  15111. });
  15112. Object.defineProperty(Canvas2D, "instances", {
  15113. get: function () {
  15114. return Canvas2D_1._INSTANCES;
  15115. },
  15116. enumerable: true,
  15117. configurable: true
  15118. });
  15119. Object.defineProperty(Canvas2D.prototype, "primitiveCollisionManager", {
  15120. get: function () {
  15121. return this._primitiveCollisionManager;
  15122. },
  15123. enumerable: true,
  15124. configurable: true
  15125. });
  15126. Canvas2D.prototype._canvasPreInit = function (settings) {
  15127. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D_1.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  15128. this._cachingStrategy = cachingStrategy;
  15129. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  15130. };
  15131. Canvas2D.prototype._setupInteraction = function (enable) {
  15132. var _this = this;
  15133. // No change detection
  15134. if (enable === this._interactionEnabled) {
  15135. return;
  15136. }
  15137. // Set the new state
  15138. this._interactionEnabled = enable;
  15139. // ScreenSpace mode
  15140. if (this._isScreenSpace) {
  15141. // Disable interaction
  15142. if (!enable) {
  15143. if (this._scenePrePointerObserver) {
  15144. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  15145. this._scenePrePointerObserver = null;
  15146. }
  15147. return;
  15148. }
  15149. // Enable Interaction
  15150. // Register the observable
  15151. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  15152. if (_this.isVisible === false) {
  15153. return;
  15154. }
  15155. var hs = 1 / _this.engine.getHardwareScalingLevel();
  15156. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  15157. _this._handlePointerEventForInteraction(e, localPos, s);
  15158. });
  15159. }
  15160. else {
  15161. var scene = this.scene;
  15162. if (enable) {
  15163. scene.constantlyUpdateMeshUnderPointer = true;
  15164. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  15165. if (_this.isVisible === false) {
  15166. return;
  15167. }
  15168. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  15169. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  15170. _this._handlePointerEventForInteraction(e, localPos, s);
  15171. }
  15172. else if (_this._actualIntersectionList && _this._actualIntersectionList.length > 0) {
  15173. _this._handlePointerEventForInteraction(e, null, s);
  15174. }
  15175. });
  15176. }
  15177. else {
  15178. if (this._scenePointerObserver) {
  15179. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  15180. this._scenePointerObserver = null;
  15181. }
  15182. }
  15183. }
  15184. };
  15185. /**
  15186. * Internal method, you should use the Prim2DBase version instead
  15187. */
  15188. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  15189. if (this.isPointerCaptured(pointerId)) {
  15190. return false;
  15191. }
  15192. // Try to capture the pointer on the HTML side
  15193. try {
  15194. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  15195. }
  15196. catch (e) {
  15197. }
  15198. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  15199. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  15200. this._capturedPointers.add(pointerId.toString(), primitive);
  15201. return true;
  15202. };
  15203. /**
  15204. * Internal method, you should use the Prim2DBase version instead
  15205. */
  15206. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  15207. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  15208. return false;
  15209. }
  15210. // Try to release the pointer on the HTML side
  15211. try {
  15212. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  15213. }
  15214. catch (e) {
  15215. }
  15216. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  15217. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  15218. this._capturedPointers.remove(pointerId.toString());
  15219. return true;
  15220. };
  15221. /**
  15222. * Determine if the given pointer is captured or not
  15223. * @param pointerId the Id of the pointer
  15224. * @return true if it's captured, false otherwise
  15225. */
  15226. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  15227. return this._capturedPointers.contains(pointerId.toString());
  15228. };
  15229. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  15230. // Avoid unnecessary lookup
  15231. if (this._capturedPointers.count === 0) {
  15232. return null;
  15233. }
  15234. return this._capturedPointers.get(pointerId.toString());
  15235. };
  15236. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  15237. // Dispose check
  15238. if (this.isDisposed) {
  15239. return;
  15240. }
  15241. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  15242. if (localPosition) {
  15243. if (!this._updatePointerInfo(eventData, localPosition)) {
  15244. return;
  15245. }
  15246. }
  15247. else {
  15248. this._primPointerInfo.canvasPointerPos = null;
  15249. }
  15250. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  15251. // 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.
  15252. // 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.
  15253. this._updateIntersectionList(localPosition ? this._primPointerInfo.canvasPointerPos : null, capturedPrim !== null, true);
  15254. // 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
  15255. this._updateOverStatus(true);
  15256. // Check if we have nothing to raise
  15257. if (!this._actualOverPrimitive && !capturedPrim) {
  15258. return;
  15259. }
  15260. // Update the relatedTarget info with the over primitive or the captured one (if any)
  15261. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  15262. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  15263. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  15264. // Analyze the pointer event type and fire proper events on the primitive
  15265. var skip = false;
  15266. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  15267. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  15268. }
  15269. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  15270. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  15271. }
  15272. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  15273. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  15274. }
  15275. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  15276. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  15277. }
  15278. eventState.skipNextObservers = skip;
  15279. };
  15280. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  15281. var s = this.scale;
  15282. var pii = this._primPointerInfo;
  15283. pii.cancelBubble = false;
  15284. if (!pii.canvasPointerPos) {
  15285. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  15286. }
  15287. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  15288. if (!camera || !camera.viewport) {
  15289. return false;
  15290. }
  15291. var engine = this._scene.getEngine();
  15292. if (this._isScreenSpace) {
  15293. var cameraViewport = camera.viewport;
  15294. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15295. // Moving coordinates to local viewport world
  15296. var x = localPosition.x - viewport.x;
  15297. var y = localPosition.y - viewport.y;
  15298. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  15299. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  15300. }
  15301. else {
  15302. pii.canvasPointerPos.x = localPosition.x / s;
  15303. pii.canvasPointerPos.y = localPosition.y / s;
  15304. }
  15305. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  15306. pii.mouseWheelDelta = 0;
  15307. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  15308. var event = eventData.event;
  15309. if (event.wheelDelta) {
  15310. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  15311. }
  15312. else if (event.detail) {
  15313. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  15314. }
  15315. }
  15316. else {
  15317. var pe = eventData.event;
  15318. pii.ctrlKey = pe.ctrlKey;
  15319. pii.altKey = pe.altKey;
  15320. pii.shiftKey = pe.shiftKey;
  15321. pii.metaKey = pe.metaKey;
  15322. pii.button = pe.button;
  15323. pii.buttons = pe.buttons;
  15324. pii.pointerId = pe.pointerId;
  15325. pii.width = pe.width;
  15326. pii.height = pe.height;
  15327. pii.presssure = pe.pressure;
  15328. pii.tilt.x = pe.tiltX;
  15329. pii.tilt.y = pe.tiltY;
  15330. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  15331. }
  15332. return true;
  15333. };
  15334. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
  15335. if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
  15336. return;
  15337. }
  15338. var ii = Canvas2D_1._interInfo;
  15339. var outCase = mouseLocalPos == null;
  15340. if (!outCase) {
  15341. // 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
  15342. if (!this._globalTransform) {
  15343. this.updateCachedStates(true);
  15344. }
  15345. ii.pickPosition.x = mouseLocalPos.x;
  15346. ii.pickPosition.y = mouseLocalPos.y;
  15347. ii.findFirstOnly = false;
  15348. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  15349. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  15350. // Reset intersection info as we don't hit anything
  15351. ii.intersectedPrimitives = new Array();
  15352. ii.topMostIntersectedPrimitive = null;
  15353. }
  15354. else {
  15355. // The pointer is inside the Canvas, do an intersection test
  15356. this.intersect(ii);
  15357. // Sort primitives to get them from top to bottom
  15358. ii.intersectedPrimitives = ii.intersectedPrimitives.sort(function (a, b) { return a.prim.actualZOffset - b.prim.actualZOffset; });
  15359. }
  15360. }
  15361. {
  15362. // Update prev/actual intersection info, fire "overPrim" property change if needed
  15363. this._previousIntersectionList = this._actualIntersectionList;
  15364. this._actualIntersectionList = outCase ? new Array() : ii.intersectedPrimitives;
  15365. this._previousOverPrimitive = this._actualOverPrimitive;
  15366. this._actualOverPrimitive = outCase ? null : ii.topMostIntersectedPrimitive;
  15367. var prev = (this._previousOverPrimitive != null) ? this._previousOverPrimitive.prim : null;
  15368. var actual = (this._actualOverPrimitive != null) ? this._actualOverPrimitive.prim : null;
  15369. if (prev !== actual) {
  15370. this.onPropertyChanged("overPrim", this._previousOverPrimitive ? this._previousOverPrimitive.prim : null, this._actualOverPrimitive ? this._actualOverPrimitive.prim : null);
  15371. }
  15372. }
  15373. this._intersectionRenderId = this.scene.getRenderId();
  15374. };
  15375. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  15376. Canvas2D.prototype._updateOverStatus = function (force) {
  15377. if ((!force && (this.scene.getRenderId() === this._hoverStatusRenderId)) || !this._actualIntersectionList) {
  15378. return;
  15379. }
  15380. if (this._previousIntersectionList == null) {
  15381. this._previousIntersectionList = [];
  15382. }
  15383. // Detect a change of over
  15384. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  15385. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  15386. if (prevPrim !== actualPrim) {
  15387. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  15388. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  15389. // See the NOTE section of: https://www.w3.org/TR/pointerevents/#setting-pointer-capture
  15390. if (capturedPrim) {
  15391. if (capturedPrim === prevPrim) {
  15392. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  15393. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  15394. }
  15395. else if (capturedPrim === actualPrim) {
  15396. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  15397. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  15398. }
  15399. }
  15400. else {
  15401. var _loop_1 = function (prev) {
  15402. if (!BABYLON.Tools.first(this_1._actualIntersectionList, function (pii) { return pii.prim === prev.prim; })) {
  15403. this_1._primPointerInfo.updateRelatedTarget(prev.prim, prev.intersectionLocation);
  15404. this_1._bubbleNotifyPrimPointerObserver(prev.prim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  15405. }
  15406. };
  15407. var this_1 = this;
  15408. // Check for Out & Leave
  15409. for (var _i = 0, _a = this._previousIntersectionList; _i < _a.length; _i++) {
  15410. var prev = _a[_i];
  15411. _loop_1(prev);
  15412. }
  15413. var _loop_2 = function (actual) {
  15414. if (!BABYLON.Tools.first(this_2._previousIntersectionList, function (pii) { return pii.prim === actual.prim; })) {
  15415. this_2._primPointerInfo.updateRelatedTarget(actual.prim, actual.intersectionLocation);
  15416. this_2._bubbleNotifyPrimPointerObserver(actual.prim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  15417. }
  15418. };
  15419. var this_2 = this;
  15420. // Check for Over & Enter
  15421. for (var _b = 0, _c = this._actualIntersectionList; _b < _c.length; _b++) {
  15422. var actual = _c[_b];
  15423. _loop_2(actual);
  15424. }
  15425. }
  15426. }
  15427. this._hoverStatusRenderId = this.scene.getRenderId();
  15428. };
  15429. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  15430. if (this._primPointerInfo.isCaptured) {
  15431. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  15432. }
  15433. else {
  15434. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  15435. var pii = _a[_i];
  15436. if (pii.prim === prim) {
  15437. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  15438. return;
  15439. }
  15440. }
  15441. }
  15442. };
  15443. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  15444. if (!this._notifDebugMode) {
  15445. return;
  15446. }
  15447. var debug = "";
  15448. for (var i = 0; i < prim.hierarchyDepth; i++) {
  15449. debug += " ";
  15450. }
  15451. var pii = this._primPointerInfo;
  15452. 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;
  15453. console.log(debug);
  15454. };
  15455. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  15456. var ppi = this._primPointerInfo;
  15457. var event = eventData ? eventData.event : null;
  15458. var cur = prim;
  15459. while (cur && !cur.isDisposed) {
  15460. this._updatePrimPointerPos(cur);
  15461. // For the first level we have to fire Enter or Leave for corresponding Over or Out
  15462. if (cur === prim) {
  15463. // Fire the proper notification
  15464. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  15465. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerEnter);
  15466. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  15467. }
  15468. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  15469. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerLeave);
  15470. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  15471. }
  15472. }
  15473. // Exec the observers
  15474. this._debugExecObserver(cur, mask);
  15475. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  15476. eventData.skipOnPointerObservable = true;
  15477. return false;
  15478. }
  15479. this._triggerActionManager(cur, ppi, mask, event);
  15480. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  15481. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  15482. if (ppi.cancelBubble) {
  15483. return false;
  15484. }
  15485. // Loop to the parent
  15486. cur = cur.parent;
  15487. }
  15488. return true;
  15489. };
  15490. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  15491. var _this = this;
  15492. // 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
  15493. if (!this._globalTransform) {
  15494. this.updateCachedStates(true);
  15495. }
  15496. // Process Trigger related to PointerDown
  15497. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  15498. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  15499. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  15500. this._pickStartingTime = new Date().getTime();
  15501. this._pickedDownPrim = null;
  15502. if (prim.actionManager) {
  15503. this._pickedDownPrim = prim;
  15504. if (prim.actionManager.hasPickTriggers) {
  15505. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15506. switch (eventData.button) {
  15507. case 0:
  15508. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  15509. break;
  15510. case 1:
  15511. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  15512. break;
  15513. case 2:
  15514. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  15515. break;
  15516. }
  15517. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  15518. }
  15519. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15520. window.setTimeout(function () {
  15521. var ppi = _this._primPointerInfo;
  15522. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  15523. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
  15524. _this._updateOverStatus(false);
  15525. var ii = new BABYLON.IntersectInfo2D();
  15526. ii.pickPosition = ppi.canvasPointerPos.clone();
  15527. ii.findFirstOnly = false;
  15528. _this.intersect(ii);
  15529. if (ii.isPrimIntersected(prim) !== null) {
  15530. if (prim.actionManager) {
  15531. 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)) {
  15532. _this._pickStartingTime = 0;
  15533. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  15534. }
  15535. }
  15536. }
  15537. }, BABYLON.ActionManager.LongPressDelay);
  15538. }
  15539. }
  15540. }
  15541. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  15542. this._pickStartingTime = 0;
  15543. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15544. if (prim.actionManager) {
  15545. // OnPickUpTrigger
  15546. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  15547. // OnPickTrigger
  15548. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  15549. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  15550. }
  15551. }
  15552. // OnPickOutTrigger
  15553. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  15554. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  15555. }
  15556. }
  15557. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  15558. if (prim.actionManager) {
  15559. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15560. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  15561. }
  15562. }
  15563. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  15564. if (prim.actionManager) {
  15565. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15566. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  15567. }
  15568. }
  15569. };
  15570. /**
  15571. * Don't forget to call the dispose method when you're done with the Canvas instance.
  15572. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  15573. */
  15574. Canvas2D.prototype.dispose = function () {
  15575. if (!_super.prototype.dispose.call(this)) {
  15576. return false;
  15577. }
  15578. if (this._profilingCanvas) {
  15579. this._profilingCanvas.dispose();
  15580. this._profilingCanvas = null;
  15581. }
  15582. if (this.interactionEnabled) {
  15583. this._setupInteraction(false);
  15584. }
  15585. if (this._renderingGroupObserver) {
  15586. this._scene.onRenderingGroupObservable.remove(this._renderingGroupObserver);
  15587. this._renderingGroupObserver = null;
  15588. }
  15589. if (this._beforeRenderObserver) {
  15590. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  15591. this._beforeRenderObserver = null;
  15592. }
  15593. if (this._afterRenderObserver) {
  15594. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  15595. this._afterRenderObserver = null;
  15596. }
  15597. if (this._groupCacheMaps) {
  15598. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  15599. this._groupCacheMaps = null;
  15600. }
  15601. // Unregister this instance
  15602. var index = Canvas2D_1._INSTANCES.indexOf(this);
  15603. if (index > -1) {
  15604. Canvas2D_1._INSTANCES.splice(index, 1);
  15605. }
  15606. return true;
  15607. };
  15608. Object.defineProperty(Canvas2D.prototype, "scene", {
  15609. /**
  15610. * Accessor to the Scene that owns the Canvas
  15611. * @returns The instance of the Scene object
  15612. */
  15613. get: function () {
  15614. return this._scene;
  15615. },
  15616. enumerable: true,
  15617. configurable: true
  15618. });
  15619. Object.defineProperty(Canvas2D.prototype, "engine", {
  15620. /**
  15621. * Accessor to the Engine that drives the Scene used by this Canvas
  15622. * @returns The instance of the Engine object
  15623. */
  15624. get: function () {
  15625. return this._engine;
  15626. },
  15627. enumerable: true,
  15628. configurable: true
  15629. });
  15630. Object.defineProperty(Canvas2D.prototype, "renderObservable", {
  15631. /**
  15632. * And observable called during the Canvas rendering process.
  15633. * This observable is called twice per render, each time with a different mask:
  15634. * - 1: before render is executed
  15635. * - 2: after render is executed
  15636. */
  15637. get: function () {
  15638. if (!this._renderObservable) {
  15639. this._renderObservable = new BABYLON.Observable();
  15640. }
  15641. return this._renderObservable;
  15642. },
  15643. enumerable: true,
  15644. configurable: true
  15645. });
  15646. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  15647. /**
  15648. * Accessor of the Caching Strategy used by this Canvas.
  15649. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  15650. * @returns the value corresponding to the used strategy.
  15651. */
  15652. get: function () {
  15653. return this._cachingStrategy;
  15654. },
  15655. enumerable: true,
  15656. configurable: true
  15657. });
  15658. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  15659. /**
  15660. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  15661. * @returns {}
  15662. */
  15663. get: function () {
  15664. return this._isScreenSpace;
  15665. },
  15666. enumerable: true,
  15667. configurable: true
  15668. });
  15669. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  15670. /**
  15671. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  15672. */
  15673. get: function () {
  15674. return this._worldSpaceNode;
  15675. },
  15676. set: function (val) {
  15677. this._worldSpaceNode = val;
  15678. },
  15679. enumerable: true,
  15680. configurable: true
  15681. });
  15682. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  15683. /**
  15684. * Check if the WebGL Instanced Array extension is supported or not
  15685. */
  15686. get: function () {
  15687. return this._supprtInstancedArray;
  15688. },
  15689. enumerable: true,
  15690. configurable: true
  15691. });
  15692. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  15693. /**
  15694. * Property that defines the fill object used to draw the background of the Canvas.
  15695. * Note that Canvas with a Caching Strategy of
  15696. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  15697. */
  15698. get: function () {
  15699. if (!this._background || !this._background.isVisible) {
  15700. return null;
  15701. }
  15702. return this._background.fill;
  15703. },
  15704. set: function (value) {
  15705. this.checkBackgroundAvailability();
  15706. if (value === this._background.fill) {
  15707. return;
  15708. }
  15709. this._background.fill = value;
  15710. this._background.levelVisible = true;
  15711. },
  15712. enumerable: true,
  15713. configurable: true
  15714. });
  15715. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  15716. /**
  15717. * Property that defines the border object used to draw the background of the Canvas.
  15718. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  15719. */
  15720. get: function () {
  15721. if (!this._background || !this._background.isVisible) {
  15722. return null;
  15723. }
  15724. return this._background.border;
  15725. },
  15726. set: function (value) {
  15727. this.checkBackgroundAvailability();
  15728. if (value === this._background.border) {
  15729. return;
  15730. }
  15731. this._background.border = value;
  15732. this._background.levelVisible = true;
  15733. },
  15734. enumerable: true,
  15735. configurable: true
  15736. });
  15737. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  15738. /**
  15739. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  15740. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  15741. */
  15742. get: function () {
  15743. if (!this._background || !this._background.isVisible) {
  15744. return null;
  15745. }
  15746. return this._background.borderThickness;
  15747. },
  15748. set: function (value) {
  15749. this.checkBackgroundAvailability();
  15750. if (value === this._background.borderThickness) {
  15751. return;
  15752. }
  15753. this._background.borderThickness = value;
  15754. },
  15755. enumerable: true,
  15756. configurable: true
  15757. });
  15758. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  15759. /**
  15760. * You can set the roundRadius of the background
  15761. * @returns The current roundRadius
  15762. */
  15763. get: function () {
  15764. if (!this._background || !this._background.isVisible) {
  15765. return null;
  15766. }
  15767. return this._background.roundRadius;
  15768. },
  15769. set: function (value) {
  15770. this.checkBackgroundAvailability();
  15771. if (value === this._background.roundRadius) {
  15772. return;
  15773. }
  15774. this._background.roundRadius = value;
  15775. this._background.levelVisible = true;
  15776. },
  15777. enumerable: true,
  15778. configurable: true
  15779. });
  15780. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  15781. /**
  15782. * Enable/Disable interaction for this Canvas
  15783. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  15784. */
  15785. get: function () {
  15786. return this._interactionEnabled;
  15787. },
  15788. set: function (enable) {
  15789. this._setupInteraction(enable);
  15790. },
  15791. enumerable: true,
  15792. configurable: true
  15793. });
  15794. Object.defineProperty(Canvas2D.prototype, "fitRenderingDevice", {
  15795. get: function () {
  15796. return this._fitRenderingDevice;
  15797. },
  15798. enumerable: true,
  15799. configurable: true
  15800. });
  15801. Object.defineProperty(Canvas2D.prototype, "designSize", {
  15802. get: function () {
  15803. return this._designSize;
  15804. },
  15805. enumerable: true,
  15806. configurable: true
  15807. });
  15808. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  15809. get: function () {
  15810. return this._designUseHorizAxis;
  15811. },
  15812. enumerable: true,
  15813. configurable: true
  15814. });
  15815. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizeAxis", {
  15816. set: function (value) {
  15817. this._designUseHorizAxis = value;
  15818. },
  15819. enumerable: true,
  15820. configurable: true
  15821. });
  15822. Object.defineProperty(Canvas2D.prototype, "overPrim", {
  15823. /**
  15824. * Return
  15825. */
  15826. get: function () {
  15827. if (this._actualIntersectionList && this._actualIntersectionList.length > 0) {
  15828. return this._actualIntersectionList[0].prim;
  15829. }
  15830. return null;
  15831. },
  15832. enumerable: true,
  15833. configurable: true
  15834. });
  15835. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  15836. /**
  15837. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  15838. * @returns {}
  15839. */
  15840. get: function () {
  15841. return this.__engineData;
  15842. },
  15843. enumerable: true,
  15844. configurable: true
  15845. });
  15846. Object.defineProperty(Canvas2D.prototype, "unitScaleFactor", {
  15847. get: function () {
  15848. return this._unitScaleFactor;
  15849. },
  15850. enumerable: true,
  15851. configurable: true
  15852. });
  15853. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  15854. if (this._profilingCanvas) {
  15855. return this._profilingCanvas;
  15856. }
  15857. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  15858. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D_1.CACHESTRATEGY_DONTCACHE, children: [
  15859. new BABYLON.Rectangle2D({
  15860. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  15861. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "12pt Lucida Console", fontSignedDistanceField: true })
  15862. ]
  15863. })
  15864. ]
  15865. });
  15866. this._profileInfoText = canvas.findById("ProfileInfoText");
  15867. this._profilingCanvas = canvas;
  15868. return canvas;
  15869. };
  15870. Canvas2D.prototype.checkBackgroundAvailability = function () {
  15871. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  15872. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  15873. }
  15874. };
  15875. Canvas2D.prototype._initPerfMetrics = function () {
  15876. this._drawCallsOpaqueCounter.fetchNewFrame();
  15877. this._drawCallsAlphaTestCounter.fetchNewFrame();
  15878. this._drawCallsTransparentCounter.fetchNewFrame();
  15879. this._groupRenderCounter.fetchNewFrame();
  15880. this._updateTransparentDataCounter.fetchNewFrame();
  15881. this._cachedGroupRenderCounter.fetchNewFrame();
  15882. this._updateCachedStateCounter.fetchNewFrame();
  15883. this._updateLayoutCounter.fetchNewFrame();
  15884. this._updatePositioningCounter.fetchNewFrame();
  15885. this._updateLocalTransformCounter.fetchNewFrame();
  15886. this._updateGlobalTransformCounter.fetchNewFrame();
  15887. this._boundingInfoRecomputeCounter.fetchNewFrame();
  15888. };
  15889. Canvas2D.prototype._fetchPerfMetrics = function () {
  15890. this._drawCallsOpaqueCounter.addCount(0, true);
  15891. this._drawCallsAlphaTestCounter.addCount(0, true);
  15892. this._drawCallsTransparentCounter.addCount(0, true);
  15893. this._groupRenderCounter.addCount(0, true);
  15894. this._updateTransparentDataCounter.addCount(0, true);
  15895. this._cachedGroupRenderCounter.addCount(0, true);
  15896. this._updateCachedStateCounter.addCount(0, true);
  15897. this._updateLayoutCounter.addCount(0, true);
  15898. this._updatePositioningCounter.addCount(0, true);
  15899. this._updateLocalTransformCounter.addCount(0, true);
  15900. this._updateGlobalTransformCounter.addCount(0, true);
  15901. this._boundingInfoRecomputeCounter.addCount(0, true);
  15902. };
  15903. Canvas2D.prototype._updateProfileCanvas = function () {
  15904. if (this._profileInfoText == null) {
  15905. return;
  15906. }
  15907. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  15908. var p = "Draw Calls:\n" +
  15909. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  15910. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  15911. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  15912. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  15913. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  15914. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  15915. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  15916. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  15917. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  15918. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  15919. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  15920. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")");
  15921. this._profileInfoText.text = p;
  15922. };
  15923. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  15924. switch (renderMode) {
  15925. case BABYLON.Render2DContext.RenderModeOpaque:
  15926. this._drawCallsOpaqueCounter.addCount(count, false);
  15927. return;
  15928. case BABYLON.Render2DContext.RenderModeAlphaTest:
  15929. this._drawCallsAlphaTestCounter.addCount(count, false);
  15930. return;
  15931. case BABYLON.Render2DContext.RenderModeTransparent:
  15932. this._drawCallsTransparentCounter.addCount(count, false);
  15933. return;
  15934. }
  15935. };
  15936. Canvas2D.prototype._addGroupRenderCount = function (count) {
  15937. this._groupRenderCounter.addCount(count, false);
  15938. };
  15939. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  15940. this._updateTransparentDataCounter.addCount(count, false);
  15941. };
  15942. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  15943. this._cachedGroupRenderCounter.addCount(count, false);
  15944. };
  15945. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  15946. this._updateCachedStateCounter.addCount(count, false);
  15947. };
  15948. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  15949. this._updateLayoutCounter.addCount(count, false);
  15950. };
  15951. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  15952. this._updatePositioningCounter.addCount(count, false);
  15953. };
  15954. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  15955. this._updateLocalTransformCounter.addCount(count, false);
  15956. };
  15957. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  15958. this._updateGlobalTransformCounter.addCount(count, false);
  15959. };
  15960. Canvas2D.prototype._updateTrackedNodes = function () {
  15961. // Get the used camera
  15962. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  15963. // Compute some matrix stuff
  15964. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  15965. var rh = this.engine.getRenderHeight();
  15966. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  15967. // Compute the screen position of each group that track a given scene node
  15968. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  15969. var group = _a[_i];
  15970. if (group.isDisposed) {
  15971. continue;
  15972. }
  15973. var node = group.trackedNode;
  15974. var worldMtx = node.getWorldMatrix();
  15975. var proj = BABYLON.Vector3.Project(Canvas2D_1._v, worldMtx, Canvas2D_1._m, v);
  15976. // Set the visibility state accordingly, if the position is outside the frustum (well on the Z planes only...) set the group to hidden
  15977. group.levelVisible = proj.z >= 0 && proj.z < 1.0;
  15978. var s = this.scale;
  15979. group.x = Math.round(proj.x / s);
  15980. group.y = Math.round((rh - proj.y) / s);
  15981. }
  15982. // If it's a WorldSpaceCanvas and it's tracking a node, let's update the WSC transformation data
  15983. if (this._trackNode) {
  15984. var rot = null;
  15985. var scale = null;
  15986. var worldmtx = this._trackNode.getWorldMatrix();
  15987. var pos = worldmtx.getTranslation().add(this._trackNodeOffset);
  15988. var wsc = this;
  15989. var wsn = wsc.worldSpaceCanvasNode;
  15990. if (this._trackNodeBillboard) {
  15991. var viewMtx = cam.getViewMatrix().clone().invert();
  15992. viewMtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  15993. rot = Canvas2D_1.tR.clone();
  15994. }
  15995. worldmtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  15996. var mtx = BABYLON.Matrix.Compose(Canvas2D_1.tS, Canvas2D_1.tR, BABYLON.Vector3.Zero());
  15997. pos = worldmtx.getTranslation().add(BABYLON.Vector3.TransformCoordinates(this._trackNodeOffset, mtx));
  15998. if (Canvas2D_1.tS.lengthSquared() !== 1) {
  15999. scale = Canvas2D_1.tS.clone();
  16000. }
  16001. if (!this._trackNodeBillboard) {
  16002. rot = Canvas2D_1.tR.clone();
  16003. }
  16004. if (wsn instanceof BABYLON.AbstractMesh) {
  16005. wsn.position = pos;
  16006. wsn.rotationQuaternion = rot;
  16007. if (scale) {
  16008. wsn.scaling = scale;
  16009. }
  16010. }
  16011. else {
  16012. throw new Error("Can't Track another Scene Node Type than AbstractMesh right now, call me lazy!");
  16013. }
  16014. }
  16015. };
  16016. /**
  16017. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  16018. */
  16019. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  16020. this._updateCanvasState(forceRecompute);
  16021. };
  16022. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  16023. if (this._globalTransformStep < 2) {
  16024. return;
  16025. }
  16026. var n = this.worldSpaceCanvasNode;
  16027. var bi = n.getBoundingInfo().boundingBox;
  16028. var v = bi.vectorsWorld;
  16029. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  16030. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  16031. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  16032. var projPoints = new Array(4);
  16033. for (var i = 0; i < 4; i++) {
  16034. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D_1._mI, Canvas2D_1._m, vp);
  16035. }
  16036. var left = projPoints[3].subtract(projPoints[0]).length();
  16037. var top = projPoints[3].subtract(projPoints[1]).length();
  16038. var right = projPoints[1].subtract(projPoints[2]).length();
  16039. var bottom = projPoints[2].subtract(projPoints[0]).length();
  16040. var w = Math.round(Math.max(top, bottom));
  16041. var h = Math.round(Math.max(right, left));
  16042. var isW = w > h;
  16043. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  16044. var edge = Math.max(w, h);
  16045. if (edge < 256) {
  16046. edge = 256;
  16047. }
  16048. else {
  16049. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  16050. }
  16051. // Clip values if needed
  16052. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  16053. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  16054. if (newScale !== this.scale) {
  16055. var scale = newScale;
  16056. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  16057. this._setRenderingScale(scale);
  16058. }
  16059. };
  16060. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  16061. // Check if the update has already been made for this render Frame
  16062. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  16063. return;
  16064. }
  16065. // Detect a change of rendering size
  16066. var renderingSizeChanged = false;
  16067. var newWidth = this.engine.getRenderWidth();
  16068. if (newWidth !== this._renderingSize.width) {
  16069. renderingSizeChanged = true;
  16070. }
  16071. this._renderingSize.width = newWidth;
  16072. var newHeight = this.engine.getRenderHeight();
  16073. if (newHeight !== this._renderingSize.height) {
  16074. renderingSizeChanged = true;
  16075. }
  16076. this._renderingSize.height = newHeight;
  16077. // If the canvas fit the rendering size and it changed, update
  16078. if (renderingSizeChanged && this._fitRenderingDevice) {
  16079. this.actualSize = this._renderingSize.clone();
  16080. this.size = this._renderingSize.clone();
  16081. if (this._background) {
  16082. this._background.size = this.size;
  16083. }
  16084. // Dirty the Layout at the Canvas level to recompute as the size changed
  16085. this._setLayoutDirty();
  16086. }
  16087. // If there's a design size, update the scale according to the renderingSize
  16088. if (this._designSize) {
  16089. var scale = void 0;
  16090. if (this._designUseHorizAxis) {
  16091. scale = this._renderingSize.width / this._designSize.width;
  16092. }
  16093. else {
  16094. scale = this._renderingSize.height / this._designSize.height;
  16095. }
  16096. this.size = this._designSize.clone();
  16097. this.actualSize = this._designSize.clone();
  16098. this.scale = scale;
  16099. }
  16100. var context = new BABYLON.PrepareRender2DContext();
  16101. ++this._globalTransformProcessStep;
  16102. this.updateCachedStates(false);
  16103. this._prepareGroupRender(context);
  16104. this._updateRenderId = this.scene.getRenderId();
  16105. };
  16106. /**
  16107. * Method that renders the Canvas, you should not invoke
  16108. */
  16109. Canvas2D.prototype._render = function () {
  16110. this._initPerfMetrics();
  16111. if (this._renderObservable && this._renderObservable.hasObservers()) {
  16112. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_PRE);
  16113. }
  16114. this._updateCanvasState(false);
  16115. this._updateTrackedNodes();
  16116. // Nothing to do is the Canvas is not visible
  16117. if (this.isVisible === false) {
  16118. return;
  16119. }
  16120. if (!this._isScreenSpace) {
  16121. this._updateAdaptiveSizeWorldCanvas();
  16122. }
  16123. this._updateCanvasState(false);
  16124. if (this._primitiveCollisionManager) {
  16125. this._primitiveCollisionManager._update();
  16126. }
  16127. if (this._primPointerInfo.canvasPointerPos) {
  16128. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
  16129. this._updateOverStatus(false);
  16130. }
  16131. this.engine.setState(false, undefined, true);
  16132. this._groupRender();
  16133. if (!this._isScreenSpace) {
  16134. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  16135. this.worldSpaceCacheChanged();
  16136. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  16137. }
  16138. }
  16139. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  16140. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  16141. this._cachedCanvasGroup._renderCachedCanvas();
  16142. }
  16143. this._fetchPerfMetrics();
  16144. this._updateProfileCanvas();
  16145. if (this._renderObservable && this._renderObservable.hasObservers()) {
  16146. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_POST);
  16147. }
  16148. };
  16149. /**
  16150. * Internal method that allocate a cache for the given group.
  16151. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  16152. * @param group The group to allocate the cache of.
  16153. * @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.
  16154. */
  16155. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  16156. if (useMipMap === void 0) { useMipMap = false; }
  16157. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  16158. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  16159. var rd = group._renderableData;
  16160. var noResizeScale = rd._noResizeOnScale;
  16161. var isCanvas = parent == null;
  16162. var scale;
  16163. if (noResizeScale) {
  16164. scale = isCanvas ? Canvas2D_1._unS : group.parent.actualScale;
  16165. }
  16166. else {
  16167. scale = group.actualScale;
  16168. }
  16169. // Determine size
  16170. var size = group.actualSize;
  16171. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  16172. var originalSize = size.clone();
  16173. if (minSize) {
  16174. size.width = Math.max(minSize.width, size.width);
  16175. size.height = Math.max(minSize.height, size.height);
  16176. }
  16177. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  16178. // Try to find a spot in one of the cached texture
  16179. var res = null;
  16180. var map;
  16181. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  16182. var _map = mapArray_1[_i];
  16183. map = _map;
  16184. var node = map.allocateRect(size);
  16185. if (node) {
  16186. res = { node: node, texture: map };
  16187. break;
  16188. }
  16189. }
  16190. // Couldn't find a map that could fit the rect, create a new map for it
  16191. if (!res) {
  16192. var mapSize = new BABYLON.Size(Canvas2D_1._groupTextureCacheSize, Canvas2D_1._groupTextureCacheSize);
  16193. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  16194. if (size.width > mapSize.width || size.height > mapSize.height) {
  16195. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  16196. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  16197. }
  16198. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  16199. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  16200. map.hasAlpha = true;
  16201. map.anisotropicFilteringLevel = 4;
  16202. mapArray.splice(0, 0, map);
  16203. var node = map.allocateRect(size);
  16204. res = { node: node, texture: map };
  16205. }
  16206. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  16207. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  16208. if (group !== this || this._isScreenSpace) {
  16209. var node = res.node;
  16210. // 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
  16211. var sprite = void 0;
  16212. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS) {
  16213. if (this._cachedCanvasGroup) {
  16214. this._cachedCanvasGroup.dispose();
  16215. }
  16216. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  16217. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: originalSize, spriteLocation: node.pos });
  16218. sprite.zOrder = 1;
  16219. sprite.origin = BABYLON.Vector2.Zero();
  16220. }
  16221. else {
  16222. 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 });
  16223. sprite.origin = group.origin.clone();
  16224. sprite.addExternalData("__cachedGroup__", group);
  16225. sprite.pointerEventObservable.add(function (e, s) {
  16226. if (group.pointerEventObservable !== null) {
  16227. group.pointerEventObservable.notifyObservers(e, s.mask);
  16228. }
  16229. });
  16230. res.sprite = sprite;
  16231. }
  16232. if (sprite && noResizeScale) {
  16233. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  16234. sprite.scaleX = relScale.x;
  16235. sprite.scaleY = relScale.y;
  16236. }
  16237. }
  16238. return res;
  16239. };
  16240. /**
  16241. * Internal method used to register a Scene Node to track position for the given group
  16242. * Do not invoke this method, for internal purpose only.
  16243. * @param group the group to track its associated Scene Node
  16244. */
  16245. Canvas2D.prototype._registerTrackedNode = function (group) {
  16246. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  16247. return;
  16248. }
  16249. if (!this._trackedGroups) {
  16250. this._trackedGroups = new Array();
  16251. }
  16252. this._trackedGroups.push(group);
  16253. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  16254. };
  16255. /**
  16256. * Internal method used to unregister a tracked Scene Node
  16257. * Do not invoke this method, it's for internal purpose only.
  16258. * @param group the group to unregister its tracked Scene Node from.
  16259. */
  16260. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  16261. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  16262. return;
  16263. }
  16264. var i = this._trackedGroups.indexOf(group);
  16265. if (i !== -1) {
  16266. this._trackedGroups.splice(i, 1);
  16267. }
  16268. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  16269. };
  16270. /**
  16271. * Get a Solid Color Brush instance matching the given color.
  16272. * @param color The color to retrieve
  16273. * @return A shared instance of the SolidColorBrush2D class that use the given color
  16274. */
  16275. Canvas2D.GetSolidColorBrush = function (color) {
  16276. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  16277. };
  16278. /**
  16279. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  16280. * @param color The color to retrieve
  16281. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  16282. */
  16283. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  16284. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  16285. };
  16286. /**
  16287. * Get a Gradient Color Brush
  16288. * @param color1 starting color
  16289. * @param color2 engine color
  16290. * @param translation translation vector to apply. default is [0;0]
  16291. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  16292. * @param scale scaling factor to apply. default is 1.
  16293. */
  16294. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  16295. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  16296. if (rotation === void 0) { rotation = 0; }
  16297. if (scale === void 0) { scale = 1; }
  16298. return Canvas2D_1._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  16299. };
  16300. /**
  16301. * Create a solid or gradient brush from a string value.
  16302. * @param brushString should be either
  16303. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  16304. * - "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.
  16305. */
  16306. Canvas2D.GetBrushFromString = function (brushString) {
  16307. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  16308. brushString = brushString.trim();
  16309. var split = brushString.split(",");
  16310. // Solid, formatted as: "[solid:]#FF808080"
  16311. if (split.length === 1) {
  16312. var value = null;
  16313. if (brushString.indexOf("solid:") === 0) {
  16314. value = brushString.substr(6).trim();
  16315. }
  16316. else if (brushString.indexOf("#") === 0) {
  16317. value = brushString;
  16318. }
  16319. else {
  16320. return null;
  16321. }
  16322. return Canvas2D_1.GetSolidColorBrushFromHex(value);
  16323. }
  16324. else {
  16325. if (split[0].indexOf("gradient:") === 0) {
  16326. split[0] = split[0].substr(9).trim();
  16327. }
  16328. try {
  16329. var start = BABYLON.Color4.FromHexString(split[0].trim());
  16330. var end = BABYLON.Color4.FromHexString(split[1].trim());
  16331. var t = BABYLON.Vector2.Zero();
  16332. if (split.length > 2) {
  16333. var v = split[2].trim();
  16334. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  16335. return null;
  16336. }
  16337. var sep = v.indexOf(":");
  16338. var x = parseFloat(v.substr(1, sep));
  16339. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  16340. t = new BABYLON.Vector2(x, y);
  16341. }
  16342. var r = 0;
  16343. if (split.length > 3) {
  16344. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  16345. }
  16346. var s = 1;
  16347. if (split.length > 4) {
  16348. s = parseFloat(split[4].trim());
  16349. }
  16350. return Canvas2D_1.GetGradientColorBrush(start, end, t, r, s);
  16351. }
  16352. catch (e) {
  16353. return null;
  16354. }
  16355. }
  16356. };
  16357. return Canvas2D;
  16358. }(BABYLON.Group2D));
  16359. /**
  16360. * 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.
  16361. * This strategy doesn't allow primitives added directly as children of the Canvas.
  16362. * 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.
  16363. */
  16364. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  16365. /**
  16366. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  16367. * 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.
  16368. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  16369. * 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.
  16370. */
  16371. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  16372. /**
  16373. * 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).
  16374. */
  16375. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  16376. /**
  16377. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  16378. * 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).
  16379. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  16380. */
  16381. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  16382. /**
  16383. * Observable Mask to be notified before rendering is made
  16384. */
  16385. Canvas2D.RENDEROBSERVABLE_PRE = 1;
  16386. /**
  16387. * Observable Mask to be notified after rendering is made
  16388. */
  16389. Canvas2D.RENDEROBSERVABLE_POST = 2;
  16390. Canvas2D._INSTANCES = [];
  16391. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  16392. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  16393. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  16394. Canvas2D._m = BABYLON.Matrix.Identity();
  16395. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  16396. Canvas2D.tS = BABYLON.Vector3.Zero();
  16397. Canvas2D.tT = BABYLON.Vector3.Zero();
  16398. Canvas2D.tR = BABYLON.Quaternion.Identity();
  16399. /**
  16400. * Define the default size used for both the width and height of a MapTexture to allocate.
  16401. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  16402. */
  16403. Canvas2D._groupTextureCacheSize = 1024;
  16404. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  16405. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  16406. Canvas2D = Canvas2D_1 = __decorate([
  16407. BABYLON.className("Canvas2D", "BABYLON")
  16408. ], Canvas2D);
  16409. BABYLON.Canvas2D = Canvas2D;
  16410. var WorldSpaceCanvas2D = (function (_super) {
  16411. __extends(WorldSpaceCanvas2D, _super);
  16412. /**
  16413. * 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.
  16414. * 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.
  16415. * @param scene the Scene that owns the Canvas
  16416. * @param size the dimension of the Canvas in World Space
  16417. * @param settings a combination of settings, possible ones are
  16418. * - children: an array of direct children primitives
  16419. * - id: a text identifier, for information purpose only, default is null.
  16420. * - 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).
  16421. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  16422. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  16423. * - 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
  16424. * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
  16425. * - trackNodeBillboard: if true the WorldSpaceCanvas will always face the screen
  16426. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  16427. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  16428. * - 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).
  16429. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  16430. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  16431. * - 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.
  16432. * - 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.
  16433. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  16434. * - 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.
  16435. * - 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.
  16436. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16437. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16438. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16439. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16440. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  16441. */
  16442. function WorldSpaceCanvas2D(scene, size, settings) {
  16443. var _this = this;
  16444. BABYLON.Prim2DBase._isCanvasInit = true;
  16445. var s = settings;
  16446. s.isScreenSpace = false;
  16447. if (settings.unitScaleFactor != null) {
  16448. s.size = size.multiplyByFloats(settings.unitScaleFactor, settings.unitScaleFactor);
  16449. }
  16450. else {
  16451. s.size = size.clone();
  16452. }
  16453. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  16454. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  16455. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  16456. }
  16457. _this = _super.call(this, scene, settings) || this;
  16458. BABYLON.Prim2DBase._isCanvasInit = false;
  16459. _this._unitScaleFactor = (settings.unitScaleFactor != null) ? settings.unitScaleFactor : 1;
  16460. _this._renderableData._useMipMap = true;
  16461. _this._renderableData._anisotropicLevel = 8;
  16462. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  16463. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  16464. //}
  16465. _this._trackNode = (settings.trackNode != null) ? settings.trackNode : null;
  16466. _this._trackNodeOffset = (settings.trackNodeOffset != null) ? settings.trackNodeOffset : BABYLON.Vector3.Zero();
  16467. _this._trackNodeBillboard = (settings.trackNodeBillboard != null) ? settings.trackNodeBillboard : true;
  16468. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  16469. _this._customWorldSpaceNode = !createWorldSpaceNode;
  16470. var id = settings ? settings.id || null : null;
  16471. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  16472. var capMaxTextSize = _this.engine.getCaps().maxRenderTextureSize;
  16473. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 1K if allowed otherwise the max allowed
  16474. if (settings.maxAdaptiveCanvasSize == null) {
  16475. _this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  16476. }
  16477. else {
  16478. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  16479. _this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  16480. }
  16481. if (createWorldSpaceNode) {
  16482. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, _this);
  16483. var vertexData = BABYLON.VertexData.CreatePlane({
  16484. width: size.width,
  16485. height: size.height,
  16486. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  16487. });
  16488. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  16489. _this.applyCachedTexture(vertexData, mtl);
  16490. vertexData.applyToMesh(plane, true);
  16491. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  16492. mtl.disableLighting = true;
  16493. mtl.useAlphaFromDiffuseTexture = true;
  16494. if (settings && settings.sideOrientation) {
  16495. mtl.backFaceCulling = (settings.sideOrientation === BABYLON.Mesh.DEFAULTSIDE || settings.sideOrientation === BABYLON.Mesh.FRONTSIDE);
  16496. }
  16497. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  16498. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  16499. plane.material = mtl;
  16500. _this._worldSpaceNode = plane;
  16501. }
  16502. else {
  16503. _this._worldSpaceNode = settings.customWorldSpaceNode;
  16504. _this.applyCachedTexture(null, null);
  16505. }
  16506. _this.propertyChanged.add(function (e, st) {
  16507. if (e.propertyName !== "isVisible") {
  16508. return;
  16509. }
  16510. var mesh = _this._worldSpaceNode;
  16511. if (mesh) {
  16512. mesh.isVisible = e.newValue;
  16513. }
  16514. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  16515. return _this;
  16516. }
  16517. WorldSpaceCanvas2D.prototype.dispose = function () {
  16518. if (!_super.prototype.dispose.call(this)) {
  16519. return false;
  16520. }
  16521. if (!this._customWorldSpaceNode && this._worldSpaceNode) {
  16522. this._worldSpaceNode.dispose();
  16523. this._worldSpaceNode = null;
  16524. }
  16525. };
  16526. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNode", {
  16527. get: function () {
  16528. return this._trackNode;
  16529. },
  16530. set: function (value) {
  16531. if (this._trackNode === value) {
  16532. return;
  16533. }
  16534. this._trackNode = value;
  16535. },
  16536. enumerable: true,
  16537. configurable: true
  16538. });
  16539. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeOffset", {
  16540. get: function () {
  16541. return this._trackNodeOffset;
  16542. },
  16543. set: function (value) {
  16544. if (!this._trackNodeOffset) {
  16545. this._trackNodeOffset = value.clone();
  16546. }
  16547. else {
  16548. this._trackNodeOffset.copyFrom(value);
  16549. }
  16550. },
  16551. enumerable: true,
  16552. configurable: true
  16553. });
  16554. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeBillboard", {
  16555. get: function () {
  16556. return this._trackNodeBillboard;
  16557. },
  16558. set: function (value) {
  16559. this._trackNodeBillboard = value;
  16560. },
  16561. enumerable: true,
  16562. configurable: true
  16563. });
  16564. return WorldSpaceCanvas2D;
  16565. }(Canvas2D));
  16566. WorldSpaceCanvas2D = __decorate([
  16567. BABYLON.className("WorldSpaceCanvas2D", "BABYLON")
  16568. ], WorldSpaceCanvas2D);
  16569. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  16570. var ScreenSpaceCanvas2D = (function (_super) {
  16571. __extends(ScreenSpaceCanvas2D, _super);
  16572. /**
  16573. * 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.
  16574. * 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.
  16575. * All caching strategies will be available.
  16576. * 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]
  16577. * @param scene the Scene that owns the Canvas
  16578. * @param settings a combination of settings, possible ones are
  16579. * - children: an array of direct children primitives
  16580. * - id: a text identifier, for information purpose only
  16581. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  16582. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  16583. * - 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]
  16584. * - width: the width of the Canvas. you can alternatively use the size setting.
  16585. * - height: the height of the Canvas. you can alternatively use the size setting.
  16586. * - 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
  16587. * - 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.
  16588. * - 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.
  16589. * - 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.
  16590. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  16591. * - 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.
  16592. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  16593. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  16594. * - 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.
  16595. * - 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.
  16596. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  16597. * - 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.
  16598. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16599. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16600. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16601. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16602. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  16603. */
  16604. function ScreenSpaceCanvas2D(scene, settings) {
  16605. var _this = this;
  16606. BABYLON.Prim2DBase._isCanvasInit = true;
  16607. _this = _super.call(this, scene, settings) || this;
  16608. return _this;
  16609. }
  16610. return ScreenSpaceCanvas2D;
  16611. }(Canvas2D));
  16612. ScreenSpaceCanvas2D = __decorate([
  16613. BABYLON.className("ScreenSpaceCanvas2D", "BABYLON")
  16614. ], ScreenSpaceCanvas2D);
  16615. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  16616. var Canvas2D_1;
  16617. })(BABYLON || (BABYLON = {}));
  16618. var __extends = (this && this.__extends) || function (d, b) {
  16619. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16620. function __() { this.constructor = d; }
  16621. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16622. };
  16623. var BABYLON;
  16624. (function (BABYLON) {
  16625. /**
  16626. * This is the class that is used to display a World Space Canvas into a 3D scene
  16627. */
  16628. var WorldSpaceCanvas2DNode = (function (_super) {
  16629. __extends(WorldSpaceCanvas2DNode, _super);
  16630. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  16631. var _this = _super.call(this, name, scene) || this;
  16632. _this._canvas = canvas;
  16633. return _this;
  16634. }
  16635. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  16636. _super.prototype.dispose.call(this);
  16637. if (this._canvas) {
  16638. this._canvas.dispose();
  16639. this._canvas = null;
  16640. }
  16641. };
  16642. return WorldSpaceCanvas2DNode;
  16643. }(BABYLON.Mesh));
  16644. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  16645. })(BABYLON || (BABYLON = {}));
  16646. var __extends = (this && this.__extends) || function (d, b) {
  16647. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16648. function __() { this.constructor = d; }
  16649. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16650. };
  16651. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  16652. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  16653. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  16654. 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;
  16655. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16656. };
  16657. var BABYLON;
  16658. (function (BABYLON) {
  16659. var Command = (function () {
  16660. function Command(execute, canExecute) {
  16661. if (!execute) {
  16662. throw Error("At least an execute lambda must be given at Command creation time");
  16663. }
  16664. this._canExecuteChanged = null;
  16665. this._lastCanExecuteResult = null;
  16666. this.execute = execute;
  16667. this.canExecute = canExecute;
  16668. }
  16669. Command.prototype.canExecute = function (parameter) {
  16670. var res = true;
  16671. if (this._canExecute) {
  16672. res = this._canExecute(parameter);
  16673. }
  16674. if (res !== this._lastCanExecuteResult) {
  16675. if (this._canExecuteChanged && this._canExecuteChanged.hasObservers()) {
  16676. this._canExecuteChanged.notifyObservers(null);
  16677. }
  16678. this._lastCanExecuteResult = res;
  16679. }
  16680. return res;
  16681. };
  16682. Command.prototype.execute = function (parameter) {
  16683. this._execute(parameter);
  16684. };
  16685. Object.defineProperty(Command.prototype, "canExecuteChanged", {
  16686. get: function () {
  16687. if (!this._canExecuteChanged) {
  16688. this._canExecuteChanged = new BABYLON.Observable();
  16689. }
  16690. return this._canExecuteChanged;
  16691. },
  16692. enumerable: true,
  16693. configurable: true
  16694. });
  16695. return Command;
  16696. }());
  16697. BABYLON.Command = Command;
  16698. var UIElement = (function (_super) {
  16699. __extends(UIElement, _super);
  16700. function UIElement(settings) {
  16701. var _this = _super.call(this) || this;
  16702. if (!settings) {
  16703. throw Error("A settings object must be passed with at least either a parent or owner parameter");
  16704. }
  16705. var type = BABYLON.Tools.getFullClassName(_this);
  16706. _this._ownerWindow = null;
  16707. _this._parent = null;
  16708. _this._visualPlaceholder = null;
  16709. _this._visualTemplateRoot = null;
  16710. _this._visualChildrenPlaceholder = null;
  16711. _this._hierarchyDepth = 0;
  16712. _this._renderingTemplateName = (settings.templateName != null) ? settings.templateName : GUIManager.DefaultTemplateName;
  16713. _this._style = (settings.styleName != null) ? GUIManager.getStyle(type, settings.styleName) : null;
  16714. _this._flags = 0;
  16715. _this._id = (settings.id != null) ? settings.id : null;
  16716. _this._uid = null;
  16717. _this._width = (settings.width != null) ? settings.width : null;
  16718. _this._height = (settings.height != null) ? settings.height : null;
  16719. _this._minWidth = (settings.minWidth != null) ? settings.minWidth : 0;
  16720. _this._minHeight = (settings.minHeight != null) ? settings.minHeight : 0;
  16721. _this._maxWidth = (settings.maxWidth != null) ? settings.maxWidth : Number.MAX_VALUE;
  16722. _this._maxHeight = (settings.maxHeight != null) ? settings.maxHeight : Number.MAX_VALUE;
  16723. _this._margin = null;
  16724. _this._padding = null;
  16725. _this._marginAlignment = null;
  16726. _this._setFlags(UIElement.flagIsVisible | UIElement.flagIsEnabled);
  16727. // Default Margin Alignment for UIElement is stretch for horizontal/vertical and not left/bottom (which is the default for Canvas2D Primitives)
  16728. //this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  16729. //this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  16730. // Set the layout/margin stuffs
  16731. if (settings.marginTop) {
  16732. _this.margin.setTop(settings.marginTop);
  16733. }
  16734. if (settings.marginLeft) {
  16735. _this.margin.setLeft(settings.marginLeft);
  16736. }
  16737. if (settings.marginRight) {
  16738. _this.margin.setRight(settings.marginRight);
  16739. }
  16740. if (settings.marginBottom) {
  16741. _this.margin.setBottom(settings.marginBottom);
  16742. }
  16743. if (settings.margin) {
  16744. if (typeof settings.margin === "string") {
  16745. _this.margin.fromString(settings.margin);
  16746. }
  16747. else {
  16748. _this.margin.fromUniformPixels(settings.margin);
  16749. }
  16750. }
  16751. if (settings.marginHAlignment) {
  16752. _this.marginAlignment.horizontal = settings.marginHAlignment;
  16753. }
  16754. if (settings.marginVAlignment) {
  16755. _this.marginAlignment.vertical = settings.marginVAlignment;
  16756. }
  16757. if (settings.marginAlignment) {
  16758. _this.marginAlignment.fromString(settings.marginAlignment);
  16759. }
  16760. if (settings.paddingTop) {
  16761. _this.padding.setTop(settings.paddingTop);
  16762. }
  16763. if (settings.paddingLeft) {
  16764. _this.padding.setLeft(settings.paddingLeft);
  16765. }
  16766. if (settings.paddingRight) {
  16767. _this.padding.setRight(settings.paddingRight);
  16768. }
  16769. if (settings.paddingBottom) {
  16770. _this.padding.setBottom(settings.paddingBottom);
  16771. }
  16772. if (settings.padding) {
  16773. _this.padding.fromString(settings.padding);
  16774. }
  16775. if (settings.paddingHAlignment) {
  16776. _this.paddingAlignment.horizontal = settings.paddingHAlignment;
  16777. }
  16778. if (settings.paddingVAlignment) {
  16779. _this.paddingAlignment.vertical = settings.paddingVAlignment;
  16780. }
  16781. if (settings.paddingAlignment) {
  16782. _this.paddingAlignment.fromString(settings.paddingAlignment);
  16783. }
  16784. if (settings.parent != null) {
  16785. _this._parent = settings.parent;
  16786. _this._hierarchyDepth = _this._parent._hierarchyDepth + 1;
  16787. }
  16788. return _this;
  16789. }
  16790. Object.defineProperty(UIElement, "enabledState", {
  16791. get: function () {
  16792. return UIElement._enableState;
  16793. },
  16794. enumerable: true,
  16795. configurable: true
  16796. });
  16797. Object.defineProperty(UIElement, "disabledState", {
  16798. get: function () {
  16799. return UIElement._disabledState;
  16800. },
  16801. enumerable: true,
  16802. configurable: true
  16803. });
  16804. Object.defineProperty(UIElement, "mouseOverState", {
  16805. get: function () {
  16806. return UIElement._mouseOverState;
  16807. },
  16808. enumerable: true,
  16809. configurable: true
  16810. });
  16811. UIElement.prototype.dispose = function () {
  16812. if (this.isDisposed) {
  16813. return false;
  16814. }
  16815. if (this._renderingTemplate) {
  16816. this._renderingTemplate.detach();
  16817. this._renderingTemplate = null;
  16818. }
  16819. _super.prototype.dispose.call(this);
  16820. // Don't set to null, it may upset somebody...
  16821. this.animations.splice(0);
  16822. return true;
  16823. };
  16824. /**
  16825. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  16826. * Look at Sprite2D for more information
  16827. */
  16828. UIElement.prototype.getAnimatables = function () {
  16829. return new Array();
  16830. };
  16831. // TODO
  16832. // PROPERTIES
  16833. // Style
  16834. // Id
  16835. // Parent/Children
  16836. // ActualWidth/Height, MinWidth/Height, MaxWidth/Height,
  16837. // Alignment/Margin
  16838. // Visibility, IsVisible
  16839. // IsEnabled (is false, control is disabled, no interaction and a specific render state)
  16840. // CacheMode of Visual Elements
  16841. // Focusable/IsFocused
  16842. // IsPointerCaptured, CapturePointer, IsPointerDirectlyOver, IsPointerOver. De-correlate mouse, stylus, touch?
  16843. // ContextMenu
  16844. // Cursor
  16845. // DesiredSize
  16846. // IsInputEnable ?
  16847. // Opacity, OpacityMask ?
  16848. // SnapToDevicePixels
  16849. // Tag
  16850. // ToolTip
  16851. // METHODS
  16852. // BringIntoView (for scrollable content, to move the scroll to bring the given element visible in the parent's area)
  16853. // Capture/ReleaseCapture (mouse, touch, stylus)
  16854. // Focus
  16855. // PointFrom/ToScreen to translate coordinates
  16856. // EVENTS
  16857. // ContextMenuOpening/Closing/Changed
  16858. // DragEnter/LeaveOver, Drop
  16859. // Got/LostFocus
  16860. // IsEnabledChanged
  16861. // IsPointerOver/DirectlyOverChanged
  16862. // IsVisibleChanged
  16863. // KeyDown/Up
  16864. // LayoutUpdated ?
  16865. // Pointer related events
  16866. // SizeChanged
  16867. // ToolTipOpening/Closing
  16868. UIElement.prototype.findById = function (id) {
  16869. if (this._id === id) {
  16870. return this;
  16871. }
  16872. var children = this._getChildren();
  16873. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  16874. var child = children_1[_i];
  16875. var r = child.findById(id);
  16876. if (r != null) {
  16877. return r;
  16878. }
  16879. }
  16880. };
  16881. Object.defineProperty(UIElement.prototype, "ownerWindow", {
  16882. get: function () {
  16883. return this._ownerWindow;
  16884. },
  16885. enumerable: true,
  16886. configurable: true
  16887. });
  16888. Object.defineProperty(UIElement.prototype, "style", {
  16889. get: function () {
  16890. if (!this.style) {
  16891. return GUIManager.DefaultStyleName;
  16892. }
  16893. return this._style.name;
  16894. },
  16895. set: function (value) {
  16896. if (this._style && (this._style.name === value)) {
  16897. return;
  16898. }
  16899. var newStyle = null;
  16900. if (value) {
  16901. newStyle = GUIManager.getStyle(BABYLON.Tools.getFullClassName(this), value);
  16902. if (!newStyle) {
  16903. throw Error("Couldn't find Style " + value + " for UIElement " + BABYLON.Tools.getFullClassName(this));
  16904. }
  16905. }
  16906. if (this._style) {
  16907. this._style.removeStyle(this);
  16908. }
  16909. if (newStyle) {
  16910. newStyle.applyStyle(this);
  16911. }
  16912. this._style = newStyle;
  16913. },
  16914. enumerable: true,
  16915. configurable: true
  16916. });
  16917. Object.defineProperty(UIElement.prototype, "id", {
  16918. /**
  16919. * A string that identifies the UIElement.
  16920. * The id is optional and there's possible collision with other UIElement's id as the uniqueness is not supported.
  16921. */
  16922. get: function () {
  16923. return this._id;
  16924. },
  16925. set: function (value) {
  16926. if (this._id === value) {
  16927. return;
  16928. }
  16929. this._id = value;
  16930. },
  16931. enumerable: true,
  16932. configurable: true
  16933. });
  16934. Object.defineProperty(UIElement.prototype, "uid", {
  16935. /**
  16936. * Return a unique id automatically generated.
  16937. * This property is mainly used for serialization to ensure a perfect way of identifying a UIElement
  16938. */
  16939. get: function () {
  16940. if (!this._uid) {
  16941. this._uid = BABYLON.Tools.RandomId();
  16942. }
  16943. return this._uid;
  16944. },
  16945. enumerable: true,
  16946. configurable: true
  16947. });
  16948. Object.defineProperty(UIElement.prototype, "hierarchyDepth", {
  16949. get: function () {
  16950. return this._hierarchyDepth;
  16951. },
  16952. enumerable: true,
  16953. configurable: true
  16954. });
  16955. Object.defineProperty(UIElement.prototype, "parent", {
  16956. get: function () {
  16957. return this._parent;
  16958. },
  16959. set: function (value) {
  16960. this._parent = value;
  16961. },
  16962. enumerable: true,
  16963. configurable: true
  16964. });
  16965. Object.defineProperty(UIElement.prototype, "width", {
  16966. get: function () {
  16967. return this._width;
  16968. },
  16969. set: function (value) {
  16970. this._width = value;
  16971. },
  16972. enumerable: true,
  16973. configurable: true
  16974. });
  16975. Object.defineProperty(UIElement.prototype, "height", {
  16976. get: function () {
  16977. return this._height;
  16978. },
  16979. set: function (value) {
  16980. this._height = value;
  16981. },
  16982. enumerable: true,
  16983. configurable: true
  16984. });
  16985. Object.defineProperty(UIElement.prototype, "minWidth", {
  16986. get: function () {
  16987. return this._minWidth;
  16988. },
  16989. set: function (value) {
  16990. this._minWidth = value;
  16991. },
  16992. enumerable: true,
  16993. configurable: true
  16994. });
  16995. Object.defineProperty(UIElement.prototype, "minHheight", {
  16996. get: function () {
  16997. return this._minHeight;
  16998. },
  16999. enumerable: true,
  17000. configurable: true
  17001. });
  17002. Object.defineProperty(UIElement.prototype, "minHeight", {
  17003. set: function (value) {
  17004. this._minHeight = value;
  17005. },
  17006. enumerable: true,
  17007. configurable: true
  17008. });
  17009. Object.defineProperty(UIElement.prototype, "maxWidth", {
  17010. get: function () {
  17011. return this._maxWidth;
  17012. },
  17013. set: function (value) {
  17014. this._maxWidth = value;
  17015. },
  17016. enumerable: true,
  17017. configurable: true
  17018. });
  17019. Object.defineProperty(UIElement.prototype, "maxHeight", {
  17020. get: function () {
  17021. return this._maxHeight;
  17022. },
  17023. set: function (value) {
  17024. this._maxHeight = value;
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. Object.defineProperty(UIElement.prototype, "actualWidth", {
  17030. get: function () {
  17031. return this._actualWidth;
  17032. },
  17033. set: function (value) {
  17034. this._actualWidth = value;
  17035. },
  17036. enumerable: true,
  17037. configurable: true
  17038. });
  17039. Object.defineProperty(UIElement.prototype, "actualHeight", {
  17040. get: function () {
  17041. return this._actualHeight;
  17042. },
  17043. set: function (value) {
  17044. this._actualHeight = value;
  17045. },
  17046. enumerable: true,
  17047. configurable: true
  17048. });
  17049. Object.defineProperty(UIElement.prototype, "margin", {
  17050. get: function () {
  17051. var _this = this;
  17052. if (!this._margin) {
  17053. this._margin = new BABYLON.PrimitiveThickness(function () {
  17054. if (!_this.parent) {
  17055. return null;
  17056. }
  17057. return _this.parent.margin;
  17058. });
  17059. }
  17060. return this._margin;
  17061. },
  17062. set: function (value) {
  17063. this.margin.copyFrom(value);
  17064. },
  17065. enumerable: true,
  17066. configurable: true
  17067. });
  17068. Object.defineProperty(UIElement.prototype, "_hasMargin", {
  17069. get: function () {
  17070. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  17071. },
  17072. enumerable: true,
  17073. configurable: true
  17074. });
  17075. Object.defineProperty(UIElement.prototype, "padding", {
  17076. get: function () {
  17077. var _this = this;
  17078. if (!this._padding) {
  17079. this._padding = new BABYLON.PrimitiveThickness(function () {
  17080. if (!_this.parent) {
  17081. return null;
  17082. }
  17083. return _this.parent.padding;
  17084. });
  17085. }
  17086. return this._padding;
  17087. },
  17088. set: function (value) {
  17089. this.padding.copyFrom(value);
  17090. },
  17091. enumerable: true,
  17092. configurable: true
  17093. });
  17094. Object.defineProperty(UIElement.prototype, "_hasPadding", {
  17095. get: function () {
  17096. return this._padding !== null && !this._padding.isDefault;
  17097. },
  17098. enumerable: true,
  17099. configurable: true
  17100. });
  17101. Object.defineProperty(UIElement.prototype, "marginAlignment", {
  17102. get: function () {
  17103. if (!this._marginAlignment) {
  17104. this._marginAlignment = new BABYLON.PrimitiveAlignment();
  17105. }
  17106. return this._marginAlignment;
  17107. },
  17108. set: function (value) {
  17109. this.marginAlignment.copyFrom(value);
  17110. },
  17111. enumerable: true,
  17112. configurable: true
  17113. });
  17114. Object.defineProperty(UIElement.prototype, "_hasMarginAlignment", {
  17115. /**
  17116. * Check if there a marginAlignment specified (non null and not default)
  17117. */
  17118. get: function () {
  17119. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. Object.defineProperty(UIElement.prototype, "paddingAlignment", {
  17125. get: function () {
  17126. if (!this._paddingAlignment) {
  17127. this._paddingAlignment = new BABYLON.PrimitiveAlignment();
  17128. }
  17129. return this._paddingAlignment;
  17130. },
  17131. set: function (value) {
  17132. this.paddingAlignment.copyFrom(value);
  17133. },
  17134. enumerable: true,
  17135. configurable: true
  17136. });
  17137. Object.defineProperty(UIElement.prototype, "_hasPaddingAlignment", {
  17138. /**
  17139. * Check if there a marginAlignment specified (non null and not default)
  17140. */
  17141. get: function () {
  17142. return (this._paddingAlignment !== null && !this._paddingAlignment.isDefault);
  17143. },
  17144. enumerable: true,
  17145. configurable: true
  17146. });
  17147. Object.defineProperty(UIElement.prototype, "isVisible", {
  17148. get: function () {
  17149. return this._isFlagSet(UIElement.flagIsVisible);
  17150. },
  17151. set: function (value) {
  17152. if (this.isVisible === value) {
  17153. return;
  17154. }
  17155. this._visualPlaceholder.levelVisible = value;
  17156. this._changeFlags(UIElement.flagIsVisible, value);
  17157. },
  17158. enumerable: true,
  17159. configurable: true
  17160. });
  17161. Object.defineProperty(UIElement.prototype, "isEnabled", {
  17162. get: function () {
  17163. return this._isFlagSet(UIElement.flagIsEnabled);
  17164. },
  17165. set: function (value) {
  17166. this._changeFlags(UIElement.flagIsEnabled, value);
  17167. },
  17168. enumerable: true,
  17169. configurable: true
  17170. });
  17171. Object.defineProperty(UIElement.prototype, "isFocused", {
  17172. get: function () {
  17173. return this._isFlagSet(UIElement.flagIsFocus);
  17174. },
  17175. set: function (value) {
  17176. // If the UIElement doesn't accept focus, set it on its parent
  17177. if (!this.isFocusable) {
  17178. var p = this.parent;
  17179. if (!p) {
  17180. return;
  17181. }
  17182. p.isFocused = value;
  17183. }
  17184. // If the focus is being set, notify the Focus Manager
  17185. if (value) {
  17186. this.ownerWindow.focusManager.setFocusOn(this, this.getFocusScope());
  17187. }
  17188. this._changeFlags(UIElement.flagIsFocus, value);
  17189. },
  17190. enumerable: true,
  17191. configurable: true
  17192. });
  17193. Object.defineProperty(UIElement.prototype, "isMouseOver", {
  17194. get: function () {
  17195. return this._isFlagSet(UIElement.flagIsMouseOver);
  17196. },
  17197. set: function (value) {
  17198. this._changeFlags(UIElement.flagIsMouseOver, value);
  17199. },
  17200. enumerable: true,
  17201. configurable: true
  17202. });
  17203. Object.defineProperty(UIElement.prototype, "isFocusScope", {
  17204. get: function () {
  17205. return this._isFlagSet(UIElement.flagIsFocusScope);
  17206. },
  17207. set: function (value) {
  17208. this._changeFlags(UIElement.flagIsFocusScope, value);
  17209. },
  17210. enumerable: true,
  17211. configurable: true
  17212. });
  17213. Object.defineProperty(UIElement.prototype, "isFocusable", {
  17214. get: function () {
  17215. return this._isFlagSet(UIElement.flagIsFocusable);
  17216. },
  17217. set: function (value) {
  17218. this._changeFlags(UIElement.flagIsFocusable, value);
  17219. },
  17220. enumerable: true,
  17221. configurable: true
  17222. });
  17223. // 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)
  17224. UIElement.prototype.getFocusScope = function () {
  17225. if (this.isFocusScope) {
  17226. return this;
  17227. }
  17228. var p = this.parent;
  17229. if (!p) {
  17230. return null;
  17231. }
  17232. return p.getFocusScope();
  17233. };
  17234. /**
  17235. * Check if a given flag is set
  17236. * @param flag the flag value
  17237. * @return true if set, false otherwise
  17238. */
  17239. UIElement.prototype._isFlagSet = function (flag) {
  17240. return (this._flags & flag) !== 0;
  17241. };
  17242. /**
  17243. * Check if all given flags are set
  17244. * @param flags the flags ORed
  17245. * @return true if all the flags are set, false otherwise
  17246. */
  17247. UIElement.prototype._areAllFlagsSet = function (flags) {
  17248. return (this._flags & flags) === flags;
  17249. };
  17250. /**
  17251. * Check if at least one flag of the given flags is set
  17252. * @param flags the flags ORed
  17253. * @return true if at least one flag is set, false otherwise
  17254. */
  17255. UIElement.prototype._areSomeFlagsSet = function (flags) {
  17256. return (this._flags & flags) !== 0;
  17257. };
  17258. /**
  17259. * Clear the given flags
  17260. * @param flags the flags to clear
  17261. */
  17262. UIElement.prototype._clearFlags = function (flags) {
  17263. this._flags &= ~flags;
  17264. };
  17265. /**
  17266. * Set the given flags to true state
  17267. * @param flags the flags ORed to set
  17268. * @return the flags state before this call
  17269. */
  17270. UIElement.prototype._setFlags = function (flags) {
  17271. var cur = this._flags;
  17272. this._flags |= flags;
  17273. return cur;
  17274. };
  17275. /**
  17276. * Change the state of the given flags
  17277. * @param flags the flags ORed to change
  17278. * @param state true to set them, false to clear them
  17279. */
  17280. UIElement.prototype._changeFlags = function (flags, state) {
  17281. if (state) {
  17282. this._flags |= flags;
  17283. }
  17284. else {
  17285. this._flags &= ~flags;
  17286. }
  17287. };
  17288. UIElement.prototype._assignTemplate = function (templateName) {
  17289. if (!templateName) {
  17290. templateName = GUIManager.DefaultTemplateName;
  17291. }
  17292. var className = BABYLON.Tools.getFullClassName(this);
  17293. if (!className) {
  17294. throw Error("Couldn't access class name of this UIElement, you have to decorate the type with the className decorator");
  17295. }
  17296. var factory = GUIManager.getRenderingTemplate(className, templateName);
  17297. if (!factory) {
  17298. throw Error("Couldn't get the renderingTemplate " + templateName + " of class " + className);
  17299. }
  17300. this._renderingTemplateName = templateName;
  17301. this._renderingTemplate = factory();
  17302. this._renderingTemplate.attach(this);
  17303. };
  17304. UIElement.prototype._createVisualTree = function () {
  17305. var parentPrim = this.ownerWindow.canvas;
  17306. if (this.parent) {
  17307. parentPrim = this.parent.visualChildrenPlaceholder;
  17308. }
  17309. if (!this._renderingTemplate) {
  17310. this._assignTemplate(this._renderingTemplateName);
  17311. }
  17312. this._visualPlaceholder = new BABYLON.Group2D({ parent: parentPrim, id: "GUI " + BABYLON.Tools.getClassName(this) + " RootGroup of " + this.id });
  17313. var p = this._visualPlaceholder;
  17314. p.addExternalData("_GUIOwnerElement_", this);
  17315. p.dataSource = this;
  17316. p.createSimpleDataBinding(BABYLON.Prim2DBase.widthProperty, "width", BABYLON.DataBinding.MODE_ONEWAY);
  17317. p.createSimpleDataBinding(BABYLON.Prim2DBase.heightProperty, "height", BABYLON.DataBinding.MODE_ONEWAY);
  17318. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualWidthProperty, "actualWidth", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  17319. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualHeightProperty, "actualHeight", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  17320. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "margin", BABYLON.DataBinding.MODE_ONEWAY);
  17321. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "marginAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  17322. this.createVisualTree();
  17323. };
  17324. UIElement.prototype._patchUIElement = function (ownerWindow, parent) {
  17325. if (ownerWindow) {
  17326. if (!this._ownerWindow) {
  17327. ownerWindow._registerVisualToBuild(this);
  17328. }
  17329. this._ownerWindow = ownerWindow;
  17330. }
  17331. this._parent = parent;
  17332. if (parent) {
  17333. this._hierarchyDepth = parent.hierarchyDepth + 1;
  17334. }
  17335. var children = this._getChildren();
  17336. if (children) {
  17337. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  17338. var curChild = children_2[_i];
  17339. curChild._patchUIElement(ownerWindow, this);
  17340. }
  17341. }
  17342. };
  17343. // 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.
  17344. UIElement.prototype._getDataSource = function () {
  17345. var levelDS = _super.prototype._getDataSource.call(this);
  17346. if (levelDS != null) {
  17347. return levelDS;
  17348. }
  17349. var p = this.parent;
  17350. if (p != null) {
  17351. return p.dataSource;
  17352. }
  17353. return null;
  17354. };
  17355. UIElement.prototype.createVisualTree = function () {
  17356. var res = this._renderingTemplate.createVisualTree(this, this._visualPlaceholder);
  17357. this._visualTemplateRoot = res.root;
  17358. this._visualChildrenPlaceholder = res.contentPlaceholder;
  17359. };
  17360. Object.defineProperty(UIElement.prototype, "visualPlaceholder", {
  17361. get: function () {
  17362. return this._visualPlaceholder;
  17363. },
  17364. enumerable: true,
  17365. configurable: true
  17366. });
  17367. Object.defineProperty(UIElement.prototype, "visualTemplateRoot", {
  17368. get: function () {
  17369. return this._visualTemplateRoot;
  17370. },
  17371. enumerable: true,
  17372. configurable: true
  17373. });
  17374. Object.defineProperty(UIElement.prototype, "visualChildrenPlaceholder", {
  17375. get: function () {
  17376. return this._visualChildrenPlaceholder;
  17377. },
  17378. enumerable: true,
  17379. configurable: true
  17380. });
  17381. Object.defineProperty(UIElement.prototype, "_position", {
  17382. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  17383. ,
  17384. enumerable: true,
  17385. configurable: true
  17386. });
  17387. return UIElement;
  17388. }(BABYLON.SmartPropertyBase));
  17389. UIElement.UIELEMENT_PROPCOUNT = 16;
  17390. UIElement.flagVisualToBuild = 0x0000001;
  17391. UIElement.flagIsVisible = 0x0000002;
  17392. UIElement.flagIsFocus = 0x0000004;
  17393. UIElement.flagIsFocusScope = 0x0000008;
  17394. UIElement.flagIsFocusable = 0x0000010;
  17395. UIElement.flagIsEnabled = 0x0000020;
  17396. UIElement.flagIsMouseOver = 0x0000040;
  17397. UIElement._enableState = "Enabled";
  17398. UIElement._disabledState = "Disabled";
  17399. UIElement._mouseOverState = "MouseOver";
  17400. __decorate([
  17401. BABYLON.dependencyProperty(0, function (pi) { return UIElement.parentProperty = pi; })
  17402. ], UIElement.prototype, "parent", null);
  17403. __decorate([
  17404. BABYLON.dependencyProperty(1, function (pi) { return UIElement.widthProperty = pi; })
  17405. ], UIElement.prototype, "width", null);
  17406. __decorate([
  17407. BABYLON.dependencyProperty(2, function (pi) { return UIElement.heightProperty = pi; })
  17408. ], UIElement.prototype, "height", null);
  17409. __decorate([
  17410. BABYLON.dependencyProperty(3, function (pi) { return UIElement.minWidthProperty = pi; })
  17411. ], UIElement.prototype, "minWidth", null);
  17412. __decorate([
  17413. BABYLON.dependencyProperty(4, function (pi) { return UIElement.minHeightProperty = pi; })
  17414. ], UIElement.prototype, "minHheight", null);
  17415. __decorate([
  17416. BABYLON.dependencyProperty(5, function (pi) { return UIElement.maxWidthProperty = pi; })
  17417. ], UIElement.prototype, "maxWidth", null);
  17418. __decorate([
  17419. BABYLON.dependencyProperty(6, function (pi) { return UIElement.maxHeightProperty = pi; })
  17420. ], UIElement.prototype, "maxHeight", null);
  17421. __decorate([
  17422. BABYLON.dependencyProperty(7, function (pi) { return UIElement.actualWidthProperty = pi; })
  17423. ], UIElement.prototype, "actualWidth", null);
  17424. __decorate([
  17425. BABYLON.dependencyProperty(8, function (pi) { return UIElement.actualHeightProperty = pi; })
  17426. ], UIElement.prototype, "actualHeight", null);
  17427. __decorate([
  17428. BABYLON.dynamicLevelProperty(9, function (pi) { return UIElement.marginProperty = pi; })
  17429. ], UIElement.prototype, "margin", null);
  17430. __decorate([
  17431. BABYLON.dynamicLevelProperty(10, function (pi) { return UIElement.paddingProperty = pi; })
  17432. ], UIElement.prototype, "padding", null);
  17433. __decorate([
  17434. BABYLON.dynamicLevelProperty(11, function (pi) { return UIElement.marginAlignmentProperty = pi; })
  17435. ], UIElement.prototype, "marginAlignment", null);
  17436. __decorate([
  17437. BABYLON.dynamicLevelProperty(12, function (pi) { return UIElement.paddingAlignmentProperty = pi; })
  17438. ], UIElement.prototype, "paddingAlignment", null);
  17439. __decorate([
  17440. BABYLON.dynamicLevelProperty(13, function (pi) { return UIElement.isEnabledProperty = pi; })
  17441. ], UIElement.prototype, "isEnabled", null);
  17442. __decorate([
  17443. BABYLON.dynamicLevelProperty(14, function (pi) { return UIElement.isFocusedProperty = pi; })
  17444. ], UIElement.prototype, "isFocused", null);
  17445. __decorate([
  17446. BABYLON.dynamicLevelProperty(15, function (pi) { return UIElement.isMouseOverProperty = pi; })
  17447. ], UIElement.prototype, "isMouseOver", null);
  17448. BABYLON.UIElement = UIElement;
  17449. var UIElementStyle = (function () {
  17450. function UIElementStyle() {
  17451. }
  17452. Object.defineProperty(UIElementStyle.prototype, "name", {
  17453. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  17454. ,
  17455. enumerable: true,
  17456. configurable: true
  17457. });
  17458. return UIElementStyle;
  17459. }());
  17460. BABYLON.UIElementStyle = UIElementStyle;
  17461. var GUIManager = (function () {
  17462. function GUIManager() {
  17463. }
  17464. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17465. // DATA TEMPLATE MANAGER
  17466. GUIManager.registerDataTemplate = function (className, factory) {
  17467. };
  17468. // DATA TEMPLATE MANAGER
  17469. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17470. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17471. // STYLE MANAGER
  17472. GUIManager.getStyle = function (uiElType, styleName) {
  17473. var styles = GUIManager.stylesByUIElement.get(uiElType);
  17474. if (!styles) {
  17475. throw Error("The type " + uiElType + " is unknown, no style were registered for it.");
  17476. }
  17477. var style = styles.get(styleName);
  17478. if (!style) {
  17479. throw Error("Couldn't find Template " + styleName + " of UIElement type " + uiElType);
  17480. }
  17481. return style;
  17482. };
  17483. GUIManager.registerStyle = function (uiElType, templateName, style) {
  17484. var templates = GUIManager.stylesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  17485. if (templates.contains(templateName)) {
  17486. templates[templateName] = style;
  17487. }
  17488. else {
  17489. templates.add(templateName, style);
  17490. }
  17491. };
  17492. Object.defineProperty(GUIManager, "DefaultStyleName", {
  17493. get: function () {
  17494. return GUIManager._defaultStyleName;
  17495. },
  17496. set: function (value) {
  17497. GUIManager._defaultStyleName = value;
  17498. },
  17499. enumerable: true,
  17500. configurable: true
  17501. });
  17502. // STYLE MANAGER
  17503. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17504. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17505. // RENDERING TEMPLATE MANAGER
  17506. GUIManager.getRenderingTemplate = function (uiElType, templateName) {
  17507. var templates = GUIManager.renderingTemplatesByUIElement.get(uiElType);
  17508. if (!templates) {
  17509. throw Error("The type " + uiElType + " is unknown, no Rendering Template were registered for it.");
  17510. }
  17511. var templateFactory = templates.get(templateName);
  17512. if (!templateFactory) {
  17513. throw Error("Couldn't find Template " + templateName + " of UI Element type " + uiElType);
  17514. }
  17515. return templateFactory;
  17516. };
  17517. GUIManager.registerRenderingTemplate = function (uiElType, templateName, factory) {
  17518. var templates = GUIManager.renderingTemplatesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  17519. if (templates.contains(templateName)) {
  17520. templates[templateName] = factory;
  17521. }
  17522. else {
  17523. templates.add(templateName, factory);
  17524. }
  17525. };
  17526. Object.defineProperty(GUIManager, "DefaultTemplateName", {
  17527. get: function () {
  17528. return GUIManager._defaultTemplateName;
  17529. },
  17530. set: function (value) {
  17531. GUIManager._defaultTemplateName = value;
  17532. },
  17533. enumerable: true,
  17534. configurable: true
  17535. });
  17536. return GUIManager;
  17537. }());
  17538. GUIManager.stylesByUIElement = new BABYLON.StringDictionary();
  17539. GUIManager.renderingTemplatesByUIElement = new BABYLON.StringDictionary();
  17540. // RENDERING TEMPLATE MANAGER
  17541. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17542. GUIManager._defaultTemplateName = "Default";
  17543. GUIManager._defaultStyleName = "Default";
  17544. BABYLON.GUIManager = GUIManager;
  17545. var UIElementRenderingTemplateBase = (function () {
  17546. function UIElementRenderingTemplateBase() {
  17547. }
  17548. UIElementRenderingTemplateBase.prototype.attach = function (owner) {
  17549. this._owner = owner;
  17550. };
  17551. UIElementRenderingTemplateBase.prototype.detach = function () {
  17552. };
  17553. Object.defineProperty(UIElementRenderingTemplateBase.prototype, "owner", {
  17554. get: function () {
  17555. return this._owner;
  17556. },
  17557. enumerable: true,
  17558. configurable: true
  17559. });
  17560. return UIElementRenderingTemplateBase;
  17561. }());
  17562. BABYLON.UIElementRenderingTemplateBase = UIElementRenderingTemplateBase;
  17563. function registerWindowRenderingTemplate(uiElType, templateName, factory) {
  17564. return function () {
  17565. GUIManager.registerRenderingTemplate(uiElType, templateName, factory);
  17566. };
  17567. }
  17568. BABYLON.registerWindowRenderingTemplate = registerWindowRenderingTemplate;
  17569. })(BABYLON || (BABYLON = {}));
  17570. var __extends = (this && this.__extends) || function (d, b) {
  17571. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17572. function __() { this.constructor = d; }
  17573. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17574. };
  17575. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17576. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17577. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17578. 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;
  17579. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17580. };
  17581. var BABYLON;
  17582. (function (BABYLON) {
  17583. var StackPanel = StackPanel_1 = (function (_super) {
  17584. __extends(StackPanel, _super);
  17585. function StackPanel(settings) {
  17586. var _this = this;
  17587. if (!settings) {
  17588. settings = {};
  17589. }
  17590. _this = _super.call(this, settings) || this;
  17591. _this.isOrientationHorizontal = (settings.isOrientationHorizontal == null) ? true : settings.isOrientationHorizontal;
  17592. _this._children = new Array();
  17593. if (settings.children != null) {
  17594. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  17595. var child = _a[_i];
  17596. _this._children.push(child);
  17597. }
  17598. }
  17599. return _this;
  17600. }
  17601. Object.defineProperty(StackPanel.prototype, "isOrientationHorizontal", {
  17602. get: function () {
  17603. return this._isOrientationHorizontal;
  17604. },
  17605. set: function (value) {
  17606. this._isOrientationHorizontal = value;
  17607. },
  17608. enumerable: true,
  17609. configurable: true
  17610. });
  17611. StackPanel.prototype.createVisualTree = function () {
  17612. _super.prototype.createVisualTree.call(this);
  17613. // A StackPanel Control has a Group2D, child of the visualPlaceHolder, which is the Children placeholder.
  17614. // The Children UIElement Tree will be create inside this placeholder.
  17615. this._childrenPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "StackPanel Children Placeholder of " + this.id });
  17616. var p = this._childrenPlaceholder;
  17617. p.layoutEngine = this.isOrientationHorizontal ? BABYLON.StackPanelLayoutEngine.Horizontal : BABYLON.StackPanelLayoutEngine.Vertical;
  17618. // 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.
  17619. p.dataSource = this;
  17620. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  17621. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  17622. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  17623. // But it's not the case for a StackPanel, the placeholder of UIElement Children (the content)
  17624. this._visualChildrenPlaceholder = this._childrenPlaceholder;
  17625. };
  17626. Object.defineProperty(StackPanel.prototype, "children", {
  17627. get: function () {
  17628. return this._children;
  17629. },
  17630. enumerable: true,
  17631. configurable: true
  17632. });
  17633. StackPanel.prototype._getChildren = function () {
  17634. return this.children;
  17635. };
  17636. return StackPanel;
  17637. }(BABYLON.UIElement));
  17638. StackPanel.STACKPANEL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3;
  17639. __decorate([
  17640. BABYLON.dependencyProperty(StackPanel_1.STACKPANEL_PROPCOUNT + 0, function (pi) { return StackPanel_1.orientationHorizontalProperty = pi; })
  17641. ], StackPanel.prototype, "isOrientationHorizontal", null);
  17642. StackPanel = StackPanel_1 = __decorate([
  17643. BABYLON.className("StackPanel", "BABYLON")
  17644. ], StackPanel);
  17645. BABYLON.StackPanel = StackPanel;
  17646. var DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = (function (_super) {
  17647. __extends(DefaultStackPanelRenderingTemplate, _super);
  17648. function DefaultStackPanelRenderingTemplate() {
  17649. return _super !== null && _super.apply(this, arguments) || this;
  17650. }
  17651. DefaultStackPanelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  17652. return { root: visualPlaceholder, contentPlaceholder: visualPlaceholder };
  17653. };
  17654. DefaultStackPanelRenderingTemplate.prototype.attach = function (owner) {
  17655. _super.prototype.attach.call(this, owner);
  17656. };
  17657. return DefaultStackPanelRenderingTemplate;
  17658. }(BABYLON.UIElementRenderingTemplateBase));
  17659. DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = __decorate([
  17660. BABYLON.registerWindowRenderingTemplate("BABYLON.StackPanel", "Default", function () { return new DefaultStackPanelRenderingTemplate_1(); })
  17661. ], DefaultStackPanelRenderingTemplate);
  17662. BABYLON.DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate;
  17663. var StackPanel_1, DefaultStackPanelRenderingTemplate_1;
  17664. })(BABYLON || (BABYLON = {}));
  17665. var __extends = (this && this.__extends) || function (d, b) {
  17666. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17667. function __() { this.constructor = d; }
  17668. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17669. };
  17670. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17671. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17672. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17673. 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;
  17674. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17675. };
  17676. var BABYLON;
  17677. (function (BABYLON) {
  17678. var Control = Control_1 = (function (_super) {
  17679. __extends(Control, _super);
  17680. function Control(settings) {
  17681. return _super.call(this, settings) || this;
  17682. }
  17683. Object.defineProperty(Control.prototype, "background", {
  17684. get: function () {
  17685. if (!this._background) {
  17686. this._background = new BABYLON.ObservableStringDictionary(false);
  17687. }
  17688. return this._background;
  17689. },
  17690. set: function (value) {
  17691. this.background.copyFrom(value);
  17692. },
  17693. enumerable: true,
  17694. configurable: true
  17695. });
  17696. Object.defineProperty(Control.prototype, "border", {
  17697. get: function () {
  17698. return this._border;
  17699. },
  17700. set: function (value) {
  17701. this._border = value;
  17702. },
  17703. enumerable: true,
  17704. configurable: true
  17705. });
  17706. Object.defineProperty(Control.prototype, "borderThickness", {
  17707. get: function () {
  17708. return this._borderThickness;
  17709. },
  17710. set: function (value) {
  17711. this._borderThickness = value;
  17712. },
  17713. enumerable: true,
  17714. configurable: true
  17715. });
  17716. Object.defineProperty(Control.prototype, "fontName", {
  17717. get: function () {
  17718. return this._fontName;
  17719. },
  17720. set: function (value) {
  17721. this._fontName = value;
  17722. },
  17723. enumerable: true,
  17724. configurable: true
  17725. });
  17726. Object.defineProperty(Control.prototype, "foreground", {
  17727. get: function () {
  17728. return this._foreground;
  17729. },
  17730. set: function (value) {
  17731. this._foreground = value;
  17732. },
  17733. enumerable: true,
  17734. configurable: true
  17735. });
  17736. return Control;
  17737. }(BABYLON.UIElement));
  17738. Control.CONTROL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 5;
  17739. __decorate([
  17740. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 0, function (pi) { return Control_1.backgroundProperty = pi; })
  17741. ], Control.prototype, "background", null);
  17742. __decorate([
  17743. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 1, function (pi) { return Control_1.borderProperty = pi; })
  17744. ], Control.prototype, "border", null);
  17745. __decorate([
  17746. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 2, function (pi) { return Control_1.borderThicknessProperty = pi; })
  17747. ], Control.prototype, "borderThickness", null);
  17748. __decorate([
  17749. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3, function (pi) { return Control_1.fontNameProperty = pi; })
  17750. ], Control.prototype, "fontName", null);
  17751. __decorate([
  17752. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 4, function (pi) { return Control_1.foregroundProperty = pi; })
  17753. ], Control.prototype, "foreground", null);
  17754. Control = Control_1 = __decorate([
  17755. BABYLON.className("Control", "BABYLON")
  17756. ], Control);
  17757. BABYLON.Control = Control;
  17758. var Control_1;
  17759. })(BABYLON || (BABYLON = {}));
  17760. var __extends = (this && this.__extends) || function (d, b) {
  17761. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17762. function __() { this.constructor = d; }
  17763. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17764. };
  17765. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17766. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17767. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17768. 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;
  17769. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17770. };
  17771. var BABYLON;
  17772. (function (BABYLON) {
  17773. var ContentControl = ContentControl_1 = (function (_super) {
  17774. __extends(ContentControl, _super);
  17775. function ContentControl(settings) {
  17776. var _this = this;
  17777. if (!settings) {
  17778. settings = {};
  17779. }
  17780. _this = _super.call(this, settings) || this;
  17781. if (settings.content != null) {
  17782. _this._content = settings.content;
  17783. }
  17784. return _this;
  17785. }
  17786. ContentControl.prototype.dispose = function () {
  17787. if (this.isDisposed) {
  17788. return false;
  17789. }
  17790. if (this.content && this.content.dispose) {
  17791. this.content.dispose();
  17792. this.content = null;
  17793. }
  17794. if (this.__contentUIElement) {
  17795. this.__contentUIElement.dispose();
  17796. this.__contentUIElement = null;
  17797. }
  17798. _super.prototype.dispose.call(this);
  17799. return true;
  17800. };
  17801. Object.defineProperty(ContentControl.prototype, "content", {
  17802. get: function () {
  17803. return this._content;
  17804. },
  17805. set: function (value) {
  17806. this._content = value;
  17807. },
  17808. enumerable: true,
  17809. configurable: true
  17810. });
  17811. Object.defineProperty(ContentControl.prototype, "_contentUIElement", {
  17812. get: function () {
  17813. if (!this.__contentUIElement) {
  17814. this._buildContentUIElement();
  17815. }
  17816. return this.__contentUIElement;
  17817. },
  17818. enumerable: true,
  17819. configurable: true
  17820. });
  17821. ContentControl.prototype._createVisualTree = function () {
  17822. // Base implementation will create the Group2D for the Visual Placeholder and its Visual Tree
  17823. _super.prototype._createVisualTree.call(this);
  17824. // A Content Control has a Group2D, child of the visualPlaceHolder, which is the Content placeholder.
  17825. // The Content UIElement Tree will be create inside this placeholder.
  17826. this._contentPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "ContentControl Content Placeholder of " + this.id });
  17827. var p = this._contentPlaceholder;
  17828. // 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.
  17829. p.dataSource = this;
  17830. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  17831. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  17832. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  17833. // But it's not the case for a ContentControl, the placeholder of UIElement Children (the content)
  17834. this._visualChildrenPlaceholder = this._contentPlaceholder;
  17835. };
  17836. ContentControl.prototype._buildContentUIElement = function () {
  17837. var c = this._content;
  17838. this.__contentUIElement = null;
  17839. // Already a UIElement
  17840. if (c instanceof BABYLON.UIElement) {
  17841. this.__contentUIElement = c;
  17842. }
  17843. else if ((typeof c === "string") || (typeof c === "boolean") || (typeof c === "number")) {
  17844. var l = new BABYLON.Label({ parent: this, id: "Content of " + this.id });
  17845. var binding = new BABYLON.DataBinding();
  17846. binding.propertyPathName = "content";
  17847. binding.stringFormat = function (v) { return "" + v; };
  17848. binding.dataSource = this;
  17849. l.createDataBinding(BABYLON.Label.textProperty, binding);
  17850. this.__contentUIElement = l;
  17851. }
  17852. else {
  17853. }
  17854. if (this.__contentUIElement) {
  17855. this.__contentUIElement._patchUIElement(this.ownerWindow, this);
  17856. }
  17857. };
  17858. ContentControl.prototype._getChildren = function () {
  17859. var children = new Array();
  17860. if (this.content) {
  17861. children.push(this._contentUIElement);
  17862. }
  17863. return children;
  17864. };
  17865. return ContentControl;
  17866. }(BABYLON.Control));
  17867. ContentControl.CONTENTCONTROL_PROPCOUNT = BABYLON.Control.CONTROL_PROPCOUNT + 2;
  17868. __decorate([
  17869. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return ContentControl_1.contentProperty = pi; })
  17870. ], ContentControl.prototype, "content", null);
  17871. ContentControl = ContentControl_1 = __decorate([
  17872. BABYLON.className("ContentControl", "BABYLON")
  17873. ], ContentControl);
  17874. BABYLON.ContentControl = ContentControl;
  17875. var ContentControl_1;
  17876. })(BABYLON || (BABYLON = {}));
  17877. var __extends = (this && this.__extends) || function (d, b) {
  17878. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17879. function __() { this.constructor = d; }
  17880. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17881. };
  17882. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17883. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17884. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17885. 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;
  17886. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17887. };
  17888. var BABYLON;
  17889. (function (BABYLON) {
  17890. var FocusScopeData = (function () {
  17891. function FocusScopeData(focusScope) {
  17892. this.focusScope = focusScope;
  17893. this.focusedElement = null;
  17894. }
  17895. return FocusScopeData;
  17896. }());
  17897. var FocusManager = (function () {
  17898. function FocusManager() {
  17899. this._focusScopes = new BABYLON.StringDictionary();
  17900. this._rootScope = new FocusScopeData(null);
  17901. this._activeScope = null;
  17902. }
  17903. FocusManager.prototype.setFocusOn = function (el, focusScope) {
  17904. var fsd = (focusScope != null) ? this._focusScopes.getOrAddWithFactory(focusScope.uid, function (k) { return new FocusScopeData(focusScope); }) : this._rootScope;
  17905. if (fsd.focusedElement !== el) {
  17906. // Remove focus from current
  17907. if (fsd.focusedElement) {
  17908. fsd.focusedElement.isFocused = false;
  17909. }
  17910. fsd.focusedElement = el;
  17911. }
  17912. if (this._activeScope !== fsd) {
  17913. this._activeScope = fsd;
  17914. }
  17915. };
  17916. return FocusManager;
  17917. }());
  17918. BABYLON.FocusManager = FocusManager;
  17919. var GUISceneData = (function () {
  17920. function GUISceneData(scene) {
  17921. this.scene = scene;
  17922. this.screenSpaceCanvas = new BABYLON.ScreenSpaceCanvas2D(scene, { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE });
  17923. this.focusManager = new FocusManager();
  17924. }
  17925. return GUISceneData;
  17926. }());
  17927. var Window = Window_1 = (function (_super) {
  17928. __extends(Window, _super);
  17929. function Window(scene, settings) {
  17930. var _this = this;
  17931. if (!settings) {
  17932. settings = {};
  17933. }
  17934. _this = _super.call(this, settings) || this;
  17935. // Per default a Window is focus scope
  17936. _this.isFocusScope = true;
  17937. _this.isActive = false;
  17938. if (!_this._UIElementVisualToBuildList) {
  17939. _this._UIElementVisualToBuildList = new Array();
  17940. }
  17941. // Patch the owner and also the parent property through the whole tree
  17942. _this._patchUIElement(_this, null);
  17943. // Screen Space UI
  17944. if (!settings.worldPosition && !settings.worldRotation) {
  17945. _this._sceneData = Window_1.getSceneData(scene);
  17946. _this._canvas = _this._sceneData.screenSpaceCanvas;
  17947. _this._isWorldSpaceCanvas = false;
  17948. _this._left = (settings.left != null) ? settings.left : 0;
  17949. _this._bottom = (settings.bottom != null) ? settings.bottom : 0;
  17950. }
  17951. else {
  17952. var w = (settings.width == null) ? 100 : settings.width;
  17953. var h = (settings.height == null) ? 100 : settings.height;
  17954. var wpos = (settings.worldPosition == null) ? BABYLON.Vector3.Zero() : settings.worldPosition;
  17955. var wrot = (settings.worldRotation == null) ? BABYLON.Quaternion.Identity() : settings.worldRotation;
  17956. _this._canvas = new BABYLON.WorldSpaceCanvas2D(scene, new BABYLON.Size(w, h), { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE, worldPosition: wpos, worldRotation: wrot });
  17957. _this._isWorldSpaceCanvas = true;
  17958. }
  17959. _this._renderObserver = _this._canvas.renderObservable.add(function (e, s) { return _this._canvasPreRender(); }, BABYLON.Canvas2D.RENDEROBSERVABLE_PRE);
  17960. _this._disposeObserver = _this._canvas.disposeObservable.add(function (e, s) { return _this._canvasDisposed(); });
  17961. _this._canvas.propertyChanged.add(function (e, s) {
  17962. if (e.propertyName === "overPrim") {
  17963. _this._overPrimChanged(e.oldValue, e.newValue);
  17964. }
  17965. });
  17966. _this._mouseOverUIElement = null;
  17967. return _this;
  17968. }
  17969. Object.defineProperty(Window.prototype, "canvas", {
  17970. get: function () {
  17971. return this._canvas;
  17972. },
  17973. enumerable: true,
  17974. configurable: true
  17975. });
  17976. Object.defineProperty(Window.prototype, "left", {
  17977. get: function () {
  17978. return this._left;
  17979. },
  17980. set: function (value) {
  17981. var old = new BABYLON.Vector2(this._left, this._bottom);
  17982. this._left = value;
  17983. this.onPropertyChanged("_position", old, this._position);
  17984. },
  17985. enumerable: true,
  17986. configurable: true
  17987. });
  17988. Object.defineProperty(Window.prototype, "bottom", {
  17989. get: function () {
  17990. return this._bottom;
  17991. },
  17992. set: function (value) {
  17993. var old = new BABYLON.Vector2(this._left, this._bottom);
  17994. this._bottom = value;
  17995. this.onPropertyChanged("_position", old, this._position);
  17996. },
  17997. enumerable: true,
  17998. configurable: true
  17999. });
  18000. Object.defineProperty(Window.prototype, "position", {
  18001. get: function () {
  18002. return this._position;
  18003. },
  18004. set: function (value) {
  18005. this._left = value.x;
  18006. this._bottom = value.y;
  18007. },
  18008. enumerable: true,
  18009. configurable: true
  18010. });
  18011. Object.defineProperty(Window.prototype, "isActive", {
  18012. get: function () {
  18013. return this._isActive;
  18014. },
  18015. set: function (value) {
  18016. this._isActive = value;
  18017. },
  18018. enumerable: true,
  18019. configurable: true
  18020. });
  18021. Object.defineProperty(Window.prototype, "focusManager", {
  18022. get: function () {
  18023. return this._sceneData.focusManager;
  18024. },
  18025. enumerable: true,
  18026. configurable: true
  18027. });
  18028. Object.defineProperty(Window.prototype, "_position", {
  18029. get: function () {
  18030. return new BABYLON.Vector2(this.left, this.bottom);
  18031. },
  18032. enumerable: true,
  18033. configurable: true
  18034. });
  18035. Window.prototype.createVisualTree = function () {
  18036. _super.prototype.createVisualTree.call(this);
  18037. var p = this._visualPlaceholder;
  18038. p.createSimpleDataBinding(BABYLON.Group2D.positionProperty, "position");
  18039. };
  18040. Window.prototype._registerVisualToBuild = function (uiel) {
  18041. if (uiel._isFlagSet(BABYLON.UIElement.flagVisualToBuild)) {
  18042. return;
  18043. }
  18044. if (!this._UIElementVisualToBuildList) {
  18045. this._UIElementVisualToBuildList = new Array();
  18046. }
  18047. this._UIElementVisualToBuildList.push(uiel);
  18048. uiel._setFlags(BABYLON.UIElement.flagVisualToBuild);
  18049. };
  18050. Window.prototype._overPrimChanged = function (oldPrim, newPrim) {
  18051. var curOverEl = this._mouseOverUIElement;
  18052. var newOverEl = null;
  18053. var curGroup = newPrim ? newPrim.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  18054. while (curGroup) {
  18055. var uiel = curGroup.getExternalData("_GUIOwnerElement_");
  18056. if (uiel) {
  18057. newOverEl = uiel;
  18058. break;
  18059. }
  18060. curGroup = curGroup.parent ? curGroup.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  18061. }
  18062. if (curOverEl === newOverEl) {
  18063. return;
  18064. }
  18065. if (curOverEl) {
  18066. curOverEl.isMouseOver = false;
  18067. }
  18068. if (newOverEl) {
  18069. newOverEl.isMouseOver = true;
  18070. }
  18071. this._mouseOverUIElement = newOverEl;
  18072. };
  18073. Window.prototype._canvasPreRender = function () {
  18074. // Check if we have visual to create
  18075. if (this._UIElementVisualToBuildList.length > 0) {
  18076. // Sort the UI Element to get the highest (so lowest hierarchy depth) in the hierarchy tree first
  18077. var sortedElementList = this._UIElementVisualToBuildList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  18078. for (var _i = 0, sortedElementList_1 = sortedElementList; _i < sortedElementList_1.length; _i++) {
  18079. var el = sortedElementList_1[_i];
  18080. el._createVisualTree();
  18081. }
  18082. this._UIElementVisualToBuildList.splice(0);
  18083. }
  18084. };
  18085. Window.prototype._canvasDisposed = function () {
  18086. this._canvas.disposeObservable.remove(this._disposeObserver);
  18087. this._canvas.renderObservable.remove(this._renderObserver);
  18088. };
  18089. Window.getSceneData = function (scene) {
  18090. return Window_1._sceneData.getOrAddWithFactory(scene.uid, function (k) { return new GUISceneData(scene); });
  18091. };
  18092. return Window;
  18093. }(BABYLON.ContentControl));
  18094. Window.WINDOW_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 4;
  18095. Window._sceneData = new BABYLON.StringDictionary();
  18096. __decorate([
  18097. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 0, function (pi) { return Window_1.leftProperty = pi; })
  18098. ], Window.prototype, "left", null);
  18099. __decorate([
  18100. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 1, function (pi) { return Window_1.bottomProperty = pi; })
  18101. ], Window.prototype, "bottom", null);
  18102. __decorate([
  18103. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 2, function (pi) { return Window_1.positionProperty = pi; })
  18104. ], Window.prototype, "position", null);
  18105. __decorate([
  18106. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3, function (pi) { return Window_1.isActiveProperty = pi; })
  18107. ], Window.prototype, "isActive", null);
  18108. Window = Window_1 = __decorate([
  18109. BABYLON.className("Window", "BABYLON")
  18110. ], Window);
  18111. BABYLON.Window = Window;
  18112. var DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = (function (_super) {
  18113. __extends(DefaultWindowRenderingTemplate, _super);
  18114. function DefaultWindowRenderingTemplate() {
  18115. return _super !== null && _super.apply(this, arguments) || this;
  18116. }
  18117. DefaultWindowRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  18118. var r = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#808080FF" });
  18119. return { root: r, contentPlaceholder: r };
  18120. };
  18121. return DefaultWindowRenderingTemplate;
  18122. }(BABYLON.UIElementRenderingTemplateBase));
  18123. DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = __decorate([
  18124. BABYLON.registerWindowRenderingTemplate("BABYLON.Window", "Default", function () { return new DefaultWindowRenderingTemplate_1(); })
  18125. ], DefaultWindowRenderingTemplate);
  18126. BABYLON.DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate;
  18127. var Window_1, DefaultWindowRenderingTemplate_1;
  18128. })(BABYLON || (BABYLON = {}));
  18129. var __extends = (this && this.__extends) || function (d, b) {
  18130. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18131. function __() { this.constructor = d; }
  18132. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18133. };
  18134. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18135. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18136. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18137. 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;
  18138. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18139. };
  18140. var BABYLON;
  18141. (function (BABYLON) {
  18142. var Label = Label_1 = (function (_super) {
  18143. __extends(Label, _super);
  18144. function Label(settings) {
  18145. var _this = this;
  18146. if (!settings) {
  18147. settings = {};
  18148. }
  18149. _this = _super.call(this, settings) || this;
  18150. if (settings.text != null) {
  18151. _this.text = settings.text;
  18152. }
  18153. return _this;
  18154. }
  18155. Object.defineProperty(Label.prototype, "_position", {
  18156. get: function () {
  18157. return BABYLON.Vector2.Zero();
  18158. },
  18159. enumerable: true,
  18160. configurable: true
  18161. });
  18162. Label.prototype._getChildren = function () {
  18163. return Label_1._emptyArray;
  18164. };
  18165. Label.prototype.createVisualTree = function () {
  18166. _super.prototype.createVisualTree.call(this);
  18167. var p = this._visualChildrenPlaceholder;
  18168. };
  18169. Object.defineProperty(Label.prototype, "text", {
  18170. get: function () {
  18171. return this._text;
  18172. },
  18173. set: function (value) {
  18174. this._text = value;
  18175. },
  18176. enumerable: true,
  18177. configurable: true
  18178. });
  18179. return Label;
  18180. }(BABYLON.Control));
  18181. Label._emptyArray = new Array();
  18182. __decorate([
  18183. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return Label_1.textProperty = pi; })
  18184. ], Label.prototype, "text", null);
  18185. Label = Label_1 = __decorate([
  18186. BABYLON.className("Label", "BABYLON")
  18187. ], Label);
  18188. BABYLON.Label = Label;
  18189. var DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = (function (_super) {
  18190. __extends(DefaultLabelRenderingTemplate, _super);
  18191. function DefaultLabelRenderingTemplate() {
  18192. return _super !== null && _super.apply(this, arguments) || this;
  18193. }
  18194. DefaultLabelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  18195. var r = new BABYLON.Text2D("", { parent: visualPlaceholder });
  18196. r.createSimpleDataBinding(BABYLON.Text2D.textProperty, "text");
  18197. r.dataSource = owner;
  18198. return { root: r, contentPlaceholder: r };
  18199. };
  18200. return DefaultLabelRenderingTemplate;
  18201. }(BABYLON.UIElementRenderingTemplateBase));
  18202. DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = __decorate([
  18203. BABYLON.registerWindowRenderingTemplate("BABYLON.Label", "Default", function () { return new DefaultLabelRenderingTemplate_1(); })
  18204. ], DefaultLabelRenderingTemplate);
  18205. BABYLON.DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate;
  18206. var Label_1, DefaultLabelRenderingTemplate_1;
  18207. })(BABYLON || (BABYLON = {}));
  18208. var __extends = (this && this.__extends) || function (d, b) {
  18209. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18210. function __() { this.constructor = d; }
  18211. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18212. };
  18213. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18214. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18215. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18216. 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;
  18217. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18218. };
  18219. var BABYLON;
  18220. (function (BABYLON) {
  18221. var Button = Button_1 = (function (_super) {
  18222. __extends(Button, _super);
  18223. function Button(settings) {
  18224. var _this = this;
  18225. if (!settings) {
  18226. settings = {};
  18227. }
  18228. _this = _super.call(this, settings) || this;
  18229. if (settings.paddingAlignment == null) {
  18230. _this.paddingAlignment.horizontal = BABYLON.PrimitiveAlignment.AlignCenter;
  18231. _this.paddingAlignment.vertical = BABYLON.PrimitiveAlignment.AlignCenter;
  18232. }
  18233. _this._normalStateBackground = new BABYLON.ObservableStringDictionary(false);
  18234. _this._normalStateBorder = new BABYLON.ObservableStringDictionary(false);
  18235. _this._defaultStateBackground = new BABYLON.ObservableStringDictionary(false);
  18236. _this._defaultStateBorder = new BABYLON.ObservableStringDictionary(false);
  18237. _this._normalStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#337AB7FF"));
  18238. _this._normalStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#7BA9D0FF"));
  18239. _this._normalStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#286090FF"));
  18240. _this._normalStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#1E496EFF"));
  18241. _this._normalStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E6DA4FF"));
  18242. _this._normalStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#77A0C4FF"));
  18243. _this._normalStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#204D74FF"));
  18244. _this._normalStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E5D9EFF"));
  18245. _this._defaultStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  18246. _this._defaultStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  18247. _this._defaultStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#E6E6E6FF"));
  18248. _this._defaultStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#D4D4D4FF"));
  18249. _this._defaultStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#CCCCCCFF"));
  18250. _this._defaultStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#DEDEDEFF"));
  18251. _this._defaultStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#ADADADFF"));
  18252. _this._defaultStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#6C8EC5FF"));
  18253. return _this;
  18254. }
  18255. Object.defineProperty(Button, "pushedState", {
  18256. get: function () {
  18257. return Button_1._pushedState;
  18258. },
  18259. enumerable: true,
  18260. configurable: true
  18261. });
  18262. Object.defineProperty(Button.prototype, "isPushed", {
  18263. get: function () {
  18264. return this._isPushed;
  18265. },
  18266. set: function (value) {
  18267. this._isPushed = value;
  18268. },
  18269. enumerable: true,
  18270. configurable: true
  18271. });
  18272. Object.defineProperty(Button.prototype, "isDefault", {
  18273. get: function () {
  18274. return this._isDefault;
  18275. },
  18276. set: function (value) {
  18277. this._isDefault = value;
  18278. },
  18279. enumerable: true,
  18280. configurable: true
  18281. });
  18282. Object.defineProperty(Button.prototype, "isOutline", {
  18283. get: function () {
  18284. return this._isOutline;
  18285. },
  18286. set: function (value) {
  18287. this._isOutline = value;
  18288. },
  18289. enumerable: true,
  18290. configurable: true
  18291. });
  18292. Object.defineProperty(Button.prototype, "clickObservable", {
  18293. get: function () {
  18294. if (!this._clickObservable) {
  18295. this._clickObservable = new BABYLON.Observable();
  18296. }
  18297. return this._clickObservable;
  18298. },
  18299. enumerable: true,
  18300. configurable: true
  18301. });
  18302. Button.prototype._raiseClick = function () {
  18303. if (this._clickObservable && this._clickObservable.hasObservers()) {
  18304. this._clickObservable.notifyObservers(this);
  18305. }
  18306. };
  18307. Button.prototype.createVisualTree = function () {
  18308. var _this = this;
  18309. _super.prototype.createVisualTree.call(this);
  18310. var p = this._visualPlaceholder;
  18311. p.pointerEventObservable.add(function (e, s) {
  18312. // check if input must be discarded
  18313. if (!_this.isVisible || !_this.isEnabled) {
  18314. return;
  18315. }
  18316. // We reject an event coming from the placeholder because it means it's on an empty spot, so it's not valid.
  18317. if (e.relatedTarget === _this._visualPlaceholder) {
  18318. return;
  18319. }
  18320. if (s.mask === BABYLON.PrimitivePointerInfo.PointerUp) {
  18321. _this._raiseClick();
  18322. _this.isPushed = false;
  18323. }
  18324. else if (s.mask === BABYLON.PrimitivePointerInfo.PointerDown) {
  18325. _this.isPushed = true;
  18326. _this.isFocused = true;
  18327. }
  18328. }, BABYLON.PrimitivePointerInfo.PointerUp | BABYLON.PrimitivePointerInfo.PointerDown);
  18329. };
  18330. Object.defineProperty(Button.prototype, "normalStateBackground", {
  18331. get: function () {
  18332. return this._normalStateBackground;
  18333. },
  18334. enumerable: true,
  18335. configurable: true
  18336. });
  18337. Object.defineProperty(Button.prototype, "defaultStateBackground", {
  18338. get: function () {
  18339. return this._defaultStateBackground;
  18340. },
  18341. enumerable: true,
  18342. configurable: true
  18343. });
  18344. Object.defineProperty(Button.prototype, "normalStateBorder", {
  18345. get: function () {
  18346. return this._normalStateBorder;
  18347. },
  18348. enumerable: true,
  18349. configurable: true
  18350. });
  18351. Object.defineProperty(Button.prototype, "defaultStateBorder", {
  18352. get: function () {
  18353. return this._defaultStateBorder;
  18354. },
  18355. enumerable: true,
  18356. configurable: true
  18357. });
  18358. return Button;
  18359. }(BABYLON.ContentControl));
  18360. Button.BUTTON_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3;
  18361. Button._pushedState = "Pushed";
  18362. __decorate([
  18363. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 0, function (pi) { return Button_1.isPushedProperty = pi; })
  18364. ], Button.prototype, "isPushed", null);
  18365. __decorate([
  18366. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 1, function (pi) { return Button_1.isDefaultProperty = pi; })
  18367. ], Button.prototype, "isDefault", null);
  18368. __decorate([
  18369. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 2, function (pi) { return Button_1.isOutlineProperty = pi; })
  18370. ], Button.prototype, "isOutline", null);
  18371. Button = Button_1 = __decorate([
  18372. BABYLON.className("Button", "BABYLON")
  18373. ], Button);
  18374. BABYLON.Button = Button;
  18375. var DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = (function (_super) {
  18376. __extends(DefaultButtonRenderingTemplate, _super);
  18377. function DefaultButtonRenderingTemplate() {
  18378. return _super !== null && _super.apply(this, arguments) || this;
  18379. }
  18380. DefaultButtonRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  18381. this._rect = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#FF8080FF", border: "#FF8080FF", roundRadius: 10, borderThickness: 2 });
  18382. this.stateChange();
  18383. return { root: this._rect, contentPlaceholder: this._rect };
  18384. };
  18385. DefaultButtonRenderingTemplate.prototype.attach = function (owner) {
  18386. var _this = this;
  18387. _super.prototype.attach.call(this, owner);
  18388. this.owner.propertyChanged.add(function (e, s) { return _this.stateChange(); }, BABYLON.UIElement.isEnabledProperty.flagId |
  18389. BABYLON.UIElement.isFocusedProperty.flagId |
  18390. BABYLON.UIElement.isMouseOverProperty.flagId |
  18391. Button.isDefaultProperty.flagId |
  18392. Button.isOutlineProperty.flagId |
  18393. Button.isPushedProperty.flagId);
  18394. // Register for brush change and update the Visual
  18395. var button = owner;
  18396. button.normalStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18397. button.normalStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18398. button.defaultStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18399. button.defaultStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18400. };
  18401. DefaultButtonRenderingTemplate.prototype.stateChange = function () {
  18402. //console.log("state changed");
  18403. var b = this.owner;
  18404. var state = BABYLON.UIElement.enabledState;
  18405. var bg = b.isDefault ? b.defaultStateBackground.get(state) : b.normalStateBackground.get(state);
  18406. var bd = b.isDefault ? b.defaultStateBorder.get(state) : b.normalStateBorder.get(state);
  18407. if (b.isPushed) {
  18408. state = Button.pushedState;
  18409. if (b.isDefault) {
  18410. bg = b.defaultStateBackground.get(state);
  18411. bd = b.defaultStateBorder.get(state);
  18412. }
  18413. else {
  18414. bg = b.normalStateBackground.get(state);
  18415. bd = b.normalStateBorder.get(state);
  18416. }
  18417. }
  18418. else if (b.isMouseOver) {
  18419. state = BABYLON.UIElement.mouseOverState;
  18420. if (b.isDefault) {
  18421. bg = b.defaultStateBackground.get(state);
  18422. bd = b.defaultStateBorder.get(state);
  18423. }
  18424. else {
  18425. bg = b.normalStateBackground.get(state);
  18426. bd = b.normalStateBorder.get(state);
  18427. }
  18428. }
  18429. else if (!b.isEnabled) {
  18430. state = BABYLON.UIElement.disabledState;
  18431. if (b.isDefault) {
  18432. bg = b.defaultStateBackground.get(state);
  18433. bd = b.defaultStateBorder.get(state);
  18434. }
  18435. else {
  18436. bg = b.normalStateBackground.get(state);
  18437. bd = b.normalStateBorder.get(state);
  18438. }
  18439. }
  18440. this._rect.fill = bg;
  18441. this._rect.border = bd;
  18442. };
  18443. return DefaultButtonRenderingTemplate;
  18444. }(BABYLON.UIElementRenderingTemplateBase));
  18445. DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = __decorate([
  18446. BABYLON.registerWindowRenderingTemplate("BABYLON.Button", "Default", function () { return new DefaultButtonRenderingTemplate_1(); })
  18447. ], DefaultButtonRenderingTemplate);
  18448. BABYLON.DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate;
  18449. var Button_1, DefaultButtonRenderingTemplate_1;
  18450. })(BABYLON || (BABYLON = {}));