babylon.canvas2d.js 904 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386
  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,1.0);\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. /**
  2987. * The default Layout Engine, primitive are positioning into a Canvas, using their x/y coordinates.
  2988. * This layout must be used as a Singleton through the CanvasLayoutEngine.Singleton property.
  2989. */
  2990. function CanvasLayoutEngine() {
  2991. return _super !== null && _super.apply(this, arguments) || this;
  2992. }
  2993. // A very simple (no) layout computing...
  2994. // The Canvas and its direct children gets the Canvas' size as Layout Area
  2995. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  2996. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  2997. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  2998. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  2999. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3000. var child = _a[_i];
  3001. this._doUpdate(child);
  3002. }
  3003. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3004. }
  3005. };
  3006. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  3007. // Canvas ?
  3008. if (prim instanceof BABYLON.Canvas2D) {
  3009. prim.layoutArea = prim.actualSize; //.multiplyByFloats(prim.scaleX, prim.scaleY);
  3010. }
  3011. else if (prim.parent instanceof BABYLON.Canvas2D) {
  3012. prim.layoutArea = prim.owner.actualSize; //.multiplyByFloats(prim.owner.scaleX, prim.owner.scaleY);
  3013. }
  3014. else {
  3015. prim.layoutArea = prim.parent.contentArea;
  3016. }
  3017. };
  3018. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  3019. get: function () {
  3020. return true;
  3021. },
  3022. enumerable: true,
  3023. configurable: true
  3024. });
  3025. return CanvasLayoutEngine;
  3026. }(LayoutEngineBase));
  3027. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine_1();
  3028. CanvasLayoutEngine = CanvasLayoutEngine_1 = __decorate([
  3029. BABYLON.className("CanvasLayoutEngine", "BABYLON")
  3030. ], CanvasLayoutEngine);
  3031. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  3032. var StackPanelLayoutEngine = StackPanelLayoutEngine_1 = (function (_super) {
  3033. __extends(StackPanelLayoutEngine, _super);
  3034. function StackPanelLayoutEngine() {
  3035. var _this = _super.call(this) || this;
  3036. _this._isHorizontal = true;
  3037. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  3038. return _this;
  3039. }
  3040. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  3041. get: function () {
  3042. if (!StackPanelLayoutEngine_1._horizontal) {
  3043. StackPanelLayoutEngine_1._horizontal = new StackPanelLayoutEngine_1();
  3044. StackPanelLayoutEngine_1._horizontal.isHorizontal = true;
  3045. StackPanelLayoutEngine_1._horizontal.lock();
  3046. }
  3047. return StackPanelLayoutEngine_1._horizontal;
  3048. },
  3049. enumerable: true,
  3050. configurable: true
  3051. });
  3052. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  3053. get: function () {
  3054. if (!StackPanelLayoutEngine_1._vertical) {
  3055. StackPanelLayoutEngine_1._vertical = new StackPanelLayoutEngine_1();
  3056. StackPanelLayoutEngine_1._vertical.isHorizontal = false;
  3057. StackPanelLayoutEngine_1._vertical.lock();
  3058. }
  3059. return StackPanelLayoutEngine_1._vertical;
  3060. },
  3061. enumerable: true,
  3062. configurable: true
  3063. });
  3064. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  3065. get: function () {
  3066. return this._isHorizontal;
  3067. },
  3068. set: function (val) {
  3069. if (this.isLocked()) {
  3070. return;
  3071. }
  3072. this._isHorizontal = val;
  3073. },
  3074. enumerable: true,
  3075. configurable: true
  3076. });
  3077. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  3078. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3079. var x = 0;
  3080. var y = 0;
  3081. var h = this.isHorizontal;
  3082. var max = 0;
  3083. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3084. var child = _a[_i];
  3085. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3086. continue;
  3087. }
  3088. var layoutArea = void 0;
  3089. if (child._hasMargin) {
  3090. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, StackPanelLayoutEngine_1.dstOffset, StackPanelLayoutEngine_1.dstArea, true);
  3091. layoutArea = StackPanelLayoutEngine_1.dstArea.clone();
  3092. child.layoutArea = layoutArea;
  3093. }
  3094. else {
  3095. layoutArea = child.layoutArea;
  3096. child.margin.computeArea(child.actualSize, layoutArea);
  3097. }
  3098. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  3099. }
  3100. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  3101. var child = _c[_b];
  3102. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3103. continue;
  3104. }
  3105. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  3106. var layoutArea = child.layoutArea;
  3107. if (h) {
  3108. x += layoutArea.width;
  3109. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  3110. }
  3111. else {
  3112. y += layoutArea.height;
  3113. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  3114. }
  3115. }
  3116. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3117. }
  3118. };
  3119. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  3120. get: function () {
  3121. return false;
  3122. },
  3123. enumerable: true,
  3124. configurable: true
  3125. });
  3126. return StackPanelLayoutEngine;
  3127. }(LayoutEngineBase));
  3128. StackPanelLayoutEngine._horizontal = null;
  3129. StackPanelLayoutEngine._vertical = null;
  3130. StackPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  3131. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  3132. StackPanelLayoutEngine = StackPanelLayoutEngine_1 = __decorate([
  3133. BABYLON.className("StackPanelLayoutEngine", "BABYLON")
  3134. ], StackPanelLayoutEngine);
  3135. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  3136. var CanvasLayoutEngine_1, StackPanelLayoutEngine_1;
  3137. })(BABYLON || (BABYLON = {}));
  3138. //# sourceMappingURL=babylon.canvas2dLayoutEngine.js.map
  3139. var __extends = (this && this.__extends) || function (d, b) {
  3140. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3141. function __() { this.constructor = d; }
  3142. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3143. };
  3144. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3145. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3146. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  3147. 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;
  3148. return c > 3 && r && Object.defineProperty(target, key, r), r;
  3149. };
  3150. var BABYLON;
  3151. (function (BABYLON) {
  3152. /**
  3153. * Base class implementing the ILocable interface.
  3154. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  3155. */
  3156. var LockableBase = (function () {
  3157. function LockableBase() {
  3158. }
  3159. LockableBase.prototype.isLocked = function () {
  3160. return this._isLocked;
  3161. };
  3162. LockableBase.prototype.lock = function () {
  3163. if (this._isLocked) {
  3164. return true;
  3165. }
  3166. this.onLock();
  3167. this._isLocked = true;
  3168. return false;
  3169. };
  3170. /**
  3171. * Protected handler that will be called when the instance is about to be locked.
  3172. */
  3173. LockableBase.prototype.onLock = function () {
  3174. };
  3175. return LockableBase;
  3176. }());
  3177. BABYLON.LockableBase = LockableBase;
  3178. var SolidColorBrush2D = (function (_super) {
  3179. __extends(SolidColorBrush2D, _super);
  3180. function SolidColorBrush2D(color, lock) {
  3181. if (lock === void 0) { lock = false; }
  3182. var _this = _super.call(this) || this;
  3183. _this._color = color;
  3184. if (lock) {
  3185. {
  3186. _this.lock();
  3187. }
  3188. }
  3189. return _this;
  3190. }
  3191. /**
  3192. * Return true if the brush is transparent, false if it's totally opaque
  3193. */
  3194. SolidColorBrush2D.prototype.isTransparent = function () {
  3195. return this._color && this._color.a < 1.0;
  3196. };
  3197. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  3198. /**
  3199. * The color used by this instance to render
  3200. * @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.
  3201. */
  3202. get: function () {
  3203. return this._color;
  3204. },
  3205. set: function (value) {
  3206. if (this.isLocked()) {
  3207. return;
  3208. }
  3209. this._color = value;
  3210. },
  3211. enumerable: true,
  3212. configurable: true
  3213. });
  3214. /**
  3215. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  3216. */
  3217. SolidColorBrush2D.prototype.toString = function () {
  3218. return this._color.toHexString();
  3219. };
  3220. return SolidColorBrush2D;
  3221. }(LockableBase));
  3222. SolidColorBrush2D = __decorate([
  3223. BABYLON.className("SolidColorBrush2D", "BABYLON")
  3224. ], SolidColorBrush2D);
  3225. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  3226. var GradientColorBrush2D = (function (_super) {
  3227. __extends(GradientColorBrush2D, _super);
  3228. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  3229. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  3230. if (rotation === void 0) { rotation = 0; }
  3231. if (scale === void 0) { scale = 1; }
  3232. if (lock === void 0) { lock = false; }
  3233. var _this = _super.call(this) || this;
  3234. _this._color1 = color1;
  3235. _this._color2 = color2;
  3236. _this._translation = translation;
  3237. _this._rotation = rotation;
  3238. _this._scale = scale;
  3239. if (lock) {
  3240. _this.lock();
  3241. }
  3242. return _this;
  3243. }
  3244. /**
  3245. * Return true if the brush is transparent, false if it's totally opaque
  3246. */
  3247. GradientColorBrush2D.prototype.isTransparent = function () {
  3248. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  3249. };
  3250. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  3251. /**
  3252. * First color, the blend will start from this color
  3253. */
  3254. get: function () {
  3255. return this._color1;
  3256. },
  3257. set: function (value) {
  3258. if (this.isLocked()) {
  3259. return;
  3260. }
  3261. this._color1 = value;
  3262. },
  3263. enumerable: true,
  3264. configurable: true
  3265. });
  3266. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  3267. /**
  3268. * Second color, the blend will end to this color
  3269. */
  3270. get: function () {
  3271. return this._color2;
  3272. },
  3273. set: function (value) {
  3274. if (this.isLocked()) {
  3275. return;
  3276. }
  3277. this._color2 = value;
  3278. },
  3279. enumerable: true,
  3280. configurable: true
  3281. });
  3282. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  3283. /**
  3284. * Translation vector to apply on the blend
  3285. * Default is [0;0]
  3286. */
  3287. get: function () {
  3288. return this._translation;
  3289. },
  3290. set: function (value) {
  3291. if (this.isLocked()) {
  3292. return;
  3293. }
  3294. this._translation = value;
  3295. },
  3296. enumerable: true,
  3297. configurable: true
  3298. });
  3299. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  3300. /**
  3301. * Rotation in radian to apply to the brush
  3302. * Default direction of the brush is vertical, you can change this using this property.
  3303. * Default is 0.
  3304. */
  3305. get: function () {
  3306. return this._rotation;
  3307. },
  3308. set: function (value) {
  3309. if (this.isLocked()) {
  3310. return;
  3311. }
  3312. this._rotation = value;
  3313. },
  3314. enumerable: true,
  3315. configurable: true
  3316. });
  3317. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  3318. /**
  3319. * Scale factor to apply to the gradient.
  3320. * Default is 1: no scale.
  3321. */
  3322. get: function () {
  3323. return this._scale;
  3324. },
  3325. set: function (value) {
  3326. if (this.isLocked()) {
  3327. return;
  3328. }
  3329. this._scale = value;
  3330. },
  3331. enumerable: true,
  3332. configurable: true
  3333. });
  3334. /**
  3335. * Return a string describing the brush
  3336. */
  3337. GradientColorBrush2D.prototype.toString = function () {
  3338. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  3339. };
  3340. /**
  3341. * Build a unique key string for the given parameters
  3342. */
  3343. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  3344. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  3345. };
  3346. return GradientColorBrush2D;
  3347. }(LockableBase));
  3348. GradientColorBrush2D = __decorate([
  3349. BABYLON.className("GradientColorBrush2D", "BABYLON")
  3350. ], GradientColorBrush2D);
  3351. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  3352. })(BABYLON || (BABYLON = {}));
  3353. //# sourceMappingURL=babylon.brushes2d.js.map
  3354. var __extends = (this && this.__extends) || function (d, b) {
  3355. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3356. function __() { this.constructor = d; }
  3357. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3358. };
  3359. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3360. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3361. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  3362. 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;
  3363. return c > 3 && r && Object.defineProperty(target, key, r), r;
  3364. };
  3365. var BABYLON;
  3366. (function (BABYLON) {
  3367. var Prim2DClassInfo = (function () {
  3368. function Prim2DClassInfo() {
  3369. }
  3370. return Prim2DClassInfo;
  3371. }());
  3372. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  3373. var Prim2DPropInfo = (function () {
  3374. function Prim2DPropInfo() {
  3375. }
  3376. return Prim2DPropInfo;
  3377. }());
  3378. Prim2DPropInfo.PROPKIND_MODEL = 1;
  3379. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  3380. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  3381. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  3382. var ClassTreeInfo = (function () {
  3383. function ClassTreeInfo(baseClass, type, classContentFactory) {
  3384. this._baseClass = baseClass;
  3385. this._type = type;
  3386. this._subClasses = new Array();
  3387. this._levelContent = new BABYLON.StringDictionary();
  3388. this._classContentFactory = classContentFactory;
  3389. }
  3390. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  3391. get: function () {
  3392. if (!this._classContent) {
  3393. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  3394. }
  3395. return this._classContent;
  3396. },
  3397. enumerable: true,
  3398. configurable: true
  3399. });
  3400. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  3401. get: function () {
  3402. return this._type;
  3403. },
  3404. enumerable: true,
  3405. configurable: true
  3406. });
  3407. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  3408. get: function () {
  3409. return this._levelContent;
  3410. },
  3411. enumerable: true,
  3412. configurable: true
  3413. });
  3414. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  3415. get: function () {
  3416. if (!this._fullContent) {
  3417. var dic_1 = new BABYLON.StringDictionary();
  3418. var curLevel = this;
  3419. while (curLevel) {
  3420. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  3421. curLevel = curLevel._baseClass;
  3422. }
  3423. this._fullContent = dic_1;
  3424. }
  3425. return this._fullContent;
  3426. },
  3427. enumerable: true,
  3428. configurable: true
  3429. });
  3430. ClassTreeInfo.prototype.getLevelOf = function (type) {
  3431. // Are we already there?
  3432. if (type === this._type) {
  3433. return this;
  3434. }
  3435. var baseProto = Object.getPrototypeOf(type);
  3436. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  3437. if (!curProtoContent) {
  3438. this.getLevelOf(baseProto);
  3439. }
  3440. return this.getOrAddType(baseProto, type);
  3441. };
  3442. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  3443. // Are we at the level corresponding to the baseType?
  3444. // If so, get or add the level we're looking for
  3445. if (baseType === this._type) {
  3446. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  3447. var subType = _a[_i];
  3448. if (subType.type === type) {
  3449. return subType.node;
  3450. }
  3451. }
  3452. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  3453. var info = { type: type, node: node };
  3454. this._subClasses.push(info);
  3455. return info.node;
  3456. }
  3457. // Recurse down to keep looking for the node corresponding to the baseTypeName
  3458. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  3459. var subType = _c[_b];
  3460. var info = subType.node.getOrAddType(baseType, type);
  3461. if (info) {
  3462. return info;
  3463. }
  3464. }
  3465. return null;
  3466. };
  3467. ClassTreeInfo.get = function (type) {
  3468. var dic = type["__classTreeInfo"];
  3469. if (!dic) {
  3470. return null;
  3471. }
  3472. return dic.getLevelOf(type);
  3473. };
  3474. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  3475. var dic = type["__classTreeInfo"];
  3476. if (!dic) {
  3477. dic = new ClassTreeInfo(null, type, classContentFactory);
  3478. type["__classTreeInfo"] = dic;
  3479. }
  3480. return dic;
  3481. };
  3482. return ClassTreeInfo;
  3483. }());
  3484. BABYLON.ClassTreeInfo = ClassTreeInfo;
  3485. var DataBinding = DataBinding_1 = (function () {
  3486. function DataBinding() {
  3487. this._converter = null;
  3488. this._mode = DataBinding_1.MODE_DEFAULT;
  3489. this._uiElementId = null;
  3490. this._dataSource = null;
  3491. this._currentDataSource = null;
  3492. this._propertyPathName = null;
  3493. this._stringFormat = null;
  3494. this._updateSourceTrigger = DataBinding_1.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  3495. this._boundTo = null;
  3496. this._owner = null;
  3497. this._updateCounter = 0;
  3498. }
  3499. Object.defineProperty(DataBinding.prototype, "converter", {
  3500. /**
  3501. * Provide a callback that will convert the value obtained by the Data Binding to the type of the SmartProperty it's bound to.
  3502. * If no value are set, then it's assumed that the sourceValue is of the same type as the SmartProperty's one.
  3503. * 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.
  3504. * @param sourceValue the source object retrieve by the Data Binding mechanism
  3505. * @returns the object of a compatible type with the SmartProperty it's bound to
  3506. */
  3507. get: function () {
  3508. return this._converter;
  3509. },
  3510. set: function (value) {
  3511. if (this._converter === value) {
  3512. return;
  3513. }
  3514. this._converter = value;
  3515. },
  3516. enumerable: true,
  3517. configurable: true
  3518. });
  3519. Object.defineProperty(DataBinding.prototype, "mode", {
  3520. /**
  3521. * 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
  3522. */
  3523. get: function () {
  3524. if (this._mode === DataBinding_1.MODE_DEFAULT) {
  3525. return this._boundTo.bindingMode;
  3526. }
  3527. return this._mode;
  3528. },
  3529. set: function (value) {
  3530. if (this._mode === value) {
  3531. return;
  3532. }
  3533. this._mode = value;
  3534. },
  3535. enumerable: true,
  3536. configurable: true
  3537. });
  3538. Object.defineProperty(DataBinding.prototype, "uiElementId", {
  3539. /**
  3540. * You can override the Data Source object with this member which is the Id of a uiElement existing in the UI Logical tree.
  3541. * If not set and source no set too, then the dataSource property will be used.
  3542. */
  3543. get: function () {
  3544. return this._uiElementId;
  3545. },
  3546. set: function (value) {
  3547. if (this._uiElementId === value) {
  3548. return;
  3549. }
  3550. this._uiElementId = value;
  3551. },
  3552. enumerable: true,
  3553. configurable: true
  3554. });
  3555. Object.defineProperty(DataBinding.prototype, "dataSource", {
  3556. /**
  3557. * You can override the Data Source object with this member which is the source object to use directly.
  3558. * If not set and uiElement no set too, then the dataSource property of the SmartPropertyBase object will be used.
  3559. */
  3560. get: function () {
  3561. return this._dataSource;
  3562. },
  3563. set: function (value) {
  3564. if (this._dataSource === value) {
  3565. return;
  3566. }
  3567. this._dataSource = value;
  3568. },
  3569. enumerable: true,
  3570. configurable: true
  3571. });
  3572. Object.defineProperty(DataBinding.prototype, "propertyPathName", {
  3573. /**
  3574. * The path & name of the property to get from the source object.
  3575. * 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.
  3576. * If nothing is set then the source object will be used.
  3577. * 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.
  3578. * 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.
  3579. */
  3580. get: function () {
  3581. return this._propertyPathName;
  3582. },
  3583. set: function (value) {
  3584. if (this._propertyPathName === value) {
  3585. return;
  3586. }
  3587. if (this._owner) {
  3588. }
  3589. this._propertyPathName = value;
  3590. if (this._owner) {
  3591. }
  3592. },
  3593. enumerable: true,
  3594. configurable: true
  3595. });
  3596. Object.defineProperty(DataBinding.prototype, "stringFormat", {
  3597. /**
  3598. * 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}`
  3599. */
  3600. get: function () {
  3601. return this._stringFormat;
  3602. },
  3603. set: function (value) {
  3604. if (this._stringFormat === value) {
  3605. return;
  3606. }
  3607. this._stringFormat = value;
  3608. },
  3609. enumerable: true,
  3610. configurable: true
  3611. });
  3612. Object.defineProperty(DataBinding.prototype, "updateSourceTrigger", {
  3613. /**
  3614. * 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.
  3615. */
  3616. get: function () {
  3617. return this._updateSourceTrigger;
  3618. },
  3619. set: function (value) {
  3620. if (this._updateSourceTrigger === value) {
  3621. return;
  3622. }
  3623. this._updateSourceTrigger = value;
  3624. },
  3625. enumerable: true,
  3626. configurable: true
  3627. });
  3628. DataBinding.prototype.canUpdateTarget = function (resetUpdateCounter) {
  3629. if (resetUpdateCounter) {
  3630. this._updateCounter = 0;
  3631. }
  3632. var mode = this.mode;
  3633. if (mode === DataBinding_1.MODE_ONETIME) {
  3634. return this._updateCounter === 0;
  3635. }
  3636. if (mode === DataBinding_1.MODE_ONEWAYTOSOURCE) {
  3637. return false;
  3638. }
  3639. return true;
  3640. };
  3641. DataBinding.prototype.updateTarget = function () {
  3642. var value = this._getActualDataSource();
  3643. var properties = this.propertyPathName.split(".");
  3644. for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
  3645. var propertyName = properties_1[_i];
  3646. value = value[propertyName];
  3647. }
  3648. this._storeBoundValue(this._owner, value);
  3649. };
  3650. DataBinding.prototype._storeBoundValue = function (watcher, value) {
  3651. if ((++this._updateCounter > 1) && (this.mode === DataBinding_1.MODE_ONETIME)) {
  3652. return;
  3653. }
  3654. var newValue = value;
  3655. if (this._converter) {
  3656. newValue = this._converter(value);
  3657. }
  3658. if (this._stringFormat) {
  3659. newValue = this._stringFormat(newValue);
  3660. }
  3661. watcher[this._boundTo.name] = newValue;
  3662. };
  3663. DataBinding.prototype._getActualDataSource = function () {
  3664. if (this.dataSource) {
  3665. return this.dataSource;
  3666. }
  3667. if (this.uiElementId) {
  3668. // TODO Find UIElement
  3669. return null;
  3670. }
  3671. return this._owner.dataSource;
  3672. };
  3673. DataBinding.prototype._registerDataSource = function (updateTarget) {
  3674. var ds = this._getActualDataSource();
  3675. if (ds === this._currentDataSource) {
  3676. return;
  3677. }
  3678. if (this._currentDataSource) {
  3679. BindingHelper.unregisterDataSource(this._currentDataSource, this, 0);
  3680. }
  3681. if (ds) {
  3682. BindingHelper.registerDataSource(ds, this);
  3683. if (updateTarget && this.canUpdateTarget(true)) {
  3684. this.updateTarget();
  3685. }
  3686. }
  3687. this._currentDataSource = ds;
  3688. };
  3689. DataBinding.prototype._unregisterDataSource = function () {
  3690. var ds = this._getActualDataSource();
  3691. if (ds) {
  3692. BindingHelper.unregisterDataSource(ds, this, 0);
  3693. }
  3694. };
  3695. return DataBinding;
  3696. }());
  3697. /**
  3698. * Use the mode specified in the SmartProperty declaration
  3699. */
  3700. DataBinding.MODE_DEFAULT = 1;
  3701. /**
  3702. * Update the binding target only once when the Smart Property's value is first accessed
  3703. */
  3704. DataBinding.MODE_ONETIME = 2;
  3705. /**
  3706. * Update the smart property when the source changes.
  3707. * The source won't be updated if the smart property value is set.
  3708. */
  3709. DataBinding.MODE_ONEWAY = 3;
  3710. /**
  3711. * Only update the source when the target's data is changing.
  3712. */
  3713. DataBinding.MODE_ONEWAYTOSOURCE = 4;
  3714. /**
  3715. * Update the bind target when the source changes and update the source when the Smart Property value is set.
  3716. */
  3717. DataBinding.MODE_TWOWAY = 5;
  3718. /**
  3719. * Use the Update Source Trigger defined in the SmartProperty declaration
  3720. */
  3721. DataBinding.UPDATESOURCETRIGGER_DEFAULT = 1;
  3722. /**
  3723. * Update the source as soon as the Smart Property has a value change
  3724. */
  3725. DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED = 2;
  3726. /**
  3727. * Update the source when the binding target loses focus
  3728. */
  3729. DataBinding.UPDATESOURCETRIGGER_LOSTFOCUS = 3;
  3730. /**
  3731. * Update the source will be made by explicitly calling the UpdateFromDataSource method
  3732. */
  3733. DataBinding.UPDATESOURCETRIGGER_EXPLICIT = 4;
  3734. DataBinding = DataBinding_1 = __decorate([
  3735. BABYLON.className("DataBinding", "BABYLON")
  3736. ], DataBinding);
  3737. BABYLON.DataBinding = DataBinding;
  3738. var SmartPropertyBase = SmartPropertyBase_1 = (function (_super) {
  3739. __extends(SmartPropertyBase, _super);
  3740. function SmartPropertyBase() {
  3741. var _this = _super.call(this) || this;
  3742. _this._dataSource = null;
  3743. _this._dataSourceObserver = null;
  3744. _this._instanceDirtyFlags = 0;
  3745. _this._isDisposed = false;
  3746. _this._bindings = null;
  3747. _this._hasBinding = 0;
  3748. _this._bindingSourceChanged = 0;
  3749. _this._disposeObservable = null;
  3750. return _this;
  3751. }
  3752. Object.defineProperty(SmartPropertyBase.prototype, "disposeObservable", {
  3753. get: function () {
  3754. if (!this._disposeObservable) {
  3755. this._disposeObservable = new BABYLON.Observable();
  3756. }
  3757. return this._disposeObservable;
  3758. },
  3759. enumerable: true,
  3760. configurable: true
  3761. });
  3762. Object.defineProperty(SmartPropertyBase.prototype, "isDisposed", {
  3763. /**
  3764. * Check if the object is disposed or not.
  3765. * @returns true if the object is dispose, false otherwise.
  3766. */
  3767. get: function () {
  3768. return this._isDisposed;
  3769. },
  3770. enumerable: true,
  3771. configurable: true
  3772. });
  3773. /**
  3774. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  3775. * @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.
  3776. */
  3777. SmartPropertyBase.prototype.dispose = function () {
  3778. if (this.isDisposed) {
  3779. return false;
  3780. }
  3781. if (this._disposeObservable && this._disposeObservable.hasObservers()) {
  3782. this._disposeObservable.notifyObservers(this);
  3783. }
  3784. this._isDisposed = true;
  3785. return true;
  3786. };
  3787. /**
  3788. * Check if a given set of properties are dirty or not.
  3789. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  3790. * @return true if at least one property is dirty, false if none of them are.
  3791. */
  3792. SmartPropertyBase.prototype.checkPropertiesDirty = function (flags) {
  3793. return (this._instanceDirtyFlags & flags) !== 0;
  3794. };
  3795. /**
  3796. * Clear a given set of properties.
  3797. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  3798. * @return the new set of property still marked as dirty
  3799. */
  3800. SmartPropertyBase.prototype.clearPropertiesDirty = function (flags) {
  3801. this._instanceDirtyFlags &= ~flags;
  3802. return this._instanceDirtyFlags;
  3803. };
  3804. SmartPropertyBase.prototype._resetPropertiesDirty = function () {
  3805. this._instanceDirtyFlags = 0;
  3806. };
  3807. /**
  3808. * Add an externally attached data from its key.
  3809. * This method call will fail and return false, if such key already exists.
  3810. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  3811. * @param key the unique key that identifies the data
  3812. * @param data the data object to associate to the key for this Engine instance
  3813. * @return true if no such key were already present and the data was added successfully, false otherwise
  3814. */
  3815. SmartPropertyBase.prototype.addExternalData = function (key, data) {
  3816. if (!this._externalData) {
  3817. this._externalData = new BABYLON.StringDictionary();
  3818. }
  3819. return this._externalData.add(key, data);
  3820. };
  3821. /**
  3822. * Get an externally attached data from its key
  3823. * @param key the unique key that identifies the data
  3824. * @return the associated data, if present (can be null), or undefined if not present
  3825. */
  3826. SmartPropertyBase.prototype.getExternalData = function (key) {
  3827. if (!this._externalData) {
  3828. return null;
  3829. }
  3830. return this._externalData.get(key);
  3831. };
  3832. /**
  3833. * Get an externally attached data from its key, create it using a factory if it's not already present
  3834. * @param key the unique key that identifies the data
  3835. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  3836. * @return the associated data, can be null if the factory returned null.
  3837. */
  3838. SmartPropertyBase.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  3839. if (!this._externalData) {
  3840. this._externalData = new BABYLON.StringDictionary();
  3841. }
  3842. return this._externalData.getOrAddWithFactory(key, factory);
  3843. };
  3844. /**
  3845. * Remove an externally attached data from the Engine instance
  3846. * @param key the unique key that identifies the data
  3847. * @return true if the data was successfully removed, false if it doesn't exist
  3848. */
  3849. SmartPropertyBase.prototype.removeExternalData = function (key) {
  3850. if (!this._externalData) {
  3851. return false;
  3852. }
  3853. return this._externalData.remove(key);
  3854. };
  3855. SmartPropertyBase._hookProperty = function (propId, piStore, kind, settings) {
  3856. return function (target, propName, descriptor) {
  3857. if (!settings) {
  3858. settings = {};
  3859. }
  3860. var propInfo = SmartPropertyBase_1._createPropInfo(target, propName, propId, kind, settings);
  3861. if (piStore) {
  3862. piStore(propInfo);
  3863. }
  3864. var getter = descriptor.get, setter = descriptor.set;
  3865. var typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  3866. // Overload the property setter implementation to add our own logic
  3867. descriptor.set = function (val) {
  3868. if (!setter) {
  3869. throw Error("Property '" + propInfo.name + "' of type '" + BABYLON.Tools.getFullClassName(this) + "' has no setter defined but was invoked as if it had one.");
  3870. }
  3871. // check for disposed first, do nothing
  3872. if (this.isDisposed) {
  3873. return;
  3874. }
  3875. var curVal = getter.call(this);
  3876. if (SmartPropertyBase_1._checkUnchanged(curVal, val)) {
  3877. return;
  3878. }
  3879. // Cast the object we're working one
  3880. var prim = this;
  3881. // Change the value
  3882. setter.call(this, val);
  3883. // Notify change, dirty flags update
  3884. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  3885. };
  3886. };
  3887. };
  3888. SmartPropertyBase._createPropInfo = function (target, propName, propId, kind, settings) {
  3889. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  3890. var node = dic.getLevelOf(target);
  3891. var propInfo = node.levelContent.get(propId.toString());
  3892. if (propInfo) {
  3893. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  3894. }
  3895. // Create, setup and add the PropInfo object to our prop dictionary
  3896. propInfo = new Prim2DPropInfo();
  3897. propInfo.id = propId;
  3898. propInfo.flagId = Math.pow(2, propId);
  3899. propInfo.kind = kind;
  3900. propInfo.name = propName;
  3901. propInfo.bindingMode = (settings.bindingMode !== undefined) ? settings.bindingMode : DataBinding.MODE_TWOWAY;
  3902. propInfo.bindingUpdateSourceTrigger = (settings.bindingUpdateSourceTrigger !== undefined) ? settings.bindingUpdateSourceTrigger : DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  3903. propInfo.dirtyBoundingInfo = (settings.dirtyBoundingInfo !== undefined) ? settings.dirtyBoundingInfo : false;
  3904. propInfo.dirtyParentBoundingInfo = (settings.dirtyParentBoundingBox !== undefined) ? settings.dirtyParentBoundingBox : false;
  3905. propInfo.typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  3906. node.levelContent.add(propName, propInfo);
  3907. return propInfo;
  3908. };
  3909. Object.defineProperty(SmartPropertyBase.prototype, "propDic", {
  3910. /**
  3911. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  3912. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  3913. */
  3914. get: function () {
  3915. if (!this._propInfo) {
  3916. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  3917. if (!cti) {
  3918. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  3919. }
  3920. this._propInfo = cti.fullContent;
  3921. }
  3922. return this._propInfo;
  3923. },
  3924. enumerable: true,
  3925. configurable: true
  3926. });
  3927. SmartPropertyBase._checkUnchanged = function (curValue, newValue) {
  3928. // Nothing to nothing: nothing to do!
  3929. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  3930. return true;
  3931. }
  3932. // Check value unchanged
  3933. if ((curValue != null) && (newValue != null)) {
  3934. if (typeof (curValue.equals) == "function") {
  3935. if (curValue.equals(newValue)) {
  3936. return true;
  3937. }
  3938. }
  3939. else {
  3940. if (curValue === newValue) {
  3941. return true;
  3942. }
  3943. }
  3944. }
  3945. return false;
  3946. };
  3947. SmartPropertyBase.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  3948. // Trigger property changed
  3949. var info = SmartPropertyBase_1.propChangeGuarding ? new BABYLON.PropertyChangedInfo() : SmartPropertyPrim.propChangedInfo;
  3950. info.oldValue = curValue;
  3951. info.newValue = newValue;
  3952. info.propertyName = propName;
  3953. var propMask = propInfo ? propInfo.flagId : -1;
  3954. try {
  3955. SmartPropertyBase_1.propChangeGuarding = true;
  3956. this.propertyChanged.notifyObservers(info, propMask);
  3957. }
  3958. finally {
  3959. SmartPropertyBase_1.propChangeGuarding = false;
  3960. }
  3961. };
  3962. SmartPropertyBase.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  3963. if (this.isDisposed) {
  3964. return;
  3965. }
  3966. if (!propInfo) {
  3967. return;
  3968. }
  3969. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  3970. };
  3971. Object.defineProperty(SmartPropertyBase.prototype, "dataSource", {
  3972. /**
  3973. * Set the object from which Smart Properties using Binding will take/update their data from/to.
  3974. * 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.
  3975. */
  3976. get: function () {
  3977. // Don't access to _dataSource directly but via a call to the _getDataSource method which can be overloaded in inherited classes
  3978. return this._getDataSource();
  3979. },
  3980. set: function (value) {
  3981. if (this._dataSource === value) {
  3982. return;
  3983. }
  3984. var oldValue = this._dataSource;
  3985. this._dataSource = value;
  3986. if (this._bindings && value != null) {
  3987. // Register the bindings
  3988. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  3989. var binding = _a[_i];
  3990. if (binding != null) {
  3991. binding._registerDataSource(true);
  3992. }
  3993. }
  3994. }
  3995. this.onPropertyChanged("dataSource", oldValue, value);
  3996. },
  3997. enumerable: true,
  3998. configurable: true
  3999. });
  4000. // Inheriting classes can overload this method to provides additional logic for dataSource access
  4001. SmartPropertyBase.prototype._getDataSource = function () {
  4002. return this._dataSource;
  4003. };
  4004. SmartPropertyBase.prototype.createSimpleDataBinding = function (propInfo, propertyPathName, mode) {
  4005. if (mode === void 0) { mode = DataBinding.MODE_DEFAULT; }
  4006. var binding = new DataBinding();
  4007. binding.propertyPathName = propertyPathName;
  4008. binding.mode = mode;
  4009. return this.createDataBinding(propInfo, binding);
  4010. };
  4011. SmartPropertyBase.prototype.createDataBinding = function (propInfo, binding) {
  4012. if (!this._bindings) {
  4013. this._bindings = new Array();
  4014. }
  4015. if (!binding || binding._owner != null) {
  4016. throw Error("A valid/unused Binding must be passed.");
  4017. }
  4018. // Unregister a potentially existing binding for this property
  4019. this.removeDataBinding(propInfo);
  4020. // register the binding
  4021. binding._owner = this;
  4022. binding._boundTo = propInfo;
  4023. this._bindings[propInfo.id] = binding;
  4024. this._hasBinding |= propInfo.flagId;
  4025. binding._registerDataSource(true);
  4026. return binding;
  4027. };
  4028. SmartPropertyBase.prototype.removeDataBinding = function (propInfo) {
  4029. if ((this._hasBinding & propInfo.flagId) === 0) {
  4030. return false;
  4031. }
  4032. var curBinding = this._bindings[propInfo.id];
  4033. curBinding._unregisterDataSource();
  4034. this._bindings[propInfo.id] = null;
  4035. this._hasBinding &= ~propInfo.flagId;
  4036. return true;
  4037. };
  4038. SmartPropertyBase.prototype.updateFromDataSource = function () {
  4039. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  4040. var binding = _a[_i];
  4041. if (binding) {
  4042. }
  4043. }
  4044. };
  4045. return SmartPropertyBase;
  4046. }(BABYLON.PropertyChangedBase));
  4047. SmartPropertyBase.propChangedInfo = new BABYLON.PropertyChangedInfo();
  4048. SmartPropertyBase.propChangeGuarding = false;
  4049. SmartPropertyBase = SmartPropertyBase_1 = __decorate([
  4050. BABYLON.className("SmartPropertyBase", "BABYLON")
  4051. ], SmartPropertyBase);
  4052. BABYLON.SmartPropertyBase = SmartPropertyBase;
  4053. var BindingInfo = (function () {
  4054. function BindingInfo(binding, level, isLast) {
  4055. this.binding = binding;
  4056. this.level = level;
  4057. this.isLast = isLast;
  4058. }
  4059. return BindingInfo;
  4060. }());
  4061. var MonitoredObjectData = (function () {
  4062. function MonitoredObjectData(monitoredObject) {
  4063. var _this = this;
  4064. this.monitoredObject = monitoredObject;
  4065. this.monitoredIntermediateProperties = new BABYLON.StringDictionary();
  4066. this.observer = this.monitoredObject.propertyChanged.add(function (e, s) { _this.propertyChangedHandler(e.propertyName, e.oldValue, e.newValue); });
  4067. this.boundProperties = new BABYLON.StringDictionary();
  4068. this.monitoredIntermediateMask = 0;
  4069. this.boundPropertiesMask = 0;
  4070. }
  4071. MonitoredObjectData.prototype.propertyChangedHandler = function (propName, oldValue, newValue) {
  4072. var propId = BindingHelper._getPropertyID(this.monitoredObject, propName);
  4073. var propIdStr = propId.toString();
  4074. // Loop through all the registered bindings for this property that had a value change
  4075. if ((this.boundPropertiesMask & propId) !== 0) {
  4076. var bindingInfos = this.boundProperties.get(propIdStr);
  4077. for (var _i = 0, bindingInfos_1 = bindingInfos; _i < bindingInfos_1.length; _i++) {
  4078. var bi = bindingInfos_1[_i];
  4079. if (!bi.isLast) {
  4080. BindingHelper.unregisterDataSource(this.monitoredObject, bi.binding, bi.level);
  4081. BindingHelper.registerDataSource(bi.binding._currentDataSource, bi.binding);
  4082. }
  4083. if (bi.binding.canUpdateTarget(false)) {
  4084. bi.binding.updateTarget();
  4085. }
  4086. }
  4087. }
  4088. };
  4089. return MonitoredObjectData;
  4090. }());
  4091. var BindingHelper = (function () {
  4092. function BindingHelper() {
  4093. }
  4094. BindingHelper.registerDataSource = function (dataSource, binding) {
  4095. var properties = binding.propertyPathName.split(".");
  4096. var ownerMod = null;
  4097. var ownerInterPropId = 0;
  4098. var propertyOwner = dataSource;
  4099. var _loop_1 = function (i) {
  4100. var propName = properties[i];
  4101. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  4102. var propIdStr = propId.toString();
  4103. var mod = void 0;
  4104. if (ownerMod) {
  4105. var o_1 = ownerMod;
  4106. var po_1 = propertyOwner;
  4107. var oii_1 = ownerInterPropId;
  4108. mod = ownerMod.monitoredIntermediateProperties.getOrAddWithFactory(oii_1.toString(), function (k) {
  4109. o_1.monitoredIntermediateMask |= oii_1;
  4110. return BindingHelper._getMonitoredObjectData(po_1);
  4111. });
  4112. }
  4113. else {
  4114. mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  4115. }
  4116. var m = mod;
  4117. var bindingInfos = mod.boundProperties.getOrAddWithFactory(propIdStr, function (k) {
  4118. m.boundPropertiesMask |= propId;
  4119. return new Array();
  4120. });
  4121. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  4122. if (!bi) {
  4123. bindingInfos.push(new BindingInfo(binding, i, (i + 1) === properties.length));
  4124. }
  4125. ownerMod = mod;
  4126. ownerInterPropId = propId;
  4127. propertyOwner = propertyOwner[propName];
  4128. };
  4129. for (var i = 0; i < properties.length; i++) {
  4130. _loop_1(i);
  4131. }
  4132. };
  4133. BindingHelper.unregisterDataSource = function (dataSource, binding, level) {
  4134. var properties = binding.propertyPathName.split(".");
  4135. var propertyOwner = dataSource;
  4136. var mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  4137. for (var i = 0; i < properties.length; i++) {
  4138. var propName = properties[i];
  4139. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  4140. var propIdStr = propId.toString();
  4141. if (i >= level) {
  4142. mod = BindingHelper._unregisterBinding(mod, propId, binding);
  4143. }
  4144. else {
  4145. mod = mod.monitoredIntermediateProperties.get(propIdStr);
  4146. }
  4147. propertyOwner = propertyOwner[propName];
  4148. }
  4149. };
  4150. BindingHelper._unregisterBinding = function (mod, propertyID, binding) {
  4151. var propertyIDStr = propertyID.toString();
  4152. var res = null;
  4153. // Check if the property is registered as an intermediate and remove it
  4154. if ((mod.monitoredIntermediateMask & propertyID) !== 0) {
  4155. res = mod.monitoredIntermediateProperties.get(propertyIDStr);
  4156. mod.monitoredIntermediateProperties.remove(propertyIDStr);
  4157. // Update the mask
  4158. mod.monitoredIntermediateMask &= ~propertyID;
  4159. }
  4160. // Check if the property is registered as a final property and remove it
  4161. if ((mod.boundPropertiesMask & propertyID) !== 0) {
  4162. var bindingInfos = mod.boundProperties.get(propertyIDStr);
  4163. // Find the binding and remove it
  4164. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  4165. if (bi) {
  4166. var bii = bindingInfos.indexOf(bi);
  4167. bindingInfos.splice(bii, 1);
  4168. }
  4169. // If the array is empty, update the mask
  4170. if (bindingInfos.length === 0) {
  4171. mod.boundPropertiesMask &= ~propertyID;
  4172. }
  4173. }
  4174. // Check if the MOD is empty and unregister the observer and remove it from the list of MODs
  4175. if (mod.boundPropertiesMask === 0 && mod.monitoredIntermediateMask === 0) {
  4176. // Unregister the observer on Property Change
  4177. mod.monitoredObject.propertyChanged.remove(mod.observer);
  4178. // Remove the MOD from the dic
  4179. var objectId = BindingHelper._getObjectId(mod.monitoredObject);
  4180. BindingHelper._monitoredObjects.remove(objectId);
  4181. }
  4182. return res;
  4183. };
  4184. BindingHelper._getMonitoredObjectData = function (object) {
  4185. var objectId = BindingHelper._getObjectId(object);
  4186. var mod = BindingHelper._monitoredObjects.getOrAddWithFactory(objectId, function (k) { return new MonitoredObjectData(object); });
  4187. return mod;
  4188. };
  4189. BindingHelper._getObjectId = function (obj) {
  4190. var id = obj["__bindingHelperObjectId__"];
  4191. if (id == null) {
  4192. id = BABYLON.Tools.RandomId();
  4193. obj["__bindingHelperObjectId__"] = id;
  4194. return id;
  4195. }
  4196. return id;
  4197. };
  4198. BindingHelper._getObjectTypePropertyIDs = function (obj) {
  4199. var fullName = BABYLON.Tools.getFullClassName(obj);
  4200. if (!fullName) {
  4201. throw Error("Types involved in Data Binding must be decorated with the @className decorator");
  4202. }
  4203. var d = BindingHelper._propertiesID.getOrAddWithFactory(fullName, function () { return new BABYLON.StringDictionary(); });
  4204. return d;
  4205. };
  4206. BindingHelper._getPropertyID = function (object, propName) {
  4207. var otd = BindingHelper._getObjectTypePropertyIDs(object);
  4208. // Make sure we have a WatchedPropertyData for this property of this object type. This will contains the flagIg of the watched property.
  4209. // We use this flagId to flag for each watched instance which properties are watched, as final or intermediate and which directions are used
  4210. var propData = otd.getOrAddWithFactory(propName, function (k) { return 1 << otd.count; });
  4211. return propData;
  4212. };
  4213. return BindingHelper;
  4214. }());
  4215. BindingHelper._propertiesID = new BABYLON.StringDictionary();
  4216. BindingHelper._monitoredObjects = new BABYLON.StringDictionary();
  4217. var SmartPropertyPrim = SmartPropertyPrim_1 = (function (_super) {
  4218. __extends(SmartPropertyPrim, _super);
  4219. function SmartPropertyPrim() {
  4220. var _this = _super.call(this) || this;
  4221. _this._flags = 0;
  4222. _this._uid = null;
  4223. _this._modelKey = null;
  4224. _this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  4225. _this._boundingInfo = new BABYLON.BoundingInfo2D();
  4226. _this.animations = new Array();
  4227. return _this;
  4228. }
  4229. /**
  4230. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  4231. * @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.
  4232. */
  4233. SmartPropertyPrim.prototype.dispose = function () {
  4234. if (this.isDisposed) {
  4235. return false;
  4236. }
  4237. _super.prototype.dispose.call(this);
  4238. // Don't set to null, it may upset somebody...
  4239. this.animations.splice(0);
  4240. return true;
  4241. };
  4242. Object.defineProperty(SmartPropertyPrim.prototype, "uid", {
  4243. /**
  4244. * return a unique identifier for the Canvas2D
  4245. */
  4246. get: function () {
  4247. if (!this._uid) {
  4248. this._uid = BABYLON.Tools.RandomId();
  4249. }
  4250. return this._uid;
  4251. },
  4252. enumerable: true,
  4253. configurable: true
  4254. });
  4255. /**
  4256. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  4257. * Look at Sprite2D for more information
  4258. */
  4259. SmartPropertyPrim.prototype.getAnimatables = function () {
  4260. return new Array();
  4261. };
  4262. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  4263. /**
  4264. * Property giving the Model Key associated to the property.
  4265. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  4266. * @returns the model key string.
  4267. */
  4268. get: function () {
  4269. var _this = this;
  4270. // No need to compute it?
  4271. if (!this._isFlagSet(SmartPropertyPrim_1.flagModelDirty) && this._modelKey) {
  4272. return this._modelKey;
  4273. }
  4274. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  4275. var propDic = this.propDic;
  4276. propDic.forEach(function (k, v) {
  4277. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  4278. var propVal = _this[v.name];
  4279. // 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
  4280. if (propVal && propVal.constructor === Array) {
  4281. var firstVal = propVal[0];
  4282. if (!firstVal) {
  4283. propVal = 0;
  4284. }
  4285. else {
  4286. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  4287. }
  4288. }
  4289. var value = "[null]";
  4290. if (propVal != null) {
  4291. if (v.typeLevelCompare) {
  4292. value = BABYLON.Tools.getClassName(propVal);
  4293. }
  4294. else {
  4295. // String Dictionaries' content are too complex, with use a Random GUID to make the model unique
  4296. if (propVal instanceof BABYLON.StringDictionary) {
  4297. value = BABYLON.Tools.RandomId();
  4298. }
  4299. else if (propVal instanceof BABYLON.BaseTexture) {
  4300. value = propVal.uid;
  4301. }
  4302. else {
  4303. value = propVal.toString();
  4304. }
  4305. }
  4306. }
  4307. modelKey += v.name + ":" + value + ";";
  4308. }
  4309. });
  4310. this._clearFlags(SmartPropertyPrim_1.flagModelDirty);
  4311. this._modelKey = modelKey;
  4312. return modelKey;
  4313. },
  4314. enumerable: true,
  4315. configurable: true
  4316. });
  4317. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  4318. /**
  4319. * States if the Primitive is dirty and should be rendered again next time.
  4320. * @returns true is dirty, false otherwise
  4321. */
  4322. get: function () {
  4323. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim_1.flagModelDirty | SmartPropertyPrim_1.flagModelUpdate | SmartPropertyPrim_1.flagPositioningDirty | SmartPropertyPrim_1.flagLayoutDirty);
  4324. },
  4325. enumerable: true,
  4326. configurable: true
  4327. });
  4328. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  4329. this._setFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  4330. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  4331. if (this instanceof BABYLON.Prim2DBase) {
  4332. var curprim = this;
  4333. while (curprim) {
  4334. curprim._setFlags(SmartPropertyPrim_1.flagBoundingInfoDirty);
  4335. if (curprim.isSizeAuto) {
  4336. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  4337. curprim._setFlags(SmartPropertyPrim_1.flagPositioningDirty);
  4338. }
  4339. if (curprim instanceof BABYLON.Group2D) {
  4340. if (curprim.isRenderableGroup) {
  4341. break;
  4342. }
  4343. }
  4344. curprim = curprim.parent;
  4345. }
  4346. }
  4347. };
  4348. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  4349. _super.prototype._handlePropChanged.call(this, curValue, newValue, propName, propInfo, typeLevelCompare);
  4350. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  4351. if (propInfo.dirtyBoundingInfo) {
  4352. this._boundingBoxDirty();
  4353. }
  4354. else if (propInfo.dirtyParentBoundingInfo) {
  4355. var p = this._parent;
  4356. if (p != null) {
  4357. p._boundingBoxDirty();
  4358. }
  4359. }
  4360. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  4361. if (this instanceof BABYLON.Group2D && this._renderableData) {
  4362. this.handleGroupChanged(propInfo);
  4363. }
  4364. // Check for parent layout dirty
  4365. if (this instanceof BABYLON.Prim2DBase) {
  4366. var p = this._parent;
  4367. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  4368. p._setLayoutDirty();
  4369. }
  4370. }
  4371. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  4372. var instanceDirty = false;
  4373. if (typeLevelCompare && curValue != null && newValue != null) {
  4374. var cvProto = curValue.__proto__;
  4375. var nvProto = newValue.__proto__;
  4376. instanceDirty = (cvProto === nvProto);
  4377. }
  4378. // Set the dirty flags
  4379. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  4380. if (!this.isDirty) {
  4381. this._setFlags(SmartPropertyPrim_1.flagModelDirty);
  4382. }
  4383. }
  4384. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  4385. var propMask = propInfo.flagId;
  4386. this.onPrimitivePropertyDirty(propMask);
  4387. }
  4388. };
  4389. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  4390. this.onPrimBecomesDirty();
  4391. this._instanceDirtyFlags |= propFlagId;
  4392. };
  4393. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  4394. };
  4395. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  4396. _super.prototype._resetPropertiesDirty.call(this);
  4397. this._clearFlags(SmartPropertyPrim_1.flagPrimInDirtyList | SmartPropertyPrim_1.flagNeedRefresh);
  4398. };
  4399. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  4400. /**
  4401. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  4402. */
  4403. get: function () {
  4404. if (this._isFlagSet(SmartPropertyPrim_1.flagLevelBoundingInfoDirty)) {
  4405. if (this.updateLevelBoundingInfo()) {
  4406. this._boundingInfo.dirtyWorldAABB();
  4407. this._clearFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  4408. }
  4409. else {
  4410. this._levelBoundingInfo.clear();
  4411. }
  4412. }
  4413. return this._levelBoundingInfo;
  4414. },
  4415. enumerable: true,
  4416. configurable: true
  4417. });
  4418. /**
  4419. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  4420. */
  4421. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  4422. return false;
  4423. };
  4424. /**
  4425. * Property method called when the Primitive becomes dirty
  4426. */
  4427. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  4428. };
  4429. /**
  4430. * Check if a given flag is set
  4431. * @param flag the flag value
  4432. * @return true if set, false otherwise
  4433. */
  4434. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  4435. return (this._flags & flag) !== 0;
  4436. };
  4437. /**
  4438. * Check if all given flags are set
  4439. * @param flags the flags ORed
  4440. * @return true if all the flags are set, false otherwise
  4441. */
  4442. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  4443. return (this._flags & flags) === flags;
  4444. };
  4445. /**
  4446. * Check if at least one flag of the given flags is set
  4447. * @param flags the flags ORed
  4448. * @return true if at least one flag is set, false otherwise
  4449. */
  4450. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  4451. return (this._flags & flags) !== 0;
  4452. };
  4453. /**
  4454. * Clear the given flags
  4455. * @param flags the flags to clear
  4456. */
  4457. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  4458. this._flags &= ~flags;
  4459. };
  4460. /**
  4461. * Set the given flags to true state
  4462. * @param flags the flags ORed to set
  4463. * @return the flags state before this call
  4464. */
  4465. SmartPropertyPrim.prototype._setFlags = function (flags) {
  4466. var cur = this._flags;
  4467. this._flags |= flags;
  4468. return cur;
  4469. };
  4470. /**
  4471. * Change the state of the given flags
  4472. * @param flags the flags ORed to change
  4473. * @param state true to set them, false to clear them
  4474. */
  4475. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  4476. if (state) {
  4477. this._flags |= flags;
  4478. }
  4479. else {
  4480. this._flags &= ~flags;
  4481. }
  4482. };
  4483. return SmartPropertyPrim;
  4484. }(SmartPropertyBase));
  4485. SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT = 0;
  4486. SmartPropertyPrim.flagNoPartOfLayout = 0x0000001; // set if the primitive's position/size must not be computed by Layout Engine
  4487. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  4488. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  4489. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  4490. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  4491. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  4492. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  4493. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  4494. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  4495. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  4496. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  4497. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  4498. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  4499. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  4500. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  4501. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  4502. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  4503. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  4504. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  4505. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  4506. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  4507. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0200000; // set if the layout bounding info is dirty
  4508. SmartPropertyPrim.flagCollisionActor = 0x0400000; // set if the primitive is part of the collision engine
  4509. SmartPropertyPrim.flagModelUpdate = 0x0800000; // set if the primitive's model data is to update
  4510. SmartPropertyPrim = SmartPropertyPrim_1 = __decorate([
  4511. BABYLON.className("SmartPropertyPrim", "BABYLON")
  4512. ], SmartPropertyPrim);
  4513. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  4514. function dependencyProperty(propId, piStore, mode, updateSourceTrigger) {
  4515. if (mode === void 0) { mode = DataBinding.MODE_TWOWAY; }
  4516. if (updateSourceTrigger === void 0) { updateSourceTrigger = DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED; }
  4517. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { bindingMode: mode, bindingUpdateSourceTrigger: updateSourceTrigger });
  4518. }
  4519. BABYLON.dependencyProperty = dependencyProperty;
  4520. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  4521. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  4522. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  4523. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  4524. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_MODEL, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  4525. }
  4526. BABYLON.modelLevelProperty = modelLevelProperty;
  4527. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  4528. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  4529. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  4530. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  4531. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_INSTANCE, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  4532. }
  4533. BABYLON.instanceLevelProperty = instanceLevelProperty;
  4534. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  4535. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  4536. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  4537. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  4538. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  4539. }
  4540. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  4541. var DataBinding_1, SmartPropertyBase_1, SmartPropertyPrim_1;
  4542. })(BABYLON || (BABYLON = {}));
  4543. //# sourceMappingURL=babylon.smartPropertyPrim.js.map
  4544. var __extends = (this && this.__extends) || function (d, b) {
  4545. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4546. function __() { this.constructor = d; }
  4547. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4548. };
  4549. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4550. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4551. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4552. 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;
  4553. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4554. };
  4555. var BABYLON;
  4556. (function (BABYLON) {
  4557. var PrepareRender2DContext = (function () {
  4558. function PrepareRender2DContext() {
  4559. this.forceRefreshPrimitive = false;
  4560. }
  4561. return PrepareRender2DContext;
  4562. }());
  4563. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  4564. var Render2DContext = (function () {
  4565. function Render2DContext(renderMode) {
  4566. this._renderMode = renderMode;
  4567. this.useInstancing = false;
  4568. this.groupInfoPartData = null;
  4569. this.partDataStartIndex = this.partDataEndIndex = null;
  4570. this.instancedBuffers = null;
  4571. }
  4572. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  4573. /**
  4574. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  4575. */
  4576. get: function () {
  4577. return this._renderMode;
  4578. },
  4579. enumerable: true,
  4580. configurable: true
  4581. });
  4582. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  4583. /**
  4584. * The set of primitives to render is opaque.
  4585. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  4586. */
  4587. get: function () {
  4588. return Render2DContext._renderModeOpaque;
  4589. },
  4590. enumerable: true,
  4591. configurable: true
  4592. });
  4593. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  4594. /**
  4595. * The set of primitives to render is using Alpha Test (aka masking).
  4596. * 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.
  4597. */
  4598. get: function () {
  4599. return Render2DContext._renderModeAlphaTest;
  4600. },
  4601. enumerable: true,
  4602. configurable: true
  4603. });
  4604. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  4605. /**
  4606. * The set of primitives to render is transparent.
  4607. * 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.
  4608. */
  4609. get: function () {
  4610. return Render2DContext._renderModeTransparent;
  4611. },
  4612. enumerable: true,
  4613. configurable: true
  4614. });
  4615. return Render2DContext;
  4616. }());
  4617. Render2DContext._renderModeOpaque = 1;
  4618. Render2DContext._renderModeAlphaTest = 2;
  4619. Render2DContext._renderModeTransparent = 3;
  4620. BABYLON.Render2DContext = Render2DContext;
  4621. /**
  4622. * This class store information for the pointerEventObservable Observable.
  4623. * 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.
  4624. */
  4625. var PrimitivePointerInfo = (function () {
  4626. function PrimitivePointerInfo() {
  4627. this.primitivePointerPos = BABYLON.Vector2.Zero();
  4628. this.tilt = BABYLON.Vector2.Zero();
  4629. this.cancelBubble = false;
  4630. }
  4631. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  4632. // 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.
  4633. /**
  4634. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  4635. * Bubbles: yes
  4636. */
  4637. get: function () {
  4638. return PrimitivePointerInfo._pointerOver;
  4639. },
  4640. enumerable: true,
  4641. configurable: true
  4642. });
  4643. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  4644. /**
  4645. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  4646. * Bubbles: no
  4647. */
  4648. get: function () {
  4649. return PrimitivePointerInfo._pointerEnter;
  4650. },
  4651. enumerable: true,
  4652. configurable: true
  4653. });
  4654. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  4655. /**
  4656. * 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.
  4657. * Bubbles: yes
  4658. */
  4659. get: function () {
  4660. return PrimitivePointerInfo._pointerDown;
  4661. },
  4662. enumerable: true,
  4663. configurable: true
  4664. });
  4665. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  4666. /**
  4667. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  4668. * Bubbles: yes
  4669. */
  4670. get: function () {
  4671. return PrimitivePointerInfo._pointerMouseWheel;
  4672. },
  4673. enumerable: true,
  4674. configurable: true
  4675. });
  4676. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  4677. /**
  4678. * 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.
  4679. * Bubbles: yes
  4680. */
  4681. get: function () {
  4682. return PrimitivePointerInfo._pointerMove;
  4683. },
  4684. enumerable: true,
  4685. configurable: true
  4686. });
  4687. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  4688. /**
  4689. * 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.
  4690. * Bubbles: yes
  4691. */
  4692. get: function () {
  4693. return PrimitivePointerInfo._pointerUp;
  4694. },
  4695. enumerable: true,
  4696. configurable: true
  4697. });
  4698. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  4699. /**
  4700. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  4701. * Bubbles: yes
  4702. */
  4703. get: function () {
  4704. return PrimitivePointerInfo._pointerOut;
  4705. },
  4706. enumerable: true,
  4707. configurable: true
  4708. });
  4709. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  4710. /**
  4711. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  4712. * Bubbles: no
  4713. */
  4714. get: function () {
  4715. return PrimitivePointerInfo._pointerLeave;
  4716. },
  4717. enumerable: true,
  4718. configurable: true
  4719. });
  4720. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  4721. /**
  4722. * 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.
  4723. * Bubbles: yes
  4724. */
  4725. get: function () {
  4726. return PrimitivePointerInfo._pointerGotCapture;
  4727. },
  4728. enumerable: true,
  4729. configurable: true
  4730. });
  4731. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  4732. /**
  4733. * This event type is raised after pointer capture is released for a pointer.
  4734. * Bubbles: yes
  4735. */
  4736. get: function () {
  4737. return PrimitivePointerInfo._pointerLostCapture;
  4738. },
  4739. enumerable: true,
  4740. configurable: true
  4741. });
  4742. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  4743. get: function () {
  4744. return PrimitivePointerInfo._mouseWheelPrecision;
  4745. },
  4746. enumerable: true,
  4747. configurable: true
  4748. });
  4749. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  4750. this.relatedTarget = prim;
  4751. this.relatedTargetPointerPos = primPointerPos;
  4752. };
  4753. PrimitivePointerInfo.getEventTypeName = function (mask) {
  4754. switch (mask) {
  4755. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  4756. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  4757. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  4758. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  4759. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  4760. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  4761. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  4762. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  4763. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  4764. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  4765. }
  4766. };
  4767. return PrimitivePointerInfo;
  4768. }());
  4769. PrimitivePointerInfo._pointerOver = 0x0001;
  4770. PrimitivePointerInfo._pointerEnter = 0x0002;
  4771. PrimitivePointerInfo._pointerDown = 0x0004;
  4772. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  4773. PrimitivePointerInfo._pointerMove = 0x0010;
  4774. PrimitivePointerInfo._pointerUp = 0x0020;
  4775. PrimitivePointerInfo._pointerOut = 0x0040;
  4776. PrimitivePointerInfo._pointerLeave = 0x0080;
  4777. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  4778. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  4779. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  4780. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  4781. /**
  4782. * Defines the horizontal and vertical alignment information for a Primitive.
  4783. */
  4784. var PrimitiveAlignment = PrimitiveAlignment_1 = (function () {
  4785. function PrimitiveAlignment(changeCallback) {
  4786. this._changedCallback = changeCallback;
  4787. this._horizontal = PrimitiveAlignment_1.AlignLeft;
  4788. this._vertical = PrimitiveAlignment_1.AlignBottom;
  4789. }
  4790. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  4791. /**
  4792. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  4793. */
  4794. get: function () { return PrimitiveAlignment_1._AlignLeft; },
  4795. enumerable: true,
  4796. configurable: true
  4797. });
  4798. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  4799. /**
  4800. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  4801. */
  4802. get: function () { return PrimitiveAlignment_1._AlignTop; },
  4803. enumerable: true,
  4804. configurable: true
  4805. });
  4806. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  4807. /**
  4808. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  4809. */
  4810. get: function () { return PrimitiveAlignment_1._AlignRight; },
  4811. enumerable: true,
  4812. configurable: true
  4813. });
  4814. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  4815. /**
  4816. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  4817. */
  4818. get: function () { return PrimitiveAlignment_1._AlignBottom; },
  4819. enumerable: true,
  4820. configurable: true
  4821. });
  4822. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  4823. /**
  4824. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  4825. */
  4826. get: function () { return PrimitiveAlignment_1._AlignCenter; },
  4827. enumerable: true,
  4828. configurable: true
  4829. });
  4830. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  4831. /**
  4832. * The content is stretched toward the opposite edges of the Primitive
  4833. */
  4834. get: function () { return PrimitiveAlignment_1._AlignStretch; },
  4835. enumerable: true,
  4836. configurable: true
  4837. });
  4838. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  4839. /**
  4840. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  4841. */
  4842. get: function () {
  4843. return this._horizontal;
  4844. },
  4845. set: function (value) {
  4846. if (this._horizontal === value) {
  4847. return;
  4848. }
  4849. this._horizontal = value;
  4850. this.onChangeCallback();
  4851. },
  4852. enumerable: true,
  4853. configurable: true
  4854. });
  4855. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  4856. /**
  4857. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  4858. */
  4859. get: function () {
  4860. return this._vertical;
  4861. },
  4862. set: function (value) {
  4863. if (this._vertical === value) {
  4864. return;
  4865. }
  4866. this._vertical = value;
  4867. this.onChangeCallback();
  4868. },
  4869. enumerable: true,
  4870. configurable: true
  4871. });
  4872. PrimitiveAlignment.prototype.onChangeCallback = function () {
  4873. if (this._changedCallback) {
  4874. this._changedCallback();
  4875. }
  4876. };
  4877. /**
  4878. * Set the horizontal alignment from a string value.
  4879. * @param text can be either: 'left','right','center','stretch'
  4880. */
  4881. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  4882. var v = text.trim().toLocaleLowerCase();
  4883. switch (v) {
  4884. case "left":
  4885. this.horizontal = PrimitiveAlignment_1.AlignLeft;
  4886. return;
  4887. case "right":
  4888. this.horizontal = PrimitiveAlignment_1.AlignRight;
  4889. return;
  4890. case "center":
  4891. this.horizontal = PrimitiveAlignment_1.AlignCenter;
  4892. return;
  4893. case "stretch":
  4894. this.horizontal = PrimitiveAlignment_1.AlignStretch;
  4895. return;
  4896. }
  4897. };
  4898. /**
  4899. * Set the vertical alignment from a string value.
  4900. * @param text can be either: 'top','bottom','center','stretch'
  4901. */
  4902. PrimitiveAlignment.prototype.setVertical = function (text) {
  4903. var v = text.trim().toLocaleLowerCase();
  4904. switch (v) {
  4905. case "top":
  4906. this.vertical = PrimitiveAlignment_1.AlignTop;
  4907. return;
  4908. case "bottom":
  4909. this.vertical = PrimitiveAlignment_1.AlignBottom;
  4910. return;
  4911. case "center":
  4912. this.vertical = PrimitiveAlignment_1.AlignCenter;
  4913. return;
  4914. case "stretch":
  4915. this.vertical = PrimitiveAlignment_1.AlignStretch;
  4916. return;
  4917. }
  4918. };
  4919. /**
  4920. * Set the horizontal and or vertical alignments from a string value.
  4921. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  4922. */
  4923. PrimitiveAlignment.prototype.fromString = function (value) {
  4924. var m = value.trim().split(",");
  4925. if (m.length === 1) {
  4926. this.setHorizontal(m[0]);
  4927. this.setVertical(m[0]);
  4928. }
  4929. else {
  4930. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  4931. var v = m_1[_i];
  4932. v = v.toLocaleLowerCase().trim();
  4933. // Horizontal
  4934. var i = v.indexOf("h:");
  4935. if (i === -1) {
  4936. i = v.indexOf("horizontal:");
  4937. }
  4938. if (i !== -1) {
  4939. v = v.substr(v.indexOf(":") + 1);
  4940. this.setHorizontal(v);
  4941. continue;
  4942. }
  4943. // Vertical
  4944. i = v.indexOf("v:");
  4945. if (i === -1) {
  4946. i = v.indexOf("vertical:");
  4947. }
  4948. if (i !== -1) {
  4949. v = v.substr(v.indexOf(":") + 1);
  4950. this.setVertical(v);
  4951. continue;
  4952. }
  4953. }
  4954. }
  4955. };
  4956. PrimitiveAlignment.prototype.copyFrom = function (pa) {
  4957. this._horizontal = pa._horizontal;
  4958. this._vertical = pa._vertical;
  4959. this.onChangeCallback();
  4960. };
  4961. Object.defineProperty(PrimitiveAlignment.prototype, "isDefault", {
  4962. get: function () {
  4963. return this.horizontal === PrimitiveAlignment_1.AlignLeft && this.vertical === PrimitiveAlignment_1.AlignBottom;
  4964. },
  4965. enumerable: true,
  4966. configurable: true
  4967. });
  4968. return PrimitiveAlignment;
  4969. }());
  4970. PrimitiveAlignment._AlignLeft = 1;
  4971. PrimitiveAlignment._AlignTop = 1; // Same as left
  4972. PrimitiveAlignment._AlignRight = 2;
  4973. PrimitiveAlignment._AlignBottom = 2; // Same as right
  4974. PrimitiveAlignment._AlignCenter = 3;
  4975. PrimitiveAlignment._AlignStretch = 4;
  4976. PrimitiveAlignment = PrimitiveAlignment_1 = __decorate([
  4977. BABYLON.className("PrimitiveAlignment", "BABYLON")
  4978. ], PrimitiveAlignment);
  4979. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  4980. /**
  4981. * Stores information about a Primitive that was intersected
  4982. */
  4983. var PrimitiveIntersectedInfo = (function () {
  4984. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  4985. this.prim = prim;
  4986. this.intersectionLocation = intersectionLocation;
  4987. }
  4988. return PrimitiveIntersectedInfo;
  4989. }());
  4990. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  4991. /**
  4992. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  4993. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  4994. */
  4995. var PrimitiveThickness = PrimitiveThickness_1 = (function () {
  4996. function PrimitiveThickness(parentAccess, changedCallback) {
  4997. this._parentAccess = parentAccess;
  4998. this._changedCallback = changedCallback;
  4999. this._pixels = new Array(4);
  5000. this._percentages = new Array(4);
  5001. this._setType(0, PrimitiveThickness_1.Auto);
  5002. this._setType(1, PrimitiveThickness_1.Auto);
  5003. this._setType(2, PrimitiveThickness_1.Auto);
  5004. this._setType(3, PrimitiveThickness_1.Auto);
  5005. this._pixels[0] = 0;
  5006. this._pixels[1] = 0;
  5007. this._pixels[2] = 0;
  5008. this._pixels[3] = 0;
  5009. }
  5010. /**
  5011. * Set the thickness from a string value
  5012. * @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.
  5013. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5014. */
  5015. PrimitiveThickness.prototype.fromString = function (thickness) {
  5016. this._clear();
  5017. var m = thickness.trim().split(",");
  5018. // Special case, one value to apply to all edges
  5019. if (m.length === 1 && thickness.indexOf(":") === -1) {
  5020. this._setStringValue(m[0], 0, false);
  5021. this._setStringValue(m[0], 1, false);
  5022. this._setStringValue(m[0], 2, false);
  5023. this._setStringValue(m[0], 3, false);
  5024. this.onChangeCallback();
  5025. return;
  5026. }
  5027. var res = false;
  5028. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  5029. var cm = m_2[_i];
  5030. res = this._extractString(cm, false) || res;
  5031. }
  5032. if (!res) {
  5033. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  5034. }
  5035. // Check the margin that weren't set and set them in auto
  5036. if ((this._flags & 0x000F) === 0)
  5037. this._flags |= PrimitiveThickness_1.Pixel << 0;
  5038. if ((this._flags & 0x00F0) === 0)
  5039. this._flags |= PrimitiveThickness_1.Pixel << 4;
  5040. if ((this._flags & 0x0F00) === 0)
  5041. this._flags |= PrimitiveThickness_1.Pixel << 8;
  5042. if ((this._flags & 0xF000) === 0)
  5043. this._flags |= PrimitiveThickness_1.Pixel << 12;
  5044. this.onChangeCallback();
  5045. };
  5046. /**
  5047. * Set the thickness from multiple string
  5048. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5049. * @param top the top thickness to set
  5050. * @param left the left thickness to set
  5051. * @param right the right thickness to set
  5052. * @param bottom the bottom thickness to set
  5053. */
  5054. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  5055. this._clear();
  5056. this._setStringValue(top, 0, false);
  5057. this._setStringValue(left, 1, false);
  5058. this._setStringValue(right, 2, false);
  5059. this._setStringValue(bottom, 3, false);
  5060. this.onChangeCallback();
  5061. return this;
  5062. };
  5063. /**
  5064. * Set the thickness from pixel values
  5065. * @param top the top thickness in pixels to set
  5066. * @param left the left thickness in pixels to set
  5067. * @param right the right thickness in pixels to set
  5068. * @param bottom the bottom thickness in pixels to set
  5069. */
  5070. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  5071. this._clear();
  5072. this._pixels[0] = top;
  5073. this._pixels[1] = left;
  5074. this._pixels[2] = right;
  5075. this._pixels[3] = bottom;
  5076. this.onChangeCallback();
  5077. return this;
  5078. };
  5079. /**
  5080. * Apply the same pixel value to all edges
  5081. * @param margin the value to set, in pixels.
  5082. */
  5083. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  5084. this._clear();
  5085. this._pixels[0] = margin;
  5086. this._pixels[1] = margin;
  5087. this._pixels[2] = margin;
  5088. this._pixels[3] = margin;
  5089. this.onChangeCallback();
  5090. return this;
  5091. };
  5092. PrimitiveThickness.prototype.copyFrom = function (pt) {
  5093. this._clear();
  5094. for (var i = 0; i < 4; i++) {
  5095. this._pixels[i] = pt._pixels[i];
  5096. this._percentages[i] = pt._percentages[i];
  5097. }
  5098. this._flags = pt._flags;
  5099. this.onChangeCallback();
  5100. };
  5101. /**
  5102. * Set all edges in auto
  5103. */
  5104. PrimitiveThickness.prototype.auto = function () {
  5105. this._clear();
  5106. this._flags = (PrimitiveThickness_1.Auto << 0) | (PrimitiveThickness_1.Auto << 4) | (PrimitiveThickness_1.Auto << 8) | (PrimitiveThickness_1.Auto << 12);
  5107. this._pixels[0] = 0;
  5108. this._pixels[1] = 0;
  5109. this._pixels[2] = 0;
  5110. this._pixels[3] = 0;
  5111. this.onChangeCallback();
  5112. return this;
  5113. };
  5114. PrimitiveThickness.prototype._clear = function () {
  5115. this._flags = 0;
  5116. this._pixels[0] = 0;
  5117. this._pixels[1] = 0;
  5118. this._pixels[2] = 0;
  5119. this._pixels[3] = 0;
  5120. this._percentages[0] = null;
  5121. this._percentages[1] = null;
  5122. this._percentages[2] = null;
  5123. this._percentages[3] = null;
  5124. };
  5125. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  5126. var v = value.trim().toLocaleLowerCase();
  5127. if (v.indexOf("top:") === 0) {
  5128. v = v.substr(4).trim();
  5129. return this._setStringValue(v, 0, emitChanged);
  5130. }
  5131. if (v.indexOf("left:") === 0) {
  5132. v = v.substr(5).trim();
  5133. return this._setStringValue(v, 1, emitChanged);
  5134. }
  5135. if (v.indexOf("right:") === 0) {
  5136. v = v.substr(6).trim();
  5137. return this._setStringValue(v, 2, emitChanged);
  5138. }
  5139. if (v.indexOf("bottom:") === 0) {
  5140. v = v.substr(7).trim();
  5141. return this._setStringValue(v, 3, emitChanged);
  5142. }
  5143. return false;
  5144. };
  5145. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  5146. // Check for auto
  5147. var v = value.trim().toLocaleLowerCase();
  5148. if (v === "auto") {
  5149. if (this._isType(index, PrimitiveThickness_1.Auto)) {
  5150. return true;
  5151. }
  5152. this._setType(index, PrimitiveThickness_1.Auto);
  5153. this._pixels[index] = 0;
  5154. if (emitChanged) {
  5155. this.onChangeCallback();
  5156. }
  5157. }
  5158. else if (v === "inherit") {
  5159. if (this._isType(index, PrimitiveThickness_1.Inherit)) {
  5160. return true;
  5161. }
  5162. this._setType(index, PrimitiveThickness_1.Inherit);
  5163. this._pixels[index] = null;
  5164. if (emitChanged) {
  5165. this.onChangeCallback();
  5166. }
  5167. }
  5168. else {
  5169. var pI = v.indexOf("%");
  5170. // Check for percentage
  5171. if (pI !== -1) {
  5172. var n_1 = v.substr(0, pI);
  5173. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  5174. if (this._isType(index, PrimitiveThickness_1.Percentage) && (this._percentages[index] === number_1)) {
  5175. return true;
  5176. }
  5177. this._setType(index, PrimitiveThickness_1.Percentage);
  5178. if (isNaN(number_1)) {
  5179. return false;
  5180. }
  5181. this._percentages[index] = number_1;
  5182. if (emitChanged) {
  5183. this.onChangeCallback();
  5184. }
  5185. return true;
  5186. }
  5187. // Check for pixel
  5188. var n = void 0;
  5189. pI = v.indexOf("px");
  5190. if (pI !== -1) {
  5191. n = v.substr(0, pI).trim();
  5192. }
  5193. else {
  5194. n = v;
  5195. }
  5196. var number = Number(n);
  5197. if (this._isType(index, PrimitiveThickness_1.Pixel) && (this._pixels[index] === number)) {
  5198. return true;
  5199. }
  5200. if (isNaN(number)) {
  5201. return false;
  5202. }
  5203. this._pixels[index] = number;
  5204. this._setType(index, PrimitiveThickness_1.Pixel);
  5205. if (emitChanged) {
  5206. this.onChangeCallback();
  5207. }
  5208. return true;
  5209. }
  5210. };
  5211. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  5212. // 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
  5213. value = Math.round(value);
  5214. if (this._isType(index, PrimitiveThickness_1.Pixel) && this._pixels[index] === value) {
  5215. return;
  5216. }
  5217. this._setType(index, PrimitiveThickness_1.Pixel);
  5218. this._pixels[index] = value;
  5219. if (emitChanged) {
  5220. this.onChangeCallback();
  5221. }
  5222. };
  5223. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  5224. // Clip Value to bounds
  5225. value = Math.min(1, value);
  5226. value = Math.max(0, value);
  5227. value = Math.round(value * 100) / 100; // 0.01 precision
  5228. if (this._isType(index, PrimitiveThickness_1.Percentage) && this._percentages[index] === value) {
  5229. return;
  5230. }
  5231. this._setType(index, PrimitiveThickness_1.Percentage);
  5232. this._percentages[index] = value;
  5233. if (emitChanged) {
  5234. this.onChangeCallback();
  5235. }
  5236. };
  5237. PrimitiveThickness.prototype._getStringValue = function (index) {
  5238. var f = (this._flags >> (index * 4)) & 0xF;
  5239. switch (f) {
  5240. case PrimitiveThickness_1.Auto:
  5241. return "auto";
  5242. case PrimitiveThickness_1.Pixel:
  5243. return this._pixels[index] + "px";
  5244. case PrimitiveThickness_1.Percentage:
  5245. return this._percentages[index] * 100 + "%";
  5246. case PrimitiveThickness_1.Inherit:
  5247. return "inherit";
  5248. }
  5249. return "";
  5250. };
  5251. PrimitiveThickness.prototype._isType = function (index, type) {
  5252. var f = (this._flags >> (index * 4)) & 0xF;
  5253. return f === type;
  5254. };
  5255. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  5256. var t = (this._flags >> (index * 4)) & 0xF;
  5257. if (processInherit && (t === PrimitiveThickness_1.Inherit)) {
  5258. var p = this._parentAccess();
  5259. if (p) {
  5260. return p._getType(index, true);
  5261. }
  5262. return PrimitiveThickness_1.Auto;
  5263. }
  5264. return t;
  5265. };
  5266. PrimitiveThickness.prototype._setType = function (index, type) {
  5267. this._flags &= ~(0xF << (index * 4));
  5268. this._flags |= type << (index * 4);
  5269. };
  5270. PrimitiveThickness.prototype.setTop = function (value) {
  5271. if (typeof value === "string") {
  5272. this._setStringValue(value, 0, true);
  5273. }
  5274. else {
  5275. this.topPixels = value;
  5276. }
  5277. };
  5278. PrimitiveThickness.prototype.setLeft = function (value) {
  5279. if (typeof value === "string") {
  5280. this._setStringValue(value, 1, true);
  5281. }
  5282. else {
  5283. this.leftPixels = value;
  5284. }
  5285. };
  5286. PrimitiveThickness.prototype.setRight = function (value) {
  5287. if (typeof value === "string") {
  5288. this._setStringValue(value, 2, true);
  5289. }
  5290. else {
  5291. this.rightPixels = value;
  5292. }
  5293. };
  5294. PrimitiveThickness.prototype.setBottom = function (value) {
  5295. if (typeof value === "string") {
  5296. this._setStringValue(value, 3, true);
  5297. }
  5298. else {
  5299. this.bottomPixels = value;
  5300. }
  5301. };
  5302. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  5303. /**
  5304. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5305. */
  5306. get: function () {
  5307. return this._getStringValue(0);
  5308. },
  5309. set: function (value) {
  5310. this._setStringValue(value, 0, true);
  5311. },
  5312. enumerable: true,
  5313. configurable: true
  5314. });
  5315. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  5316. /**
  5317. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5318. */
  5319. get: function () {
  5320. return this._getStringValue(1);
  5321. },
  5322. set: function (value) {
  5323. this._setStringValue(value, 1, true);
  5324. },
  5325. enumerable: true,
  5326. configurable: true
  5327. });
  5328. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  5329. /**
  5330. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5331. */
  5332. get: function () {
  5333. return this._getStringValue(2);
  5334. },
  5335. set: function (value) {
  5336. this._setStringValue(value, 2, true);
  5337. },
  5338. enumerable: true,
  5339. configurable: true
  5340. });
  5341. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  5342. /**
  5343. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5344. */
  5345. get: function () {
  5346. return this._getStringValue(3);
  5347. },
  5348. set: function (value) {
  5349. this._setStringValue(value, 3, true);
  5350. },
  5351. enumerable: true,
  5352. configurable: true
  5353. });
  5354. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  5355. /**
  5356. * Get/set the top thickness in pixel.
  5357. */
  5358. get: function () {
  5359. return this._pixels[0];
  5360. },
  5361. set: function (value) {
  5362. this._setPixels(value, 0, true);
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  5368. /**
  5369. * Get/set the left thickness in pixel.
  5370. */
  5371. get: function () {
  5372. return this._pixels[1];
  5373. },
  5374. set: function (value) {
  5375. this._setPixels(value, 1, true);
  5376. },
  5377. enumerable: true,
  5378. configurable: true
  5379. });
  5380. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  5381. /**
  5382. * Get/set the right thickness in pixel.
  5383. */
  5384. get: function () {
  5385. return this._pixels[2];
  5386. },
  5387. set: function (value) {
  5388. this._setPixels(value, 2, true);
  5389. },
  5390. enumerable: true,
  5391. configurable: true
  5392. });
  5393. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  5394. /**
  5395. * Get/set the bottom thickness in pixel.
  5396. */
  5397. get: function () {
  5398. return this._pixels[3];
  5399. },
  5400. set: function (value) {
  5401. this._setPixels(value, 3, true);
  5402. },
  5403. enumerable: true,
  5404. configurable: true
  5405. });
  5406. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  5407. /**
  5408. * Get/set the top thickness in percentage.
  5409. * The get will return a valid value only if the edge type is percentage.
  5410. * The Set will change the edge mode if needed
  5411. */
  5412. get: function () {
  5413. return this._percentages[0];
  5414. },
  5415. set: function (value) {
  5416. this._setPercentage(value, 0, true);
  5417. },
  5418. enumerable: true,
  5419. configurable: true
  5420. });
  5421. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  5422. /**
  5423. * Get/set the left thickness in percentage.
  5424. * The get will return a valid value only if the edge mode is percentage.
  5425. * The Set will change the edge mode if needed
  5426. */
  5427. get: function () {
  5428. return this._percentages[1];
  5429. },
  5430. set: function (value) {
  5431. this._setPercentage(value, 1, true);
  5432. },
  5433. enumerable: true,
  5434. configurable: true
  5435. });
  5436. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  5437. /**
  5438. * Get/set the right thickness in percentage.
  5439. * The get will return a valid value only if the edge mode is percentage.
  5440. * The Set will change the edge mode if needed
  5441. */
  5442. get: function () {
  5443. return this._percentages[2];
  5444. },
  5445. set: function (value) {
  5446. this._setPercentage(value, 2, true);
  5447. },
  5448. enumerable: true,
  5449. configurable: true
  5450. });
  5451. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  5452. /**
  5453. * Get/set the bottom thickness in percentage.
  5454. * The get will return a valid value only if the edge mode is percentage.
  5455. * The Set will change the edge mode if needed
  5456. */
  5457. get: function () {
  5458. return this._percentages[3];
  5459. },
  5460. set: function (value) {
  5461. this._setPercentage(value, 3, true);
  5462. },
  5463. enumerable: true,
  5464. configurable: true
  5465. });
  5466. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  5467. /**
  5468. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  5469. */
  5470. get: function () {
  5471. return this._getType(0, false);
  5472. },
  5473. set: function (mode) {
  5474. this._setType(0, mode);
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  5480. /**
  5481. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  5482. */
  5483. get: function () {
  5484. return this._getType(1, false);
  5485. },
  5486. set: function (mode) {
  5487. this._setType(1, mode);
  5488. },
  5489. enumerable: true,
  5490. configurable: true
  5491. });
  5492. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  5493. /**
  5494. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  5495. */
  5496. get: function () {
  5497. return this._getType(2, false);
  5498. },
  5499. set: function (mode) {
  5500. this._setType(2, mode);
  5501. },
  5502. enumerable: true,
  5503. configurable: true
  5504. });
  5505. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  5506. /**
  5507. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  5508. */
  5509. get: function () {
  5510. return this._getType(3, false);
  5511. },
  5512. set: function (mode) {
  5513. this._setType(3, mode);
  5514. },
  5515. enumerable: true,
  5516. configurable: true
  5517. });
  5518. Object.defineProperty(PrimitiveThickness.prototype, "isDefault", {
  5519. get: function () {
  5520. return this._flags === 0x1111;
  5521. },
  5522. enumerable: true,
  5523. configurable: true
  5524. });
  5525. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  5526. var type = this._getType(index, false);
  5527. if (type === PrimitiveThickness_1.Inherit) {
  5528. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  5529. return;
  5530. }
  5531. if (type !== PrimitiveThickness_1.Percentage) {
  5532. return;
  5533. }
  5534. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  5535. this._pixels[index] = pixels;
  5536. if (emitChanged) {
  5537. this.onChangeCallback();
  5538. }
  5539. };
  5540. PrimitiveThickness.prototype.onChangeCallback = function () {
  5541. if (this._changedCallback) {
  5542. this._changedCallback();
  5543. }
  5544. };
  5545. /**
  5546. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  5547. * @param sourceArea the source area where the content must be sized/positioned
  5548. * @param contentSize the content size to position/resize
  5549. * @param alignment the alignment setting
  5550. * @param dstOffset the position of the content, x, y, z, w are left, bottom, right, top
  5551. * @param dstArea the new size of the content
  5552. */
  5553. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea, computeLayoutArea) {
  5554. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  5555. // Fetch some data
  5556. var topType = this._getType(0, true);
  5557. var leftType = this._getType(1, true);
  5558. var rightType = this._getType(2, true);
  5559. var bottomType = this._getType(3, true);
  5560. var hasWidth = contentSize && (contentSize.width != null);
  5561. var hasHeight = contentSize && (contentSize.height != null);
  5562. var width = hasWidth ? contentSize.width : 0;
  5563. var height = hasHeight ? contentSize.height : 0;
  5564. var isTopAuto = topType === PrimitiveThickness_1.Auto;
  5565. var isLeftAuto = leftType === PrimitiveThickness_1.Auto;
  5566. var isRightAuto = rightType === PrimitiveThickness_1.Auto;
  5567. var isBottomAuto = bottomType === PrimitiveThickness_1.Auto;
  5568. switch (alignment.horizontal) {
  5569. case PrimitiveAlignment.AlignLeft:
  5570. {
  5571. if (isLeftAuto) {
  5572. dstOffset.x = 0;
  5573. }
  5574. else {
  5575. this._computePixels(1, sourceArea, true);
  5576. dstOffset.x = this.leftPixels;
  5577. }
  5578. dstArea.width = width;
  5579. if (computeLayoutArea) {
  5580. dstArea.width += this.leftPixels;
  5581. }
  5582. dstOffset.z = sourceArea.width - (dstOffset.x + width);
  5583. break;
  5584. }
  5585. case PrimitiveAlignment.AlignRight:
  5586. {
  5587. if (isRightAuto) {
  5588. dstOffset.x = Math.round(sourceArea.width - width);
  5589. }
  5590. else {
  5591. this._computePixels(2, sourceArea, true);
  5592. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  5593. }
  5594. dstArea.width = width;
  5595. if (computeLayoutArea) {
  5596. dstArea.width += this.rightPixels;
  5597. }
  5598. dstOffset.z = this.rightPixels;
  5599. break;
  5600. }
  5601. case PrimitiveAlignment.AlignStretch:
  5602. {
  5603. if (isLeftAuto) {
  5604. dstOffset.x = 0;
  5605. }
  5606. else {
  5607. this._computePixels(1, sourceArea, true);
  5608. dstOffset.x = this.leftPixels;
  5609. }
  5610. var right = 0;
  5611. if (!isRightAuto) {
  5612. this._computePixels(2, sourceArea, true);
  5613. right = this.rightPixels;
  5614. }
  5615. dstArea.width = sourceArea.width - (dstOffset.x + right);
  5616. dstOffset.z = this.rightPixels;
  5617. break;
  5618. }
  5619. case PrimitiveAlignment.AlignCenter:
  5620. {
  5621. if (!isLeftAuto) {
  5622. this._computePixels(1, sourceArea, true);
  5623. }
  5624. if (!isRightAuto) {
  5625. this._computePixels(2, sourceArea, true);
  5626. }
  5627. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  5628. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  5629. dstArea.width = width;
  5630. dstOffset.z = sourceArea.width - (dstOffset.x + width);
  5631. break;
  5632. }
  5633. }
  5634. switch (alignment.vertical) {
  5635. case PrimitiveAlignment.AlignTop:
  5636. {
  5637. if (isTopAuto) {
  5638. dstOffset.y = sourceArea.height - height;
  5639. }
  5640. else {
  5641. this._computePixels(0, sourceArea, true);
  5642. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  5643. }
  5644. dstArea.height = height;
  5645. if (computeLayoutArea) {
  5646. dstArea.height += this.topPixels;
  5647. }
  5648. dstOffset.w = this.topPixels;
  5649. break;
  5650. }
  5651. case PrimitiveAlignment.AlignBottom:
  5652. {
  5653. if (isBottomAuto) {
  5654. dstOffset.y = 0;
  5655. }
  5656. else {
  5657. this._computePixels(3, sourceArea, true);
  5658. dstOffset.y = this.bottomPixels;
  5659. }
  5660. dstArea.height = height;
  5661. if (computeLayoutArea) {
  5662. dstArea.height += this.bottomPixels;
  5663. }
  5664. dstOffset.w = sourceArea.height - (dstOffset.y + height);
  5665. break;
  5666. }
  5667. case PrimitiveAlignment.AlignStretch:
  5668. {
  5669. if (isBottomAuto) {
  5670. dstOffset.y = 0;
  5671. }
  5672. else {
  5673. this._computePixels(3, sourceArea, true);
  5674. dstOffset.y = this.bottomPixels;
  5675. }
  5676. var top_1 = 0;
  5677. if (!isTopAuto) {
  5678. this._computePixels(0, sourceArea, true);
  5679. top_1 = this.topPixels;
  5680. }
  5681. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  5682. dstOffset.w = this.topPixels;
  5683. break;
  5684. }
  5685. case PrimitiveAlignment.AlignCenter:
  5686. {
  5687. if (!isTopAuto) {
  5688. this._computePixels(0, sourceArea, true);
  5689. }
  5690. if (!isBottomAuto) {
  5691. this._computePixels(3, sourceArea, true);
  5692. }
  5693. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  5694. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  5695. dstArea.height = height;
  5696. dstOffset.w = sourceArea.height - (dstOffset.y + height);
  5697. break;
  5698. }
  5699. }
  5700. };
  5701. /**
  5702. * Compute an area and its position considering this thickness properties based on a given source area
  5703. * @param sourceArea the source area
  5704. * @param dstOffset the position of the resulting area
  5705. * @param dstArea the size of the resulting area
  5706. */
  5707. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  5708. this._computePixels(0, sourceArea, true);
  5709. this._computePixels(1, sourceArea, true);
  5710. this._computePixels(2, sourceArea, true);
  5711. this._computePixels(3, sourceArea, true);
  5712. dstOffset.x = this.leftPixels;
  5713. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  5714. dstOffset.y = this.bottomPixels;
  5715. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  5716. dstOffset.z = this.rightPixels;
  5717. dstOffset.w = this.topPixels;
  5718. };
  5719. /**
  5720. * Compute an area considering this thickness properties based on a given source area
  5721. * @param sourceArea the source area
  5722. * @param result the resulting area
  5723. */
  5724. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  5725. this._computePixels(0, sourceArea, true);
  5726. this._computePixels(1, sourceArea, true);
  5727. this._computePixels(2, sourceArea, true);
  5728. this._computePixels(3, sourceArea, true);
  5729. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  5730. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  5731. };
  5732. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  5733. this._computePixels(0, sourceArea, true);
  5734. this._computePixels(1, sourceArea, true);
  5735. this._computePixels(2, sourceArea, true);
  5736. this._computePixels(3, sourceArea, true);
  5737. dstOffset.x = this.leftPixels;
  5738. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  5739. dstOffset.y = this.bottomPixels;
  5740. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  5741. dstOffset.z = this.rightPixels;
  5742. dstOffset.w = this.topPixels;
  5743. };
  5744. return PrimitiveThickness;
  5745. }());
  5746. PrimitiveThickness.Auto = 0x1;
  5747. PrimitiveThickness.Inherit = 0x2;
  5748. PrimitiveThickness.Percentage = 0x4;
  5749. PrimitiveThickness.Pixel = 0x8;
  5750. PrimitiveThickness = PrimitiveThickness_1 = __decorate([
  5751. BABYLON.className("PrimitiveThickness", "BABYLON")
  5752. ], PrimitiveThickness);
  5753. BABYLON.PrimitiveThickness = PrimitiveThickness;
  5754. /**
  5755. * Main class used for the Primitive Intersection API
  5756. */
  5757. var IntersectInfo2D = (function () {
  5758. function IntersectInfo2D() {
  5759. this.findFirstOnly = false;
  5760. this.intersectHidden = false;
  5761. this.pickPosition = BABYLON.Vector2.Zero();
  5762. }
  5763. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  5764. /**
  5765. * true if at least one primitive intersected during the test
  5766. */
  5767. get: function () {
  5768. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  5769. },
  5770. enumerable: true,
  5771. configurable: true
  5772. });
  5773. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  5774. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  5775. var cur = _a[_i];
  5776. if (cur.prim === prim) {
  5777. return cur.intersectionLocation;
  5778. }
  5779. }
  5780. return null;
  5781. };
  5782. // Internals, don't use
  5783. IntersectInfo2D.prototype._exit = function (firstLevel) {
  5784. if (firstLevel) {
  5785. this._globalPickPosition = null;
  5786. }
  5787. };
  5788. return IntersectInfo2D;
  5789. }());
  5790. BABYLON.IntersectInfo2D = IntersectInfo2D;
  5791. var Prim2DBase = Prim2DBase_1 = (function (_super) {
  5792. __extends(Prim2DBase, _super);
  5793. function Prim2DBase(settings) {
  5794. var _this = this;
  5795. // Avoid checking every time if the object exists
  5796. if (settings == null) {
  5797. settings = {};
  5798. }
  5799. // BASE CLASS CALL
  5800. _this = _super.call(this) || this;
  5801. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  5802. var owner;
  5803. var parent;
  5804. if (Prim2DBase_1._isCanvasInit) {
  5805. owner = _this;
  5806. parent = null;
  5807. _this._canvasPreInit(settings);
  5808. }
  5809. else {
  5810. if (settings.parent != null) {
  5811. parent = settings.parent;
  5812. owner = settings.parent.owner;
  5813. if (!owner) {
  5814. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  5815. }
  5816. 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)) {
  5817. 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");
  5818. }
  5819. }
  5820. }
  5821. // Fields initialization
  5822. _this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  5823. _this._size = null; //Size.Zero();
  5824. _this._scale = new BABYLON.Vector2(1, 1);
  5825. _this._actualSize = null;
  5826. _this._boundingSize = BABYLON.Size.Zero();
  5827. _this._layoutArea = BABYLON.Size.Zero();
  5828. _this._layoutAreaPos = null;
  5829. _this._layoutBoundingInfo = null;
  5830. _this._marginOffset = BABYLON.Vector4.Zero();
  5831. _this._paddingOffset = BABYLON.Vector4.Zero();
  5832. _this._parentPaddingOffset = BABYLON.Vector2.Zero();
  5833. _this._parentContentArea = BABYLON.Size.Zero();
  5834. _this._lastAutoSizeArea = BABYLON.Size.Zero();
  5835. _this._contentArea = new BABYLON.Size(null, null);
  5836. _this._pointerEventObservable = new BABYLON.Observable();
  5837. _this._owner = owner;
  5838. _this._parent = null;
  5839. _this._margin = null;
  5840. _this._padding = null;
  5841. _this._marginAlignment = null;
  5842. _this._id = settings.id;
  5843. _this._children = new Array();
  5844. _this._localTransform = new BABYLON.Matrix();
  5845. _this._globalTransform = null;
  5846. _this._invGlobalTransform = null;
  5847. _this._globalTransformProcessStep = 0;
  5848. _this._globalTransformStep = 0;
  5849. _this._renderGroup = null;
  5850. _this._primLinearPosition = 0;
  5851. _this._manualZOrder = null;
  5852. _this._zOrder = 0;
  5853. _this._zMax = 0;
  5854. _this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  5855. _this._actualOpacity = 0;
  5856. _this._actualScale = BABYLON.Vector2.Zero();
  5857. _this._displayDebugAreas = false;
  5858. _this._debugAreaGroup = null;
  5859. _this._primTriArray = null;
  5860. _this._primTriArrayDirty = true;
  5861. _this._levelBoundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  5862. _this._boundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  5863. var isPickable = true;
  5864. var isContainer = true;
  5865. if (settings.isPickable !== undefined) {
  5866. isPickable = settings.isPickable;
  5867. }
  5868. if (settings.isContainer !== undefined) {
  5869. isContainer = settings.isContainer;
  5870. }
  5871. if (settings.dontInheritParentScale) {
  5872. _this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  5873. }
  5874. _this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  5875. if (settings.opacity != null) {
  5876. _this._opacity = settings.opacity;
  5877. }
  5878. else {
  5879. _this._opacity = 1;
  5880. }
  5881. _this._updateRenderMode();
  5882. if (settings.childrenFlatZOrder) {
  5883. _this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  5884. }
  5885. // If the parent is given, initialize the hierarchy/owner related data
  5886. if (parent != null) {
  5887. parent.addChild(_this);
  5888. _this._hierarchyDepth = parent._hierarchyDepth + 1;
  5889. _this._patchHierarchy(parent.owner);
  5890. }
  5891. // If it's a group, detect its own states
  5892. if (_this.owner && _this instanceof BABYLON.Group2D) {
  5893. var group = _this;
  5894. group.detectGroupStates();
  5895. }
  5896. // Time to insert children if some are specified
  5897. if (settings.children != null) {
  5898. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  5899. var child = _a[_i];
  5900. _this.addChild(child);
  5901. // Good time to patch the hierarchy, it won't go very far if there's no need to
  5902. if (_this.owner != null && _this._hierarchyDepth != null) {
  5903. child._patchHierarchy(_this.owner);
  5904. }
  5905. }
  5906. }
  5907. if (settings.zOrder != null) {
  5908. _this.zOrder = settings.zOrder;
  5909. }
  5910. // Set the model related properties
  5911. if (settings.position != null) {
  5912. _this.position = settings.position;
  5913. }
  5914. else if (settings.x != null || settings.y != null) {
  5915. _this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  5916. }
  5917. else {
  5918. _this._position = null;
  5919. }
  5920. _this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  5921. if (settings.scale != null) {
  5922. _this.scale = settings.scale;
  5923. }
  5924. else {
  5925. if (settings.scaleX != null) {
  5926. _this.scaleX = settings.scaleX;
  5927. }
  5928. if (settings.scaleY != null) {
  5929. _this.scaleY = settings.scaleY;
  5930. }
  5931. }
  5932. _this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  5933. _this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  5934. // Layout Engine
  5935. if (settings.layoutEngine != null) {
  5936. if (typeof settings.layoutEngine === "string") {
  5937. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  5938. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  5939. _this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  5940. }
  5941. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  5942. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  5943. }
  5944. else if (name_1.indexOf("verticalstackpanel") === 0) {
  5945. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  5946. }
  5947. }
  5948. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  5949. _this.layoutEngine = settings.layoutEngine;
  5950. }
  5951. }
  5952. // Set the layout/margin stuffs
  5953. if (settings.marginTop) {
  5954. _this.margin.setTop(settings.marginTop);
  5955. }
  5956. if (settings.marginLeft) {
  5957. _this.margin.setLeft(settings.marginLeft);
  5958. }
  5959. if (settings.marginRight) {
  5960. _this.margin.setRight(settings.marginRight);
  5961. }
  5962. if (settings.marginBottom) {
  5963. _this.margin.setBottom(settings.marginBottom);
  5964. }
  5965. if (settings.margin) {
  5966. if (typeof settings.margin === "string") {
  5967. _this.margin.fromString(settings.margin);
  5968. }
  5969. else {
  5970. _this.margin.fromUniformPixels(settings.margin);
  5971. }
  5972. }
  5973. if (settings.marginHAlignment) {
  5974. _this.marginAlignment.horizontal = settings.marginHAlignment;
  5975. }
  5976. if (settings.marginVAlignment) {
  5977. _this.marginAlignment.vertical = settings.marginVAlignment;
  5978. }
  5979. if (settings.marginAlignment) {
  5980. _this.marginAlignment.fromString(settings.marginAlignment);
  5981. }
  5982. if (settings.paddingTop) {
  5983. _this.padding.setTop(settings.paddingTop);
  5984. }
  5985. if (settings.paddingLeft) {
  5986. _this.padding.setLeft(settings.paddingLeft);
  5987. }
  5988. if (settings.paddingRight) {
  5989. _this.padding.setRight(settings.paddingRight);
  5990. }
  5991. if (settings.paddingBottom) {
  5992. _this.padding.setBottom(settings.paddingBottom);
  5993. }
  5994. if (settings.padding) {
  5995. _this.padding.fromString(settings.padding);
  5996. }
  5997. if (settings.layoutData) {
  5998. var p = _this.parent;
  5999. if (p && p.layoutEngine) {
  6000. p.layoutEngine.newChild(_this, settings.layoutData);
  6001. }
  6002. }
  6003. // Dirty layout and positioning
  6004. _this._parentLayoutDirty();
  6005. _this._positioningDirty();
  6006. // Add in the PCM
  6007. if (settings.levelCollision || settings.deepCollision) {
  6008. _this._actorInfo = _this.owner._primitiveCollisionManager._addActor(_this, settings.deepCollision === true);
  6009. _this._setFlags(BABYLON.SmartPropertyPrim.flagCollisionActor);
  6010. }
  6011. else {
  6012. _this._actorInfo = null;
  6013. }
  6014. return _this;
  6015. }
  6016. Object.defineProperty(Prim2DBase.prototype, "intersectWithObservable", {
  6017. /**
  6018. * Return the ChangedDictionary observable of the StringDictionary containing the primitives intersecting with this one
  6019. */
  6020. get: function () {
  6021. if (!this._actorInfo) {
  6022. return null;
  6023. }
  6024. return this._actorInfo.intersectWith.dictionaryChanged;
  6025. },
  6026. enumerable: true,
  6027. configurable: true
  6028. });
  6029. Object.defineProperty(Prim2DBase.prototype, "intersectWith", {
  6030. /**
  6031. * Return the ObservableStringDictionary containing all the primitives intersecting with this one.
  6032. * The key is the primitive uid, the value is the ActorInfo object
  6033. * @returns {}
  6034. */
  6035. get: function () {
  6036. if (!this._actorInfo) {
  6037. return null;
  6038. }
  6039. return this._actorInfo.intersectWith;
  6040. },
  6041. enumerable: true,
  6042. configurable: true
  6043. });
  6044. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  6045. get: function () {
  6046. if (!this._actionManager) {
  6047. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  6048. }
  6049. return this._actionManager;
  6050. },
  6051. enumerable: true,
  6052. configurable: true
  6053. });
  6054. /**
  6055. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  6056. * @param predicate the predicate to test on each parent
  6057. * @return the first primitive where the predicate was successful
  6058. */
  6059. Prim2DBase.prototype.traverseUp = function (predicate) {
  6060. var p = this;
  6061. while (p != null) {
  6062. if (predicate(p)) {
  6063. return p;
  6064. }
  6065. p = p._parent;
  6066. }
  6067. return null;
  6068. };
  6069. Object.defineProperty(Prim2DBase.prototype, "owner", {
  6070. /**
  6071. * Retrieve the owner Canvas2D
  6072. */
  6073. get: function () {
  6074. return this._owner;
  6075. },
  6076. enumerable: true,
  6077. configurable: true
  6078. });
  6079. Object.defineProperty(Prim2DBase.prototype, "parent", {
  6080. /**
  6081. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  6082. */
  6083. get: function () {
  6084. return this._parent;
  6085. },
  6086. enumerable: true,
  6087. configurable: true
  6088. });
  6089. Object.defineProperty(Prim2DBase.prototype, "children", {
  6090. /**
  6091. * The array of direct children primitives
  6092. */
  6093. get: function () {
  6094. return this._children;
  6095. },
  6096. enumerable: true,
  6097. configurable: true
  6098. });
  6099. Object.defineProperty(Prim2DBase.prototype, "id", {
  6100. /**
  6101. * The identifier of this primitive, may not be unique, it's for information purpose only
  6102. */
  6103. get: function () {
  6104. return this._id;
  6105. },
  6106. set: function (value) {
  6107. if (this._id === value) {
  6108. return;
  6109. }
  6110. var oldValue = this._id;
  6111. this.onPropertyChanged("id", oldValue, this._id);
  6112. },
  6113. enumerable: true,
  6114. configurable: true
  6115. });
  6116. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  6117. get: function () {
  6118. if (this._actualPosition != null) {
  6119. return this._actualPosition;
  6120. }
  6121. if (this._position != null) {
  6122. return this._position;
  6123. }
  6124. // At least return 0,0, we can't return null on actualPosition
  6125. return Prim2DBase_1._nullPosition;
  6126. },
  6127. /**
  6128. * DO NOT INVOKE for internal purpose only
  6129. */
  6130. set: function (val) {
  6131. this._actualPosition = val;
  6132. },
  6133. enumerable: true,
  6134. configurable: true
  6135. });
  6136. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  6137. /**
  6138. * Shortcut to actualPosition.x
  6139. */
  6140. get: function () {
  6141. return this.actualPosition.x;
  6142. },
  6143. set: function (val) {
  6144. this._actualPosition.x = val;
  6145. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  6146. },
  6147. enumerable: true,
  6148. configurable: true
  6149. });
  6150. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  6151. /**
  6152. * Shortcut to actualPosition.y
  6153. */
  6154. get: function () {
  6155. return this.actualPosition.y;
  6156. },
  6157. set: function (val) {
  6158. this._actualPosition.y = val;
  6159. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  6160. },
  6161. enumerable: true,
  6162. configurable: true
  6163. });
  6164. Object.defineProperty(Prim2DBase.prototype, "position", {
  6165. /**
  6166. * Position of the primitive, relative to its parent.
  6167. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  6168. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  6169. * Setting this property may have no effect is specific alignment are in effect.
  6170. */
  6171. get: function () {
  6172. if (!this._position) {
  6173. this._position = BABYLON.Vector2.Zero();
  6174. }
  6175. return this._position;
  6176. },
  6177. set: function (value) {
  6178. if (!this._checkPositionChange()) {
  6179. return;
  6180. }
  6181. this._position = value;
  6182. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  6183. },
  6184. enumerable: true,
  6185. configurable: true
  6186. });
  6187. Object.defineProperty(Prim2DBase.prototype, "x", {
  6188. /**
  6189. * Direct access to the position.x value of the primitive
  6190. * Use this property when you only want to change one component of the position property
  6191. */
  6192. get: function () {
  6193. if (!this._position) {
  6194. return null;
  6195. }
  6196. return this._position.x;
  6197. },
  6198. set: function (value) {
  6199. if (!this._checkPositionChange()) {
  6200. return;
  6201. }
  6202. if (!this._position) {
  6203. this._position = BABYLON.Vector2.Zero();
  6204. }
  6205. if (this._position.x === value) {
  6206. return;
  6207. }
  6208. this._position.x = value;
  6209. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  6210. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  6211. },
  6212. enumerable: true,
  6213. configurable: true
  6214. });
  6215. Object.defineProperty(Prim2DBase.prototype, "y", {
  6216. /**
  6217. * Direct access to the position.y value of the primitive
  6218. * Use this property when you only want to change one component of the position property
  6219. */
  6220. get: function () {
  6221. if (!this._position) {
  6222. return null;
  6223. }
  6224. return this._position.y;
  6225. },
  6226. set: function (value) {
  6227. if (!this._checkPositionChange()) {
  6228. return;
  6229. }
  6230. if (!this._position) {
  6231. this._position = BABYLON.Vector2.Zero();
  6232. }
  6233. if (this._position.y === value) {
  6234. return;
  6235. }
  6236. this._position.y = value;
  6237. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  6238. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  6239. },
  6240. enumerable: true,
  6241. configurable: true
  6242. });
  6243. Object.defineProperty(Prim2DBase.prototype, "size", {
  6244. /**
  6245. * Size of the primitive or its bounding area
  6246. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  6247. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  6248. */
  6249. get: function () {
  6250. return this.internalGetSize();
  6251. },
  6252. set: function (value) {
  6253. this.internalSetSize(value);
  6254. },
  6255. enumerable: true,
  6256. configurable: true
  6257. });
  6258. Prim2DBase.prototype.internalGetSize = function () {
  6259. if (!this._size || this._size.width == null || this._size.height == null) {
  6260. if (Prim2DBase_1.boundinbBoxReentrency) {
  6261. return Prim2DBase_1.nullSize;
  6262. }
  6263. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  6264. return this._boundingSize;
  6265. }
  6266. Prim2DBase_1.boundinbBoxReentrency = true;
  6267. var b = this.boundingInfo;
  6268. Prim2DBase_1.boundinbBoxReentrency = false;
  6269. return this._boundingSize;
  6270. }
  6271. return this._size;
  6272. };
  6273. Prim2DBase.prototype.internalSetSize = function (value) {
  6274. this._size = value;
  6275. };
  6276. Object.defineProperty(Prim2DBase.prototype, "width", {
  6277. /**
  6278. * Direct access to the size.width value of the primitive
  6279. * Use this property when you only want to change one component of the size property
  6280. */
  6281. get: function () {
  6282. if (!this.size) {
  6283. return null;
  6284. }
  6285. return this.size.width;
  6286. },
  6287. set: function (value) {
  6288. if (this.size && this.size.width === value) {
  6289. return;
  6290. }
  6291. if (!this.size) {
  6292. this.size = new BABYLON.Size(value, 0);
  6293. }
  6294. else {
  6295. this.size.width = value;
  6296. }
  6297. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  6298. this._positioningDirty();
  6299. },
  6300. enumerable: true,
  6301. configurable: true
  6302. });
  6303. Object.defineProperty(Prim2DBase.prototype, "height", {
  6304. /**
  6305. * Direct access to the size.height value of the primitive
  6306. * Use this property when you only want to change one component of the size property
  6307. */
  6308. get: function () {
  6309. if (!this.size) {
  6310. return null;
  6311. }
  6312. return this.size.height;
  6313. },
  6314. set: function (value) {
  6315. if (this.size && this.size.height === value) {
  6316. return;
  6317. }
  6318. if (!this.size) {
  6319. this.size = new BABYLON.Size(0, value);
  6320. }
  6321. else {
  6322. this.size.height = value;
  6323. }
  6324. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  6325. this._positioningDirty();
  6326. },
  6327. enumerable: true,
  6328. configurable: true
  6329. });
  6330. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  6331. get: function () {
  6332. return this._rotation;
  6333. },
  6334. set: function (value) {
  6335. this._rotation = value;
  6336. },
  6337. enumerable: true,
  6338. configurable: true
  6339. });
  6340. Object.defineProperty(Prim2DBase.prototype, "scale", {
  6341. get: function () {
  6342. return this._scale.x;
  6343. },
  6344. set: function (value) {
  6345. this._scale.x = this._scale.y = value;
  6346. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6347. this._spreadActualScaleDirty();
  6348. },
  6349. enumerable: true,
  6350. configurable: true
  6351. });
  6352. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  6353. /**
  6354. * Return the size of the primitive as it's being rendered into the target.
  6355. * 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.
  6356. * BEWARE: don't use the setter, it's for internal purpose only
  6357. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  6358. */
  6359. get: function () {
  6360. if (this._actualSize) {
  6361. return this._actualSize;
  6362. }
  6363. return this._size;
  6364. },
  6365. set: function (value) {
  6366. if (this._actualSize.equals(value)) {
  6367. return;
  6368. }
  6369. this._actualSize = value;
  6370. },
  6371. enumerable: true,
  6372. configurable: true
  6373. });
  6374. Object.defineProperty(Prim2DBase.prototype, "actualWidth", {
  6375. /**
  6376. * Shortcut to actualSize.width
  6377. */
  6378. get: function () {
  6379. return this.actualSize.width;
  6380. },
  6381. set: function (val) {
  6382. this._actualSize.width = val;
  6383. this._triggerPropertyChanged(Prim2DBase_1.actualSizeProperty, this._actualSize);
  6384. },
  6385. enumerable: true,
  6386. configurable: true
  6387. });
  6388. Object.defineProperty(Prim2DBase.prototype, "actualHeight", {
  6389. /**
  6390. * Shortcut to actualPosition.height
  6391. */
  6392. get: function () {
  6393. return this.actualSize.height;
  6394. },
  6395. set: function (val) {
  6396. this._actualSize.height = val;
  6397. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualSize);
  6398. },
  6399. enumerable: true,
  6400. configurable: true
  6401. });
  6402. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  6403. get: function () {
  6404. if (this._manualZOrder != null) {
  6405. return this._manualZOrder;
  6406. }
  6407. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  6408. this._updateZOrder();
  6409. }
  6410. return (1 - this._zOrder);
  6411. },
  6412. enumerable: true,
  6413. configurable: true
  6414. });
  6415. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  6416. /**
  6417. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  6418. * The Primitive's size won't be less than specified.
  6419. * The default value depends of the Primitive type
  6420. */
  6421. get: function () {
  6422. return this._minSize;
  6423. },
  6424. set: function (value) {
  6425. if (this._minSize && value && this._minSize.equals(value)) {
  6426. return;
  6427. }
  6428. this._minSize = value;
  6429. this._parentLayoutDirty();
  6430. },
  6431. enumerable: true,
  6432. configurable: true
  6433. });
  6434. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  6435. /**
  6436. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  6437. * The Primitive's size won't be more than specified.
  6438. * The default value depends of the Primitive type
  6439. */
  6440. get: function () {
  6441. return this._maxSize;
  6442. },
  6443. set: function (value) {
  6444. if (this._maxSize && value && this._maxSize.equals(value)) {
  6445. return;
  6446. }
  6447. this._maxSize = value;
  6448. this._parentLayoutDirty();
  6449. },
  6450. enumerable: true,
  6451. configurable: true
  6452. });
  6453. Object.defineProperty(Prim2DBase.prototype, "origin", {
  6454. /**
  6455. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  6456. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  6457. * For instance:
  6458. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  6459. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  6460. * 0,1 means the center is top/left
  6461. * @returns The normalized center.
  6462. */
  6463. get: function () {
  6464. return this._origin;
  6465. },
  6466. set: function (value) {
  6467. this._origin = value;
  6468. },
  6469. enumerable: true,
  6470. configurable: true
  6471. });
  6472. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  6473. get: function () {
  6474. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  6475. },
  6476. set: function (value) {
  6477. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  6478. },
  6479. enumerable: true,
  6480. configurable: true
  6481. });
  6482. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  6483. get: function () {
  6484. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  6485. },
  6486. set: function (value) {
  6487. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  6488. },
  6489. enumerable: true,
  6490. configurable: true
  6491. });
  6492. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  6493. get: function () {
  6494. return this._manualZOrder;
  6495. },
  6496. set: function (value) {
  6497. if (this._manualZOrder === value) {
  6498. return;
  6499. }
  6500. this._manualZOrder = value;
  6501. this.onZOrderChanged();
  6502. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  6503. this._actualZOrderChangedObservable.notifyObservers(value);
  6504. }
  6505. },
  6506. enumerable: true,
  6507. configurable: true
  6508. });
  6509. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  6510. get: function () {
  6511. return this._manualZOrder != null;
  6512. },
  6513. enumerable: true,
  6514. configurable: true
  6515. });
  6516. Object.defineProperty(Prim2DBase.prototype, "margin", {
  6517. get: function () {
  6518. var _this = this;
  6519. if (!this._margin) {
  6520. this._margin = new PrimitiveThickness(function () {
  6521. if (!_this.parent) {
  6522. return null;
  6523. }
  6524. return _this.parent.margin;
  6525. }, function () { return _this._positioningDirty(); });
  6526. }
  6527. return this._margin;
  6528. },
  6529. set: function (value) {
  6530. this.margin.copyFrom(value);
  6531. },
  6532. enumerable: true,
  6533. configurable: true
  6534. });
  6535. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  6536. /**
  6537. * Check for both margin and marginAlignment, return true if at least one of them is specified with a non default value
  6538. */
  6539. get: function () {
  6540. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  6541. },
  6542. enumerable: true,
  6543. configurable: true
  6544. });
  6545. Object.defineProperty(Prim2DBase.prototype, "padding", {
  6546. get: function () {
  6547. var _this = this;
  6548. if (!this._padding) {
  6549. this._padding = new PrimitiveThickness(function () {
  6550. if (!_this.parent) {
  6551. return null;
  6552. }
  6553. return _this.parent.padding;
  6554. }, function () { return _this._positioningDirty(); });
  6555. }
  6556. return this._padding;
  6557. },
  6558. set: function (value) {
  6559. this.padding.copyFrom(value);
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  6565. get: function () {
  6566. return this._padding !== null && !this._padding.isDefault;
  6567. },
  6568. enumerable: true,
  6569. configurable: true
  6570. });
  6571. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  6572. get: function () {
  6573. var _this = this;
  6574. if (!this._marginAlignment) {
  6575. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  6576. }
  6577. return this._marginAlignment;
  6578. },
  6579. set: function (value) {
  6580. this.marginAlignment.copyFrom(value);
  6581. },
  6582. enumerable: true,
  6583. configurable: true
  6584. });
  6585. Object.defineProperty(Prim2DBase.prototype, "_hasMarginAlignment", {
  6586. /**
  6587. * Check if there a marginAlignment specified (non null and not default)
  6588. */
  6589. get: function () {
  6590. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  6591. },
  6592. enumerable: true,
  6593. configurable: true
  6594. });
  6595. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  6596. get: function () {
  6597. return this._opacity;
  6598. },
  6599. set: function (value) {
  6600. if (value < 0) {
  6601. value = 0;
  6602. }
  6603. else if (value > 1) {
  6604. value = 1;
  6605. }
  6606. if (this._opacity === value) {
  6607. return;
  6608. }
  6609. this._opacity = value;
  6610. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  6611. this._spreadActualOpacityChanged();
  6612. this._updateRenderMode();
  6613. },
  6614. enumerable: true,
  6615. configurable: true
  6616. });
  6617. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  6618. get: function () {
  6619. return this._scale.x;
  6620. },
  6621. set: function (value) {
  6622. this._scale.x = value;
  6623. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6624. this._spreadActualScaleDirty();
  6625. },
  6626. enumerable: true,
  6627. configurable: true
  6628. });
  6629. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  6630. get: function () {
  6631. return this._scale.y;
  6632. },
  6633. set: function (value) {
  6634. this._scale.y = value;
  6635. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6636. this._spreadActualScaleDirty();
  6637. },
  6638. enumerable: true,
  6639. configurable: true
  6640. });
  6641. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  6642. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  6643. var child = _a[_i];
  6644. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6645. child._spreadActualScaleDirty();
  6646. }
  6647. };
  6648. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  6649. /**
  6650. * 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
  6651. */
  6652. get: function () {
  6653. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  6654. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  6655. var sx = this.scaleX;
  6656. var sy = this.scaleY;
  6657. while (cur) {
  6658. sx *= cur.scaleX;
  6659. sy *= cur.scaleY;
  6660. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  6661. }
  6662. this._actualScale.copyFromFloats(sx, sy);
  6663. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  6664. }
  6665. return this._actualScale;
  6666. },
  6667. enumerable: true,
  6668. configurable: true
  6669. });
  6670. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  6671. /**
  6672. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  6673. */
  6674. get: function () {
  6675. return this.actualScale.x;
  6676. },
  6677. enumerable: true,
  6678. configurable: true
  6679. });
  6680. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  6681. /**
  6682. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  6683. */
  6684. get: function () {
  6685. return this.actualScale.y;
  6686. },
  6687. enumerable: true,
  6688. configurable: true
  6689. });
  6690. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  6691. /**
  6692. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  6693. */
  6694. get: function () {
  6695. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  6696. var cur = this.parent;
  6697. var op = this.opacity;
  6698. while (cur) {
  6699. op *= cur.opacity;
  6700. cur = cur.parent;
  6701. }
  6702. this._actualOpacity = op;
  6703. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  6704. }
  6705. return this._actualOpacity;
  6706. },
  6707. enumerable: true,
  6708. configurable: true
  6709. });
  6710. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  6711. /**
  6712. * Get/set the layout engine to use for this primitive.
  6713. * The default layout engine is the CanvasLayoutEngine.
  6714. */
  6715. get: function () {
  6716. if (!this._layoutEngine) {
  6717. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  6718. }
  6719. return this._layoutEngine;
  6720. },
  6721. set: function (value) {
  6722. if (this._layoutEngine === value) {
  6723. return;
  6724. }
  6725. this._changeLayoutEngine(value);
  6726. },
  6727. enumerable: true,
  6728. configurable: true
  6729. });
  6730. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  6731. /**
  6732. * Get/set the layout are of this primitive.
  6733. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  6734. * The setter should only be called by a Layout Engine class.
  6735. */
  6736. get: function () {
  6737. return this._layoutArea;
  6738. },
  6739. set: function (val) {
  6740. if (this._layoutArea.equals(val)) {
  6741. return;
  6742. }
  6743. this._positioningDirty();
  6744. if (this.parent) {
  6745. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  6746. }
  6747. this._layoutArea = val;
  6748. },
  6749. enumerable: true,
  6750. configurable: true
  6751. });
  6752. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  6753. /**
  6754. * Get/set the layout area position (relative to the parent primitive).
  6755. * The setter should only be called by a Layout Engine class.
  6756. */
  6757. get: function () {
  6758. if (!this._layoutAreaPos) {
  6759. this._layoutAreaPos = BABYLON.Vector2.Zero();
  6760. }
  6761. return this._layoutAreaPos;
  6762. },
  6763. set: function (val) {
  6764. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  6765. return;
  6766. }
  6767. if (this.parent) {
  6768. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  6769. }
  6770. this._positioningDirty();
  6771. this._layoutAreaPos = val;
  6772. },
  6773. enumerable: true,
  6774. configurable: true
  6775. });
  6776. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  6777. /**
  6778. * Define if the Primitive can be subject to intersection test or not (default is true)
  6779. */
  6780. get: function () {
  6781. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  6782. },
  6783. set: function (value) {
  6784. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  6785. },
  6786. enumerable: true,
  6787. configurable: true
  6788. });
  6789. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  6790. /**
  6791. * Define if the Primitive acts as a container or not
  6792. * A container will encapsulate its children for interaction event.
  6793. * If it's not a container events will be process down to children if the primitive is not pickable.
  6794. * Default value is true
  6795. */
  6796. get: function () {
  6797. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  6798. },
  6799. set: function (value) {
  6800. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  6801. },
  6802. enumerable: true,
  6803. configurable: true
  6804. });
  6805. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  6806. /**
  6807. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  6808. */
  6809. get: function () {
  6810. return this._hierarchyDepth;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  6816. /**
  6817. * Retrieve the Group that is responsible to render this primitive
  6818. */
  6819. get: function () {
  6820. return this._renderGroup;
  6821. },
  6822. enumerable: true,
  6823. configurable: true
  6824. });
  6825. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  6826. /**
  6827. * Get the global transformation matrix of the primitive
  6828. */
  6829. get: function () {
  6830. if (this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  6831. this.updateCachedStates(false);
  6832. }
  6833. return this._globalTransform;
  6834. },
  6835. enumerable: true,
  6836. configurable: true
  6837. });
  6838. /**
  6839. * return the global position of the primitive, relative to its canvas
  6840. */
  6841. Prim2DBase.prototype.getGlobalPosition = function () {
  6842. var v = new BABYLON.Vector2(0, 0);
  6843. this.getGlobalPositionByRef(v);
  6844. return v;
  6845. };
  6846. /**
  6847. * return the global position of the primitive, relative to its canvas
  6848. * @param v the valid Vector2 object where the global position will be stored
  6849. */
  6850. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  6851. v.x = this.globalTransform.m[12];
  6852. v.y = this.globalTransform.m[13];
  6853. };
  6854. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  6855. /**
  6856. * Get invert of the global transformation matrix of the primitive
  6857. */
  6858. get: function () {
  6859. this._updateLocalTransform();
  6860. return this._invGlobalTransform;
  6861. },
  6862. enumerable: true,
  6863. configurable: true
  6864. });
  6865. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  6866. /**
  6867. * Get the local transformation of the primitive
  6868. */
  6869. get: function () {
  6870. this._updateLocalTransform();
  6871. return this._localTransform;
  6872. },
  6873. enumerable: true,
  6874. configurable: true
  6875. });
  6876. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  6877. /**
  6878. * Get the boundingInfo associated to the primitive and its children.
  6879. * The value is supposed to be always up to date
  6880. */
  6881. get: function () {
  6882. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  6883. if (this.owner) {
  6884. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  6885. }
  6886. var sizedByContent = this.isSizedByContent;
  6887. if (sizedByContent) {
  6888. this._boundingInfo.clear();
  6889. }
  6890. else {
  6891. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  6892. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  6893. return this._boundingInfo;
  6894. }
  6895. }
  6896. var bi = this._boundingInfo;
  6897. var tps = new BABYLON.BoundingInfo2D();
  6898. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  6899. var curChild = _a[_i];
  6900. var bb = curChild.boundingInfo;
  6901. bb.transformToRef(curChild.localTransform, tps);
  6902. bi.unionToRef(tps, bi);
  6903. }
  6904. // If the size is determined by the content we have to update the contentArea
  6905. // and compute the size considering the padding (if any)
  6906. if (sizedByContent) {
  6907. bi.maxToRef(Prim2DBase_1._bMax);
  6908. this._contentArea.width = Prim2DBase_1._bMax.x;
  6909. this._contentArea.height = Prim2DBase_1._bMax.y;
  6910. if (this._hasPadding) {
  6911. var padding = this.padding;
  6912. var mm = Prim2DBase_1._bMinMax;
  6913. bi.minMaxToRef(mm);
  6914. mm.z += padding.leftPixels + padding.rightPixels;
  6915. mm.w += padding.bottomPixels + padding.topPixels;
  6916. this._paddingOffset.copyFromFloats(padding.leftPixels, padding.bottomPixels, padding.rightPixels, padding.topPixels);
  6917. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(mm.x, mm.z, mm.y, mm.w, bi);
  6918. }
  6919. }
  6920. this._boundingInfo.sizeToRef(Prim2DBase_1._bSize);
  6921. 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);
  6922. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  6923. }
  6924. return this._boundingInfo;
  6925. },
  6926. enumerable: true,
  6927. configurable: true
  6928. });
  6929. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  6930. /**
  6931. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  6932. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  6933. */
  6934. get: function () {
  6935. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  6936. if (!this._layoutBoundingInfo) {
  6937. this._layoutBoundingInfo = new BABYLON.BoundingInfo2D();
  6938. }
  6939. if (this.isSizedByContent) {
  6940. this._layoutBoundingInfo.clear();
  6941. }
  6942. else {
  6943. this._layoutBoundingInfo.copyFrom(this.levelBoundingInfo);
  6944. }
  6945. var bi = this._layoutBoundingInfo;
  6946. var tps = new BABYLON.BoundingInfo2D();
  6947. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  6948. var curChild = _a[_i];
  6949. var bb = void 0;
  6950. if (curChild._layoutAreaPos) {
  6951. var s = curChild._layoutArea;
  6952. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(0, s.width, 0, s.height, Prim2DBase_1._tpsBB);
  6953. bb = Prim2DBase_1._tpsBB;
  6954. }
  6955. else {
  6956. bb = curChild.boundingInfo;
  6957. }
  6958. bb.transformToRef(curChild.localTransform, tps);
  6959. bi.unionToRef(tps, bi);
  6960. }
  6961. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  6962. }
  6963. return this._layoutBoundingInfo;
  6964. },
  6965. enumerable: true,
  6966. configurable: true
  6967. });
  6968. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  6969. /**
  6970. * Determine if the size is automatically computed or fixed because manually specified.
  6971. * Use the actualSize property to get the final/real size of the primitive
  6972. * @returns true if the size is automatically computed, false if it were manually specified.
  6973. */
  6974. get: function () {
  6975. return this._size == null;
  6976. },
  6977. enumerable: true,
  6978. configurable: true
  6979. });
  6980. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  6981. /**
  6982. * Return true if this prim has an auto size which is set by the children's global bounding box
  6983. */
  6984. get: function () {
  6985. return (this._size == null) && (this._children.length > 0);
  6986. },
  6987. enumerable: true,
  6988. configurable: true
  6989. });
  6990. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  6991. /**
  6992. * Determine if the position is automatically computed or fixed because manually specified.
  6993. * Use the actualPosition property to get the final/real position of the primitive
  6994. * @returns true if the position is automatically computed, false if it were manually specified.
  6995. */
  6996. get: function () {
  6997. return this._position == null;
  6998. },
  6999. enumerable: true,
  7000. configurable: true
  7001. });
  7002. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  7003. /**
  7004. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  7005. */
  7006. get: function () {
  7007. return this._pointerEventObservable;
  7008. },
  7009. enumerable: true,
  7010. configurable: true
  7011. });
  7012. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  7013. get: function () {
  7014. if (!this._actualZOrderChangedObservable) {
  7015. this._actualZOrderChangedObservable = new BABYLON.Observable();
  7016. }
  7017. return this._actualZOrderChangedObservable;
  7018. },
  7019. enumerable: true,
  7020. configurable: true
  7021. });
  7022. Object.defineProperty(Prim2DBase.prototype, "displayDebugAreas", {
  7023. get: function () {
  7024. return this._displayDebugAreas;
  7025. },
  7026. set: function (value) {
  7027. if (this._displayDebugAreas === value) {
  7028. return;
  7029. }
  7030. if (value === false) {
  7031. this._debugAreaGroup.dispose();
  7032. this._debugAreaGroup = null;
  7033. }
  7034. else {
  7035. var layoutFill = "#F0808040"; // Red - Layout area
  7036. var layoutBorder = "#F08080FF";
  7037. var marginFill = "#F0F04040"; // Yellow - Margin area
  7038. var marginBorder = "#F0F040FF";
  7039. var paddingFill = "#F040F040"; // Magenta - Padding Area
  7040. var paddingBorder = "#F040F0FF";
  7041. var contentFill = "#40F0F040"; // Cyan - Content area
  7042. var contentBorder = "#40F0F0FF";
  7043. var s = new BABYLON.Size(10, 10);
  7044. var p = BABYLON.Vector2.Zero();
  7045. this._debugAreaGroup = new BABYLON.Group2D({ dontInheritParentScale: true,
  7046. parent: (this.parent != null) ? this.parent : this, id: "###DEBUG AREA GROUP###", children: [
  7047. new BABYLON.Group2D({
  7048. id: "###Layout Area###", position: p, size: s, children: [
  7049. new BABYLON.Rectangle2D({ id: "###Layout Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: layoutBorder }),
  7050. new BABYLON.Rectangle2D({ id: "###Layout Top###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  7051. new BABYLON.Rectangle2D({ id: "###Layout Left###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  7052. new BABYLON.Rectangle2D({ id: "###Layout Right###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  7053. new BABYLON.Rectangle2D({ id: "###Layout Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill })
  7054. ]
  7055. }),
  7056. new BABYLON.Group2D({
  7057. id: "###Margin Area###", position: p, size: s, children: [
  7058. new BABYLON.Rectangle2D({ id: "###Margin Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: marginBorder }),
  7059. new BABYLON.Rectangle2D({ id: "###Margin Top###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  7060. new BABYLON.Rectangle2D({ id: "###Margin Left###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  7061. new BABYLON.Rectangle2D({ id: "###Margin Right###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  7062. new BABYLON.Rectangle2D({ id: "###Margin Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill })
  7063. ]
  7064. }),
  7065. new BABYLON.Group2D({
  7066. id: "###Padding Area###", position: p, size: s, children: [
  7067. new BABYLON.Rectangle2D({ id: "###Padding Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: paddingBorder }),
  7068. new BABYLON.Rectangle2D({ id: "###Padding Top###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  7069. new BABYLON.Rectangle2D({ id: "###Padding Left###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  7070. new BABYLON.Rectangle2D({ id: "###Padding Right###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  7071. new BABYLON.Rectangle2D({ id: "###Padding Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill })
  7072. ]
  7073. }),
  7074. new BABYLON.Group2D({
  7075. id: "###Content Area###", position: p, size: s, children: [
  7076. new BABYLON.Rectangle2D({ id: "###Content Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: contentBorder }),
  7077. new BABYLON.Rectangle2D({ id: "###Content Top###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  7078. new BABYLON.Rectangle2D({ id: "###Content Left###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  7079. new BABYLON.Rectangle2D({ id: "###Content Right###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  7080. new BABYLON.Rectangle2D({ id: "###Content Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill })
  7081. ]
  7082. })
  7083. ]
  7084. });
  7085. this._debugAreaGroup._setFlags(BABYLON.SmartPropertyPrim.flagNoPartOfLayout);
  7086. this._updateDebugArea();
  7087. }
  7088. this._displayDebugAreas = value;
  7089. },
  7090. enumerable: true,
  7091. configurable: true
  7092. });
  7093. Prim2DBase.prototype._updateDebugArea = function () {
  7094. var areaNames = ["Layout", "Margin", "Padding", "Content"];
  7095. var areaZones = ["Area", "Frame", "Top", "Left", "Right", "Bottom"];
  7096. var prims = new Array(4);
  7097. // Get all the primitives used to display the areas
  7098. for (var i = 0; i < 4; i++) {
  7099. prims[i] = new Array(6);
  7100. for (var j = 0; j < 6; j++) {
  7101. prims[i][j] = this._debugAreaGroup.findById("###" + areaNames[i] + " " + areaZones[j] + "###");
  7102. if (j > 1) {
  7103. prims[i][j].levelVisible = false;
  7104. }
  7105. }
  7106. }
  7107. // Update the visibility status of layout/margin/padding
  7108. var hasLayout = this._layoutAreaPos != null;
  7109. var hasPos = (this.actualPosition.x !== 0) || (this.actualPosition.y !== 0);
  7110. var hasMargin = this._hasMargin;
  7111. var hasPadding = this._hasPadding;
  7112. prims[0][0].levelVisible = hasLayout;
  7113. prims[1][0].levelVisible = hasMargin;
  7114. prims[2][0].levelVisible = hasPadding;
  7115. prims[3][0].levelVisible = true;
  7116. // Current offset
  7117. var curOffset = BABYLON.Vector2.Zero();
  7118. // Store the area info of the layout area
  7119. var curAreaIndex = 0;
  7120. // Store data about each area
  7121. var areaInfo = new Array(4);
  7122. var storeAreaInfo = function (pos, size) {
  7123. var min = pos.clone();
  7124. var max = pos.clone();
  7125. if (size.width > 0) {
  7126. max.x += size.width;
  7127. }
  7128. if (size.height > 0) {
  7129. max.y += size.height;
  7130. }
  7131. areaInfo[curAreaIndex++] = { off: pos, size: size, min: min, max: max };
  7132. };
  7133. var isCanvas = this instanceof BABYLON.Canvas2D;
  7134. var marginH = this._marginOffset.x + this._marginOffset.z;
  7135. var marginV = this._marginOffset.y + this._marginOffset.w;
  7136. var actualSize = this.actualSize.multiplyByFloats(isCanvas ? 1 : this.scaleX, isCanvas ? 1 : this.scaleY);
  7137. var w = hasLayout ? (this.layoutAreaPos.x + this.layoutArea.width) : (marginH + actualSize.width);
  7138. var h = hasLayout ? (this.layoutAreaPos.y + this.layoutArea.height) : (marginV + actualSize.height);
  7139. var pos = (!hasLayout && !hasMargin && !hasPadding && hasPos) ? this.actualPosition : BABYLON.Vector2.Zero();
  7140. storeAreaInfo(pos, new BABYLON.Size(w, h));
  7141. // Compute the layout related data
  7142. if (hasLayout) {
  7143. var layoutOffset = this.layoutAreaPos.clone();
  7144. storeAreaInfo(layoutOffset, (hasMargin || hasPadding) ? this.layoutArea.clone() : actualSize.clone());
  7145. curOffset = layoutOffset.clone();
  7146. }
  7147. // Compute margin data
  7148. if (hasMargin) {
  7149. var marginOffset = curOffset.clone();
  7150. marginOffset.x += this._marginOffset.x;
  7151. marginOffset.y += this._marginOffset.y;
  7152. var marginArea = actualSize;
  7153. storeAreaInfo(marginOffset, marginArea);
  7154. curOffset = marginOffset.clone();
  7155. }
  7156. if (hasPadding) {
  7157. var contentOffset = curOffset.clone();
  7158. contentOffset.x += this._paddingOffset.x;
  7159. contentOffset.y += this._paddingOffset.y;
  7160. var contentArea = this.contentArea;
  7161. storeAreaInfo(contentOffset, contentArea);
  7162. curOffset = curOffset.add(contentOffset);
  7163. }
  7164. // Helper function that set the pos and size of a given prim
  7165. var setArea = function (i, j, pos, size) {
  7166. prims[i][j].position = pos;
  7167. prims[i][j].size = size;
  7168. };
  7169. var setFullRect = function (i, pos, size) {
  7170. var plist = prims[i];
  7171. plist[2].levelVisible = true;
  7172. plist[3].levelVisible = false;
  7173. plist[4].levelVisible = false;
  7174. plist[5].levelVisible = false;
  7175. setArea(i, 1, pos, size);
  7176. setArea(i, 2, pos, size);
  7177. };
  7178. var setQuadRect = function (i, areaIndex) {
  7179. var plist = prims[i];
  7180. plist[2].levelVisible = true;
  7181. plist[3].levelVisible = true;
  7182. plist[4].levelVisible = true;
  7183. plist[5].levelVisible = true;
  7184. var ca = areaInfo[areaIndex];
  7185. var na = areaInfo[areaIndex + 1];
  7186. var tp = new BABYLON.Vector2(ca.min.x, na.max.y);
  7187. var ts = new BABYLON.Size(ca.size.width, ca.max.y - tp.y);
  7188. var lp = new BABYLON.Vector2(ca.min.x, na.min.y);
  7189. var ls = new BABYLON.Size(na.min.x - ca.min.x, na.max.y - na.min.y);
  7190. var rp = new BABYLON.Vector2(na.max.x, na.min.y);
  7191. var rs = new BABYLON.Size(ca.max.x - na.max.x, na.max.y - na.min.y);
  7192. var bp = new BABYLON.Vector2(ca.min.x, ca.min.y);
  7193. var bs = new BABYLON.Size(ca.size.width, na.min.y - ca.min.y);
  7194. // Frame
  7195. plist[1].position = ca.off;
  7196. plist[1].size = ca.size;
  7197. // Top rect
  7198. plist[2].position = tp;
  7199. plist[2].size = ts;
  7200. // Left rect
  7201. plist[3].position = lp;
  7202. plist[3].size = ls;
  7203. // Right rect
  7204. plist[4].position = rp;
  7205. plist[4].size = rs;
  7206. // Bottom rect
  7207. plist[5].position = bp;
  7208. plist[5].size = bs;
  7209. };
  7210. var areaCount = curAreaIndex;
  7211. curAreaIndex = 0;
  7212. // Available zones
  7213. var availableZones = [false, hasLayout, hasMargin, hasPadding, true];
  7214. for (var k = 1; k < 5; k++) {
  7215. if (availableZones[k]) {
  7216. var ai = areaInfo[curAreaIndex];
  7217. setArea(k - 1, 0, BABYLON.Vector2.Zero(), ai.size);
  7218. // setArea(k-1, 1, Vector2.Zero(), ai.size);
  7219. if (k === 4) {
  7220. setFullRect(k - 1, ai.off, ai.size);
  7221. }
  7222. else {
  7223. setQuadRect(k - 1, curAreaIndex);
  7224. }
  7225. ++curAreaIndex;
  7226. }
  7227. }
  7228. };
  7229. Prim2DBase.prototype.findById = function (id) {
  7230. if (this._id === id) {
  7231. return this;
  7232. }
  7233. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7234. var child = _a[_i];
  7235. var r = child.findById(id);
  7236. if (r != null) {
  7237. return r;
  7238. }
  7239. }
  7240. };
  7241. Prim2DBase.prototype.onZOrderChanged = function () {
  7242. };
  7243. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  7244. return false;
  7245. };
  7246. /**
  7247. * Capture all the Events of the given PointerId for this primitive.
  7248. * Don't forget to call releasePointerEventsCapture when done.
  7249. * @param pointerId the Id of the pointer to capture the events from.
  7250. */
  7251. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  7252. return this.owner._setPointerCapture(pointerId, this);
  7253. };
  7254. /**
  7255. * Release a captured pointer made with setPointerEventCapture.
  7256. * @param pointerId the Id of the pointer to release the capture from.
  7257. */
  7258. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  7259. return this.owner._releasePointerCapture(pointerId, this);
  7260. };
  7261. /**
  7262. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  7263. * @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.
  7264. */
  7265. Prim2DBase.prototype.intersect = function (intersectInfo) {
  7266. if (!intersectInfo) {
  7267. return false;
  7268. }
  7269. // If this is null it means this method is call for the first level, initialize stuffs
  7270. var firstLevel = !intersectInfo._globalPickPosition;
  7271. if (firstLevel) {
  7272. // 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).
  7273. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  7274. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  7275. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  7276. intersectInfo.intersectedPrimitives = new Array();
  7277. intersectInfo.topMostIntersectedPrimitive = null;
  7278. }
  7279. if (!Prim2DBase_1._bypassGroup2DExclusion && this instanceof BABYLON.Group2D && this.isCachedGroup && !this.isRenderableGroup) {
  7280. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7281. intersectInfo._exit(firstLevel);
  7282. return false;
  7283. }
  7284. if (!intersectInfo.intersectHidden && !this.isVisible) {
  7285. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7286. intersectInfo._exit(firstLevel);
  7287. return false;
  7288. }
  7289. var id = this.id;
  7290. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  7291. try {
  7292. Prim2DBase_1._bypassGroup2DExclusion = true;
  7293. var ownerGroup = this.getExternalData("__cachedGroup__");
  7294. return ownerGroup.intersect(intersectInfo);
  7295. }
  7296. finally {
  7297. Prim2DBase_1._bypassGroup2DExclusion = false;
  7298. }
  7299. }
  7300. // 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).
  7301. var isIntersectionTest = false;
  7302. if (this instanceof BABYLON.Group2D) {
  7303. var g = this;
  7304. isIntersectionTest = g.isCachedGroup;
  7305. }
  7306. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  7307. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7308. intersectInfo._exit(firstLevel);
  7309. return false;
  7310. }
  7311. // Fast rejection test with boundingInfo
  7312. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  7313. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  7314. intersectInfo._exit(firstLevel);
  7315. return false;
  7316. }
  7317. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  7318. var levelIntersectRes = false;
  7319. if (this.isPickable) {
  7320. levelIntersectRes = this.levelIntersect(intersectInfo);
  7321. if (levelIntersectRes) {
  7322. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  7323. intersectInfo.intersectedPrimitives.push(pii);
  7324. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  7325. intersectInfo.topMostIntersectedPrimitive = pii;
  7326. }
  7327. // If we must stop at the first intersection, we're done, quit!
  7328. if (intersectInfo.findFirstOnly) {
  7329. intersectInfo._exit(firstLevel);
  7330. return true;
  7331. }
  7332. }
  7333. }
  7334. // Recurse to children if needed
  7335. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  7336. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7337. var curChild = _a[_i];
  7338. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  7339. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  7340. continue;
  7341. }
  7342. // Must compute the localPickLocation for the children level
  7343. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  7344. // If we got an intersection with the child and we only need to find the first one, quit!
  7345. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  7346. intersectInfo._exit(firstLevel);
  7347. return true;
  7348. }
  7349. }
  7350. }
  7351. intersectInfo._exit(firstLevel);
  7352. return intersectInfo.isIntersected;
  7353. };
  7354. Prim2DBase.prototype.intersectOtherPrim = function (other) {
  7355. var setA = this.triList;
  7356. var setB = other.triList;
  7357. return BABYLON.Tri2DArray.doesIntersect(setA, setB, other.globalTransform.multiply(this.globalTransform.clone().invert()));
  7358. };
  7359. Object.defineProperty(Prim2DBase.prototype, "triList", {
  7360. get: function () {
  7361. if (this._primTriArrayDirty) {
  7362. this.updateTriArray();
  7363. this._primTriArrayDirty = false;
  7364. }
  7365. return this._primTriArray;
  7366. },
  7367. enumerable: true,
  7368. configurable: true
  7369. });
  7370. // 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
  7371. Prim2DBase.prototype.updateTriArray = function () {
  7372. if (this._primTriArray == null) {
  7373. this._primTriArray = new BABYLON.Tri2DArray(2);
  7374. }
  7375. else {
  7376. this._primTriArray.clear(2);
  7377. }
  7378. var size = this.actualSize;
  7379. var lb = new BABYLON.Vector2(0, 0);
  7380. var rt = new BABYLON.Vector2(size.width, size.height);
  7381. var lt = new BABYLON.Vector2(0, size.height);
  7382. var rb = new BABYLON.Vector2(size.width, 0);
  7383. this._primTriArray.storeTriangle(0, lb, lt, rt);
  7384. this._primTriArray.storeTriangle(1, lb, rt, rb);
  7385. };
  7386. /**
  7387. * Move a child object into a new position regarding its siblings to change its rendering order.
  7388. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  7389. * @param child the object to move
  7390. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  7391. */
  7392. Prim2DBase.prototype.moveChild = function (child, previous) {
  7393. if (child.parent !== this) {
  7394. return false;
  7395. }
  7396. var childIndex = this._children.indexOf(child);
  7397. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  7398. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  7399. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7400. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  7401. }
  7402. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  7403. return true;
  7404. };
  7405. /**
  7406. * Move the given child so it's displayed on the top of all its siblings
  7407. * @param child the primitive to move to the top
  7408. */
  7409. Prim2DBase.prototype.moveChildToTop = function (child) {
  7410. return this.moveChild(child, this._children[this._children.length - 1]);
  7411. };
  7412. /**
  7413. * Move the given child so it's displayed on the bottom of all its siblings
  7414. * @param child the primitive to move to the top
  7415. */
  7416. Prim2DBase.prototype.moveChildToBottom = function (child) {
  7417. return this.moveChild(child, null);
  7418. };
  7419. /**
  7420. * Move this primitive to be at the top among all its sibling
  7421. */
  7422. Prim2DBase.prototype.moveToTop = function () {
  7423. if (this.parent == null) {
  7424. return false;
  7425. }
  7426. return this.parent.moveChildToTop(this);
  7427. };
  7428. /**
  7429. * Move this primitive to be at the bottom among all its sibling
  7430. */
  7431. Prim2DBase.prototype.moveToBottom = function () {
  7432. if (this.parent == null) {
  7433. return false;
  7434. }
  7435. return this.parent.moveChildToBottom(this);
  7436. };
  7437. Prim2DBase.prototype.addChild = function (child) {
  7438. child._parent = this;
  7439. this._boundingBoxDirty();
  7440. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7441. if (flat) {
  7442. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7443. child._setZOrder(this._zOrder, true);
  7444. child._zMax = this._zOrder;
  7445. }
  7446. else {
  7447. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7448. }
  7449. var length = this._children.push(child);
  7450. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  7451. };
  7452. /**
  7453. * Dispose the primitive, remove it from its parent.
  7454. */
  7455. Prim2DBase.prototype.dispose = function () {
  7456. if (!_super.prototype.dispose.call(this)) {
  7457. return false;
  7458. }
  7459. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagCollisionActor)) {
  7460. this.owner._primitiveCollisionManager._removeActor(this);
  7461. this._actorInfo = null;
  7462. }
  7463. if (this._pointerEventObservable) {
  7464. this._pointerEventObservable.clear();
  7465. this._pointerEventObservable = null;
  7466. }
  7467. if (this._actionManager) {
  7468. this._actionManager.dispose();
  7469. this._actionManager = null;
  7470. }
  7471. this.owner.scene.stopAnimation(this);
  7472. // If there's a parent, remove this object from its parent list
  7473. if (this._parent) {
  7474. if (this instanceof BABYLON.Group2D) {
  7475. var g = this;
  7476. if (g.isRenderableGroup) {
  7477. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  7478. if (parentRenderable != null) {
  7479. var l = parentRenderable._renderableData._childrenRenderableGroups;
  7480. var i_1 = l.indexOf(g);
  7481. if (i_1 !== -1) {
  7482. l.splice(i_1, 1);
  7483. }
  7484. }
  7485. }
  7486. }
  7487. var i = this._parent._children.indexOf(this);
  7488. if (i !== undefined) {
  7489. this._parent._children.splice(i, 1);
  7490. }
  7491. this._parent = null;
  7492. }
  7493. // Recurse dispose to children
  7494. if (this._children) {
  7495. while (this._children.length > 0) {
  7496. this._children[this._children.length - 1].dispose();
  7497. }
  7498. }
  7499. return true;
  7500. };
  7501. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  7502. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  7503. this._renderGroup._addPrimToDirtyList(this);
  7504. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  7505. }
  7506. };
  7507. Prim2DBase.prototype._needPrepare = function () {
  7508. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagModelUpdate | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  7509. };
  7510. Prim2DBase.prototype._prepareRender = function (context) {
  7511. this._prepareRenderPre(context);
  7512. this._prepareRenderPost(context);
  7513. };
  7514. Prim2DBase.prototype._prepareRenderPre = function (context) {
  7515. };
  7516. Prim2DBase.prototype._prepareRenderPost = function (context) {
  7517. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  7518. if (this instanceof BABYLON.Group2D) {
  7519. var self = this;
  7520. if (self.isRenderableGroup) {
  7521. return;
  7522. }
  7523. }
  7524. // Check if we need to recurse the prepare to children primitives
  7525. // - must have children
  7526. // - the global transform of this level have changed, or
  7527. // - the visible state of primitive has changed
  7528. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  7529. this.checkPropertiesDirty(Prim2DBase_1.isVisibleProperty.flagId))) {
  7530. this._children.forEach(function (c) {
  7531. // As usual stop the recursion if we meet a renderable group
  7532. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  7533. c._prepareRender(context);
  7534. }
  7535. });
  7536. }
  7537. // Finally reset the dirty flags as we've processed everything
  7538. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  7539. this._instanceDirtyFlags = 0;
  7540. };
  7541. Prim2DBase.prototype._canvasPreInit = function (settings) {
  7542. };
  7543. Prim2DBase.CheckParent = function (parent) {
  7544. //if (!Prim2DBase._isCanvasInit && !parent) {
  7545. // 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)");
  7546. //}
  7547. };
  7548. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  7549. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  7550. var cur = list_1[_i];
  7551. cur.updateCachedStates(recurse);
  7552. }
  7553. };
  7554. Prim2DBase.prototype._parentLayoutDirty = function () {
  7555. if (!this._parent || this._parent.isDisposed) {
  7556. return;
  7557. }
  7558. this._parent._setLayoutDirty();
  7559. };
  7560. Prim2DBase.prototype._setLayoutDirty = function () {
  7561. this.onPrimBecomesDirty();
  7562. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  7563. };
  7564. Prim2DBase.prototype._checkPositionChange = function () {
  7565. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  7566. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  7567. return false;
  7568. }
  7569. return true;
  7570. };
  7571. Prim2DBase.prototype._positioningDirty = function () {
  7572. this.onPrimBecomesDirty();
  7573. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7574. };
  7575. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  7576. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7577. var child = _a[_i];
  7578. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  7579. child._updateRenderMode();
  7580. child.onPrimBecomesDirty();
  7581. child._spreadActualOpacityChanged();
  7582. }
  7583. };
  7584. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  7585. this._layoutEngine = engine;
  7586. };
  7587. Prim2DBase.prototype._updateLocalTransform = function () {
  7588. 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;
  7589. if (this.checkPropertiesDirty(tflags)) {
  7590. if (this.owner) {
  7591. this.owner.addupdateLocalTransformCounter(1);
  7592. }
  7593. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  7594. var local;
  7595. var pos = this._position ? this.position : this.layoutAreaPos;
  7596. if (this._origin.x === 0 && this._origin.y === 0) {
  7597. 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));
  7598. this._localTransform = local;
  7599. }
  7600. else {
  7601. // -Origin offset
  7602. var as = this.actualSize;
  7603. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase_1._t0);
  7604. // -Origin * rotation
  7605. rot.toRotationMatrix(Prim2DBase_1._t1);
  7606. Prim2DBase_1._t0.multiplyToRef(Prim2DBase_1._t1, Prim2DBase_1._t2);
  7607. // -Origin * rotation * scale
  7608. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase_1._t0);
  7609. Prim2DBase_1._t2.multiplyToRef(Prim2DBase_1._t0, Prim2DBase_1._t1);
  7610. // -Origin * rotation * scale * (Origin + Position)
  7611. 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);
  7612. Prim2DBase_1._t1.multiplyToRef(Prim2DBase_1._t2, this._localTransform);
  7613. }
  7614. this.clearPropertiesDirty(tflags);
  7615. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7616. return true;
  7617. }
  7618. return false;
  7619. };
  7620. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  7621. if (this.isDisposed) {
  7622. return;
  7623. }
  7624. this.owner.addCachedGroupRenderCounter(1);
  7625. // Check if the parent is synced
  7626. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  7627. this._parent.updateCachedStates(false);
  7628. }
  7629. // Update Z-Order if needed
  7630. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7631. this._updateZOrder();
  7632. }
  7633. // Update actualSize only if there' not positioning to recompute and the size changed
  7634. // Otherwise positioning will take care of it.
  7635. var sizeDirty = this.checkPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  7636. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  7637. var size = this.size;
  7638. if (size) {
  7639. if (this.size.width != null) {
  7640. this.actualSize.width = this.size.width;
  7641. }
  7642. if (this.size.height != null) {
  7643. this.actualSize.height = this.size.height;
  7644. }
  7645. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  7646. }
  7647. }
  7648. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7649. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7650. // Check for layout update
  7651. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  7652. this.owner.addUpdateLayoutCounter(1);
  7653. this._layoutEngine.updateLayout(this);
  7654. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  7655. }
  7656. var autoContentChanged = false;
  7657. if (this.isSizeAuto) {
  7658. if (!this._lastAutoSizeArea) {
  7659. autoContentChanged = this.actualSize !== null;
  7660. }
  7661. else {
  7662. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  7663. }
  7664. }
  7665. // Check for positioning update
  7666. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  7667. this._updatePositioning();
  7668. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7669. if (sizeDirty) {
  7670. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  7671. }
  7672. positioningComputed = true;
  7673. }
  7674. if (positioningComputed && this._parent) {
  7675. this._parentContentArea.copyFrom(this._parent.contentArea);
  7676. }
  7677. // Check if we must update this prim
  7678. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  7679. this.owner.addUpdateGlobalTransformCounter(1);
  7680. var curVisibleState = this.isVisible;
  7681. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  7682. // Detect a change of visibility
  7683. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  7684. // Get/compute the localTransform
  7685. var localDirty = this._updateLocalTransform();
  7686. var parentPaddingChanged = false;
  7687. var parentPaddingOffset = Prim2DBase_1._v0;
  7688. if (this._parent) {
  7689. parentPaddingOffset = new BABYLON.Vector2(this._parent._paddingOffset.x, this._parent._paddingOffset.y);
  7690. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  7691. }
  7692. // Check if there are changes in the parent that will force us to update the global matrix
  7693. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  7694. // Check if we have to update the globalTransform
  7695. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  7696. var globalTransform = this._parent ? this._parent._globalTransform : null;
  7697. var localTransform = void 0;
  7698. Prim2DBase_1._transMtx.copyFrom(this._localTransform);
  7699. Prim2DBase_1._transMtx.m[12] += parentPaddingOffset.x;
  7700. Prim2DBase_1._transMtx.m[13] += parentPaddingOffset.y;
  7701. localTransform = Prim2DBase_1._transMtx;
  7702. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  7703. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  7704. this._levelBoundingInfo.dirtyWorldAABB();
  7705. this._boundingInfo.dirtyWorldAABB();
  7706. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  7707. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  7708. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7709. }
  7710. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  7711. }
  7712. if (recurse) {
  7713. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7714. var child = _a[_i];
  7715. // Stop the recursion if we meet a renderable group
  7716. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  7717. }
  7718. }
  7719. };
  7720. Prim2DBase.prototype._updatePositioning = function () {
  7721. if (this.owner) {
  7722. this.owner.addUpdatePositioningCounter(1);
  7723. }
  7724. // From this point we assume that the primitive layoutArea is computed and up to date.
  7725. // We know have to :
  7726. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  7727. // 2. Determine the contentArea based on the padding property.
  7728. var isSizeAuto = this.isSizeAuto;
  7729. // 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
  7730. if (!this._hasMarginAlignment && (isSizeAuto || (this.actualSize.width == null || this.actualSize.height == null))) {
  7731. if (isSizeAuto || this.actualSize.width == null) {
  7732. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  7733. }
  7734. if (isSizeAuto || this.actualSize.height == null) {
  7735. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  7736. }
  7737. }
  7738. // Apply margin
  7739. if (this._hasMargin) {
  7740. this.margin.computeWithAlignment(this.layoutArea, this.size || this.actualSize, this.marginAlignment, this._marginOffset, Prim2DBase_1._size);
  7741. this.actualSize = Prim2DBase_1._size.clone();
  7742. }
  7743. if (this._hasPadding) {
  7744. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so we resize the primitive itself
  7745. if (isSizeAuto) {
  7746. // Changing the padding has resize the prim, which forces us to recompute margin again
  7747. if (this._hasMargin) {
  7748. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase_1._size, this.marginAlignment, this._marginOffset, Prim2DBase_1._size);
  7749. }
  7750. }
  7751. else {
  7752. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase_1._icZone, Prim2DBase_1._icArea);
  7753. Prim2DBase_1._icArea.width = Math.max(0, Prim2DBase_1._icArea.width);
  7754. Prim2DBase_1._icArea.height = Math.max(0, Prim2DBase_1._icArea.height);
  7755. this.padding.compute(Prim2DBase_1._icArea, this._paddingOffset, Prim2DBase_1._size);
  7756. this._paddingOffset.x += Prim2DBase_1._icZone.x;
  7757. this._paddingOffset.y += Prim2DBase_1._icZone.y;
  7758. this._paddingOffset.z -= Prim2DBase_1._icZone.z;
  7759. this._paddingOffset.w -= Prim2DBase_1._icZone.w;
  7760. this._contentArea.copyFrom(Prim2DBase_1._size);
  7761. }
  7762. }
  7763. else {
  7764. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase_1._icZone, Prim2DBase_1._icArea);
  7765. Prim2DBase_1._icArea.width = Math.max(0, Prim2DBase_1._icArea.width);
  7766. Prim2DBase_1._icArea.height = Math.max(0, Prim2DBase_1._icArea.height);
  7767. this._paddingOffset.x = Prim2DBase_1._icZone.x;
  7768. this._paddingOffset.y = Prim2DBase_1._icZone.y;
  7769. this._paddingOffset.z = Prim2DBase_1._icZone.z;
  7770. this._paddingOffset.w = Prim2DBase_1._icZone.w;
  7771. this._contentArea.copyFrom(Prim2DBase_1._icArea);
  7772. }
  7773. if (!this._position) {
  7774. var aPos = new BABYLON.Vector2(this.layoutAreaPos.x + this._marginOffset.x, this.layoutAreaPos.y + this._marginOffset.y);
  7775. this.actualPosition = aPos;
  7776. }
  7777. if (isSizeAuto) {
  7778. this._lastAutoSizeArea = this.actualSize;
  7779. }
  7780. if (this.displayDebugAreas) {
  7781. this._updateDebugArea();
  7782. }
  7783. };
  7784. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  7785. /**
  7786. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  7787. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  7788. */
  7789. get: function () {
  7790. if (!this._size || this._size.width == null || this._size.height == null) {
  7791. if (Prim2DBase_1.boundinbBoxReentrency) {
  7792. return Prim2DBase_1.nullSize;
  7793. }
  7794. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  7795. return this._contentArea;
  7796. }
  7797. Prim2DBase_1.boundinbBoxReentrency = true;
  7798. var b = this.boundingInfo;
  7799. Prim2DBase_1.boundinbBoxReentrency = false;
  7800. return this._contentArea;
  7801. }
  7802. else
  7803. // Check for positioning update
  7804. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  7805. this._updatePositioning();
  7806. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  7807. }
  7808. return this._contentArea;
  7809. },
  7810. enumerable: true,
  7811. configurable: true
  7812. });
  7813. Prim2DBase.prototype._patchHierarchy = function (owner) {
  7814. this._owner = owner;
  7815. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  7816. if (this._renderGroup != null) {
  7817. return;
  7818. }
  7819. if (this instanceof BABYLON.Group2D) {
  7820. var group = this;
  7821. group.detectGroupStates();
  7822. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  7823. group.owner._registerTrackedNode(this);
  7824. }
  7825. }
  7826. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  7827. if (this._parent) {
  7828. this._parentLayoutDirty();
  7829. }
  7830. // Make sure the prim is in the dirtyList if it should be
  7831. if (this._renderGroup && this.isDirty) {
  7832. var list = this._renderGroup._renderableData._primDirtyList;
  7833. var i = list.indexOf(this);
  7834. if (i === -1) {
  7835. list.push(this);
  7836. }
  7837. }
  7838. // Recurse
  7839. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7840. var child = _a[_i];
  7841. child._hierarchyDepth = this._hierarchyDepth + 1;
  7842. child._patchHierarchy(owner);
  7843. }
  7844. };
  7845. Prim2DBase.prototype._updateZOrder = function () {
  7846. var prevLinPos = this._primLinearPosition;
  7847. var startI = 0;
  7848. var startZ = this._zOrder;
  7849. // 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
  7850. var childrenCount = this._children.length;
  7851. if (this._firstZDirtyIndex > 0) {
  7852. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  7853. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  7854. prevLinPos = prevPrim._primLinearPosition;
  7855. startI = this._firstZDirtyIndex - 1;
  7856. startZ = prevPrim._zOrder;
  7857. }
  7858. }
  7859. var startPos = prevLinPos;
  7860. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  7861. Prim2DBase_1._totalCount = 0;
  7862. for (var i = startI; i < childrenCount; i++) {
  7863. var child = this._children[i];
  7864. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  7865. }
  7866. // Compute the new Z-Order for all the primitives
  7867. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  7868. var zDelta = (this._zMax - startZ) / (Prim2DBase_1._totalCount * (Prim2DBase_1._zRebuildReentrency ? 1 : 1.2));
  7869. // 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.
  7870. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  7871. // 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...
  7872. if (Prim2DBase_1._zRebuildReentrency) {
  7873. var p = this._parent;
  7874. if (p == null) {
  7875. // 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...)
  7876. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  7877. Prim2DBase_1._zRebuildReentrency = false;
  7878. return;
  7879. }
  7880. p._firstZDirtyIndex = 0;
  7881. return p._updateZOrder();
  7882. }
  7883. Prim2DBase_1._zRebuildReentrency = true;
  7884. this._firstZDirtyIndex = 0;
  7885. this._updateZOrder();
  7886. Prim2DBase_1._zRebuildReentrency = false;
  7887. }
  7888. for (var i = startI; i < childrenCount; i++) {
  7889. var child = this._children[i];
  7890. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  7891. }
  7892. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  7893. for (var _i = 0, _a = Prim2DBase_1._zOrderChangedNotifList; _i < _a.length; _i++) {
  7894. var p = _a[_i];
  7895. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  7896. }
  7897. Prim2DBase_1._zOrderChangedNotifList.splice(0);
  7898. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  7899. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7900. };
  7901. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  7902. if (this.isManualZOrder) {
  7903. return prevLinPos;
  7904. }
  7905. this._primLinearPosition = ++prevLinPos;
  7906. Prim2DBase_1._totalCount++;
  7907. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  7908. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  7909. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7910. var child = _a[_i];
  7911. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  7912. }
  7913. }
  7914. return prevLinPos;
  7915. };
  7916. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  7917. if (this.isManualZOrder) {
  7918. return null;
  7919. }
  7920. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  7921. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  7922. this._setZOrder(newZ, false);
  7923. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7924. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  7925. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7926. }
  7927. var curZ = newZ;
  7928. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  7929. if (isFlat) {
  7930. if (this._children.length > 0) {
  7931. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  7932. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7933. var child = _a[_i];
  7934. child._updatePrimitiveFlatZOrder(this._zOrder);
  7935. }
  7936. }
  7937. }
  7938. else {
  7939. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  7940. var child = _c[_b];
  7941. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  7942. if (r != null) {
  7943. curZ = r;
  7944. }
  7945. }
  7946. }
  7947. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  7948. return curZ;
  7949. };
  7950. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  7951. if (this.isManualZOrder) {
  7952. return;
  7953. }
  7954. this._setZOrder(newZ, false);
  7955. this._zMax = newZ;
  7956. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7957. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  7958. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  7959. }
  7960. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7961. var child = _a[_i];
  7962. child._updatePrimitiveFlatZOrder(newZ);
  7963. }
  7964. };
  7965. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  7966. if (newZ !== this._zOrder) {
  7967. this._zOrder = newZ;
  7968. this.onPrimBecomesDirty();
  7969. this.onZOrderChanged();
  7970. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  7971. if (directEmit) {
  7972. this._actualZOrderChangedObservable.notifyObservers(newZ);
  7973. }
  7974. else {
  7975. Prim2DBase_1._zOrderChangedNotifList.push(this);
  7976. }
  7977. }
  7978. }
  7979. };
  7980. Prim2DBase.prototype._updateRenderMode = function () {
  7981. };
  7982. /**
  7983. * This method is used to alter the contentArea of the Primitive before margin is applied.
  7984. * 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.
  7985. * @param primSize the current size of the primitive
  7986. * @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
  7987. * @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!
  7988. */
  7989. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  7990. initialContentArea.copyFrom(primSize);
  7991. initialContentPosition.x = initialContentPosition.y = initialContentPosition.z = initialContentPosition.w = 0;
  7992. };
  7993. /**
  7994. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  7995. * Check the Rectangle2D implementation for a concrete application.
  7996. * @param primSize the current size of the primitive
  7997. * @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!
  7998. */
  7999. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  8000. newPrimSize.copyFrom(primSize);
  8001. };
  8002. return Prim2DBase;
  8003. }(BABYLON.SmartPropertyPrim));
  8004. Prim2DBase.PRIM2DBASE_PROPCOUNT = 25;
  8005. Prim2DBase._bigInt = Math.pow(2, 30);
  8006. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  8007. Prim2DBase.boundinbBoxReentrency = false;
  8008. Prim2DBase.nullSize = BABYLON.Size.Zero();
  8009. Prim2DBase._bMinMax = BABYLON.Vector4.Zero();
  8010. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  8011. Prim2DBase._bSize = BABYLON.Size.Zero();
  8012. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  8013. Prim2DBase._bypassGroup2DExclusion = false;
  8014. Prim2DBase._isCanvasInit = false;
  8015. Prim2DBase._t0 = new BABYLON.Matrix();
  8016. Prim2DBase._t1 = new BABYLON.Matrix();
  8017. Prim2DBase._t2 = new BABYLON.Matrix();
  8018. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  8019. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  8020. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  8021. Prim2DBase._icZone = BABYLON.Vector4.Zero();
  8022. Prim2DBase._icArea = BABYLON.Size.Zero();
  8023. Prim2DBase._size = BABYLON.Size.Zero();
  8024. Prim2DBase._zOrderChangedNotifList = new Array();
  8025. Prim2DBase._zRebuildReentrency = false;
  8026. Prim2DBase._totalCount = 0;
  8027. __decorate([
  8028. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase_1.actualPositionProperty = pi; }, false, false, true)
  8029. ], Prim2DBase.prototype, "actualPosition", null);
  8030. __decorate([
  8031. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 1, function (pi) { return Prim2DBase_1.actualXProperty = pi; }, false, false, true)
  8032. ], Prim2DBase.prototype, "actualX", null);
  8033. __decorate([
  8034. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 2, function (pi) { return Prim2DBase_1.actualYProperty = pi; }, false, false, true)
  8035. ], Prim2DBase.prototype, "actualY", null);
  8036. __decorate([
  8037. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 3, function (pi) { return Prim2DBase_1.positionProperty = pi; }, false, false, true)
  8038. ], Prim2DBase.prototype, "position", null);
  8039. __decorate([
  8040. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 4, function (pi) { return Prim2DBase_1.xProperty = pi; }, false, false, true)
  8041. ], Prim2DBase.prototype, "x", null);
  8042. __decorate([
  8043. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 5, function (pi) { return Prim2DBase_1.yProperty = pi; }, false, false, true)
  8044. ], Prim2DBase.prototype, "y", null);
  8045. __decorate([
  8046. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 6, function (pi) { return Prim2DBase_1.sizeProperty = pi; }, false, true)
  8047. ], Prim2DBase.prototype, "size", null);
  8048. __decorate([
  8049. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 7, function (pi) { return Prim2DBase_1.widthProperty = pi; }, false, true)
  8050. ], Prim2DBase.prototype, "width", null);
  8051. __decorate([
  8052. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 8, function (pi) { return Prim2DBase_1.heightProperty = pi; }, false, true)
  8053. ], Prim2DBase.prototype, "height", null);
  8054. __decorate([
  8055. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 9, function (pi) { return Prim2DBase_1.rotationProperty = pi; }, false, true)
  8056. ], Prim2DBase.prototype, "rotation", null);
  8057. __decorate([
  8058. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 10, function (pi) { return Prim2DBase_1.scaleProperty = pi; }, false, true)
  8059. ], Prim2DBase.prototype, "scale", null);
  8060. __decorate([
  8061. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 11, function (pi) { return Prim2DBase_1.actualSizeProperty = pi; }, false, true)
  8062. ], Prim2DBase.prototype, "actualSize", null);
  8063. __decorate([
  8064. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 12, function (pi) { return Prim2DBase_1.actualWidthProperty = pi; }, false, true)
  8065. ], Prim2DBase.prototype, "actualWidth", null);
  8066. __decorate([
  8067. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 13, function (pi) { return Prim2DBase_1.actualHeightProperty = pi; }, false, true)
  8068. ], Prim2DBase.prototype, "actualHeight", null);
  8069. __decorate([
  8070. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 14, function (pi) { return Prim2DBase_1.originProperty = pi; }, false, true)
  8071. ], Prim2DBase.prototype, "origin", null);
  8072. __decorate([
  8073. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 15, function (pi) { return Prim2DBase_1.levelVisibleProperty = pi; })
  8074. ], Prim2DBase.prototype, "levelVisible", null);
  8075. __decorate([
  8076. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 16, function (pi) { return Prim2DBase_1.isVisibleProperty = pi; })
  8077. ], Prim2DBase.prototype, "isVisible", null);
  8078. __decorate([
  8079. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 17, function (pi) { return Prim2DBase_1.zOrderProperty = pi; })
  8080. ], Prim2DBase.prototype, "zOrder", null);
  8081. __decorate([
  8082. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 18, function (pi) { return Prim2DBase_1.marginProperty = pi; })
  8083. ], Prim2DBase.prototype, "margin", null);
  8084. __decorate([
  8085. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 19, function (pi) { return Prim2DBase_1.paddingProperty = pi; })
  8086. ], Prim2DBase.prototype, "padding", null);
  8087. __decorate([
  8088. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 20, function (pi) { return Prim2DBase_1.marginAlignmentProperty = pi; })
  8089. ], Prim2DBase.prototype, "marginAlignment", null);
  8090. __decorate([
  8091. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 21, function (pi) { return Prim2DBase_1.opacityProperty = pi; })
  8092. ], Prim2DBase.prototype, "opacity", null);
  8093. __decorate([
  8094. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 22, function (pi) { return Prim2DBase_1.scaleXProperty = pi; }, false, true)
  8095. ], Prim2DBase.prototype, "scaleX", null);
  8096. __decorate([
  8097. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 23, function (pi) { return Prim2DBase_1.scaleYProperty = pi; }, false, true)
  8098. ], Prim2DBase.prototype, "scaleY", null);
  8099. __decorate([
  8100. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 24, function (pi) { return Prim2DBase_1.actualScaleProperty = pi; }, false, true)
  8101. ], Prim2DBase.prototype, "actualScale", null);
  8102. Prim2DBase = Prim2DBase_1 = __decorate([
  8103. BABYLON.className("Prim2DBase", "BABYLON")
  8104. ], Prim2DBase);
  8105. BABYLON.Prim2DBase = Prim2DBase;
  8106. var PrimitiveAlignment_1, PrimitiveThickness_1, Prim2DBase_1;
  8107. })(BABYLON || (BABYLON = {}));
  8108. //# sourceMappingURL=babylon.prim2dBase.js.map
  8109. var __extends = (this && this.__extends) || function (d, b) {
  8110. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8111. function __() { this.constructor = d; }
  8112. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  8113. };
  8114. var BABYLON;
  8115. (function (BABYLON) {
  8116. var GroupInstanceInfo = (function () {
  8117. function GroupInstanceInfo(owner, mrc, partCount) {
  8118. this._partCount = partCount;
  8119. this.owner = owner;
  8120. this.modelRenderCache = mrc;
  8121. this.modelRenderCache.addRef();
  8122. this.partIndexFromId = new BABYLON.StringDictionary();
  8123. this._usedShaderCategories = new Array(partCount);
  8124. this._strides = new Array(partCount);
  8125. this._opaqueData = null;
  8126. this._alphaTestData = null;
  8127. this._transparentData = null;
  8128. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  8129. }
  8130. GroupInstanceInfo.prototype.dispose = function () {
  8131. if (this._isDisposed) {
  8132. return false;
  8133. }
  8134. if (this.modelRenderCache) {
  8135. this.modelRenderCache.dispose();
  8136. this.modelRenderCache = null;
  8137. }
  8138. var engine = this.owner.owner.engine;
  8139. if (this._opaqueData) {
  8140. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  8141. this._opaqueData = null;
  8142. }
  8143. if (this._alphaTestData) {
  8144. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  8145. this._alphaTestData = null;
  8146. }
  8147. if (this._transparentData) {
  8148. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  8149. this._transparentData = null;
  8150. }
  8151. this.partIndexFromId = null;
  8152. this._isDisposed = true;
  8153. return true;
  8154. };
  8155. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  8156. get: function () {
  8157. return this._opaqueData != null;
  8158. },
  8159. enumerable: true,
  8160. configurable: true
  8161. });
  8162. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  8163. get: function () {
  8164. return this._alphaTestData != null;
  8165. },
  8166. enumerable: true,
  8167. configurable: true
  8168. });
  8169. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  8170. get: function () {
  8171. return this._transparentData != null;
  8172. },
  8173. enumerable: true,
  8174. configurable: true
  8175. });
  8176. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  8177. get: function () {
  8178. if (!this._opaqueData) {
  8179. this._opaqueData = new Array(this._partCount);
  8180. for (var i = 0; i < this._partCount; i++) {
  8181. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  8182. }
  8183. }
  8184. return this._opaqueData;
  8185. },
  8186. enumerable: true,
  8187. configurable: true
  8188. });
  8189. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  8190. get: function () {
  8191. if (!this._alphaTestData) {
  8192. this._alphaTestData = new Array(this._partCount);
  8193. for (var i = 0; i < this._partCount; i++) {
  8194. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  8195. }
  8196. }
  8197. return this._alphaTestData;
  8198. },
  8199. enumerable: true,
  8200. configurable: true
  8201. });
  8202. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  8203. get: function () {
  8204. if (!this._transparentData) {
  8205. this._transparentData = new Array(this._partCount);
  8206. for (var i = 0; i < this._partCount; i++) {
  8207. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  8208. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  8209. }
  8210. }
  8211. return this._transparentData;
  8212. },
  8213. enumerable: true,
  8214. configurable: true
  8215. });
  8216. GroupInstanceInfo.prototype.sortTransparentData = function () {
  8217. if (!this.transparentOrderDirty) {
  8218. return;
  8219. }
  8220. for (var i = 0; i < this._transparentData.length; i++) {
  8221. var td = this._transparentData[i];
  8222. td._partData.sort();
  8223. }
  8224. this.transparentOrderDirty = false;
  8225. };
  8226. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  8227. get: function () {
  8228. return this._usedShaderCategories;
  8229. },
  8230. enumerable: true,
  8231. configurable: true
  8232. });
  8233. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  8234. get: function () {
  8235. return this._strides;
  8236. },
  8237. enumerable: true,
  8238. configurable: true
  8239. });
  8240. return GroupInstanceInfo;
  8241. }());
  8242. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  8243. var TransparentSegment = (function () {
  8244. function TransparentSegment() {
  8245. this.groupInsanceInfo = null;
  8246. this.startZ = 0;
  8247. this.endZ = 0;
  8248. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  8249. this.endDataIndex = 0;
  8250. this.partBuffers = null;
  8251. }
  8252. TransparentSegment.prototype.dispose = function (engine) {
  8253. if (this.partBuffers) {
  8254. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  8255. this.partBuffers.splice(0);
  8256. this.partBuffers = null;
  8257. }
  8258. };
  8259. return TransparentSegment;
  8260. }());
  8261. BABYLON.TransparentSegment = TransparentSegment;
  8262. var GroupInfoPartData = (function () {
  8263. function GroupInfoPartData(stride) {
  8264. this._partData = null;
  8265. this._partBuffer = null;
  8266. this._partBufferSize = 0;
  8267. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  8268. this._isDisposed = false;
  8269. }
  8270. GroupInfoPartData.prototype.dispose = function (engine) {
  8271. if (this._isDisposed) {
  8272. return false;
  8273. }
  8274. if (this._partBuffer) {
  8275. engine._releaseBuffer(this._partBuffer);
  8276. this._partBuffer = null;
  8277. }
  8278. this._partData = null;
  8279. this._isDisposed = true;
  8280. };
  8281. return GroupInfoPartData;
  8282. }());
  8283. BABYLON.GroupInfoPartData = GroupInfoPartData;
  8284. var TransparentGroupInfoPartData = (function (_super) {
  8285. __extends(TransparentGroupInfoPartData, _super);
  8286. function TransparentGroupInfoPartData(stride, zoff) {
  8287. var _this = _super.call(this, stride) || this;
  8288. _this._partData.compareValueOffset = zoff;
  8289. _this._partData.sortingAscending = false;
  8290. return _this;
  8291. }
  8292. return TransparentGroupInfoPartData;
  8293. }(GroupInfoPartData));
  8294. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  8295. var ModelRenderCache = (function () {
  8296. function ModelRenderCache(engine, modelKey) {
  8297. this._engine = engine;
  8298. this._modelKey = modelKey;
  8299. this._nextKey = 1;
  8300. this._refCounter = 1;
  8301. this._partData = null;
  8302. }
  8303. ModelRenderCache.prototype.dispose = function () {
  8304. if (--this._refCounter !== 0) {
  8305. return false;
  8306. }
  8307. // Remove the Model Render Cache from the global dictionary
  8308. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  8309. if (edata) {
  8310. edata.DisposeModelRenderCache(this);
  8311. }
  8312. return true;
  8313. };
  8314. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  8315. get: function () {
  8316. return this._refCounter <= 0;
  8317. },
  8318. enumerable: true,
  8319. configurable: true
  8320. });
  8321. ModelRenderCache.prototype.addRef = function () {
  8322. return ++this._refCounter;
  8323. };
  8324. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  8325. get: function () {
  8326. return this._modelKey;
  8327. },
  8328. enumerable: true,
  8329. configurable: true
  8330. });
  8331. ModelRenderCache.prototype.updateModelRenderCache = function (prim) {
  8332. return false;
  8333. };
  8334. /**
  8335. * Render the model instances
  8336. * @param instanceInfo
  8337. * @param context
  8338. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  8339. */
  8340. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  8341. return true;
  8342. };
  8343. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  8344. for (var i = 0; i < this._partData.length; i++) {
  8345. if (this._partData[i]._partId === partId) {
  8346. return i;
  8347. }
  8348. }
  8349. return null;
  8350. };
  8351. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  8352. var i = this.getPartIndexFromId(partId);
  8353. if (i === null) {
  8354. return null;
  8355. }
  8356. var ci = this._partsClassInfo[i];
  8357. var categories = this._partData[i]._partUsedCategories;
  8358. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  8359. return res;
  8360. };
  8361. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  8362. var pd = this._partData[partIndex];
  8363. var offset = (pd._partDataStride / 4) * elementCount;
  8364. var pci = this._partsClassInfo[partIndex];
  8365. var self = this;
  8366. pci.fullContent.forEach(function (k, v) {
  8367. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  8368. switch (v.dataType) {
  8369. case 4 /* float */:
  8370. {
  8371. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8372. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  8373. break;
  8374. }
  8375. case 0 /* Vector2 */:
  8376. {
  8377. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8378. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  8379. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  8380. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  8381. break;
  8382. }
  8383. case 5 /* Color3 */:
  8384. case 1 /* Vector3 */:
  8385. {
  8386. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8387. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  8388. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  8389. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  8390. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  8391. break;
  8392. }
  8393. case 6 /* Color4 */:
  8394. case 2 /* Vector4 */:
  8395. {
  8396. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  8397. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  8398. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  8399. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  8400. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  8401. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  8402. break;
  8403. }
  8404. default:
  8405. }
  8406. }
  8407. });
  8408. };
  8409. return ModelRenderCache;
  8410. }());
  8411. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  8412. // let i = this.getPartIndexFromId(partId);
  8413. // if (i === null) {
  8414. // return null;
  8415. // }
  8416. // let pci = this._partsClassInfo[i];
  8417. // pci.fullContent.forEach((k, v) => {
  8418. // if (uniforms.indexOf(v.attributeName) !== -1) {
  8419. // v.uniformLocation = effect.getUniform(v.attributeName);
  8420. // }
  8421. // });
  8422. //}
  8423. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  8424. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  8425. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  8426. BABYLON.ModelRenderCache = ModelRenderCache;
  8427. var ModelRenderCachePartData = (function () {
  8428. function ModelRenderCachePartData() {
  8429. }
  8430. return ModelRenderCachePartData;
  8431. }());
  8432. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  8433. })(BABYLON || (BABYLON = {}));
  8434. //# sourceMappingURL=babylon.modelRenderCache.js.map
  8435. var __extends = (this && this.__extends) || function (d, b) {
  8436. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  8437. function __() { this.constructor = d; }
  8438. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  8439. };
  8440. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  8441. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  8442. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8443. 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;
  8444. return c > 3 && r && Object.defineProperty(target, key, r), r;
  8445. };
  8446. var BABYLON;
  8447. (function (BABYLON) {
  8448. var InstanceClassInfo = (function () {
  8449. function InstanceClassInfo(base) {
  8450. this._baseInfo = base;
  8451. this._nextOffset = new BABYLON.StringDictionary();
  8452. this._attributes = new Array();
  8453. }
  8454. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  8455. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  8456. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  8457. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  8458. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  8459. if (push) {
  8460. this._attributes.push(propInfo);
  8461. }
  8462. };
  8463. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  8464. var catInline = ";" + categories.join(";") + ";";
  8465. var res = new Array();
  8466. var curInfo = this;
  8467. while (curInfo) {
  8468. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  8469. var attrib = _a[_i];
  8470. // 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
  8471. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  8472. var index = effect.getAttributeLocationByName(attrib.attributeName);
  8473. if (index === -1) {
  8474. throw new Error("Attribute " + attrib.attributeName + " was not found in Effect: " + effect.name + ". It's certainly no longer used in the Effect's Shaders");
  8475. }
  8476. var iai = new BABYLON.InstancingAttributeInfo();
  8477. iai.index = index;
  8478. 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)
  8479. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  8480. iai.attributeName = attrib.attributeName;
  8481. res.push(iai);
  8482. }
  8483. }
  8484. curInfo = curInfo._baseInfo;
  8485. }
  8486. return res;
  8487. };
  8488. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  8489. var res = new Array();
  8490. var curInfo = this;
  8491. while (curInfo) {
  8492. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  8493. var attrib = _a[_i];
  8494. // 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
  8495. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  8496. res.push(attrib.attributeName);
  8497. }
  8498. }
  8499. curInfo = curInfo._baseInfo;
  8500. }
  8501. return res;
  8502. };
  8503. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  8504. var curOffset = 0;
  8505. var curBase = this._baseInfo;
  8506. while (curBase) {
  8507. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  8508. curBase = curBase._baseInfo;
  8509. }
  8510. return curOffset;
  8511. };
  8512. return InstanceClassInfo;
  8513. }());
  8514. BABYLON.InstanceClassInfo = InstanceClassInfo;
  8515. var InstancePropInfo = (function () {
  8516. function InstancePropInfo() {
  8517. this.instanceOffset = new BABYLON.StringDictionary();
  8518. }
  8519. InstancePropInfo.prototype.setSize = function (val) {
  8520. if (val instanceof BABYLON.Vector2) {
  8521. this.size = 8;
  8522. this.dataType = 0 /* Vector2 */;
  8523. return;
  8524. }
  8525. if (val instanceof BABYLON.Vector3) {
  8526. this.size = 12;
  8527. this.dataType = 1 /* Vector3 */;
  8528. return;
  8529. }
  8530. if (val instanceof BABYLON.Vector4) {
  8531. this.size = 16;
  8532. this.dataType = 2 /* Vector4 */;
  8533. return;
  8534. }
  8535. if (val instanceof BABYLON.Matrix) {
  8536. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  8537. }
  8538. if (typeof (val) === "number") {
  8539. this.size = 4;
  8540. this.dataType = 4 /* float */;
  8541. return;
  8542. }
  8543. if (val instanceof BABYLON.Color3) {
  8544. this.size = 12;
  8545. this.dataType = 5 /* Color3 */;
  8546. return;
  8547. }
  8548. if (val instanceof BABYLON.Color4) {
  8549. this.size = 16;
  8550. this.dataType = 6 /* Color4 */;
  8551. return;
  8552. }
  8553. if (val instanceof BABYLON.Size) {
  8554. this.size = 8;
  8555. this.dataType = 7 /* Size */;
  8556. return;
  8557. }
  8558. return;
  8559. };
  8560. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  8561. switch (this.dataType) {
  8562. case 0 /* Vector2 */:
  8563. {
  8564. var v = val;
  8565. array[offset + 0] = v.x;
  8566. array[offset + 1] = v.y;
  8567. break;
  8568. }
  8569. case 1 /* Vector3 */:
  8570. {
  8571. var v = val;
  8572. array[offset + 0] = v.x;
  8573. array[offset + 1] = v.y;
  8574. array[offset + 2] = v.z;
  8575. break;
  8576. }
  8577. case 2 /* Vector4 */:
  8578. {
  8579. var v = val;
  8580. array[offset + 0] = v.x;
  8581. array[offset + 1] = v.y;
  8582. array[offset + 2] = v.z;
  8583. array[offset + 3] = v.w;
  8584. break;
  8585. }
  8586. case 5 /* Color3 */:
  8587. {
  8588. var v = val;
  8589. array[offset + 0] = v.r;
  8590. array[offset + 1] = v.g;
  8591. array[offset + 2] = v.b;
  8592. break;
  8593. }
  8594. case 6 /* Color4 */:
  8595. {
  8596. var v = val;
  8597. array[offset + 0] = v.r;
  8598. array[offset + 1] = v.g;
  8599. array[offset + 2] = v.b;
  8600. array[offset + 3] = v.a;
  8601. break;
  8602. }
  8603. case 4 /* float */:
  8604. {
  8605. var v = val;
  8606. array[offset] = v;
  8607. break;
  8608. }
  8609. case 3 /* Matrix */:
  8610. {
  8611. var v = val;
  8612. for (var i = 0; i < 16; i++) {
  8613. array[offset + i] = v.m[i];
  8614. }
  8615. break;
  8616. }
  8617. case 7 /* Size */:
  8618. {
  8619. var s = val;
  8620. array[offset + 0] = s.width;
  8621. array[offset + 1] = s.height;
  8622. break;
  8623. }
  8624. }
  8625. };
  8626. return InstancePropInfo;
  8627. }());
  8628. BABYLON.InstancePropInfo = InstancePropInfo;
  8629. function instanceData(category, shaderAttributeName) {
  8630. return function (target, propName, descriptor) {
  8631. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  8632. var node = dic.getLevelOf(target);
  8633. var instanceDataName = propName;
  8634. shaderAttributeName = shaderAttributeName || instanceDataName;
  8635. var info = node.levelContent.get(instanceDataName);
  8636. if (info) {
  8637. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  8638. }
  8639. info = new InstancePropInfo();
  8640. info.attributeName = shaderAttributeName;
  8641. info.category = category || null;
  8642. if (info.category) {
  8643. info.delimitedCategory = ";" + info.category + ";";
  8644. }
  8645. node.levelContent.add(instanceDataName, info);
  8646. descriptor.get = function () {
  8647. return null;
  8648. };
  8649. descriptor.set = function (val) {
  8650. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  8651. // Quit if it's the case, otherwise we could overwrite data somewhere...
  8652. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  8653. return;
  8654. }
  8655. if (!info.size) {
  8656. info.setSize(val);
  8657. node.classContent.mapProperty(info, true);
  8658. }
  8659. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  8660. node.classContent.mapProperty(info, false);
  8661. }
  8662. var obj = this;
  8663. if (obj.dataBuffer && obj.dataElements) {
  8664. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  8665. info.writeData(obj.dataBuffer.buffer, offset, val);
  8666. }
  8667. };
  8668. };
  8669. }
  8670. BABYLON.instanceData = instanceData;
  8671. var InstanceDataBase = (function () {
  8672. function InstanceDataBase(partId, dataElementCount) {
  8673. this.id = partId;
  8674. this.curElement = 0;
  8675. this._dataElementCount = dataElementCount;
  8676. this.renderMode = 0;
  8677. this.arrayLengthChanged = false;
  8678. }
  8679. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  8680. get: function () {
  8681. return null;
  8682. },
  8683. set: function (value) {
  8684. },
  8685. enumerable: true,
  8686. configurable: true
  8687. });
  8688. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  8689. get: function () {
  8690. return null;
  8691. },
  8692. set: function (value) {
  8693. },
  8694. enumerable: true,
  8695. configurable: true
  8696. });
  8697. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  8698. get: function () {
  8699. return null;
  8700. },
  8701. set: function (value) {
  8702. },
  8703. enumerable: true,
  8704. configurable: true
  8705. });
  8706. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  8707. get: function () {
  8708. return null;
  8709. },
  8710. set: function (value) {
  8711. },
  8712. enumerable: true,
  8713. configurable: true
  8714. });
  8715. InstanceDataBase.prototype.getClassTreeInfo = function () {
  8716. if (!this.typeInfo) {
  8717. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  8718. }
  8719. return this.typeInfo;
  8720. };
  8721. InstanceDataBase.prototype.allocElements = function () {
  8722. if (!this.dataBuffer || this.dataElements) {
  8723. return;
  8724. }
  8725. var res = new Array(this.dataElementCount);
  8726. for (var i = 0; i < this.dataElementCount; i++) {
  8727. res[i] = this.dataBuffer.allocElement();
  8728. }
  8729. this.dataElements = res;
  8730. };
  8731. InstanceDataBase.prototype.freeElements = function () {
  8732. if (!this.dataElements) {
  8733. return;
  8734. }
  8735. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  8736. var ei = _a[_i];
  8737. this.dataBuffer.freeElement(ei);
  8738. }
  8739. this.dataElements = null;
  8740. };
  8741. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  8742. get: function () {
  8743. return this._dataElementCount;
  8744. },
  8745. set: function (value) {
  8746. if (value === this._dataElementCount) {
  8747. return;
  8748. }
  8749. this.arrayLengthChanged = true;
  8750. this.freeElements();
  8751. this._dataElementCount = value;
  8752. this.allocElements();
  8753. },
  8754. enumerable: true,
  8755. configurable: true
  8756. });
  8757. return InstanceDataBase;
  8758. }());
  8759. __decorate([
  8760. instanceData()
  8761. ], InstanceDataBase.prototype, "zBias", null);
  8762. __decorate([
  8763. instanceData()
  8764. ], InstanceDataBase.prototype, "transformX", null);
  8765. __decorate([
  8766. instanceData()
  8767. ], InstanceDataBase.prototype, "transformY", null);
  8768. __decorate([
  8769. instanceData()
  8770. ], InstanceDataBase.prototype, "opacity", null);
  8771. BABYLON.InstanceDataBase = InstanceDataBase;
  8772. var RenderablePrim2D = RenderablePrim2D_1 = (function (_super) {
  8773. __extends(RenderablePrim2D, _super);
  8774. function RenderablePrim2D(settings) {
  8775. var _this = _super.call(this, settings) || this;
  8776. _this._transparentPrimitiveInfo = null;
  8777. return _this;
  8778. }
  8779. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  8780. get: function () {
  8781. return this._useTextureAlpha() || this._isPrimAlphaTest();
  8782. },
  8783. enumerable: true,
  8784. configurable: true
  8785. });
  8786. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  8787. get: function () {
  8788. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  8789. },
  8790. enumerable: true,
  8791. configurable: true
  8792. });
  8793. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  8794. get: function () {
  8795. return this._renderMode;
  8796. },
  8797. enumerable: true,
  8798. configurable: true
  8799. });
  8800. /**
  8801. * Dispose the primitive and its resources, remove it from its parent
  8802. */
  8803. RenderablePrim2D.prototype.dispose = function () {
  8804. if (!_super.prototype.dispose.call(this)) {
  8805. return false;
  8806. }
  8807. if (this.renderGroup) {
  8808. this.renderGroup._setCacheGroupDirty();
  8809. }
  8810. if (this._transparentPrimitiveInfo) {
  8811. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  8812. this._transparentPrimitiveInfo = null;
  8813. }
  8814. if (this._instanceDataParts) {
  8815. this._cleanupInstanceDataParts();
  8816. }
  8817. if (this._modelRenderCache) {
  8818. this._modelRenderCache.dispose();
  8819. this._modelRenderCache = null;
  8820. }
  8821. if (this._instanceDataParts) {
  8822. this._instanceDataParts.forEach(function (p) {
  8823. p.freeElements();
  8824. });
  8825. this._instanceDataParts = null;
  8826. }
  8827. return true;
  8828. };
  8829. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  8830. var gii = null;
  8831. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  8832. var part = _a[_i];
  8833. part.freeElements();
  8834. gii = part.groupInstanceInfo;
  8835. }
  8836. if (gii) {
  8837. var usedCount = 0;
  8838. if (gii.hasOpaqueData) {
  8839. var od = gii.opaqueData[0];
  8840. usedCount += od._partData.usedElementCount;
  8841. gii.opaqueDirty = true;
  8842. }
  8843. if (gii.hasAlphaTestData) {
  8844. var atd = gii.alphaTestData[0];
  8845. usedCount += atd._partData.usedElementCount;
  8846. gii.alphaTestDirty = true;
  8847. }
  8848. if (gii.hasTransparentData) {
  8849. var td = gii.transparentData[0];
  8850. usedCount += td._partData.usedElementCount;
  8851. gii.transparentDirty = true;
  8852. }
  8853. if (usedCount === 0 && gii.modelRenderCache != null) {
  8854. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  8855. gii.dispose();
  8856. }
  8857. if (this._modelRenderCache) {
  8858. this._modelRenderCache.dispose();
  8859. this._modelRenderCache = null;
  8860. }
  8861. }
  8862. this._instanceDataParts = null;
  8863. };
  8864. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  8865. _super.prototype._prepareRenderPre.call(this, context);
  8866. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  8867. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  8868. this._cleanupInstanceDataParts();
  8869. }
  8870. // Need to create the model?
  8871. var setupModelRenderCache = false;
  8872. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  8873. setupModelRenderCache = this._createModelRenderCache();
  8874. }
  8875. var gii = null;
  8876. var newInstance = false;
  8877. // Need to create the instance data parts?
  8878. if (!this._instanceDataParts) {
  8879. // Yes, flag it for later, more processing will have to be done
  8880. newInstance = true;
  8881. gii = this._createModelDataParts();
  8882. }
  8883. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  8884. if (setupModelRenderCache) {
  8885. this.setupModelRenderCache(this._modelRenderCache);
  8886. }
  8887. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelUpdate)) {
  8888. if (this._modelRenderCache.updateModelRenderCache(this)) {
  8889. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  8890. }
  8891. }
  8892. // 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.
  8893. // 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.
  8894. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  8895. this._updateInstanceDataParts(gii);
  8896. }
  8897. };
  8898. RenderablePrim2D.prototype._createModelRenderCache = function () {
  8899. var _this = this;
  8900. var setupModelRenderCache = false;
  8901. if (this._modelRenderCache) {
  8902. this._modelRenderCache.dispose();
  8903. }
  8904. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  8905. var mrc = _this.createModelRenderCache(key);
  8906. setupModelRenderCache = true;
  8907. return mrc;
  8908. });
  8909. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  8910. // if this is still false it means the MRC already exists, so we add a reference to it
  8911. if (!setupModelRenderCache) {
  8912. this._modelRenderCache.addRef();
  8913. }
  8914. return setupModelRenderCache;
  8915. };
  8916. RenderablePrim2D.prototype._createModelDataParts = function () {
  8917. var _this = this;
  8918. // Create the instance data parts of the primitive and store them
  8919. var parts = this.createInstanceDataParts();
  8920. this._instanceDataParts = parts;
  8921. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  8922. if (!this._modelRenderCache._partData) {
  8923. this._setupModelRenderCache(parts);
  8924. }
  8925. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  8926. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  8927. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  8928. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  8929. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  8930. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  8931. var part = _this._instanceDataParts[j];
  8932. res.partIndexFromId.add(part.id.toString(), j);
  8933. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  8934. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  8935. }
  8936. return res;
  8937. });
  8938. // Get the GroupInfoDataPart corresponding to the render category of the part
  8939. var rm = 0;
  8940. var gipd = null;
  8941. if (this.isTransparent) {
  8942. gipd = gii.transparentData;
  8943. rm = BABYLON.Render2DContext.RenderModeTransparent;
  8944. }
  8945. else if (this.isAlphaTest) {
  8946. gipd = gii.alphaTestData;
  8947. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  8948. }
  8949. else {
  8950. gipd = gii.opaqueData;
  8951. rm = BABYLON.Render2DContext.RenderModeOpaque;
  8952. }
  8953. // For each instance data part of the primitive, allocate the instanced element it needs for render
  8954. for (var i = 0; i < parts.length; i++) {
  8955. var part = parts[i];
  8956. part.dataBuffer = gipd[i]._partData;
  8957. part.allocElements();
  8958. part.renderMode = rm;
  8959. part.groupInstanceInfo = gii;
  8960. }
  8961. return gii;
  8962. };
  8963. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  8964. var ctiArray = new Array();
  8965. this._modelRenderCache._partData = new Array();
  8966. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  8967. var dataPart = parts_1[_i];
  8968. var pd = new BABYLON.ModelRenderCachePartData();
  8969. this._modelRenderCache._partData.push(pd);
  8970. var cat = this.getUsedShaderCategories(dataPart);
  8971. var cti = dataPart.getClassTreeInfo();
  8972. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  8973. var curVisible = this.isVisible;
  8974. this.isVisible = true;
  8975. // 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.
  8976. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  8977. var joinCat = ";" + cat.join(";") + ";";
  8978. pd._partJoinedUsedCategories = joinCat;
  8979. InstanceClassInfo._CurCategories = joinCat;
  8980. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  8981. if (!this.refreshInstanceDataPart(dataPart)) {
  8982. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  8983. }
  8984. this.afterRefreshForLayoutConstruction(dataPart, obj);
  8985. this.isVisible = curVisible;
  8986. var size = 0;
  8987. cti.fullContent.forEach(function (k, v) {
  8988. if (!v.category || cat.indexOf(v.category) !== -1) {
  8989. if (v.attributeName === "zBias") {
  8990. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  8991. }
  8992. if (!v.size) {
  8993. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  8994. }
  8995. else {
  8996. size += v.size;
  8997. }
  8998. }
  8999. });
  9000. pd._partDataStride = size;
  9001. pd._partUsedCategories = cat;
  9002. pd._partId = dataPart.id;
  9003. ctiArray.push(cti);
  9004. }
  9005. this._modelRenderCache._partsClassInfo = ctiArray;
  9006. };
  9007. RenderablePrim2D.prototype.onZOrderChanged = function () {
  9008. if (this.isTransparent && this._transparentPrimitiveInfo) {
  9009. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  9010. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  9011. // Flag the transparentData dirty has will have to sort it again
  9012. gii.transparentOrderDirty = true;
  9013. }
  9014. };
  9015. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  9016. return false;
  9017. };
  9018. RenderablePrim2D.prototype._useTextureAlpha = function () {
  9019. return false;
  9020. };
  9021. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  9022. return false;
  9023. };
  9024. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  9025. return false;
  9026. };
  9027. RenderablePrim2D.prototype._isPrimTransparent = function () {
  9028. return false;
  9029. };
  9030. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  9031. // Fetch the GroupInstanceInfo if we don't already have it
  9032. var rd = this.renderGroup._renderableData;
  9033. if (!gii) {
  9034. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  9035. }
  9036. var isTransparent = this.isTransparent;
  9037. var isAlphaTest = this.isAlphaTest;
  9038. var wereTransparent = false;
  9039. // Check a render mode change
  9040. var rmChanged = false;
  9041. if (this._instanceDataParts.length > 0) {
  9042. var firstPart = this._instanceDataParts[0];
  9043. var partRM = firstPart.renderMode;
  9044. var curRM = this.renderMode;
  9045. if (partRM !== curRM) {
  9046. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  9047. rmChanged = true;
  9048. var gipd = void 0;
  9049. switch (curRM) {
  9050. case BABYLON.Render2DContext.RenderModeTransparent:
  9051. gipd = gii.transparentData;
  9052. break;
  9053. case BABYLON.Render2DContext.RenderModeAlphaTest:
  9054. gipd = gii.alphaTestData;
  9055. break;
  9056. default:
  9057. gipd = gii.opaqueData;
  9058. }
  9059. for (var i = 0; i < this._instanceDataParts.length; i++) {
  9060. var part = this._instanceDataParts[i];
  9061. part.freeElements();
  9062. part.dataBuffer = gipd[i]._partData;
  9063. part.renderMode = curRM;
  9064. }
  9065. }
  9066. }
  9067. // Handle changes related to ZOffset
  9068. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  9069. if (isTransparent || wereTransparent) {
  9070. // Handle visibility change, which is also triggered when the primitive just got created
  9071. if (visChanged || rmChanged) {
  9072. if (this.isVisible && !wereTransparent) {
  9073. if (!this._transparentPrimitiveInfo) {
  9074. // Add the primitive to the list of transparent ones in the group that render is
  9075. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  9076. }
  9077. }
  9078. else {
  9079. if (this._transparentPrimitiveInfo) {
  9080. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  9081. this._transparentPrimitiveInfo = null;
  9082. }
  9083. }
  9084. gii.transparentOrderDirty = true;
  9085. }
  9086. }
  9087. var rebuildTrans = false;
  9088. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  9089. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  9090. var part = _a[_i];
  9091. var justAllocated = false;
  9092. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  9093. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  9094. part.allocElements();
  9095. justAllocated = true;
  9096. }
  9097. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  9098. // Will return false if the instance should not be rendered (not visible or other any reasons)
  9099. part.arrayLengthChanged = false;
  9100. if (!this.refreshInstanceDataPart(part)) {
  9101. // Free the data element
  9102. if (part.dataElements) {
  9103. part.freeElements();
  9104. }
  9105. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  9106. if (this.isVisible) {
  9107. rd._primNewDirtyList.push(this);
  9108. }
  9109. }
  9110. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  9111. }
  9112. this._instanceDirtyFlags = 0;
  9113. // Make the appropriate data dirty
  9114. if (isTransparent) {
  9115. gii.transparentDirty = true;
  9116. if (rebuildTrans) {
  9117. rd._transparentListChanged = true;
  9118. }
  9119. }
  9120. else if (isAlphaTest) {
  9121. gii.alphaTestDirty = true;
  9122. }
  9123. else {
  9124. gii.opaqueDirty = true;
  9125. }
  9126. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  9127. };
  9128. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  9129. var minOff = BABYLON.Prim2DBase._bigInt;
  9130. var maxOff = 0;
  9131. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  9132. var part = _a[_i];
  9133. if (part && part.dataElements) {
  9134. part.dataBuffer.pack();
  9135. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  9136. var el = _c[_b];
  9137. minOff = Math.min(minOff, el.offset);
  9138. maxOff = Math.max(maxOff, el.offset);
  9139. }
  9140. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  9141. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  9142. }
  9143. }
  9144. };
  9145. // This internal method is mainly used for transparency processing
  9146. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  9147. var length = this._instanceDataParts.length;
  9148. for (var i = 0; i < length; i++) {
  9149. var part = this._instanceDataParts[i];
  9150. if (part) {
  9151. var stride = part.dataBuffer.stride;
  9152. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  9153. // check if it's the last in the DFA
  9154. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  9155. return null;
  9156. }
  9157. // Return the Z of the next primitive that lies in the DFA
  9158. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  9159. }
  9160. }
  9161. return null;
  9162. };
  9163. // This internal method is mainly used for transparency processing
  9164. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  9165. var length = this._instanceDataParts.length;
  9166. for (var i = 0; i < length; i++) {
  9167. var part = this._instanceDataParts[i];
  9168. if (part) {
  9169. var stride = part.dataBuffer.stride;
  9170. var firstElementOffset = part.dataElements[0].offset;
  9171. // check if it's the first in the DFA
  9172. if (firstElementOffset === 0) {
  9173. return null;
  9174. }
  9175. // Return the Z of the previous primitive that lies in the DFA
  9176. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  9177. }
  9178. }
  9179. return null;
  9180. };
  9181. /**
  9182. * Transform a given point using the Primitive's origin setting.
  9183. * This method requires the Primitive's actualSize to be accurate
  9184. * @param p the point to transform
  9185. * @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.
  9186. * @param res an allocated Vector2 that will receive the transformed content
  9187. */
  9188. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  9189. var actualSize = this.actualSize;
  9190. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  9191. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  9192. };
  9193. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  9194. this.transformPointWithOriginByRef(p, originOffset, res);
  9195. return res;
  9196. };
  9197. /**
  9198. * Get the info for a given effect based on the dataPart metadata
  9199. * @param dataPartId partId in part list to get the info
  9200. * @param vertexBufferAttributes vertex buffer attributes to manually add
  9201. * @param uniforms uniforms to manually add
  9202. * @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
  9203. */
  9204. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  9205. if (uniforms === void 0) { uniforms = null; }
  9206. if (useInstanced === void 0) { useInstanced = null; }
  9207. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  9208. if (!dataPart) {
  9209. return null;
  9210. }
  9211. var instancedArray = this.owner.supportInstancedArray;
  9212. if (useInstanced != null) {
  9213. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  9214. if (useInstanced && instancedArray === false) {
  9215. return null;
  9216. }
  9217. // Use the caller's setting
  9218. instancedArray = useInstanced;
  9219. }
  9220. var cti = dataPart.getClassTreeInfo();
  9221. var categories = this.getUsedShaderCategories(dataPart);
  9222. var att = cti.classContent.getShaderAttributes(categories);
  9223. var defines = "";
  9224. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  9225. if (instancedArray) {
  9226. defines += "#define Instanced\n";
  9227. }
  9228. return {
  9229. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  9230. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  9231. defines: defines
  9232. };
  9233. };
  9234. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  9235. get: function () {
  9236. return this._modelRenderCache;
  9237. },
  9238. enumerable: true,
  9239. configurable: true
  9240. });
  9241. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  9242. return null;
  9243. };
  9244. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  9245. };
  9246. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  9247. return null;
  9248. };
  9249. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  9250. return [];
  9251. };
  9252. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  9253. };
  9254. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  9255. };
  9256. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  9257. return true;
  9258. };
  9259. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  9260. if (!this.isVisible) {
  9261. return false;
  9262. }
  9263. part.isVisible = this.isVisible;
  9264. // 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)
  9265. if (part.dataElementCount === 1) {
  9266. part.curElement = 0;
  9267. this.updateInstanceDataPart(part);
  9268. }
  9269. return true;
  9270. };
  9271. /**
  9272. * Update the instanceDataBase level properties of a part
  9273. * @param part the part to update
  9274. * @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).
  9275. */
  9276. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  9277. if (positionOffset === void 0) { positionOffset = null; }
  9278. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  9279. 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.
  9280. var size = this.renderGroup.viewportSize;
  9281. var zBias = this.actualZOffset;
  9282. var offX = 0;
  9283. var offY = 0;
  9284. // If there's an offset, apply the global transformation matrix on it to get a global offset
  9285. if (positionOffset) {
  9286. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  9287. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  9288. }
  9289. // 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
  9290. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  9291. // So for X:
  9292. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  9293. // - 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].
  9294. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  9295. var w = size.width;
  9296. var h = size.height;
  9297. var invZBias = 1 / zBias;
  9298. 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);
  9299. 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);
  9300. if (!this.applyActualScaleOnTransform()) {
  9301. t.m[0] = tx.x, t.m[4] = tx.y, t.m[12] = tx.w;
  9302. t.m[1] = ty.x, t.m[5] = ty.y, t.m[13] = ty.w;
  9303. var las = this.actualScale;
  9304. t.decompose(RenderablePrim2D_1._s, RenderablePrim2D_1._r, RenderablePrim2D_1._t);
  9305. var scale = new BABYLON.Vector3(RenderablePrim2D_1._s.x / las.x, RenderablePrim2D_1._s.y / las.y, 1);
  9306. t = BABYLON.Matrix.Compose(scale, RenderablePrim2D_1._r, RenderablePrim2D_1._t);
  9307. tx = new BABYLON.Vector4(t.m[0], t.m[4], 0, t.m[12]);
  9308. ty = new BABYLON.Vector4(t.m[1], t.m[5], 0, t.m[13]);
  9309. }
  9310. tx.x /= w;
  9311. tx.y /= w;
  9312. ty.x /= h;
  9313. ty.y /= h;
  9314. part.transformX = tx;
  9315. part.transformY = ty;
  9316. part.opacity = this.actualOpacity;
  9317. // 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)
  9318. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  9319. };
  9320. RenderablePrim2D.prototype._updateRenderMode = function () {
  9321. if (this.isTransparent) {
  9322. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  9323. }
  9324. else if (this.isAlphaTest) {
  9325. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  9326. }
  9327. else {
  9328. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  9329. }
  9330. };
  9331. return RenderablePrim2D;
  9332. }(BABYLON.Prim2DBase));
  9333. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  9334. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  9335. RenderablePrim2D._s = BABYLON.Vector3.Zero();
  9336. RenderablePrim2D._r = BABYLON.Quaternion.Identity();
  9337. RenderablePrim2D._t = BABYLON.Vector3.Zero();
  9338. RenderablePrim2D._uV3 = new BABYLON.Vector3(1, 1, 1);
  9339. __decorate([
  9340. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D_1.isAlphaTestProperty = pi; })
  9341. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  9342. __decorate([
  9343. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D_1.isTransparentProperty = pi; })
  9344. ], RenderablePrim2D.prototype, "isTransparent", null);
  9345. RenderablePrim2D = RenderablePrim2D_1 = __decorate([
  9346. BABYLON.className("RenderablePrim2D", "BABYLON")
  9347. ], RenderablePrim2D);
  9348. BABYLON.RenderablePrim2D = RenderablePrim2D;
  9349. var RenderablePrim2D_1;
  9350. })(BABYLON || (BABYLON = {}));
  9351. //# sourceMappingURL=babylon.renderablePrim2d.js.map
  9352. var __extends = (this && this.__extends) || function (d, b) {
  9353. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9354. function __() { this.constructor = d; }
  9355. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9356. };
  9357. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  9358. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  9359. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9360. 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;
  9361. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9362. };
  9363. var BABYLON;
  9364. (function (BABYLON) {
  9365. var Shape2D = Shape2D_1 = (function (_super) {
  9366. __extends(Shape2D, _super);
  9367. function Shape2D(settings) {
  9368. var _this = _super.call(this, settings) || this;
  9369. if (!settings) {
  9370. settings = {};
  9371. }
  9372. var borderBrush = null;
  9373. if (settings.border) {
  9374. if (typeof (settings.border) === "string") {
  9375. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  9376. }
  9377. else {
  9378. borderBrush = settings.border;
  9379. }
  9380. }
  9381. var fillBrush = null;
  9382. if (settings.fill) {
  9383. if (typeof (settings.fill) === "string") {
  9384. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  9385. }
  9386. else {
  9387. fillBrush = settings.fill;
  9388. }
  9389. }
  9390. _this._isTransparent = false;
  9391. _this._oldTransparent = false;
  9392. _this.border = borderBrush;
  9393. _this.fill = fillBrush;
  9394. _this._updateTransparencyStatus();
  9395. _this.borderThickness = settings.borderThickness;
  9396. return _this;
  9397. }
  9398. Object.defineProperty(Shape2D.prototype, "border", {
  9399. get: function () {
  9400. return this._border;
  9401. },
  9402. set: function (value) {
  9403. this._border = value;
  9404. this._updateTransparencyStatus();
  9405. },
  9406. enumerable: true,
  9407. configurable: true
  9408. });
  9409. Object.defineProperty(Shape2D.prototype, "fill", {
  9410. /**
  9411. * Get/set the brush to render the Fill part of the Primitive
  9412. */
  9413. get: function () {
  9414. return this._fill;
  9415. },
  9416. set: function (value) {
  9417. this._fill = value;
  9418. this._updateTransparencyStatus();
  9419. },
  9420. enumerable: true,
  9421. configurable: true
  9422. });
  9423. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  9424. get: function () {
  9425. return this._borderThickness;
  9426. },
  9427. set: function (value) {
  9428. this._borderThickness = value;
  9429. },
  9430. enumerable: true,
  9431. configurable: true
  9432. });
  9433. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  9434. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  9435. // Fill Part
  9436. if (dataPart.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  9437. var fill = this.fill;
  9438. if (fill instanceof BABYLON.SolidColorBrush2D) {
  9439. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLSOLID);
  9440. }
  9441. if (fill instanceof BABYLON.GradientColorBrush2D) {
  9442. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLGRADIENT);
  9443. }
  9444. }
  9445. // Border Part
  9446. if (dataPart.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  9447. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDER);
  9448. var border = this.border;
  9449. if (border instanceof BABYLON.SolidColorBrush2D) {
  9450. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERSOLID);
  9451. }
  9452. if (border instanceof BABYLON.GradientColorBrush2D) {
  9453. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERGRADIENT);
  9454. }
  9455. }
  9456. return cat;
  9457. };
  9458. Shape2D.prototype.applyActualScaleOnTransform = function () {
  9459. return false;
  9460. };
  9461. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  9462. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  9463. return false;
  9464. }
  9465. // Fill Part
  9466. if (part.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  9467. var d = part;
  9468. if (this.fill) {
  9469. var fill = this.fill;
  9470. if (fill instanceof BABYLON.SolidColorBrush2D) {
  9471. d.fillSolidColor = fill.color;
  9472. }
  9473. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  9474. d.fillGradientColor1 = fill.color1;
  9475. d.fillGradientColor2 = fill.color2;
  9476. 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));
  9477. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  9478. d.fillGradientTY = ty;
  9479. }
  9480. }
  9481. }
  9482. else if (part.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  9483. var d = part;
  9484. if (this.border) {
  9485. d.borderThickness = this.borderThickness;
  9486. var border = this.border;
  9487. if (border instanceof BABYLON.SolidColorBrush2D) {
  9488. d.borderSolidColor = border.color;
  9489. }
  9490. else if (border instanceof BABYLON.GradientColorBrush2D) {
  9491. d.borderGradientColor1 = border.color1;
  9492. d.borderGradientColor2 = border.color2;
  9493. 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));
  9494. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  9495. d.borderGradientTY = ty;
  9496. }
  9497. }
  9498. }
  9499. return true;
  9500. };
  9501. Shape2D.prototype._updateTransparencyStatus = function () {
  9502. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  9503. if (this._isTransparent !== this._oldTransparent) {
  9504. this._oldTransparent = this._isTransparent;
  9505. this._updateRenderMode();
  9506. }
  9507. };
  9508. Shape2D.prototype._mustUpdateInstance = function () {
  9509. var res = this._oldTransparent !== this._isTransparent;
  9510. if (res) {
  9511. this._updateRenderMode();
  9512. this._oldTransparent = this._isTransparent;
  9513. }
  9514. return res;
  9515. };
  9516. Shape2D.prototype._isPrimTransparent = function () {
  9517. return this._isTransparent;
  9518. };
  9519. return Shape2D;
  9520. }(BABYLON.RenderablePrim2D));
  9521. Shape2D.SHAPE2D_BORDERPARTID = 1;
  9522. Shape2D.SHAPE2D_FILLPARTID = 2;
  9523. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  9524. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  9525. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  9526. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  9527. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  9528. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  9529. __decorate([
  9530. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D_1.borderProperty = pi; }, true)
  9531. ], Shape2D.prototype, "border", null);
  9532. __decorate([
  9533. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D_1.fillProperty = pi; }, true)
  9534. ], Shape2D.prototype, "fill", null);
  9535. __decorate([
  9536. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D_1.borderThicknessProperty = pi; })
  9537. ], Shape2D.prototype, "borderThickness", null);
  9538. Shape2D = Shape2D_1 = __decorate([
  9539. BABYLON.className("Shape2D", "BABYLON")
  9540. ], Shape2D);
  9541. BABYLON.Shape2D = Shape2D;
  9542. var Shape2DInstanceData = (function (_super) {
  9543. __extends(Shape2DInstanceData, _super);
  9544. function Shape2DInstanceData() {
  9545. return _super !== null && _super.apply(this, arguments) || this;
  9546. }
  9547. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  9548. // FILL ATTRIBUTES
  9549. get: function () {
  9550. return null;
  9551. },
  9552. set: function (value) {
  9553. },
  9554. enumerable: true,
  9555. configurable: true
  9556. });
  9557. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  9558. get: function () {
  9559. return null;
  9560. },
  9561. set: function (value) {
  9562. },
  9563. enumerable: true,
  9564. configurable: true
  9565. });
  9566. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  9567. get: function () {
  9568. return null;
  9569. },
  9570. set: function (value) {
  9571. },
  9572. enumerable: true,
  9573. configurable: true
  9574. });
  9575. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  9576. get: function () {
  9577. return null;
  9578. },
  9579. set: function (value) {
  9580. },
  9581. enumerable: true,
  9582. configurable: true
  9583. });
  9584. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  9585. // BORDER ATTRIBUTES
  9586. get: function () {
  9587. return null;
  9588. },
  9589. set: function (value) {
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  9595. get: function () {
  9596. return null;
  9597. },
  9598. set: function (value) {
  9599. },
  9600. enumerable: true,
  9601. configurable: true
  9602. });
  9603. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  9604. get: function () {
  9605. return null;
  9606. },
  9607. set: function (value) {
  9608. },
  9609. enumerable: true,
  9610. configurable: true
  9611. });
  9612. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  9613. get: function () {
  9614. return null;
  9615. },
  9616. set: function (value) {
  9617. },
  9618. enumerable: true,
  9619. configurable: true
  9620. });
  9621. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  9622. get: function () {
  9623. return null;
  9624. },
  9625. set: function (value) {
  9626. },
  9627. enumerable: true,
  9628. configurable: true
  9629. });
  9630. return Shape2DInstanceData;
  9631. }(BABYLON.InstanceDataBase));
  9632. __decorate([
  9633. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  9634. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  9635. __decorate([
  9636. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  9637. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  9638. __decorate([
  9639. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  9640. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  9641. __decorate([
  9642. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  9643. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  9644. __decorate([
  9645. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  9646. ], Shape2DInstanceData.prototype, "borderThickness", null);
  9647. __decorate([
  9648. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  9649. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  9650. __decorate([
  9651. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  9652. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  9653. __decorate([
  9654. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  9655. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  9656. __decorate([
  9657. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  9658. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  9659. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  9660. var Shape2D_1;
  9661. })(BABYLON || (BABYLON = {}));
  9662. //# sourceMappingURL=babylon.shape2d.js.map
  9663. var __extends = (this && this.__extends) || function (d, b) {
  9664. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9665. function __() { this.constructor = d; }
  9666. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9667. };
  9668. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  9669. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  9670. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9671. 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;
  9672. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9673. };
  9674. var BABYLON;
  9675. (function (BABYLON) {
  9676. var Group2D = Group2D_1 = (function (_super) {
  9677. __extends(Group2D, _super);
  9678. /**
  9679. * Create an Logical or Renderable Group.
  9680. * @param settings a combination of settings, possible ones are
  9681. * - 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)
  9682. * - children: an array of direct children
  9683. * - id a text identifier, for information purpose
  9684. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  9685. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  9686. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  9687. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  9688. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  9689. * - zOrder: override the zOrder with the specified value
  9690. * - origin: define the normalized origin point location, default [0.5;0.5]
  9691. * - 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.
  9692. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  9693. * - 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).
  9694. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  9695. * - 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.
  9696. * - 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.
  9697. * - 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!
  9698. * - 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.
  9699. * - 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).
  9700. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  9701. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9702. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9703. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9704. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9705. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  9706. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  9707. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  9708. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  9709. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9710. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9711. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9712. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9713. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  9714. */
  9715. function Group2D(settings) {
  9716. var _this = this;
  9717. if (settings == null) {
  9718. settings = {};
  9719. }
  9720. if (settings.origin == null) {
  9721. settings.origin = new BABYLON.Vector2(0, 0);
  9722. }
  9723. _this = _super.call(this, settings) || this;
  9724. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  9725. _this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  9726. if (_this._trackedNode && _this.owner) {
  9727. _this.owner._registerTrackedNode(_this);
  9728. }
  9729. _this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  9730. var rd = _this._renderableData;
  9731. if (rd) {
  9732. rd._noResizeOnScale = (_this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  9733. }
  9734. _this.size = size;
  9735. _this._viewportPosition = BABYLON.Vector2.Zero();
  9736. _this._viewportSize = BABYLON.Size.Zero();
  9737. return _this;
  9738. }
  9739. Group2D._createCachedCanvasGroup = function (owner) {
  9740. 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 });
  9741. return g;
  9742. };
  9743. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  9744. this._bindCacheTarget();
  9745. if (vertexData) {
  9746. var uv = vertexData.uvs;
  9747. var nodeuv = this._renderableData._cacheNodeUVs;
  9748. for (var i = 0; i < 4; i++) {
  9749. uv[i * 2 + 0] = nodeuv[i].x;
  9750. uv[i * 2 + 1] = nodeuv[i].y;
  9751. }
  9752. }
  9753. if (material) {
  9754. material.diffuseTexture = this._renderableData._cacheTexture;
  9755. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  9756. }
  9757. this._renderableData._cacheTexture.hasAlpha = true;
  9758. this._unbindCacheTarget();
  9759. };
  9760. Object.defineProperty(Group2D.prototype, "cachedRect", {
  9761. /**
  9762. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  9763. * 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.
  9764. */
  9765. get: function () {
  9766. if (!this._renderableData) {
  9767. return null;
  9768. }
  9769. return this._renderableData._cacheNode;
  9770. },
  9771. enumerable: true,
  9772. configurable: true
  9773. });
  9774. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  9775. /**
  9776. * The UVs into the MapTexture that map the cached group
  9777. */
  9778. get: function () {
  9779. if (!this._renderableData) {
  9780. return null;
  9781. }
  9782. return this._renderableData._cacheNodeUVs;
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  9788. get: function () {
  9789. if (!this._renderableData) {
  9790. return null;
  9791. }
  9792. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  9793. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  9794. }
  9795. return this._renderableData._cacheNodeUVsChangedObservable;
  9796. },
  9797. enumerable: true,
  9798. configurable: true
  9799. });
  9800. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  9801. /**
  9802. * Access the texture that maintains a cached version of the Group2D.
  9803. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  9804. */
  9805. get: function () {
  9806. if (!this._renderableData) {
  9807. return null;
  9808. }
  9809. return this._renderableData._cacheTexture;
  9810. },
  9811. enumerable: true,
  9812. configurable: true
  9813. });
  9814. /**
  9815. * Call this method to remove this Group and its children from the Canvas
  9816. */
  9817. Group2D.prototype.dispose = function () {
  9818. if (!_super.prototype.dispose.call(this)) {
  9819. return false;
  9820. }
  9821. if (this._trackedNode != null) {
  9822. this.owner._unregisterTrackedNode(this);
  9823. this._trackedNode = null;
  9824. }
  9825. if (this._renderableData) {
  9826. this._renderableData.dispose(this.owner);
  9827. this._renderableData = null;
  9828. }
  9829. return true;
  9830. };
  9831. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  9832. /**
  9833. * @returns Returns true if the Group render content, false if it's a logical group only
  9834. */
  9835. get: function () {
  9836. return this._isRenderableGroup;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  9842. /**
  9843. * @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
  9844. */
  9845. get: function () {
  9846. return this._isCachedGroup;
  9847. },
  9848. enumerable: true,
  9849. configurable: true
  9850. });
  9851. Object.defineProperty(Group2D.prototype, "size", {
  9852. get: function () {
  9853. return this._size;
  9854. },
  9855. /**
  9856. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  9857. * 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.
  9858. */
  9859. set: function (val) {
  9860. this._size = val;
  9861. },
  9862. enumerable: true,
  9863. configurable: true
  9864. });
  9865. Object.defineProperty(Group2D.prototype, "viewportSize", {
  9866. get: function () {
  9867. return this._viewportSize;
  9868. },
  9869. enumerable: true,
  9870. configurable: true
  9871. });
  9872. Object.defineProperty(Group2D.prototype, "actualSize", {
  9873. get: function () {
  9874. // The computed size will be floor on both width and height
  9875. var actualSize;
  9876. // Return the actualSize if set
  9877. if (this._actualSize) {
  9878. return this._actualSize;
  9879. }
  9880. // Return the size if set by the user
  9881. if (this._size) {
  9882. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  9883. }
  9884. else {
  9885. var m = this.layoutBoundingInfo.max();
  9886. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  9887. }
  9888. // 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)
  9889. if (!actualSize.equals(this._actualSize)) {
  9890. this.onPrimitivePropertyDirty(Group2D_1.actualSizeProperty.flagId);
  9891. this._actualSize = actualSize;
  9892. this.handleGroupChanged(Group2D_1.actualSizeProperty);
  9893. }
  9894. return actualSize;
  9895. },
  9896. set: function (value) {
  9897. this._actualSize = value;
  9898. },
  9899. enumerable: true,
  9900. configurable: true
  9901. });
  9902. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  9903. /**
  9904. * 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.
  9905. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  9906. * 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.
  9907. */
  9908. get: function () {
  9909. return this._cacheBehavior;
  9910. },
  9911. enumerable: true,
  9912. configurable: true
  9913. });
  9914. Group2D.prototype._addPrimToDirtyList = function (prim) {
  9915. this._renderableData._primDirtyList.push(prim);
  9916. };
  9917. Group2D.prototype._renderCachedCanvas = function () {
  9918. this.owner._addGroupRenderCount(1);
  9919. this.updateCachedStates(true);
  9920. var context = new BABYLON.PrepareRender2DContext();
  9921. this._prepareGroupRender(context);
  9922. this._groupRender();
  9923. };
  9924. Object.defineProperty(Group2D.prototype, "trackedNode", {
  9925. /**
  9926. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  9927. */
  9928. get: function () {
  9929. return this._trackedNode;
  9930. },
  9931. set: function (val) {
  9932. if (val != null) {
  9933. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  9934. this.owner._registerTrackedNode(this);
  9935. }
  9936. this._trackedNode = val;
  9937. }
  9938. else {
  9939. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  9940. this.owner._unregisterTrackedNode(this);
  9941. }
  9942. this._trackedNode = null;
  9943. }
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Group2D.prototype.levelIntersect = function (intersectInfo) {
  9949. // 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
  9950. return true;
  9951. };
  9952. Group2D.prototype.updateLevelBoundingInfo = function () {
  9953. var size;
  9954. // If the size is set by the user, the boundingInfo is computed from this value
  9955. if (this.size) {
  9956. size = this.size;
  9957. }
  9958. else {
  9959. size = new BABYLON.Size(0, 0);
  9960. }
  9961. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  9962. return true;
  9963. };
  9964. // Method called only on renderable groups to prepare the rendering
  9965. Group2D.prototype._prepareGroupRender = function (context) {
  9966. var sortedDirtyList = null;
  9967. // Update the Global Transformation and visibility status of the changed primitives
  9968. var rd = this._renderableData;
  9969. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  9970. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  9971. this.updateCachedStatesOf(sortedDirtyList, true);
  9972. }
  9973. var s = this.actualSize;
  9974. var a = this.actualScale;
  9975. var sw = Math.ceil(s.width * a.x);
  9976. var sh = Math.ceil(s.height * a.y);
  9977. // 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.
  9978. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  9979. if ((this instanceof BABYLON.Canvas2D || this.id === "__cachedCanvasGroup__") && this.owner.designSize != null) {
  9980. sw = this.owner.engine.getRenderWidth();
  9981. sh = this.owner.engine.getRenderHeight();
  9982. }
  9983. // Setup the size of the rendering viewport
  9984. // 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
  9985. if (!this._isCachedGroup) {
  9986. // Compute the WebGL viewport's location/size
  9987. var t = this._globalTransform.getTranslation();
  9988. var rs = this.owner._renderingSize;
  9989. sh = Math.min(sh, rs.height - t.y);
  9990. sw = Math.min(sw, rs.width - t.x);
  9991. var x = t.x;
  9992. var y = t.y;
  9993. // 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
  9994. this._viewportPosition.x = x;
  9995. this._viewportPosition.y = y;
  9996. }
  9997. // 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.
  9998. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  9999. context.forceRefreshPrimitive = true;
  10000. this._viewportSize.width = sw;
  10001. this._viewportSize.height = sh;
  10002. }
  10003. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  10004. // If the group is cached, set the dirty flag to true because of the incoming changes
  10005. this._cacheGroupDirty = this._isCachedGroup;
  10006. rd._primNewDirtyList.splice(0);
  10007. // If it's a force refresh, prepare all the children
  10008. if (context.forceRefreshPrimitive) {
  10009. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10010. var p = _a[_i];
  10011. p._prepareRender(context);
  10012. }
  10013. }
  10014. else {
  10015. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  10016. // the hierarchyDepth in order to prepare primitives from top to bottom
  10017. if (!sortedDirtyList) {
  10018. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  10019. }
  10020. sortedDirtyList.forEach(function (p) {
  10021. // 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.
  10022. // 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.
  10023. if (!p.isDisposed && p._needPrepare()) {
  10024. p._prepareRender(context);
  10025. }
  10026. });
  10027. }
  10028. // Everything is updated, clear the dirty list
  10029. rd._primDirtyList.forEach(function (p) {
  10030. if (rd._primNewDirtyList.indexOf(p) === -1) {
  10031. p._resetPropertiesDirty();
  10032. }
  10033. else {
  10034. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  10035. }
  10036. });
  10037. rd._primDirtyList.splice(0);
  10038. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  10039. }
  10040. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  10041. rd._childrenRenderableGroups.forEach(function (g) {
  10042. g._prepareGroupRender(context);
  10043. });
  10044. };
  10045. Group2D.prototype._groupRender = function () {
  10046. var _this = this;
  10047. var engine = this.owner.engine;
  10048. var failedCount = 0;
  10049. // First recurse to children render group to render them (in their cache or on screen)
  10050. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  10051. var childGroup = _a[_i];
  10052. childGroup._groupRender();
  10053. }
  10054. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  10055. if (!this.isCachedGroup || this._cacheGroupDirty) {
  10056. this.owner._addGroupRenderCount(1);
  10057. if (this.isCachedGroup) {
  10058. this._bindCacheTarget();
  10059. }
  10060. else {
  10061. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  10062. }
  10063. var curAlphaTest = engine.getAlphaTesting() === true;
  10064. var curDepthWrite = engine.getDepthWrite() === true;
  10065. // ===================================================================
  10066. // First pass, update the InstancedArray and render Opaque primitives
  10067. // Disable Alpha Testing, Enable Depth Write
  10068. engine.setAlphaTesting(false);
  10069. engine.setDepthWrite(true);
  10070. // For each different model of primitive to render
  10071. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  10072. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  10073. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  10074. var renderCount = _this._prepareContext(engine, context_1, v);
  10075. // If null is returned, there's no opaque data to render
  10076. if (renderCount === null) {
  10077. return;
  10078. }
  10079. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  10080. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  10081. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  10082. var renderFailed = !v.modelRenderCache.render(v, context_1);
  10083. // Update dirty flag/related
  10084. v.opaqueDirty = renderFailed;
  10085. failedCount += renderFailed ? 1 : 0;
  10086. }
  10087. });
  10088. // =======================================================================
  10089. // Second pass, update the InstancedArray and render AlphaTest primitives
  10090. // Enable Alpha Testing, Enable Depth Write
  10091. engine.setAlphaTesting(true);
  10092. engine.setDepthWrite(true);
  10093. // For each different model of primitive to render
  10094. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  10095. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  10096. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  10097. var renderCount = _this._prepareContext(engine, context_1, v);
  10098. // If null is returned, there's no opaque data to render
  10099. if (renderCount === null) {
  10100. return;
  10101. }
  10102. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  10103. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  10104. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  10105. var renderFailed = !v.modelRenderCache.render(v, context_1);
  10106. // Update dirty flag/related
  10107. v.opaqueDirty = renderFailed;
  10108. failedCount += renderFailed ? 1 : 0;
  10109. }
  10110. });
  10111. // =======================================================================
  10112. // Third pass, transparent primitive rendering
  10113. // Enable Alpha Testing, Disable Depth Write
  10114. engine.setAlphaTesting(true);
  10115. engine.setDepthWrite(false);
  10116. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  10117. if (this._renderableData._transparentListChanged) {
  10118. this._updateTransparentData();
  10119. }
  10120. // From this point on we have up to date data to render, so let's go
  10121. failedCount += this._renderTransparentData();
  10122. // =======================================================================
  10123. // Unbind target/restore viewport setting, clear dirty flag, and quit
  10124. // The group's content is no longer dirty
  10125. this._cacheGroupDirty = failedCount !== 0;
  10126. if (this.isCachedGroup) {
  10127. this._unbindCacheTarget();
  10128. }
  10129. else {
  10130. if (curVP) {
  10131. engine.setViewport(curVP);
  10132. }
  10133. }
  10134. // Restore saved states
  10135. engine.setAlphaTesting(curAlphaTest);
  10136. engine.setDepthWrite(curDepthWrite);
  10137. }
  10138. };
  10139. Group2D.prototype._setCacheGroupDirty = function () {
  10140. this._cacheGroupDirty = true;
  10141. };
  10142. Group2D.prototype._updateTransparentData = function () {
  10143. this.owner._addUpdateTransparentDataCount(1);
  10144. var rd = this._renderableData;
  10145. // Sort all the primitive from their depth, max (bottom) to min (top)
  10146. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  10147. var checkAndAddPrimInSegment = function (seg, tpiI) {
  10148. var tpi = rd._transparentPrimitives[tpiI];
  10149. // Fast rejection: if gii are different
  10150. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  10151. return false;
  10152. }
  10153. //let tpiZ = tpi._primitive.actualZOffset;
  10154. // We've made it so far, the tpi can be part of the segment, add it
  10155. tpi._transparentSegment = seg;
  10156. tpi._primitive._updateTransparentSegmentIndices(seg);
  10157. return true;
  10158. };
  10159. // Free the existing TransparentSegments
  10160. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  10161. var ts = _a[_i];
  10162. ts.dispose(this.owner.engine);
  10163. }
  10164. rd._transparentSegments.splice(0);
  10165. var prevSeg = null;
  10166. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  10167. var tpi = rd._transparentPrimitives[tpiI];
  10168. // Check if the Data in which the primitive is stored is not sorted properly
  10169. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  10170. tpi._groupInstanceInfo.sortTransparentData();
  10171. }
  10172. // Reset the segment, we have to create/rebuild it
  10173. tpi._transparentSegment = null;
  10174. // If there's a previous valid segment, check if this prim can be part of it
  10175. if (prevSeg) {
  10176. checkAndAddPrimInSegment(prevSeg, tpiI);
  10177. }
  10178. // If we couldn't insert in the adjacent segments, he have to create one
  10179. if (!tpi._transparentSegment) {
  10180. var ts = new BABYLON.TransparentSegment();
  10181. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  10182. var prim = tpi._primitive;
  10183. ts.startZ = prim.actualZOffset;
  10184. prim._updateTransparentSegmentIndices(ts);
  10185. ts.endZ = ts.startZ;
  10186. tpi._transparentSegment = ts;
  10187. rd._transparentSegments.push(ts);
  10188. }
  10189. // Update prevSeg
  10190. prevSeg = tpi._transparentSegment;
  10191. }
  10192. //rd._firstChangedPrim = null;
  10193. rd._transparentListChanged = false;
  10194. };
  10195. Group2D.prototype._renderTransparentData = function () {
  10196. var failedCount = 0;
  10197. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  10198. var rd = this._renderableData;
  10199. var useInstanced = this.owner.supportInstancedArray;
  10200. var length = rd._transparentSegments.length;
  10201. for (var i = 0; i < length; i++) {
  10202. context.instancedBuffers = null;
  10203. var ts = rd._transparentSegments[i];
  10204. var gii = ts.groupInsanceInfo;
  10205. var mrc = gii.modelRenderCache;
  10206. var engine = this.owner.engine;
  10207. var count = ts.endDataIndex - ts.startDataIndex;
  10208. // Use Instanced Array if it's supported and if there's at least minPartCountToUseInstancedArray prims to draw.
  10209. // We don't want to create an Instanced Buffer for less that minPartCountToUseInstancedArray prims
  10210. if (useInstanced && count >= this.owner.minPartCountToUseInstancedArray) {
  10211. if (!ts.partBuffers) {
  10212. var buffers = new Array();
  10213. for (var j = 0; j < gii.transparentData.length; j++) {
  10214. var gitd = gii.transparentData[j];
  10215. var dfa = gitd._partData;
  10216. var data = dfa.pack();
  10217. var stride = dfa.stride;
  10218. var neededSize = count * stride * 4;
  10219. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  10220. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  10221. engine.updateArrayBuffer(segData);
  10222. buffers.push(buffer);
  10223. }
  10224. ts.partBuffers = buffers;
  10225. }
  10226. else if (gii.transparentDirty) {
  10227. for (var j = 0; j < gii.transparentData.length; j++) {
  10228. var gitd = gii.transparentData[j];
  10229. var dfa = gitd._partData;
  10230. var data = dfa.pack();
  10231. var stride = dfa.stride;
  10232. var buffer = ts.partBuffers[j];
  10233. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  10234. engine.bindArrayBuffer(buffer);
  10235. engine.updateArrayBuffer(segData);
  10236. }
  10237. }
  10238. context.useInstancing = true;
  10239. context.instancesCount = count;
  10240. context.instancedBuffers = ts.partBuffers;
  10241. context.groupInfoPartData = gii.transparentData;
  10242. var renderFailed = !mrc.render(gii, context);
  10243. failedCount += renderFailed ? 1 : 0;
  10244. }
  10245. else {
  10246. context.useInstancing = false;
  10247. context.partDataStartIndex = ts.startDataIndex;
  10248. context.partDataEndIndex = ts.endDataIndex;
  10249. context.groupInfoPartData = gii.transparentData;
  10250. var renderFailed = !mrc.render(gii, context);
  10251. failedCount += renderFailed ? 1 : 0;
  10252. }
  10253. }
  10254. return failedCount;
  10255. };
  10256. Group2D.prototype._prepareContext = function (engine, context, gii) {
  10257. var gipd = null;
  10258. var setDirty;
  10259. var getDirty;
  10260. // Render Mode specifics
  10261. switch (context.renderMode) {
  10262. case BABYLON.Render2DContext.RenderModeOpaque:
  10263. {
  10264. if (!gii.hasOpaqueData) {
  10265. return null;
  10266. }
  10267. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  10268. getDirty = function () { return gii.opaqueDirty; };
  10269. context.groupInfoPartData = gii.opaqueData;
  10270. gipd = gii.opaqueData;
  10271. break;
  10272. }
  10273. case BABYLON.Render2DContext.RenderModeAlphaTest:
  10274. {
  10275. if (!gii.hasAlphaTestData) {
  10276. return null;
  10277. }
  10278. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  10279. getDirty = function () { return gii.alphaTestDirty; };
  10280. context.groupInfoPartData = gii.alphaTestData;
  10281. gipd = gii.alphaTestData;
  10282. break;
  10283. }
  10284. default:
  10285. throw new Error("_prepareContext is only for opaque or alphaTest");
  10286. }
  10287. var renderCount = 0;
  10288. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  10289. // Skip it if instanced arrays are not supported
  10290. if (this.owner.supportInstancedArray) {
  10291. // Flag for instancing
  10292. context.useInstancing = true;
  10293. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  10294. for (var i = 0; i < gipd.length; i++) {
  10295. var pid = gipd[i];
  10296. // If the instances of the model was changed, pack the data
  10297. var array = pid._partData;
  10298. var instanceData_1 = array.pack();
  10299. renderCount += array.usedElementCount;
  10300. // Compute the size the instance buffer should have
  10301. var neededSize = array.usedElementCount * array.stride * 4;
  10302. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  10303. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  10304. if (pid._partBuffer) {
  10305. engine.deleteInstancesBuffer(pid._partBuffer);
  10306. }
  10307. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  10308. pid._partBufferSize = neededSize;
  10309. setDirty(false);
  10310. // Update the WebGL buffer to match the new content of the instances data
  10311. engine.updateArrayBuffer(instanceData_1);
  10312. }
  10313. else if (getDirty()) {
  10314. // Update the WebGL buffer to match the new content of the instances data
  10315. engine.bindArrayBuffer(pid._partBuffer);
  10316. engine.updateArrayBuffer(instanceData_1);
  10317. }
  10318. }
  10319. setDirty(false);
  10320. }
  10321. else {
  10322. context.partDataStartIndex = 0;
  10323. // Find the first valid object to get the count
  10324. if (context.groupInfoPartData.length > 0) {
  10325. var i = 0;
  10326. while (!context.groupInfoPartData[i]) {
  10327. i++;
  10328. }
  10329. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  10330. }
  10331. }
  10332. return renderCount;
  10333. };
  10334. Group2D.prototype._setRenderingScale = function (scale) {
  10335. if (this._renderableData._renderingScale === scale) {
  10336. return;
  10337. }
  10338. this._renderableData._renderingScale = scale;
  10339. };
  10340. Group2D.prototype._bindCacheTarget = function () {
  10341. var curWidth;
  10342. var curHeight;
  10343. var rd = this._renderableData;
  10344. var rs = rd._renderingScale;
  10345. var noResizeScale = rd._noResizeOnScale;
  10346. var isCanvas = this.parent == null;
  10347. var scale;
  10348. if (noResizeScale) {
  10349. scale = isCanvas ? Group2D_1._uV : this.parent.actualScale;
  10350. }
  10351. else {
  10352. scale = this.actualScale;
  10353. }
  10354. if (isCanvas && this.owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS && this.owner.isScreenSpace) {
  10355. if (this.owner.designSize || this.owner.fitRenderingDevice) {
  10356. Group2D_1._s.width = this.owner.engine.getRenderWidth();
  10357. Group2D_1._s.height = this.owner.engine.getRenderHeight();
  10358. }
  10359. else {
  10360. Group2D_1._s.copyFrom(this.owner.size);
  10361. }
  10362. }
  10363. else {
  10364. Group2D_1._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  10365. Group2D_1._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  10366. }
  10367. var sizeChanged = !Group2D_1._s.equals(rd._cacheSize);
  10368. if (rd._cacheNode) {
  10369. var size = rd._cacheNode.contentSize;
  10370. // Check if we have to deallocate because the size is too small
  10371. if ((size.width < Group2D_1._s.width) || (size.height < Group2D_1._s.height)) {
  10372. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  10373. // For World space: no over-provisioning
  10374. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  10375. curWidth = Math.floor(Group2D_1._s.width * overprovisioning);
  10376. curHeight = Math.floor(Group2D_1._s.height * overprovisioning);
  10377. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  10378. rd._cacheTexture.freeRect(rd._cacheNode);
  10379. rd._cacheNode = null;
  10380. }
  10381. }
  10382. if (!rd._cacheNode) {
  10383. // Check if we have to allocate a rendering zone in the global cache texture
  10384. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  10385. rd._cacheNode = res.node;
  10386. rd._cacheTexture = res.texture;
  10387. if (rd._cacheRenderSprite) {
  10388. rd._cacheRenderSprite.dispose();
  10389. }
  10390. rd._cacheRenderSprite = res.sprite;
  10391. sizeChanged = true;
  10392. }
  10393. if (sizeChanged) {
  10394. rd._cacheSize.copyFrom(Group2D_1._s);
  10395. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  10396. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  10397. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  10398. }
  10399. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  10400. }
  10401. var n = rd._cacheNode;
  10402. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D_1._s, true);
  10403. };
  10404. Group2D.prototype._unbindCacheTarget = function () {
  10405. if (this._renderableData._cacheTexture) {
  10406. this._renderableData._cacheTexture.unbindTexture();
  10407. }
  10408. };
  10409. Group2D.prototype._spreadActualScaleDirty = function () {
  10410. if (this._renderableData && this._renderableData._cacheRenderSprite) {
  10411. this.handleGroupChanged(BABYLON.Prim2DBase.actualScaleProperty);
  10412. }
  10413. _super.prototype._spreadActualScaleDirty.call(this);
  10414. };
  10415. Group2D.prototype.handleGroupChanged = function (prop) {
  10416. // This method is only for cachedGroup
  10417. var rd = this._renderableData;
  10418. if (!rd) {
  10419. return;
  10420. }
  10421. var cachedSprite = rd._cacheRenderSprite;
  10422. if (!this.isCachedGroup || !cachedSprite) {
  10423. return;
  10424. }
  10425. // For now we only support these property changes
  10426. // TODO: add more! :)
  10427. switch (prop.id) {
  10428. case BABYLON.Prim2DBase.actualPositionProperty.id:
  10429. cachedSprite.actualPosition = this.actualPosition.clone();
  10430. if (cachedSprite.position != null) {
  10431. cachedSprite.position = cachedSprite.actualPosition.clone();
  10432. }
  10433. break;
  10434. case BABYLON.Prim2DBase.rotationProperty.id:
  10435. cachedSprite.rotation = this.rotation;
  10436. break;
  10437. case BABYLON.Prim2DBase.scaleProperty.id:
  10438. cachedSprite.scale = this.scale;
  10439. break;
  10440. case BABYLON.Prim2DBase.originProperty.id:
  10441. cachedSprite.origin = this.origin.clone();
  10442. break;
  10443. case Group2D_1.actualSizeProperty.id:
  10444. cachedSprite.size = this.actualSize.clone();
  10445. break;
  10446. }
  10447. };
  10448. Group2D.prototype.detectGroupStates = function () {
  10449. var isCanvas = this instanceof BABYLON.Canvas2D;
  10450. var canvasStrat = this.owner.cachingStrategy;
  10451. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  10452. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  10453. this._isRenderableGroup = isCanvas;
  10454. this._isCachedGroup = false;
  10455. }
  10456. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  10457. if (isCanvas) {
  10458. this._isRenderableGroup = true;
  10459. this._isCachedGroup = true;
  10460. }
  10461. else {
  10462. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  10463. this._isCachedGroup = false;
  10464. }
  10465. }
  10466. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  10467. if (isCanvas) {
  10468. this._isRenderableGroup = true;
  10469. this._isCachedGroup = false;
  10470. }
  10471. else {
  10472. if (this.hierarchyDepth === 1) {
  10473. this._isRenderableGroup = true;
  10474. this._isCachedGroup = true;
  10475. }
  10476. else {
  10477. this._isRenderableGroup = false;
  10478. this._isCachedGroup = false;
  10479. }
  10480. }
  10481. }
  10482. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  10483. if (isCanvas) {
  10484. this._isRenderableGroup = true;
  10485. this._isCachedGroup = false;
  10486. }
  10487. else {
  10488. var gcb = this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_OPTIONMASK;
  10489. if ((gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D_1.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  10490. this._isRenderableGroup = gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  10491. this._isCachedGroup = false;
  10492. }
  10493. if (gcb === Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  10494. this._isRenderableGroup = true;
  10495. this._isCachedGroup = true;
  10496. }
  10497. }
  10498. }
  10499. if (this._isRenderableGroup) {
  10500. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  10501. if (!this._renderableData) {
  10502. this._renderableData = new RenderableGroupData();
  10503. }
  10504. }
  10505. // If the group is tagged as renderable we add it to the renderable tree
  10506. if (this._isCachedGroup) {
  10507. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  10508. var cur = this.parent;
  10509. while (cur) {
  10510. if (cur instanceof Group2D_1 && cur._isRenderableGroup) {
  10511. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  10512. cur._renderableData._childrenRenderableGroups.push(this);
  10513. }
  10514. break;
  10515. }
  10516. cur = cur.parent;
  10517. }
  10518. }
  10519. };
  10520. return Group2D;
  10521. }(BABYLON.Prim2DBase));
  10522. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  10523. /**
  10524. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  10525. */
  10526. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  10527. /**
  10528. * When used, this group's content won't be cached, no matter which strategy used.
  10529. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  10530. */
  10531. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  10532. /**
  10533. * When used, the group's content will be cached in the nearest cached parent group/canvas
  10534. */
  10535. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  10536. /**
  10537. * 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
  10538. */
  10539. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  10540. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  10541. Group2D._uV = new BABYLON.Vector2(1, 1);
  10542. Group2D._s = BABYLON.Size.Zero();
  10543. Group2D._unS = new BABYLON.Vector2(1, 1);
  10544. __decorate([
  10545. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D_1.sizeProperty = pi; }, false, true)
  10546. ], Group2D.prototype, "size", null);
  10547. __decorate([
  10548. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D_1.actualSizeProperty = pi; })
  10549. ], Group2D.prototype, "actualSize", null);
  10550. Group2D = Group2D_1 = __decorate([
  10551. BABYLON.className("Group2D", "BABYLON")
  10552. ], Group2D);
  10553. BABYLON.Group2D = Group2D;
  10554. var RenderableGroupData = (function () {
  10555. function RenderableGroupData() {
  10556. this._primDirtyList = new Array();
  10557. this._primNewDirtyList = new Array();
  10558. this._childrenRenderableGroups = new Array();
  10559. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  10560. this._transparentPrimitives = new Array();
  10561. this._transparentSegments = new Array();
  10562. this._transparentListChanged = false;
  10563. this._cacheNode = null;
  10564. this._cacheTexture = null;
  10565. this._cacheRenderSprite = null;
  10566. this._renderingScale = 1;
  10567. this._cacheNodeUVs = null;
  10568. this._cacheNodeUVsChangedObservable = null;
  10569. this._cacheSize = BABYLON.Size.Zero();
  10570. this._useMipMap = false;
  10571. this._anisotropicLevel = 1;
  10572. this._noResizeOnScale = false;
  10573. }
  10574. RenderableGroupData.prototype.dispose = function (owner) {
  10575. var engine = owner.engine;
  10576. if (this._cacheRenderSprite) {
  10577. this._cacheRenderSprite.dispose();
  10578. this._cacheRenderSprite = null;
  10579. }
  10580. if (this._cacheTexture && this._cacheNode) {
  10581. this._cacheTexture.freeRect(this._cacheNode);
  10582. this._cacheTexture = null;
  10583. this._cacheNode = null;
  10584. }
  10585. if (this._primDirtyList) {
  10586. this._primDirtyList.splice(0);
  10587. this._primDirtyList = null;
  10588. }
  10589. if (this._renderGroupInstancesInfo) {
  10590. this._renderGroupInstancesInfo.forEach(function (k, v) {
  10591. v.dispose();
  10592. });
  10593. this._renderGroupInstancesInfo = null;
  10594. }
  10595. if (this._cacheNodeUVsChangedObservable) {
  10596. this._cacheNodeUVsChangedObservable.clear();
  10597. this._cacheNodeUVsChangedObservable = null;
  10598. }
  10599. if (this._transparentSegments) {
  10600. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  10601. var ts = _a[_i];
  10602. ts.dispose(engine);
  10603. }
  10604. this._transparentSegments.splice(0);
  10605. this._transparentSegments = null;
  10606. }
  10607. };
  10608. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  10609. var tpi = new TransparentPrimitiveInfo();
  10610. tpi._primitive = prim;
  10611. tpi._groupInstanceInfo = gii;
  10612. tpi._transparentSegment = null;
  10613. this._transparentPrimitives.push(tpi);
  10614. this._transparentListChanged = true;
  10615. return tpi;
  10616. };
  10617. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  10618. var index = this._transparentPrimitives.indexOf(tpi);
  10619. if (index !== -1) {
  10620. this._transparentPrimitives.splice(index, 1);
  10621. this._transparentListChanged = true;
  10622. }
  10623. };
  10624. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  10625. this._transparentListChanged = true;
  10626. //this.updateSmallestZChangedPrim(tpi);
  10627. };
  10628. return RenderableGroupData;
  10629. }());
  10630. BABYLON.RenderableGroupData = RenderableGroupData;
  10631. var TransparentPrimitiveInfo = (function () {
  10632. function TransparentPrimitiveInfo() {
  10633. }
  10634. return TransparentPrimitiveInfo;
  10635. }());
  10636. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  10637. var Group2D_1;
  10638. })(BABYLON || (BABYLON = {}));
  10639. //# sourceMappingURL=babylon.group2d.js.map
  10640. var __extends = (this && this.__extends) || function (d, b) {
  10641. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10642. function __() { this.constructor = d; }
  10643. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  10644. };
  10645. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  10646. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  10647. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  10648. 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;
  10649. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10650. };
  10651. var BABYLON;
  10652. (function (BABYLON) {
  10653. var WireFrame2DRenderCache = (function (_super) {
  10654. __extends(WireFrame2DRenderCache, _super);
  10655. function WireFrame2DRenderCache() {
  10656. var _this = _super !== null && _super.apply(this, arguments) || this;
  10657. _this.effectsReady = false;
  10658. _this.vb = null;
  10659. _this.vtxCount = 0;
  10660. _this.instancingAttributes = null;
  10661. _this.effect = null;
  10662. _this.effectInstanced = null;
  10663. return _this;
  10664. }
  10665. WireFrame2DRenderCache.prototype.render = function (instanceInfo, context) {
  10666. // Do nothing if the shader is still loading/preparing
  10667. if (!this.effectsReady) {
  10668. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  10669. return false;
  10670. }
  10671. this.effectsReady = true;
  10672. }
  10673. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  10674. var canvas = instanceInfo.owner.owner;
  10675. var engine = canvas.engine;
  10676. var cur = engine.getAlphaMode();
  10677. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  10678. engine.enableEffect(effect);
  10679. engine.bindBuffersDirectly(this.vb, null, [2, 4], 24, effect);
  10680. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  10681. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  10682. }
  10683. var pid = context.groupInfoPartData[0];
  10684. if (context.useInstancing) {
  10685. if (!this.instancingAttributes) {
  10686. this.instancingAttributes = this.loadInstancingAttributes(WireFrame2D.WIREFRAME2D_MAINPARTID, effect);
  10687. }
  10688. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  10689. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  10690. canvas._addDrawCallCount(1, context.renderMode);
  10691. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  10692. engine.drawUnIndexed(false, 0, this.vtxCount, count);
  10693. // engine.draw(true, 0, 6, count);
  10694. engine.unbindInstanceAttributes();
  10695. }
  10696. else {
  10697. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  10698. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  10699. this.setupUniforms(effect, 0, pid._partData, i);
  10700. engine.drawUnIndexed(false, 0, this.vtxCount);
  10701. }
  10702. }
  10703. engine.setAlphaMode(cur, true);
  10704. return true;
  10705. };
  10706. WireFrame2DRenderCache.prototype.updateModelRenderCache = function (prim) {
  10707. var w = prim;
  10708. w._updateVertexBuffer(this);
  10709. return true;
  10710. };
  10711. WireFrame2DRenderCache.prototype.dispose = function () {
  10712. if (!_super.prototype.dispose.call(this)) {
  10713. return false;
  10714. }
  10715. if (this.vb) {
  10716. this._engine._releaseBuffer(this.vb);
  10717. this.vb = null;
  10718. }
  10719. this.effect = null;
  10720. this.effectInstanced = null;
  10721. return true;
  10722. };
  10723. return WireFrame2DRenderCache;
  10724. }(BABYLON.ModelRenderCache));
  10725. BABYLON.WireFrame2DRenderCache = WireFrame2DRenderCache;
  10726. var WireFrameVertex2D = (function () {
  10727. function WireFrameVertex2D(p, c) {
  10728. if (c === void 0) { c = null; }
  10729. this.fromVector2(p);
  10730. if (c != null) {
  10731. this.fromColor4(c);
  10732. }
  10733. else {
  10734. this.r = this.g = this.b = this.a = 1;
  10735. }
  10736. }
  10737. WireFrameVertex2D.prototype.fromVector2 = function (p) {
  10738. this.x = p.x;
  10739. this.y = p.y;
  10740. };
  10741. WireFrameVertex2D.prototype.fromColor3 = function (c) {
  10742. this.r = c.r;
  10743. this.g = c.g;
  10744. this.b = c.b;
  10745. this.a = 1;
  10746. };
  10747. WireFrameVertex2D.prototype.fromColor4 = function (c) {
  10748. this.r = c.r;
  10749. this.g = c.g;
  10750. this.b = c.b;
  10751. this.a = c.a;
  10752. };
  10753. return WireFrameVertex2D;
  10754. }());
  10755. WireFrameVertex2D = __decorate([
  10756. BABYLON.className("WireFrameVertex2D", "BABYLON")
  10757. ], WireFrameVertex2D);
  10758. BABYLON.WireFrameVertex2D = WireFrameVertex2D;
  10759. var WireFrameGroup2D = (function () {
  10760. /**
  10761. * Construct a WireFrameGroup2D object
  10762. * @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.
  10763. * @param defaultColor specify the default color that will be used when a vertex is pushed, white will be used if not specified.
  10764. */
  10765. function WireFrameGroup2D(id, defaultColor) {
  10766. if (id === void 0) { id = null; }
  10767. if (defaultColor === void 0) { defaultColor = null; }
  10768. this._id = (id == null) ? BABYLON.Tools.RandomId() : id;
  10769. this._uid = BABYLON.Tools.RandomId();
  10770. this._defaultColor = (defaultColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : defaultColor;
  10771. this._buildingStrip = false;
  10772. this._vertices = new Array();
  10773. }
  10774. Object.defineProperty(WireFrameGroup2D.prototype, "uid", {
  10775. get: function () {
  10776. return this._uid;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(WireFrameGroup2D.prototype, "id", {
  10782. /**
  10783. * Retrieve the ID of the group
  10784. */
  10785. get: function () {
  10786. return this._id;
  10787. },
  10788. enumerable: true,
  10789. configurable: true
  10790. });
  10791. /**
  10792. * Push a vertex in the array of vertices.
  10793. * 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.
  10794. * @param p Position of the vertex
  10795. * @param c Color of the vertex, if null the default color of the group will be used
  10796. */
  10797. WireFrameGroup2D.prototype.pushVertex = function (p, c) {
  10798. if (c === void 0) { c = null; }
  10799. var v = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  10800. this._vertices.push(v);
  10801. if (this._buildingStrip) {
  10802. var v2 = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  10803. this._vertices.push(v2);
  10804. }
  10805. };
  10806. /**
  10807. * 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!!!
  10808. * @param p Position of the vertex
  10809. * @param c Color of the vertex, if null the default color of the group will be used
  10810. */
  10811. WireFrameGroup2D.prototype.startLineStrip = function (p, c) {
  10812. if (c === void 0) { c = null; }
  10813. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  10814. this._buildingStrip = true;
  10815. };
  10816. /**
  10817. * Close the Strip by storing a last vertex
  10818. * @param p Position of the vertex
  10819. * @param c Color of the vertex, if null the default color of the group will be used
  10820. */
  10821. WireFrameGroup2D.prototype.endLineStrip = function (p, c) {
  10822. if (c === void 0) { c = null; }
  10823. this._buildingStrip = false;
  10824. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  10825. };
  10826. Object.defineProperty(WireFrameGroup2D.prototype, "vertices", {
  10827. /**
  10828. * Access to the array of Vertices, you can manipulate its content but BEWARE of what you're doing!
  10829. */
  10830. get: function () {
  10831. return this._vertices;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. return WireFrameGroup2D;
  10837. }());
  10838. WireFrameGroup2D = __decorate([
  10839. BABYLON.className("WireFrameGroup2D", "BABYLON")
  10840. ], WireFrameGroup2D);
  10841. BABYLON.WireFrameGroup2D = WireFrameGroup2D;
  10842. var WireFrame2D = WireFrame2D_1 = (function (_super) {
  10843. __extends(WireFrame2D, _super);
  10844. /**
  10845. * Create an WireFrame 2D primitive
  10846. * @param wireFrameGroups an array of WireFrameGroup.
  10847. * @param settings a combination of settings, possible ones are
  10848. * - 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)
  10849. * - children: an array of direct children
  10850. * - id a text identifier, for information purpose
  10851. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  10852. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  10853. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  10854. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  10855. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  10856. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  10857. * - zOrder: override the zOrder with the specified value
  10858. * - origin: define the normalized origin point location, default [0.5;0.5]
  10859. * - alignToPixel: the rendered lines will be aligned to the rendering device' pixels
  10860. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  10861. * - 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.
  10862. * - 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.
  10863. * - 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!
  10864. * - 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.
  10865. * - 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).
  10866. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  10867. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10868. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10869. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10870. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10871. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  10872. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  10873. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  10874. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  10875. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10876. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10877. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10878. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10879. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  10880. */
  10881. function WireFrame2D(wireFrameGroups, settings) {
  10882. var _this = this;
  10883. if (!settings) {
  10884. settings = {};
  10885. }
  10886. _this = _super.call(this, settings) || this;
  10887. _this._wireFrameGroups = new BABYLON.StringDictionary();
  10888. for (var _i = 0, wireFrameGroups_1 = wireFrameGroups; _i < wireFrameGroups_1.length; _i++) {
  10889. var wfg = wireFrameGroups_1[_i];
  10890. _this._wireFrameGroups.add(wfg.id, wfg);
  10891. }
  10892. _this._vtxTransparent = false;
  10893. if (settings.size != null) {
  10894. _this.size = settings.size;
  10895. }
  10896. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  10897. return _this;
  10898. }
  10899. Object.defineProperty(WireFrame2D.prototype, "wireFrameGroups", {
  10900. get: function () {
  10901. return this._wireFrameGroups;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. /**
  10907. * If you change the content of the wireFrameGroups you MUST call this method for the changes to be reflected during rendering
  10908. */
  10909. WireFrame2D.prototype.wireFrameGroupsDirty = function () {
  10910. this._setFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  10911. this.onPrimBecomesDirty();
  10912. };
  10913. Object.defineProperty(WireFrame2D.prototype, "size", {
  10914. get: function () {
  10915. if (this._size == null) {
  10916. this._computeMinMaxTrans();
  10917. }
  10918. return this._size;
  10919. },
  10920. set: function (value) {
  10921. this.internalSetSize(value);
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(WireFrame2D.prototype, "actualSize", {
  10927. get: function () {
  10928. if (this._actualSize) {
  10929. return this._actualSize;
  10930. }
  10931. return this.size;
  10932. },
  10933. set: function (value) {
  10934. this._actualSize = value;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. WireFrame2D.prototype.updateLevelBoundingInfo = function () {
  10940. var v = this._computeMinMaxTrans();
  10941. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(v.x, v.z, v.y, v.w, this._levelBoundingInfo);
  10942. return true;
  10943. };
  10944. WireFrame2D.prototype.levelIntersect = function (intersectInfo) {
  10945. // TODO !
  10946. return true;
  10947. };
  10948. Object.defineProperty(WireFrame2D.prototype, "alignToPixel", {
  10949. /**
  10950. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  10951. */
  10952. get: function () {
  10953. return this._alignToPixel;
  10954. },
  10955. set: function (value) {
  10956. this._alignToPixel = value;
  10957. },
  10958. enumerable: true,
  10959. configurable: true
  10960. });
  10961. WireFrame2D.prototype.createModelRenderCache = function (modelKey) {
  10962. var renderCache = new WireFrame2DRenderCache(this.owner.engine, modelKey);
  10963. return renderCache;
  10964. };
  10965. WireFrame2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  10966. var renderCache = modelRenderCache;
  10967. var engine = this.owner.engine;
  10968. // Create the VertexBuffer
  10969. this._updateVertexBuffer(renderCache);
  10970. // 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
  10971. var ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], true);
  10972. if (ei) {
  10973. renderCache.effectInstanced = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  10974. }
  10975. ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], false);
  10976. renderCache.effect = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  10977. return renderCache;
  10978. };
  10979. WireFrame2D.prototype._updateVertexBuffer = function (mrc) {
  10980. var engine = this.owner.engine;
  10981. if (mrc.vb != null) {
  10982. engine._releaseBuffer(mrc.vb);
  10983. }
  10984. var vtxCount = 0;
  10985. this._wireFrameGroups.forEach(function (k, v) { return vtxCount += v.vertices.length; });
  10986. var vb = new Float32Array(vtxCount * 6);
  10987. var i = 0;
  10988. this._wireFrameGroups.forEach(function (k, v) {
  10989. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  10990. var vtx = _a[_i];
  10991. vb[i++] = vtx.x;
  10992. vb[i++] = vtx.y;
  10993. vb[i++] = vtx.r;
  10994. vb[i++] = vtx.g;
  10995. vb[i++] = vtx.b;
  10996. vb[i++] = vtx.a;
  10997. }
  10998. });
  10999. mrc.vb = engine.createVertexBuffer(vb);
  11000. mrc.vtxCount = vtxCount;
  11001. };
  11002. WireFrame2D.prototype.refreshInstanceDataPart = function (part) {
  11003. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  11004. return false;
  11005. }
  11006. if (part.id === WireFrame2D_1.WIREFRAME2D_MAINPARTID) {
  11007. var d = this._instanceDataParts[0];
  11008. d.properties = new BABYLON.Vector3(this.alignToPixel ? 1 : 0, 2 / this.renderGroup.actualWidth, 2 / this.renderGroup.actualHeight);
  11009. }
  11010. return true;
  11011. };
  11012. WireFrame2D.prototype._computeMinMaxTrans = function () {
  11013. var xmin = Number.MAX_VALUE;
  11014. var xmax = Number.MIN_VALUE;
  11015. var ymin = Number.MAX_VALUE;
  11016. var ymax = Number.MIN_VALUE;
  11017. var transparent = false;
  11018. this._wireFrameGroups.forEach(function (k, v) {
  11019. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  11020. var vtx = _a[_i];
  11021. xmin = Math.min(xmin, vtx.x);
  11022. xmax = Math.max(xmax, vtx.x);
  11023. ymin = Math.min(ymin, vtx.y);
  11024. ymax = Math.max(ymax, vtx.y);
  11025. if (vtx.a < 1) {
  11026. transparent = true;
  11027. }
  11028. }
  11029. });
  11030. this._vtxTransparent = transparent;
  11031. this._size = new BABYLON.Size(xmax - xmin, ymax - ymin);
  11032. return new BABYLON.Vector4(xmin, ymin, xmax, ymax);
  11033. };
  11034. WireFrame2D.prototype.createInstanceDataParts = function () {
  11035. return [new WireFrame2DInstanceData(WireFrame2D_1.WIREFRAME2D_MAINPARTID)];
  11036. };
  11037. return WireFrame2D;
  11038. }(BABYLON.RenderablePrim2D));
  11039. WireFrame2D.WIREFRAME2D_MAINPARTID = 1;
  11040. __decorate([
  11041. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return WireFrame2D_1.wireFrameGroupsProperty = pi; })
  11042. ], WireFrame2D.prototype, "wireFrameGroups", null);
  11043. __decorate([
  11044. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return WireFrame2D_1.actualSizeProperty = pi; }, false, true)
  11045. ], WireFrame2D.prototype, "actualSize", null);
  11046. WireFrame2D = WireFrame2D_1 = __decorate([
  11047. BABYLON.className("WireFrame2D", "BABYLON")
  11048. ], WireFrame2D);
  11049. BABYLON.WireFrame2D = WireFrame2D;
  11050. var WireFrame2DInstanceData = (function (_super) {
  11051. __extends(WireFrame2DInstanceData, _super);
  11052. function WireFrame2DInstanceData(partId) {
  11053. return _super.call(this, partId, 1) || this;
  11054. }
  11055. Object.defineProperty(WireFrame2DInstanceData.prototype, "properties", {
  11056. // the properties is for now the alignedToPixel value
  11057. get: function () {
  11058. return null;
  11059. },
  11060. set: function (value) {
  11061. },
  11062. enumerable: true,
  11063. configurable: true
  11064. });
  11065. return WireFrame2DInstanceData;
  11066. }(BABYLON.InstanceDataBase));
  11067. __decorate([
  11068. BABYLON.instanceData()
  11069. ], WireFrame2DInstanceData.prototype, "properties", null);
  11070. BABYLON.WireFrame2DInstanceData = WireFrame2DInstanceData;
  11071. var WireFrame2D_1;
  11072. })(BABYLON || (BABYLON = {}));
  11073. //# sourceMappingURL=babylon.wireFrame2d.js.map
  11074. var __extends = (this && this.__extends) || function (d, b) {
  11075. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11076. function __() { this.constructor = d; }
  11077. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11078. };
  11079. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11080. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11081. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11082. 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;
  11083. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11084. };
  11085. var BABYLON;
  11086. (function (BABYLON) {
  11087. var Rectangle2DRenderCache = (function (_super) {
  11088. __extends(Rectangle2DRenderCache, _super);
  11089. function Rectangle2DRenderCache(engine, modelKey) {
  11090. var _this = _super.call(this, engine, modelKey) || this;
  11091. _this.effectsReady = false;
  11092. _this.fillVB = null;
  11093. _this.fillIB = null;
  11094. _this.fillIndicesCount = 0;
  11095. _this.instancingFillAttributes = null;
  11096. _this.effectFill = null;
  11097. _this.effectFillInstanced = null;
  11098. _this.borderVB = null;
  11099. _this.borderIB = null;
  11100. _this.borderIndicesCount = 0;
  11101. _this.instancingBorderAttributes = null;
  11102. _this.effectBorder = null;
  11103. _this.effectBorderInstanced = null;
  11104. return _this;
  11105. }
  11106. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  11107. // Do nothing if the shader is still loading/preparing
  11108. if (!this.effectsReady) {
  11109. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  11110. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  11111. return false;
  11112. }
  11113. this.effectsReady = true;
  11114. }
  11115. var canvas = instanceInfo.owner.owner;
  11116. var engine = canvas.engine;
  11117. var depthFunction = 0;
  11118. if (this.effectFill && this.effectBorder) {
  11119. depthFunction = engine.getDepthFunction();
  11120. engine.setDepthFunctionToLessOrEqual();
  11121. }
  11122. var curAlphaMode = engine.getAlphaMode();
  11123. if (this.effectFill) {
  11124. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  11125. var pid = context.groupInfoPartData[partIndex];
  11126. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11127. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11128. }
  11129. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  11130. engine.enableEffect(effect);
  11131. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  11132. if (context.useInstancing) {
  11133. if (!this.instancingFillAttributes) {
  11134. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  11135. }
  11136. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11137. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11138. canvas._addDrawCallCount(1, context.renderMode);
  11139. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  11140. engine.draw(true, 0, this.fillIndicesCount, count);
  11141. engine.unbindInstanceAttributes();
  11142. }
  11143. else {
  11144. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11145. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11146. this.setupUniforms(effect, partIndex, pid._partData, i);
  11147. engine.draw(true, 0, this.fillIndicesCount);
  11148. }
  11149. }
  11150. }
  11151. if (this.effectBorder) {
  11152. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  11153. var pid = context.groupInfoPartData[partIndex];
  11154. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11155. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11156. }
  11157. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  11158. engine.enableEffect(effect);
  11159. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  11160. if (context.useInstancing) {
  11161. if (!this.instancingBorderAttributes) {
  11162. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  11163. }
  11164. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11165. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11166. canvas._addDrawCallCount(1, context.renderMode);
  11167. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  11168. engine.draw(true, 0, this.borderIndicesCount, count);
  11169. engine.unbindInstanceAttributes();
  11170. }
  11171. else {
  11172. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11173. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11174. this.setupUniforms(effect, partIndex, pid._partData, i);
  11175. engine.draw(true, 0, this.borderIndicesCount);
  11176. }
  11177. }
  11178. }
  11179. engine.setAlphaMode(curAlphaMode, true);
  11180. if (this.effectFill && this.effectBorder) {
  11181. engine.setDepthFunction(depthFunction);
  11182. }
  11183. return true;
  11184. };
  11185. Rectangle2DRenderCache.prototype.dispose = function () {
  11186. if (!_super.prototype.dispose.call(this)) {
  11187. return false;
  11188. }
  11189. if (this.fillVB) {
  11190. this._engine._releaseBuffer(this.fillVB);
  11191. this.fillVB = null;
  11192. }
  11193. if (this.fillIB) {
  11194. this._engine._releaseBuffer(this.fillIB);
  11195. this.fillIB = null;
  11196. }
  11197. this.effectFill = null;
  11198. this.effectFillInstanced = null;
  11199. this.effectBorder = null;
  11200. this.effectBorderInstanced = null;
  11201. if (this.borderVB) {
  11202. this._engine._releaseBuffer(this.borderVB);
  11203. this.borderVB = null;
  11204. }
  11205. if (this.borderIB) {
  11206. this._engine._releaseBuffer(this.borderIB);
  11207. this.borderIB = null;
  11208. }
  11209. return true;
  11210. };
  11211. return Rectangle2DRenderCache;
  11212. }(BABYLON.ModelRenderCache));
  11213. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  11214. var Rectangle2DInstanceData = (function (_super) {
  11215. __extends(Rectangle2DInstanceData, _super);
  11216. function Rectangle2DInstanceData(partId) {
  11217. return _super.call(this, partId, 1) || this;
  11218. }
  11219. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  11220. get: function () {
  11221. return null;
  11222. },
  11223. set: function (value) {
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. return Rectangle2DInstanceData;
  11229. }(BABYLON.Shape2DInstanceData));
  11230. __decorate([
  11231. BABYLON.instanceData()
  11232. ], Rectangle2DInstanceData.prototype, "properties", null);
  11233. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  11234. var Rectangle2D = Rectangle2D_1 = (function (_super) {
  11235. __extends(Rectangle2D, _super);
  11236. /**
  11237. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  11238. * @param settings a combination of settings, possible ones are
  11239. * - 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)
  11240. * - children: an array of direct children
  11241. * - id a text identifier, for information purpose
  11242. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  11243. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  11244. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  11245. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  11246. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  11247. * - zOrder: override the zOrder with the specified value
  11248. * - origin: define the normalized origin point location, default [0.5;0.5]
  11249. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  11250. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  11251. * - 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)
  11252. * - 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)
  11253. * - borderThickness: the thickness of the drawn border, default is 1.
  11254. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  11255. * - 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.
  11256. * - 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.
  11257. * - 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!
  11258. * - 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.
  11259. * - 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).
  11260. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  11261. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11262. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11263. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11264. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11265. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  11266. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  11267. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  11268. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  11269. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11270. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11271. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11272. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11273. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  11274. */
  11275. function Rectangle2D(settings) {
  11276. var _this = this;
  11277. // Avoid checking every time if the object exists
  11278. if (settings == null) {
  11279. settings = {};
  11280. }
  11281. _this = _super.call(this, settings) || this;
  11282. if (settings.size != null) {
  11283. _this.size = settings.size;
  11284. }
  11285. else if (settings.width || settings.height) {
  11286. var size = new BABYLON.Size(settings.width, settings.height);
  11287. _this.size = size;
  11288. }
  11289. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  11290. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  11291. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  11292. //this.size = size;
  11293. _this.roundRadius = roundRadius;
  11294. _this.borderThickness = borderThickness;
  11295. return _this;
  11296. }
  11297. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  11298. get: function () {
  11299. if (this._actualSize) {
  11300. return this._actualSize;
  11301. }
  11302. return this.size;
  11303. },
  11304. set: function (value) {
  11305. this._actualSize = value;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  11311. get: function () {
  11312. return this._notRounded;
  11313. },
  11314. set: function (value) {
  11315. this._notRounded = value;
  11316. },
  11317. enumerable: true,
  11318. configurable: true
  11319. });
  11320. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  11321. get: function () {
  11322. return this._roundRadius;
  11323. },
  11324. set: function (value) {
  11325. this._roundRadius = value;
  11326. this.notRounded = value === 0;
  11327. this._positioningDirty();
  11328. },
  11329. enumerable: true,
  11330. configurable: true
  11331. });
  11332. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  11333. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  11334. if (this.notRounded) {
  11335. return true;
  11336. }
  11337. // 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.
  11338. // 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)
  11339. // 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.
  11340. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  11341. var size = this.size;
  11342. Rectangle2D_1._i0.x = intersectInfo._localPickPosition.x;
  11343. Rectangle2D_1._i0.y = intersectInfo._localPickPosition.y;
  11344. var rr = this.roundRadius;
  11345. var rrs = rr * rr;
  11346. // Check if the point is in the bottom/left quarter area
  11347. Rectangle2D_1._i1.x = rr;
  11348. Rectangle2D_1._i1.y = rr;
  11349. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  11350. // Compute the intersection point in the quarter local space
  11351. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11352. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11353. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11354. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11355. }
  11356. // Check if the point is in the top/left quarter area
  11357. Rectangle2D_1._i1.x = rr;
  11358. Rectangle2D_1._i1.y = size.height - rr;
  11359. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  11360. // Compute the intersection point in the quarter local space
  11361. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11362. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11363. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11364. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11365. }
  11366. // Check if the point is in the top/right quarter area
  11367. Rectangle2D_1._i1.x = size.width - rr;
  11368. Rectangle2D_1._i1.y = size.height - rr;
  11369. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  11370. // Compute the intersection point in the quarter local space
  11371. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11372. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11373. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11374. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11375. }
  11376. // Check if the point is in the bottom/right quarter area
  11377. Rectangle2D_1._i1.x = size.width - rr;
  11378. Rectangle2D_1._i1.y = rr;
  11379. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  11380. // Compute the intersection point in the quarter local space
  11381. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  11382. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  11383. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  11384. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  11385. }
  11386. // At any other locations the point is guarantied to be inside
  11387. return true;
  11388. };
  11389. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  11390. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  11391. return true;
  11392. };
  11393. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  11394. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  11395. return renderCache;
  11396. };
  11397. Rectangle2D.prototype.updateTriArray = function () {
  11398. // Not Rounded = sharp edge rect, the default implementation is the right one!
  11399. if (this.notRounded) {
  11400. _super.prototype.updateTriArray.call(this);
  11401. return;
  11402. }
  11403. // Rounded Corner? It's more complicated! :)
  11404. var subDiv = Rectangle2D_1.roundSubdivisions * 4;
  11405. if (this._primTriArray == null) {
  11406. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  11407. }
  11408. else {
  11409. this._primTriArray.clear(subDiv);
  11410. }
  11411. var size = this.actualSize;
  11412. var w = size.width;
  11413. var h = size.height;
  11414. var r = this.roundRadius;
  11415. var rsub0 = subDiv * 0.25;
  11416. var rsub1 = subDiv * 0.50;
  11417. var rsub2 = subDiv * 0.75;
  11418. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  11419. var twopi = Math.PI * 2;
  11420. var nru = r / w;
  11421. var nrv = r / h;
  11422. var computePos = function (index, p) {
  11423. // right/bottom
  11424. if (index < rsub0) {
  11425. p.x = 1.0 - nru;
  11426. p.y = nrv;
  11427. }
  11428. else if (index < rsub1) {
  11429. p.x = nru;
  11430. p.y = nrv;
  11431. }
  11432. else if (index < rsub2) {
  11433. p.x = nru;
  11434. p.y = 1.0 - nrv;
  11435. }
  11436. else {
  11437. p.x = 1.0 - nru;
  11438. p.y = 1.0 - nrv;
  11439. }
  11440. var angle = twopi - (index * twopi / (subDiv - 0.5));
  11441. p.x += Math.cos(angle) * nru;
  11442. p.y += Math.sin(angle) * nrv;
  11443. p.x *= w;
  11444. p.y *= h;
  11445. };
  11446. console.log("Genetre TriList for " + this.id);
  11447. var first = BABYLON.Vector2.Zero();
  11448. var cur = BABYLON.Vector2.Zero();
  11449. computePos(0, first);
  11450. var prev = first.clone();
  11451. for (var index = 1; index < subDiv; index++) {
  11452. computePos(index, cur);
  11453. this._primTriArray.storeTriangle(index - 1, center, prev, cur);
  11454. console.log(index - 1 + ", " + center + ", " + prev + ", " + cur);
  11455. prev.copyFrom(cur);
  11456. }
  11457. this._primTriArray.storeTriangle(subDiv - 1, center, first, prev);
  11458. console.log(subDiv - 1 + ", " + center + ", " + prev + ", " + first);
  11459. };
  11460. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  11461. var renderCache = modelRenderCache;
  11462. var engine = this.owner.engine;
  11463. // Need to create WebGL resources for fill part?
  11464. if (this.fill) {
  11465. var vbSize = ((this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4) + 1;
  11466. var vb = new Float32Array(vbSize);
  11467. for (var i = 0; i < vbSize; i++) {
  11468. vb[i] = i;
  11469. }
  11470. renderCache.fillVB = engine.createVertexBuffer(vb);
  11471. var triCount = vbSize - 1;
  11472. var ib = new Float32Array(triCount * 3);
  11473. for (var i = 0; i < triCount; i++) {
  11474. ib[i * 3 + 0] = 0;
  11475. ib[i * 3 + 2] = i + 1;
  11476. ib[i * 3 + 1] = i + 2;
  11477. }
  11478. ib[triCount * 3 - 2] = 1;
  11479. renderCache.fillIB = engine.createIndexBuffer(ib);
  11480. renderCache.fillIndicesCount = triCount * 3;
  11481. // 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
  11482. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  11483. if (ei) {
  11484. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11485. }
  11486. // Get the non instanced version
  11487. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  11488. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11489. }
  11490. // Need to create WebGL resource for border part?
  11491. if (this.border) {
  11492. var vbSize = (this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4 * 2;
  11493. var vb = new Float32Array(vbSize);
  11494. for (var i = 0; i < vbSize; i++) {
  11495. vb[i] = i;
  11496. }
  11497. renderCache.borderVB = engine.createVertexBuffer(vb);
  11498. var triCount = vbSize;
  11499. var rs = triCount / 2;
  11500. var ib = new Float32Array(triCount * 3);
  11501. for (var i = 0; i < rs; i++) {
  11502. var r0 = i;
  11503. var r1 = (i + 1) % rs;
  11504. ib[i * 6 + 0] = rs + r1;
  11505. ib[i * 6 + 1] = rs + r0;
  11506. ib[i * 6 + 2] = r0;
  11507. ib[i * 6 + 3] = r1;
  11508. ib[i * 6 + 4] = rs + r1;
  11509. ib[i * 6 + 5] = r0;
  11510. }
  11511. renderCache.borderIB = engine.createIndexBuffer(ib);
  11512. renderCache.borderIndicesCount = triCount * 3;
  11513. // 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
  11514. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  11515. if (ei) {
  11516. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11517. }
  11518. // Get the non instanced version
  11519. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  11520. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11521. }
  11522. return renderCache;
  11523. };
  11524. // 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
  11525. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  11526. // Fall back to default implementation if there's no round Radius
  11527. if (this._notRounded) {
  11528. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  11529. }
  11530. else {
  11531. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  11532. initialContentPosition.x = initialContentPosition.y = rr;
  11533. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  11534. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  11535. initialContentPosition.z = primSize.width - (initialContentPosition.x + initialContentArea.width);
  11536. initialContentPosition.w = primSize.height - (initialContentPosition.y + initialContentArea.height);
  11537. }
  11538. };
  11539. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  11540. // Fall back to default implementation if there's no round Radius
  11541. if (this._notRounded) {
  11542. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  11543. }
  11544. else {
  11545. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  11546. newPrimSize.copyFrom(primSize);
  11547. newPrimSize.width += rr * 2;
  11548. newPrimSize.height += rr * 2;
  11549. }
  11550. };
  11551. Rectangle2D.prototype.createInstanceDataParts = function () {
  11552. var res = new Array();
  11553. if (this.border) {
  11554. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  11555. }
  11556. if (this.fill) {
  11557. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  11558. }
  11559. return res;
  11560. };
  11561. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  11562. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  11563. return false;
  11564. }
  11565. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  11566. var d = part;
  11567. var size = this.actualSize;
  11568. var s = this.actualScale;
  11569. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  11570. }
  11571. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  11572. var d = part;
  11573. var size = this.actualSize;
  11574. var s = this.actualScale;
  11575. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  11576. }
  11577. return true;
  11578. };
  11579. return Rectangle2D;
  11580. }(BABYLON.Shape2D));
  11581. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  11582. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  11583. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  11584. Rectangle2D.roundSubdivisions = 16;
  11585. __decorate([
  11586. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D_1.actualSizeProperty = pi; }, false, true)
  11587. ], Rectangle2D.prototype, "actualSize", null);
  11588. __decorate([
  11589. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D_1.notRoundedProperty = pi; })
  11590. ], Rectangle2D.prototype, "notRounded", null);
  11591. __decorate([
  11592. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D_1.roundRadiusProperty = pi; })
  11593. ], Rectangle2D.prototype, "roundRadius", null);
  11594. Rectangle2D = Rectangle2D_1 = __decorate([
  11595. BABYLON.className("Rectangle2D", "BABYLON")
  11596. ], Rectangle2D);
  11597. BABYLON.Rectangle2D = Rectangle2D;
  11598. var Rectangle2D_1;
  11599. })(BABYLON || (BABYLON = {}));
  11600. var __extends = (this && this.__extends) || function (d, b) {
  11601. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11602. function __() { this.constructor = d; }
  11603. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11604. };
  11605. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11606. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11607. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11608. 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;
  11609. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11610. };
  11611. var BABYLON;
  11612. (function (BABYLON) {
  11613. var Ellipse2DRenderCache = (function (_super) {
  11614. __extends(Ellipse2DRenderCache, _super);
  11615. function Ellipse2DRenderCache(engine, modelKey) {
  11616. var _this = _super.call(this, engine, modelKey) || this;
  11617. _this.effectsReady = false;
  11618. _this.fillVB = null;
  11619. _this.fillIB = null;
  11620. _this.fillIndicesCount = 0;
  11621. _this.instancingFillAttributes = null;
  11622. _this.effectFillInstanced = null;
  11623. _this.effectFill = null;
  11624. _this.borderVB = null;
  11625. _this.borderIB = null;
  11626. _this.borderIndicesCount = 0;
  11627. _this.instancingBorderAttributes = null;
  11628. _this.effectBorderInstanced = null;
  11629. _this.effectBorder = null;
  11630. return _this;
  11631. }
  11632. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  11633. // Do nothing if the shader is still loading/preparing
  11634. if (!this.effectsReady) {
  11635. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  11636. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  11637. return false;
  11638. }
  11639. this.effectsReady = true;
  11640. }
  11641. var canvas = instanceInfo.owner.owner;
  11642. var engine = canvas.engine;
  11643. var depthFunction = 0;
  11644. if (this.effectFill && this.effectBorder) {
  11645. depthFunction = engine.getDepthFunction();
  11646. engine.setDepthFunctionToLessOrEqual();
  11647. }
  11648. var curAlphaMode = engine.getAlphaMode();
  11649. if (this.effectFill) {
  11650. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  11651. var pid = context.groupInfoPartData[partIndex];
  11652. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11653. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11654. }
  11655. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  11656. engine.enableEffect(effect);
  11657. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  11658. if (context.useInstancing) {
  11659. if (!this.instancingFillAttributes) {
  11660. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  11661. }
  11662. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11663. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11664. canvas._addDrawCallCount(1, context.renderMode);
  11665. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  11666. engine.draw(true, 0, this.fillIndicesCount, count);
  11667. engine.unbindInstanceAttributes();
  11668. }
  11669. else {
  11670. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11671. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11672. this.setupUniforms(effect, partIndex, pid._partData, i);
  11673. engine.draw(true, 0, this.fillIndicesCount);
  11674. }
  11675. }
  11676. }
  11677. if (this.effectBorder) {
  11678. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  11679. var pid = context.groupInfoPartData[partIndex];
  11680. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  11681. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  11682. }
  11683. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  11684. engine.enableEffect(effect);
  11685. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  11686. if (context.useInstancing) {
  11687. if (!this.instancingBorderAttributes) {
  11688. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  11689. }
  11690. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  11691. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  11692. canvas._addDrawCallCount(1, context.renderMode);
  11693. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  11694. engine.draw(true, 0, this.borderIndicesCount, count);
  11695. engine.unbindInstanceAttributes();
  11696. }
  11697. else {
  11698. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  11699. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  11700. this.setupUniforms(effect, partIndex, pid._partData, i);
  11701. engine.draw(true, 0, this.borderIndicesCount);
  11702. }
  11703. }
  11704. }
  11705. engine.setAlphaMode(curAlphaMode, true);
  11706. if (this.effectFill && this.effectBorder) {
  11707. engine.setDepthFunction(depthFunction);
  11708. }
  11709. return true;
  11710. };
  11711. Ellipse2DRenderCache.prototype.dispose = function () {
  11712. if (!_super.prototype.dispose.call(this)) {
  11713. return false;
  11714. }
  11715. if (this.fillVB) {
  11716. this._engine._releaseBuffer(this.fillVB);
  11717. this.fillVB = null;
  11718. }
  11719. if (this.fillIB) {
  11720. this._engine._releaseBuffer(this.fillIB);
  11721. this.fillIB = null;
  11722. }
  11723. this.effectFill = null;
  11724. this.effectFillInstanced = null;
  11725. this.effectBorder = null;
  11726. this.effectBorderInstanced = null;
  11727. if (this.borderVB) {
  11728. this._engine._releaseBuffer(this.borderVB);
  11729. this.borderVB = null;
  11730. }
  11731. if (this.borderIB) {
  11732. this._engine._releaseBuffer(this.borderIB);
  11733. this.borderIB = null;
  11734. }
  11735. return true;
  11736. };
  11737. return Ellipse2DRenderCache;
  11738. }(BABYLON.ModelRenderCache));
  11739. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  11740. var Ellipse2DInstanceData = (function (_super) {
  11741. __extends(Ellipse2DInstanceData, _super);
  11742. function Ellipse2DInstanceData(partId) {
  11743. return _super.call(this, partId, 1) || this;
  11744. }
  11745. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  11746. get: function () {
  11747. return null;
  11748. },
  11749. set: function (value) {
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. return Ellipse2DInstanceData;
  11755. }(BABYLON.Shape2DInstanceData));
  11756. __decorate([
  11757. BABYLON.instanceData()
  11758. ], Ellipse2DInstanceData.prototype, "properties", null);
  11759. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  11760. var Ellipse2D = Ellipse2D_1 = (function (_super) {
  11761. __extends(Ellipse2D, _super);
  11762. /**
  11763. * Create an Ellipse 2D Shape primitive
  11764. * @param settings a combination of settings, possible ones are
  11765. * - 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)
  11766. * - children: an array of direct children
  11767. * - id: a text identifier, for information purpose
  11768. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  11769. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  11770. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  11771. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  11772. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  11773. * - zOrder: override the zOrder with the specified value
  11774. * - origin: define the normalized origin point location, default [0.5;0.5]
  11775. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  11776. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  11777. * - 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)
  11778. * - 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)
  11779. * - borderThickness: the thickness of the drawn border, default is 1.
  11780. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  11781. * - 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.
  11782. * - 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.
  11783. * - 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!
  11784. * - 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.
  11785. * - 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).
  11786. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  11787. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11788. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11789. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11790. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11791. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  11792. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  11793. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  11794. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  11795. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11796. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11797. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11798. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11799. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  11800. */
  11801. function Ellipse2D(settings) {
  11802. var _this = this;
  11803. // Avoid checking every time if the object exists
  11804. if (settings == null) {
  11805. settings = {};
  11806. }
  11807. _this = _super.call(this, settings) || this;
  11808. if (settings.size != null) {
  11809. _this.size = settings.size;
  11810. }
  11811. else if (settings.width || settings.height) {
  11812. var size = new BABYLON.Size(settings.width, settings.height);
  11813. _this.size = size;
  11814. }
  11815. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  11816. _this.subdivisions = sub;
  11817. return _this;
  11818. }
  11819. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  11820. get: function () {
  11821. if (this._actualSize) {
  11822. return this._actualSize;
  11823. }
  11824. return this.size;
  11825. },
  11826. set: function (value) {
  11827. this._actualSize = value;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  11833. get: function () {
  11834. return this._subdivisions;
  11835. },
  11836. set: function (value) {
  11837. this._subdivisions = value;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  11843. var w = this.size.width / 2;
  11844. var h = this.size.height / 2;
  11845. var x = intersectInfo._localPickPosition.x - w;
  11846. var y = intersectInfo._localPickPosition.y - h;
  11847. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  11848. };
  11849. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  11850. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  11851. return true;
  11852. };
  11853. Ellipse2D.prototype.updateTriArray = function () {
  11854. var subDiv = this._subdivisions;
  11855. if (this._primTriArray == null) {
  11856. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  11857. }
  11858. else {
  11859. this._primTriArray.clear(subDiv);
  11860. }
  11861. var size = this.actualSize;
  11862. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  11863. var v1 = BABYLON.Vector2.Zero();
  11864. var v2 = BABYLON.Vector2.Zero();
  11865. for (var i = 0; i < subDiv; i++) {
  11866. var angle1 = Math.PI * 2 * (i - 1) / subDiv;
  11867. var angle2 = Math.PI * 2 * i / subDiv;
  11868. v1.x = ((Math.cos(angle1) / 2.0) + 0.5) * size.width;
  11869. v1.y = ((Math.sin(angle1) / 2.0) + 0.5) * size.height;
  11870. v2.x = ((Math.cos(angle2) / 2.0) + 0.5) * size.width;
  11871. v2.y = ((Math.sin(angle2) / 2.0) + 0.5) * size.height;
  11872. this._primTriArray.storeTriangle(i, center, v1, v2);
  11873. }
  11874. };
  11875. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  11876. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  11877. return renderCache;
  11878. };
  11879. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  11880. var renderCache = modelRenderCache;
  11881. var engine = this.owner.engine;
  11882. // Need to create WebGL resources for fill part?
  11883. if (this.fill) {
  11884. var vbSize = this.subdivisions + 1;
  11885. var vb = new Float32Array(vbSize);
  11886. for (var i = 0; i < vbSize; i++) {
  11887. vb[i] = i;
  11888. }
  11889. renderCache.fillVB = engine.createVertexBuffer(vb);
  11890. var triCount = vbSize - 1;
  11891. var ib = new Float32Array(triCount * 3);
  11892. for (var i = 0; i < triCount; i++) {
  11893. ib[i * 3 + 0] = 0;
  11894. ib[i * 3 + 2] = i + 1;
  11895. ib[i * 3 + 1] = i + 2;
  11896. }
  11897. ib[triCount * 3 - 2] = 1;
  11898. renderCache.fillIB = engine.createIndexBuffer(ib);
  11899. renderCache.fillIndicesCount = triCount * 3;
  11900. // 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
  11901. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  11902. if (ei) {
  11903. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  11904. }
  11905. // Get the non instanced version
  11906. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  11907. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  11908. }
  11909. // Need to create WebGL resource for border part?
  11910. if (this.border) {
  11911. var vbSize = this.subdivisions * 2;
  11912. var vb = new Float32Array(vbSize);
  11913. for (var i = 0; i < vbSize; i++) {
  11914. vb[i] = i;
  11915. }
  11916. renderCache.borderVB = engine.createVertexBuffer(vb);
  11917. var triCount = vbSize;
  11918. var rs = triCount / 2;
  11919. var ib = new Float32Array(triCount * 3);
  11920. for (var i = 0; i < rs; i++) {
  11921. var r0 = i;
  11922. var r1 = (i + 1) % rs;
  11923. ib[i * 6 + 0] = rs + r1;
  11924. ib[i * 6 + 1] = rs + r0;
  11925. ib[i * 6 + 2] = r0;
  11926. ib[i * 6 + 3] = r1;
  11927. ib[i * 6 + 4] = rs + r1;
  11928. ib[i * 6 + 5] = r0;
  11929. }
  11930. renderCache.borderIB = engine.createIndexBuffer(ib);
  11931. renderCache.borderIndicesCount = (triCount * 3);
  11932. // 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
  11933. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  11934. if (ei) {
  11935. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11936. }
  11937. // Get the non instanced version
  11938. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  11939. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11940. }
  11941. return renderCache;
  11942. };
  11943. Ellipse2D.prototype.createInstanceDataParts = function () {
  11944. var res = new Array();
  11945. if (this.border) {
  11946. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  11947. }
  11948. if (this.fill) {
  11949. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  11950. }
  11951. return res;
  11952. };
  11953. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  11954. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  11955. return false;
  11956. }
  11957. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  11958. var d = part;
  11959. var size = this.actualSize;
  11960. var s = this.actualScale;
  11961. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  11962. }
  11963. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  11964. var d = part;
  11965. var size = this.actualSize;
  11966. var s = this.actualScale;
  11967. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  11968. }
  11969. return true;
  11970. };
  11971. return Ellipse2D;
  11972. }(BABYLON.Shape2D));
  11973. __decorate([
  11974. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D_1.acutalSizeProperty = pi; }, false, true)
  11975. ], Ellipse2D.prototype, "actualSize", null);
  11976. __decorate([
  11977. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D_1.subdivisionsProperty = pi; })
  11978. ], Ellipse2D.prototype, "subdivisions", null);
  11979. Ellipse2D = Ellipse2D_1 = __decorate([
  11980. BABYLON.className("Ellipse2D", "BABYLON")
  11981. ], Ellipse2D);
  11982. BABYLON.Ellipse2D = Ellipse2D;
  11983. var Ellipse2D_1;
  11984. })(BABYLON || (BABYLON = {}));
  11985. var __extends = (this && this.__extends) || function (d, b) {
  11986. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11987. function __() { this.constructor = d; }
  11988. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11989. };
  11990. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11991. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11992. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11993. 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;
  11994. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11995. };
  11996. var BABYLON;
  11997. (function (BABYLON) {
  11998. var Sprite2DRenderCache = (function (_super) {
  11999. __extends(Sprite2DRenderCache, _super);
  12000. function Sprite2DRenderCache() {
  12001. var _this = _super !== null && _super.apply(this, arguments) || this;
  12002. _this.effectsReady = false;
  12003. _this.vb = null;
  12004. _this.ib = null;
  12005. _this.instancingAttributes = null;
  12006. _this.texture = null;
  12007. _this.effect = null;
  12008. _this.effectInstanced = null;
  12009. return _this;
  12010. }
  12011. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  12012. // Do nothing if the shader is still loading/preparing
  12013. if (!this.effectsReady) {
  12014. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  12015. return false;
  12016. }
  12017. this.effectsReady = true;
  12018. }
  12019. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  12020. var canvas = instanceInfo.owner.owner;
  12021. var engine = canvas.engine;
  12022. var cur = engine.getAlphaMode();
  12023. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  12024. engine.enableEffect(effect);
  12025. effect.setTexture("diffuseSampler", this.texture);
  12026. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  12027. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12028. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12029. }
  12030. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  12031. var pid = context.groupInfoPartData[0];
  12032. if (context.useInstancing) {
  12033. if (!this.instancingAttributes) {
  12034. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  12035. }
  12036. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  12037. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12038. canvas._addDrawCallCount(1, context.renderMode);
  12039. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  12040. engine.draw(true, 0, 6, count);
  12041. engine.unbindInstanceAttributes();
  12042. }
  12043. else {
  12044. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12045. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12046. this.setupUniforms(effect, 0, pid._partData, i);
  12047. engine.draw(true, 0, 6);
  12048. }
  12049. }
  12050. engine.setAlphaMode(cur, true);
  12051. return true;
  12052. };
  12053. Sprite2DRenderCache.prototype.dispose = function () {
  12054. if (!_super.prototype.dispose.call(this)) {
  12055. return false;
  12056. }
  12057. if (this.vb) {
  12058. this._engine._releaseBuffer(this.vb);
  12059. this.vb = null;
  12060. }
  12061. if (this.ib) {
  12062. this._engine._releaseBuffer(this.ib);
  12063. this.ib = null;
  12064. }
  12065. //if (this.texture) {
  12066. // this.texture.dispose();
  12067. // this.texture = null;
  12068. //}
  12069. this.effect = null;
  12070. this.effectInstanced = null;
  12071. return true;
  12072. };
  12073. return Sprite2DRenderCache;
  12074. }(BABYLON.ModelRenderCache));
  12075. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  12076. var Sprite2D = Sprite2D_1 = (function (_super) {
  12077. __extends(Sprite2D, _super);
  12078. /**
  12079. * Create an 2D Sprite primitive
  12080. * @param texture the texture that stores the sprite to render
  12081. * @param settings a combination of settings, possible ones are
  12082. * - 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)
  12083. * - children: an array of direct children
  12084. * - id a text identifier, for information purpose
  12085. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  12086. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12087. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12088. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  12089. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12090. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12091. * - zOrder: override the zOrder with the specified value
  12092. * - origin: define the normalized origin point location, default [0.5;0.5]
  12093. * - 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.
  12094. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  12095. * - 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.
  12096. * - 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
  12097. * - invertY: if true the texture Y will be inverted, default is false.
  12098. * - 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.
  12099. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  12100. * - 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.
  12101. * - 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.
  12102. * - 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!
  12103. * - 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.
  12104. * - 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).
  12105. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12106. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12107. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12108. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12109. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12110. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12111. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12112. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12113. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12114. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12115. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12116. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12117. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12118. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12119. */
  12120. function Sprite2D(texture, settings) {
  12121. var _this = this;
  12122. if (!settings) {
  12123. settings = {};
  12124. }
  12125. _this = _super.call(this, settings) || this;
  12126. _this.texture = texture;
  12127. _this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12128. _this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12129. _this._useSize = false;
  12130. _this.spriteSize = (settings.spriteSize != null) ? settings.spriteSize.clone() : null;
  12131. _this.spriteLocation = (settings.spriteLocation != null) ? settings.spriteLocation.clone() : new BABYLON.Vector2(0, 0);
  12132. if (settings.size != null) {
  12133. _this.size = settings.size;
  12134. }
  12135. _this.spriteFrame = 0;
  12136. _this.invertY = (settings.invertY == null) ? false : settings.invertY;
  12137. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  12138. _this.useAlphaFromTexture = true;
  12139. _this._scale9 = (settings.scale9 != null) ? settings.scale9.clone() : null;
  12140. // 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.
  12141. // The fucking delayed texture sprite bug is fixed!
  12142. if (settings.spriteSize == null) {
  12143. _this.spriteSize = new BABYLON.Size(10, 10);
  12144. }
  12145. if (settings.spriteSize == null || !texture.isReady()) {
  12146. if (texture.isReady()) {
  12147. var s = texture.getBaseSize();
  12148. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  12149. _this._updateSpriteScaleFactor();
  12150. }
  12151. else {
  12152. texture.onLoadObservable.add(function () {
  12153. if (settings.spriteSize == null) {
  12154. var s = texture.getBaseSize();
  12155. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  12156. }
  12157. _this._updateSpriteScaleFactor();
  12158. _this._positioningDirty();
  12159. _this._setLayoutDirty();
  12160. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D_1.textureProperty.flagId; // To make sure the sprite is issued again for render
  12161. });
  12162. }
  12163. }
  12164. return _this;
  12165. }
  12166. Object.defineProperty(Sprite2D.prototype, "texture", {
  12167. get: function () {
  12168. return this._texture;
  12169. },
  12170. set: function (value) {
  12171. this._texture = value;
  12172. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  12173. },
  12174. enumerable: true,
  12175. configurable: true
  12176. });
  12177. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  12178. get: function () {
  12179. return this._useAlphaFromTexture;
  12180. },
  12181. set: function (value) {
  12182. if (this._useAlphaFromTexture === value) {
  12183. return;
  12184. }
  12185. this._useAlphaFromTexture = value;
  12186. this._updateRenderMode();
  12187. },
  12188. enumerable: true,
  12189. configurable: true
  12190. });
  12191. Object.defineProperty(Sprite2D.prototype, "size", {
  12192. get: function () {
  12193. if (this._size == null) {
  12194. return this.spriteSize;
  12195. }
  12196. return this.internalGetSize();
  12197. },
  12198. set: function (value) {
  12199. this._useSize = value != null;
  12200. this.internalSetSize(value);
  12201. this._updateSpriteScaleFactor();
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  12207. get: function () {
  12208. if (this._actualSize) {
  12209. return this._actualSize;
  12210. }
  12211. return this.size;
  12212. },
  12213. set: function (value) {
  12214. this._actualSize = value;
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  12220. get: function () {
  12221. return this._spriteSize;
  12222. },
  12223. set: function (value) {
  12224. this._spriteSize = value;
  12225. this._updateSpriteScaleFactor();
  12226. },
  12227. enumerable: true,
  12228. configurable: true
  12229. });
  12230. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  12231. get: function () {
  12232. return this._spriteLocation;
  12233. },
  12234. set: function (value) {
  12235. this._spriteLocation = value;
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  12241. get: function () {
  12242. return this._spriteFrame;
  12243. },
  12244. set: function (value) {
  12245. this._spriteFrame = value;
  12246. },
  12247. enumerable: true,
  12248. configurable: true
  12249. });
  12250. Object.defineProperty(Sprite2D.prototype, "invertY", {
  12251. get: function () {
  12252. return this._invertY;
  12253. },
  12254. set: function (value) {
  12255. this._invertY = value;
  12256. },
  12257. enumerable: true,
  12258. configurable: true
  12259. });
  12260. Object.defineProperty(Sprite2D.prototype, "isScale9", {
  12261. get: function () {
  12262. return this._scale9 !== null;
  12263. },
  12264. enumerable: true,
  12265. configurable: true
  12266. });
  12267. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  12268. //@instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, pi => Sprite2D.spriteScaleFactorProperty = pi)
  12269. ///**
  12270. // * Get/set the sprite location (in pixels) in the texture
  12271. // */
  12272. //public get spriteScaleFactor(): Vector2 {
  12273. // return this._spriteScaleFactor;
  12274. //}
  12275. //public set spriteScaleFactor(value: Vector2) {
  12276. // this._spriteScaleFactor = value;
  12277. //}
  12278. /**
  12279. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  12280. */
  12281. get: function () {
  12282. return this._alignToPixel;
  12283. },
  12284. set: function (value) {
  12285. this._alignToPixel = value;
  12286. },
  12287. enumerable: true,
  12288. configurable: true
  12289. });
  12290. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  12291. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  12292. return true;
  12293. };
  12294. /**
  12295. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  12296. */
  12297. Sprite2D.prototype.getAnimatables = function () {
  12298. var res = new Array();
  12299. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  12300. res.push(this.texture);
  12301. }
  12302. return res;
  12303. };
  12304. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  12305. // 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
  12306. return true;
  12307. };
  12308. Object.defineProperty(Sprite2D.prototype, "isSizeAuto", {
  12309. get: function () {
  12310. return this.size == null;
  12311. },
  12312. enumerable: true,
  12313. configurable: true
  12314. });
  12315. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  12316. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  12317. return renderCache;
  12318. };
  12319. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  12320. var renderCache = modelRenderCache;
  12321. var engine = this.owner.engine;
  12322. var vb = new Float32Array(4);
  12323. for (var i = 0; i < 4; i++) {
  12324. vb[i] = i;
  12325. }
  12326. renderCache.vb = engine.createVertexBuffer(vb);
  12327. var ib = new Float32Array(6);
  12328. ib[0] = 0;
  12329. ib[1] = 2;
  12330. ib[2] = 1;
  12331. ib[3] = 0;
  12332. ib[4] = 3;
  12333. ib[5] = 2;
  12334. renderCache.ib = engine.createIndexBuffer(ib);
  12335. renderCache.texture = this.texture;
  12336. // 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
  12337. var ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  12338. if (ei) {
  12339. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  12340. }
  12341. ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  12342. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  12343. return renderCache;
  12344. };
  12345. Sprite2D.prototype.getUsedShaderCategories = function (dataPart) {
  12346. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  12347. if (dataPart.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  12348. var useScale9 = this._scale9 != null;
  12349. if (useScale9) {
  12350. cat.push(Sprite2D_1.SHAPE2D_CATEGORY_SCALE9);
  12351. }
  12352. }
  12353. return cat;
  12354. };
  12355. Sprite2D.prototype.createInstanceDataParts = function () {
  12356. return [new Sprite2DInstanceData(Sprite2D_1.SPRITE2D_MAINPARTID)];
  12357. };
  12358. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  12359. Sprite2D_1.layoutConstructMode = true;
  12360. };
  12361. // if obj contains something, we restore the _text property
  12362. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  12363. Sprite2D_1.layoutConstructMode = false;
  12364. };
  12365. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  12366. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  12367. return false;
  12368. }
  12369. if (!this.texture.isReady() && !Sprite2D_1.layoutConstructMode) {
  12370. return false;
  12371. }
  12372. if (part.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  12373. var d = this._instanceDataParts[0];
  12374. if (Sprite2D_1.layoutConstructMode) {
  12375. d.topLeftUV = BABYLON.Vector2.Zero();
  12376. d.sizeUV = BABYLON.Vector2.Zero();
  12377. d.properties = BABYLON.Vector3.Zero();
  12378. d.textureSize = BABYLON.Vector2.Zero();
  12379. d.scaleFactor = BABYLON.Vector2.Zero();
  12380. if (this.isScale9) {
  12381. d.scale9 = BABYLON.Vector4.Zero();
  12382. }
  12383. }
  12384. else {
  12385. var ts = this.texture.getBaseSize();
  12386. var ss = this.spriteSize;
  12387. var sl = this.spriteLocation;
  12388. var ssf = this.actualScale;
  12389. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  12390. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  12391. d.sizeUV = suv;
  12392. d.scaleFactor = ssf;
  12393. Sprite2D_1._prop.x = this.spriteFrame;
  12394. Sprite2D_1._prop.y = this.invertY ? 1 : 0;
  12395. Sprite2D_1._prop.z = this.alignToPixel ? 1 : 0;
  12396. d.properties = Sprite2D_1._prop;
  12397. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  12398. var scale9 = this._scale9;
  12399. if (scale9 != null) {
  12400. 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);
  12401. d.scale9 = normalizedScale9;
  12402. }
  12403. }
  12404. }
  12405. return true;
  12406. };
  12407. Sprite2D.prototype._mustUpdateInstance = function () {
  12408. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  12409. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  12410. if (res) {
  12411. this._updateRenderMode();
  12412. }
  12413. return res;
  12414. };
  12415. Sprite2D.prototype._useTextureAlpha = function () {
  12416. return this.texture != null && this.texture.hasAlpha;
  12417. };
  12418. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  12419. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  12420. };
  12421. Sprite2D.prototype._updateSpriteScaleFactor = function () {
  12422. if (!this._useSize) {
  12423. return;
  12424. }
  12425. var sS = this.spriteSize;
  12426. var s = this.size;
  12427. if (s == null || sS == null) {
  12428. return;
  12429. }
  12430. this.scaleX = s.width / sS.width;
  12431. this.scaleY = s.height / sS.height;
  12432. };
  12433. return Sprite2D;
  12434. }(BABYLON.RenderablePrim2D));
  12435. Sprite2D.SPRITE2D_MAINPARTID = 1;
  12436. Sprite2D.SHAPE2D_CATEGORY_SCALE9 = "Scale9";
  12437. Sprite2D._prop = BABYLON.Vector3.Zero();
  12438. Sprite2D.layoutConstructMode = false;
  12439. __decorate([
  12440. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D_1.textureProperty = pi; })
  12441. ], Sprite2D.prototype, "texture", null);
  12442. __decorate([
  12443. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D_1.useAlphaFromTextureProperty = pi; })
  12444. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  12445. __decorate([
  12446. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D_1.actualSizeProperty = pi; }, false, true)
  12447. ], Sprite2D.prototype, "actualSize", null);
  12448. __decorate([
  12449. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D_1.spriteSizeProperty = pi; })
  12450. ], Sprite2D.prototype, "spriteSize", null);
  12451. __decorate([
  12452. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D_1.spriteLocationProperty = pi; })
  12453. ], Sprite2D.prototype, "spriteLocation", null);
  12454. __decorate([
  12455. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D_1.spriteFrameProperty = pi; })
  12456. ], Sprite2D.prototype, "spriteFrame", null);
  12457. __decorate([
  12458. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D_1.invertYProperty = pi; })
  12459. ], Sprite2D.prototype, "invertY", null);
  12460. __decorate([
  12461. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 8, function (pi) { return Sprite2D_1.spriteScale9Property = pi; })
  12462. ], Sprite2D.prototype, "isScale9", null);
  12463. Sprite2D = Sprite2D_1 = __decorate([
  12464. BABYLON.className("Sprite2D", "BABYLON")
  12465. ], Sprite2D);
  12466. BABYLON.Sprite2D = Sprite2D;
  12467. var Sprite2DInstanceData = (function (_super) {
  12468. __extends(Sprite2DInstanceData, _super);
  12469. function Sprite2DInstanceData(partId) {
  12470. return _super.call(this, partId, 1) || this;
  12471. }
  12472. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  12473. get: function () {
  12474. return null;
  12475. },
  12476. set: function (value) {
  12477. },
  12478. enumerable: true,
  12479. configurable: true
  12480. });
  12481. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  12482. get: function () {
  12483. return null;
  12484. },
  12485. set: function (value) {
  12486. },
  12487. enumerable: true,
  12488. configurable: true
  12489. });
  12490. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  12491. get: function () {
  12492. return null;
  12493. },
  12494. set: function (value) {
  12495. },
  12496. enumerable: true,
  12497. configurable: true
  12498. });
  12499. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  12500. get: function () {
  12501. return null;
  12502. },
  12503. set: function (value) {
  12504. },
  12505. enumerable: true,
  12506. configurable: true
  12507. });
  12508. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  12509. // 3 floats being:
  12510. // - x: frame number to display
  12511. // - y: invertY setting
  12512. // - z: alignToPixel setting
  12513. get: function () {
  12514. return null;
  12515. },
  12516. set: function (value) {
  12517. },
  12518. enumerable: true,
  12519. configurable: true
  12520. });
  12521. Object.defineProperty(Sprite2DInstanceData.prototype, "scale9", {
  12522. get: function () {
  12523. return null;
  12524. },
  12525. set: function (value) {
  12526. },
  12527. enumerable: true,
  12528. configurable: true
  12529. });
  12530. return Sprite2DInstanceData;
  12531. }(BABYLON.InstanceDataBase));
  12532. __decorate([
  12533. BABYLON.instanceData()
  12534. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  12535. __decorate([
  12536. BABYLON.instanceData()
  12537. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  12538. __decorate([
  12539. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  12540. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  12541. __decorate([
  12542. BABYLON.instanceData()
  12543. ], Sprite2DInstanceData.prototype, "textureSize", null);
  12544. __decorate([
  12545. BABYLON.instanceData()
  12546. ], Sprite2DInstanceData.prototype, "properties", null);
  12547. __decorate([
  12548. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  12549. ], Sprite2DInstanceData.prototype, "scale9", null);
  12550. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  12551. var Sprite2D_1;
  12552. })(BABYLON || (BABYLON = {}));
  12553. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12554. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12555. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12556. 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;
  12557. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12558. };
  12559. var BABYLON;
  12560. (function (BABYLON) {
  12561. /**
  12562. * This class will contains information about a sub picture present in an Atlas Picture.
  12563. */
  12564. var AtlasSubPictureInfo = (function () {
  12565. function AtlasSubPictureInfo() {
  12566. }
  12567. return AtlasSubPictureInfo;
  12568. }());
  12569. BABYLON.AtlasSubPictureInfo = AtlasSubPictureInfo;
  12570. /**
  12571. * This class represent an Atlas Picture, it contains the information of all the sub pictures and the Texture that stores the bitmap.
  12572. * You get an instance of this class using methods of the AtlasPictureInfoFactory
  12573. */
  12574. var AtlasPictureInfo = (function () {
  12575. function AtlasPictureInfo() {
  12576. }
  12577. /**
  12578. * Creates many sprite from the Atlas Picture
  12579. * @param filterCallback a predicate if true is returned then the corresponding sub picture will be used to create a sprite.
  12580. * The Predicate has many parameters:
  12581. * - index: just an index incremented at each sub picture submitted for Sprite creation
  12582. * - name: the sub picture's name
  12583. * - aspi: the AtlasSubPictureInfo corresponding to the submitted sub picture
  12584. * - settings: the Sprite2D creation settings, you can alter this JSON object but BEWARE, the alterations will be kept for subsequent Sprite2D creations!
  12585. * @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.
  12586. */
  12587. AtlasPictureInfo.prototype.createSprites = function (filterCallback, spriteSettings) {
  12588. var _this = this;
  12589. var res = new Array();
  12590. var index = 0;
  12591. this.subPictures.forEach(function (k, v) {
  12592. if (!filterCallback || filterCallback(index++, k, v, spriteSettings)) {
  12593. var s = _this.createSprite(k, spriteSettings);
  12594. if (s) {
  12595. res.push(s);
  12596. }
  12597. }
  12598. });
  12599. return res;
  12600. };
  12601. /**
  12602. * Create one Sprite from a sub picture
  12603. * @param subPictureName the name of the sub picture to use
  12604. * @param spriteSettings the Sprite2D settings to use for the Sprite instance creation
  12605. */
  12606. AtlasPictureInfo.prototype.createSprite = function (subPictureName, spriteSettings) {
  12607. var spi = this.subPictures.get(subPictureName);
  12608. if (!spi) {
  12609. return null;
  12610. }
  12611. if (!spriteSettings) {
  12612. spriteSettings = {};
  12613. }
  12614. var s = spriteSettings;
  12615. s.id = subPictureName;
  12616. s.spriteLocation = spi.location;
  12617. s.spriteSize = spi.size;
  12618. var sprite = new BABYLON.Sprite2D(this.texture, spriteSettings);
  12619. return sprite;
  12620. };
  12621. return AtlasPictureInfo;
  12622. }());
  12623. BABYLON.AtlasPictureInfo = AtlasPictureInfo;
  12624. /**
  12625. * This if the Factory class containing static method to create Atlas Pictures Info objects or add new loaders
  12626. */
  12627. var AtlasPictureInfoFactory = (function () {
  12628. function AtlasPictureInfoFactory() {
  12629. }
  12630. /**
  12631. * Add a custom loader
  12632. * @param fileExtension must be the file extension (without the dot) of the file that is loaded by this loader (e.g.: json)
  12633. * @param plugin the instance of the loader
  12634. */
  12635. AtlasPictureInfoFactory.addLoader = function (fileExtension, plugin) {
  12636. var a = AtlasPictureInfoFactory.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  12637. a.push(plugin);
  12638. };
  12639. /**
  12640. * Load an Atlas Picture Info object from a data file at a given url and with a given texture
  12641. * @param texture the texture containing the atlas bitmap
  12642. * @param url the URL of the Atlas Info data file
  12643. * @param onLoad a callback that will be called when the AtlasPictureInfo object will be loaded and ready
  12644. * @param onError a callback that will be called in case of error
  12645. */
  12646. AtlasPictureInfoFactory.loadFromUrl = function (texture, url, onLoad, onError) {
  12647. if (onError === void 0) { onError = null; }
  12648. var xhr = new XMLHttpRequest();
  12649. xhr.onreadystatechange = function () {
  12650. if (xhr.readyState === XMLHttpRequest.DONE) {
  12651. if (xhr.status === 200) {
  12652. var ext = url.split('.').pop().split(/\#|\?/)[0];
  12653. var plugins = AtlasPictureInfoFactory.plugins.get(ext.toLocaleLowerCase());
  12654. if (!plugins) {
  12655. if (onError) {
  12656. onError("couldn't find a plugin for this file extension", -1);
  12657. }
  12658. return;
  12659. }
  12660. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  12661. var p = plugins_1[_i];
  12662. var ret = p.loadFile(xhr.response);
  12663. if (ret) {
  12664. if (ret.api) {
  12665. ret.api.texture = texture;
  12666. if (onLoad) {
  12667. onLoad(ret.api);
  12668. }
  12669. }
  12670. else if (onError) {
  12671. onError(ret.errorMsg, ret.errorCode);
  12672. }
  12673. return;
  12674. }
  12675. }
  12676. if (onError) {
  12677. onError("No plugin to load this Atlas Data file format", -1);
  12678. }
  12679. }
  12680. else {
  12681. if (onError) {
  12682. onError("Couldn't load file through HTTP Request, HTTP Status " + xhr.status, xhr.status);
  12683. }
  12684. }
  12685. }
  12686. };
  12687. xhr.open("GET", url, true);
  12688. xhr.send();
  12689. return null;
  12690. };
  12691. return AtlasPictureInfoFactory;
  12692. }());
  12693. AtlasPictureInfoFactory.plugins = new BABYLON.StringDictionary();
  12694. BABYLON.AtlasPictureInfoFactory = AtlasPictureInfoFactory;
  12695. // Loader class for the TexturePacker's JSON Array data format
  12696. var JSONArrayLoader = JSONArrayLoader_1 = (function () {
  12697. function JSONArrayLoader() {
  12698. }
  12699. JSONArrayLoader.prototype.loadFile = function (content) {
  12700. var errorMsg = null;
  12701. var errorCode = 0;
  12702. var root = null;
  12703. var api = null;
  12704. try {
  12705. var frames_1;
  12706. var meta = void 0;
  12707. try {
  12708. root = JSON.parse(content);
  12709. frames_1 = root.frames;
  12710. meta = root.meta;
  12711. if (!frames_1 || !meta) {
  12712. throw Error("Not a JSON Array file format");
  12713. }
  12714. }
  12715. catch (ex1) {
  12716. return null;
  12717. }
  12718. api = new AtlasPictureInfo();
  12719. api.atlasSize = new BABYLON.Size(meta.size.w, meta.size.h);
  12720. api.subPictures = new BABYLON.StringDictionary();
  12721. for (var _i = 0, frames_2 = frames_1; _i < frames_2.length; _i++) {
  12722. var f = frames_2[_i];
  12723. var aspi = new AtlasSubPictureInfo();
  12724. aspi.name = f.filename;
  12725. aspi.location = new BABYLON.Vector2(f.frame.x, api.atlasSize.height - (f.frame.y + f.frame.h));
  12726. aspi.size = new BABYLON.Size(f.frame.w, f.frame.h);
  12727. api.subPictures.add(aspi.name, aspi);
  12728. }
  12729. }
  12730. catch (ex2) {
  12731. errorMsg = "Unknown Exception: " + ex2;
  12732. errorCode = -2;
  12733. }
  12734. return { api: api, errorMsg: errorMsg, errorCode: errorCode };
  12735. };
  12736. return JSONArrayLoader;
  12737. }());
  12738. JSONArrayLoader = JSONArrayLoader_1 = __decorate([
  12739. AtlasLoaderPlugin("json", new JSONArrayLoader_1())
  12740. ], JSONArrayLoader);
  12741. /**
  12742. * Use this decorator when you declare an Atlas Loader Class for the loader to register itself automatically.
  12743. * @param fileExtension the extension of the file that the plugin is loading (there can be many plugin for the same extension)
  12744. * @param plugin an instance of the plugin class to add to the AtlasPictureInfoFactory
  12745. */
  12746. function AtlasLoaderPlugin(fileExtension, plugin) {
  12747. return function () {
  12748. AtlasPictureInfoFactory.addLoader(fileExtension, plugin);
  12749. };
  12750. }
  12751. BABYLON.AtlasLoaderPlugin = AtlasLoaderPlugin;
  12752. var JSONArrayLoader_1;
  12753. })(BABYLON || (BABYLON = {}));
  12754. var __extends = (this && this.__extends) || function (d, b) {
  12755. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12756. function __() { this.constructor = d; }
  12757. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12758. };
  12759. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12760. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12761. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12762. 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;
  12763. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12764. };
  12765. var BABYLON;
  12766. (function (BABYLON) {
  12767. var Text2DRenderCache = (function (_super) {
  12768. __extends(Text2DRenderCache, _super);
  12769. function Text2DRenderCache() {
  12770. var _this = _super !== null && _super.apply(this, arguments) || this;
  12771. _this.effectsReady = false;
  12772. _this.vb = null;
  12773. _this.ib = null;
  12774. _this.instancingAttributes = null;
  12775. _this.fontTexture = null;
  12776. _this.effect = null;
  12777. _this.effectInstanced = null;
  12778. return _this;
  12779. }
  12780. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  12781. // Do nothing if the shader is still loading/preparing
  12782. if (!this.effectsReady) {
  12783. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  12784. return false;
  12785. }
  12786. this.effectsReady = true;
  12787. }
  12788. var canvas = instanceInfo.owner.owner;
  12789. var engine = canvas.engine;
  12790. this.fontTexture.update();
  12791. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  12792. engine.enableEffect(effect);
  12793. effect.setTexture("diffuseSampler", this.fontTexture);
  12794. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  12795. var sdf = this.fontTexture.isSignedDistanceField;
  12796. // Enable alpha mode only if the texture is not using SDF, SDF is rendered in AlphaTest mode, which mean no alpha blend
  12797. var curAlphaMode;
  12798. if (!sdf) {
  12799. curAlphaMode = engine.getAlphaMode();
  12800. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12801. }
  12802. var pid = context.groupInfoPartData[0];
  12803. if (context.useInstancing) {
  12804. if (!this.instancingAttributes) {
  12805. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  12806. }
  12807. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  12808. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12809. canvas._addDrawCallCount(1, context.renderMode);
  12810. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  12811. engine.draw(true, 0, 6, count);
  12812. engine.unbindInstanceAttributes();
  12813. }
  12814. else {
  12815. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12816. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12817. this.setupUniforms(effect, 0, pid._partData, i);
  12818. engine.draw(true, 0, 6);
  12819. }
  12820. }
  12821. if (!sdf) {
  12822. engine.setAlphaMode(curAlphaMode, true);
  12823. }
  12824. return true;
  12825. };
  12826. Text2DRenderCache.prototype.dispose = function () {
  12827. if (!_super.prototype.dispose.call(this)) {
  12828. return false;
  12829. }
  12830. if (this.vb) {
  12831. this._engine._releaseBuffer(this.vb);
  12832. this.vb = null;
  12833. }
  12834. if (this.ib) {
  12835. this._engine._releaseBuffer(this.ib);
  12836. this.ib = null;
  12837. }
  12838. if (this.fontTexture) {
  12839. this.fontTexture.decCachedFontTextureCounter();
  12840. this.fontTexture = null;
  12841. }
  12842. this.effect = null;
  12843. this.effectInstanced = null;
  12844. return true;
  12845. };
  12846. return Text2DRenderCache;
  12847. }(BABYLON.ModelRenderCache));
  12848. BABYLON.Text2DRenderCache = Text2DRenderCache;
  12849. var Text2DInstanceData = (function (_super) {
  12850. __extends(Text2DInstanceData, _super);
  12851. function Text2DInstanceData(partId, dataElementCount) {
  12852. return _super.call(this, partId, dataElementCount) || this;
  12853. }
  12854. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  12855. get: function () {
  12856. return null;
  12857. },
  12858. set: function (value) {
  12859. },
  12860. enumerable: true,
  12861. configurable: true
  12862. });
  12863. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  12864. get: function () {
  12865. return null;
  12866. },
  12867. set: function (value) {
  12868. },
  12869. enumerable: true,
  12870. configurable: true
  12871. });
  12872. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  12873. get: function () {
  12874. return null;
  12875. },
  12876. set: function (value) {
  12877. },
  12878. enumerable: true,
  12879. configurable: true
  12880. });
  12881. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  12882. get: function () {
  12883. return null;
  12884. },
  12885. set: function (value) {
  12886. },
  12887. enumerable: true,
  12888. configurable: true
  12889. });
  12890. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  12891. get: function () {
  12892. return null;
  12893. },
  12894. set: function (value) {
  12895. },
  12896. enumerable: true,
  12897. configurable: true
  12898. });
  12899. return Text2DInstanceData;
  12900. }(BABYLON.InstanceDataBase));
  12901. __decorate([
  12902. BABYLON.instanceData()
  12903. ], Text2DInstanceData.prototype, "topLeftUV", null);
  12904. __decorate([
  12905. BABYLON.instanceData()
  12906. ], Text2DInstanceData.prototype, "sizeUV", null);
  12907. __decorate([
  12908. BABYLON.instanceData()
  12909. ], Text2DInstanceData.prototype, "textureSize", null);
  12910. __decorate([
  12911. BABYLON.instanceData()
  12912. ], Text2DInstanceData.prototype, "color", null);
  12913. __decorate([
  12914. BABYLON.instanceData()
  12915. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  12916. BABYLON.Text2DInstanceData = Text2DInstanceData;
  12917. var Text2D = Text2D_1 = (function (_super) {
  12918. __extends(Text2D, _super);
  12919. /**
  12920. * Create a Text primitive
  12921. * @param text the text to display
  12922. * @param settings a combination of settings, possible ones are
  12923. * - 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)
  12924. * - children: an array of direct children
  12925. * - id a text identifier, for information purpose
  12926. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  12927. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12928. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12929. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12930. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12931. * - zOrder: override the zOrder with the specified value
  12932. * - origin: define the normalized origin point location, default [0.5;0.5]
  12933. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  12934. * - 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.
  12935. * - 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.
  12936. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  12937. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  12938. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  12939. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  12940. * - 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.
  12941. * - 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.
  12942. * - 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!
  12943. * - 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.
  12944. * - 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).
  12945. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12946. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12947. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12948. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12949. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12950. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12951. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12952. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12953. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12954. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12955. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12956. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12957. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12958. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12959. * - textAlignmentH: align text horizontally (Text2D.AlignLeft, Text2D.AlignCenter, Text2D.AlignRight)
  12960. * - textAlignmentV: align text vertically (Text2D.AlignTop, Text2D.AlignCenter, Text2D.AlignBottom)
  12961. * - textAlignment: a string defining the text alignment, text can be: [<h:|horizontal:><left|right|center>], [<v:|vertical:><top|bottom|center>]
  12962. * - wordWrap: if true the text will wrap inside content area
  12963. */
  12964. function Text2D(text, settings) {
  12965. var _this = this;
  12966. if (!settings) {
  12967. settings = {};
  12968. }
  12969. _this = _super.call(this, settings) || this;
  12970. if (settings.bitmapFontTexture != null) {
  12971. _this._fontTexture = settings.bitmapFontTexture;
  12972. _this._fontName = null;
  12973. _this._fontSuperSample = false;
  12974. _this._fontSDF = false;
  12975. }
  12976. else {
  12977. _this._fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  12978. _this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  12979. _this._fontSDF = (settings.fontSignedDistanceField != null && settings.fontSignedDistanceField);
  12980. }
  12981. _this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  12982. _this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  12983. _this._textSize = null;
  12984. _this.text = text;
  12985. _this.size = (settings.size == null) ? null : settings.size;
  12986. _this.textAlignmentH = (settings.textAlignmentH == null) ? Text2D_1.AlignLeft : settings.textAlignmentH;
  12987. _this.textAlignmentV = (settings.textAlignmentV == null) ? Text2D_1.AlignTop : settings.textAlignmentV;
  12988. _this.textAlignment = (settings.textAlignment == null) ? "" : settings.textAlignment;
  12989. _this._wordWrap = (settings.wordWrap == null) ? false : settings.wordWrap;
  12990. _this._updateRenderMode();
  12991. return _this;
  12992. }
  12993. Object.defineProperty(Text2D, "AlignLeft", {
  12994. /**
  12995. * Alignment is made relative to the left edge of the Content Area. Valid for horizontal alignment only.
  12996. */
  12997. get: function () { return Text2D_1._AlignLeft; },
  12998. enumerable: true,
  12999. configurable: true
  13000. });
  13001. Object.defineProperty(Text2D, "AlignTop", {
  13002. /**
  13003. * Alignment is made relative to the top edge of the Content Area. Valid for vertical alignment only.
  13004. */
  13005. get: function () { return Text2D_1._AlignTop; },
  13006. enumerable: true,
  13007. configurable: true
  13008. });
  13009. Object.defineProperty(Text2D, "AlignRight", {
  13010. /**
  13011. * Alignment is made relative to the right edge of the Content Area. Valid for horizontal alignment only.
  13012. */
  13013. get: function () { return Text2D_1._AlignRight; },
  13014. enumerable: true,
  13015. configurable: true
  13016. });
  13017. Object.defineProperty(Text2D, "AlignBottom", {
  13018. /**
  13019. * Alignment is made relative to the bottom edge of the Content Area. Valid for vertical alignment only.
  13020. */
  13021. get: function () { return Text2D_1._AlignBottom; },
  13022. enumerable: true,
  13023. configurable: true
  13024. });
  13025. Object.defineProperty(Text2D, "AlignCenter", {
  13026. /**
  13027. * Alignment is made to center the text from equal distance to the opposite edges of the Content Area
  13028. */
  13029. get: function () { return Text2D_1._AlignCenter; },
  13030. enumerable: true,
  13031. configurable: true
  13032. });
  13033. Object.defineProperty(Text2D.prototype, "fontName", {
  13034. get: function () {
  13035. return this._fontName;
  13036. },
  13037. set: function (value) {
  13038. if (this._fontName) {
  13039. throw new Error("Font Name change is not supported right now.");
  13040. }
  13041. this._fontName = value;
  13042. },
  13043. enumerable: true,
  13044. configurable: true
  13045. });
  13046. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  13047. get: function () {
  13048. return this._defaultFontColor;
  13049. },
  13050. set: function (value) {
  13051. this._defaultFontColor = value;
  13052. },
  13053. enumerable: true,
  13054. configurable: true
  13055. });
  13056. Object.defineProperty(Text2D.prototype, "text", {
  13057. get: function () {
  13058. return this._text;
  13059. },
  13060. set: function (value) {
  13061. if (!value) {
  13062. value = "";
  13063. }
  13064. this._text = value;
  13065. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  13066. this._size = null;
  13067. this._updateCharCount();
  13068. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  13069. var s = this.textSize;
  13070. },
  13071. enumerable: true,
  13072. configurable: true
  13073. });
  13074. Object.defineProperty(Text2D.prototype, "size", {
  13075. get: function () {
  13076. if (this._size != null) {
  13077. return this._size;
  13078. }
  13079. return this.textSize;
  13080. },
  13081. set: function (value) {
  13082. this._size = value;
  13083. },
  13084. enumerable: true,
  13085. configurable: true
  13086. });
  13087. Object.defineProperty(Text2D.prototype, "fontSuperSample", {
  13088. get: function () {
  13089. return this._fontTexture && this._fontTexture.isSuperSampled;
  13090. },
  13091. enumerable: true,
  13092. configurable: true
  13093. });
  13094. Object.defineProperty(Text2D.prototype, "fontSignedDistanceField", {
  13095. get: function () {
  13096. return this._fontTexture && this._fontTexture.isSignedDistanceField;
  13097. },
  13098. enumerable: true,
  13099. configurable: true
  13100. });
  13101. Object.defineProperty(Text2D.prototype, "isSizeAuto", {
  13102. get: function () {
  13103. return false;
  13104. },
  13105. enumerable: true,
  13106. configurable: true
  13107. });
  13108. Object.defineProperty(Text2D.prototype, "actualSize", {
  13109. /**
  13110. * Get the actual size of the Text2D primitive
  13111. */
  13112. get: function () {
  13113. if (this._actualSize) {
  13114. return this._actualSize;
  13115. }
  13116. return this.size;
  13117. },
  13118. enumerable: true,
  13119. configurable: true
  13120. });
  13121. Object.defineProperty(Text2D.prototype, "textSize", {
  13122. /**
  13123. * Get the area that bounds the text associated to the primitive
  13124. */
  13125. get: function () {
  13126. if (!this._textSize) {
  13127. if (this.owner && this._text) {
  13128. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  13129. if (!newSize.equals(this._textSize)) {
  13130. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  13131. this._positioningDirty();
  13132. }
  13133. this._textSize = newSize;
  13134. }
  13135. else {
  13136. return Text2D_1.nullSize;
  13137. }
  13138. }
  13139. return this._textSize;
  13140. },
  13141. enumerable: true,
  13142. configurable: true
  13143. });
  13144. Object.defineProperty(Text2D.prototype, "fontTexture", {
  13145. get: function () {
  13146. if (this._fontTexture) {
  13147. return this._fontTexture;
  13148. }
  13149. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  13150. return null;
  13151. }
  13152. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  13153. return this._fontTexture;
  13154. },
  13155. enumerable: true,
  13156. configurable: true
  13157. });
  13158. /**
  13159. * Dispose the primitive, remove it from its parent
  13160. */
  13161. Text2D.prototype.dispose = function () {
  13162. if (!_super.prototype.dispose.call(this)) {
  13163. return false;
  13164. }
  13165. if (this._fontTexture) {
  13166. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  13167. this._fontTexture = null;
  13168. }
  13169. return true;
  13170. };
  13171. Text2D.prototype.updateLevelBoundingInfo = function () {
  13172. if (!this.owner || !this._text) {
  13173. return false;
  13174. }
  13175. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  13176. return true;
  13177. };
  13178. Object.defineProperty(Text2D.prototype, "textAlignment", {
  13179. /**
  13180. * You can get/set the text alignment through this property
  13181. */
  13182. get: function () {
  13183. return this._textAlignment;
  13184. },
  13185. set: function (value) {
  13186. this._textAlignment = value;
  13187. this._setTextAlignmentfromString(value);
  13188. },
  13189. enumerable: true,
  13190. configurable: true
  13191. });
  13192. Text2D.prototype.levelIntersect = function (intersectInfo) {
  13193. // 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...
  13194. return true;
  13195. };
  13196. Text2D.prototype.createModelRenderCache = function (modelKey) {
  13197. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  13198. return renderCache;
  13199. };
  13200. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  13201. var renderCache = modelRenderCache;
  13202. var engine = this.owner.engine;
  13203. renderCache.fontTexture = this.fontTexture;
  13204. renderCache.fontTexture.incCachedFontTextureCounter();
  13205. var vb = new Float32Array(4);
  13206. for (var i = 0; i < 4; i++) {
  13207. vb[i] = i;
  13208. }
  13209. renderCache.vb = engine.createVertexBuffer(vb);
  13210. var ib = new Float32Array(6);
  13211. ib[0] = 0;
  13212. ib[1] = 2;
  13213. ib[2] = 1;
  13214. ib[3] = 0;
  13215. ib[4] = 3;
  13216. ib[5] = 2;
  13217. renderCache.ib = engine.createIndexBuffer(ib);
  13218. // 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
  13219. var ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, true);
  13220. if (ei) {
  13221. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13222. }
  13223. ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, false);
  13224. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13225. return renderCache;
  13226. };
  13227. Text2D.prototype.createInstanceDataParts = function () {
  13228. return [new Text2DInstanceData(Text2D_1.TEXT2D_MAINPARTID, this._charCount)];
  13229. };
  13230. // Looks like a hack!? Yes! Because that's what it is!
  13231. // 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
  13232. // 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)
  13233. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  13234. if (!this._charCount) {
  13235. var curText = this._text;
  13236. this.text = "A";
  13237. return curText;
  13238. }
  13239. };
  13240. // if obj contains something, we restore the _text property
  13241. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  13242. if (obj !== undefined) {
  13243. this.text = obj;
  13244. }
  13245. };
  13246. Text2D.prototype.getUsedShaderCategories = function (dataPart) {
  13247. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  13248. if (this._fontSDF) {
  13249. cat.push(Text2D_1.TEXT2D_CATEGORY_SDF);
  13250. }
  13251. return cat;
  13252. };
  13253. Text2D.prototype.refreshInstanceDataPart = function (part) {
  13254. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  13255. return false;
  13256. }
  13257. if (part.id === Text2D_1.TEXT2D_MAINPARTID) {
  13258. var d = part;
  13259. var texture = this.fontTexture;
  13260. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  13261. var ts = texture.getSize();
  13262. var offset = BABYLON.Vector2.Zero();
  13263. var lh = this.fontTexture.lineHeight;
  13264. d.dataElementCount = this._charCount;
  13265. d.curElement = 0;
  13266. var lineLengths = [];
  13267. var charWidths = [];
  13268. var charsPerLine = [];
  13269. var numCharsCurrenLine = 0;
  13270. var contentAreaWidth = this.contentArea.width;
  13271. var contentAreaHeight = this.contentArea.height;
  13272. var numCharsCurrentWord = 0;
  13273. var widthCurrentWord = 0;
  13274. var numWordsPerLine = 0;
  13275. var text = this.text;
  13276. var tabWidth = this._tabulationSize * texture.spaceWidth;
  13277. for (var i_1 = 0; i_1 < text.length; i_1++) {
  13278. var char = text[i_1];
  13279. numCharsCurrenLine++;
  13280. charWidths[i_1] = 0;
  13281. // Line feed
  13282. if (this._isWhiteSpaceCharVert(char)) {
  13283. lineLengths.push(offset.x);
  13284. charsPerLine.push(numCharsCurrenLine - 1);
  13285. numCharsCurrenLine = 1;
  13286. offset.x = 0;
  13287. if (widthCurrentWord > 0) {
  13288. numWordsPerLine++;
  13289. }
  13290. numWordsPerLine = 0;
  13291. numCharsCurrentWord = 0;
  13292. widthCurrentWord = 0;
  13293. continue;
  13294. }
  13295. var ci = texture.getChar(char);
  13296. var charWidth = 0;
  13297. if (char === "\t") {
  13298. charWidth = tabWidth;
  13299. }
  13300. else {
  13301. charWidth = ci.charWidth;
  13302. }
  13303. offset.x += charWidth;
  13304. charWidths[i_1] = charWidth;
  13305. if (this._isWhiteSpaceCharHoriz(char)) {
  13306. if (widthCurrentWord > 0) {
  13307. numWordsPerLine++;
  13308. }
  13309. numCharsCurrentWord = 0;
  13310. widthCurrentWord = 0;
  13311. }
  13312. else {
  13313. widthCurrentWord += ci.charWidth;
  13314. numCharsCurrentWord++;
  13315. }
  13316. if (this._wordWrap && numWordsPerLine > 0 && offset.x > contentAreaWidth) {
  13317. lineLengths.push(offset.x - widthCurrentWord);
  13318. numCharsCurrenLine -= numCharsCurrentWord;
  13319. var j = i_1 - numCharsCurrentWord;
  13320. //skip white space at the end of this line
  13321. while (this._isWhiteSpaceCharHoriz(text[j])) {
  13322. lineLengths[lineLengths.length - 1] -= charWidths[j];
  13323. j--;
  13324. }
  13325. charsPerLine.push(numCharsCurrenLine);
  13326. if (this._isWhiteSpaceCharHoriz(text[i_1])) {
  13327. //skip white space at the beginning of next line
  13328. var numSpaces = 0;
  13329. while (this._isWhiteSpaceCharHoriz(text[i_1 + numSpaces])) {
  13330. numSpaces++;
  13331. charWidths[i_1 + numSpaces] = 0;
  13332. }
  13333. i_1 += numSpaces - 1;
  13334. offset.x = 0;
  13335. numCharsCurrenLine = numSpaces - 1;
  13336. }
  13337. else {
  13338. numCharsCurrenLine = numCharsCurrentWord;
  13339. offset.x = widthCurrentWord;
  13340. }
  13341. numWordsPerLine = 0;
  13342. }
  13343. }
  13344. lineLengths.push(offset.x);
  13345. charsPerLine.push(numCharsCurrenLine);
  13346. //skip white space at the end
  13347. var i = text.length - 1;
  13348. while (this._isWhiteSpaceCharHoriz(text[i])) {
  13349. lineLengths[lineLengths.length - 1] -= charWidths[i];
  13350. i--;
  13351. }
  13352. var charNum = 0;
  13353. var maxLineLen = 0;
  13354. var alignH = this.textAlignmentH;
  13355. var alignV = this.textAlignmentV;
  13356. offset.x = 0;
  13357. if (alignH == Text2D_1.AlignRight || alignH == Text2D_1.AlignCenter) {
  13358. for (var i_2 = 0; i_2 < lineLengths.length; i_2++) {
  13359. if (lineLengths[i_2] > maxLineLen) {
  13360. maxLineLen = lineLengths[i_2];
  13361. }
  13362. }
  13363. }
  13364. var textHeight = lineLengths.length * lh;
  13365. var offsetX = this.padding.leftPixels;
  13366. if (alignH == Text2D_1.AlignRight) {
  13367. offsetX += contentAreaWidth - maxLineLen;
  13368. }
  13369. else if (alignH == Text2D_1.AlignCenter) {
  13370. offsetX += (contentAreaWidth - maxLineLen) * .5;
  13371. }
  13372. offset.x += offsetX;
  13373. offset.y += contentAreaHeight + textHeight - lh;
  13374. offset.y += this.padding.bottomPixels;
  13375. if (alignV == Text2D_1.AlignBottom) {
  13376. offset.y -= contentAreaHeight;
  13377. }
  13378. else if (alignV == Text2D_1.AlignCenter) {
  13379. offset.y -= (contentAreaHeight - textHeight) * .5 + lineLengths.length * lh;
  13380. }
  13381. else {
  13382. offset.y -= lineLengths.length * lh;
  13383. }
  13384. for (var i_3 = 0; i_3 < lineLengths.length; i_3++) {
  13385. var numChars = charsPerLine[i_3];
  13386. var lineLength = lineLengths[i_3];
  13387. if (alignH == Text2D_1.AlignRight) {
  13388. offset.x += maxLineLen - lineLength;
  13389. }
  13390. else if (alignH == Text2D_1.AlignCenter) {
  13391. offset.x += (maxLineLen - lineLength) * .5;
  13392. }
  13393. for (var j = 0; j < numChars; j++) {
  13394. var char = text[charNum];
  13395. var charWidth = charWidths[charNum];
  13396. this.updateInstanceDataPart(d, offset);
  13397. offset.x += charWidth;
  13398. if (!this._isWhiteSpaceCharHoriz(char)) {
  13399. var ci = texture.getChar(char);
  13400. d.topLeftUV = ci.topLeftUV;
  13401. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  13402. d.sizeUV = suv;
  13403. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  13404. d.color = this.defaultFontColor;
  13405. d.superSampleFactor = superSampleFactor;
  13406. ++d.curElement;
  13407. }
  13408. charNum++;
  13409. }
  13410. offset.x = offsetX;
  13411. offset.y -= texture.lineHeight;
  13412. }
  13413. }
  13414. return true;
  13415. };
  13416. Text2D.prototype._isWhiteSpaceCharHoriz = function (char) {
  13417. if (char === " " || char === "\t") {
  13418. return true;
  13419. }
  13420. };
  13421. Text2D.prototype._isWhiteSpaceCharVert = function (char) {
  13422. if (char === "\n" || char === "\r") {
  13423. return true;
  13424. }
  13425. };
  13426. Text2D.prototype._updateCharCount = function () {
  13427. var count = 0;
  13428. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  13429. var char = _a[_i];
  13430. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  13431. continue;
  13432. }
  13433. ++count;
  13434. }
  13435. this._charCount = count;
  13436. };
  13437. Text2D.prototype._setTextAlignmentfromString = function (value) {
  13438. var m = value.trim().split(",");
  13439. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  13440. var v = m_1[_i];
  13441. v = v.toLocaleLowerCase().trim();
  13442. // Horizontal
  13443. var i = v.indexOf("h:");
  13444. if (i === -1) {
  13445. i = v.indexOf("horizontal:");
  13446. }
  13447. if (i !== -1) {
  13448. v = v.substr(v.indexOf(":") + 1);
  13449. this._setTextAlignmentHorizontal(v);
  13450. continue;
  13451. }
  13452. // Vertical
  13453. i = v.indexOf("v:");
  13454. if (i === -1) {
  13455. i = v.indexOf("vertical:");
  13456. }
  13457. if (i !== -1) {
  13458. v = v.substr(v.indexOf(":") + 1);
  13459. this._setTextAlignmentVertical(v);
  13460. continue;
  13461. }
  13462. }
  13463. };
  13464. Text2D.prototype._setTextAlignmentHorizontal = function (text) {
  13465. var v = text.trim().toLocaleLowerCase();
  13466. switch (v) {
  13467. case "left":
  13468. this.textAlignmentH = Text2D_1.AlignLeft;
  13469. return;
  13470. case "right":
  13471. this.textAlignmentH = Text2D_1.AlignRight;
  13472. return;
  13473. case "center":
  13474. this.textAlignmentH = Text2D_1.AlignCenter;
  13475. return;
  13476. }
  13477. };
  13478. Text2D.prototype._setTextAlignmentVertical = function (text) {
  13479. var v = text.trim().toLocaleLowerCase();
  13480. switch (v) {
  13481. case "top":
  13482. this.textAlignmentV = Text2D_1.AlignTop;
  13483. return;
  13484. case "bottom":
  13485. this.textAlignmentV = Text2D_1.AlignBottom;
  13486. return;
  13487. case "center":
  13488. this.textAlignmentV = Text2D_1.AlignCenter;
  13489. return;
  13490. }
  13491. };
  13492. Text2D.prototype._useTextureAlpha = function () {
  13493. return this._fontSDF;
  13494. };
  13495. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  13496. return !this._fontSDF;
  13497. };
  13498. return Text2D;
  13499. }(BABYLON.RenderablePrim2D));
  13500. Text2D.TEXT2D_MAINPARTID = 1;
  13501. Text2D.TEXT2D_CATEGORY_SDF = "SignedDistanceField";
  13502. Text2D._AlignLeft = 1;
  13503. Text2D._AlignTop = 1; // Same as left
  13504. Text2D._AlignRight = 2;
  13505. Text2D._AlignBottom = 2; // Same as right
  13506. Text2D._AlignCenter = 3;
  13507. __decorate([
  13508. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D_1.fontProperty = pi; }, false, true)
  13509. ], Text2D.prototype, "fontName", null);
  13510. __decorate([
  13511. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D_1.defaultFontColorProperty = pi; })
  13512. ], Text2D.prototype, "defaultFontColor", null);
  13513. __decorate([
  13514. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D_1.textProperty = pi; }, false, true)
  13515. ], Text2D.prototype, "text", null);
  13516. __decorate([
  13517. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D_1.sizeProperty = pi; })
  13518. ], Text2D.prototype, "size", null);
  13519. __decorate([
  13520. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  13521. ], Text2D.prototype, "fontSuperSample", null);
  13522. __decorate([
  13523. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  13524. ], Text2D.prototype, "fontSignedDistanceField", null);
  13525. Text2D = Text2D_1 = __decorate([
  13526. BABYLON.className("Text2D", "BABYLON")
  13527. ], Text2D);
  13528. BABYLON.Text2D = Text2D;
  13529. var Text2D_1;
  13530. })(BABYLON || (BABYLON = {}));
  13531. var __extends = (this && this.__extends) || function (d, b) {
  13532. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13533. function __() { this.constructor = d; }
  13534. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13535. };
  13536. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13537. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13538. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13539. 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;
  13540. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13541. };
  13542. var BABYLON;
  13543. (function (BABYLON) {
  13544. var Lines2DRenderCache = (function (_super) {
  13545. __extends(Lines2DRenderCache, _super);
  13546. function Lines2DRenderCache(engine, modelKey) {
  13547. var _this = _super.call(this, engine, modelKey) || this;
  13548. _this.effectsReady = false;
  13549. _this.fillVB = null;
  13550. _this.fillIB = null;
  13551. _this.fillIndicesCount = 0;
  13552. _this.instancingFillAttributes = null;
  13553. _this.effectFill = null;
  13554. _this.effectFillInstanced = null;
  13555. _this.borderVB = null;
  13556. _this.borderIB = null;
  13557. _this.borderIndicesCount = 0;
  13558. _this.instancingBorderAttributes = null;
  13559. _this.effectBorder = null;
  13560. _this.effectBorderInstanced = null;
  13561. return _this;
  13562. }
  13563. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  13564. // Do nothing if the shader is still loading/preparing
  13565. if (!this.effectsReady) {
  13566. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  13567. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  13568. return false;
  13569. }
  13570. this.effectsReady = true;
  13571. }
  13572. var canvas = instanceInfo.owner.owner;
  13573. var engine = canvas.engine;
  13574. var depthFunction = 0;
  13575. if (this.effectFill && this.effectBorder) {
  13576. depthFunction = engine.getDepthFunction();
  13577. engine.setDepthFunctionToLessOrEqual();
  13578. }
  13579. var curAlphaMode = engine.getAlphaMode();
  13580. if (this.effectFill) {
  13581. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  13582. var pid = context.groupInfoPartData[partIndex];
  13583. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13584. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13585. }
  13586. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  13587. engine.enableEffect(effect);
  13588. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  13589. if (context.useInstancing) {
  13590. if (!this.instancingFillAttributes) {
  13591. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  13592. }
  13593. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13594. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13595. canvas._addDrawCallCount(1, context.renderMode);
  13596. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  13597. engine.draw(true, 0, this.fillIndicesCount, count);
  13598. engine.unbindInstanceAttributes();
  13599. }
  13600. else {
  13601. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13602. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13603. this.setupUniforms(effect, partIndex, pid._partData, i);
  13604. engine.draw(true, 0, this.fillIndicesCount);
  13605. }
  13606. }
  13607. }
  13608. if (this.effectBorder) {
  13609. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  13610. var pid = context.groupInfoPartData[partIndex];
  13611. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13612. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13613. }
  13614. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  13615. engine.enableEffect(effect);
  13616. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  13617. if (context.useInstancing) {
  13618. if (!this.instancingBorderAttributes) {
  13619. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  13620. }
  13621. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13622. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13623. canvas._addDrawCallCount(1, context.renderMode);
  13624. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  13625. engine.draw(true, 0, this.borderIndicesCount, count);
  13626. engine.unbindInstanceAttributes();
  13627. }
  13628. else {
  13629. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13630. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13631. this.setupUniforms(effect, partIndex, pid._partData, i);
  13632. engine.draw(true, 0, this.borderIndicesCount);
  13633. }
  13634. }
  13635. }
  13636. engine.setAlphaMode(curAlphaMode, true);
  13637. if (this.effectFill && this.effectBorder) {
  13638. engine.setDepthFunction(depthFunction);
  13639. }
  13640. return true;
  13641. };
  13642. Lines2DRenderCache.prototype.dispose = function () {
  13643. if (!_super.prototype.dispose.call(this)) {
  13644. return false;
  13645. }
  13646. if (this.fillVB) {
  13647. this._engine._releaseBuffer(this.fillVB);
  13648. this.fillVB = null;
  13649. }
  13650. if (this.fillIB) {
  13651. this._engine._releaseBuffer(this.fillIB);
  13652. this.fillIB = null;
  13653. }
  13654. this.effectFill = null;
  13655. this.effectFillInstanced = null;
  13656. this.effectBorder = null;
  13657. this.effectBorderInstanced = null;
  13658. if (this.borderVB) {
  13659. this._engine._releaseBuffer(this.borderVB);
  13660. this.borderVB = null;
  13661. }
  13662. if (this.borderIB) {
  13663. this._engine._releaseBuffer(this.borderIB);
  13664. this.borderIB = null;
  13665. }
  13666. return true;
  13667. };
  13668. return Lines2DRenderCache;
  13669. }(BABYLON.ModelRenderCache));
  13670. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  13671. var Lines2DInstanceData = (function (_super) {
  13672. __extends(Lines2DInstanceData, _super);
  13673. function Lines2DInstanceData(partId) {
  13674. return _super.call(this, partId, 1) || this;
  13675. }
  13676. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  13677. get: function () {
  13678. return null;
  13679. },
  13680. set: function (value) {
  13681. },
  13682. enumerable: true,
  13683. configurable: true
  13684. });
  13685. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  13686. get: function () {
  13687. return null;
  13688. },
  13689. set: function (value) {
  13690. },
  13691. enumerable: true,
  13692. configurable: true
  13693. });
  13694. return Lines2DInstanceData;
  13695. }(BABYLON.Shape2DInstanceData));
  13696. __decorate([
  13697. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  13698. ], Lines2DInstanceData.prototype, "boundingMin", null);
  13699. __decorate([
  13700. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  13701. ], Lines2DInstanceData.prototype, "boundingMax", null);
  13702. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  13703. var Lines2D = Lines2D_1 = (function (_super) {
  13704. __extends(Lines2D, _super);
  13705. /**
  13706. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  13707. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  13708. * @param settings a combination of settings, possible ones are
  13709. * - 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)
  13710. * - children: an array of direct children
  13711. * - id a text identifier, for information purpose
  13712. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13713. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13714. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13715. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13716. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13717. * - zOrder: override the zOrder with the specified value
  13718. * - origin: define the normalized origin point location, default [0.5;0.5]
  13719. * - 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.
  13720. * - 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.
  13721. * - 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.
  13722. * - 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.
  13723. * - 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)
  13724. * - 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)
  13725. * - borderThickness: the thickness of the drawn border, default is 1.
  13726. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  13727. * - 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.
  13728. * - 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.
  13729. * - 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!
  13730. * - 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.
  13731. * - 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).
  13732. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13733. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13734. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13735. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13736. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13737. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13738. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13739. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13740. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13741. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13742. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13743. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13744. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13745. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13746. */
  13747. function Lines2D(points, settings) {
  13748. var _this = this;
  13749. if (!settings) {
  13750. settings = {};
  13751. }
  13752. _this = _super.call(this, settings) || this;
  13753. _this._fillVB = null;
  13754. _this._fillIB = null;
  13755. _this._borderVB = null;
  13756. _this._borderIB = null;
  13757. _this._size = BABYLON.Size.Zero();
  13758. _this._boundingMin = null;
  13759. _this._boundingMax = null;
  13760. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  13761. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  13762. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  13763. var closed = (settings.closed == null) ? false : settings.closed;
  13764. _this.points = points;
  13765. _this.fillThickness = fillThickness;
  13766. _this.startCap = startCap;
  13767. _this.endCap = endCap;
  13768. _this.closed = closed;
  13769. return _this;
  13770. }
  13771. Object.defineProperty(Lines2D, "NoCap", {
  13772. /**
  13773. * No Cap to apply on the extremity
  13774. */
  13775. get: function () { return Lines2D_1._noCap; },
  13776. enumerable: true,
  13777. configurable: true
  13778. });
  13779. Object.defineProperty(Lines2D, "RoundCap", {
  13780. /**
  13781. * A round cap, will use the line thickness as diameter
  13782. */
  13783. get: function () { return Lines2D_1._roundCap; },
  13784. enumerable: true,
  13785. configurable: true
  13786. });
  13787. Object.defineProperty(Lines2D, "TriangleCap", {
  13788. /**
  13789. * Creates a triangle at the extremity.
  13790. */
  13791. get: function () { return Lines2D_1._triangleCap; },
  13792. enumerable: true,
  13793. configurable: true
  13794. });
  13795. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  13796. /**
  13797. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  13798. */
  13799. get: function () { return Lines2D_1._squareAnchorCap; },
  13800. enumerable: true,
  13801. configurable: true
  13802. });
  13803. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  13804. /**
  13805. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  13806. */
  13807. get: function () { return Lines2D_1._roundAnchorCap; },
  13808. enumerable: true,
  13809. configurable: true
  13810. });
  13811. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  13812. /**
  13813. * Creates a diamond anchor at the extremity.
  13814. */
  13815. get: function () { return Lines2D_1._diamondAnchorCap; },
  13816. enumerable: true,
  13817. configurable: true
  13818. });
  13819. Object.defineProperty(Lines2D, "ArrowCap", {
  13820. /**
  13821. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  13822. */
  13823. get: function () { return Lines2D_1._arrowCap; },
  13824. enumerable: true,
  13825. configurable: true
  13826. });
  13827. Object.defineProperty(Lines2D.prototype, "points", {
  13828. get: function () {
  13829. return this._points;
  13830. },
  13831. set: function (value) {
  13832. this._points = value;
  13833. this._primTriArrayDirty = true;
  13834. this._boundingBoxDirty();
  13835. },
  13836. enumerable: true,
  13837. configurable: true
  13838. });
  13839. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  13840. get: function () {
  13841. return this._fillThickness;
  13842. },
  13843. set: function (value) {
  13844. this._fillThickness = value;
  13845. },
  13846. enumerable: true,
  13847. configurable: true
  13848. });
  13849. Object.defineProperty(Lines2D.prototype, "closed", {
  13850. get: function () {
  13851. return this._closed;
  13852. },
  13853. set: function (value) {
  13854. this._closed = value;
  13855. },
  13856. enumerable: true,
  13857. configurable: true
  13858. });
  13859. Object.defineProperty(Lines2D.prototype, "startCap", {
  13860. get: function () {
  13861. return this._startCap;
  13862. },
  13863. set: function (value) {
  13864. this._startCap = value;
  13865. },
  13866. enumerable: true,
  13867. configurable: true
  13868. });
  13869. Object.defineProperty(Lines2D.prototype, "endCap", {
  13870. get: function () {
  13871. return this._endCap;
  13872. },
  13873. set: function (value) {
  13874. this._endCap = value;
  13875. },
  13876. enumerable: true,
  13877. configurable: true
  13878. });
  13879. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  13880. var p = intersectInfo._localPickPosition;
  13881. this.updateTriArray();
  13882. return this._primTriArray.doesContain(p);
  13883. };
  13884. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  13885. get: function () {
  13886. if (!this._boundingMin) {
  13887. this._computeLines2D();
  13888. }
  13889. return this._boundingMin;
  13890. },
  13891. enumerable: true,
  13892. configurable: true
  13893. });
  13894. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  13895. get: function () {
  13896. if (!this._boundingMax) {
  13897. this._computeLines2D();
  13898. }
  13899. return this._boundingMax;
  13900. },
  13901. enumerable: true,
  13902. configurable: true
  13903. });
  13904. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  13905. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  13906. // Remove the BORDER category, we don't use it in the VertexShader
  13907. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  13908. if (i !== -1) {
  13909. res.splice(i, 1);
  13910. }
  13911. return res;
  13912. };
  13913. Lines2D.prototype.updateLevelBoundingInfo = function () {
  13914. if (!this._size) {
  13915. return false;
  13916. }
  13917. if (!this._boundingMin) {
  13918. this._computeLines2D();
  13919. }
  13920. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  13921. return true;
  13922. };
  13923. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  13924. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  13925. return renderCache;
  13926. };
  13927. ///////////////////////////////////////////////////////////////////////////////////
  13928. // Methods for Lines building
  13929. Lines2D.prototype._perp = function (v, res) {
  13930. res.x = v.y;
  13931. res.y = -v.x;
  13932. };
  13933. ;
  13934. Lines2D.prototype._direction = function (a, b, res) {
  13935. a.subtractToRef(b, res);
  13936. res.normalize();
  13937. };
  13938. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  13939. a.addToRef(b, tangent);
  13940. tangent.normalize();
  13941. miter.x = -tangent.y;
  13942. miter.y = tangent.x;
  13943. Lines2D_1._miterTps.x = -a.y;
  13944. Lines2D_1._miterTps.y = a.x;
  13945. return 1 / BABYLON.Vector2.Dot(miter, Lines2D_1._miterTps);
  13946. };
  13947. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  13948. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  13949. if (d === 0)
  13950. return false;
  13951. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  13952. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  13953. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  13954. return false;
  13955. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  13956. return false;
  13957. return true;
  13958. };
  13959. Lines2D.prototype._updateMinMax = function (array, offset) {
  13960. if (offset >= array.length) {
  13961. return;
  13962. }
  13963. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  13964. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  13965. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  13966. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  13967. };
  13968. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  13969. var borderMode = borderThickness != null && !isNaN(borderThickness);
  13970. var off = index * (borderMode ? 8 : 4);
  13971. // 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)
  13972. if (off >= array.length) {
  13973. return;
  13974. }
  13975. // Store start/end normal, we need it for the cap construction
  13976. if (index === 0) {
  13977. this._perp(n, Lines2D_1._startDir);
  13978. }
  13979. else if (index === max - 1) {
  13980. this._perp(n, Lines2D_1._endDir);
  13981. Lines2D_1._endDir.x *= -1;
  13982. Lines2D_1._endDir.y *= -1;
  13983. }
  13984. var swap = false;
  13985. array[off + 0] = p.x + n.x * halfThickness;
  13986. array[off + 1] = p.y + n.y * halfThickness;
  13987. array[off + 2] = p.x + n.x * -halfThickness;
  13988. array[off + 3] = p.y + n.y * -halfThickness;
  13989. this._updateMinMax(array, off);
  13990. this._updateMinMax(array, off + 2);
  13991. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  13992. // 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
  13993. if (detectFlip != 0) {
  13994. // Flip if intersect
  13995. var flipOff = detectFlip * (borderMode ? 8 : 4);
  13996. 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])) {
  13997. swap = true;
  13998. var tps = array[off + 0];
  13999. array[off + 0] = array[off + 2];
  14000. array[off + 2] = tps;
  14001. tps = array[off + 1];
  14002. array[off + 1] = array[off + 3];
  14003. array[off + 3] = tps;
  14004. }
  14005. }
  14006. if (borderMode) {
  14007. var t = halfThickness + borderThickness;
  14008. array[off + 4] = p.x + n.x * (swap ? -t : t);
  14009. array[off + 5] = p.y + n.y * (swap ? -t : t);
  14010. array[off + 6] = p.x + n.x * (swap ? t : -t);
  14011. array[off + 7] = p.y + n.y * (swap ? t : -t);
  14012. this._updateMinMax(array, off + 4);
  14013. this._updateMinMax(array, off + 6);
  14014. }
  14015. if (contour) {
  14016. off += borderMode ? 4 : 0;
  14017. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  14018. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  14019. }
  14020. };
  14021. Lines2D.prototype._getCapSize = function (type, border) {
  14022. if (border === void 0) { border = false; }
  14023. var sd = Lines2D_1._roundCapSubDiv;
  14024. // If no array given, we call this to get the size
  14025. var vbsize = 0, ibsize = 0;
  14026. switch (type) {
  14027. case Lines2D_1.NoCap:
  14028. {
  14029. // If the line is not close and we're computing border, we add the size to generate the edge border
  14030. if (!this.closed && border) {
  14031. vbsize = 4;
  14032. ibsize = 6;
  14033. }
  14034. else {
  14035. vbsize = ibsize = 0;
  14036. }
  14037. break;
  14038. }
  14039. case Lines2D_1.RoundCap:
  14040. {
  14041. if (border) {
  14042. vbsize = sd;
  14043. ibsize = (sd - 2) * 3;
  14044. }
  14045. else {
  14046. vbsize = (sd / 2) + 1;
  14047. ibsize = (sd / 2) * 3;
  14048. }
  14049. break;
  14050. }
  14051. case Lines2D_1.ArrowCap:
  14052. {
  14053. if (border) {
  14054. vbsize = 12;
  14055. ibsize = 24;
  14056. }
  14057. else {
  14058. vbsize = 3;
  14059. ibsize = 3;
  14060. }
  14061. break;
  14062. }
  14063. case Lines2D_1.TriangleCap:
  14064. {
  14065. if (border) {
  14066. vbsize = 6;
  14067. ibsize = 12;
  14068. }
  14069. else {
  14070. vbsize = 3;
  14071. ibsize = 3;
  14072. }
  14073. break;
  14074. }
  14075. case Lines2D_1.DiamondAnchorCap:
  14076. {
  14077. if (border) {
  14078. vbsize = 10;
  14079. ibsize = 24;
  14080. }
  14081. else {
  14082. vbsize = 5;
  14083. ibsize = 9;
  14084. }
  14085. break;
  14086. }
  14087. case Lines2D_1.SquareAnchorCap:
  14088. {
  14089. if (border) {
  14090. vbsize = 12;
  14091. ibsize = 30;
  14092. }
  14093. else {
  14094. vbsize = 4;
  14095. ibsize = 6;
  14096. }
  14097. break;
  14098. }
  14099. case Lines2D_1.RoundAnchorCap:
  14100. {
  14101. if (border) {
  14102. vbsize = sd * 2;
  14103. ibsize = (sd - 1) * 6;
  14104. }
  14105. else {
  14106. vbsize = sd + 1;
  14107. ibsize = (sd + 1) * 3;
  14108. }
  14109. break;
  14110. }
  14111. }
  14112. return { vbsize: vbsize * 2, ibsize: ibsize };
  14113. };
  14114. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  14115. var c = Math.cos(rotation);
  14116. var s = Math.sin(rotation);
  14117. Lines2D_1._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  14118. Lines2D_1._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  14119. var offset = baseOffset + (index * 2);
  14120. vb[offset + 0] = Lines2D_1._tpsV.x;
  14121. vb[offset + 1] = Lines2D_1._tpsV.y;
  14122. if (contour) {
  14123. contour.push(Lines2D_1._tpsV.x);
  14124. contour.push(Lines2D_1._tpsV.y);
  14125. }
  14126. this._updateMinMax(vb, offset);
  14127. return (baseOffset + index * 2) / 2;
  14128. };
  14129. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  14130. ib[baseOffset + index] = vertexIndex;
  14131. };
  14132. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  14133. // 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
  14134. var sd = Lines2D_1._roundCapSubDiv;
  14135. var dir = new BABYLON.Vector2(1, 0);
  14136. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  14137. var ht = thickness / 2;
  14138. var t = thickness;
  14139. var borderMode = borderThickness != null;
  14140. var bt = borderThickness;
  14141. switch (type) {
  14142. case Lines2D_1.NoCap:
  14143. if (borderMode && !this.closed) {
  14144. var vi = 0;
  14145. var ii = 0;
  14146. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  14147. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  14148. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  14149. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  14150. this._storeIndex(ib, ibi, ii++, v1);
  14151. this._storeIndex(ib, ibi, ii++, v2);
  14152. this._storeIndex(ib, ibi, ii++, v3);
  14153. this._storeIndex(ib, ibi, ii++, v1);
  14154. this._storeIndex(ib, ibi, ii++, v3);
  14155. this._storeIndex(ib, ibi, ii++, v4);
  14156. }
  14157. break;
  14158. case Lines2D_1.ArrowCap:
  14159. ht *= 2;
  14160. case Lines2D_1.TriangleCap:
  14161. {
  14162. if (borderMode) {
  14163. var f = type === Lines2D_1.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  14164. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  14165. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  14166. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  14167. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  14168. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  14169. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  14170. var ii = 0;
  14171. this._storeIndex(ib, ibi, ii++, v1);
  14172. this._storeIndex(ib, ibi, ii++, v4);
  14173. this._storeIndex(ib, ibi, ii++, v5);
  14174. this._storeIndex(ib, ibi, ii++, v1);
  14175. this._storeIndex(ib, ibi, ii++, v5);
  14176. this._storeIndex(ib, ibi, ii++, v2);
  14177. this._storeIndex(ib, ibi, ii++, v6);
  14178. this._storeIndex(ib, ibi, ii++, v3);
  14179. this._storeIndex(ib, ibi, ii++, v2);
  14180. this._storeIndex(ib, ibi, ii++, v6);
  14181. this._storeIndex(ib, ibi, ii++, v2);
  14182. this._storeIndex(ib, ibi, ii++, v5);
  14183. if (type === Lines2D_1.ArrowCap) {
  14184. var rht = thickness / 2;
  14185. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  14186. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  14187. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  14188. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  14189. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  14190. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  14191. this._storeIndex(ib, ibi, ii++, v7);
  14192. this._storeIndex(ib, ibi, ii++, v8);
  14193. this._storeIndex(ib, ibi, ii++, v9);
  14194. this._storeIndex(ib, ibi, ii++, v7);
  14195. this._storeIndex(ib, ibi, ii++, v9);
  14196. this._storeIndex(ib, ibi, ii++, v4);
  14197. this._storeIndex(ib, ibi, ii++, v10);
  14198. this._storeIndex(ib, ibi, ii++, v12);
  14199. this._storeIndex(ib, ibi, ii++, v11);
  14200. this._storeIndex(ib, ibi, ii++, v10);
  14201. this._storeIndex(ib, ibi, ii++, v6);
  14202. this._storeIndex(ib, ibi, ii++, v12);
  14203. }
  14204. }
  14205. else {
  14206. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  14207. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  14208. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  14209. this._storeIndex(ib, ibi, 0, v1);
  14210. this._storeIndex(ib, ibi, 1, v2);
  14211. this._storeIndex(ib, ibi, 2, v3);
  14212. }
  14213. break;
  14214. }
  14215. case Lines2D_1.RoundCap:
  14216. {
  14217. if (borderMode) {
  14218. var curA = -Math.PI / 2;
  14219. var incA = Math.PI / (sd / 2 - 1);
  14220. var ii = 0;
  14221. for (var i = 0; i < (sd / 2); i++) {
  14222. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  14223. 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);
  14224. if (i > 0) {
  14225. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14226. this._storeIndex(ib, ibi, ii++, v2 - 2);
  14227. this._storeIndex(ib, ibi, ii++, v2);
  14228. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14229. this._storeIndex(ib, ibi, ii++, v2);
  14230. this._storeIndex(ib, ibi, ii++, v1);
  14231. }
  14232. curA += incA;
  14233. }
  14234. }
  14235. else {
  14236. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  14237. var curA = -Math.PI / 2;
  14238. var incA = Math.PI / (sd / 2 - 1);
  14239. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  14240. curA += incA;
  14241. for (var i = 1; i < (sd / 2); i++) {
  14242. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  14243. this._storeIndex(ib, ibi, i * 3 + 0, c);
  14244. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  14245. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  14246. curA += incA;
  14247. }
  14248. }
  14249. break;
  14250. }
  14251. case Lines2D_1.SquareAnchorCap:
  14252. {
  14253. var vi = 0;
  14254. var c = borderMode ? null : contour;
  14255. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  14256. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  14257. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  14258. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  14259. if (borderMode) {
  14260. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  14261. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  14262. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  14263. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  14264. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  14265. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  14266. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  14267. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  14268. var ii = 0;
  14269. this._storeIndex(ib, ibi, ii++, v6);
  14270. this._storeIndex(ib, ibi, ii++, v1);
  14271. this._storeIndex(ib, ibi, ii++, v5);
  14272. this._storeIndex(ib, ibi, ii++, v6);
  14273. this._storeIndex(ib, ibi, ii++, v7);
  14274. this._storeIndex(ib, ibi, ii++, v1);
  14275. this._storeIndex(ib, ibi, ii++, v1);
  14276. this._storeIndex(ib, ibi, ii++, v7);
  14277. this._storeIndex(ib, ibi, ii++, v8);
  14278. this._storeIndex(ib, ibi, ii++, v1);
  14279. this._storeIndex(ib, ibi, ii++, v8);
  14280. this._storeIndex(ib, ibi, ii++, v2);
  14281. this._storeIndex(ib, ibi, ii++, v2);
  14282. this._storeIndex(ib, ibi, ii++, v8);
  14283. this._storeIndex(ib, ibi, ii++, v9);
  14284. this._storeIndex(ib, ibi, ii++, v2);
  14285. this._storeIndex(ib, ibi, ii++, v9);
  14286. this._storeIndex(ib, ibi, ii++, v3);
  14287. this._storeIndex(ib, ibi, ii++, v3);
  14288. this._storeIndex(ib, ibi, ii++, v9);
  14289. this._storeIndex(ib, ibi, ii++, v10);
  14290. this._storeIndex(ib, ibi, ii++, v3);
  14291. this._storeIndex(ib, ibi, ii++, v10);
  14292. this._storeIndex(ib, ibi, ii++, v4);
  14293. this._storeIndex(ib, ibi, ii++, v10);
  14294. this._storeIndex(ib, ibi, ii++, v11);
  14295. this._storeIndex(ib, ibi, ii++, v4);
  14296. this._storeIndex(ib, ibi, ii++, v11);
  14297. this._storeIndex(ib, ibi, ii++, v12);
  14298. this._storeIndex(ib, ibi, ii++, v4);
  14299. }
  14300. else {
  14301. this._storeIndex(ib, ibi, 0, v1);
  14302. this._storeIndex(ib, ibi, 1, v2);
  14303. this._storeIndex(ib, ibi, 2, v3);
  14304. this._storeIndex(ib, ibi, 3, v1);
  14305. this._storeIndex(ib, ibi, 4, v3);
  14306. this._storeIndex(ib, ibi, 5, v4);
  14307. }
  14308. break;
  14309. }
  14310. case Lines2D_1.RoundAnchorCap:
  14311. {
  14312. var cpos = Math.sqrt(t * t - ht * ht);
  14313. var center = new BABYLON.Vector2(cpos, 0);
  14314. var curA = BABYLON.Tools.ToRadians(-150);
  14315. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  14316. if (borderMode) {
  14317. var ii = 0;
  14318. for (var i = 0; i < sd; i++) {
  14319. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  14320. 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);
  14321. if (i > 0) {
  14322. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14323. this._storeIndex(ib, ibi, ii++, v2 - 2);
  14324. this._storeIndex(ib, ibi, ii++, v2);
  14325. this._storeIndex(ib, ibi, ii++, v1 - 2);
  14326. this._storeIndex(ib, ibi, ii++, v2);
  14327. this._storeIndex(ib, ibi, ii++, v1);
  14328. }
  14329. curA += incA;
  14330. }
  14331. }
  14332. else {
  14333. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  14334. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  14335. curA += incA;
  14336. for (var i = 1; i < sd; i++) {
  14337. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  14338. this._storeIndex(ib, ibi, i * 3 + 0, c);
  14339. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  14340. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  14341. curA += incA;
  14342. }
  14343. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  14344. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  14345. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  14346. }
  14347. break;
  14348. }
  14349. case Lines2D_1.DiamondAnchorCap:
  14350. {
  14351. var vi = 0;
  14352. var c = borderMode ? null : contour;
  14353. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  14354. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  14355. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  14356. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  14357. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  14358. if (borderMode) {
  14359. var f = Math.sqrt(bt * bt * 2);
  14360. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  14361. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  14362. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  14363. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  14364. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  14365. var ii = 0;
  14366. this._storeIndex(ib, ibi, ii++, v6);
  14367. this._storeIndex(ib, ibi, ii++, v7);
  14368. this._storeIndex(ib, ibi, ii++, v1);
  14369. this._storeIndex(ib, ibi, ii++, v1);
  14370. this._storeIndex(ib, ibi, ii++, v7);
  14371. this._storeIndex(ib, ibi, ii++, v2);
  14372. this._storeIndex(ib, ibi, ii++, v2);
  14373. this._storeIndex(ib, ibi, ii++, v7);
  14374. this._storeIndex(ib, ibi, ii++, v8);
  14375. this._storeIndex(ib, ibi, ii++, v2);
  14376. this._storeIndex(ib, ibi, ii++, v8);
  14377. this._storeIndex(ib, ibi, ii++, v3);
  14378. this._storeIndex(ib, ibi, ii++, v3);
  14379. this._storeIndex(ib, ibi, ii++, v8);
  14380. this._storeIndex(ib, ibi, ii++, v9);
  14381. this._storeIndex(ib, ibi, ii++, v3);
  14382. this._storeIndex(ib, ibi, ii++, v9);
  14383. this._storeIndex(ib, ibi, ii++, v4);
  14384. this._storeIndex(ib, ibi, ii++, v4);
  14385. this._storeIndex(ib, ibi, ii++, v9);
  14386. this._storeIndex(ib, ibi, ii++, v10);
  14387. this._storeIndex(ib, ibi, ii++, v4);
  14388. this._storeIndex(ib, ibi, ii++, v10);
  14389. this._storeIndex(ib, ibi, ii++, v5);
  14390. }
  14391. else {
  14392. this._storeIndex(ib, ibi, 0, v1);
  14393. this._storeIndex(ib, ibi, 1, v2);
  14394. this._storeIndex(ib, ibi, 2, v3);
  14395. this._storeIndex(ib, ibi, 3, v1);
  14396. this._storeIndex(ib, ibi, 4, v3);
  14397. this._storeIndex(ib, ibi, 5, v5);
  14398. this._storeIndex(ib, ibi, 6, v5);
  14399. this._storeIndex(ib, ibi, 7, v3);
  14400. this._storeIndex(ib, ibi, 8, v4);
  14401. }
  14402. break;
  14403. }
  14404. }
  14405. return null;
  14406. };
  14407. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  14408. var lineA = BABYLON.Vector2.Zero();
  14409. var lineB = BABYLON.Vector2.Zero();
  14410. var tangent = BABYLON.Vector2.Zero();
  14411. var miter = BABYLON.Vector2.Zero();
  14412. var curNormal = null;
  14413. if (this.closed) {
  14414. this.points.push(this.points[0]);
  14415. }
  14416. var total = this.points.length;
  14417. for (var i = 1; i < total; i++) {
  14418. var last = this.points[i - 1];
  14419. var cur = this.points[i];
  14420. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  14421. this._direction(cur, last, lineA);
  14422. if (!curNormal) {
  14423. curNormal = BABYLON.Vector2.Zero();
  14424. this._perp(lineA, curNormal);
  14425. }
  14426. if (i === 1) {
  14427. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  14428. }
  14429. if (!next) {
  14430. this._perp(lineA, curNormal);
  14431. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  14432. }
  14433. else {
  14434. this._direction(next, cur, lineB);
  14435. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  14436. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  14437. }
  14438. }
  14439. if (this.points.length > 2 && this.closed) {
  14440. var last2 = this.points[total - 2];
  14441. var cur2 = this.points[0];
  14442. var next2 = this.points[1];
  14443. this._direction(cur2, last2, lineA);
  14444. this._direction(next2, cur2, lineB);
  14445. this._perp(lineA, curNormal);
  14446. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  14447. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  14448. // Patch contour
  14449. if (contour) {
  14450. var off = (bt == null) ? 0 : 4;
  14451. contour[0].x = vb[off + 0];
  14452. contour[0].y = vb[off + 1];
  14453. contour[1].x = vb[off + 2];
  14454. contour[1].y = vb[off + 3];
  14455. }
  14456. }
  14457. // Remove the point we added at the beginning
  14458. if (this.closed) {
  14459. this.points.splice(total - 1);
  14460. }
  14461. };
  14462. // Methods for Lines building
  14463. ///////////////////////////////////////////////////////////////////////////////////
  14464. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  14465. var renderCache = modelRenderCache;
  14466. var engine = this.owner.engine;
  14467. if (this._fillVB === null) {
  14468. this._computeLines2D();
  14469. }
  14470. // Need to create WebGL resources for fill part?
  14471. if (this.fill) {
  14472. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  14473. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  14474. renderCache.fillIndicesCount = this._fillIB.length;
  14475. // 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
  14476. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  14477. if (ei) {
  14478. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  14479. }
  14480. // Get the non instanced version
  14481. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  14482. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  14483. }
  14484. // Need to create WebGL resources for border part?
  14485. if (this.border) {
  14486. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  14487. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  14488. renderCache.borderIndicesCount = this._borderIB.length;
  14489. // 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
  14490. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  14491. if (ei) {
  14492. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  14493. }
  14494. // Get the non instanced version
  14495. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  14496. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  14497. }
  14498. this._fillVB = null;
  14499. this._fillIB = null;
  14500. this._borderVB = null;
  14501. this._borderIB = null;
  14502. return renderCache;
  14503. };
  14504. Lines2D.prototype.updateTriArray = function () {
  14505. if (this._primTriArrayDirty) {
  14506. this._computeLines2D();
  14507. }
  14508. };
  14509. Lines2D.prototype._computeLines2D = function () {
  14510. var _this = this;
  14511. // Init min/max because their being computed here
  14512. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  14513. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  14514. var contour = new Array();
  14515. var startCapContour = new Array();
  14516. var endCapContour = new Array();
  14517. // Need to create WebGL resources for fill part?
  14518. if (this.fill) {
  14519. var startCapInfo = this._getCapSize(this.startCap);
  14520. var endCapInfo = this._getCapSize(this.endCap);
  14521. var count = this.points.length;
  14522. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  14523. this._fillVB = new Float32Array(vbSize);
  14524. var vb = this._fillVB;
  14525. var ht = this.fillThickness / 2;
  14526. var total = this.points.length;
  14527. this._buildLine(vb, this.border ? null : contour, ht);
  14528. var max = total * 2;
  14529. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  14530. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  14531. var ib = this._fillIB;
  14532. for (var i = 0; i < triCount; i += 2) {
  14533. ib[i * 3 + 0] = i + 0;
  14534. ib[i * 3 + 1] = i + 1;
  14535. ib[i * 3 + 2] = (i + 2) % max;
  14536. ib[i * 3 + 3] = i + 1;
  14537. ib[i * 3 + 4] = (i + 3) % max;
  14538. ib[i * 3 + 5] = (i + 2) % max;
  14539. }
  14540. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D_1._startDir, this.border ? null : startCapContour);
  14541. 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);
  14542. }
  14543. // Need to create WebGL resources for border part?
  14544. if (this.border) {
  14545. var startCapInfo = this._getCapSize(this.startCap, true);
  14546. var endCapInfo = this._getCapSize(this.endCap, true);
  14547. var count = this.points.length;
  14548. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  14549. this._borderVB = new Float32Array(vbSize);
  14550. var vb = this._borderVB;
  14551. var ht = this.fillThickness / 2;
  14552. var bt = this.borderThickness;
  14553. var total = this.points.length;
  14554. this._buildLine(vb, contour, ht, bt);
  14555. var max = total * 2 * 2;
  14556. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  14557. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  14558. var ib = this._borderIB;
  14559. for (var i = 0; i < triCount; i += 4) {
  14560. ib[i * 3 + 0] = i + 0;
  14561. ib[i * 3 + 1] = i + 2;
  14562. ib[i * 3 + 2] = (i + 6) % max;
  14563. ib[i * 3 + 3] = i + 0;
  14564. ib[i * 3 + 4] = (i + 6) % max;
  14565. ib[i * 3 + 5] = (i + 4) % max;
  14566. ib[i * 3 + 6] = i + 3;
  14567. ib[i * 3 + 7] = i + 1;
  14568. ib[i * 3 + 8] = (i + 5) % max;
  14569. ib[i * 3 + 9] = i + 3;
  14570. ib[i * 3 + 10] = (i + 5) % max;
  14571. ib[i * 3 + 11] = (i + 7) % max;
  14572. }
  14573. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D_1._startDir, startCapContour);
  14574. 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);
  14575. }
  14576. var startCapTri;
  14577. if (startCapContour.length > 0) {
  14578. startCapTri = Earcut.earcut(startCapContour, null, 2);
  14579. }
  14580. var endCapTri;
  14581. if (endCapContour.length > 0) {
  14582. endCapTri = Earcut.earcut(endCapContour, null, 2);
  14583. }
  14584. // Build the Tri2DArray using the contour info from the shape and the caps (if any)
  14585. {
  14586. var pl = this.points.length;
  14587. // Count the number of needed triangles
  14588. var count = ((this.closed ? pl : (pl - 1)) * 2) + (startCapTri != null ? ((startCapTri.length + endCapTri.length) / 3) : 0);
  14589. // Init/Clear the TriArray
  14590. if (!this._primTriArray) {
  14591. this._primTriArray = new BABYLON.Tri2DArray(count);
  14592. }
  14593. else {
  14594. this._primTriArray.clear(count);
  14595. }
  14596. var pta_1 = this._primTriArray;
  14597. var l = this.closed ? pl + 1 : pl;
  14598. this.transformPointWithOriginToRef(contour[0], null, Lines2D_1._prevA);
  14599. this.transformPointWithOriginToRef(contour[1], null, Lines2D_1._prevB);
  14600. var si_1 = 0;
  14601. for (var i = 1; i < l; i++) {
  14602. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 0], null, Lines2D_1._curA);
  14603. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 1], null, Lines2D_1._curB);
  14604. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curA);
  14605. pta_1.storeTriangle(si_1++, Lines2D_1._curA, Lines2D_1._prevB, Lines2D_1._curB);
  14606. Lines2D_1._prevA.x = Lines2D_1._curA.x;
  14607. Lines2D_1._prevA.y = Lines2D_1._curA.y;
  14608. Lines2D_1._prevB.x = Lines2D_1._curB.x;
  14609. Lines2D_1._prevB.y = Lines2D_1._curB.y;
  14610. }
  14611. var capIntersect = function (tri, points) {
  14612. var l = tri.length;
  14613. for (var i = 0; i < l; i += 3) {
  14614. Lines2D_1._curA.x = points[tri[i + 0] * 2 + 0];
  14615. Lines2D_1._curA.y = points[tri[i + 0] * 2 + 1];
  14616. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._curB);
  14617. Lines2D_1._curA.x = points[tri[i + 1] * 2 + 0];
  14618. Lines2D_1._curA.y = points[tri[i + 1] * 2 + 1];
  14619. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevA);
  14620. Lines2D_1._curA.x = points[tri[i + 2] * 2 + 0];
  14621. Lines2D_1._curA.y = points[tri[i + 2] * 2 + 1];
  14622. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevB);
  14623. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curB);
  14624. }
  14625. return false;
  14626. };
  14627. if (startCapTri) {
  14628. if (startCapTri) {
  14629. capIntersect(startCapTri, startCapContour);
  14630. }
  14631. if (endCapTri) {
  14632. capIntersect(endCapTri, endCapContour);
  14633. }
  14634. }
  14635. this._primTriArrayDirty = false;
  14636. }
  14637. var bs = this._boundingMax.subtract(this._boundingMin);
  14638. this._size.width = bs.x;
  14639. this._size.height = bs.y;
  14640. };
  14641. Object.defineProperty(Lines2D.prototype, "size", {
  14642. get: function () {
  14643. if (this._size == null) {
  14644. this._computeLines2D();
  14645. }
  14646. return this._size;
  14647. },
  14648. enumerable: true,
  14649. configurable: true
  14650. });
  14651. Lines2D.prototype.createInstanceDataParts = function () {
  14652. var res = new Array();
  14653. if (this.border) {
  14654. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  14655. }
  14656. if (this.fill) {
  14657. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  14658. }
  14659. return res;
  14660. };
  14661. Lines2D.prototype.applyActualScaleOnTransform = function () {
  14662. return true;
  14663. };
  14664. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  14665. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  14666. return false;
  14667. }
  14668. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  14669. var d = part;
  14670. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  14671. d.boundingMin = this.boundingMin;
  14672. d.boundingMax = this.boundingMax;
  14673. }
  14674. }
  14675. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  14676. var d = part;
  14677. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  14678. d.boundingMin = this.boundingMin;
  14679. d.boundingMax = this.boundingMax;
  14680. }
  14681. }
  14682. return true;
  14683. };
  14684. return Lines2D;
  14685. }(BABYLON.Shape2D));
  14686. Lines2D._prevA = BABYLON.Vector2.Zero();
  14687. Lines2D._prevB = BABYLON.Vector2.Zero();
  14688. Lines2D._curA = BABYLON.Vector2.Zero();
  14689. Lines2D._curB = BABYLON.Vector2.Zero();
  14690. Lines2D._miterTps = BABYLON.Vector2.Zero();
  14691. Lines2D._startDir = BABYLON.Vector2.Zero();
  14692. Lines2D._endDir = BABYLON.Vector2.Zero();
  14693. Lines2D._tpsV = BABYLON.Vector2.Zero();
  14694. Lines2D._noCap = 0;
  14695. Lines2D._roundCap = 1;
  14696. Lines2D._triangleCap = 2;
  14697. Lines2D._squareAnchorCap = 3;
  14698. Lines2D._roundAnchorCap = 4;
  14699. Lines2D._diamondAnchorCap = 5;
  14700. Lines2D._arrowCap = 6;
  14701. Lines2D._roundCapSubDiv = 36;
  14702. __decorate([
  14703. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D_1.pointsProperty = pi; })
  14704. ], Lines2D.prototype, "points", null);
  14705. __decorate([
  14706. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D_1.fillThicknessProperty = pi; })
  14707. ], Lines2D.prototype, "fillThickness", null);
  14708. __decorate([
  14709. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D_1.closedProperty = pi; })
  14710. ], Lines2D.prototype, "closed", null);
  14711. __decorate([
  14712. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D_1.startCapProperty = pi; })
  14713. ], Lines2D.prototype, "startCap", null);
  14714. __decorate([
  14715. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D_1.endCapProperty = pi; })
  14716. ], Lines2D.prototype, "endCap", null);
  14717. Lines2D = Lines2D_1 = __decorate([
  14718. BABYLON.className("Lines2D", "BABYLON")
  14719. ], Lines2D);
  14720. BABYLON.Lines2D = Lines2D;
  14721. var Lines2D_1;
  14722. })(BABYLON || (BABYLON = {}));
  14723. var __extends = (this && this.__extends) || function (d, b) {
  14724. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14725. function __() { this.constructor = d; }
  14726. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14727. };
  14728. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  14729. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  14730. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14731. 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;
  14732. return c > 3 && r && Object.defineProperty(target, key, r), r;
  14733. };
  14734. var BABYLON;
  14735. (function (BABYLON) {
  14736. // This class contains data that lifetime is bounding to the Babylon Engine object
  14737. var Canvas2DEngineBoundData = (function () {
  14738. function Canvas2DEngineBoundData() {
  14739. this._modelCache = new BABYLON.StringDictionary();
  14740. }
  14741. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  14742. return this._modelCache.getOrAddWithFactory(key, factory);
  14743. };
  14744. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  14745. if (!modelRenderCache.isDisposed) {
  14746. return false;
  14747. }
  14748. this._modelCache.remove(modelRenderCache.modelKey);
  14749. return true;
  14750. };
  14751. return Canvas2DEngineBoundData;
  14752. }());
  14753. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  14754. var Canvas2D = Canvas2D_1 = (function (_super) {
  14755. __extends(Canvas2D, _super);
  14756. function Canvas2D(scene, settings) {
  14757. var _this = _super.call(this, settings) || this;
  14758. /**
  14759. * 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.
  14760. * Beware that you have to take under consideration the origin and unitScaleFactor in your calculations! Good luck!
  14761. */
  14762. _this.worldSpaceToNodeLocal = function (worldPos) {
  14763. var node = _this._worldSpaceNode;
  14764. if (!node) {
  14765. return;
  14766. }
  14767. var mtx = node.getWorldMatrix().clone();
  14768. mtx.invert();
  14769. var usf = _this.unitScaleFactor;
  14770. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  14771. var res = new BABYLON.Vector2(v.x, v.y);
  14772. var size = _this.actualSize;
  14773. res.x += (size.width / usf) * 0.5; // res is centered, make it relative to bottom/left
  14774. res.y += (size.height / usf) * 0.5;
  14775. res.x *= usf; // multiply by the unitScaleFactor, which defines if the canvas is nth time bigger than the original world plane
  14776. res.y *= usf;
  14777. return res;
  14778. };
  14779. /**
  14780. * 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
  14781. */
  14782. _this.worldSpaceCacheChanged = function () {
  14783. var plane = _this.worldSpaceCanvasNode;
  14784. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  14785. vd.uvs = new Float32Array(8);
  14786. var material = plane.material;
  14787. var tex = _this._renderableData._cacheTexture;
  14788. if (material.diffuseTexture !== tex) {
  14789. material.diffuseTexture = tex;
  14790. tex.hasAlpha = true;
  14791. }
  14792. var nodeuv = _this._renderableData._cacheNodeUVs;
  14793. for (var i = 0; i < 4; i++) {
  14794. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  14795. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  14796. }
  14797. vd.applyToMesh(plane);
  14798. };
  14799. _this._notifDebugMode = false;
  14800. /**
  14801. * Instanced Array will be create if there's at least this number of parts/prim that can fit into it
  14802. */
  14803. _this.minPartCountToUseInstancedArray = 5;
  14804. _this._mapCounter = 0;
  14805. _this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  14806. _this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  14807. _this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  14808. _this._groupRenderCounter = new BABYLON.PerfCounter();
  14809. _this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  14810. _this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  14811. _this._updateCachedStateCounter = new BABYLON.PerfCounter();
  14812. _this._updateLayoutCounter = new BABYLON.PerfCounter();
  14813. _this._updatePositioningCounter = new BABYLON.PerfCounter();
  14814. _this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  14815. _this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  14816. _this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  14817. _this._cachedCanvasGroup = null;
  14818. _this._renderingGroupObserver = null;
  14819. _this._beforeRenderObserver = null;
  14820. _this._afterRenderObserver = null;
  14821. _this._profileInfoText = null;
  14822. BABYLON.Prim2DBase._isCanvasInit = false;
  14823. if (!settings) {
  14824. settings = {};
  14825. }
  14826. if (_this._cachingStrategy !== Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  14827. _this._background = new BABYLON.Rectangle2D({ parent: _this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  14828. _this._background.zOrder = 1.0;
  14829. _this._background.isPickable = false;
  14830. _this._background.origin = BABYLON.Vector2.Zero();
  14831. _this._background.levelVisible = false;
  14832. if (settings.backgroundRoundRadius != null) {
  14833. _this.backgroundRoundRadius = settings.backgroundRoundRadius;
  14834. }
  14835. if (settings.backgroundBorder != null) {
  14836. if (typeof (settings.backgroundBorder) === "string") {
  14837. _this.backgroundBorder = Canvas2D_1.GetBrushFromString(settings.backgroundBorder);
  14838. }
  14839. else {
  14840. _this.backgroundBorder = settings.backgroundBorder;
  14841. }
  14842. }
  14843. if (settings.backgroundBorderThickNess != null) {
  14844. _this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  14845. }
  14846. if (settings.backgroundFill != null) {
  14847. if (typeof (settings.backgroundFill) === "string") {
  14848. _this.backgroundFill = Canvas2D_1.GetBrushFromString(settings.backgroundFill);
  14849. }
  14850. else {
  14851. _this.backgroundFill = settings.backgroundFill;
  14852. }
  14853. }
  14854. // Put a handler to resize the background whenever the canvas is resizing
  14855. _this.propertyChanged.add(function (e, s) {
  14856. if (e.propertyName === "size") {
  14857. _this._background.size = _this.size;
  14858. }
  14859. }, BABYLON.Group2D.sizeProperty.flagId);
  14860. _this._background._patchHierarchy(_this);
  14861. }
  14862. var engine = scene.getEngine();
  14863. _this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  14864. _this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  14865. _this._capturedPointers = new BABYLON.StringDictionary();
  14866. _this._pickStartingPosition = BABYLON.Vector2.Zero();
  14867. _this._hierarchyLevelMaxSiblingCount = 50;
  14868. _this._hierarchyDepth = 0;
  14869. _this._zOrder = 0;
  14870. _this._zMax = 1;
  14871. _this._scene = scene;
  14872. _this._engine = engine;
  14873. _this._renderingSize = new BABYLON.Size(0, 0);
  14874. _this._designSize = settings.designSize || null;
  14875. _this._designUseHorizAxis = settings.designUseHorizAxis === true;
  14876. if (!_this._trackedGroups) {
  14877. _this._trackedGroups = new Array();
  14878. }
  14879. _this._maxAdaptiveWorldSpaceCanvasSize = null;
  14880. _this._groupCacheMaps = new BABYLON.StringDictionary();
  14881. _this._patchHierarchy(_this);
  14882. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  14883. _this._fitRenderingDevice = !settings.size;
  14884. if (!settings.size) {
  14885. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  14886. }
  14887. // Register scene dispose to also dispose the canvas when it'll happens
  14888. scene.onDisposeObservable.add(function (d, s) {
  14889. _this.dispose();
  14890. });
  14891. if (_this._isScreenSpace) {
  14892. if (settings.renderingPhase) {
  14893. if (!settings.renderingPhase.camera || settings.renderingPhase.renderingGroupID == null) {
  14894. throw Error("You have to specify a valid camera and renderingGroup");
  14895. }
  14896. _this._renderingGroupObserver = _this._scene.onRenderingGroupObservable.add(function (e, s) {
  14897. if ((_this._scene.activeCamera === settings.renderingPhase.camera) && (e.renderStage === BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT)) {
  14898. _this._engine.clear(null, false, true, true);
  14899. _this._render();
  14900. }
  14901. }, Math.pow(2, settings.renderingPhase.renderingGroupID));
  14902. }
  14903. else {
  14904. _this._afterRenderObserver = _this._scene.onAfterRenderObservable.add(function (d, s) {
  14905. _this._engine.clear(null, false, true, true);
  14906. _this._render();
  14907. });
  14908. }
  14909. }
  14910. else {
  14911. _this._beforeRenderObserver = _this._scene.onBeforeRenderObservable.add(function (d, s) {
  14912. _this._render();
  14913. });
  14914. }
  14915. _this._supprtInstancedArray = _this._engine.getCaps().instancedArrays !== null;
  14916. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  14917. // Setup the canvas for interaction (or not)
  14918. _this._setupInteraction(enableInteraction);
  14919. // Initialize the Primitive Collision Manager
  14920. if (settings.enableCollisionManager) {
  14921. var enableBorders = settings.collisionManagerUseBorders;
  14922. _this._primitiveCollisionManager = (settings.customCollisionManager == null) ? BABYLON.PrimitiveCollisionManagerBase.allocBasicPCM(_this, enableBorders) : settings.customCollisionManager(_this, enableBorders);
  14923. }
  14924. // Register this instance
  14925. Canvas2D_1._INSTANCES.push(_this);
  14926. return _this;
  14927. }
  14928. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  14929. get: function () {
  14930. return this._drawCallsOpaqueCounter;
  14931. },
  14932. enumerable: true,
  14933. configurable: true
  14934. });
  14935. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  14936. get: function () {
  14937. return this._drawCallsAlphaTestCounter;
  14938. },
  14939. enumerable: true,
  14940. configurable: true
  14941. });
  14942. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  14943. get: function () {
  14944. return this._drawCallsTransparentCounter;
  14945. },
  14946. enumerable: true,
  14947. configurable: true
  14948. });
  14949. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  14950. get: function () {
  14951. return this._groupRenderCounter;
  14952. },
  14953. enumerable: true,
  14954. configurable: true
  14955. });
  14956. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  14957. get: function () {
  14958. return this._updateTransparentDataCounter;
  14959. },
  14960. enumerable: true,
  14961. configurable: true
  14962. });
  14963. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  14964. get: function () {
  14965. return this._cachedGroupRenderCounter;
  14966. },
  14967. enumerable: true,
  14968. configurable: true
  14969. });
  14970. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  14971. get: function () {
  14972. return this._updateCachedStateCounter;
  14973. },
  14974. enumerable: true,
  14975. configurable: true
  14976. });
  14977. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  14978. get: function () {
  14979. return this._updateLayoutCounter;
  14980. },
  14981. enumerable: true,
  14982. configurable: true
  14983. });
  14984. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  14985. get: function () {
  14986. return this._updatePositioningCounter;
  14987. },
  14988. enumerable: true,
  14989. configurable: true
  14990. });
  14991. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  14992. get: function () {
  14993. return this._updateLocalTransformCounter;
  14994. },
  14995. enumerable: true,
  14996. configurable: true
  14997. });
  14998. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  14999. get: function () {
  15000. return this._updateGlobalTransformCounter;
  15001. },
  15002. enumerable: true,
  15003. configurable: true
  15004. });
  15005. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  15006. get: function () {
  15007. return this._boundingInfoRecomputeCounter;
  15008. },
  15009. enumerable: true,
  15010. configurable: true
  15011. });
  15012. Object.defineProperty(Canvas2D, "instances", {
  15013. get: function () {
  15014. return Canvas2D_1._INSTANCES;
  15015. },
  15016. enumerable: true,
  15017. configurable: true
  15018. });
  15019. Object.defineProperty(Canvas2D.prototype, "primitiveCollisionManager", {
  15020. get: function () {
  15021. return this._primitiveCollisionManager;
  15022. },
  15023. enumerable: true,
  15024. configurable: true
  15025. });
  15026. Canvas2D.prototype._canvasPreInit = function (settings) {
  15027. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D_1.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  15028. this._cachingStrategy = cachingStrategy;
  15029. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  15030. };
  15031. Canvas2D.prototype._setupInteraction = function (enable) {
  15032. var _this = this;
  15033. // No change detection
  15034. if (enable === this._interactionEnabled) {
  15035. return;
  15036. }
  15037. // Set the new state
  15038. this._interactionEnabled = enable;
  15039. // ScreenSpace mode
  15040. if (this._isScreenSpace) {
  15041. // Disable interaction
  15042. if (!enable) {
  15043. if (this._scenePrePointerObserver) {
  15044. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  15045. this._scenePrePointerObserver = null;
  15046. }
  15047. return;
  15048. }
  15049. // Enable Interaction
  15050. // Register the observable
  15051. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  15052. if (_this.isVisible === false) {
  15053. return;
  15054. }
  15055. var hs = 1 / _this.engine.getHardwareScalingLevel();
  15056. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  15057. _this._handlePointerEventForInteraction(e, localPos, s);
  15058. });
  15059. }
  15060. else {
  15061. var scene = this.scene;
  15062. if (enable) {
  15063. scene.constantlyUpdateMeshUnderPointer = true;
  15064. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  15065. if (_this.isVisible === false) {
  15066. return;
  15067. }
  15068. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  15069. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  15070. _this._handlePointerEventForInteraction(e, localPos, s);
  15071. }
  15072. });
  15073. }
  15074. else {
  15075. if (this._scenePointerObserver) {
  15076. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  15077. this._scenePointerObserver = null;
  15078. }
  15079. }
  15080. }
  15081. };
  15082. /**
  15083. * Internal method, you should use the Prim2DBase version instead
  15084. */
  15085. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  15086. if (this.isPointerCaptured(pointerId)) {
  15087. return false;
  15088. }
  15089. // Try to capture the pointer on the HTML side
  15090. try {
  15091. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  15092. }
  15093. catch (e) {
  15094. }
  15095. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  15096. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  15097. this._capturedPointers.add(pointerId.toString(), primitive);
  15098. return true;
  15099. };
  15100. /**
  15101. * Internal method, you should use the Prim2DBase version instead
  15102. */
  15103. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  15104. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  15105. return false;
  15106. }
  15107. // Try to release the pointer on the HTML side
  15108. try {
  15109. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  15110. }
  15111. catch (e) {
  15112. }
  15113. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  15114. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  15115. this._capturedPointers.remove(pointerId.toString());
  15116. return true;
  15117. };
  15118. /**
  15119. * Determine if the given pointer is captured or not
  15120. * @param pointerId the Id of the pointer
  15121. * @return true if it's captured, false otherwise
  15122. */
  15123. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  15124. return this._capturedPointers.contains(pointerId.toString());
  15125. };
  15126. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  15127. // Avoid unnecessary lookup
  15128. if (this._capturedPointers.count === 0) {
  15129. return null;
  15130. }
  15131. return this._capturedPointers.get(pointerId.toString());
  15132. };
  15133. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  15134. // Dispose check
  15135. if (this.isDisposed) {
  15136. return;
  15137. }
  15138. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  15139. if (!this._updatePointerInfo(eventData, localPosition)) {
  15140. return;
  15141. }
  15142. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  15143. // 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.
  15144. // 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.
  15145. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null, true);
  15146. // 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
  15147. this._updateOverStatus(true);
  15148. // Check if we have nothing to raise
  15149. if (!this._actualOverPrimitive && !capturedPrim) {
  15150. return;
  15151. }
  15152. // Update the relatedTarget info with the over primitive or the captured one (if any)
  15153. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  15154. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  15155. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  15156. // Analyze the pointer event type and fire proper events on the primitive
  15157. var skip = false;
  15158. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  15159. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  15160. }
  15161. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  15162. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  15163. }
  15164. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  15165. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  15166. }
  15167. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  15168. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  15169. }
  15170. eventState.skipNextObservers = skip;
  15171. };
  15172. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  15173. var s = this.scale;
  15174. var pii = this._primPointerInfo;
  15175. pii.cancelBubble = false;
  15176. if (!pii.canvasPointerPos) {
  15177. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  15178. }
  15179. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  15180. if (!camera || !camera.viewport) {
  15181. return false;
  15182. }
  15183. var engine = this._scene.getEngine();
  15184. if (this._isScreenSpace) {
  15185. var cameraViewport = camera.viewport;
  15186. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  15187. // Moving coordinates to local viewport world
  15188. var x = localPosition.x - viewport.x;
  15189. var y = localPosition.y - viewport.y;
  15190. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  15191. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  15192. }
  15193. else {
  15194. pii.canvasPointerPos.x = localPosition.x / s;
  15195. pii.canvasPointerPos.y = localPosition.y / s;
  15196. }
  15197. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  15198. pii.mouseWheelDelta = 0;
  15199. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  15200. var event = eventData.event;
  15201. if (event.wheelDelta) {
  15202. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  15203. }
  15204. else if (event.detail) {
  15205. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  15206. }
  15207. }
  15208. else {
  15209. var pe = eventData.event;
  15210. pii.ctrlKey = pe.ctrlKey;
  15211. pii.altKey = pe.altKey;
  15212. pii.shiftKey = pe.shiftKey;
  15213. pii.metaKey = pe.metaKey;
  15214. pii.button = pe.button;
  15215. pii.buttons = pe.buttons;
  15216. pii.pointerId = pe.pointerId;
  15217. pii.width = pe.width;
  15218. pii.height = pe.height;
  15219. pii.presssure = pe.pressure;
  15220. pii.tilt.x = pe.tiltX;
  15221. pii.tilt.y = pe.tiltY;
  15222. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  15223. }
  15224. return true;
  15225. };
  15226. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
  15227. if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
  15228. return;
  15229. }
  15230. // 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
  15231. if (!this._globalTransform) {
  15232. this.updateCachedStates(true);
  15233. }
  15234. var ii = Canvas2D_1._interInfo;
  15235. ii.pickPosition.x = mouseLocalPos.x;
  15236. ii.pickPosition.y = mouseLocalPos.y;
  15237. ii.findFirstOnly = false;
  15238. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  15239. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  15240. // Reset intersection info as we don't hit anything
  15241. ii.intersectedPrimitives = new Array();
  15242. ii.topMostIntersectedPrimitive = null;
  15243. }
  15244. else {
  15245. // The pointer is inside the Canvas, do an intersection test
  15246. this.intersect(ii);
  15247. // Sort primitives to get them from top to bottom
  15248. ii.intersectedPrimitives = ii.intersectedPrimitives.sort(function (a, b) { return a.prim.actualZOffset - b.prim.actualZOffset; });
  15249. }
  15250. {
  15251. // Update prev/actual intersection info, fire "overPrim" property change if needed
  15252. this._previousIntersectionList = this._actualIntersectionList;
  15253. this._actualIntersectionList = ii.intersectedPrimitives;
  15254. this._previousOverPrimitive = this._actualOverPrimitive;
  15255. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  15256. var prev = (this._previousOverPrimitive != null) ? this._previousOverPrimitive.prim : null;
  15257. var actual = (this._actualOverPrimitive != null) ? this._actualOverPrimitive.prim : null;
  15258. if (prev !== actual) {
  15259. this.onPropertyChanged("overPrim", this._previousOverPrimitive ? this._previousOverPrimitive.prim : null, this._actualOverPrimitive ? this._actualOverPrimitive.prim : null);
  15260. }
  15261. }
  15262. this._intersectionRenderId = this.scene.getRenderId();
  15263. };
  15264. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  15265. Canvas2D.prototype._updateOverStatus = function (force) {
  15266. if ((!force && (this.scene.getRenderId() === this._hoverStatusRenderId)) || !this._actualIntersectionList) {
  15267. return;
  15268. }
  15269. if (this._previousIntersectionList == null) {
  15270. this._previousIntersectionList = [];
  15271. }
  15272. // Detect a change of over
  15273. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  15274. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  15275. if (prevPrim !== actualPrim) {
  15276. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  15277. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  15278. // See the NOTE section of: https://www.w3.org/TR/pointerevents/#setting-pointer-capture
  15279. if (capturedPrim) {
  15280. if (capturedPrim === prevPrim) {
  15281. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  15282. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  15283. }
  15284. else if (capturedPrim === actualPrim) {
  15285. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  15286. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  15287. }
  15288. }
  15289. else {
  15290. var _loop_1 = function (prev) {
  15291. if (!BABYLON.Tools.first(this_1._actualIntersectionList, function (pii) { return pii.prim === prev.prim; })) {
  15292. this_1._primPointerInfo.updateRelatedTarget(prev.prim, prev.intersectionLocation);
  15293. this_1._bubbleNotifyPrimPointerObserver(prev.prim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  15294. }
  15295. };
  15296. var this_1 = this;
  15297. // Check for Out & Leave
  15298. for (var _i = 0, _a = this._previousIntersectionList; _i < _a.length; _i++) {
  15299. var prev = _a[_i];
  15300. _loop_1(prev);
  15301. }
  15302. var _loop_2 = function (actual) {
  15303. if (!BABYLON.Tools.first(this_2._previousIntersectionList, function (pii) { return pii.prim === actual.prim; })) {
  15304. this_2._primPointerInfo.updateRelatedTarget(actual.prim, actual.intersectionLocation);
  15305. this_2._bubbleNotifyPrimPointerObserver(actual.prim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  15306. }
  15307. };
  15308. var this_2 = this;
  15309. // Check for Over & Enter
  15310. for (var _b = 0, _c = this._actualIntersectionList; _b < _c.length; _b++) {
  15311. var actual = _c[_b];
  15312. _loop_2(actual);
  15313. }
  15314. }
  15315. }
  15316. this._hoverStatusRenderId = this.scene.getRenderId();
  15317. };
  15318. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  15319. if (this._primPointerInfo.isCaptured) {
  15320. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  15321. }
  15322. else {
  15323. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  15324. var pii = _a[_i];
  15325. if (pii.prim === prim) {
  15326. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  15327. return;
  15328. }
  15329. }
  15330. }
  15331. };
  15332. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  15333. if (!this._notifDebugMode) {
  15334. return;
  15335. }
  15336. var debug = "";
  15337. for (var i = 0; i < prim.hierarchyDepth; i++) {
  15338. debug += " ";
  15339. }
  15340. var pii = this._primPointerInfo;
  15341. 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;
  15342. console.log(debug);
  15343. };
  15344. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  15345. var ppi = this._primPointerInfo;
  15346. var event = eventData ? eventData.event : null;
  15347. var cur = prim;
  15348. while (cur && !cur.isDisposed) {
  15349. this._updatePrimPointerPos(cur);
  15350. // For the first level we have to fire Enter or Leave for corresponding Over or Out
  15351. if (cur === prim) {
  15352. // Fire the proper notification
  15353. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  15354. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerEnter);
  15355. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  15356. }
  15357. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  15358. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerLeave);
  15359. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  15360. }
  15361. }
  15362. // Exec the observers
  15363. this._debugExecObserver(cur, mask);
  15364. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  15365. eventData.skipOnPointerObservable = true;
  15366. return false;
  15367. }
  15368. this._triggerActionManager(cur, ppi, mask, event);
  15369. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  15370. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  15371. if (ppi.cancelBubble) {
  15372. return false;
  15373. }
  15374. // Loop to the parent
  15375. cur = cur.parent;
  15376. }
  15377. return true;
  15378. };
  15379. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  15380. var _this = this;
  15381. // 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
  15382. if (!this._globalTransform) {
  15383. this.updateCachedStates(true);
  15384. }
  15385. // Process Trigger related to PointerDown
  15386. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  15387. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  15388. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  15389. this._pickStartingTime = new Date().getTime();
  15390. this._pickedDownPrim = null;
  15391. if (prim.actionManager) {
  15392. this._pickedDownPrim = prim;
  15393. if (prim.actionManager.hasPickTriggers) {
  15394. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15395. switch (eventData.button) {
  15396. case 0:
  15397. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  15398. break;
  15399. case 1:
  15400. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  15401. break;
  15402. case 2:
  15403. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  15404. break;
  15405. }
  15406. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  15407. }
  15408. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15409. window.setTimeout(function () {
  15410. var ppi = _this._primPointerInfo;
  15411. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  15412. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
  15413. _this._updateOverStatus(false);
  15414. var ii = new BABYLON.IntersectInfo2D();
  15415. ii.pickPosition = ppi.canvasPointerPos.clone();
  15416. ii.findFirstOnly = false;
  15417. _this.intersect(ii);
  15418. if (ii.isPrimIntersected(prim) !== null) {
  15419. if (prim.actionManager) {
  15420. 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)) {
  15421. _this._pickStartingTime = 0;
  15422. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  15423. }
  15424. }
  15425. }
  15426. }, BABYLON.ActionManager.LongPressDelay);
  15427. }
  15428. }
  15429. }
  15430. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  15431. this._pickStartingTime = 0;
  15432. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15433. if (prim.actionManager) {
  15434. // OnPickUpTrigger
  15435. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  15436. // OnPickTrigger
  15437. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  15438. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  15439. }
  15440. }
  15441. // OnPickOutTrigger
  15442. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  15443. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  15444. }
  15445. }
  15446. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  15447. if (prim.actionManager) {
  15448. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15449. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  15450. }
  15451. }
  15452. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  15453. if (prim.actionManager) {
  15454. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  15455. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  15456. }
  15457. }
  15458. };
  15459. /**
  15460. * Don't forget to call the dispose method when you're done with the Canvas instance.
  15461. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  15462. */
  15463. Canvas2D.prototype.dispose = function () {
  15464. if (!_super.prototype.dispose.call(this)) {
  15465. return false;
  15466. }
  15467. if (this._profilingCanvas) {
  15468. this._profilingCanvas.dispose();
  15469. this._profilingCanvas = null;
  15470. }
  15471. if (this.interactionEnabled) {
  15472. this._setupInteraction(false);
  15473. }
  15474. if (this._renderingGroupObserver) {
  15475. this._scene.onRenderingGroupObservable.remove(this._renderingGroupObserver);
  15476. this._renderingGroupObserver = null;
  15477. }
  15478. if (this._beforeRenderObserver) {
  15479. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  15480. this._beforeRenderObserver = null;
  15481. }
  15482. if (this._afterRenderObserver) {
  15483. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  15484. this._afterRenderObserver = null;
  15485. }
  15486. if (this._groupCacheMaps) {
  15487. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  15488. this._groupCacheMaps = null;
  15489. }
  15490. // Unregister this instance
  15491. var index = Canvas2D_1._INSTANCES.indexOf(this);
  15492. if (index > -1) {
  15493. Canvas2D_1._INSTANCES.splice(index, 1);
  15494. }
  15495. return true;
  15496. };
  15497. Object.defineProperty(Canvas2D.prototype, "scene", {
  15498. /**
  15499. * Accessor to the Scene that owns the Canvas
  15500. * @returns The instance of the Scene object
  15501. */
  15502. get: function () {
  15503. return this._scene;
  15504. },
  15505. enumerable: true,
  15506. configurable: true
  15507. });
  15508. Object.defineProperty(Canvas2D.prototype, "engine", {
  15509. /**
  15510. * Accessor to the Engine that drives the Scene used by this Canvas
  15511. * @returns The instance of the Engine object
  15512. */
  15513. get: function () {
  15514. return this._engine;
  15515. },
  15516. enumerable: true,
  15517. configurable: true
  15518. });
  15519. Object.defineProperty(Canvas2D.prototype, "renderObservable", {
  15520. /**
  15521. * And observable called during the Canvas rendering process.
  15522. * This observable is called twice per render, each time with a different mask:
  15523. * - 1: before render is executed
  15524. * - 2: after render is executed
  15525. */
  15526. get: function () {
  15527. if (!this._renderObservable) {
  15528. this._renderObservable = new BABYLON.Observable();
  15529. }
  15530. return this._renderObservable;
  15531. },
  15532. enumerable: true,
  15533. configurable: true
  15534. });
  15535. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  15536. /**
  15537. * Accessor of the Caching Strategy used by this Canvas.
  15538. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  15539. * @returns the value corresponding to the used strategy.
  15540. */
  15541. get: function () {
  15542. return this._cachingStrategy;
  15543. },
  15544. enumerable: true,
  15545. configurable: true
  15546. });
  15547. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  15548. /**
  15549. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  15550. * @returns {}
  15551. */
  15552. get: function () {
  15553. return this._isScreenSpace;
  15554. },
  15555. enumerable: true,
  15556. configurable: true
  15557. });
  15558. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  15559. /**
  15560. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  15561. */
  15562. get: function () {
  15563. return this._worldSpaceNode;
  15564. },
  15565. set: function (val) {
  15566. this._worldSpaceNode = val;
  15567. },
  15568. enumerable: true,
  15569. configurable: true
  15570. });
  15571. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  15572. /**
  15573. * Check if the WebGL Instanced Array extension is supported or not
  15574. */
  15575. get: function () {
  15576. return this._supprtInstancedArray;
  15577. },
  15578. enumerable: true,
  15579. configurable: true
  15580. });
  15581. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  15582. /**
  15583. * Property that defines the fill object used to draw the background of the Canvas.
  15584. * Note that Canvas with a Caching Strategy of
  15585. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  15586. */
  15587. get: function () {
  15588. if (!this._background || !this._background.isVisible) {
  15589. return null;
  15590. }
  15591. return this._background.fill;
  15592. },
  15593. set: function (value) {
  15594. this.checkBackgroundAvailability();
  15595. if (value === this._background.fill) {
  15596. return;
  15597. }
  15598. this._background.fill = value;
  15599. this._background.levelVisible = true;
  15600. },
  15601. enumerable: true,
  15602. configurable: true
  15603. });
  15604. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  15605. /**
  15606. * Property that defines the border object used to draw the background of the Canvas.
  15607. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  15608. */
  15609. get: function () {
  15610. if (!this._background || !this._background.isVisible) {
  15611. return null;
  15612. }
  15613. return this._background.border;
  15614. },
  15615. set: function (value) {
  15616. this.checkBackgroundAvailability();
  15617. if (value === this._background.border) {
  15618. return;
  15619. }
  15620. this._background.border = value;
  15621. this._background.levelVisible = true;
  15622. },
  15623. enumerable: true,
  15624. configurable: true
  15625. });
  15626. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  15627. /**
  15628. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  15629. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  15630. */
  15631. get: function () {
  15632. if (!this._background || !this._background.isVisible) {
  15633. return null;
  15634. }
  15635. return this._background.borderThickness;
  15636. },
  15637. set: function (value) {
  15638. this.checkBackgroundAvailability();
  15639. if (value === this._background.borderThickness) {
  15640. return;
  15641. }
  15642. this._background.borderThickness = value;
  15643. },
  15644. enumerable: true,
  15645. configurable: true
  15646. });
  15647. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  15648. /**
  15649. * You can set the roundRadius of the background
  15650. * @returns The current roundRadius
  15651. */
  15652. get: function () {
  15653. if (!this._background || !this._background.isVisible) {
  15654. return null;
  15655. }
  15656. return this._background.roundRadius;
  15657. },
  15658. set: function (value) {
  15659. this.checkBackgroundAvailability();
  15660. if (value === this._background.roundRadius) {
  15661. return;
  15662. }
  15663. this._background.roundRadius = value;
  15664. this._background.levelVisible = true;
  15665. },
  15666. enumerable: true,
  15667. configurable: true
  15668. });
  15669. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  15670. /**
  15671. * Enable/Disable interaction for this Canvas
  15672. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  15673. */
  15674. get: function () {
  15675. return this._interactionEnabled;
  15676. },
  15677. set: function (enable) {
  15678. this._setupInteraction(enable);
  15679. },
  15680. enumerable: true,
  15681. configurable: true
  15682. });
  15683. Object.defineProperty(Canvas2D.prototype, "fitRenderingDevice", {
  15684. get: function () {
  15685. return this._fitRenderingDevice;
  15686. },
  15687. enumerable: true,
  15688. configurable: true
  15689. });
  15690. Object.defineProperty(Canvas2D.prototype, "designSize", {
  15691. get: function () {
  15692. return this._designSize;
  15693. },
  15694. enumerable: true,
  15695. configurable: true
  15696. });
  15697. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  15698. get: function () {
  15699. return this._designUseHorizAxis;
  15700. },
  15701. enumerable: true,
  15702. configurable: true
  15703. });
  15704. Object.defineProperty(Canvas2D.prototype, "overPrim", {
  15705. /**
  15706. * Return
  15707. */
  15708. get: function () {
  15709. if (this._actualIntersectionList && this._actualIntersectionList.length > 0) {
  15710. return this._actualIntersectionList[0].prim;
  15711. }
  15712. return null;
  15713. },
  15714. enumerable: true,
  15715. configurable: true
  15716. });
  15717. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  15718. /**
  15719. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  15720. * @returns {}
  15721. */
  15722. get: function () {
  15723. return this.__engineData;
  15724. },
  15725. enumerable: true,
  15726. configurable: true
  15727. });
  15728. Object.defineProperty(Canvas2D.prototype, "unitScaleFactor", {
  15729. get: function () {
  15730. return this._unitScaleFactor;
  15731. },
  15732. enumerable: true,
  15733. configurable: true
  15734. });
  15735. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  15736. if (this._profilingCanvas) {
  15737. return this._profilingCanvas;
  15738. }
  15739. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  15740. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D_1.CACHESTRATEGY_DONTCACHE, children: [
  15741. new BABYLON.Rectangle2D({
  15742. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  15743. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "12pt Lucida Console", fontSignedDistanceField: true })
  15744. ]
  15745. })
  15746. ]
  15747. });
  15748. this._profileInfoText = canvas.findById("ProfileInfoText");
  15749. this._profilingCanvas = canvas;
  15750. return canvas;
  15751. };
  15752. Canvas2D.prototype.checkBackgroundAvailability = function () {
  15753. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  15754. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  15755. }
  15756. };
  15757. Canvas2D.prototype._initPerfMetrics = function () {
  15758. this._drawCallsOpaqueCounter.fetchNewFrame();
  15759. this._drawCallsAlphaTestCounter.fetchNewFrame();
  15760. this._drawCallsTransparentCounter.fetchNewFrame();
  15761. this._groupRenderCounter.fetchNewFrame();
  15762. this._updateTransparentDataCounter.fetchNewFrame();
  15763. this._cachedGroupRenderCounter.fetchNewFrame();
  15764. this._updateCachedStateCounter.fetchNewFrame();
  15765. this._updateLayoutCounter.fetchNewFrame();
  15766. this._updatePositioningCounter.fetchNewFrame();
  15767. this._updateLocalTransformCounter.fetchNewFrame();
  15768. this._updateGlobalTransformCounter.fetchNewFrame();
  15769. this._boundingInfoRecomputeCounter.fetchNewFrame();
  15770. };
  15771. Canvas2D.prototype._fetchPerfMetrics = function () {
  15772. this._drawCallsOpaqueCounter.addCount(0, true);
  15773. this._drawCallsAlphaTestCounter.addCount(0, true);
  15774. this._drawCallsTransparentCounter.addCount(0, true);
  15775. this._groupRenderCounter.addCount(0, true);
  15776. this._updateTransparentDataCounter.addCount(0, true);
  15777. this._cachedGroupRenderCounter.addCount(0, true);
  15778. this._updateCachedStateCounter.addCount(0, true);
  15779. this._updateLayoutCounter.addCount(0, true);
  15780. this._updatePositioningCounter.addCount(0, true);
  15781. this._updateLocalTransformCounter.addCount(0, true);
  15782. this._updateGlobalTransformCounter.addCount(0, true);
  15783. this._boundingInfoRecomputeCounter.addCount(0, true);
  15784. };
  15785. Canvas2D.prototype._updateProfileCanvas = function () {
  15786. if (this._profileInfoText == null) {
  15787. return;
  15788. }
  15789. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  15790. var p = "Draw Calls:\n" +
  15791. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  15792. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  15793. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  15794. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  15795. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  15796. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  15797. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  15798. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  15799. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  15800. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  15801. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  15802. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")");
  15803. this._profileInfoText.text = p;
  15804. };
  15805. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  15806. switch (renderMode) {
  15807. case BABYLON.Render2DContext.RenderModeOpaque:
  15808. this._drawCallsOpaqueCounter.addCount(count, false);
  15809. return;
  15810. case BABYLON.Render2DContext.RenderModeAlphaTest:
  15811. this._drawCallsAlphaTestCounter.addCount(count, false);
  15812. return;
  15813. case BABYLON.Render2DContext.RenderModeTransparent:
  15814. this._drawCallsTransparentCounter.addCount(count, false);
  15815. return;
  15816. }
  15817. };
  15818. Canvas2D.prototype._addGroupRenderCount = function (count) {
  15819. this._groupRenderCounter.addCount(count, false);
  15820. };
  15821. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  15822. this._updateTransparentDataCounter.addCount(count, false);
  15823. };
  15824. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  15825. this._cachedGroupRenderCounter.addCount(count, false);
  15826. };
  15827. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  15828. this._updateCachedStateCounter.addCount(count, false);
  15829. };
  15830. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  15831. this._updateLayoutCounter.addCount(count, false);
  15832. };
  15833. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  15834. this._updatePositioningCounter.addCount(count, false);
  15835. };
  15836. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  15837. this._updateLocalTransformCounter.addCount(count, false);
  15838. };
  15839. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  15840. this._updateGlobalTransformCounter.addCount(count, false);
  15841. };
  15842. Canvas2D.prototype._updateTrackedNodes = function () {
  15843. // Get the used camera
  15844. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  15845. // Compute some matrix stuff
  15846. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  15847. var rh = this.engine.getRenderHeight();
  15848. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  15849. // Compute the screen position of each group that track a given scene node
  15850. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  15851. var group = _a[_i];
  15852. if (group.isDisposed) {
  15853. continue;
  15854. }
  15855. var node = group.trackedNode;
  15856. var worldMtx = node.getWorldMatrix();
  15857. var proj = BABYLON.Vector3.Project(Canvas2D_1._v, worldMtx, Canvas2D_1._m, v);
  15858. // Set the visibility state accordingly, if the position is outside the frustum (well on the Z planes only...) set the group to hidden
  15859. group.levelVisible = proj.z >= 0 && proj.z < 1.0;
  15860. var s = this.scale;
  15861. group.x = Math.round(proj.x / s);
  15862. group.y = Math.round((rh - proj.y) / s);
  15863. }
  15864. // If it's a WorldSpaceCanvas and it's tracking a node, let's update the WSC transformation data
  15865. if (this._trackNode) {
  15866. var rot = null;
  15867. var scale = null;
  15868. var worldmtx = this._trackNode.getWorldMatrix();
  15869. var pos = worldmtx.getTranslation().add(this._trackNodeOffset);
  15870. var wsc = this;
  15871. var wsn = wsc.worldSpaceCanvasNode;
  15872. if (this._trackNodeBillboard) {
  15873. var viewMtx = cam.getViewMatrix().clone().invert();
  15874. viewMtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  15875. rot = Canvas2D_1.tR.clone();
  15876. }
  15877. worldmtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  15878. var mtx = BABYLON.Matrix.Compose(Canvas2D_1.tS, Canvas2D_1.tR, BABYLON.Vector3.Zero());
  15879. pos = worldmtx.getTranslation().add(BABYLON.Vector3.TransformCoordinates(this._trackNodeOffset, mtx));
  15880. if (Canvas2D_1.tS.lengthSquared() !== 1) {
  15881. scale = Canvas2D_1.tS.clone();
  15882. }
  15883. if (!this._trackNodeBillboard) {
  15884. rot = Canvas2D_1.tR.clone();
  15885. }
  15886. if (wsn instanceof BABYLON.AbstractMesh) {
  15887. wsn.position = pos;
  15888. wsn.rotationQuaternion = rot;
  15889. if (scale) {
  15890. wsn.scaling = scale;
  15891. }
  15892. }
  15893. else {
  15894. throw new Error("Can't Track another Scene Node Type than AbstractMesh right now, call me lazy!");
  15895. }
  15896. }
  15897. };
  15898. /**
  15899. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  15900. */
  15901. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  15902. this._updateCanvasState(forceRecompute);
  15903. };
  15904. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  15905. if (this._globalTransformStep < 2) {
  15906. return;
  15907. }
  15908. var n = this.worldSpaceCanvasNode;
  15909. var bi = n.getBoundingInfo().boundingBox;
  15910. var v = bi.vectorsWorld;
  15911. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  15912. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  15913. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  15914. var projPoints = new Array(4);
  15915. for (var i = 0; i < 4; i++) {
  15916. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D_1._mI, Canvas2D_1._m, vp);
  15917. }
  15918. var left = projPoints[3].subtract(projPoints[0]).length();
  15919. var top = projPoints[3].subtract(projPoints[1]).length();
  15920. var right = projPoints[1].subtract(projPoints[2]).length();
  15921. var bottom = projPoints[2].subtract(projPoints[0]).length();
  15922. var w = Math.round(Math.max(top, bottom));
  15923. var h = Math.round(Math.max(right, left));
  15924. var isW = w > h;
  15925. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  15926. var edge = Math.max(w, h);
  15927. if (edge < 256) {
  15928. edge = 256;
  15929. }
  15930. else {
  15931. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  15932. }
  15933. // Clip values if needed
  15934. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  15935. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  15936. if (newScale !== this.scale) {
  15937. var scale = newScale;
  15938. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  15939. this._setRenderingScale(scale);
  15940. }
  15941. };
  15942. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  15943. // Check if the update has already been made for this render Frame
  15944. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  15945. return;
  15946. }
  15947. // Detect a change of rendering size
  15948. var renderingSizeChanged = false;
  15949. var newWidth = this.engine.getRenderWidth();
  15950. if (newWidth !== this._renderingSize.width) {
  15951. renderingSizeChanged = true;
  15952. }
  15953. this._renderingSize.width = newWidth;
  15954. var newHeight = this.engine.getRenderHeight();
  15955. if (newHeight !== this._renderingSize.height) {
  15956. renderingSizeChanged = true;
  15957. }
  15958. this._renderingSize.height = newHeight;
  15959. // If the canvas fit the rendering size and it changed, update
  15960. if (renderingSizeChanged && this._fitRenderingDevice) {
  15961. this.actualSize = this._renderingSize.clone();
  15962. this.size = this._renderingSize.clone();
  15963. if (this._background) {
  15964. this._background.size = this.size;
  15965. }
  15966. // Dirty the Layout at the Canvas level to recompute as the size changed
  15967. this._setLayoutDirty();
  15968. }
  15969. // If there's a design size, update the scale according to the renderingSize
  15970. if (this._designSize) {
  15971. var scale = void 0;
  15972. if (this._designUseHorizAxis) {
  15973. scale = this._renderingSize.width / this._designSize.width;
  15974. }
  15975. else {
  15976. scale = this._renderingSize.height / this._designSize.height;
  15977. }
  15978. this.size = this._designSize.clone();
  15979. this.actualSize = this._designSize.clone();
  15980. this.scale = scale;
  15981. }
  15982. var context = new BABYLON.PrepareRender2DContext();
  15983. ++this._globalTransformProcessStep;
  15984. this.updateCachedStates(false);
  15985. this._prepareGroupRender(context);
  15986. this._updateRenderId = this.scene.getRenderId();
  15987. };
  15988. /**
  15989. * Method that renders the Canvas, you should not invoke
  15990. */
  15991. Canvas2D.prototype._render = function () {
  15992. this._initPerfMetrics();
  15993. if (this._renderObservable && this._renderObservable.hasObservers()) {
  15994. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_PRE);
  15995. }
  15996. this._updateCanvasState(false);
  15997. this._updateTrackedNodes();
  15998. // Nothing to do is the Canvas is not visible
  15999. if (this.isVisible === false) {
  16000. return;
  16001. }
  16002. if (!this._isScreenSpace) {
  16003. this._updateAdaptiveSizeWorldCanvas();
  16004. }
  16005. this._updateCanvasState(false);
  16006. if (this._primitiveCollisionManager) {
  16007. this._primitiveCollisionManager._update();
  16008. }
  16009. if (this._primPointerInfo.canvasPointerPos) {
  16010. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
  16011. this._updateOverStatus(false);
  16012. }
  16013. this.engine.setState(false);
  16014. this._groupRender();
  16015. if (!this._isScreenSpace) {
  16016. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  16017. this.worldSpaceCacheChanged();
  16018. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  16019. }
  16020. }
  16021. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  16022. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  16023. this._cachedCanvasGroup._renderCachedCanvas();
  16024. }
  16025. this._fetchPerfMetrics();
  16026. this._updateProfileCanvas();
  16027. if (this._renderObservable && this._renderObservable.hasObservers()) {
  16028. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_POST);
  16029. }
  16030. };
  16031. /**
  16032. * Internal method that allocate a cache for the given group.
  16033. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  16034. * @param group The group to allocate the cache of.
  16035. * @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.
  16036. */
  16037. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  16038. if (useMipMap === void 0) { useMipMap = false; }
  16039. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  16040. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  16041. var rd = group._renderableData;
  16042. var noResizeScale = rd._noResizeOnScale;
  16043. var isCanvas = parent == null;
  16044. var scale;
  16045. if (noResizeScale) {
  16046. scale = isCanvas ? Canvas2D_1._unS : group.parent.actualScale;
  16047. }
  16048. else {
  16049. scale = group.actualScale;
  16050. }
  16051. // Determine size
  16052. var size = group.actualSize;
  16053. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  16054. var originalSize = size.clone();
  16055. if (minSize) {
  16056. size.width = Math.max(minSize.width, size.width);
  16057. size.height = Math.max(minSize.height, size.height);
  16058. }
  16059. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  16060. // Try to find a spot in one of the cached texture
  16061. var res = null;
  16062. var map;
  16063. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  16064. var _map = mapArray_1[_i];
  16065. map = _map;
  16066. var node = map.allocateRect(size);
  16067. if (node) {
  16068. res = { node: node, texture: map };
  16069. break;
  16070. }
  16071. }
  16072. // Couldn't find a map that could fit the rect, create a new map for it
  16073. if (!res) {
  16074. var mapSize = new BABYLON.Size(Canvas2D_1._groupTextureCacheSize, Canvas2D_1._groupTextureCacheSize);
  16075. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  16076. if (size.width > mapSize.width || size.height > mapSize.height) {
  16077. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  16078. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  16079. }
  16080. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  16081. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  16082. map.hasAlpha = true;
  16083. map.anisotropicFilteringLevel = 4;
  16084. mapArray.splice(0, 0, map);
  16085. var node = map.allocateRect(size);
  16086. res = { node: node, texture: map };
  16087. }
  16088. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  16089. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  16090. if (group !== this || this._isScreenSpace) {
  16091. var node = res.node;
  16092. // 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
  16093. var sprite = void 0;
  16094. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS) {
  16095. if (this._cachedCanvasGroup) {
  16096. this._cachedCanvasGroup.dispose();
  16097. }
  16098. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  16099. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: originalSize, spriteLocation: node.pos });
  16100. sprite.zOrder = 1;
  16101. sprite.origin = BABYLON.Vector2.Zero();
  16102. }
  16103. else {
  16104. 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 });
  16105. sprite.origin = group.origin.clone();
  16106. sprite.addExternalData("__cachedGroup__", group);
  16107. sprite.pointerEventObservable.add(function (e, s) {
  16108. if (group.pointerEventObservable !== null) {
  16109. group.pointerEventObservable.notifyObservers(e, s.mask);
  16110. }
  16111. });
  16112. res.sprite = sprite;
  16113. }
  16114. if (sprite && noResizeScale) {
  16115. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  16116. sprite.scaleX = relScale.x;
  16117. sprite.scaleY = relScale.y;
  16118. }
  16119. }
  16120. return res;
  16121. };
  16122. /**
  16123. * Internal method used to register a Scene Node to track position for the given group
  16124. * Do not invoke this method, for internal purpose only.
  16125. * @param group the group to track its associated Scene Node
  16126. */
  16127. Canvas2D.prototype._registerTrackedNode = function (group) {
  16128. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  16129. return;
  16130. }
  16131. if (!this._trackedGroups) {
  16132. this._trackedGroups = new Array();
  16133. }
  16134. this._trackedGroups.push(group);
  16135. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  16136. };
  16137. /**
  16138. * Internal method used to unregister a tracked Scene Node
  16139. * Do not invoke this method, it's for internal purpose only.
  16140. * @param group the group to unregister its tracked Scene Node from.
  16141. */
  16142. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  16143. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  16144. return;
  16145. }
  16146. var i = this._trackedGroups.indexOf(group);
  16147. if (i !== -1) {
  16148. this._trackedGroups.splice(i, 1);
  16149. }
  16150. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  16151. };
  16152. /**
  16153. * Get a Solid Color Brush instance matching the given color.
  16154. * @param color The color to retrieve
  16155. * @return A shared instance of the SolidColorBrush2D class that use the given color
  16156. */
  16157. Canvas2D.GetSolidColorBrush = function (color) {
  16158. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  16159. };
  16160. /**
  16161. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  16162. * @param color The color to retrieve
  16163. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  16164. */
  16165. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  16166. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  16167. };
  16168. /**
  16169. * Get a Gradient Color Brush
  16170. * @param color1 starting color
  16171. * @param color2 engine color
  16172. * @param translation translation vector to apply. default is [0;0]
  16173. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  16174. * @param scale scaling factor to apply. default is 1.
  16175. */
  16176. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  16177. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  16178. if (rotation === void 0) { rotation = 0; }
  16179. if (scale === void 0) { scale = 1; }
  16180. return Canvas2D_1._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  16181. };
  16182. /**
  16183. * Create a solid or gradient brush from a string value.
  16184. * @param brushString should be either
  16185. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  16186. * - "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.
  16187. */
  16188. Canvas2D.GetBrushFromString = function (brushString) {
  16189. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  16190. brushString = brushString.trim();
  16191. var split = brushString.split(",");
  16192. // Solid, formatted as: "[solid:]#FF808080"
  16193. if (split.length === 1) {
  16194. var value = null;
  16195. if (brushString.indexOf("solid:") === 0) {
  16196. value = brushString.substr(6).trim();
  16197. }
  16198. else if (brushString.indexOf("#") === 0) {
  16199. value = brushString;
  16200. }
  16201. else {
  16202. return null;
  16203. }
  16204. return Canvas2D_1.GetSolidColorBrushFromHex(value);
  16205. }
  16206. else {
  16207. if (split[0].indexOf("gradient:") === 0) {
  16208. split[0] = split[0].substr(9).trim();
  16209. }
  16210. try {
  16211. var start = BABYLON.Color4.FromHexString(split[0].trim());
  16212. var end = BABYLON.Color4.FromHexString(split[1].trim());
  16213. var t = BABYLON.Vector2.Zero();
  16214. if (split.length > 2) {
  16215. var v = split[2].trim();
  16216. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  16217. return null;
  16218. }
  16219. var sep = v.indexOf(":");
  16220. var x = parseFloat(v.substr(1, sep));
  16221. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  16222. t = new BABYLON.Vector2(x, y);
  16223. }
  16224. var r = 0;
  16225. if (split.length > 3) {
  16226. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  16227. }
  16228. var s = 1;
  16229. if (split.length > 4) {
  16230. s = parseFloat(split[4].trim());
  16231. }
  16232. return Canvas2D_1.GetGradientColorBrush(start, end, t, r, s);
  16233. }
  16234. catch (e) {
  16235. return null;
  16236. }
  16237. }
  16238. };
  16239. return Canvas2D;
  16240. }(BABYLON.Group2D));
  16241. /**
  16242. * 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.
  16243. * This strategy doesn't allow primitives added directly as children of the Canvas.
  16244. * 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.
  16245. */
  16246. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  16247. /**
  16248. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  16249. * 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.
  16250. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  16251. * 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.
  16252. */
  16253. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  16254. /**
  16255. * 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).
  16256. */
  16257. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  16258. /**
  16259. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  16260. * 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).
  16261. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  16262. */
  16263. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  16264. /**
  16265. * Observable Mask to be notified before rendering is made
  16266. */
  16267. Canvas2D.RENDEROBSERVABLE_PRE = 1;
  16268. /**
  16269. * Observable Mask to be notified after rendering is made
  16270. */
  16271. Canvas2D.RENDEROBSERVABLE_POST = 2;
  16272. Canvas2D._INSTANCES = [];
  16273. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  16274. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  16275. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  16276. Canvas2D._m = BABYLON.Matrix.Identity();
  16277. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  16278. Canvas2D.tS = BABYLON.Vector3.Zero();
  16279. Canvas2D.tT = BABYLON.Vector3.Zero();
  16280. Canvas2D.tR = BABYLON.Quaternion.Identity();
  16281. /**
  16282. * Define the default size used for both the width and height of a MapTexture to allocate.
  16283. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  16284. */
  16285. Canvas2D._groupTextureCacheSize = 1024;
  16286. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  16287. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  16288. Canvas2D = Canvas2D_1 = __decorate([
  16289. BABYLON.className("Canvas2D", "BABYLON")
  16290. ], Canvas2D);
  16291. BABYLON.Canvas2D = Canvas2D;
  16292. var WorldSpaceCanvas2D = (function (_super) {
  16293. __extends(WorldSpaceCanvas2D, _super);
  16294. /**
  16295. * 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.
  16296. * 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.
  16297. * @param scene the Scene that owns the Canvas
  16298. * @param size the dimension of the Canvas in World Space
  16299. * @param settings a combination of settings, possible ones are
  16300. * - children: an array of direct children primitives
  16301. * - id: a text identifier, for information purpose only, default is null.
  16302. * - 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).
  16303. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  16304. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  16305. * - 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
  16306. * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
  16307. * - trackNodeBillboard: if true the WorldSpaceCanvas will always face the screen
  16308. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  16309. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  16310. * - 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).
  16311. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  16312. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  16313. * - 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.
  16314. * - 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.
  16315. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  16316. * - 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.
  16317. * - 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.
  16318. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16319. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16320. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16321. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  16322. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  16323. */
  16324. function WorldSpaceCanvas2D(scene, size, settings) {
  16325. var _this = this;
  16326. BABYLON.Prim2DBase._isCanvasInit = true;
  16327. var s = settings;
  16328. s.isScreenSpace = false;
  16329. if (settings.unitScaleFactor != null) {
  16330. s.size = size.multiplyByFloats(settings.unitScaleFactor, settings.unitScaleFactor);
  16331. }
  16332. else {
  16333. s.size = size.clone();
  16334. }
  16335. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  16336. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  16337. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  16338. }
  16339. _this = _super.call(this, scene, settings) || this;
  16340. BABYLON.Prim2DBase._isCanvasInit = false;
  16341. _this._unitScaleFactor = (settings.unitScaleFactor != null) ? settings.unitScaleFactor : 1;
  16342. _this._renderableData._useMipMap = true;
  16343. _this._renderableData._anisotropicLevel = 8;
  16344. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  16345. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  16346. //}
  16347. if (settings.trackNode != null) {
  16348. _this._trackNode = settings.trackNode;
  16349. _this._trackNodeOffset = (settings.trackNodeOffset != null) ? settings.trackNodeOffset : BABYLON.Vector3.Zero();
  16350. _this._trackNodeBillboard = (settings.trackNodeBillboard != null) ? settings.trackNodeBillboard : false;
  16351. }
  16352. else {
  16353. _this._trackNode = null;
  16354. _this._trackNodeOffset = null;
  16355. _this._trackNodeBillboard = false;
  16356. }
  16357. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  16358. _this._customWorldSpaceNode = !createWorldSpaceNode;
  16359. var id = settings ? settings.id || null : null;
  16360. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  16361. var capMaxTextSize = _this.engine.getCaps().maxRenderTextureSize;
  16362. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 1K if allowed otherwise the max allowed
  16363. if (settings.maxAdaptiveCanvasSize == null) {
  16364. _this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  16365. }
  16366. else {
  16367. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  16368. _this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  16369. }
  16370. if (createWorldSpaceNode) {
  16371. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, _this);
  16372. var vertexData = BABYLON.VertexData.CreatePlane({
  16373. width: size.width,
  16374. height: size.height,
  16375. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  16376. });
  16377. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  16378. _this.applyCachedTexture(vertexData, mtl);
  16379. vertexData.applyToMesh(plane, true);
  16380. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  16381. mtl.disableLighting = true;
  16382. mtl.useAlphaFromDiffuseTexture = true;
  16383. if (settings && settings.sideOrientation) {
  16384. mtl.backFaceCulling = (settings.sideOrientation === BABYLON.Mesh.DEFAULTSIDE || settings.sideOrientation === BABYLON.Mesh.FRONTSIDE);
  16385. }
  16386. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  16387. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  16388. plane.material = mtl;
  16389. _this._worldSpaceNode = plane;
  16390. }
  16391. else {
  16392. _this._worldSpaceNode = settings.customWorldSpaceNode;
  16393. _this.applyCachedTexture(null, null);
  16394. }
  16395. _this.propertyChanged.add(function (e, st) {
  16396. if (e.propertyName !== "isVisible") {
  16397. return;
  16398. }
  16399. var mesh = _this._worldSpaceNode;
  16400. if (mesh) {
  16401. mesh.isVisible = e.newValue;
  16402. }
  16403. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  16404. return _this;
  16405. }
  16406. WorldSpaceCanvas2D.prototype.dispose = function () {
  16407. if (!_super.prototype.dispose.call(this)) {
  16408. return false;
  16409. }
  16410. if (!this._customWorldSpaceNode && this._worldSpaceNode) {
  16411. this._worldSpaceNode.dispose();
  16412. this._worldSpaceNode = null;
  16413. }
  16414. };
  16415. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNode", {
  16416. get: function () {
  16417. return this._trackNode;
  16418. },
  16419. set: function (value) {
  16420. if (this._trackNode === value) {
  16421. return;
  16422. }
  16423. this._trackNode = value;
  16424. },
  16425. enumerable: true,
  16426. configurable: true
  16427. });
  16428. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeOffset", {
  16429. get: function () {
  16430. return this._trackNodeOffset;
  16431. },
  16432. set: function (value) {
  16433. if (!this._trackNodeOffset) {
  16434. this._trackNodeOffset = value.clone();
  16435. }
  16436. else {
  16437. this._trackNodeOffset.copyFrom(value);
  16438. }
  16439. },
  16440. enumerable: true,
  16441. configurable: true
  16442. });
  16443. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeBillboard", {
  16444. get: function () {
  16445. return this._trackNodeBillboard;
  16446. },
  16447. set: function (value) {
  16448. this._trackNodeBillboard = value;
  16449. },
  16450. enumerable: true,
  16451. configurable: true
  16452. });
  16453. return WorldSpaceCanvas2D;
  16454. }(Canvas2D));
  16455. WorldSpaceCanvas2D = __decorate([
  16456. BABYLON.className("WorldSpaceCanvas2D", "BABYLON")
  16457. ], WorldSpaceCanvas2D);
  16458. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  16459. var ScreenSpaceCanvas2D = (function (_super) {
  16460. __extends(ScreenSpaceCanvas2D, _super);
  16461. /**
  16462. * 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.
  16463. * 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.
  16464. * All caching strategies will be available.
  16465. * 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]
  16466. * @param scene the Scene that owns the Canvas
  16467. * @param settings a combination of settings, possible ones are
  16468. * - children: an array of direct children primitives
  16469. * - id: a text identifier, for information purpose only
  16470. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  16471. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  16472. * - 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]
  16473. * - width: the width of the Canvas. you can alternatively use the size setting.
  16474. * - height: the height of the Canvas. you can alternatively use the size setting.
  16475. * - 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
  16476. * - 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.
  16477. * - 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.
  16478. * - 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.
  16479. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  16480. * - 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.
  16481. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  16482. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  16483. * - 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.
  16484. * - 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.
  16485. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  16486. * - 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.
  16487. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16488. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16489. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16490. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  16491. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  16492. */
  16493. function ScreenSpaceCanvas2D(scene, settings) {
  16494. var _this = this;
  16495. BABYLON.Prim2DBase._isCanvasInit = true;
  16496. _this = _super.call(this, scene, settings) || this;
  16497. return _this;
  16498. }
  16499. return ScreenSpaceCanvas2D;
  16500. }(Canvas2D));
  16501. ScreenSpaceCanvas2D = __decorate([
  16502. BABYLON.className("ScreenSpaceCanvas2D", "BABYLON")
  16503. ], ScreenSpaceCanvas2D);
  16504. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  16505. var Canvas2D_1;
  16506. })(BABYLON || (BABYLON = {}));
  16507. var __extends = (this && this.__extends) || function (d, b) {
  16508. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16509. function __() { this.constructor = d; }
  16510. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16511. };
  16512. var BABYLON;
  16513. (function (BABYLON) {
  16514. /**
  16515. * This is the class that is used to display a World Space Canvas into a 3D scene
  16516. */
  16517. var WorldSpaceCanvas2DNode = (function (_super) {
  16518. __extends(WorldSpaceCanvas2DNode, _super);
  16519. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  16520. var _this = _super.call(this, name, scene) || this;
  16521. _this._canvas = canvas;
  16522. return _this;
  16523. }
  16524. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  16525. _super.prototype.dispose.call(this);
  16526. if (this._canvas) {
  16527. this._canvas.dispose();
  16528. this._canvas = null;
  16529. }
  16530. };
  16531. return WorldSpaceCanvas2DNode;
  16532. }(BABYLON.Mesh));
  16533. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  16534. })(BABYLON || (BABYLON = {}));
  16535. var __extends = (this && this.__extends) || function (d, b) {
  16536. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16537. function __() { this.constructor = d; }
  16538. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16539. };
  16540. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  16541. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  16542. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  16543. 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;
  16544. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16545. };
  16546. var BABYLON;
  16547. (function (BABYLON) {
  16548. var Command = (function () {
  16549. function Command(execute, canExecute) {
  16550. if (!execute) {
  16551. throw Error("At least an execute lambda must be given at Command creation time");
  16552. }
  16553. this._canExecuteChanged = null;
  16554. this._lastCanExecuteResult = null;
  16555. this.execute = execute;
  16556. this.canExecute = canExecute;
  16557. }
  16558. Command.prototype.canExecute = function (parameter) {
  16559. var res = true;
  16560. if (this._canExecute) {
  16561. res = this._canExecute(parameter);
  16562. }
  16563. if (res !== this._lastCanExecuteResult) {
  16564. if (this._canExecuteChanged && this._canExecuteChanged.hasObservers()) {
  16565. this._canExecuteChanged.notifyObservers(null);
  16566. }
  16567. this._lastCanExecuteResult = res;
  16568. }
  16569. return res;
  16570. };
  16571. Command.prototype.execute = function (parameter) {
  16572. this._execute(parameter);
  16573. };
  16574. Object.defineProperty(Command.prototype, "canExecuteChanged", {
  16575. get: function () {
  16576. if (!this._canExecuteChanged) {
  16577. this._canExecuteChanged = new BABYLON.Observable();
  16578. }
  16579. return this._canExecuteChanged;
  16580. },
  16581. enumerable: true,
  16582. configurable: true
  16583. });
  16584. return Command;
  16585. }());
  16586. BABYLON.Command = Command;
  16587. var UIElement = (function (_super) {
  16588. __extends(UIElement, _super);
  16589. function UIElement(settings) {
  16590. var _this = _super.call(this) || this;
  16591. if (!settings) {
  16592. throw Error("A settings object must be passed with at least either a parent or owner parameter");
  16593. }
  16594. var type = BABYLON.Tools.getFullClassName(_this);
  16595. _this._ownerWindow = null;
  16596. _this._parent = null;
  16597. _this._visualPlaceholder = null;
  16598. _this._visualTemplateRoot = null;
  16599. _this._visualChildrenPlaceholder = null;
  16600. _this._hierarchyDepth = 0;
  16601. _this._renderingTemplateName = (settings.templateName != null) ? settings.templateName : GUIManager.DefaultTemplateName;
  16602. _this._style = (settings.styleName != null) ? GUIManager.getStyle(type, settings.styleName) : null;
  16603. _this._flags = 0;
  16604. _this._id = (settings.id != null) ? settings.id : null;
  16605. _this._uid = null;
  16606. _this._width = (settings.width != null) ? settings.width : null;
  16607. _this._height = (settings.height != null) ? settings.height : null;
  16608. _this._minWidth = (settings.minWidth != null) ? settings.minWidth : 0;
  16609. _this._minHeight = (settings.minHeight != null) ? settings.minHeight : 0;
  16610. _this._maxWidth = (settings.maxWidth != null) ? settings.maxWidth : Number.MAX_VALUE;
  16611. _this._maxHeight = (settings.maxHeight != null) ? settings.maxHeight : Number.MAX_VALUE;
  16612. _this._margin = null;
  16613. _this._padding = null;
  16614. _this._marginAlignment = null;
  16615. _this._setFlags(UIElement.flagIsVisible | UIElement.flagIsEnabled);
  16616. // Default Margin Alignment for UIElement is stretch for horizontal/vertical and not left/bottom (which is the default for Canvas2D Primitives)
  16617. //this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  16618. //this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  16619. // Set the layout/margin stuffs
  16620. if (settings.marginTop) {
  16621. _this.margin.setTop(settings.marginTop);
  16622. }
  16623. if (settings.marginLeft) {
  16624. _this.margin.setLeft(settings.marginLeft);
  16625. }
  16626. if (settings.marginRight) {
  16627. _this.margin.setRight(settings.marginRight);
  16628. }
  16629. if (settings.marginBottom) {
  16630. _this.margin.setBottom(settings.marginBottom);
  16631. }
  16632. if (settings.margin) {
  16633. if (typeof settings.margin === "string") {
  16634. _this.margin.fromString(settings.margin);
  16635. }
  16636. else {
  16637. _this.margin.fromUniformPixels(settings.margin);
  16638. }
  16639. }
  16640. if (settings.marginHAlignment) {
  16641. _this.marginAlignment.horizontal = settings.marginHAlignment;
  16642. }
  16643. if (settings.marginVAlignment) {
  16644. _this.marginAlignment.vertical = settings.marginVAlignment;
  16645. }
  16646. if (settings.marginAlignment) {
  16647. _this.marginAlignment.fromString(settings.marginAlignment);
  16648. }
  16649. if (settings.paddingTop) {
  16650. _this.padding.setTop(settings.paddingTop);
  16651. }
  16652. if (settings.paddingLeft) {
  16653. _this.padding.setLeft(settings.paddingLeft);
  16654. }
  16655. if (settings.paddingRight) {
  16656. _this.padding.setRight(settings.paddingRight);
  16657. }
  16658. if (settings.paddingBottom) {
  16659. _this.padding.setBottom(settings.paddingBottom);
  16660. }
  16661. if (settings.padding) {
  16662. _this.padding.fromString(settings.padding);
  16663. }
  16664. if (settings.paddingHAlignment) {
  16665. _this.paddingAlignment.horizontal = settings.paddingHAlignment;
  16666. }
  16667. if (settings.paddingVAlignment) {
  16668. _this.paddingAlignment.vertical = settings.paddingVAlignment;
  16669. }
  16670. if (settings.paddingAlignment) {
  16671. _this.paddingAlignment.fromString(settings.paddingAlignment);
  16672. }
  16673. if (settings.parent != null) {
  16674. _this._parent = settings.parent;
  16675. _this._hierarchyDepth = _this._parent._hierarchyDepth + 1;
  16676. }
  16677. return _this;
  16678. }
  16679. Object.defineProperty(UIElement, "enabledState", {
  16680. get: function () {
  16681. return UIElement._enableState;
  16682. },
  16683. enumerable: true,
  16684. configurable: true
  16685. });
  16686. Object.defineProperty(UIElement, "disabledState", {
  16687. get: function () {
  16688. return UIElement._disabledState;
  16689. },
  16690. enumerable: true,
  16691. configurable: true
  16692. });
  16693. Object.defineProperty(UIElement, "mouseOverState", {
  16694. get: function () {
  16695. return UIElement._mouseOverState;
  16696. },
  16697. enumerable: true,
  16698. configurable: true
  16699. });
  16700. UIElement.prototype.dispose = function () {
  16701. if (this.isDisposed) {
  16702. return false;
  16703. }
  16704. if (this._renderingTemplate) {
  16705. this._renderingTemplate.detach();
  16706. this._renderingTemplate = null;
  16707. }
  16708. _super.prototype.dispose.call(this);
  16709. // Don't set to null, it may upset somebody...
  16710. this.animations.splice(0);
  16711. return true;
  16712. };
  16713. /**
  16714. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  16715. * Look at Sprite2D for more information
  16716. */
  16717. UIElement.prototype.getAnimatables = function () {
  16718. return new Array();
  16719. };
  16720. // TODO
  16721. // PROPERTIES
  16722. // Style
  16723. // Id
  16724. // Parent/Children
  16725. // ActualWidth/Height, MinWidth/Height, MaxWidth/Height,
  16726. // Alignment/Margin
  16727. // Visibility, IsVisible
  16728. // IsEnabled (is false, control is disabled, no interaction and a specific render state)
  16729. // CacheMode of Visual Elements
  16730. // Focusable/IsFocused
  16731. // IsPointerCaptured, CapturePointer, IsPointerDirectlyOver, IsPointerOver. De-correlate mouse, stylus, touch?
  16732. // ContextMenu
  16733. // Cursor
  16734. // DesiredSize
  16735. // IsInputEnable ?
  16736. // Opacity, OpacityMask ?
  16737. // SnapToDevicePixels
  16738. // Tag
  16739. // ToolTip
  16740. // METHODS
  16741. // BringIntoView (for scrollable content, to move the scroll to bring the given element visible in the parent's area)
  16742. // Capture/ReleaseCapture (mouse, touch, stylus)
  16743. // Focus
  16744. // PointFrom/ToScreen to translate coordinates
  16745. // EVENTS
  16746. // ContextMenuOpening/Closing/Changed
  16747. // DragEnter/LeaveOver, Drop
  16748. // Got/LostFocus
  16749. // IsEnabledChanged
  16750. // IsPointerOver/DirectlyOverChanged
  16751. // IsVisibleChanged
  16752. // KeyDown/Up
  16753. // LayoutUpdated ?
  16754. // Pointer related events
  16755. // SizeChanged
  16756. // ToolTipOpening/Closing
  16757. UIElement.prototype.findById = function (id) {
  16758. if (this._id === id) {
  16759. return this;
  16760. }
  16761. var children = this._getChildren();
  16762. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  16763. var child = children_1[_i];
  16764. var r = child.findById(id);
  16765. if (r != null) {
  16766. return r;
  16767. }
  16768. }
  16769. };
  16770. Object.defineProperty(UIElement.prototype, "ownerWindow", {
  16771. get: function () {
  16772. return this._ownerWindow;
  16773. },
  16774. enumerable: true,
  16775. configurable: true
  16776. });
  16777. Object.defineProperty(UIElement.prototype, "style", {
  16778. get: function () {
  16779. if (!this.style) {
  16780. return GUIManager.DefaultStyleName;
  16781. }
  16782. return this._style.name;
  16783. },
  16784. set: function (value) {
  16785. if (this._style && (this._style.name === value)) {
  16786. return;
  16787. }
  16788. var newStyle = null;
  16789. if (value) {
  16790. newStyle = GUIManager.getStyle(BABYLON.Tools.getFullClassName(this), value);
  16791. if (!newStyle) {
  16792. throw Error("Couldn't find Style " + value + " for UIElement " + BABYLON.Tools.getFullClassName(this));
  16793. }
  16794. }
  16795. if (this._style) {
  16796. this._style.removeStyle(this);
  16797. }
  16798. if (newStyle) {
  16799. newStyle.applyStyle(this);
  16800. }
  16801. this._style = newStyle;
  16802. },
  16803. enumerable: true,
  16804. configurable: true
  16805. });
  16806. Object.defineProperty(UIElement.prototype, "id", {
  16807. /**
  16808. * A string that identifies the UIElement.
  16809. * The id is optional and there's possible collision with other UIElement's id as the uniqueness is not supported.
  16810. */
  16811. get: function () {
  16812. return this._id;
  16813. },
  16814. set: function (value) {
  16815. if (this._id === value) {
  16816. return;
  16817. }
  16818. this._id = value;
  16819. },
  16820. enumerable: true,
  16821. configurable: true
  16822. });
  16823. Object.defineProperty(UIElement.prototype, "uid", {
  16824. /**
  16825. * Return a unique id automatically generated.
  16826. * This property is mainly used for serialization to ensure a perfect way of identifying a UIElement
  16827. */
  16828. get: function () {
  16829. if (!this._uid) {
  16830. this._uid = BABYLON.Tools.RandomId();
  16831. }
  16832. return this._uid;
  16833. },
  16834. enumerable: true,
  16835. configurable: true
  16836. });
  16837. Object.defineProperty(UIElement.prototype, "hierarchyDepth", {
  16838. get: function () {
  16839. return this._hierarchyDepth;
  16840. },
  16841. enumerable: true,
  16842. configurable: true
  16843. });
  16844. Object.defineProperty(UIElement.prototype, "parent", {
  16845. get: function () {
  16846. return this._parent;
  16847. },
  16848. set: function (value) {
  16849. this._parent = value;
  16850. },
  16851. enumerable: true,
  16852. configurable: true
  16853. });
  16854. Object.defineProperty(UIElement.prototype, "width", {
  16855. get: function () {
  16856. return this._width;
  16857. },
  16858. set: function (value) {
  16859. this._width = value;
  16860. },
  16861. enumerable: true,
  16862. configurable: true
  16863. });
  16864. Object.defineProperty(UIElement.prototype, "height", {
  16865. get: function () {
  16866. return this._height;
  16867. },
  16868. set: function (value) {
  16869. this._height = value;
  16870. },
  16871. enumerable: true,
  16872. configurable: true
  16873. });
  16874. Object.defineProperty(UIElement.prototype, "minWidth", {
  16875. get: function () {
  16876. return this._minWidth;
  16877. },
  16878. set: function (value) {
  16879. this._minWidth = value;
  16880. },
  16881. enumerable: true,
  16882. configurable: true
  16883. });
  16884. Object.defineProperty(UIElement.prototype, "minHheight", {
  16885. get: function () {
  16886. return this._minHeight;
  16887. },
  16888. enumerable: true,
  16889. configurable: true
  16890. });
  16891. Object.defineProperty(UIElement.prototype, "minHeight", {
  16892. set: function (value) {
  16893. this._minHeight = value;
  16894. },
  16895. enumerable: true,
  16896. configurable: true
  16897. });
  16898. Object.defineProperty(UIElement.prototype, "maxWidth", {
  16899. get: function () {
  16900. return this._maxWidth;
  16901. },
  16902. set: function (value) {
  16903. this._maxWidth = value;
  16904. },
  16905. enumerable: true,
  16906. configurable: true
  16907. });
  16908. Object.defineProperty(UIElement.prototype, "maxHeight", {
  16909. get: function () {
  16910. return this._maxHeight;
  16911. },
  16912. set: function (value) {
  16913. this._maxHeight = value;
  16914. },
  16915. enumerable: true,
  16916. configurable: true
  16917. });
  16918. Object.defineProperty(UIElement.prototype, "actualWidth", {
  16919. get: function () {
  16920. return this._actualWidth;
  16921. },
  16922. set: function (value) {
  16923. this._actualWidth = value;
  16924. },
  16925. enumerable: true,
  16926. configurable: true
  16927. });
  16928. Object.defineProperty(UIElement.prototype, "actualHeight", {
  16929. get: function () {
  16930. return this._actualHeight;
  16931. },
  16932. set: function (value) {
  16933. this._actualHeight = value;
  16934. },
  16935. enumerable: true,
  16936. configurable: true
  16937. });
  16938. Object.defineProperty(UIElement.prototype, "margin", {
  16939. get: function () {
  16940. var _this = this;
  16941. if (!this._margin) {
  16942. this._margin = new BABYLON.PrimitiveThickness(function () {
  16943. if (!_this.parent) {
  16944. return null;
  16945. }
  16946. return _this.parent.margin;
  16947. });
  16948. }
  16949. return this._margin;
  16950. },
  16951. set: function (value) {
  16952. this.margin.copyFrom(value);
  16953. },
  16954. enumerable: true,
  16955. configurable: true
  16956. });
  16957. Object.defineProperty(UIElement.prototype, "_hasMargin", {
  16958. get: function () {
  16959. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  16960. },
  16961. enumerable: true,
  16962. configurable: true
  16963. });
  16964. Object.defineProperty(UIElement.prototype, "padding", {
  16965. get: function () {
  16966. var _this = this;
  16967. if (!this._padding) {
  16968. this._padding = new BABYLON.PrimitiveThickness(function () {
  16969. if (!_this.parent) {
  16970. return null;
  16971. }
  16972. return _this.parent.padding;
  16973. });
  16974. }
  16975. return this._padding;
  16976. },
  16977. set: function (value) {
  16978. this.padding.copyFrom(value);
  16979. },
  16980. enumerable: true,
  16981. configurable: true
  16982. });
  16983. Object.defineProperty(UIElement.prototype, "_hasPadding", {
  16984. get: function () {
  16985. return this._padding !== null && !this._padding.isDefault;
  16986. },
  16987. enumerable: true,
  16988. configurable: true
  16989. });
  16990. Object.defineProperty(UIElement.prototype, "marginAlignment", {
  16991. get: function () {
  16992. if (!this._marginAlignment) {
  16993. this._marginAlignment = new BABYLON.PrimitiveAlignment();
  16994. }
  16995. return this._marginAlignment;
  16996. },
  16997. set: function (value) {
  16998. this.marginAlignment.copyFrom(value);
  16999. },
  17000. enumerable: true,
  17001. configurable: true
  17002. });
  17003. Object.defineProperty(UIElement.prototype, "_hasMarginAlignment", {
  17004. /**
  17005. * Check if there a marginAlignment specified (non null and not default)
  17006. */
  17007. get: function () {
  17008. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  17009. },
  17010. enumerable: true,
  17011. configurable: true
  17012. });
  17013. Object.defineProperty(UIElement.prototype, "paddingAlignment", {
  17014. get: function () {
  17015. if (!this._paddingAlignment) {
  17016. this._paddingAlignment = new BABYLON.PrimitiveAlignment();
  17017. }
  17018. return this._paddingAlignment;
  17019. },
  17020. set: function (value) {
  17021. this.paddingAlignment.copyFrom(value);
  17022. },
  17023. enumerable: true,
  17024. configurable: true
  17025. });
  17026. Object.defineProperty(UIElement.prototype, "_hasPaddingAlignment", {
  17027. /**
  17028. * Check if there a marginAlignment specified (non null and not default)
  17029. */
  17030. get: function () {
  17031. return (this._paddingAlignment !== null && !this._paddingAlignment.isDefault);
  17032. },
  17033. enumerable: true,
  17034. configurable: true
  17035. });
  17036. Object.defineProperty(UIElement.prototype, "isVisible", {
  17037. get: function () {
  17038. return this._isFlagSet(UIElement.flagIsVisible);
  17039. },
  17040. set: function (value) {
  17041. if (this.isVisible === value) {
  17042. return;
  17043. }
  17044. this._visualPlaceholder.levelVisible = value;
  17045. this._changeFlags(UIElement.flagIsVisible, value);
  17046. },
  17047. enumerable: true,
  17048. configurable: true
  17049. });
  17050. Object.defineProperty(UIElement.prototype, "isEnabled", {
  17051. get: function () {
  17052. return this._isFlagSet(UIElement.flagIsEnabled);
  17053. },
  17054. set: function (value) {
  17055. this._changeFlags(UIElement.flagIsEnabled, value);
  17056. },
  17057. enumerable: true,
  17058. configurable: true
  17059. });
  17060. Object.defineProperty(UIElement.prototype, "isFocused", {
  17061. get: function () {
  17062. return this._isFlagSet(UIElement.flagIsFocus);
  17063. },
  17064. set: function (value) {
  17065. // If the UIElement doesn't accept focus, set it on its parent
  17066. if (!this.isFocusable) {
  17067. var p = this.parent;
  17068. if (!p) {
  17069. return;
  17070. }
  17071. p.isFocused = value;
  17072. }
  17073. // If the focus is being set, notify the Focus Manager
  17074. if (value) {
  17075. this.ownerWindow.focusManager.setFocusOn(this, this.getFocusScope());
  17076. }
  17077. this._changeFlags(UIElement.flagIsFocus, value);
  17078. },
  17079. enumerable: true,
  17080. configurable: true
  17081. });
  17082. Object.defineProperty(UIElement.prototype, "isMouseOver", {
  17083. get: function () {
  17084. return this._isFlagSet(UIElement.flagIsMouseOver);
  17085. },
  17086. set: function (value) {
  17087. this._changeFlags(UIElement.flagIsMouseOver, value);
  17088. },
  17089. enumerable: true,
  17090. configurable: true
  17091. });
  17092. Object.defineProperty(UIElement.prototype, "isFocusScope", {
  17093. get: function () {
  17094. return this._isFlagSet(UIElement.flagIsFocusScope);
  17095. },
  17096. set: function (value) {
  17097. this._changeFlags(UIElement.flagIsFocusScope, value);
  17098. },
  17099. enumerable: true,
  17100. configurable: true
  17101. });
  17102. Object.defineProperty(UIElement.prototype, "isFocusable", {
  17103. get: function () {
  17104. return this._isFlagSet(UIElement.flagIsFocusable);
  17105. },
  17106. set: function (value) {
  17107. this._changeFlags(UIElement.flagIsFocusable, value);
  17108. },
  17109. enumerable: true,
  17110. configurable: true
  17111. });
  17112. // 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)
  17113. UIElement.prototype.getFocusScope = function () {
  17114. if (this.isFocusScope) {
  17115. return this;
  17116. }
  17117. var p = this.parent;
  17118. if (!p) {
  17119. return null;
  17120. }
  17121. return p.getFocusScope();
  17122. };
  17123. /**
  17124. * Check if a given flag is set
  17125. * @param flag the flag value
  17126. * @return true if set, false otherwise
  17127. */
  17128. UIElement.prototype._isFlagSet = function (flag) {
  17129. return (this._flags & flag) !== 0;
  17130. };
  17131. /**
  17132. * Check if all given flags are set
  17133. * @param flags the flags ORed
  17134. * @return true if all the flags are set, false otherwise
  17135. */
  17136. UIElement.prototype._areAllFlagsSet = function (flags) {
  17137. return (this._flags & flags) === flags;
  17138. };
  17139. /**
  17140. * Check if at least one flag of the given flags is set
  17141. * @param flags the flags ORed
  17142. * @return true if at least one flag is set, false otherwise
  17143. */
  17144. UIElement.prototype._areSomeFlagsSet = function (flags) {
  17145. return (this._flags & flags) !== 0;
  17146. };
  17147. /**
  17148. * Clear the given flags
  17149. * @param flags the flags to clear
  17150. */
  17151. UIElement.prototype._clearFlags = function (flags) {
  17152. this._flags &= ~flags;
  17153. };
  17154. /**
  17155. * Set the given flags to true state
  17156. * @param flags the flags ORed to set
  17157. * @return the flags state before this call
  17158. */
  17159. UIElement.prototype._setFlags = function (flags) {
  17160. var cur = this._flags;
  17161. this._flags |= flags;
  17162. return cur;
  17163. };
  17164. /**
  17165. * Change the state of the given flags
  17166. * @param flags the flags ORed to change
  17167. * @param state true to set them, false to clear them
  17168. */
  17169. UIElement.prototype._changeFlags = function (flags, state) {
  17170. if (state) {
  17171. this._flags |= flags;
  17172. }
  17173. else {
  17174. this._flags &= ~flags;
  17175. }
  17176. };
  17177. UIElement.prototype._assignTemplate = function (templateName) {
  17178. if (!templateName) {
  17179. templateName = GUIManager.DefaultTemplateName;
  17180. }
  17181. var className = BABYLON.Tools.getFullClassName(this);
  17182. if (!className) {
  17183. throw Error("Couldn't access class name of this UIElement, you have to decorate the type with the className decorator");
  17184. }
  17185. var factory = GUIManager.getRenderingTemplate(className, templateName);
  17186. if (!factory) {
  17187. throw Error("Couldn't get the renderingTemplate " + templateName + " of class " + className);
  17188. }
  17189. this._renderingTemplateName = templateName;
  17190. this._renderingTemplate = factory();
  17191. this._renderingTemplate.attach(this);
  17192. };
  17193. UIElement.prototype._createVisualTree = function () {
  17194. var parentPrim = this.ownerWindow.canvas;
  17195. if (this.parent) {
  17196. parentPrim = this.parent.visualChildrenPlaceholder;
  17197. }
  17198. if (!this._renderingTemplate) {
  17199. this._assignTemplate(this._renderingTemplateName);
  17200. }
  17201. this._visualPlaceholder = new BABYLON.Group2D({ parent: parentPrim, id: "GUI " + BABYLON.Tools.getClassName(this) + " RootGroup of " + this.id });
  17202. var p = this._visualPlaceholder;
  17203. p.addExternalData("_GUIOwnerElement_", this);
  17204. p.dataSource = this;
  17205. p.createSimpleDataBinding(BABYLON.Prim2DBase.widthProperty, "width", BABYLON.DataBinding.MODE_ONEWAY);
  17206. p.createSimpleDataBinding(BABYLON.Prim2DBase.heightProperty, "height", BABYLON.DataBinding.MODE_ONEWAY);
  17207. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualWidthProperty, "actualWidth", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  17208. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualHeightProperty, "actualHeight", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  17209. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "margin", BABYLON.DataBinding.MODE_ONEWAY);
  17210. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "marginAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  17211. this.createVisualTree();
  17212. };
  17213. UIElement.prototype._patchUIElement = function (ownerWindow, parent) {
  17214. if (ownerWindow) {
  17215. if (!this._ownerWindow) {
  17216. ownerWindow._registerVisualToBuild(this);
  17217. }
  17218. this._ownerWindow = ownerWindow;
  17219. }
  17220. this._parent = parent;
  17221. if (parent) {
  17222. this._hierarchyDepth = parent.hierarchyDepth + 1;
  17223. }
  17224. var children = this._getChildren();
  17225. if (children) {
  17226. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  17227. var curChild = children_2[_i];
  17228. curChild._patchUIElement(ownerWindow, this);
  17229. }
  17230. }
  17231. };
  17232. // 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.
  17233. UIElement.prototype._getDataSource = function () {
  17234. var levelDS = _super.prototype._getDataSource.call(this);
  17235. if (levelDS != null) {
  17236. return levelDS;
  17237. }
  17238. var p = this.parent;
  17239. if (p != null) {
  17240. return p.dataSource;
  17241. }
  17242. return null;
  17243. };
  17244. UIElement.prototype.createVisualTree = function () {
  17245. var res = this._renderingTemplate.createVisualTree(this, this._visualPlaceholder);
  17246. this._visualTemplateRoot = res.root;
  17247. this._visualChildrenPlaceholder = res.contentPlaceholder;
  17248. };
  17249. Object.defineProperty(UIElement.prototype, "visualPlaceholder", {
  17250. get: function () {
  17251. return this._visualPlaceholder;
  17252. },
  17253. enumerable: true,
  17254. configurable: true
  17255. });
  17256. Object.defineProperty(UIElement.prototype, "visualTemplateRoot", {
  17257. get: function () {
  17258. return this._visualTemplateRoot;
  17259. },
  17260. enumerable: true,
  17261. configurable: true
  17262. });
  17263. Object.defineProperty(UIElement.prototype, "visualChildrenPlaceholder", {
  17264. get: function () {
  17265. return this._visualChildrenPlaceholder;
  17266. },
  17267. enumerable: true,
  17268. configurable: true
  17269. });
  17270. Object.defineProperty(UIElement.prototype, "_position", {
  17271. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  17272. ,
  17273. enumerable: true,
  17274. configurable: true
  17275. });
  17276. return UIElement;
  17277. }(BABYLON.SmartPropertyBase));
  17278. UIElement.UIELEMENT_PROPCOUNT = 16;
  17279. UIElement.flagVisualToBuild = 0x0000001;
  17280. UIElement.flagIsVisible = 0x0000002;
  17281. UIElement.flagIsFocus = 0x0000004;
  17282. UIElement.flagIsFocusScope = 0x0000008;
  17283. UIElement.flagIsFocusable = 0x0000010;
  17284. UIElement.flagIsEnabled = 0x0000020;
  17285. UIElement.flagIsMouseOver = 0x0000040;
  17286. UIElement._enableState = "Enabled";
  17287. UIElement._disabledState = "Disabled";
  17288. UIElement._mouseOverState = "MouseOver";
  17289. __decorate([
  17290. BABYLON.dependencyProperty(0, function (pi) { return UIElement.parentProperty = pi; })
  17291. ], UIElement.prototype, "parent", null);
  17292. __decorate([
  17293. BABYLON.dependencyProperty(1, function (pi) { return UIElement.widthProperty = pi; })
  17294. ], UIElement.prototype, "width", null);
  17295. __decorate([
  17296. BABYLON.dependencyProperty(2, function (pi) { return UIElement.heightProperty = pi; })
  17297. ], UIElement.prototype, "height", null);
  17298. __decorate([
  17299. BABYLON.dependencyProperty(3, function (pi) { return UIElement.minWidthProperty = pi; })
  17300. ], UIElement.prototype, "minWidth", null);
  17301. __decorate([
  17302. BABYLON.dependencyProperty(4, function (pi) { return UIElement.minHeightProperty = pi; })
  17303. ], UIElement.prototype, "minHheight", null);
  17304. __decorate([
  17305. BABYLON.dependencyProperty(5, function (pi) { return UIElement.maxWidthProperty = pi; })
  17306. ], UIElement.prototype, "maxWidth", null);
  17307. __decorate([
  17308. BABYLON.dependencyProperty(6, function (pi) { return UIElement.maxHeightProperty = pi; })
  17309. ], UIElement.prototype, "maxHeight", null);
  17310. __decorate([
  17311. BABYLON.dependencyProperty(7, function (pi) { return UIElement.actualWidthProperty = pi; })
  17312. ], UIElement.prototype, "actualWidth", null);
  17313. __decorate([
  17314. BABYLON.dependencyProperty(8, function (pi) { return UIElement.actualHeightProperty = pi; })
  17315. ], UIElement.prototype, "actualHeight", null);
  17316. __decorate([
  17317. BABYLON.dynamicLevelProperty(9, function (pi) { return UIElement.marginProperty = pi; })
  17318. ], UIElement.prototype, "margin", null);
  17319. __decorate([
  17320. BABYLON.dynamicLevelProperty(10, function (pi) { return UIElement.paddingProperty = pi; })
  17321. ], UIElement.prototype, "padding", null);
  17322. __decorate([
  17323. BABYLON.dynamicLevelProperty(11, function (pi) { return UIElement.marginAlignmentProperty = pi; })
  17324. ], UIElement.prototype, "marginAlignment", null);
  17325. __decorate([
  17326. BABYLON.dynamicLevelProperty(12, function (pi) { return UIElement.paddingAlignmentProperty = pi; })
  17327. ], UIElement.prototype, "paddingAlignment", null);
  17328. __decorate([
  17329. BABYLON.dynamicLevelProperty(13, function (pi) { return UIElement.isEnabledProperty = pi; })
  17330. ], UIElement.prototype, "isEnabled", null);
  17331. __decorate([
  17332. BABYLON.dynamicLevelProperty(14, function (pi) { return UIElement.isFocusedProperty = pi; })
  17333. ], UIElement.prototype, "isFocused", null);
  17334. __decorate([
  17335. BABYLON.dynamicLevelProperty(15, function (pi) { return UIElement.isMouseOverProperty = pi; })
  17336. ], UIElement.prototype, "isMouseOver", null);
  17337. BABYLON.UIElement = UIElement;
  17338. var UIElementStyle = (function () {
  17339. function UIElementStyle() {
  17340. }
  17341. Object.defineProperty(UIElementStyle.prototype, "name", {
  17342. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  17343. ,
  17344. enumerable: true,
  17345. configurable: true
  17346. });
  17347. return UIElementStyle;
  17348. }());
  17349. BABYLON.UIElementStyle = UIElementStyle;
  17350. var GUIManager = (function () {
  17351. function GUIManager() {
  17352. }
  17353. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17354. // DATA TEMPLATE MANAGER
  17355. GUIManager.registerDataTemplate = function (className, factory) {
  17356. };
  17357. // DATA TEMPLATE MANAGER
  17358. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17359. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17360. // STYLE MANAGER
  17361. GUIManager.getStyle = function (uiElType, styleName) {
  17362. var styles = GUIManager.stylesByUIElement.get(uiElType);
  17363. if (!styles) {
  17364. throw Error("The type " + uiElType + " is unknown, no style were registered for it.");
  17365. }
  17366. var style = styles.get(styleName);
  17367. if (!style) {
  17368. throw Error("Couldn't find Template " + styleName + " of UIElement type " + uiElType);
  17369. }
  17370. return style;
  17371. };
  17372. GUIManager.registerStyle = function (uiElType, templateName, style) {
  17373. var templates = GUIManager.stylesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  17374. if (templates.contains(templateName)) {
  17375. templates[templateName] = style;
  17376. }
  17377. else {
  17378. templates.add(templateName, style);
  17379. }
  17380. };
  17381. Object.defineProperty(GUIManager, "DefaultStyleName", {
  17382. get: function () {
  17383. return GUIManager._defaultStyleName;
  17384. },
  17385. set: function (value) {
  17386. GUIManager._defaultStyleName = value;
  17387. },
  17388. enumerable: true,
  17389. configurable: true
  17390. });
  17391. // STYLE MANAGER
  17392. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17393. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17394. // RENDERING TEMPLATE MANAGER
  17395. GUIManager.getRenderingTemplate = function (uiElType, templateName) {
  17396. var templates = GUIManager.renderingTemplatesByUIElement.get(uiElType);
  17397. if (!templates) {
  17398. throw Error("The type " + uiElType + " is unknown, no Rendering Template were registered for it.");
  17399. }
  17400. var templateFactory = templates.get(templateName);
  17401. if (!templateFactory) {
  17402. throw Error("Couldn't find Template " + templateName + " of UI Element type " + uiElType);
  17403. }
  17404. return templateFactory;
  17405. };
  17406. GUIManager.registerRenderingTemplate = function (uiElType, templateName, factory) {
  17407. var templates = GUIManager.renderingTemplatesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  17408. if (templates.contains(templateName)) {
  17409. templates[templateName] = factory;
  17410. }
  17411. else {
  17412. templates.add(templateName, factory);
  17413. }
  17414. };
  17415. Object.defineProperty(GUIManager, "DefaultTemplateName", {
  17416. get: function () {
  17417. return GUIManager._defaultTemplateName;
  17418. },
  17419. set: function (value) {
  17420. GUIManager._defaultTemplateName = value;
  17421. },
  17422. enumerable: true,
  17423. configurable: true
  17424. });
  17425. return GUIManager;
  17426. }());
  17427. GUIManager.stylesByUIElement = new BABYLON.StringDictionary();
  17428. GUIManager.renderingTemplatesByUIElement = new BABYLON.StringDictionary();
  17429. // RENDERING TEMPLATE MANAGER
  17430. /////////////////////////////////////////////////////////////////////////////////////////////////////
  17431. GUIManager._defaultTemplateName = "Default";
  17432. GUIManager._defaultStyleName = "Default";
  17433. BABYLON.GUIManager = GUIManager;
  17434. var UIElementRenderingTemplateBase = (function () {
  17435. function UIElementRenderingTemplateBase() {
  17436. }
  17437. UIElementRenderingTemplateBase.prototype.attach = function (owner) {
  17438. this._owner = owner;
  17439. };
  17440. UIElementRenderingTemplateBase.prototype.detach = function () {
  17441. };
  17442. Object.defineProperty(UIElementRenderingTemplateBase.prototype, "owner", {
  17443. get: function () {
  17444. return this._owner;
  17445. },
  17446. enumerable: true,
  17447. configurable: true
  17448. });
  17449. return UIElementRenderingTemplateBase;
  17450. }());
  17451. BABYLON.UIElementRenderingTemplateBase = UIElementRenderingTemplateBase;
  17452. function registerWindowRenderingTemplate(uiElType, templateName, factory) {
  17453. return function () {
  17454. GUIManager.registerRenderingTemplate(uiElType, templateName, factory);
  17455. };
  17456. }
  17457. BABYLON.registerWindowRenderingTemplate = registerWindowRenderingTemplate;
  17458. })(BABYLON || (BABYLON = {}));
  17459. var __extends = (this && this.__extends) || function (d, b) {
  17460. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17461. function __() { this.constructor = d; }
  17462. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17463. };
  17464. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17465. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17466. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17467. 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;
  17468. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17469. };
  17470. var BABYLON;
  17471. (function (BABYLON) {
  17472. var StackPanel = StackPanel_1 = (function (_super) {
  17473. __extends(StackPanel, _super);
  17474. function StackPanel(settings) {
  17475. var _this = this;
  17476. if (!settings) {
  17477. settings = {};
  17478. }
  17479. _this = _super.call(this, settings) || this;
  17480. _this.isOrientationHorizontal = (settings.isOrientationHorizontal == null) ? true : settings.isOrientationHorizontal;
  17481. _this._children = new Array();
  17482. if (settings.children != null) {
  17483. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  17484. var child = _a[_i];
  17485. _this._children.push(child);
  17486. }
  17487. }
  17488. return _this;
  17489. }
  17490. Object.defineProperty(StackPanel.prototype, "isOrientationHorizontal", {
  17491. get: function () {
  17492. return this._isOrientationHorizontal;
  17493. },
  17494. set: function (value) {
  17495. this._isOrientationHorizontal = value;
  17496. },
  17497. enumerable: true,
  17498. configurable: true
  17499. });
  17500. StackPanel.prototype.createVisualTree = function () {
  17501. _super.prototype.createVisualTree.call(this);
  17502. // A StackPanel Control has a Group2D, child of the visualPlaceHolder, which is the Children placeholder.
  17503. // The Children UIElement Tree will be create inside this placeholder.
  17504. this._childrenPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "StackPanel Children Placeholder of " + this.id });
  17505. var p = this._childrenPlaceholder;
  17506. p.layoutEngine = this.isOrientationHorizontal ? BABYLON.StackPanelLayoutEngine.Horizontal : BABYLON.StackPanelLayoutEngine.Vertical;
  17507. // 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.
  17508. p.dataSource = this;
  17509. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  17510. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  17511. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  17512. // But it's not the case for a StackPanel, the placeholder of UIElement Children (the content)
  17513. this._visualChildrenPlaceholder = this._childrenPlaceholder;
  17514. };
  17515. Object.defineProperty(StackPanel.prototype, "children", {
  17516. get: function () {
  17517. return this._children;
  17518. },
  17519. enumerable: true,
  17520. configurable: true
  17521. });
  17522. StackPanel.prototype._getChildren = function () {
  17523. return this.children;
  17524. };
  17525. return StackPanel;
  17526. }(BABYLON.UIElement));
  17527. StackPanel.STACKPANEL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3;
  17528. __decorate([
  17529. BABYLON.dependencyProperty(StackPanel_1.STACKPANEL_PROPCOUNT + 0, function (pi) { return StackPanel_1.orientationHorizontalProperty = pi; })
  17530. ], StackPanel.prototype, "isOrientationHorizontal", null);
  17531. StackPanel = StackPanel_1 = __decorate([
  17532. BABYLON.className("StackPanel", "BABYLON")
  17533. ], StackPanel);
  17534. BABYLON.StackPanel = StackPanel;
  17535. var DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = (function (_super) {
  17536. __extends(DefaultStackPanelRenderingTemplate, _super);
  17537. function DefaultStackPanelRenderingTemplate() {
  17538. return _super !== null && _super.apply(this, arguments) || this;
  17539. }
  17540. DefaultStackPanelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  17541. return { root: visualPlaceholder, contentPlaceholder: visualPlaceholder };
  17542. };
  17543. DefaultStackPanelRenderingTemplate.prototype.attach = function (owner) {
  17544. _super.prototype.attach.call(this, owner);
  17545. };
  17546. return DefaultStackPanelRenderingTemplate;
  17547. }(BABYLON.UIElementRenderingTemplateBase));
  17548. DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = __decorate([
  17549. BABYLON.registerWindowRenderingTemplate("BABYLON.StackPanel", "Default", function () { return new DefaultStackPanelRenderingTemplate_1(); })
  17550. ], DefaultStackPanelRenderingTemplate);
  17551. BABYLON.DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate;
  17552. var StackPanel_1, DefaultStackPanelRenderingTemplate_1;
  17553. })(BABYLON || (BABYLON = {}));
  17554. var __extends = (this && this.__extends) || function (d, b) {
  17555. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17556. function __() { this.constructor = d; }
  17557. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17558. };
  17559. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17560. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17561. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17562. 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;
  17563. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17564. };
  17565. var BABYLON;
  17566. (function (BABYLON) {
  17567. var Control = Control_1 = (function (_super) {
  17568. __extends(Control, _super);
  17569. function Control(settings) {
  17570. return _super.call(this, settings) || this;
  17571. }
  17572. Object.defineProperty(Control.prototype, "background", {
  17573. get: function () {
  17574. if (!this._background) {
  17575. this._background = new BABYLON.ObservableStringDictionary(false);
  17576. }
  17577. return this._background;
  17578. },
  17579. set: function (value) {
  17580. this.background.copyFrom(value);
  17581. },
  17582. enumerable: true,
  17583. configurable: true
  17584. });
  17585. Object.defineProperty(Control.prototype, "border", {
  17586. get: function () {
  17587. return this._border;
  17588. },
  17589. set: function (value) {
  17590. this._border = value;
  17591. },
  17592. enumerable: true,
  17593. configurable: true
  17594. });
  17595. Object.defineProperty(Control.prototype, "borderThickness", {
  17596. get: function () {
  17597. return this._borderThickness;
  17598. },
  17599. set: function (value) {
  17600. this._borderThickness = value;
  17601. },
  17602. enumerable: true,
  17603. configurable: true
  17604. });
  17605. Object.defineProperty(Control.prototype, "fontName", {
  17606. get: function () {
  17607. return this._fontName;
  17608. },
  17609. set: function (value) {
  17610. this._fontName = value;
  17611. },
  17612. enumerable: true,
  17613. configurable: true
  17614. });
  17615. Object.defineProperty(Control.prototype, "foreground", {
  17616. get: function () {
  17617. return this._foreground;
  17618. },
  17619. set: function (value) {
  17620. this._foreground = value;
  17621. },
  17622. enumerable: true,
  17623. configurable: true
  17624. });
  17625. return Control;
  17626. }(BABYLON.UIElement));
  17627. Control.CONTROL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 5;
  17628. __decorate([
  17629. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 0, function (pi) { return Control_1.backgroundProperty = pi; })
  17630. ], Control.prototype, "background", null);
  17631. __decorate([
  17632. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 1, function (pi) { return Control_1.borderProperty = pi; })
  17633. ], Control.prototype, "border", null);
  17634. __decorate([
  17635. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 2, function (pi) { return Control_1.borderThicknessProperty = pi; })
  17636. ], Control.prototype, "borderThickness", null);
  17637. __decorate([
  17638. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3, function (pi) { return Control_1.fontNameProperty = pi; })
  17639. ], Control.prototype, "fontName", null);
  17640. __decorate([
  17641. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 4, function (pi) { return Control_1.foregroundProperty = pi; })
  17642. ], Control.prototype, "foreground", null);
  17643. Control = Control_1 = __decorate([
  17644. BABYLON.className("Control", "BABYLON")
  17645. ], Control);
  17646. BABYLON.Control = Control;
  17647. var Control_1;
  17648. })(BABYLON || (BABYLON = {}));
  17649. var __extends = (this && this.__extends) || function (d, b) {
  17650. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17651. function __() { this.constructor = d; }
  17652. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17653. };
  17654. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17655. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17656. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17657. 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;
  17658. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17659. };
  17660. var BABYLON;
  17661. (function (BABYLON) {
  17662. var ContentControl = ContentControl_1 = (function (_super) {
  17663. __extends(ContentControl, _super);
  17664. function ContentControl(settings) {
  17665. var _this = this;
  17666. if (!settings) {
  17667. settings = {};
  17668. }
  17669. _this = _super.call(this, settings) || this;
  17670. if (settings.content != null) {
  17671. _this._content = settings.content;
  17672. }
  17673. return _this;
  17674. }
  17675. ContentControl.prototype.dispose = function () {
  17676. if (this.isDisposed) {
  17677. return false;
  17678. }
  17679. if (this.content && this.content.dispose) {
  17680. this.content.dispose();
  17681. this.content = null;
  17682. }
  17683. if (this.__contentUIElement) {
  17684. this.__contentUIElement.dispose();
  17685. this.__contentUIElement = null;
  17686. }
  17687. _super.prototype.dispose.call(this);
  17688. return true;
  17689. };
  17690. Object.defineProperty(ContentControl.prototype, "content", {
  17691. get: function () {
  17692. return this._content;
  17693. },
  17694. set: function (value) {
  17695. this._content = value;
  17696. },
  17697. enumerable: true,
  17698. configurable: true
  17699. });
  17700. Object.defineProperty(ContentControl.prototype, "_contentUIElement", {
  17701. get: function () {
  17702. if (!this.__contentUIElement) {
  17703. this._buildContentUIElement();
  17704. }
  17705. return this.__contentUIElement;
  17706. },
  17707. enumerable: true,
  17708. configurable: true
  17709. });
  17710. ContentControl.prototype._createVisualTree = function () {
  17711. // Base implementation will create the Group2D for the Visual Placeholder and its Visual Tree
  17712. _super.prototype._createVisualTree.call(this);
  17713. // A Content Control has a Group2D, child of the visualPlaceHolder, which is the Content placeholder.
  17714. // The Content UIElement Tree will be create inside this placeholder.
  17715. this._contentPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "ContentControl Content Placeholder of " + this.id });
  17716. var p = this._contentPlaceholder;
  17717. // 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.
  17718. p.dataSource = this;
  17719. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  17720. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  17721. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  17722. // But it's not the case for a ContentControl, the placeholder of UIElement Children (the content)
  17723. this._visualChildrenPlaceholder = this._contentPlaceholder;
  17724. };
  17725. ContentControl.prototype._buildContentUIElement = function () {
  17726. var c = this._content;
  17727. this.__contentUIElement = null;
  17728. // Already a UIElement
  17729. if (c instanceof BABYLON.UIElement) {
  17730. this.__contentUIElement = c;
  17731. }
  17732. else if ((typeof c === "string") || (typeof c === "boolean") || (typeof c === "number")) {
  17733. var l = new BABYLON.Label({ parent: this, id: "Content of " + this.id });
  17734. var binding = new BABYLON.DataBinding();
  17735. binding.propertyPathName = "content";
  17736. binding.stringFormat = function (v) { return "" + v; };
  17737. binding.dataSource = this;
  17738. l.createDataBinding(BABYLON.Label.textProperty, binding);
  17739. this.__contentUIElement = l;
  17740. }
  17741. else {
  17742. }
  17743. if (this.__contentUIElement) {
  17744. this.__contentUIElement._patchUIElement(this.ownerWindow, this);
  17745. }
  17746. };
  17747. ContentControl.prototype._getChildren = function () {
  17748. var children = new Array();
  17749. if (this.content) {
  17750. children.push(this._contentUIElement);
  17751. }
  17752. return children;
  17753. };
  17754. return ContentControl;
  17755. }(BABYLON.Control));
  17756. ContentControl.CONTENTCONTROL_PROPCOUNT = BABYLON.Control.CONTROL_PROPCOUNT + 2;
  17757. __decorate([
  17758. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return ContentControl_1.contentProperty = pi; })
  17759. ], ContentControl.prototype, "content", null);
  17760. ContentControl = ContentControl_1 = __decorate([
  17761. BABYLON.className("ContentControl", "BABYLON")
  17762. ], ContentControl);
  17763. BABYLON.ContentControl = ContentControl;
  17764. var ContentControl_1;
  17765. })(BABYLON || (BABYLON = {}));
  17766. var __extends = (this && this.__extends) || function (d, b) {
  17767. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17768. function __() { this.constructor = d; }
  17769. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17770. };
  17771. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  17772. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  17773. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  17774. 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;
  17775. return c > 3 && r && Object.defineProperty(target, key, r), r;
  17776. };
  17777. var BABYLON;
  17778. (function (BABYLON) {
  17779. var FocusScopeData = (function () {
  17780. function FocusScopeData(focusScope) {
  17781. this.focusScope = focusScope;
  17782. this.focusedElement = null;
  17783. }
  17784. return FocusScopeData;
  17785. }());
  17786. var FocusManager = (function () {
  17787. function FocusManager() {
  17788. this._focusScopes = new BABYLON.StringDictionary();
  17789. this._rootScope = new FocusScopeData(null);
  17790. this._activeScope = null;
  17791. }
  17792. FocusManager.prototype.setFocusOn = function (el, focusScope) {
  17793. var fsd = (focusScope != null) ? this._focusScopes.getOrAddWithFactory(focusScope.uid, function (k) { return new FocusScopeData(focusScope); }) : this._rootScope;
  17794. if (fsd.focusedElement !== el) {
  17795. // Remove focus from current
  17796. if (fsd.focusedElement) {
  17797. fsd.focusedElement.isFocused = false;
  17798. }
  17799. fsd.focusedElement = el;
  17800. }
  17801. if (this._activeScope !== fsd) {
  17802. this._activeScope = fsd;
  17803. }
  17804. };
  17805. return FocusManager;
  17806. }());
  17807. BABYLON.FocusManager = FocusManager;
  17808. var GUISceneData = (function () {
  17809. function GUISceneData(scene) {
  17810. this.scene = scene;
  17811. this.screenSpaceCanvas = new BABYLON.ScreenSpaceCanvas2D(scene, { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE });
  17812. this.focusManager = new FocusManager();
  17813. }
  17814. return GUISceneData;
  17815. }());
  17816. var Window = Window_1 = (function (_super) {
  17817. __extends(Window, _super);
  17818. function Window(scene, settings) {
  17819. var _this = this;
  17820. if (!settings) {
  17821. settings = {};
  17822. }
  17823. _this = _super.call(this, settings) || this;
  17824. // Per default a Window is focus scope
  17825. _this.isFocusScope = true;
  17826. _this.isActive = false;
  17827. if (!_this._UIElementVisualToBuildList) {
  17828. _this._UIElementVisualToBuildList = new Array();
  17829. }
  17830. // Patch the owner and also the parent property through the whole tree
  17831. _this._patchUIElement(_this, null);
  17832. // Screen Space UI
  17833. if (!settings.worldPosition && !settings.worldRotation) {
  17834. _this._sceneData = Window_1.getSceneData(scene);
  17835. _this._canvas = _this._sceneData.screenSpaceCanvas;
  17836. _this._isWorldSpaceCanvas = false;
  17837. _this._left = (settings.left != null) ? settings.left : 0;
  17838. _this._bottom = (settings.bottom != null) ? settings.bottom : 0;
  17839. }
  17840. else {
  17841. var w = (settings.width == null) ? 100 : settings.width;
  17842. var h = (settings.height == null) ? 100 : settings.height;
  17843. var wpos = (settings.worldPosition == null) ? BABYLON.Vector3.Zero() : settings.worldPosition;
  17844. var wrot = (settings.worldRotation == null) ? BABYLON.Quaternion.Identity() : settings.worldRotation;
  17845. _this._canvas = new BABYLON.WorldSpaceCanvas2D(scene, new BABYLON.Size(w, h), { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE, worldPosition: wpos, worldRotation: wrot });
  17846. _this._isWorldSpaceCanvas = true;
  17847. }
  17848. _this._renderObserver = _this._canvas.renderObservable.add(function (e, s) { return _this._canvasPreRender(); }, BABYLON.Canvas2D.RENDEROBSERVABLE_PRE);
  17849. _this._disposeObserver = _this._canvas.disposeObservable.add(function (e, s) { return _this._canvasDisposed(); });
  17850. _this._canvas.propertyChanged.add(function (e, s) {
  17851. if (e.propertyName === "overPrim") {
  17852. _this._overPrimChanged(e.oldValue, e.newValue);
  17853. }
  17854. });
  17855. _this._mouseOverUIElement = null;
  17856. return _this;
  17857. }
  17858. Object.defineProperty(Window.prototype, "canvas", {
  17859. get: function () {
  17860. return this._canvas;
  17861. },
  17862. enumerable: true,
  17863. configurable: true
  17864. });
  17865. Object.defineProperty(Window.prototype, "left", {
  17866. get: function () {
  17867. return this._left;
  17868. },
  17869. set: function (value) {
  17870. var old = new BABYLON.Vector2(this._left, this._bottom);
  17871. this._left = value;
  17872. this.onPropertyChanged("_position", old, this._position);
  17873. },
  17874. enumerable: true,
  17875. configurable: true
  17876. });
  17877. Object.defineProperty(Window.prototype, "bottom", {
  17878. get: function () {
  17879. return this._bottom;
  17880. },
  17881. set: function (value) {
  17882. var old = new BABYLON.Vector2(this._left, this._bottom);
  17883. this._bottom = value;
  17884. this.onPropertyChanged("_position", old, this._position);
  17885. },
  17886. enumerable: true,
  17887. configurable: true
  17888. });
  17889. Object.defineProperty(Window.prototype, "position", {
  17890. get: function () {
  17891. return this._position;
  17892. },
  17893. set: function (value) {
  17894. this._left = value.x;
  17895. this._bottom = value.y;
  17896. },
  17897. enumerable: true,
  17898. configurable: true
  17899. });
  17900. Object.defineProperty(Window.prototype, "isActive", {
  17901. get: function () {
  17902. return this._isActive;
  17903. },
  17904. set: function (value) {
  17905. this._isActive = value;
  17906. },
  17907. enumerable: true,
  17908. configurable: true
  17909. });
  17910. Object.defineProperty(Window.prototype, "focusManager", {
  17911. get: function () {
  17912. return this._sceneData.focusManager;
  17913. },
  17914. enumerable: true,
  17915. configurable: true
  17916. });
  17917. Object.defineProperty(Window.prototype, "_position", {
  17918. get: function () {
  17919. return new BABYLON.Vector2(this.left, this.bottom);
  17920. },
  17921. enumerable: true,
  17922. configurable: true
  17923. });
  17924. Window.prototype.createVisualTree = function () {
  17925. _super.prototype.createVisualTree.call(this);
  17926. var p = this._visualPlaceholder;
  17927. p.createSimpleDataBinding(BABYLON.Group2D.positionProperty, "position");
  17928. };
  17929. Window.prototype._registerVisualToBuild = function (uiel) {
  17930. if (uiel._isFlagSet(BABYLON.UIElement.flagVisualToBuild)) {
  17931. return;
  17932. }
  17933. if (!this._UIElementVisualToBuildList) {
  17934. this._UIElementVisualToBuildList = new Array();
  17935. }
  17936. this._UIElementVisualToBuildList.push(uiel);
  17937. uiel._setFlags(BABYLON.UIElement.flagVisualToBuild);
  17938. };
  17939. Window.prototype._overPrimChanged = function (oldPrim, newPrim) {
  17940. var curOverEl = this._mouseOverUIElement;
  17941. var newOverEl = null;
  17942. var curGroup = newPrim ? newPrim.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  17943. while (curGroup) {
  17944. var uiel = curGroup.getExternalData("_GUIOwnerElement_");
  17945. if (uiel) {
  17946. newOverEl = uiel;
  17947. break;
  17948. }
  17949. curGroup = curGroup.parent ? curGroup.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  17950. }
  17951. if (curOverEl === newOverEl) {
  17952. return;
  17953. }
  17954. if (curOverEl) {
  17955. curOverEl.isMouseOver = false;
  17956. }
  17957. if (newOverEl) {
  17958. newOverEl.isMouseOver = true;
  17959. }
  17960. this._mouseOverUIElement = newOverEl;
  17961. };
  17962. Window.prototype._canvasPreRender = function () {
  17963. // Check if we have visual to create
  17964. if (this._UIElementVisualToBuildList.length > 0) {
  17965. // Sort the UI Element to get the highest (so lowest hierarchy depth) in the hierarchy tree first
  17966. var sortedElementList = this._UIElementVisualToBuildList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  17967. for (var _i = 0, sortedElementList_1 = sortedElementList; _i < sortedElementList_1.length; _i++) {
  17968. var el = sortedElementList_1[_i];
  17969. el._createVisualTree();
  17970. }
  17971. this._UIElementVisualToBuildList.splice(0);
  17972. }
  17973. };
  17974. Window.prototype._canvasDisposed = function () {
  17975. this._canvas.disposeObservable.remove(this._disposeObserver);
  17976. this._canvas.renderObservable.remove(this._renderObserver);
  17977. };
  17978. Window.getSceneData = function (scene) {
  17979. return Window_1._sceneData.getOrAddWithFactory(scene.uid, function (k) { return new GUISceneData(scene); });
  17980. };
  17981. return Window;
  17982. }(BABYLON.ContentControl));
  17983. Window.WINDOW_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 4;
  17984. Window._sceneData = new BABYLON.StringDictionary();
  17985. __decorate([
  17986. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 0, function (pi) { return Window_1.leftProperty = pi; })
  17987. ], Window.prototype, "left", null);
  17988. __decorate([
  17989. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 1, function (pi) { return Window_1.bottomProperty = pi; })
  17990. ], Window.prototype, "bottom", null);
  17991. __decorate([
  17992. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 2, function (pi) { return Window_1.positionProperty = pi; })
  17993. ], Window.prototype, "position", null);
  17994. __decorate([
  17995. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3, function (pi) { return Window_1.isActiveProperty = pi; })
  17996. ], Window.prototype, "isActive", null);
  17997. Window = Window_1 = __decorate([
  17998. BABYLON.className("Window", "BABYLON")
  17999. ], Window);
  18000. BABYLON.Window = Window;
  18001. var DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = (function (_super) {
  18002. __extends(DefaultWindowRenderingTemplate, _super);
  18003. function DefaultWindowRenderingTemplate() {
  18004. return _super !== null && _super.apply(this, arguments) || this;
  18005. }
  18006. DefaultWindowRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  18007. var r = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#808080FF" });
  18008. return { root: r, contentPlaceholder: r };
  18009. };
  18010. return DefaultWindowRenderingTemplate;
  18011. }(BABYLON.UIElementRenderingTemplateBase));
  18012. DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = __decorate([
  18013. BABYLON.registerWindowRenderingTemplate("BABYLON.Window", "Default", function () { return new DefaultWindowRenderingTemplate_1(); })
  18014. ], DefaultWindowRenderingTemplate);
  18015. BABYLON.DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate;
  18016. var Window_1, DefaultWindowRenderingTemplate_1;
  18017. })(BABYLON || (BABYLON = {}));
  18018. var __extends = (this && this.__extends) || function (d, b) {
  18019. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18020. function __() { this.constructor = d; }
  18021. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18022. };
  18023. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18024. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18025. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18026. 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;
  18027. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18028. };
  18029. var BABYLON;
  18030. (function (BABYLON) {
  18031. var Label = Label_1 = (function (_super) {
  18032. __extends(Label, _super);
  18033. function Label(settings) {
  18034. var _this = this;
  18035. if (!settings) {
  18036. settings = {};
  18037. }
  18038. _this = _super.call(this, settings) || this;
  18039. if (settings.text != null) {
  18040. _this.text = settings.text;
  18041. }
  18042. return _this;
  18043. }
  18044. Object.defineProperty(Label.prototype, "_position", {
  18045. get: function () {
  18046. return BABYLON.Vector2.Zero();
  18047. },
  18048. enumerable: true,
  18049. configurable: true
  18050. });
  18051. Label.prototype._getChildren = function () {
  18052. return Label_1._emptyArray;
  18053. };
  18054. Label.prototype.createVisualTree = function () {
  18055. _super.prototype.createVisualTree.call(this);
  18056. var p = this._visualChildrenPlaceholder;
  18057. };
  18058. Object.defineProperty(Label.prototype, "text", {
  18059. get: function () {
  18060. return this._text;
  18061. },
  18062. set: function (value) {
  18063. this._text = value;
  18064. },
  18065. enumerable: true,
  18066. configurable: true
  18067. });
  18068. return Label;
  18069. }(BABYLON.Control));
  18070. Label._emptyArray = new Array();
  18071. __decorate([
  18072. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return Label_1.textProperty = pi; })
  18073. ], Label.prototype, "text", null);
  18074. Label = Label_1 = __decorate([
  18075. BABYLON.className("Label", "BABYLON")
  18076. ], Label);
  18077. BABYLON.Label = Label;
  18078. var DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = (function (_super) {
  18079. __extends(DefaultLabelRenderingTemplate, _super);
  18080. function DefaultLabelRenderingTemplate() {
  18081. return _super !== null && _super.apply(this, arguments) || this;
  18082. }
  18083. DefaultLabelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  18084. var r = new BABYLON.Text2D("", { parent: visualPlaceholder });
  18085. r.createSimpleDataBinding(BABYLON.Text2D.textProperty, "text");
  18086. r.dataSource = owner;
  18087. return { root: r, contentPlaceholder: r };
  18088. };
  18089. return DefaultLabelRenderingTemplate;
  18090. }(BABYLON.UIElementRenderingTemplateBase));
  18091. DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = __decorate([
  18092. BABYLON.registerWindowRenderingTemplate("BABYLON.Label", "Default", function () { return new DefaultLabelRenderingTemplate_1(); })
  18093. ], DefaultLabelRenderingTemplate);
  18094. BABYLON.DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate;
  18095. var Label_1, DefaultLabelRenderingTemplate_1;
  18096. })(BABYLON || (BABYLON = {}));
  18097. var __extends = (this && this.__extends) || function (d, b) {
  18098. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18099. function __() { this.constructor = d; }
  18100. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18101. };
  18102. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18103. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18104. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18105. 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;
  18106. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18107. };
  18108. var BABYLON;
  18109. (function (BABYLON) {
  18110. var Button = Button_1 = (function (_super) {
  18111. __extends(Button, _super);
  18112. function Button(settings) {
  18113. var _this = this;
  18114. if (!settings) {
  18115. settings = {};
  18116. }
  18117. _this = _super.call(this, settings) || this;
  18118. if (settings.paddingAlignment == null) {
  18119. _this.paddingAlignment.horizontal = BABYLON.PrimitiveAlignment.AlignCenter;
  18120. _this.paddingAlignment.vertical = BABYLON.PrimitiveAlignment.AlignCenter;
  18121. }
  18122. _this._normalStateBackground = new BABYLON.ObservableStringDictionary(false);
  18123. _this._normalStateBorder = new BABYLON.ObservableStringDictionary(false);
  18124. _this._defaultStateBackground = new BABYLON.ObservableStringDictionary(false);
  18125. _this._defaultStateBorder = new BABYLON.ObservableStringDictionary(false);
  18126. _this._normalStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#337AB7FF"));
  18127. _this._normalStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#7BA9D0FF"));
  18128. _this._normalStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#286090FF"));
  18129. _this._normalStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#1E496EFF"));
  18130. _this._normalStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E6DA4FF"));
  18131. _this._normalStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#77A0C4FF"));
  18132. _this._normalStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#204D74FF"));
  18133. _this._normalStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E5D9EFF"));
  18134. _this._defaultStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  18135. _this._defaultStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  18136. _this._defaultStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#E6E6E6FF"));
  18137. _this._defaultStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#D4D4D4FF"));
  18138. _this._defaultStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#CCCCCCFF"));
  18139. _this._defaultStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#DEDEDEFF"));
  18140. _this._defaultStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#ADADADFF"));
  18141. _this._defaultStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#6C8EC5FF"));
  18142. return _this;
  18143. }
  18144. Object.defineProperty(Button, "pushedState", {
  18145. get: function () {
  18146. return Button_1._pushedState;
  18147. },
  18148. enumerable: true,
  18149. configurable: true
  18150. });
  18151. Object.defineProperty(Button.prototype, "isPushed", {
  18152. get: function () {
  18153. return this._isPushed;
  18154. },
  18155. set: function (value) {
  18156. this._isPushed = value;
  18157. },
  18158. enumerable: true,
  18159. configurable: true
  18160. });
  18161. Object.defineProperty(Button.prototype, "isDefault", {
  18162. get: function () {
  18163. return this._isDefault;
  18164. },
  18165. set: function (value) {
  18166. this._isDefault = value;
  18167. },
  18168. enumerable: true,
  18169. configurable: true
  18170. });
  18171. Object.defineProperty(Button.prototype, "isOutline", {
  18172. get: function () {
  18173. return this._isOutline;
  18174. },
  18175. set: function (value) {
  18176. this._isOutline = value;
  18177. },
  18178. enumerable: true,
  18179. configurable: true
  18180. });
  18181. Object.defineProperty(Button.prototype, "clickObservable", {
  18182. get: function () {
  18183. if (!this._clickObservable) {
  18184. this._clickObservable = new BABYLON.Observable();
  18185. }
  18186. return this._clickObservable;
  18187. },
  18188. enumerable: true,
  18189. configurable: true
  18190. });
  18191. Button.prototype._raiseClick = function () {
  18192. if (this._clickObservable && this._clickObservable.hasObservers()) {
  18193. this._clickObservable.notifyObservers(this);
  18194. }
  18195. };
  18196. Button.prototype.createVisualTree = function () {
  18197. var _this = this;
  18198. _super.prototype.createVisualTree.call(this);
  18199. var p = this._visualPlaceholder;
  18200. p.pointerEventObservable.add(function (e, s) {
  18201. // check if input must be discarded
  18202. if (!_this.isVisible || !_this.isEnabled) {
  18203. return;
  18204. }
  18205. // We reject an event coming from the placeholder because it means it's on an empty spot, so it's not valid.
  18206. if (e.relatedTarget === _this._visualPlaceholder) {
  18207. return;
  18208. }
  18209. if (s.mask === BABYLON.PrimitivePointerInfo.PointerUp) {
  18210. _this._raiseClick();
  18211. _this.isPushed = false;
  18212. }
  18213. else if (s.mask === BABYLON.PrimitivePointerInfo.PointerDown) {
  18214. _this.isPushed = true;
  18215. _this.isFocused = true;
  18216. }
  18217. }, BABYLON.PrimitivePointerInfo.PointerUp | BABYLON.PrimitivePointerInfo.PointerDown);
  18218. };
  18219. Object.defineProperty(Button.prototype, "normalStateBackground", {
  18220. get: function () {
  18221. return this._normalStateBackground;
  18222. },
  18223. enumerable: true,
  18224. configurable: true
  18225. });
  18226. Object.defineProperty(Button.prototype, "defaultStateBackground", {
  18227. get: function () {
  18228. return this._defaultStateBackground;
  18229. },
  18230. enumerable: true,
  18231. configurable: true
  18232. });
  18233. Object.defineProperty(Button.prototype, "normalStateBorder", {
  18234. get: function () {
  18235. return this._normalStateBorder;
  18236. },
  18237. enumerable: true,
  18238. configurable: true
  18239. });
  18240. Object.defineProperty(Button.prototype, "defaultStateBorder", {
  18241. get: function () {
  18242. return this._defaultStateBorder;
  18243. },
  18244. enumerable: true,
  18245. configurable: true
  18246. });
  18247. return Button;
  18248. }(BABYLON.ContentControl));
  18249. Button.BUTTON_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3;
  18250. Button._pushedState = "Pushed";
  18251. __decorate([
  18252. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 0, function (pi) { return Button_1.isPushedProperty = pi; })
  18253. ], Button.prototype, "isPushed", null);
  18254. __decorate([
  18255. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 1, function (pi) { return Button_1.isDefaultProperty = pi; })
  18256. ], Button.prototype, "isDefault", null);
  18257. __decorate([
  18258. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 2, function (pi) { return Button_1.isOutlineProperty = pi; })
  18259. ], Button.prototype, "isOutline", null);
  18260. Button = Button_1 = __decorate([
  18261. BABYLON.className("Button", "BABYLON")
  18262. ], Button);
  18263. BABYLON.Button = Button;
  18264. var DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = (function (_super) {
  18265. __extends(DefaultButtonRenderingTemplate, _super);
  18266. function DefaultButtonRenderingTemplate() {
  18267. return _super !== null && _super.apply(this, arguments) || this;
  18268. }
  18269. DefaultButtonRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  18270. this._rect = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#FF8080FF", border: "#FF8080FF", roundRadius: 10, borderThickness: 2 });
  18271. this.stateChange();
  18272. return { root: this._rect, contentPlaceholder: this._rect };
  18273. };
  18274. DefaultButtonRenderingTemplate.prototype.attach = function (owner) {
  18275. var _this = this;
  18276. _super.prototype.attach.call(this, owner);
  18277. this.owner.propertyChanged.add(function (e, s) { return _this.stateChange(); }, BABYLON.UIElement.isEnabledProperty.flagId |
  18278. BABYLON.UIElement.isFocusedProperty.flagId |
  18279. BABYLON.UIElement.isMouseOverProperty.flagId |
  18280. Button.isDefaultProperty.flagId |
  18281. Button.isOutlineProperty.flagId |
  18282. Button.isPushedProperty.flagId);
  18283. // Register for brush change and update the Visual
  18284. var button = owner;
  18285. button.normalStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18286. button.normalStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18287. button.defaultStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18288. button.defaultStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  18289. };
  18290. DefaultButtonRenderingTemplate.prototype.stateChange = function () {
  18291. //console.log("state changed");
  18292. var b = this.owner;
  18293. var state = BABYLON.UIElement.enabledState;
  18294. var bg = b.isDefault ? b.defaultStateBackground.get(state) : b.normalStateBackground.get(state);
  18295. var bd = b.isDefault ? b.defaultStateBorder.get(state) : b.normalStateBorder.get(state);
  18296. if (b.isPushed) {
  18297. state = Button.pushedState;
  18298. if (b.isDefault) {
  18299. bg = b.defaultStateBackground.get(state);
  18300. bd = b.defaultStateBorder.get(state);
  18301. }
  18302. else {
  18303. bg = b.normalStateBackground.get(state);
  18304. bd = b.normalStateBorder.get(state);
  18305. }
  18306. }
  18307. else if (b.isMouseOver) {
  18308. state = BABYLON.UIElement.mouseOverState;
  18309. if (b.isDefault) {
  18310. bg = b.defaultStateBackground.get(state);
  18311. bd = b.defaultStateBorder.get(state);
  18312. }
  18313. else {
  18314. bg = b.normalStateBackground.get(state);
  18315. bd = b.normalStateBorder.get(state);
  18316. }
  18317. }
  18318. else if (!b.isEnabled) {
  18319. state = BABYLON.UIElement.disabledState;
  18320. if (b.isDefault) {
  18321. bg = b.defaultStateBackground.get(state);
  18322. bd = b.defaultStateBorder.get(state);
  18323. }
  18324. else {
  18325. bg = b.normalStateBackground.get(state);
  18326. bd = b.normalStateBorder.get(state);
  18327. }
  18328. }
  18329. this._rect.fill = bg;
  18330. this._rect.border = bd;
  18331. };
  18332. return DefaultButtonRenderingTemplate;
  18333. }(BABYLON.UIElementRenderingTemplateBase));
  18334. DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = __decorate([
  18335. BABYLON.registerWindowRenderingTemplate("BABYLON.Button", "Default", function () { return new DefaultButtonRenderingTemplate_1(); })
  18336. ], DefaultButtonRenderingTemplate);
  18337. BABYLON.DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate;
  18338. var Button_1, DefaultButtonRenderingTemplate_1;
  18339. })(BABYLON || (BABYLON = {}));