babylon.canvas2d.js 970 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845
  1. BABYLON.Effect.ShadersStore['ellipse2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  2. BABYLON.Effect.ShadersStore['ellipse2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}";
  3. BABYLON.Effect.ShadersStore['lines2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  4. BABYLON.Effect.ShadersStore['lines2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}";
  5. BABYLON.Effect.ShadersStore['rect2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  6. BABYLON.Effect.ShadersStore['rect2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}";
  7. BABYLON.Effect.ShadersStore['sprite2dPixelShader'] = "varying vec2 vUV;\nvarying float vOpacity;\n#ifdef Scale9\nvarying vec2 vTopLeftUV;\nvarying vec2 vBottomRightUV;\nvarying vec4 vScale9;\nvarying vec2 vScaleFactor;\n#endif\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec2 uv=vUV;\n#ifdef Scale9\nvec2 sizeUV=vBottomRightUV-vTopLeftUV;\n\nfloat leftPartUV=vTopLeftUV.x+(vScale9.x/vScaleFactor.x);\nfloat rightPartUV=vTopLeftUV.x+sizeUV.x-((sizeUV.x-vScale9.z)/vScaleFactor.x);\nif (vUV.x<leftPartUV) {\nuv.x=vTopLeftUV.x+((vUV.x- vTopLeftUV.x)*vScaleFactor.x);\n}\nelse if (vUV.x>rightPartUV) {\nuv.x=vTopLeftUV.x+vScale9.z+((vUV.x-rightPartUV)*vScaleFactor.x);\n}\nelse {\nfloat r=(vUV.x-leftPartUV)/(rightPartUV-leftPartUV);\nuv.x=vTopLeftUV.x+vScale9.x+((vScale9.z-vScale9.x)*r);\n}\n\nfloat topPartUV=(vTopLeftUV.y+(vScale9.y/vScaleFactor.y));\nfloat bottomPartUV=(vTopLeftUV.y+sizeUV.y-((sizeUV.y-vScale9.w)/vScaleFactor.y));\nif (vUV.y<topPartUV) {\nuv.y=vTopLeftUV.y+((vUV.y-vTopLeftUV.y)*vScaleFactor.y);\n}\nelse if (vUV.y>bottomPartUV) {\nuv.y=vTopLeftUV.y+vScale9.w+((vUV.y-bottomPartUV)*vScaleFactor.y);\n}\nelse {\nfloat r=(vUV.y-topPartUV)/(bottomPartUV-topPartUV);\nuv.y=vTopLeftUV.y+vScale9.y+((vScale9.w-vScale9.y)*r);\n}\n#endif\nvec4 color=texture2D(diffuseSampler,uv);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}";
  8. BABYLON.Effect.ShadersStore['sprite2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\n#ifdef Scale9\natt vec2 scaleFactor;\n#endif\natt vec2 textureSize;\n\natt vec3 properties;\n#ifdef Scale9\natt vec4 scale9;\n#endif\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\n#ifdef Scale9\nvarying vec2 vTopLeftUV;\nvarying vec2 vBottomRightUV;\nvarying vec4 vScale9;\nvarying vec2 vScaleFactor;\n#endif\nvoid main(void) {\nvec2 pos2;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x),topLeftUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),(topLeftUV.y+sizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x+(frame*sizeUV.x),topLeftUV.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\n#ifdef Scale9\nif (invertY == 1.0) {\nvTopLeftUV=vec2(topLeftUV.x,1.0-(topLeftUV.y+sizeUV.y));\nvBottomRightUV=vec2(topLeftUV.x+sizeUV.x,1.0-topLeftUV.y);\nvScale9=vec4(scale9.x,sizeUV.y-scale9.w,scale9.z,sizeUV.y-scale9.y);\n}\nelse {\nvTopLeftUV=topLeftUV;\nvBottomRightUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\nvScale9=scale9;\n}\nvScaleFactor=scaleFactor;\n#endif\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ";
  9. BABYLON.Effect.ShadersStore['text2dPixelShader'] = "\nvarying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\n#ifdef SignedDistanceField\nfloat dist=texture2D(diffuseSampler,vUV).r;\nif (dist<0.5) {\ndiscard;\n}\n\n\n\n\n\ngl_FragColor=vec4(vColor.xyz*dist,vColor.a);\n#else\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n#endif\n}";
  10. BABYLON.Effect.ShadersStore['text2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}";
  11. BABYLON.Effect.ShadersStore['wireframe2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  12. BABYLON.Effect.ShadersStore['wireframe2dVertexShader'] = "\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute vec2 pos;\nattribute vec4 col;\n\n\n\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec4 vColor;\nvoid main(void) {\nvec4 p=vec4(pos.xy,1.0,1.0);\nvColor=vec4(col.xyz,col.w*opacity);\nvec4 pp=vec4(dot(p,transformX),dot(p,transformY),zBias.x,1);\nif (properties.x == 1.0) {\npp.xy=pp.xy-mod(pp.xy,properties.yz)+(properties.yz*0.5);\n}\ngl_Position=pp;\n} ";
  13. var BABYLON;
  14. (function (BABYLON) {
  15. /**
  16. * This class stores the data to make 2D transformation using a Translation (tX, tY), a Scale (sX, sY) and a rotation around the Z axis (rZ).
  17. * You can multiply two Transform2D object to produce the result of their concatenation.
  18. * You can transform a given Point (a Vector2D instance) with a Transform2D object or with the Invert of the Transform2D object.
  19. * There no need to compute/store the Invert of a Transform2D as the invertTranform methods are almost as fast as the transform ones.
  20. * This class is as light as it could be and the transformation operations are pretty optimal.
  21. */
  22. var Transform2D = (function () {
  23. function Transform2D() {
  24. this.translation = BABYLON.Vector2.Zero();
  25. this.rotation = 0;
  26. this.scale = new BABYLON.Vector2(1, 1);
  27. }
  28. /**
  29. * Set the Transform2D object with the given values
  30. * @param translation The translation to set
  31. * @param rotation The rotation (in radian) to set
  32. * @param scale The scale to set
  33. */
  34. Transform2D.prototype.set = function (translation, rotation, scale) {
  35. this.translation.copyFrom(translation);
  36. this.rotation = rotation;
  37. this.scale.copyFrom(scale);
  38. };
  39. /**
  40. * Set the Transform2D object from float values
  41. * @param transX The translation on X axis, nothing is set if not specified
  42. * @param transY The translation on Y axis, nothing is set if not specified
  43. * @param rotation The rotation in radian, nothing is set if not specified
  44. * @param scaleX The scale along the X axis, nothing is set if not specified
  45. * @param scaleY The scale along the Y axis, nothing is set if not specified
  46. */
  47. Transform2D.prototype.setFromFloats = function (transX, transY, rotation, scaleX, scaleY) {
  48. if (transX) {
  49. this.translation.x = transX;
  50. }
  51. if (transY) {
  52. this.translation.y = transY;
  53. }
  54. if (rotation) {
  55. this.rotation = rotation;
  56. }
  57. if (scaleX) {
  58. this.scale.x = scaleX;
  59. }
  60. if (scaleY) {
  61. this.scale.y = scaleY;
  62. }
  63. };
  64. /**
  65. * Return a copy of the object
  66. */
  67. Transform2D.prototype.clone = function () {
  68. var res = new Transform2D();
  69. res.translation.copyFrom(this.translation);
  70. res.rotation = this.rotation;
  71. res.scale.copyFrom(this.scale);
  72. return res;
  73. };
  74. /**
  75. * Convert a given degree angle into its radian equivalent
  76. * @param angleDegree the number to convert
  77. */
  78. Transform2D.ToRadian = function (angleDegree) {
  79. return angleDegree * Math.PI * 2 / 360;
  80. };
  81. /**
  82. * Create a new instance and returns it
  83. * @param translation The translation to store, default is (0,0)
  84. * @param rotation The rotation to store, default is 0
  85. * @param scale The scale to store, default is (1,1)
  86. */
  87. Transform2D.Make = function (translation, rotation, scale) {
  88. var res = new Transform2D();
  89. if (translation) {
  90. res.translation.copyFrom(translation);
  91. }
  92. if (rotation) {
  93. res.rotation = rotation;
  94. }
  95. if (scale) {
  96. res.scale.copyFrom(scale);
  97. }
  98. return res;
  99. };
  100. /**
  101. * Set the given Transform2D object with the given values
  102. * @param translation The translation to store, default is (0,0)
  103. * @param rotation The rotation to store, default is 0
  104. * @param scale The scale to store, default is (1,1)
  105. */
  106. Transform2D.MakeToRef = function (res, translation, rotation, scale) {
  107. if (translation) {
  108. res.translation.copyFrom(translation);
  109. }
  110. else {
  111. res.translation.copyFromFloats(0, 0);
  112. }
  113. if (rotation) {
  114. res.rotation = rotation;
  115. }
  116. else {
  117. res.rotation = 0;
  118. }
  119. if (scale) {
  120. res.scale.copyFrom(scale);
  121. }
  122. else {
  123. res.scale.copyFromFloats(1, 1);
  124. }
  125. };
  126. /**
  127. * Create a Transform2D object from float values
  128. * @param transX The translation on X axis, 0 per default
  129. * @param transY The translation on Y axis, 0 per default
  130. * @param rotation The rotation in radian, 0 per default
  131. * @param scaleX The scale along the X axis, 1 per default
  132. * @param scaleY The scale along the Y axis, 1 per default
  133. */
  134. Transform2D.MakeFromFloats = function (transX, transY, rotation, scaleX, scaleY) {
  135. var res = new Transform2D();
  136. if (transX) {
  137. res.translation.x = transX;
  138. }
  139. if (transY) {
  140. res.translation.y = transY;
  141. }
  142. if (rotation) {
  143. res.rotation = rotation;
  144. }
  145. if (scaleX) {
  146. res.scale.x = scaleX;
  147. }
  148. if (scaleY) {
  149. res.scale.y = scaleY;
  150. }
  151. return res;
  152. };
  153. /**
  154. * Set the given Transform2D object with the given float values
  155. * @param transX The translation on X axis, 0 per default
  156. * @param transY The translation on Y axis, 0 per default
  157. * @param rotation The rotation in radian, 0 per default
  158. * @param scaleX The scale along the X axis, 1 per default
  159. * @param scaleY The scale along the Y axis, 1 per default
  160. */
  161. Transform2D.MakeFromFloatsToRef = function (res, transX, transY, rotation, scaleX, scaleY) {
  162. res.translation.x = (transX != null) ? transX : 0;
  163. res.translation.y = (transY != null) ? transY : 0;
  164. res.rotation = (rotation != null) ? rotation : 0;
  165. res.scale.x = (scaleX != null) ? scaleX : 1;
  166. res.scale.y = (scaleY != null) ? scaleY : 1;
  167. };
  168. /**
  169. * Create a Transform2D containing only Zeroed values
  170. */
  171. Transform2D.Zero = function () {
  172. var res = new Transform2D();
  173. res.scale.copyFromFloats(0, 0);
  174. return res;
  175. };
  176. /**
  177. * Copy the value of the other object into 'this'
  178. * @param other The other object to copy values from
  179. */
  180. Transform2D.prototype.copyFrom = function (other) {
  181. this.translation.copyFrom(other.translation);
  182. this.rotation = other.rotation;
  183. this.scale.copyFrom(other.scale);
  184. };
  185. Transform2D.prototype.toMatrix2D = function () {
  186. var res = new Matrix2D();
  187. this.toMatrix2DToRef(res);
  188. return res;
  189. };
  190. Transform2D.prototype.toMatrix2DToRef = function (res) {
  191. var tx = this.translation.x;
  192. var ty = this.translation.y;
  193. var r = this.rotation;
  194. var cosr = Math.cos(r);
  195. var sinr = Math.sin(r);
  196. var sx = this.scale.x;
  197. var sy = this.scale.y;
  198. res.m[0] = cosr * sx;
  199. res.m[1] = sinr * sy;
  200. res.m[2] = -sinr * sx;
  201. res.m[3] = cosr * sy;
  202. res.m[4] = tx;
  203. res.m[5] = ty;
  204. };
  205. /**
  206. * In place transformation from a parent matrix.
  207. * @param parent transform object. "this" will be the result of parent * this
  208. */
  209. Transform2D.prototype.multiplyToThis = function (parent) {
  210. this.multiplyToRef(parent, this);
  211. };
  212. /**
  213. * Transform this object with a parent and return the result. Result = parent * this
  214. * @param parent The parent transformation
  215. */
  216. Transform2D.prototype.multiply = function (parent) {
  217. var res = new Transform2D();
  218. this.multiplyToRef(parent, res);
  219. return res;
  220. };
  221. /**
  222. * Transform a point and store the result in the very same object
  223. * @param p Transform this point and change the values with the transformed ones
  224. */
  225. Transform2D.prototype.transformPointInPlace = function (p) {
  226. this.transformPointToRef(p, p);
  227. };
  228. /**
  229. * Transform a point and store the result into a reference object
  230. * @param p The point to transform
  231. * @param res Will contain the new transformed coordinates. Can be the object of 'p'.
  232. */
  233. Transform2D.prototype.transformPointToRef = function (p, res) {
  234. this.transformFloatsToRef(p.x, p.y, res);
  235. };
  236. /**
  237. * Transform this object with a parent and store the result in reference object
  238. * @param parent The parent transformation
  239. * @param result Will contain parent * this. Can be the object of either parent or 'this'
  240. */
  241. Transform2D.prototype.multiplyToRef = function (parent, result) {
  242. if (!parent || !result) {
  243. throw new Error("Valid parent and result objects must be specified");
  244. }
  245. var tx = this.translation.x;
  246. var ty = this.translation.y;
  247. var ptx = parent.translation.x;
  248. var pty = parent.translation.y;
  249. var pr = parent.rotation;
  250. var psx = parent.scale.x;
  251. var psy = parent.scale.y;
  252. var cosr = Math.cos(pr);
  253. var sinr = Math.sin(pr);
  254. result.translation.x = (((tx * cosr) - (ty * sinr)) * psx) + ptx;
  255. result.translation.y = (((tx * sinr) + (ty * cosr)) * psy) + pty;
  256. this.scale.multiplyToRef(parent.scale, result.scale);
  257. result.rotation = this.rotation;
  258. };
  259. /**
  260. * Transform the given coordinates and store the result in a Vector2 object
  261. * @param x The X coordinate to transform
  262. * @param y The Y coordinate to transform
  263. * @param res The Vector2 object that will contain the result of the transformation
  264. */
  265. Transform2D.prototype.transformFloatsToRef = function (x, y, res) {
  266. var tx = this.translation.x;
  267. var ty = this.translation.y;
  268. var pr = this.rotation;
  269. var sx = this.scale.x;
  270. var sy = this.scale.y;
  271. var cosr = Math.cos(pr);
  272. var sinr = Math.sin(pr);
  273. res.x = (((x * cosr) - (y * sinr)) * sx) + tx;
  274. res.y = (((x * sinr) + (y * cosr)) * sy) + ty;
  275. };
  276. /**
  277. * Invert transform the given coordinates and store the result in a reference object. res = invert(this) * (x,y)
  278. * @param p Transform this point and change the values with the transformed ones
  279. * @param res Will contain the result of the invert transformation.
  280. */
  281. Transform2D.prototype.invertTransformFloatsToRef = function (x, y, res) {
  282. var px = x - this.translation.x;
  283. var py = y - this.translation.y;
  284. var pr = -this.rotation;
  285. var sx = this.scale.x;
  286. var sy = this.scale.y;
  287. var psx = (sx === 1) ? 1 : (1 / sx);
  288. var psy = (sy === 1) ? 1 : (1 / sy);
  289. var cosr = Math.cos(pr);
  290. var sinr = Math.sin(pr);
  291. res.x = (((px * cosr) - (py * sinr)) * psx);
  292. res.y = (((px * sinr) + (py * cosr)) * psy);
  293. };
  294. /**
  295. * Transform a point and return the result
  296. * @param p the point to transform
  297. */
  298. Transform2D.prototype.transformPoint = function (p) {
  299. var res = BABYLON.Vector2.Zero();
  300. this.transformPointToRef(p, res);
  301. return res;
  302. };
  303. /**
  304. * Transform the given coordinates and return the result in a Vector2 object
  305. * @param x The X coordinate to transform
  306. * @param y The Y coordinate to transform
  307. */
  308. Transform2D.prototype.transformFloats = function (x, y) {
  309. var res = BABYLON.Vector2.Zero();
  310. this.transformFloatsToRef(x, y, res);
  311. return res;
  312. };
  313. /**
  314. * Invert transform a given point and store the result in the very same object. p = invert(this) * p
  315. * @param p Transform this point and change the values with the transformed ones
  316. */
  317. Transform2D.prototype.invertTransformPointInPlace = function (p) {
  318. this.invertTransformPointToRef(p, p);
  319. };
  320. /**
  321. * Invert transform a given point and store the result in a reference object. res = invert(this) * p
  322. * @param p Transform this point and change the values with the transformed ones
  323. * @param res Will contain the result of the invert transformation. 'res' can be the same object as 'p'
  324. */
  325. Transform2D.prototype.invertTransformPointToRef = function (p, res) {
  326. this.invertTransformFloatsToRef(p.x, p.y, res);
  327. };
  328. /**
  329. * Invert transform a given point and return the result. return = invert(this) * p
  330. * @param p The Point to transform
  331. */
  332. Transform2D.prototype.invertTransformPoint = function (p) {
  333. var res = BABYLON.Vector2.Zero();
  334. this.invertTransformPointToRef(p, res);
  335. return res;
  336. };
  337. /**
  338. * Invert transform the given coordinates and return the result. return = invert(this) * (x,y)
  339. * @param x The X coordinate to transform
  340. * @param y The Y coordinate to transform
  341. */
  342. Transform2D.prototype.invertTransformFloats = function (x, y) {
  343. var res = BABYLON.Vector2.Zero();
  344. this.invertTransformFloatsToRef(x, y, res);
  345. return res;
  346. };
  347. return Transform2D;
  348. }());
  349. BABYLON.Transform2D = Transform2D;
  350. /**
  351. * A class storing a Matrix for 2D transformations
  352. * The stored matrix is a 2*3 Matrix
  353. * I [0,1] [mX, mY] R [ CosZ, SinZ] T [ 0, 0] S [Sx, 0]
  354. * D = [2,3] = [nX, nY] O = [-SinZ, CosZ] R = [ 0, 0] C = [ 0, Sy]
  355. * X [4,5] [tX, tY] T [ 0 , 0 ] N [Tx, Ty] L [ 0, 0]
  356. *
  357. * IDX = index, zero based. ROT = Z axis Rotation. TRN = Translation. SCL = Scale.
  358. */
  359. var Matrix2D = (function () {
  360. function Matrix2D() {
  361. this.m = new Float32Array(6);
  362. }
  363. Matrix2D.Identity = function () {
  364. var res = new Matrix2D();
  365. Matrix2D.IdentityToRef(res);
  366. return res;
  367. };
  368. Matrix2D.IdentityToRef = function (res) {
  369. res.m[1] = res.m[2] = res.m[4] = res.m[5] = 0;
  370. res.m[0] = res.m[3] = 1;
  371. };
  372. Matrix2D.prototype.copyFrom = function (other) {
  373. for (var i = 0; i < 6; i++) {
  374. this.m[i] = other.m[i];
  375. }
  376. };
  377. Matrix2D.prototype.determinant = function () {
  378. return (this.m[0] * this.m[3]) - (this.m[1] * this.m[2]);
  379. };
  380. Matrix2D.prototype.invertToThis = function () {
  381. this.invertToRef(this);
  382. };
  383. Matrix2D.prototype.invert = function () {
  384. var res = new Matrix2D();
  385. this.invertToRef(res);
  386. return res;
  387. };
  388. Matrix2D.prototype.invertToRef = function (res) {
  389. var a00 = this.m[0], a01 = this.m[1], a10 = this.m[2], a11 = this.m[3], a20 = this.m[4], a21 = this.m[5];
  390. var det21 = a21 * a10 - a11 * a20;
  391. var det = (a00 * a11) - (a01 * a10);
  392. if (det < (BABYLON.Epsilon * BABYLON.Epsilon)) {
  393. throw new Error("Can't invert matrix, near null determinant");
  394. }
  395. det = 1 / det;
  396. res.m[0] = a11 * det;
  397. res.m[1] = -a01 * det;
  398. res.m[2] = -a10 * det;
  399. res.m[3] = a00 * det;
  400. res.m[4] = det21 * det;
  401. res.m[5] = (-a21 * a00 + a01 * a20) * det;
  402. };
  403. Matrix2D.prototype.multiplyToThis = function (other) {
  404. this.multiplyToRef(other, this);
  405. };
  406. Matrix2D.prototype.multiply = function (other) {
  407. var res = new Matrix2D();
  408. this.multiplyToRef(other, res);
  409. return res;
  410. };
  411. Matrix2D.prototype.multiplyToRef = function (other, result) {
  412. var tm0 = this.m[0];
  413. var tm1 = this.m[1];
  414. //var tm2 = this.m[2];
  415. //var tm3 = this.m[3];
  416. var tm4 = this.m[2];
  417. var tm5 = this.m[3];
  418. //var tm6 = this.m[6];
  419. //var tm7 = this.m[7];
  420. var tm8 = this.m[4];
  421. var tm9 = this.m[5];
  422. //var tm10 = this.m[10];
  423. //var tm11 = this.m[11];
  424. //var tm12 = this.m[12];
  425. //var tm13 = this.m[13];
  426. //var tm14 = this.m[14];
  427. //var tm15 = this.m[15];
  428. var om0 = other.m[0];
  429. var om1 = other.m[1];
  430. //var om2 = other.m[2];
  431. //var om3 = other.m[3];
  432. var om4 = other.m[2];
  433. var om5 = other.m[3];
  434. //var om6 = other.m[6];
  435. //var om7 = other.m[7];
  436. var om8 = other.m[4];
  437. var om9 = other.m[5];
  438. //var om10 = other.m[10];
  439. //var om11 = other.m[11];
  440. //var om12 = other.m[12];
  441. //var om13 = other.m[13];
  442. //var om14 = other.m[14];
  443. //var om15 = other.m[15];
  444. result.m[0] = tm0 * om0 + tm1 * om4;
  445. result.m[1] = tm0 * om1 + tm1 * om5;
  446. //result.m[2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  447. //result.m[3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  448. result.m[2] = tm4 * om0 + tm5 * om4;
  449. result.m[3] = tm4 * om1 + tm5 * om5;
  450. //result.m[6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  451. //result.m[7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  452. result.m[4] = tm8 * om0 + tm9 * om4 + om8;
  453. result.m[5] = tm8 * om1 + tm9 * om5 + om9;
  454. //result.m[10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  455. //result.m[11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  456. //result.m[12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  457. //result.m[13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  458. //result.m[14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  459. //result.m[15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  460. };
  461. Matrix2D.prototype.transformFloats = function (x, y) {
  462. var res = BABYLON.Vector2.Zero();
  463. this.transformFloatsToRef(x, y, res);
  464. return res;
  465. };
  466. Matrix2D.prototype.transformFloatsToRef = function (x, y, r) {
  467. r.x = x * this.m[0] + y * this.m[2] + this.m[4];
  468. r.y = x * this.m[1] + y * this.m[3] + this.m[5];
  469. };
  470. Matrix2D.prototype.transformPoint = function (p) {
  471. var res = BABYLON.Vector2.Zero();
  472. this.transformFloatsToRef(p.x, p.y, res);
  473. return res;
  474. };
  475. Matrix2D.prototype.transformPointToRef = function (p, r) {
  476. this.transformFloatsToRef(p.x, p.y, r);
  477. };
  478. return Matrix2D;
  479. }());
  480. BABYLON.Matrix2D = Matrix2D;
  481. /**
  482. * Stores information about a 2D Triangle.
  483. * This class stores the 3 vertices but also the center and radius of the triangle
  484. */
  485. var Tri2DInfo = (function () {
  486. /**
  487. * Construct an instance of Tri2DInfo, you can either pass null to a, b and c and the instance will be allocated "clear", or give actual triangle info and the center/radius will be computed
  488. */
  489. function Tri2DInfo(a, b, c) {
  490. if (a === null && b === null && c === null) {
  491. this.a = BABYLON.Vector2.Zero();
  492. this.b = BABYLON.Vector2.Zero();
  493. this.c = BABYLON.Vector2.Zero();
  494. this.center = BABYLON.Vector2.Zero();
  495. this.radius = 0;
  496. return;
  497. }
  498. this.a = a.clone();
  499. this.b = b.clone();
  500. this.c = c.clone();
  501. this._updateCenterRadius();
  502. }
  503. Tri2DInfo.Zero = function () {
  504. return new Tri2DInfo(null, null, null);
  505. };
  506. Tri2DInfo.prototype.set = function (a, b, c) {
  507. this.a.copyFrom(a);
  508. this.b.copyFrom(b);
  509. this.c.copyFrom(c);
  510. this._updateCenterRadius();
  511. };
  512. Tri2DInfo.prototype.transformInPlace = function (transform) {
  513. BABYLON.Vector2.TransformToRef(this.a, transform, this.a);
  514. BABYLON.Vector2.TransformToRef(this.b, transform, this.b);
  515. BABYLON.Vector2.TransformToRef(this.c, transform, this.c);
  516. this._updateCenterRadius();
  517. };
  518. Tri2DInfo.prototype.doesContain = function (p) {
  519. return BABYLON.Vector2.PointInTriangle(p, this.a, this.b, this.c);
  520. };
  521. Tri2DInfo.prototype._updateCenterRadius = function () {
  522. this.center.x = (this.a.x + this.b.x + this.c.x) / 3;
  523. this.center.y = (this.a.y + this.b.y + this.c.y) / 3;
  524. var la = BABYLON.Vector2.DistanceSquared(this.a, this.center);
  525. var lb = BABYLON.Vector2.DistanceSquared(this.b, this.center);
  526. var lc = BABYLON.Vector2.DistanceSquared(this.c, this.center);
  527. var rs = Math.max(Math.max(la, lb), lc);
  528. this.radius = Math.sqrt(rs);
  529. };
  530. return Tri2DInfo;
  531. }());
  532. BABYLON.Tri2DInfo = Tri2DInfo;
  533. /**
  534. * Stores an array of 2D Triangles.
  535. * Internally the data is stored as a Float32Array to minimize the memory footprint.
  536. * This can use the Tri2DInfo class as proxy for storing/retrieving data.
  537. * The array can't grow, it's fixed size.
  538. */
  539. var Tri2DArray = (function () {
  540. function Tri2DArray(count) {
  541. this._count = count;
  542. this._array = new Float32Array(9 * count);
  543. }
  544. /**
  545. * Clear the content and allocate a new array to store the given count of triangles
  546. * @param count The new count of triangles to store
  547. */
  548. Tri2DArray.prototype.clear = function (count) {
  549. if (this._count === count) {
  550. return;
  551. }
  552. this._count = count;
  553. this._array = new Float32Array(9 * count);
  554. };
  555. /**
  556. * Store a given triangle at the given index
  557. * @param index the 0 based index to store the triangle in the array
  558. * @param a the A vertex of the triangle
  559. * @param b the B vertex of the triangle
  560. * @param c the C vertex of the triangle
  561. */
  562. Tri2DArray.prototype.storeTriangle = function (index, a, b, c) {
  563. var center = new BABYLON.Vector2((a.x + b.x + c.x) / 3, (a.y + b.y + c.y) / 3);
  564. var la = BABYLON.Vector2.DistanceSquared(a, center);
  565. var lb = BABYLON.Vector2.DistanceSquared(b, center);
  566. var lc = BABYLON.Vector2.DistanceSquared(c, center);
  567. var rs = Math.max(Math.max(la, lb), lc);
  568. var radius = Math.sqrt(rs);
  569. var offset = index * 9;
  570. this._array[offset + 0] = a.x;
  571. this._array[offset + 1] = a.y;
  572. this._array[offset + 2] = b.x;
  573. this._array[offset + 3] = b.y;
  574. this._array[offset + 4] = c.x;
  575. this._array[offset + 5] = c.y;
  576. this._array[offset + 6] = center.x;
  577. this._array[offset + 7] = center.y;
  578. this._array[offset + 8] = radius;
  579. };
  580. /**
  581. * Store a triangle in a Tri2DInfo object
  582. * @param index the index of the triangle to store
  583. * @param tri2dInfo the instance that will contain the data, it must be already allocated with its inner object also allocated
  584. */
  585. Tri2DArray.prototype.storeToTri2DInfo = function (index, tri2dInfo) {
  586. if (index >= this._count) {
  587. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  588. }
  589. var offset = index * 9;
  590. tri2dInfo.a.x = this._array[offset + 0];
  591. tri2dInfo.a.y = this._array[offset + 1];
  592. tri2dInfo.b.x = this._array[offset + 2];
  593. tri2dInfo.b.y = this._array[offset + 3];
  594. tri2dInfo.c.x = this._array[offset + 4];
  595. tri2dInfo.c.y = this._array[offset + 5];
  596. tri2dInfo.center.x = this._array[offset + 6];
  597. tri2dInfo.center.y = this._array[offset + 7];
  598. tri2dInfo.radius = this._array[offset + 8];
  599. };
  600. /**
  601. * Transform the given triangle and store its result in the array
  602. * @param index The index to store the result to
  603. * @param tri2dInfo The triangle to transform
  604. * @param transform The transformation matrix
  605. */
  606. Tri2DArray.prototype.transformAndStoreToTri2DInfo = function (index, tri2dInfo, transform) {
  607. if (index >= this._count) {
  608. throw new Error("Can't fetch the triangle at index " + index + ", max index is " + (this._count - 1));
  609. }
  610. var offset = index * 9;
  611. tri2dInfo.a.x = this._array[offset + 0];
  612. tri2dInfo.a.y = this._array[offset + 1];
  613. tri2dInfo.b.x = this._array[offset + 2];
  614. tri2dInfo.b.y = this._array[offset + 3];
  615. tri2dInfo.c.x = this._array[offset + 4];
  616. tri2dInfo.c.y = this._array[offset + 5];
  617. tri2dInfo.transformInPlace(transform);
  618. };
  619. Object.defineProperty(Tri2DArray.prototype, "count", {
  620. /**
  621. * Get the element count that can be stored in this array
  622. * @returns {}
  623. */
  624. get: function () {
  625. return this._count;
  626. },
  627. enumerable: true,
  628. configurable: true
  629. });
  630. /**
  631. * Check if a given point intersects with at least one of the triangles stored in the array.
  632. * If true is returned the point is intersecting with at least one triangle, false if it doesn't intersect with any of them
  633. * @param p The point to check
  634. */
  635. Tri2DArray.prototype.doesContain = function (p) {
  636. Tri2DArray._checkInitStatics();
  637. var a = Tri2DArray.tempT[0];
  638. for (var i = 0; i < this.count; i++) {
  639. this.storeToTri2DInfo(i, a);
  640. if (a.doesContain(p)) {
  641. return true;
  642. }
  643. }
  644. return false;
  645. };
  646. /**
  647. * Make a intersection test between two sets of triangles. The triangles of setB will be transformed to the frame of reference of the setA using the given bToATransform matrix.
  648. * If true is returned at least one triangle intersects with another of the other set, otherwise false is returned.
  649. * @param setA The first set of triangles
  650. * @param setB The second set of triangles
  651. * @param bToATransform The transformation matrix to transform the setB triangles into the frame of reference of the setA
  652. */
  653. Tri2DArray.doesIntersect = function (setA, setB, bToATransform) {
  654. Tri2DArray._checkInitStatics();
  655. var a = Tri2DArray.tempT[0];
  656. var b = Tri2DArray.tempT[1];
  657. var v0 = Tri2DArray.tempV[0];
  658. for (var curB = 0; curB < setB.count; curB++) {
  659. setB.transformAndStoreToTri2DInfo(curB, b, bToATransform);
  660. for (var curA = 0; curA < setA.count; curA++) {
  661. setA.storeToTri2DInfo(curA, a);
  662. // Fast rejection first
  663. v0.x = a.center.x - b.center.x;
  664. v0.y = a.center.y - b.center.y;
  665. if (v0.lengthSquared() > ((a.radius * a.radius) + (b.radius * b.radius))) {
  666. continue;
  667. }
  668. // Actual intersection test
  669. if (Math2D.TriangleTriangleDosIntersect(a.a, a.b, a.c, b.a, b.b, b.c)) {
  670. return true;
  671. }
  672. }
  673. }
  674. return false;
  675. };
  676. Tri2DArray._checkInitStatics = function () {
  677. if (Tri2DArray.tempT !== null) {
  678. return;
  679. }
  680. Tri2DArray.tempT = new Array(2);
  681. Tri2DArray.tempT[0] = new Tri2DInfo(null, null, null);
  682. Tri2DArray.tempT[1] = new Tri2DInfo(null, null, null);
  683. Tri2DArray.tempV = new Array(6);
  684. for (var i = 0; i < 6; i++) {
  685. Tri2DArray.tempV[i] = BABYLON.Vector2.Zero();
  686. }
  687. };
  688. return Tri2DArray;
  689. }());
  690. Tri2DArray.tempV = null;
  691. Tri2DArray.tempT = null;
  692. BABYLON.Tri2DArray = Tri2DArray;
  693. /**
  694. * Some 2D Math helpers functions
  695. */
  696. var Math2D = (function () {
  697. function Math2D() {
  698. }
  699. Math2D.Dot = function (a, b) {
  700. return a.x * b.x + a.y * b.y;
  701. };
  702. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  703. // Note: this one might also be considered with the above one proves to not be good enough: http://jsfiddle.net/justin_c_rounds/Gd2S2/light/
  704. Math2D.LineLineDoesIntersect = function (segA1, segA2, segB1, segB2) {
  705. var s1_x = segA2.x - segA1.x;
  706. var s1_y = segA2.y - segA1.y;
  707. var s2_x = segB2.x - segB1.x;
  708. var s2_y = segB2.y - segB1.y;
  709. var s = (-s1_y * (segA1.x - segB1.x) + s1_x * (segA1.y - segB1.y)) / (-s2_x * s1_y + s1_x * s2_y);
  710. var t = (s2_x * (segA1.y - segB1.y) - s2_y * (segA1.x - segB1.x)) / (-s2_x * s1_y + s1_x * s2_y);
  711. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  712. return true;
  713. }
  714. return false;
  715. };
  716. // From http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
  717. Math2D.LineLineIntersection = function (p0, p1, p2, p3) {
  718. var s1_x = p1.x - p0.x;
  719. var s1_y = p1.y - p0.y;
  720. var s2_x = p3.x - p2.x;
  721. var s2_y = p3.y - p2.y;
  722. var s = (-s1_y * (p0.x - p2.x) + s1_x * (p0.y - p2.y)) / (-s2_x * s1_y + s1_x * s2_y);
  723. var t = (s2_x * (p0.y - p2.y) - s2_y * (p0.x - p2.x)) / (-s2_x * s1_y + s1_x * s2_y);
  724. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
  725. return { res: true, xr: p0.x + (t * s1_x), yr: p0.y + (t * s1_y) };
  726. }
  727. return { res: false, xr: 0, yr: 0 };
  728. };
  729. // Tell me that it's slow and I'll answer: yes it is!
  730. // If you fancy to implement the SAT (Separating Axis Theorem) version: BE MY VERY WELCOMED GUEST!
  731. Math2D.TriangleTriangleDosIntersect = function (tri1A, tri1B, tri1C, tri2A, tri2B, tri2C) {
  732. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2B))
  733. return true;
  734. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2A, tri2C))
  735. return true;
  736. if (Math2D.LineLineDoesIntersect(tri1A, tri1B, tri2B, tri2C))
  737. return true;
  738. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2B))
  739. return true;
  740. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2A, tri2C))
  741. return true;
  742. if (Math2D.LineLineDoesIntersect(tri1A, tri1C, tri2B, tri2C))
  743. return true;
  744. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2B))
  745. return true;
  746. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2A, tri2C))
  747. return true;
  748. if (Math2D.LineLineDoesIntersect(tri1B, tri1C, tri2B, tri2C))
  749. return true;
  750. if (BABYLON.Vector2.PointInTriangle(tri2A, tri1A, tri1B, tri1C) &&
  751. BABYLON.Vector2.PointInTriangle(tri2B, tri1A, tri1B, tri1C) &&
  752. BABYLON.Vector2.PointInTriangle(tri2C, tri1A, tri1B, tri1C))
  753. return true;
  754. if (BABYLON.Vector2.PointInTriangle(tri1A, tri2A, tri2B, tri2C) &&
  755. BABYLON.Vector2.PointInTriangle(tri1B, tri2A, tri2B, tri2C) &&
  756. BABYLON.Vector2.PointInTriangle(tri1C, tri2A, tri2B, tri2C))
  757. return true;
  758. return false;
  759. };
  760. return Math2D;
  761. }());
  762. Math2D.v0 = BABYLON.Vector2.Zero();
  763. Math2D.v1 = BABYLON.Vector2.Zero();
  764. Math2D.v2 = BABYLON.Vector2.Zero();
  765. })(BABYLON || (BABYLON = {}));
  766. //# sourceMappingURL=babylon.math2D.js.map
  767. var BABYLON;
  768. (function (BABYLON) {
  769. var PropertyChangedInfo = (function () {
  770. function PropertyChangedInfo() {
  771. }
  772. return PropertyChangedInfo;
  773. }());
  774. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  775. /**
  776. * The purpose of this class is to provide a base implementation of the IPropertyChanged interface for the user to avoid rewriting a code needlessly.
  777. * Typical use of this class is to check for equality in a property set(), then call the onPropertyChanged method if values are different after the new value is set. The protected method will notify observers of the change.
  778. * Remark: onPropertyChanged detects reentrant code and acts in a way to make sure everything is fine, fast and allocation friendly (when there no reentrant code which should be 99% of the time)
  779. */
  780. var PropertyChangedBase = (function () {
  781. function PropertyChangedBase() {
  782. this._propertyChanged = null;
  783. }
  784. /**
  785. * Protected method to call when there's a change of value in a property set
  786. * @param propName the name of the concerned property
  787. * @param oldValue its old value
  788. * @param newValue its new value
  789. * @param mask an optional observable mask
  790. */
  791. PropertyChangedBase.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  792. if (this.propertyChanged.hasObservers()) {
  793. var pci = PropertyChangedBase.calling ? new PropertyChangedInfo() : PropertyChangedBase.pci;
  794. pci.oldValue = oldValue;
  795. pci.newValue = newValue;
  796. pci.propertyName = propName;
  797. try {
  798. PropertyChangedBase.calling = true;
  799. this.propertyChanged.notifyObservers(pci, mask);
  800. }
  801. finally {
  802. PropertyChangedBase.calling = false;
  803. }
  804. }
  805. };
  806. Object.defineProperty(PropertyChangedBase.prototype, "propertyChanged", {
  807. /**
  808. * An observable that is triggered when a property (using of the XXXXLevelProperty decorator) has its value changing.
  809. * You can add an observer that will be triggered only for a given set of Properties using the Mask feature of the Observable and the corresponding Prim2DPropInfo.flagid value (e.g. Prim2DBase.positionProperty.flagid|Prim2DBase.rotationProperty.flagid to be notified only about position or rotation change)
  810. */
  811. get: function () {
  812. if (!this._propertyChanged) {
  813. this._propertyChanged = new BABYLON.Observable();
  814. }
  815. return this._propertyChanged;
  816. },
  817. enumerable: true,
  818. configurable: true
  819. });
  820. return PropertyChangedBase;
  821. }());
  822. PropertyChangedBase.pci = new PropertyChangedInfo();
  823. PropertyChangedBase.calling = false;
  824. BABYLON.PropertyChangedBase = PropertyChangedBase;
  825. })(BABYLON || (BABYLON = {}));
  826. //# sourceMappingURL=babylon.IPropertyChanged.js.map
  827. var __extends = (this && this.__extends) || function (d, b) {
  828. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  829. function __() { this.constructor = d; }
  830. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  831. };
  832. var BABYLON;
  833. (function (BABYLON) {
  834. /**
  835. * Class for the ObservableArray.onArrayChanged observable
  836. */
  837. var ArrayChanged = (function () {
  838. function ArrayChanged() {
  839. this.action = 0;
  840. this.newItems = new Array();
  841. this.removedItems = new Array();
  842. this.changedItems = new Array();
  843. this.newStartingIndex = -1;
  844. this.removedStartingIndex = -1;
  845. }
  846. Object.defineProperty(ArrayChanged, "clearAction", {
  847. /**
  848. * The content of the array was totally cleared
  849. */
  850. get: function () {
  851. return ArrayChanged._clearAction;
  852. },
  853. enumerable: true,
  854. configurable: true
  855. });
  856. Object.defineProperty(ArrayChanged, "newItemsAction", {
  857. /**
  858. * A new item was added, the newItems field contains the key/value pairs
  859. */
  860. get: function () {
  861. return ArrayChanged._newItemsAction;
  862. },
  863. enumerable: true,
  864. configurable: true
  865. });
  866. Object.defineProperty(ArrayChanged, "removedItemsAction", {
  867. /**
  868. * An existing item was removed, the removedKey field contains its key
  869. */
  870. get: function () {
  871. return ArrayChanged._removedItemsAction;
  872. },
  873. enumerable: true,
  874. configurable: true
  875. });
  876. Object.defineProperty(ArrayChanged, "changedItemAction", {
  877. /**
  878. * One or many items in the array were changed, the
  879. */
  880. get: function () {
  881. return ArrayChanged._changedItemAction;
  882. },
  883. enumerable: true,
  884. configurable: true
  885. });
  886. Object.defineProperty(ArrayChanged, "replacedArrayAction", {
  887. /**
  888. * The array's content was totally changed
  889. * Depending on the method that used this mode the ChangedArray object may contains more information
  890. */
  891. get: function () {
  892. return ArrayChanged._replacedArrayAction;
  893. },
  894. enumerable: true,
  895. configurable: true
  896. });
  897. Object.defineProperty(ArrayChanged, "lengthChangedAction", {
  898. /**
  899. * The length of the array changed
  900. */
  901. get: function () {
  902. return ArrayChanged._lengthChangedAction;
  903. },
  904. enumerable: true,
  905. configurable: true
  906. });
  907. ArrayChanged.prototype.clear = function () {
  908. this.action = 0;
  909. this.newItems.splice(0);
  910. this.removedItems.splice(0);
  911. this.changedItems.splice(0);
  912. this.removedStartingIndex = this.removedStartingIndex = this.changedStartingIndex = 0;
  913. };
  914. return ArrayChanged;
  915. }());
  916. ArrayChanged._clearAction = 0x1;
  917. ArrayChanged._newItemsAction = 0x2;
  918. ArrayChanged._removedItemsAction = 0x4;
  919. ArrayChanged._replacedArrayAction = 0x8;
  920. ArrayChanged._lengthChangedAction = 0x10;
  921. ArrayChanged._changedItemAction = 0x20;
  922. BABYLON.ArrayChanged = ArrayChanged;
  923. var OAWatchedObjectChangedInfo = (function () {
  924. function OAWatchedObjectChangedInfo() {
  925. }
  926. return OAWatchedObjectChangedInfo;
  927. }());
  928. BABYLON.OAWatchedObjectChangedInfo = OAWatchedObjectChangedInfo;
  929. /**
  930. * This class mimics the Javascript Array and TypeScript Array<T> classes, adding new features concerning the Observable pattern.
  931. *
  932. */
  933. var ObservableArray = (function (_super) {
  934. __extends(ObservableArray, _super);
  935. /**
  936. * Create an Observable Array.
  937. * @param watchObjectsPropertyChange
  938. * @param array and optional array that will be encapsulated by this ObservableArray instance. That's right, it's NOT a copy!
  939. */
  940. function ObservableArray(watchObjectsPropertyChange, array) {
  941. var _this = _super.call(this) || this;
  942. _this.dci = new ArrayChanged();
  943. _this._callingArrayChanged = false;
  944. _this._array = (array != null) ? array : new Array();
  945. _this.dci = new ArrayChanged();
  946. _this._callingArrayChanged = false;
  947. _this._arrayChanged = null;
  948. _this._callingWatchedObjectChanged = false;
  949. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  950. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  951. _this._woci = new OAWatchedObjectChangedInfo();
  952. return _this;
  953. }
  954. Object.defineProperty(ObservableArray.prototype, "length", {
  955. /**
  956. * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
  957. */
  958. get: function () {
  959. return this._array.length;
  960. },
  961. set: function (value) {
  962. if (value === this._array.length) {
  963. return;
  964. }
  965. var oldLength = this._array.length;
  966. this._array.length = value;
  967. this.onPropertyChanged("length", oldLength, this._array.length);
  968. },
  969. enumerable: true,
  970. configurable: true
  971. });
  972. ObservableArray.prototype.getAt = function (index) {
  973. return this._array[index];
  974. };
  975. ObservableArray.prototype.setAt = function (index, value) {
  976. if (index < 0) {
  977. return false;
  978. }
  979. var insertion = (index >= this._array.length) || this._array[index] === undefined;
  980. var oldLength = 0;
  981. if (insertion) {
  982. oldLength = this._array.length;
  983. }
  984. else if (this._watchObjectsPropertyChange) {
  985. this._removeWatchedElement(this._array[index]);
  986. }
  987. this._array[index] = value;
  988. if (this._watchObjectsPropertyChange) {
  989. this._addWatchedElement(value);
  990. }
  991. if (insertion) {
  992. this.onPropertyChanged("length", oldLength, this._array.length);
  993. }
  994. var ac = this.getArrayChangedObject();
  995. if (ac) {
  996. ac.action = insertion ? ArrayChanged.newItemsAction : ArrayChanged.changedItemAction;
  997. if (insertion) {
  998. ac.newItems.splice(0, ac.newItems.length, { index: index, value: value });
  999. ac.newStartingIndex = index;
  1000. ac.changedItems.splice(0);
  1001. }
  1002. else {
  1003. ac.newItems.splice(0);
  1004. ac.changedStartingIndex = index;
  1005. ac.changedItems.splice(0, ac.changedItems.length, { index: index, value: value });
  1006. }
  1007. ac.removedItems.splice(0);
  1008. ac.removedStartingIndex = -1;
  1009. this.callArrayChanged(ac);
  1010. }
  1011. };
  1012. /**
  1013. * Returns a string representation of an array.
  1014. */
  1015. ObservableArray.prototype.toString = function () {
  1016. return this._array.toString();
  1017. };
  1018. ObservableArray.prototype.toLocaleString = function () {
  1019. return this._array.toLocaleString();
  1020. };
  1021. /**
  1022. * Appends new elements to an array, and returns the new length of the array.
  1023. * @param items New elements of the Array.
  1024. */
  1025. ObservableArray.prototype.push = function () {
  1026. var items = [];
  1027. for (var _i = 0; _i < arguments.length; _i++) {
  1028. items[_i] = arguments[_i];
  1029. }
  1030. var oldLength = this._array.length;
  1031. var n = (_a = this._array).push.apply(_a, items);
  1032. if (this._watchObjectsPropertyChange) {
  1033. this._addWatchedElement.apply(this, items);
  1034. }
  1035. this.onPropertyChanged("length", oldLength, this._array.length);
  1036. var ac = this.getArrayChangedObject();
  1037. if (ac) {
  1038. ac.action = ArrayChanged.newItemsAction;
  1039. ac.newStartingIndex = oldLength;
  1040. this.feedNotifArray.apply(this, [ac.newItems, oldLength].concat(items));
  1041. this.callArrayChanged(ac);
  1042. }
  1043. return n;
  1044. var _a;
  1045. };
  1046. /**
  1047. * Removes the last element from an array and returns it.
  1048. */
  1049. ObservableArray.prototype.pop = function () {
  1050. var firstRemove = this._array.length - 1;
  1051. var res = this._array.pop();
  1052. if (res && this._watchObjectsPropertyChange) {
  1053. this._removeWatchedElement(res);
  1054. }
  1055. if (firstRemove !== -1) {
  1056. this.onPropertyChanged("length", this._array.length + 1, this._array.length);
  1057. var ac = this.getArrayChangedObject();
  1058. if (ac) {
  1059. ac.action = ArrayChanged.removedItemsAction;
  1060. ac.removedStartingIndex = firstRemove;
  1061. this.feedNotifArray(ac.removedItems, firstRemove, res);
  1062. }
  1063. }
  1064. return res;
  1065. };
  1066. /**
  1067. * Combines two or more arrays.
  1068. * @param items Additional items to add to the end of array1.
  1069. */
  1070. ObservableArray.prototype.concat = function () {
  1071. var items = [];
  1072. for (var _i = 0; _i < arguments.length; _i++) {
  1073. items[_i] = arguments[_i];
  1074. }
  1075. return new ObservableArray(this._watchObjectsPropertyChange, (_a = this._array).concat.apply(_a, items));
  1076. var _a;
  1077. };
  1078. /**
  1079. * Adds all the elements of an array separated by the specified separator string.
  1080. * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma.
  1081. */
  1082. ObservableArray.prototype.join = function (separator) {
  1083. return this._array.join(separator);
  1084. };
  1085. /**
  1086. * Reverses the elements in an Array.
  1087. * The arrayChanged action is
  1088. */
  1089. ObservableArray.prototype.reverse = function () {
  1090. var res = this._array.reverse();
  1091. var ac = this.getArrayChangedObject();
  1092. ac.action = ArrayChanged.replacedArrayAction;
  1093. return res;
  1094. };
  1095. /**
  1096. * Removes the first element from an array and returns it, shift all subsequents element one element before.
  1097. * The ArrayChange action is replacedArrayAction, the whole array changes and must be reevaluate as such, the removed element is in removedItems.
  1098. *
  1099. */
  1100. ObservableArray.prototype.shift = function () {
  1101. var oldLength = this._array.length;
  1102. var res = this._array.shift();
  1103. if (this._watchedObjectChanged && res != null) {
  1104. this._removeWatchedElement(res);
  1105. }
  1106. if (oldLength !== 0) {
  1107. this.onPropertyChanged("length", oldLength, this._array.length);
  1108. var ac = this.getArrayChangedObject();
  1109. if (ac) {
  1110. ac.action = ArrayChanged.replacedArrayAction;
  1111. ac.removedItems.splice(0, ac.removedItems.length, { index: 0, value: res });
  1112. ac.newItems.splice(0);
  1113. ac.changedItems.splice(0);
  1114. ac.removedStartingIndex = 0;
  1115. this.callArrayChanged(ac);
  1116. }
  1117. }
  1118. return res;
  1119. };
  1120. /**
  1121. * Returns a section of an array.
  1122. * @param start The beginning of the specified portion of the array.
  1123. * @param end The end of the specified portion of the array.
  1124. */
  1125. ObservableArray.prototype.slice = function (start, end) {
  1126. return new ObservableArray(this._watchObjectsPropertyChange, this._array.slice(start, end));
  1127. };
  1128. /**
  1129. * Sorts an array.
  1130. * @param compareFn The name of the function used to determine the order of the elements. If omitted, the elements are sorted in ascending, ASCII character order.
  1131. * On the contrary of the Javascript Array's implementation, this method returns nothing
  1132. */
  1133. ObservableArray.prototype.sort = function (compareFn) {
  1134. var oldLength = this._array.length;
  1135. this._array.sort(compareFn);
  1136. if (oldLength !== 0) {
  1137. var ac = this.getArrayChangedObject();
  1138. if (ac) {
  1139. ac.clear();
  1140. ac.action = ArrayChanged.replacedArrayAction;
  1141. this.callArrayChanged(ac);
  1142. }
  1143. }
  1144. };
  1145. /**
  1146. * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
  1147. * @param start The zero-based location in the array from which to start removing elements.
  1148. * @param deleteCount The number of elements to remove.
  1149. * @param items Elements to insert into the array in place of the deleted elements.
  1150. */
  1151. ObservableArray.prototype.splice = function (start, deleteCount) {
  1152. var items = [];
  1153. for (var _i = 2; _i < arguments.length; _i++) {
  1154. items[_i - 2] = arguments[_i];
  1155. }
  1156. var oldLength = this._array.length;
  1157. if (this._watchObjectsPropertyChange) {
  1158. for (var i = start; i < start + deleteCount; i++) {
  1159. var val = this._array[i];
  1160. if (this._watchObjectsPropertyChange && val != null) {
  1161. this._removeWatchedElement(val);
  1162. }
  1163. }
  1164. }
  1165. var res = (_a = this._array).splice.apply(_a, [start, deleteCount].concat(items));
  1166. if (this._watchObjectsPropertyChange) {
  1167. this._addWatchedElement.apply(this, items);
  1168. }
  1169. if (oldLength !== this._array.length) {
  1170. this.onPropertyChanged("length", oldLength, this._array.length);
  1171. }
  1172. var ac = this.getArrayChangedObject();
  1173. if (ac) {
  1174. ac.clear();
  1175. ac.action = ArrayChanged.replacedArrayAction;
  1176. this.callArrayChanged(ac);
  1177. }
  1178. return res;
  1179. var _a;
  1180. };
  1181. /**
  1182. * Inserts new elements at the start of an array.
  1183. * @param items Elements to insert at the start of the Array.
  1184. * The ChangedArray action is replacedArrayAction, newItems contains the list of the added items
  1185. */
  1186. ObservableArray.prototype.unshift = function () {
  1187. var items = [];
  1188. for (var _i = 0; _i < arguments.length; _i++) {
  1189. items[_i] = arguments[_i];
  1190. }
  1191. var oldLength = this._array.length;
  1192. var res = (_a = this._array).unshift.apply(_a, items);
  1193. if (this._watchObjectsPropertyChange) {
  1194. this._addWatchedElement.apply(this, items);
  1195. }
  1196. this.onPropertyChanged("length", oldLength, this._array.length);
  1197. var ac = this.getArrayChangedObject();
  1198. if (ac) {
  1199. ac.clear();
  1200. ac.action = ArrayChanged.replacedArrayAction;
  1201. ac.newStartingIndex = 0, this.feedNotifArray.apply(this, [ac.newItems, 0].concat(items));
  1202. this.callArrayChanged(ac);
  1203. }
  1204. return res;
  1205. var _a;
  1206. };
  1207. /**
  1208. * Returns the index of the first occurrence of a value in an array.
  1209. * @param searchElement The value to locate in the array.
  1210. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
  1211. */
  1212. ObservableArray.prototype.indexOf = function (searchElement, fromIndex) {
  1213. return this._array.indexOf(searchElement, fromIndex);
  1214. };
  1215. /**
  1216. * Returns the index of the last occurrence of a specified value in an array.
  1217. * @param searchElement The value to locate in the array.
  1218. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array.
  1219. */
  1220. ObservableArray.prototype.lastIndexOf = function (searchElement, fromIndex) {
  1221. return this._array.lastIndexOf(searchElement, fromIndex);
  1222. };
  1223. /**
  1224. * Determines whether all the members of an array satisfy the specified test.
  1225. * @param callbackfn A function that accepts up to three arguments. The every method calls the callbackfn function for each element in array1 until the callbackfn returns false, or until the end of the array.
  1226. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1227. */
  1228. ObservableArray.prototype.every = function (callbackfn, thisArg) {
  1229. return this._array.every(callbackfn, thisArg);
  1230. };
  1231. /**
  1232. * Determines whether the specified callback function returns true for any element of an array.
  1233. * @param callbackfn A function that accepts up to three arguments. The some method calls the callbackfn function for each element in array1 until the callbackfn returns true, or until the end of the array.
  1234. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1235. */
  1236. ObservableArray.prototype.some = function (callbackfn, thisArg) {
  1237. return this._array.some(callbackfn, thisArg);
  1238. };
  1239. /**
  1240. * Performs the specified action for each element in an array.
  1241. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
  1242. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1243. */
  1244. ObservableArray.prototype.forEach = function (callbackfn, thisArg) {
  1245. return this._array.forEach(callbackfn, thisArg);
  1246. };
  1247. /**
  1248. * Calls a defined callback function on each element of an array, and returns an array that contains the results.
  1249. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
  1250. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1251. */
  1252. ObservableArray.prototype.map = function (callbackfn, thisArg) {
  1253. return this._array.map(callbackfn, thisArg);
  1254. };
  1255. /**
  1256. * Returns the elements of an array that meet the condition specified in a callback function.
  1257. * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array.
  1258. * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
  1259. */
  1260. ObservableArray.prototype.filter = function (callbackfn, thisArg) {
  1261. return this._array.filter(callbackfn, thisArg);
  1262. };
  1263. /**
  1264. * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
  1265. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array.
  1266. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
  1267. */
  1268. ObservableArray.prototype.reduce = function (callbackfn, initialValue) {
  1269. return this._array.reduce(callbackfn);
  1270. };
  1271. /**
  1272. * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function.
  1273. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array.
  1274. * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value.
  1275. */
  1276. ObservableArray.prototype.reduceRight = function (callbackfn, initialValue) {
  1277. return this._array.reduceRight(callbackfn);
  1278. };
  1279. Object.defineProperty(ObservableArray.prototype, "arrayChanged", {
  1280. get: function () {
  1281. if (!this._arrayChanged) {
  1282. this._arrayChanged = new BABYLON.Observable();
  1283. }
  1284. return this._arrayChanged;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. ObservableArray.prototype.getArrayChangedObject = function () {
  1290. if (this._arrayChanged && this._arrayChanged.hasObservers()) {
  1291. var ac = this._callingArrayChanged ? new ArrayChanged() : this.dci;
  1292. return ac;
  1293. }
  1294. return null;
  1295. };
  1296. ObservableArray.prototype.feedNotifArray = function (array, startindIndex) {
  1297. var items = [];
  1298. for (var _i = 2; _i < arguments.length; _i++) {
  1299. items[_i - 2] = arguments[_i];
  1300. }
  1301. array.splice(0);
  1302. for (var i = 0; i < items.length; i++) {
  1303. var value = this._array[i + startindIndex];
  1304. if (value !== undefined) {
  1305. array.push({ index: i + startindIndex, value: value });
  1306. }
  1307. }
  1308. };
  1309. ObservableArray.prototype.callArrayChanged = function (ac) {
  1310. try {
  1311. this._callingArrayChanged = true;
  1312. this.arrayChanged.notifyObservers(ac, ac.action);
  1313. }
  1314. finally {
  1315. this._callingArrayChanged = false;
  1316. }
  1317. };
  1318. Object.defineProperty(ObservableArray.prototype, "watchedObjectChanged", {
  1319. get: function () {
  1320. if (!this._watchedObjectChanged) {
  1321. this._watchedObjectChanged = new BABYLON.Observable();
  1322. }
  1323. return this._watchedObjectChanged;
  1324. },
  1325. enumerable: true,
  1326. configurable: true
  1327. });
  1328. ObservableArray.prototype._addWatchedElement = function () {
  1329. var _this = this;
  1330. var items = [];
  1331. for (var _i = 0; _i < arguments.length; _i++) {
  1332. items[_i] = arguments[_i];
  1333. }
  1334. var _loop_1 = function (curItem) {
  1335. if (curItem["propertyChanged"]) {
  1336. var key_1 = curItem["__ObsArrayObjID__"];
  1337. // The object may already be part of another ObsArray, so there already be a valid ID
  1338. if (!key_1) {
  1339. key_1 = BABYLON.Tools.RandomId();
  1340. curItem["__ObsArrayObjID__"] = key_1;
  1341. }
  1342. this_1._watchedObjectList.add(key_1, curItem.propertyChanged.add(function (e, d) {
  1343. _this.onWatchedObjectChanged(key_1, curItem, e);
  1344. }));
  1345. }
  1346. };
  1347. var this_1 = this;
  1348. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  1349. var curItem = items_1[_a];
  1350. _loop_1(curItem);
  1351. }
  1352. };
  1353. ObservableArray.prototype._removeWatchedElement = function () {
  1354. var items = [];
  1355. for (var _i = 0; _i < arguments.length; _i++) {
  1356. items[_i] = arguments[_i];
  1357. }
  1358. for (var _a = 0, items_2 = items; _a < items_2.length; _a++) {
  1359. var curItem = items_2[_a];
  1360. var key = curItem["__ObsArrayObjID__"];
  1361. if (key != null) {
  1362. var observer = this._watchedObjectList.getAndRemove(key);
  1363. curItem.propertyChanged.remove(observer);
  1364. }
  1365. }
  1366. };
  1367. ObservableArray.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  1368. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  1369. var woci = this._callingWatchedObjectChanged ? new OAWatchedObjectChangedInfo() : this._woci;
  1370. woci.object = object;
  1371. woci.propertyChanged = propChanged;
  1372. try {
  1373. this._callingWatchedObjectChanged = true;
  1374. this.watchedObjectChanged.notifyObservers(woci);
  1375. }
  1376. finally {
  1377. this._callingWatchedObjectChanged = false;
  1378. }
  1379. }
  1380. };
  1381. return ObservableArray;
  1382. }(BABYLON.PropertyChangedBase));
  1383. BABYLON.ObservableArray = ObservableArray;
  1384. })(BABYLON || (BABYLON = {}));
  1385. //# sourceMappingURL=babylon.observableArray.js.map
  1386. var __extends = (this && this.__extends) || function (d, b) {
  1387. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1388. function __() { this.constructor = d; }
  1389. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1390. };
  1391. var BABYLON;
  1392. (function (BABYLON) {
  1393. /**
  1394. * Class for the ObservableStringDictionary.onDictionaryChanged observable
  1395. */
  1396. var DictionaryChanged = (function () {
  1397. function DictionaryChanged() {
  1398. }
  1399. Object.defineProperty(DictionaryChanged, "clearAction", {
  1400. /**
  1401. * The content of the dictionary was totally cleared
  1402. */
  1403. get: function () {
  1404. return DictionaryChanged._clearAction;
  1405. },
  1406. enumerable: true,
  1407. configurable: true
  1408. });
  1409. Object.defineProperty(DictionaryChanged, "newItemAction", {
  1410. /**
  1411. * A new item was added, the newItem field contains the key/value pair
  1412. */
  1413. get: function () {
  1414. return DictionaryChanged._newItemAction;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. Object.defineProperty(DictionaryChanged, "removedItemAction", {
  1420. /**
  1421. * An existing item was removed, the removedKey field contains its key
  1422. */
  1423. get: function () {
  1424. return DictionaryChanged._removedItemAction;
  1425. },
  1426. enumerable: true,
  1427. configurable: true
  1428. });
  1429. Object.defineProperty(DictionaryChanged, "itemValueChangedAction", {
  1430. /**
  1431. * An existing item had a value change, the changedItem field contains the key/value
  1432. */
  1433. get: function () {
  1434. return DictionaryChanged._itemValueChangedAction;
  1435. },
  1436. enumerable: true,
  1437. configurable: true
  1438. });
  1439. Object.defineProperty(DictionaryChanged, "replacedAction", {
  1440. /**
  1441. * The dictionary's content was reset and replaced by the content of another dictionary.
  1442. * DictionaryChanged<T> contains no further information about this action
  1443. */
  1444. get: function () {
  1445. return DictionaryChanged._replacedAction;
  1446. },
  1447. enumerable: true,
  1448. configurable: true
  1449. });
  1450. return DictionaryChanged;
  1451. }());
  1452. DictionaryChanged._clearAction = 0x1;
  1453. DictionaryChanged._newItemAction = 0x2;
  1454. DictionaryChanged._removedItemAction = 0x4;
  1455. DictionaryChanged._itemValueChangedAction = 0x8;
  1456. DictionaryChanged._replacedAction = 0x10;
  1457. BABYLON.DictionaryChanged = DictionaryChanged;
  1458. var OSDWatchedObjectChangedInfo = (function () {
  1459. function OSDWatchedObjectChangedInfo() {
  1460. }
  1461. return OSDWatchedObjectChangedInfo;
  1462. }());
  1463. BABYLON.OSDWatchedObjectChangedInfo = OSDWatchedObjectChangedInfo;
  1464. var ObservableStringDictionary = (function (_super) {
  1465. __extends(ObservableStringDictionary, _super);
  1466. function ObservableStringDictionary(watchObjectsPropertyChange) {
  1467. var _this = _super.call(this) || this;
  1468. _this._propertyChanged = null;
  1469. _this._dictionaryChanged = null;
  1470. _this.dci = new DictionaryChanged();
  1471. _this._callingDicChanged = false;
  1472. _this._watchedObjectChanged = null;
  1473. _this._callingWatchedObjectChanged = false;
  1474. _this._woci = new OSDWatchedObjectChangedInfo();
  1475. _this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  1476. _this._watchedObjectList = _this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  1477. return _this;
  1478. }
  1479. /**
  1480. * This will clear this dictionary and copy the content from the 'source' one.
  1481. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  1482. * @param source the dictionary to take the content from and copy to this dictionary
  1483. */
  1484. ObservableStringDictionary.prototype.copyFrom = function (source) {
  1485. var _this = this;
  1486. var oldCount = this.count;
  1487. // Don't rely on this class' implementation for clear/add otherwise tons of notification will be thrown
  1488. _super.prototype.clear.call(this);
  1489. source.forEach(function (t, v) { return _this._add(t, v, false, _this._watchObjectsPropertyChange); });
  1490. this.onDictionaryChanged(DictionaryChanged.replacedAction, null, null, null);
  1491. this.onPropertyChanged("count", oldCount, this.count);
  1492. };
  1493. /**
  1494. * Get a value from its key or add it if it doesn't exist.
  1495. * This method will ensure you that a given key/data will be present in the dictionary.
  1496. * @param key the given key to get the matching value from
  1497. * @param factory the factory that will create the value if the key is not present in the dictionary.
  1498. * The factory will only be invoked if there's no data for the given key.
  1499. * @return the value corresponding to the key.
  1500. */
  1501. ObservableStringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  1502. var _this = this;
  1503. var val = _super.prototype.getOrAddWithFactory.call(this, key, function (k) {
  1504. var v = factory(key);
  1505. _this._add(key, v, true, _this._watchObjectsPropertyChange);
  1506. return v;
  1507. });
  1508. return val;
  1509. };
  1510. /**
  1511. * Add a new key and its corresponding value
  1512. * @param key the key to add
  1513. * @param value the value corresponding to the key
  1514. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  1515. */
  1516. ObservableStringDictionary.prototype.add = function (key, value) {
  1517. return this._add(key, value, true, this._watchObjectsPropertyChange);
  1518. };
  1519. ObservableStringDictionary.prototype.getAndRemove = function (key) {
  1520. var val = _super.prototype.get.call(this, key);
  1521. this._remove(key, true, val);
  1522. return val;
  1523. };
  1524. ObservableStringDictionary.prototype._add = function (key, value, fireNotif, registerWatcher) {
  1525. if (_super.prototype.add.call(this, key, value)) {
  1526. if (fireNotif) {
  1527. this.onDictionaryChanged(DictionaryChanged.newItemAction, { key: key, value: value }, null, null);
  1528. this.onPropertyChanged("count", this.count - 1, this.count);
  1529. }
  1530. if (registerWatcher) {
  1531. this._addWatchedElement(key, value);
  1532. }
  1533. return true;
  1534. }
  1535. return false;
  1536. };
  1537. ObservableStringDictionary.prototype._addWatchedElement = function (key, el) {
  1538. var _this = this;
  1539. if (el["propertyChanged"]) {
  1540. this._watchedObjectList.add(key, el.propertyChanged.add(function (e, d) {
  1541. _this.onWatchedObjectChanged(key, el, e);
  1542. }));
  1543. }
  1544. };
  1545. ObservableStringDictionary.prototype._removeWatchedElement = function (key, el) {
  1546. var observer = this._watchedObjectList.getAndRemove(key);
  1547. if (el["propertyChanged"]) {
  1548. el.propertyChanged.remove(observer);
  1549. }
  1550. };
  1551. ObservableStringDictionary.prototype.set = function (key, value) {
  1552. var oldValue = this.get(key);
  1553. if (this._watchObjectsPropertyChange) {
  1554. this._removeWatchedElement(key, oldValue);
  1555. }
  1556. if (_super.prototype.set.call(this, key, value)) {
  1557. this.onDictionaryChanged(DictionaryChanged.itemValueChangedAction, null, null, { key: key, oldValue: oldValue, newValue: value });
  1558. this._addWatchedElement(key, value);
  1559. return true;
  1560. }
  1561. return false;
  1562. };
  1563. /**
  1564. * Remove a key/value from the dictionary.
  1565. * @param key the key to remove
  1566. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  1567. */
  1568. ObservableStringDictionary.prototype.remove = function (key) {
  1569. return this._remove(key, true);
  1570. };
  1571. ObservableStringDictionary.prototype._remove = function (key, fireNotif, element) {
  1572. if (!element) {
  1573. element = this.get(key);
  1574. }
  1575. if (!element) {
  1576. return false;
  1577. }
  1578. if (_super.prototype.remove.call(this, key) === undefined) {
  1579. return false;
  1580. }
  1581. this.onDictionaryChanged(DictionaryChanged.removedItemAction, null, key, null);
  1582. this.onPropertyChanged("count", this.count + 1, this.count);
  1583. if (this._watchObjectsPropertyChange) {
  1584. this._removeWatchedElement(key, element);
  1585. }
  1586. return true;
  1587. };
  1588. /**
  1589. * Clear the whole content of the dictionary
  1590. */
  1591. ObservableStringDictionary.prototype.clear = function () {
  1592. var _this = this;
  1593. if (this._watchedObjectList) {
  1594. this._watchedObjectList.forEach(function (k, v) {
  1595. var el = _this.get(k);
  1596. _this._removeWatchedElement(k, el);
  1597. });
  1598. this._watchedObjectList.clear();
  1599. }
  1600. var oldCount = this.count;
  1601. _super.prototype.clear.call(this);
  1602. this.onDictionaryChanged(DictionaryChanged.clearAction, null, null, null);
  1603. this.onPropertyChanged("count", oldCount, 0);
  1604. };
  1605. Object.defineProperty(ObservableStringDictionary.prototype, "propertyChanged", {
  1606. get: function () {
  1607. if (!this._propertyChanged) {
  1608. this._propertyChanged = new BABYLON.Observable();
  1609. }
  1610. return this._propertyChanged;
  1611. },
  1612. enumerable: true,
  1613. configurable: true
  1614. });
  1615. ObservableStringDictionary.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  1616. if (this._propertyChanged && this._propertyChanged.hasObservers()) {
  1617. var pci = ObservableStringDictionary.callingPropChanged ? new BABYLON.PropertyChangedInfo() : ObservableStringDictionary.pci;
  1618. pci.oldValue = oldValue;
  1619. pci.newValue = newValue;
  1620. pci.propertyName = propName;
  1621. try {
  1622. ObservableStringDictionary.callingPropChanged = true;
  1623. this.propertyChanged.notifyObservers(pci, mask);
  1624. }
  1625. finally {
  1626. ObservableStringDictionary.callingPropChanged = false;
  1627. }
  1628. }
  1629. };
  1630. Object.defineProperty(ObservableStringDictionary.prototype, "dictionaryChanged", {
  1631. get: function () {
  1632. if (!this._dictionaryChanged) {
  1633. this._dictionaryChanged = new BABYLON.Observable();
  1634. }
  1635. return this._dictionaryChanged;
  1636. },
  1637. enumerable: true,
  1638. configurable: true
  1639. });
  1640. ObservableStringDictionary.prototype.onDictionaryChanged = function (action, newItem, removedKey, changedItem) {
  1641. if (this._dictionaryChanged && this._dictionaryChanged.hasObservers()) {
  1642. var dci = this._callingDicChanged ? new DictionaryChanged() : this.dci;
  1643. dci.action = action;
  1644. dci.newItem = newItem;
  1645. dci.removedKey = removedKey;
  1646. dci.changedItem = changedItem;
  1647. try {
  1648. this._callingDicChanged = true;
  1649. this.dictionaryChanged.notifyObservers(dci, action);
  1650. }
  1651. finally {
  1652. this._callingDicChanged = false;
  1653. }
  1654. }
  1655. };
  1656. Object.defineProperty(ObservableStringDictionary.prototype, "watchedObjectChanged", {
  1657. get: function () {
  1658. if (!this._watchedObjectChanged) {
  1659. this._watchedObjectChanged = new BABYLON.Observable();
  1660. }
  1661. return this._watchedObjectChanged;
  1662. },
  1663. enumerable: true,
  1664. configurable: true
  1665. });
  1666. ObservableStringDictionary.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  1667. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  1668. var woci = this._callingWatchedObjectChanged ? new OSDWatchedObjectChangedInfo() : this._woci;
  1669. woci.key = key;
  1670. woci.object = object;
  1671. woci.propertyChanged = propChanged;
  1672. try {
  1673. this._callingWatchedObjectChanged = true;
  1674. this.watchedObjectChanged.notifyObservers(woci);
  1675. }
  1676. finally {
  1677. this._callingWatchedObjectChanged = false;
  1678. }
  1679. }
  1680. };
  1681. return ObservableStringDictionary;
  1682. }(BABYLON.StringDictionary));
  1683. ObservableStringDictionary.pci = new BABYLON.PropertyChangedInfo();
  1684. ObservableStringDictionary.callingPropChanged = false;
  1685. BABYLON.ObservableStringDictionary = ObservableStringDictionary;
  1686. })(BABYLON || (BABYLON = {}));
  1687. //# sourceMappingURL=babylon.observableStringDictionary.js.map
  1688. var __extends = (this && this.__extends) || function (d, b) {
  1689. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1690. function __() { this.constructor = d; }
  1691. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1692. };
  1693. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  1694. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  1695. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  1696. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  1697. return c > 3 && r && Object.defineProperty(target, key, r), r;
  1698. };
  1699. var BABYLON;
  1700. (function (BABYLON) {
  1701. /**
  1702. * This class given information about a given character.
  1703. */
  1704. var CharInfo = (function () {
  1705. function CharInfo() {
  1706. }
  1707. return CharInfo;
  1708. }());
  1709. BABYLON.CharInfo = CharInfo;
  1710. /**
  1711. * This is an abstract base class to hold a Texture that will contain a FontMap
  1712. */
  1713. var BaseFontTexture = (function (_super) {
  1714. __extends(BaseFontTexture, _super);
  1715. function BaseFontTexture(url, scene, noMipmap, invertY, samplingMode) {
  1716. if (noMipmap === void 0) { noMipmap = false; }
  1717. if (invertY === void 0) { invertY = true; }
  1718. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1719. var _this = _super.call(this, url, scene, noMipmap, invertY, samplingMode) || this;
  1720. _this._cachedFontId = null;
  1721. _this._charInfos = new BABYLON.StringDictionary();
  1722. return _this;
  1723. }
  1724. Object.defineProperty(BaseFontTexture.prototype, "isSuperSampled", {
  1725. /**
  1726. * Is the Font is using Super Sampling (each font texel is doubled).
  1727. */
  1728. get: function () {
  1729. return this._superSample;
  1730. },
  1731. enumerable: true,
  1732. configurable: true
  1733. });
  1734. Object.defineProperty(BaseFontTexture.prototype, "isSignedDistanceField", {
  1735. /**
  1736. * Is the Font was rendered using the Signed Distance Field algorithm
  1737. * @returns {}
  1738. */
  1739. get: function () {
  1740. return this._signedDistanceField;
  1741. },
  1742. enumerable: true,
  1743. configurable: true
  1744. });
  1745. Object.defineProperty(BaseFontTexture.prototype, "spaceWidth", {
  1746. /**
  1747. * Get the Width (in pixel) of the Space character
  1748. */
  1749. get: function () {
  1750. return this._spaceWidth;
  1751. },
  1752. enumerable: true,
  1753. configurable: true
  1754. });
  1755. Object.defineProperty(BaseFontTexture.prototype, "lineHeight", {
  1756. /**
  1757. * Get the Line height (in pixel)
  1758. */
  1759. get: function () {
  1760. return this._lineHeight;
  1761. },
  1762. enumerable: true,
  1763. configurable: true
  1764. });
  1765. /**
  1766. * Measure the width/height that will take a given text
  1767. * @param text the text to measure
  1768. * @param tabulationSize the size (in space character) of the tabulation character, default value must be 4
  1769. */
  1770. BaseFontTexture.prototype.measureText = function (text, tabulationSize) {
  1771. var maxWidth = 0;
  1772. var curWidth = 0;
  1773. var lineCount = 1;
  1774. var charxpos = 0;
  1775. // Parse each char of the string
  1776. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  1777. var char = text_1[_i];
  1778. // Next line feed?
  1779. if (char === "\n") {
  1780. maxWidth = Math.max(maxWidth, curWidth);
  1781. charxpos = 0;
  1782. curWidth = 0;
  1783. ++lineCount;
  1784. continue;
  1785. }
  1786. // Tabulation ?
  1787. if (char === "\t") {
  1788. var nextPos = charxpos + tabulationSize;
  1789. nextPos = nextPos - (nextPos % tabulationSize);
  1790. curWidth += (nextPos - charxpos) * this.spaceWidth;
  1791. charxpos = nextPos;
  1792. continue;
  1793. }
  1794. if (char < " ") {
  1795. continue;
  1796. }
  1797. var ci = this.getChar(char);
  1798. if (!ci) {
  1799. throw new Error("Character " + char + " is not supported by FontTexture " + this.name);
  1800. }
  1801. curWidth += ci.charWidth;
  1802. ++charxpos;
  1803. }
  1804. maxWidth = Math.max(maxWidth, curWidth);
  1805. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  1806. };
  1807. return BaseFontTexture;
  1808. }(BABYLON.Texture));
  1809. BABYLON.BaseFontTexture = BaseFontTexture;
  1810. var BitmapFontInfo = (function () {
  1811. function BitmapFontInfo() {
  1812. this.kerningDic = new BABYLON.StringDictionary();
  1813. this.charDic = new BABYLON.StringDictionary();
  1814. }
  1815. return BitmapFontInfo;
  1816. }());
  1817. BABYLON.BitmapFontInfo = BitmapFontInfo;
  1818. var BitmapFontTexture = (function (_super) {
  1819. __extends(BitmapFontTexture, _super);
  1820. function BitmapFontTexture(scene, bmFontUrl, textureUrl, noMipmap, invertY, samplingMode, onLoad, onError) {
  1821. if (textureUrl === void 0) { textureUrl = null; }
  1822. if (noMipmap === void 0) { noMipmap = false; }
  1823. if (invertY === void 0) { invertY = true; }
  1824. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1825. if (onLoad === void 0) { onLoad = null; }
  1826. if (onError === void 0) { onError = null; }
  1827. var _this = _super.call(this, null, scene, noMipmap, invertY, samplingMode) || this;
  1828. _this._usedCounter = 1;
  1829. var xhr = new XMLHttpRequest();
  1830. xhr.onreadystatechange = function () {
  1831. if (xhr.readyState === XMLHttpRequest.DONE) {
  1832. if (xhr.status === 200) {
  1833. var ext = bmFontUrl.split('.').pop().split(/\#|\?/)[0];
  1834. var plugins = BitmapFontTexture.plugins.get(ext.toLocaleLowerCase());
  1835. if (!plugins) {
  1836. if (onError) {
  1837. onError("couldn't find a plugin for this file extension", -1);
  1838. }
  1839. return;
  1840. }
  1841. var _loop_1 = function (p) {
  1842. var ret = p.loadFont(xhr.response, scene, invertY);
  1843. if (ret) {
  1844. var bfi = ret.bfi;
  1845. if (textureUrl != null) {
  1846. bfi.textureUrl = textureUrl;
  1847. }
  1848. else {
  1849. var baseUrl = bmFontUrl.substr(0, bmFontUrl.lastIndexOf("/") + 1);
  1850. bfi.textureUrl = baseUrl + bfi.textureFile;
  1851. }
  1852. _this._texture = scene.getEngine().createTexture(bfi.textureUrl, noMipmap, invertY, scene, samplingMode, function () {
  1853. if (ret.bfi && onLoad) {
  1854. onLoad();
  1855. }
  1856. });
  1857. _this._lineHeight = bfi.lineHeight;
  1858. _this._charInfos.copyFrom(bfi.charDic);
  1859. var ci = _this.getChar(" ");
  1860. if (ci) {
  1861. _this._spaceWidth = ci.charWidth;
  1862. }
  1863. else {
  1864. _this._charInfos.first(function (k, v) { return _this._spaceWidth = v.charWidth; });
  1865. }
  1866. if (!ret.bfi && onError) {
  1867. onError(ret.errorMsg, ret.errorCode);
  1868. }
  1869. return { value: void 0 };
  1870. }
  1871. };
  1872. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  1873. var p = plugins_1[_i];
  1874. var state_1 = _loop_1(p);
  1875. if (typeof state_1 === "object")
  1876. return state_1.value;
  1877. }
  1878. if (onError) {
  1879. onError("No plugin to load this BMFont file format", -1);
  1880. }
  1881. }
  1882. else {
  1883. if (onError) {
  1884. onError("Couldn't load file through HTTP Request, HTTP Status " + xhr.status, xhr.status);
  1885. }
  1886. }
  1887. }
  1888. };
  1889. xhr.open("GET", bmFontUrl, true);
  1890. xhr.send();
  1891. return _this;
  1892. }
  1893. BitmapFontTexture.GetCachedFontTexture = function (scene, fontTexture) {
  1894. var dic = scene.getOrAddExternalDataWithFactory("BitmapFontTextureCache", function () { return new BABYLON.StringDictionary(); });
  1895. var ft = dic.get(fontTexture.uid);
  1896. if (ft) {
  1897. ++ft._usedCounter;
  1898. return ft;
  1899. }
  1900. dic.add(fontTexture.uid, fontTexture);
  1901. return ft;
  1902. };
  1903. BitmapFontTexture.ReleaseCachedFontTexture = function (scene, fontTexture) {
  1904. var dic = scene.getExternalData("BitmapFontTextureCache");
  1905. if (!dic) {
  1906. return;
  1907. }
  1908. var font = dic.get(fontTexture.uid);
  1909. if (--font._usedCounter === 0) {
  1910. dic.remove(fontTexture.uid);
  1911. font.dispose();
  1912. }
  1913. };
  1914. Object.defineProperty(BitmapFontTexture.prototype, "isDynamicFontTexture", {
  1915. /**
  1916. * Is the font dynamically updated, if true is returned then you have to call the update() before using the font in rendering if new character were adding using getChar()
  1917. */
  1918. get: function () {
  1919. return false;
  1920. },
  1921. enumerable: true,
  1922. configurable: true
  1923. });
  1924. /**
  1925. * This method does nothing for a BitmapFontTexture object as it's a static texture
  1926. */
  1927. BitmapFontTexture.prototype.update = function () {
  1928. };
  1929. /**
  1930. * Retrieve the CharInfo object for a given character
  1931. * @param char the character to retrieve the CharInfo object from (e.g.: "A", "a", etc.)
  1932. */
  1933. BitmapFontTexture.prototype.getChar = function (char) {
  1934. return this._charInfos.get(char);
  1935. };
  1936. /**
  1937. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  1938. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  1939. */
  1940. BitmapFontTexture.prototype.incCachedFontTextureCounter = function () {
  1941. ++this._usedCounter;
  1942. };
  1943. /**
  1944. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  1945. */
  1946. BitmapFontTexture.prototype.decCachedFontTextureCounter = function () {
  1947. var dic = this.getScene().getExternalData("BitmapFontTextureCache");
  1948. if (!dic) {
  1949. return;
  1950. }
  1951. if (--this._usedCounter === 0) {
  1952. dic.remove(this._cachedFontId);
  1953. this.dispose();
  1954. }
  1955. };
  1956. BitmapFontTexture.addLoader = function (fileExtension, plugin) {
  1957. var a = BitmapFontTexture.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  1958. a.push(plugin);
  1959. };
  1960. return BitmapFontTexture;
  1961. }(BaseFontTexture));
  1962. BitmapFontTexture.plugins = new BABYLON.StringDictionary();
  1963. BABYLON.BitmapFontTexture = BitmapFontTexture;
  1964. /**
  1965. * This class is a special kind of texture which generates on the fly characters of a given css style "fontName".
  1966. * The generated texture will be updated when new characters will be retrieved using the getChar() method, but you have
  1967. * to call the update() method for the texture to fetch these changes, you can harmlessly call update any time you want, if no
  1968. * change were made, nothing will happen.
  1969. * The Font Texture can be rendered in three modes: normal size, super sampled size (x2) or using Signed Distance Field rendering.
  1970. * Signed Distance Field should be prefered because the texture can be rendered using AlphaTest instead of Transparency, which is way more faster. More about SDF here (http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf).
  1971. * The only flaw of SDF is that the rendering quality may not be the best or the edges too sharp is the font thickness is too thin.
  1972. */
  1973. var FontTexture = (function (_super) {
  1974. __extends(FontTexture, _super);
  1975. /**
  1976. * Create a new instance of the FontTexture class
  1977. * @param name the name of the texture
  1978. * @param font the font to use, use the W3C CSS notation
  1979. * @param scene the scene that owns the texture
  1980. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  1981. * @param samplingMode the texture sampling mode
  1982. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  1983. */
  1984. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  1985. if (maxCharCount === void 0) { maxCharCount = 200; }
  1986. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  1987. if (superSample === void 0) { superSample = false; }
  1988. if (signedDistanceField === void 0) { signedDistanceField = false; }
  1989. var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
  1990. _this._curCharCount = 0;
  1991. _this._lastUpdateCharCount = -1;
  1992. _this._usedCounter = 1;
  1993. _this.name = name;
  1994. _this.debugMode = false;
  1995. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  1996. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  1997. _this._sdfScale = 8;
  1998. _this._signedDistanceField = signedDistanceField;
  1999. _this._superSample = false;
  2000. // SDF will use super sample no matter what, the resolution is otherwise too poor to produce correct result
  2001. if (superSample || signedDistanceField) {
  2002. var sfont = _this.getSuperSampleFont(font);
  2003. if (sfont) {
  2004. _this._superSample = true;
  2005. font = sfont;
  2006. }
  2007. }
  2008. // First canvas creation to determine the size of the texture to create
  2009. _this._canvas = document.createElement("canvas");
  2010. _this._context = _this._canvas.getContext("2d");
  2011. _this._context.font = font;
  2012. _this._context.fillStyle = "white";
  2013. _this._context.textBaseline = "top";
  2014. var res = _this.getFontHeight(font, "j$|");
  2015. _this._lineHeightSuper = res.height; //+4;
  2016. _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
  2017. _this._offset = res.offset;
  2018. res = _this.getFontHeight(font, "f");
  2019. _this._baseLine = res.height + res.offset - _this._offset;
  2020. var maxCharWidth = Math.max(_this._context.measureText("W").width, _this._context.measureText("_").width);
  2021. _this._spaceWidthSuper = _this._context.measureText(" ").width;
  2022. _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
  2023. _this._xMargin = Math.ceil(maxCharWidth / 32);
  2024. _this._yMargin = _this._xMargin;
  2025. // This is an approximate size, but should always be able to fit at least the maxCharCount
  2026. var totalEstSurface = (Math.ceil(_this._lineHeightSuper) + (_this._yMargin * 2)) * (Math.ceil(maxCharWidth) + (_this._xMargin * 2)) * maxCharCount;
  2027. var edge = Math.sqrt(totalEstSurface);
  2028. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  2029. // Create the texture that will store the font characters
  2030. _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  2031. var textureSize = _this.getSize();
  2032. _this.hasAlpha = _this._signedDistanceField === false;
  2033. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  2034. _this._canvas = document.createElement("canvas");
  2035. _this._canvas.width = textureSize.width;
  2036. _this._canvas.height = textureSize.height;
  2037. _this._context = _this._canvas.getContext("2d");
  2038. _this._context.textBaseline = "top";
  2039. _this._context.font = font;
  2040. _this._context.fillStyle = "white";
  2041. _this._context.imageSmoothingEnabled = false;
  2042. _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  2043. // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
  2044. // into this 2D context, then get the bitmap data, create the SDF char and push the result in the _context (which hold the whole Font Texture content)
  2045. // So you can see this context as an intermediate one, because it is.
  2046. if (_this._signedDistanceField) {
  2047. var sdfC = document.createElement("canvas");
  2048. var s = _this._sdfScale;
  2049. sdfC.width = (Math.ceil(maxCharWidth) + _this._xMargin * 2) * s;
  2050. sdfC.height = (Math.ceil(_this._lineHeightSuper) + _this._yMargin * 2) * s;
  2051. var sdfCtx = sdfC.getContext("2d");
  2052. sdfCtx.scale(s, s);
  2053. sdfCtx.textBaseline = "top";
  2054. sdfCtx.font = font;
  2055. sdfCtx.fillStyle = "white";
  2056. sdfCtx.imageSmoothingEnabled = false;
  2057. _this._sdfCanvas = sdfC;
  2058. _this._sdfContext = sdfCtx;
  2059. }
  2060. _this._currentFreePosition = BABYLON.Vector2.Zero();
  2061. // Add the basic ASCII based characters
  2062. for (var i = 0x20; i < 0x7F; i++) {
  2063. var c = String.fromCharCode(i);
  2064. _this.getChar(c);
  2065. }
  2066. _this.update();
  2067. return _this;
  2068. }
  2069. Object.defineProperty(FontTexture.prototype, "isDynamicFontTexture", {
  2070. get: function () {
  2071. return true;
  2072. },
  2073. enumerable: true,
  2074. configurable: true
  2075. });
  2076. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  2077. if (supersample === void 0) { supersample = false; }
  2078. if (signedDistanceField === void 0) { signedDistanceField = false; }
  2079. var dic = scene.getOrAddExternalDataWithFactory("FontTextureCache", function () { return new BABYLON.StringDictionary(); });
  2080. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  2081. var ft = dic.get(lfn);
  2082. if (ft) {
  2083. ++ft._usedCounter;
  2084. return ft;
  2085. }
  2086. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  2087. ft._cachedFontId = lfn;
  2088. dic.add(lfn, ft);
  2089. return ft;
  2090. };
  2091. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  2092. if (supersample === void 0) { supersample = false; }
  2093. if (signedDistanceField === void 0) { signedDistanceField = false; }
  2094. var dic = scene.getExternalData("FontTextureCache");
  2095. if (!dic) {
  2096. return;
  2097. }
  2098. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  2099. var font = dic.get(lfn);
  2100. if (--font._usedCounter === 0) {
  2101. dic.remove(lfn);
  2102. font.dispose();
  2103. }
  2104. };
  2105. /**
  2106. * Make sure the given char is present in the font map.
  2107. * @param char the character to get or add
  2108. * @return the CharInfo instance corresponding to the given character
  2109. */
  2110. FontTexture.prototype.getChar = function (char) {
  2111. var _this = this;
  2112. if (char.length !== 1) {
  2113. return null;
  2114. }
  2115. var info = this._charInfos.get(char);
  2116. if (info) {
  2117. return info;
  2118. }
  2119. info = new CharInfo();
  2120. var measure = this._context.measureText(char);
  2121. var textureSize = this.getSize();
  2122. // we reached the end of the current line?
  2123. var width = Math.ceil(measure.width);
  2124. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  2125. this._currentFreePosition.x = 0;
  2126. this._currentFreePosition.y += Math.ceil(this._lineHeightSuper + this._yMargin * 2);
  2127. // No more room?
  2128. if (this._currentFreePosition.y > textureSize.height) {
  2129. return this.getChar("!");
  2130. }
  2131. }
  2132. var curPosX = this._currentFreePosition.x + 0.5;
  2133. var curPosY = this._currentFreePosition.y + 0.5;
  2134. var curPosXMargin = curPosX + this._xMargin;
  2135. var curPosYMargin = curPosY + this._yMargin;
  2136. var drawDebug = function (ctx) {
  2137. ctx.strokeStyle = "green";
  2138. ctx.beginPath();
  2139. ctx.rect(curPosXMargin, curPosYMargin, width, _this._lineHeightSuper);
  2140. ctx.closePath();
  2141. ctx.stroke();
  2142. ctx.strokeStyle = "blue";
  2143. ctx.beginPath();
  2144. ctx.moveTo(curPosXMargin, curPosYMargin + Math.round(_this._baseLine));
  2145. ctx.lineTo(curPosXMargin + width, curPosYMargin + Math.round(_this._baseLine));
  2146. ctx.closePath();
  2147. ctx.stroke();
  2148. };
  2149. // 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)
  2150. if (this._signedDistanceField) {
  2151. var s = this._sdfScale;
  2152. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  2153. // Coordinates are subject to the context's scale
  2154. this._sdfContext.fillText(char, this._xMargin + 0.5, this._yMargin + 0.5 - this._offset);
  2155. // Canvas Pixel Coordinates, no scale
  2156. var data = this._sdfContext.getImageData(0, 0, (width + (this._xMargin * 2)) * s, this._sdfCanvas.height);
  2157. var res = this._computeSDFChar(data);
  2158. this._context.putImageData(res, curPosX, curPosY);
  2159. if (this.debugMode) {
  2160. drawDebug(this._context);
  2161. }
  2162. }
  2163. else {
  2164. if (this.debugMode) {
  2165. drawDebug(this._context);
  2166. }
  2167. // Draw the character in the HTML canvas
  2168. this._context.fillText(char, curPosXMargin, curPosYMargin - this._offset);
  2169. }
  2170. // Fill the CharInfo object
  2171. info.topLeftUV = new BABYLON.Vector2((curPosXMargin) / textureSize.width, (this._currentFreePosition.y + this._yMargin) / textureSize.height);
  2172. info.bottomRightUV = new BABYLON.Vector2((curPosXMargin + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + this._yMargin) / textureSize.height));
  2173. info.yOffset = info.xOffset = 0;
  2174. if (this._signedDistanceField) {
  2175. var off = 1 / textureSize.width;
  2176. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  2177. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  2178. }
  2179. info.charWidth = this._superSample ? (width / 2) : width;
  2180. info.xAdvance = info.charWidth;
  2181. // Add the info structure
  2182. this._charInfos.add(char, info);
  2183. this._curCharCount++;
  2184. // Set the next position
  2185. this._currentFreePosition.x += Math.ceil(width + this._xMargin * 2);
  2186. return info;
  2187. };
  2188. FontTexture.prototype._computeSDFChar = function (source) {
  2189. var scl = this._sdfScale;
  2190. var sw = source.width;
  2191. var sh = source.height;
  2192. var dw = sw / scl;
  2193. var dh = sh / scl;
  2194. var roffx = 0;
  2195. var roffy = 0;
  2196. // We shouldn't look beyond half of the biggest between width and height
  2197. var radius = scl;
  2198. var br = radius - 1;
  2199. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  2200. var sx = dx * scl;
  2201. var sy = dy * scl;
  2202. // Looking out of the area? return true to make the test going on
  2203. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  2204. return true;
  2205. }
  2206. // Get the pixel we want
  2207. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  2208. var res = (val > 0) === lookVis;
  2209. if (!res) {
  2210. roffx = offX;
  2211. roffy = offY;
  2212. }
  2213. return res;
  2214. };
  2215. var lookupArea = function (dx, dy, lookVis) {
  2216. // 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
  2217. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  2218. lookupSrc(dx, dy, 0, -br, lookVis) &&
  2219. lookupSrc(dx, dy, -br, 0, lookVis) &&
  2220. lookupSrc(dx, dy, br, 0, lookVis)) {
  2221. return 0;
  2222. }
  2223. for (var i = 1; i <= radius; i++) {
  2224. // Quick test N, S, W, E
  2225. 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)) {
  2226. return i * i; // Squared Distance is simple to compute in this case
  2227. }
  2228. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  2229. for (var j = 1; j <= i; j++) {
  2230. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  2231. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  2232. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  2233. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  2234. // We found the nearest texel having and opposite state, store the squared length
  2235. var res_1 = (i * i) + (j * j);
  2236. var count = 1;
  2237. // 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
  2238. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  2239. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  2240. ++count;
  2241. }
  2242. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  2243. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  2244. ++count;
  2245. }
  2246. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  2247. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  2248. ++count;
  2249. }
  2250. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  2251. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  2252. ++count;
  2253. }
  2254. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  2255. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  2256. ++count;
  2257. }
  2258. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  2259. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  2260. ++count;
  2261. }
  2262. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  2263. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  2264. ++count;
  2265. }
  2266. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  2267. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  2268. ++count;
  2269. }
  2270. // Compute the average based on the accumulated distance
  2271. return res_1 / count;
  2272. }
  2273. }
  2274. }
  2275. return 0;
  2276. };
  2277. var tmp = new Array(dw * dh);
  2278. for (var y = 0; y < dh; y++) {
  2279. for (var x = 0; x < dw; x++) {
  2280. var curState = lookupSrc(x, y, 0, 0, true);
  2281. var d = lookupArea(x, y, curState);
  2282. if (d === 0) {
  2283. d = radius * radius * 2;
  2284. }
  2285. tmp[(y * dw) + x] = curState ? d : -d;
  2286. }
  2287. }
  2288. var res = this._context.createImageData(dw, dh);
  2289. var size = dw * dh;
  2290. for (var j = 0; j < size; j++) {
  2291. var d = tmp[j];
  2292. var sign = (d < 0) ? -1 : 1;
  2293. d = Math.sqrt(Math.abs(d)) * sign;
  2294. d *= 127.5 / radius;
  2295. d += 127.5;
  2296. if (d < 0) {
  2297. d = 0;
  2298. }
  2299. else if (d > 255) {
  2300. d = 255;
  2301. }
  2302. d += 0.5;
  2303. res.data[j * 4 + 0] = d;
  2304. res.data[j * 4 + 1] = d;
  2305. res.data[j * 4 + 2] = d;
  2306. res.data[j * 4 + 3] = 255;
  2307. }
  2308. return res;
  2309. };
  2310. FontTexture.prototype.getSuperSampleFont = function (font) {
  2311. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  2312. 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*$/;
  2313. var res = font.toLocaleLowerCase().match(regex);
  2314. if (res == null) {
  2315. return null;
  2316. }
  2317. var size = parseInt(res[4]);
  2318. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  2319. var newFont = "";
  2320. for (var j = 1; j < res.length; j++) {
  2321. if (res[j] != null) {
  2322. newFont += res[j] + " ";
  2323. }
  2324. }
  2325. return newFont;
  2326. };
  2327. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  2328. FontTexture.prototype.getFontHeight = function (font, chars) {
  2329. var fontDraw = document.createElement("canvas");
  2330. fontDraw.width = 600;
  2331. fontDraw.height = 600;
  2332. var ctx = fontDraw.getContext('2d');
  2333. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  2334. ctx.textBaseline = 'top';
  2335. ctx.fillStyle = 'white';
  2336. ctx.font = font;
  2337. ctx.fillText(chars, 0, 0);
  2338. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  2339. var start = -1;
  2340. var end = -1;
  2341. for (var row = 0; row < fontDraw.height; row++) {
  2342. for (var column = 0; column < fontDraw.width; column++) {
  2343. var index = (row * fontDraw.width + column) * 4;
  2344. if (pixels[index] === 0) {
  2345. if (column === fontDraw.width - 1 && start !== -1) {
  2346. end = row;
  2347. row = fontDraw.height;
  2348. break;
  2349. }
  2350. continue;
  2351. }
  2352. else {
  2353. if (start === -1) {
  2354. start = row;
  2355. }
  2356. break;
  2357. }
  2358. }
  2359. }
  2360. return { height: (end - start) + 1, offset: start };
  2361. };
  2362. Object.defineProperty(FontTexture.prototype, "canRescale", {
  2363. get: function () {
  2364. return false;
  2365. },
  2366. enumerable: true,
  2367. configurable: true
  2368. });
  2369. FontTexture.prototype.getContext = function () {
  2370. return this._context;
  2371. };
  2372. /**
  2373. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  2374. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  2375. */
  2376. FontTexture.prototype.update = function () {
  2377. // Update only if there's new char added since the previous update
  2378. if (this._lastUpdateCharCount < this._curCharCount) {
  2379. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  2380. this._lastUpdateCharCount = this._curCharCount;
  2381. }
  2382. };
  2383. // cloning should be prohibited, there's no point to duplicate this texture at all
  2384. FontTexture.prototype.clone = function () {
  2385. return null;
  2386. };
  2387. /**
  2388. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  2389. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  2390. */
  2391. FontTexture.prototype.incCachedFontTextureCounter = function () {
  2392. ++this._usedCounter;
  2393. };
  2394. /**
  2395. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  2396. */
  2397. FontTexture.prototype.decCachedFontTextureCounter = function () {
  2398. var dic = this.getScene().getExternalData("FontTextureCache");
  2399. if (!dic) {
  2400. return;
  2401. }
  2402. if (--this._usedCounter === 0) {
  2403. dic.remove(this._cachedFontId);
  2404. this.dispose();
  2405. }
  2406. };
  2407. return FontTexture;
  2408. }(BaseFontTexture));
  2409. BABYLON.FontTexture = FontTexture;
  2410. /**
  2411. * Orginial code from cocos2d-js, converted to TypeScript by Nockawa
  2412. * Load the Text version of the BMFont format, no XML or binary supported, just plain old text
  2413. */
  2414. var BMFontLoaderTxt = BMFontLoaderTxt_1 = (function () {
  2415. function BMFontLoaderTxt() {
  2416. }
  2417. BMFontLoaderTxt.prototype._parseStrToObj = function (str) {
  2418. var arr = str.match(BMFontLoaderTxt_1.ITEM_EXP);
  2419. if (!arr) {
  2420. return null;
  2421. }
  2422. var obj = {};
  2423. for (var i = 0, li = arr.length; i < li; i++) {
  2424. var tempStr = arr[i];
  2425. var index = tempStr.indexOf("=");
  2426. var key = tempStr.substring(0, index);
  2427. var value = tempStr.substring(index + 1);
  2428. if (value.match(BMFontLoaderTxt_1.INT_EXP))
  2429. value = parseInt(value);
  2430. else if (value[0] === '"')
  2431. value = value.substring(1, value.length - 1);
  2432. obj[key] = value;
  2433. }
  2434. return obj;
  2435. };
  2436. BMFontLoaderTxt.prototype._buildCharInfo = function (bfi, initialLine, obj, textureSize, invertY, chars) {
  2437. var char = null;
  2438. var x = null;
  2439. var y = null;
  2440. var width = null;
  2441. var height = null;
  2442. var xoffset = 0;
  2443. var yoffset = 0;
  2444. var xadvance = 0;
  2445. var ci = new CharInfo();
  2446. for (var key in obj) {
  2447. var value = obj[key];
  2448. switch (key) {
  2449. case "id":
  2450. char = String.fromCharCode(value);
  2451. break;
  2452. case "x":
  2453. x = value;
  2454. break;
  2455. case "y":
  2456. y = value;
  2457. break;
  2458. case "width":
  2459. width = value;
  2460. break;
  2461. case "height":
  2462. height = value;
  2463. break;
  2464. case "xadvance":
  2465. xadvance = value;
  2466. break;
  2467. case "xoffset":
  2468. xoffset = value;
  2469. break;
  2470. case "yoffset":
  2471. yoffset = value;
  2472. break;
  2473. }
  2474. }
  2475. if (x != null && y != null && width != null && height != null && char != null) {
  2476. ci.xAdvance = xadvance;
  2477. ci.xOffset = xoffset;
  2478. ci.yOffset = bfi.lineHeight - height - yoffset;
  2479. if (invertY) {
  2480. ci.topLeftUV = new BABYLON.Vector2(1 - (x / textureSize.width), 1 - (y / textureSize.height));
  2481. ci.bottomRightUV = new BABYLON.Vector2(1 - ((x + width) / textureSize.width), 1 - ((y + height) / textureSize.height));
  2482. }
  2483. else {
  2484. ci.topLeftUV = new BABYLON.Vector2(x / textureSize.width, y / textureSize.height);
  2485. ci.bottomRightUV = new BABYLON.Vector2((x + width) / textureSize.width, (y + height) / textureSize.height);
  2486. }
  2487. ci.charWidth = width;
  2488. chars.add(char, ci);
  2489. }
  2490. else {
  2491. console.log("Error while parsing line " + initialLine);
  2492. }
  2493. };
  2494. BMFontLoaderTxt.prototype.loadFont = function (fontContent, scene, invertY) {
  2495. var fontStr = fontContent;
  2496. var bfi = new BitmapFontInfo();
  2497. var errorCode = 0;
  2498. var errorMsg = "OK";
  2499. //padding
  2500. var info = fontStr.match(BMFontLoaderTxt_1.INFO_EXP);
  2501. var infoObj = this._parseStrToObj(info[0]);
  2502. if (!infoObj) {
  2503. return null;
  2504. }
  2505. var paddingArr = infoObj["padding"].split(",");
  2506. bfi.padding = new BABYLON.Vector4(parseInt(paddingArr[0]), parseInt(paddingArr[1]), parseInt(paddingArr[2]), parseInt(paddingArr[3]));
  2507. //common
  2508. var commonObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.COMMON_EXP)[0]);
  2509. bfi.lineHeight = commonObj["lineHeight"];
  2510. bfi.baseLine = commonObj["base"];
  2511. bfi.textureSize = new BABYLON.Size(commonObj["scaleW"], commonObj["scaleH"]);
  2512. var maxTextureSize = scene.getEngine()._gl.getParameter(0xd33);
  2513. if (commonObj["scaleW"] > maxTextureSize.width || commonObj["scaleH"] > maxTextureSize.height) {
  2514. errorMsg = "FontMap texture's size is bigger than what WebGL supports";
  2515. errorCode = -1;
  2516. }
  2517. else {
  2518. if (commonObj["pages"] !== 1) {
  2519. errorMsg = "FontMap must contain one page only.";
  2520. errorCode = -1;
  2521. }
  2522. else {
  2523. //page
  2524. var pageObj = this._parseStrToObj(fontStr.match(BMFontLoaderTxt_1.PAGE_EXP)[0]);
  2525. if (pageObj["id"] !== 0) {
  2526. errorMsg = "Only one page of ID 0 is supported";
  2527. errorCode = -1;
  2528. }
  2529. else {
  2530. bfi.textureFile = pageObj["file"];
  2531. //char
  2532. var charLines = fontStr.match(BMFontLoaderTxt_1.CHAR_EXP);
  2533. for (var i = 0, li = charLines.length; i < li; i++) {
  2534. var charObj = this._parseStrToObj(charLines[i]);
  2535. this._buildCharInfo(bfi, charLines[i], charObj, bfi.textureSize, invertY, bfi.charDic);
  2536. }
  2537. //kerning
  2538. var kerningLines = fontStr.match(BMFontLoaderTxt_1.KERNING_EXP);
  2539. if (kerningLines) {
  2540. for (var i = 0, li = kerningLines.length; i < li; i++) {
  2541. var kerningObj = this._parseStrToObj(kerningLines[i]);
  2542. bfi.kerningDic.add(((kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)).toString(), kerningObj["amount"]);
  2543. }
  2544. }
  2545. }
  2546. }
  2547. }
  2548. return { bfi: bfi, errorCode: errorCode, errorMsg: errorMsg };
  2549. };
  2550. return BMFontLoaderTxt;
  2551. }());
  2552. BMFontLoaderTxt.INFO_EXP = /info [^\r\n]*(\r\n|$)/gi;
  2553. BMFontLoaderTxt.COMMON_EXP = /common [^\n]*(\n|$)/gi;
  2554. BMFontLoaderTxt.PAGE_EXP = /page [^\n]*(\n|$)/gi;
  2555. BMFontLoaderTxt.CHAR_EXP = /char [^\n]*(\n|$)/gi;
  2556. BMFontLoaderTxt.KERNING_EXP = /kerning [^\n]*(\n|$)/gi;
  2557. BMFontLoaderTxt.ITEM_EXP = /\w+=[^ \r\n]+/gi;
  2558. BMFontLoaderTxt.INT_EXP = /^[\-]?\d+$/;
  2559. BMFontLoaderTxt = BMFontLoaderTxt_1 = __decorate([
  2560. BitmapFontLoaderPlugin("fnt", new BMFontLoaderTxt_1())
  2561. ], BMFontLoaderTxt);
  2562. ;
  2563. function BitmapFontLoaderPlugin(fileExtension, plugin) {
  2564. return function () {
  2565. BitmapFontTexture.addLoader(fileExtension, plugin);
  2566. };
  2567. }
  2568. BABYLON.BitmapFontLoaderPlugin = BitmapFontLoaderPlugin;
  2569. var BMFontLoaderTxt_1;
  2570. })(BABYLON || (BABYLON = {}));
  2571. //# sourceMappingURL=babylon.fontTexture.js.map
  2572. var BABYLON;
  2573. (function (BABYLON) {
  2574. /**
  2575. * Stores 2D Bounding Information.
  2576. * This class handles a circle area and a bounding rectangle one.
  2577. */
  2578. var BoundingInfo2D = (function () {
  2579. function BoundingInfo2D() {
  2580. this.radius = 0;
  2581. this.center = BABYLON.Vector2.Zero();
  2582. this.extent = BABYLON.Vector2.Zero();
  2583. this._worldAABBDirty = false;
  2584. this._worldAABBDirtyObservable = null;
  2585. this._worldAABB = BABYLON.Vector4.Zero();
  2586. }
  2587. /**
  2588. * Create a BoundingInfo2D object from a given size
  2589. * @param size the size that will be used to set the extend, radius will be computed from it.
  2590. */
  2591. BoundingInfo2D.CreateFromSize = function (size) {
  2592. var r = new BoundingInfo2D();
  2593. BoundingInfo2D.CreateFromSizeToRef(size, r);
  2594. return r;
  2595. };
  2596. /**
  2597. * Create a BoundingInfo2D object from a given radius
  2598. * @param radius the radius to use, the extent will be computed from it.
  2599. */
  2600. BoundingInfo2D.CreateFromRadius = function (radius) {
  2601. var r = new BoundingInfo2D();
  2602. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  2603. return r;
  2604. };
  2605. /**
  2606. * Create a BoundingInfo2D object from a list of points.
  2607. * The resulted object will be the smallest bounding area that includes all the given points.
  2608. * @param points an array of points to compute the bounding object from.
  2609. */
  2610. BoundingInfo2D.CreateFromPoints = function (points) {
  2611. var r = new BoundingInfo2D();
  2612. BoundingInfo2D.CreateFromPointsToRef(points, r);
  2613. return r;
  2614. };
  2615. /**
  2616. * Update a BoundingInfo2D object using the given Size as input
  2617. * @param size the bounding data will be computed from this size.
  2618. * @param b must be a valid/allocated object, it will contain the result of the operation
  2619. */
  2620. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  2621. if (!size) {
  2622. size = BABYLON.Size.Zero();
  2623. }
  2624. b.center.x = +size.width / 2;
  2625. b.center.y = +size.height / 2;
  2626. b.extent.x = b.center.x;
  2627. b.extent.y = b.center.y;
  2628. b.radius = b.extent.length();
  2629. b._worldAABBDirty = true;
  2630. };
  2631. /**
  2632. * Update a BoundingInfo2D object using the given radius as input
  2633. * @param radius the bounding data will be computed from this radius
  2634. * @param b must be a valid/allocated object, it will contain the result of the operation
  2635. */
  2636. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  2637. b.center.x = b.center.y = 0;
  2638. var r = +radius;
  2639. b.extent.x = r;
  2640. b.extent.y = r;
  2641. b.radius = r;
  2642. b._worldAABBDirty = true;
  2643. };
  2644. /**
  2645. * Update a BoundingInfo2D object using the given points array as input
  2646. * @param points the point array to use to update the bounding data
  2647. * @param b must be a valid/allocated object, it will contain the result of the operation
  2648. */
  2649. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  2650. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  2651. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  2652. var p = points_1[_i];
  2653. xmin = Math.min(p.x, xmin);
  2654. xmax = Math.max(p.x, xmax);
  2655. ymin = Math.min(p.y, ymin);
  2656. ymax = Math.max(p.y, ymax);
  2657. }
  2658. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  2659. };
  2660. /**
  2661. * Update a BoundingInfo2D object using the given min/max values as input
  2662. * @param xmin the smallest x coordinate
  2663. * @param xmax the biggest x coordinate
  2664. * @param ymin the smallest y coordinate
  2665. * @param ymax the buggest y coordinate
  2666. * @param b must be a valid/allocated object, it will contain the result of the operation
  2667. */
  2668. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  2669. var w = xmax - xmin;
  2670. var h = ymax - ymin;
  2671. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  2672. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  2673. b.radius = b.extent.length();
  2674. b._worldAABBDirty = true;
  2675. };
  2676. /**
  2677. * Duplicate this instance and return a new one
  2678. * @return the duplicated instance
  2679. */
  2680. BoundingInfo2D.prototype.clone = function () {
  2681. var r = new BoundingInfo2D();
  2682. r.center = this.center.clone();
  2683. r.radius = this.radius;
  2684. r.extent = this.extent.clone();
  2685. return r;
  2686. };
  2687. BoundingInfo2D.prototype.clear = function () {
  2688. this.center.copyFromFloats(0, 0);
  2689. this.radius = 0;
  2690. this.extent.copyFromFloats(0, 0);
  2691. this._worldAABBDirty = true;
  2692. };
  2693. BoundingInfo2D.prototype.copyFrom = function (src) {
  2694. this.center.copyFrom(src.center);
  2695. this.radius = src.radius;
  2696. this.extent.copyFrom(src.extent);
  2697. this._worldAABBDirty = true;
  2698. };
  2699. BoundingInfo2D.prototype.equals = function (other) {
  2700. if (!other) {
  2701. return false;
  2702. }
  2703. return other.center.equals(this.center) && other.extent.equals(this.extent);
  2704. };
  2705. /**
  2706. * return the max extend of the bounding info
  2707. */
  2708. BoundingInfo2D.prototype.max = function () {
  2709. var r = BABYLON.Vector2.Zero();
  2710. this.maxToRef(r);
  2711. return r;
  2712. };
  2713. /**
  2714. * return the min/max extend of the bounding info.
  2715. * x, y, z, w are left, bottom, right and top
  2716. */
  2717. BoundingInfo2D.prototype.minMax = function () {
  2718. var r = BABYLON.Vector4.Zero();
  2719. this.minMaxToRef(r);
  2720. return r;
  2721. };
  2722. /**
  2723. * Update a vector2 with the max extend of the bounding info
  2724. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  2725. */
  2726. BoundingInfo2D.prototype.maxToRef = function (result) {
  2727. result.x = this.center.x + this.extent.x;
  2728. result.y = this.center.y + this.extent.y;
  2729. };
  2730. /**
  2731. * Update a vector4 with the min/max extend of the bounding info
  2732. * x, y, z, w are left, bottom, right and top
  2733. * @param result must be a valid/allocated vector4 that will contain the result of the operation
  2734. */
  2735. BoundingInfo2D.prototype.minMaxToRef = function (result) {
  2736. result.x = this.center.x - this.extent.x;
  2737. result.y = this.center.y - this.extent.y;
  2738. result.z = this.center.x + this.extent.x;
  2739. result.w = this.center.y + this.extent.y;
  2740. };
  2741. /**
  2742. * Return the size of the boundingInfo rect surface
  2743. */
  2744. BoundingInfo2D.prototype.size = function () {
  2745. var r = BABYLON.Size.Zero();
  2746. this.sizeToRef(r);
  2747. return r;
  2748. };
  2749. /**
  2750. * Stores in the result object the size of the boundingInfo rect surface
  2751. * @param result
  2752. */
  2753. BoundingInfo2D.prototype.sizeToRef = function (result) {
  2754. result.width = this.extent.x * 2;
  2755. result.height = this.extent.y * 2;
  2756. };
  2757. /**
  2758. * Inflate the boundingInfo with the given vector
  2759. * @param offset the extent will be incremented with offset and the radius will be computed again
  2760. */
  2761. BoundingInfo2D.prototype.inflate = function (offset) {
  2762. this.extent.addInPlace(offset);
  2763. this.radius = this.extent.length();
  2764. };
  2765. /**
  2766. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  2767. * @param matrix the transformation matrix to apply
  2768. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  2769. */
  2770. BoundingInfo2D.prototype.transform = function (matrix) {
  2771. var r = new BoundingInfo2D();
  2772. this.transformToRef(matrix, r);
  2773. return r;
  2774. };
  2775. /**
  2776. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  2777. * @param other the second BoundingInfo2D to compute the union with this one
  2778. * @return a new instance containing the result of the union
  2779. */
  2780. BoundingInfo2D.prototype.union = function (other) {
  2781. var r = new BoundingInfo2D();
  2782. this.unionToRef(other, r);
  2783. return r;
  2784. };
  2785. BoundingInfo2D.prototype.worldAABBIntersectionTest = function (other) {
  2786. var a = this.worldAABB;
  2787. var b = other.worldAABB;
  2788. return b.z >= a.x && b.x <= a.z && b.w >= a.y && b.y <= a.w;
  2789. };
  2790. /**
  2791. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  2792. * 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.
  2793. * @param matrix The matrix to use to compute the transformation
  2794. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  2795. */
  2796. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  2797. // Construct a bounding box based on the extent values
  2798. var p = BoundingInfo2D._transform;
  2799. p[0].x = this.center.x + this.extent.x;
  2800. p[0].y = this.center.y + this.extent.y;
  2801. p[1].x = this.center.x + this.extent.x;
  2802. p[1].y = this.center.y - this.extent.y;
  2803. p[2].x = this.center.x - this.extent.x;
  2804. p[2].y = this.center.y - this.extent.y;
  2805. p[3].x = this.center.x - this.extent.x;
  2806. p[3].y = this.center.y + this.extent.y;
  2807. // Transform the four points of the bounding box with the matrix
  2808. for (var i = 0; i < 4; i++) {
  2809. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  2810. }
  2811. BoundingInfo2D.CreateFromPointsToRef(p, result);
  2812. };
  2813. BoundingInfo2D.prototype._updateWorldAABB = function (worldMatrix) {
  2814. // Construct a bounding box based on the extent values
  2815. var p = BoundingInfo2D._transform;
  2816. p[0].x = this.center.x + this.extent.x;
  2817. p[0].y = this.center.y + this.extent.y;
  2818. p[1].x = this.center.x + this.extent.x;
  2819. p[1].y = this.center.y - this.extent.y;
  2820. p[2].x = this.center.x - this.extent.x;
  2821. p[2].y = this.center.y - this.extent.y;
  2822. p[3].x = this.center.x - this.extent.x;
  2823. p[3].y = this.center.y + this.extent.y;
  2824. // Transform the four points of the bounding box with the matrix
  2825. for (var i = 0; i < 4; i++) {
  2826. BABYLON.Vector2.TransformToRef(p[i], worldMatrix, p[i]);
  2827. }
  2828. this._worldAABB.x = Math.min(Math.min(p[0].x, p[1].x), Math.min(p[2].x, p[3].x));
  2829. this._worldAABB.y = Math.min(Math.min(p[0].y, p[1].y), Math.min(p[2].y, p[3].y));
  2830. this._worldAABB.z = Math.max(Math.max(p[0].x, p[1].x), Math.max(p[2].x, p[3].x));
  2831. this._worldAABB.w = Math.max(Math.max(p[0].y, p[1].y), Math.max(p[2].y, p[3].y));
  2832. };
  2833. Object.defineProperty(BoundingInfo2D.prototype, "worldAABBDirtyObservable", {
  2834. get: function () {
  2835. if (!this._worldAABBDirtyObservable) {
  2836. this._worldAABBDirtyObservable = new BABYLON.Observable();
  2837. }
  2838. return this._worldAABBDirtyObservable;
  2839. },
  2840. enumerable: true,
  2841. configurable: true
  2842. });
  2843. Object.defineProperty(BoundingInfo2D.prototype, "isWorldAABBDirty", {
  2844. get: function () {
  2845. return this._worldAABBDirty;
  2846. },
  2847. enumerable: true,
  2848. configurable: true
  2849. });
  2850. BoundingInfo2D.prototype.dirtyWorldAABB = function () {
  2851. if (this._worldAABBDirty) {
  2852. return;
  2853. }
  2854. this._worldAABBDirty = true;
  2855. if (this._worldAABBDirtyObservable && this._worldAABBDirtyObservable.hasObservers()) {
  2856. this._worldAABBDirtyObservable.notifyObservers(this);
  2857. }
  2858. };
  2859. Object.defineProperty(BoundingInfo2D.prototype, "worldAABB", {
  2860. /**
  2861. * Retrieve the world AABB, the Vector4's data is x=xmin, y=ymin, z=xmax, w=ymax
  2862. */
  2863. get: function () {
  2864. if (this._worldAABBDirty) {
  2865. if (!this.worldMatrixAccess) {
  2866. throw new Error("you must set the worldMatrixAccess function first");
  2867. }
  2868. this._updateWorldAABB(this.worldMatrixAccess());
  2869. this._worldAABBDirty = false;
  2870. }
  2871. return this._worldAABB;
  2872. },
  2873. enumerable: true,
  2874. configurable: true
  2875. });
  2876. /**
  2877. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  2878. * 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.
  2879. * @param other the second object used to compute the union
  2880. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  2881. */
  2882. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  2883. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  2884. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  2885. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  2886. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  2887. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  2888. };
  2889. /**
  2890. * Check if the given point is inside the BoundingInfo.
  2891. * The test is first made on the radius, then inside the rectangle described by the extent
  2892. * @param pickPosition the position to test
  2893. * @return true if the point is inside, false otherwise
  2894. */
  2895. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  2896. // is it inside the radius?
  2897. var pickLocal = pickPosition.subtract(this.center);
  2898. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  2899. // is it inside the rectangle?
  2900. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  2901. }
  2902. return false;
  2903. };
  2904. return BoundingInfo2D;
  2905. }());
  2906. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  2907. BABYLON.BoundingInfo2D = BoundingInfo2D;
  2908. })(BABYLON || (BABYLON = {}));
  2909. //# sourceMappingURL=babylon.bounding2d.js.map
  2910. var __extends = (this && this.__extends) || function (d, b) {
  2911. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  2912. function __() { this.constructor = d; }
  2913. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2914. };
  2915. var BABYLON;
  2916. (function (BABYLON) {
  2917. /**
  2918. * The base class for all implementation of a Primitive Collision Manager
  2919. */
  2920. var PrimitiveCollisionManagerBase = (function () {
  2921. function PrimitiveCollisionManagerBase(owner) {
  2922. this._owner = owner;
  2923. }
  2924. PrimitiveCollisionManagerBase.allocBasicPCM = function (owner, enableBorders) {
  2925. return new BasicPrimitiveCollisionManager(owner, enableBorders);
  2926. };
  2927. return PrimitiveCollisionManagerBase;
  2928. }());
  2929. BABYLON.PrimitiveCollisionManagerBase = PrimitiveCollisionManagerBase;
  2930. /**
  2931. * Base class of an Actor
  2932. */
  2933. var ActorInfoBase = (function () {
  2934. function ActorInfoBase() {
  2935. }
  2936. return ActorInfoBase;
  2937. }());
  2938. BABYLON.ActorInfoBase = ActorInfoBase;
  2939. var ActorInfo = (function (_super) {
  2940. __extends(ActorInfo, _super);
  2941. function ActorInfo(owner, actor, deep) {
  2942. var _this = _super.call(this) || this;
  2943. _this.owner = owner;
  2944. _this.prim = actor;
  2945. _this.flags = 0;
  2946. _this.presentInClusters = new BABYLON.StringDictionary();
  2947. _this.intersectWith = new BABYLON.ObservableStringDictionary(false);
  2948. _this.setFlags((deep ? ActorInfo.flagDeep : 0) | ActorInfo.flagDirty);
  2949. var bi = (deep ? actor.boundingInfo : actor.levelBoundingInfo);
  2950. // Dirty Actor if its WorldAABB changed
  2951. bi.worldAABBDirtyObservable.add(function (e, d) {
  2952. _this.owner.actorDirty(_this);
  2953. });
  2954. // Dirty Actor if it's getting enabled/disabled
  2955. actor.propertyChanged.add(function (e, d) {
  2956. if (d.mask === -1) {
  2957. return;
  2958. }
  2959. _this.setFlagsValue(ActorInfo.flagEnabled, e.newValue === true);
  2960. _this.owner.actorDirty(_this);
  2961. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  2962. return _this;
  2963. }
  2964. ActorInfo.prototype.setFlags = function (flags) {
  2965. this.flags |= flags;
  2966. };
  2967. ActorInfo.prototype.clearFlags = function (flags) {
  2968. this.flags &= ~flags;
  2969. };
  2970. ActorInfo.prototype.isAllFlagsSet = function (flags) {
  2971. return (this.flags & flags) === flags;
  2972. };
  2973. ActorInfo.prototype.isSomeFlagsSet = function (flags) {
  2974. return (this.flags & flags) !== 0;
  2975. };
  2976. ActorInfo.prototype.setFlagsValue = function (flags, value) {
  2977. if (value) {
  2978. this.flags |= flags;
  2979. }
  2980. else {
  2981. this.flags &= ~flags;
  2982. }
  2983. };
  2984. Object.defineProperty(ActorInfo.prototype, "worldAABB", {
  2985. get: function () {
  2986. return (this.isSomeFlagsSet(ActorInfo.flagDeep) ? this.prim.boundingInfo : this.prim.levelBoundingInfo).worldAABB;
  2987. },
  2988. enumerable: true,
  2989. configurable: true
  2990. });
  2991. Object.defineProperty(ActorInfo.prototype, "isEnabled", {
  2992. get: function () {
  2993. return this.isSomeFlagsSet(ActorInfo.flagEnabled);
  2994. },
  2995. enumerable: true,
  2996. configurable: true
  2997. });
  2998. Object.defineProperty(ActorInfo.prototype, "isDeep", {
  2999. get: function () {
  3000. return this.isSomeFlagsSet(ActorInfo.flagDeep);
  3001. },
  3002. enumerable: true,
  3003. configurable: true
  3004. });
  3005. Object.defineProperty(ActorInfo.prototype, "isDirty", {
  3006. get: function () {
  3007. return this.isSomeFlagsSet(ActorInfo.flagDirty);
  3008. },
  3009. enumerable: true,
  3010. configurable: true
  3011. });
  3012. Object.defineProperty(ActorInfo.prototype, "isRemoved", {
  3013. get: function () {
  3014. return this.isSomeFlagsSet(ActorInfo.flagRemoved);
  3015. },
  3016. enumerable: true,
  3017. configurable: true
  3018. });
  3019. return ActorInfo;
  3020. }(ActorInfoBase));
  3021. ActorInfo.flagDeep = 0x0001; // set if the actor boundingInfo must be used instead of the levelBoundingInfo
  3022. ActorInfo.flagEnabled = 0x0002; // set if the actor is enabled and should be considered for intersection tests
  3023. ActorInfo.flagDirty = 0x0004; // set if the actor's AABB is dirty
  3024. ActorInfo.flagRemoved = 0x0008; // set if the actor was removed from the PCM
  3025. var ClusterInfo = (function () {
  3026. function ClusterInfo() {
  3027. this.actors = new BABYLON.StringDictionary();
  3028. }
  3029. ClusterInfo.prototype.clear = function () {
  3030. this.actors.clear();
  3031. };
  3032. return ClusterInfo;
  3033. }());
  3034. var BasicPrimitiveCollisionManager = (function (_super) {
  3035. __extends(BasicPrimitiveCollisionManager, _super);
  3036. function BasicPrimitiveCollisionManager(owner, enableBorders) {
  3037. var _this = _super.call(this, owner) || this;
  3038. _this._actors = new BABYLON.StringDictionary();
  3039. _this._dirtyActors = new BABYLON.StringDictionary();
  3040. _this._clusters = null;
  3041. _this._maxActorByCluster = 0;
  3042. _this._AABBRenderPrim = null;
  3043. _this._canvasSize = BABYLON.Size.Zero();
  3044. _this._ClusterRenderPrim = null;
  3045. _this._debugTextBackground = null;
  3046. _this._clusterDirty = true;
  3047. _this._clusterSize = new BABYLON.Size(2, 2);
  3048. _this._clusterStep = BABYLON.Vector2.Zero();
  3049. _this._lastClusterResizeCounter = 0;
  3050. _this._freeClusters = new Array();
  3051. _this._enableBorder = enableBorders;
  3052. _this._debugUpdateOpCount = new BABYLON.PerfCounter();
  3053. _this._debugUpdateTime = new BABYLON.PerfCounter();
  3054. _this._intersectedActors = new BABYLON.ObservableStringDictionary(false);
  3055. _this._borderIntersecteddActors = new Array(4);
  3056. for (var j = 0; j < 4; j++) {
  3057. _this._borderIntersecteddActors[j] = new BABYLON.ObservableStringDictionary(false);
  3058. }
  3059. var flagId = BABYLON.Canvas2D.actualSizeProperty.flagId;
  3060. if (!BasicPrimitiveCollisionManager.WAABBCorners) {
  3061. BasicPrimitiveCollisionManager.WAABBCorners = new Array(4);
  3062. for (var i = 0; i < 4; i++) {
  3063. BasicPrimitiveCollisionManager.WAABBCorners[i] = BABYLON.Vector2.Zero();
  3064. }
  3065. BasicPrimitiveCollisionManager.WAABBCornersCluster = new Array(4);
  3066. for (var i = 0; i < 4; i++) {
  3067. BasicPrimitiveCollisionManager.WAABBCornersCluster[i] = BABYLON.Vector2.Zero();
  3068. }
  3069. }
  3070. owner.propertyChanged.add(function (e, d) {
  3071. if (d.mask === -1) {
  3072. return;
  3073. }
  3074. _this._clusterDirty = true;
  3075. console.log("canvas size changed");
  3076. }, flagId);
  3077. _this.debugRenderAABB = false;
  3078. _this.debugRenderClusters = false;
  3079. _this.debugStats = false;
  3080. return _this;
  3081. }
  3082. BasicPrimitiveCollisionManager.prototype._addActor = function (actor, deep) {
  3083. var _this = this;
  3084. return this._actors.getOrAddWithFactory(actor.uid, function () {
  3085. var ai = new ActorInfo(_this, actor, deep);
  3086. _this.actorDirty(ai);
  3087. return ai;
  3088. });
  3089. };
  3090. BasicPrimitiveCollisionManager.prototype._removeActor = function (actor) {
  3091. var ai = this._actors.getAndRemove(actor.uid);
  3092. ai.setFlags(ActorInfo.flagRemoved);
  3093. this.actorDirty(ai);
  3094. };
  3095. BasicPrimitiveCollisionManager.prototype.actorDirty = function (actor) {
  3096. actor.setFlags(ActorInfo.flagDirty);
  3097. this._dirtyActors.add(actor.prim.uid, actor);
  3098. };
  3099. BasicPrimitiveCollisionManager.prototype._update = function () {
  3100. this._canvasSize.copyFrom(this._owner.actualSize);
  3101. // Should we update the WireFrame2D Primitive that displays the WorldAABB ?
  3102. if (this.debugRenderAABB) {
  3103. if (this._dirtyActors.count > 0 || this._debugRenderAABBDirty) {
  3104. this._updateAABBDisplay();
  3105. }
  3106. }
  3107. if (this._AABBRenderPrim) {
  3108. this._AABBRenderPrim.levelVisible = this.debugRenderAABB;
  3109. }
  3110. var cw = this._clusterSize.width;
  3111. var ch = this._clusterSize.height;
  3112. // Check for Cluster resize
  3113. if (((this._clusterSize.width < 16 && this._clusterSize.height < 16 && this._maxActorByCluster >= 10) ||
  3114. (this._clusterSize.width > 2 && this._clusterSize.height > 2 && this._maxActorByCluster <= 7)) &&
  3115. this._lastClusterResizeCounter > 100) {
  3116. if (this._maxActorByCluster >= 10) {
  3117. ++cw;
  3118. ++ch;
  3119. }
  3120. else {
  3121. --cw;
  3122. --ch;
  3123. }
  3124. console.log("Change cluster size to " + cw + ":" + ch + ", max actor " + this._maxActorByCluster);
  3125. this._clusterDirty = true;
  3126. }
  3127. // Should we update the WireFrame2D Primitive that displays the clusters
  3128. if (this.debugRenderClusters && this._clusterDirty) {
  3129. this._updateClusterDisplay(cw, ch);
  3130. }
  3131. if (this._ClusterRenderPrim) {
  3132. this._ClusterRenderPrim.levelVisible = this.debugRenderClusters;
  3133. }
  3134. var updateStats = this.debugStats && (this._dirtyActors.count > 0 || this._clusterDirty);
  3135. this._debugUpdateTime.beginMonitoring();
  3136. // If the Cluster Size changed: rebuild it and add all actors. Otherwise add only new (dirty) actors
  3137. if (this._clusterDirty) {
  3138. this._initializeCluster(cw, ch);
  3139. this._rebuildAllActors();
  3140. }
  3141. else {
  3142. this._rebuildDirtyActors();
  3143. ++this._lastClusterResizeCounter;
  3144. }
  3145. // Proceed to the collision detection between primitives
  3146. this._collisionDetection();
  3147. this._debugUpdateTime.endMonitoring();
  3148. if (updateStats) {
  3149. this._updateDebugStats();
  3150. }
  3151. if (this._debugTextBackground) {
  3152. this._debugTextBackground.levelVisible = updateStats;
  3153. }
  3154. // Reset the dirty actor list: everything is processed
  3155. this._dirtyActors.clear();
  3156. };
  3157. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "debugRenderAABB", {
  3158. /**
  3159. * Renders the World AABB of all Actors
  3160. */
  3161. get: function () {
  3162. return this._debugRenderAABB;
  3163. },
  3164. set: function (val) {
  3165. if (this._debugRenderAABB === val) {
  3166. return;
  3167. }
  3168. this._debugRenderAABB = val;
  3169. this._debugRenderAABBDirty = true;
  3170. },
  3171. enumerable: true,
  3172. configurable: true
  3173. });
  3174. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "intersectedActors", {
  3175. get: function () {
  3176. return this._intersectedActors;
  3177. },
  3178. enumerable: true,
  3179. configurable: true
  3180. });
  3181. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "leftBorderIntersectedActors", {
  3182. get: function () {
  3183. return this._borderIntersecteddActors[0];
  3184. },
  3185. enumerable: true,
  3186. configurable: true
  3187. });
  3188. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "bottomBorderIntersectedActors", {
  3189. get: function () {
  3190. return this._borderIntersecteddActors[1];
  3191. },
  3192. enumerable: true,
  3193. configurable: true
  3194. });
  3195. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "rightBorderIntersectedActors", {
  3196. get: function () {
  3197. return this._borderIntersecteddActors[2];
  3198. },
  3199. enumerable: true,
  3200. configurable: true
  3201. });
  3202. Object.defineProperty(BasicPrimitiveCollisionManager.prototype, "topBorderIntersectedActors", {
  3203. get: function () {
  3204. return this._borderIntersecteddActors[3];
  3205. },
  3206. enumerable: true,
  3207. configurable: true
  3208. });
  3209. BasicPrimitiveCollisionManager.prototype._initializeCluster = function (countW, countH) {
  3210. // Check for free
  3211. if (this._clusters) {
  3212. for (var w = 0; w < this._clusterSize.height; w++) {
  3213. for (var h = 0; h < this._clusterSize.width; h++) {
  3214. this._freeClusterInfo(this._clusters[w][h]);
  3215. }
  3216. }
  3217. }
  3218. // Allocate
  3219. this._clusterSize.copyFromFloats(countW, countH);
  3220. this._clusters = [];
  3221. for (var w = 0; w < this._clusterSize.height; w++) {
  3222. this._clusters[w] = [];
  3223. for (var h = 0; h < this._clusterSize.width; h++) {
  3224. var ci = this._allocClusterInfo();
  3225. this._clusters[w][h] = ci;
  3226. }
  3227. }
  3228. this._clusterStep.copyFromFloats(this._owner.actualWidth / countW, this._owner.actualHeight / countH);
  3229. this._maxActorByCluster = 0;
  3230. this._lastClusterResizeCounter = 0;
  3231. this._clusterDirty = false;
  3232. };
  3233. BasicPrimitiveCollisionManager.prototype._rebuildAllActors = function () {
  3234. var _this = this;
  3235. this._actors.forEach(function (k, ai) {
  3236. _this._processActor(ai);
  3237. });
  3238. };
  3239. BasicPrimitiveCollisionManager.prototype._rebuildDirtyActors = function () {
  3240. var _this = this;
  3241. this._dirtyActors.forEach(function (k, ai) {
  3242. _this._processActor(ai);
  3243. });
  3244. };
  3245. BasicPrimitiveCollisionManager.prototype._processActor = function (actor) {
  3246. var _this = this;
  3247. // Check if the actor is being disabled or removed
  3248. if (!actor.isEnabled || actor.isRemoved) {
  3249. actor.presentInClusters.forEach(function (k, ci) {
  3250. ci.actors.remove(actor.prim.uid);
  3251. });
  3252. actor.presentInClusters.clear();
  3253. return;
  3254. }
  3255. var wab = actor.worldAABB;
  3256. // Build the worldAABB corners
  3257. var wac = BasicPrimitiveCollisionManager.WAABBCorners;
  3258. wac[0].copyFromFloats(wab.x, wab.y); // Bottom/Left
  3259. wac[1].copyFromFloats(wab.z, wab.y); // Bottom/Right
  3260. wac[2].copyFromFloats(wab.z, wab.w); // Top/Right
  3261. wac[3].copyFromFloats(wab.x, wab.w); // Top/Left
  3262. var cs = this._clusterStep;
  3263. var wacc = BasicPrimitiveCollisionManager.WAABBCornersCluster;
  3264. for (var i = 0; i < 4; i++) {
  3265. var p = wac[i];
  3266. var cx = (p.x - (p.x % cs.x)) / cs.x;
  3267. var cy = (p.y - (p.y % cs.y)) / cs.y;
  3268. wacc[i].copyFromFloats(Math.floor(cx), Math.floor(cy));
  3269. }
  3270. var opCount = 0;
  3271. var totalClusters = 0;
  3272. var newCI = new Array();
  3273. var sx = Math.max(0, wacc[0].x); // Start Cluster X
  3274. var sy = Math.max(0, wacc[0].y); // Start Cluster Y
  3275. var ex = Math.min(this._clusterSize.width - 1, wacc[2].x); // End Cluster X
  3276. var ey = Math.min(this._clusterSize.height - 1, wacc[2].y); // End Cluster Y
  3277. if (this._enableBorder) {
  3278. if (wac[0].x < 0) {
  3279. this._borderIntersecteddActors[0].add(actor.prim.uid, actor.prim);
  3280. }
  3281. else {
  3282. this._borderIntersecteddActors[0].remove(actor.prim.uid);
  3283. }
  3284. if (wac[0].y < 0) {
  3285. this._borderIntersecteddActors[1].add(actor.prim.uid, actor.prim);
  3286. }
  3287. else {
  3288. this._borderIntersecteddActors[1].remove(actor.prim.uid);
  3289. }
  3290. if (wac[2].x >= this._canvasSize.width) {
  3291. this._borderIntersecteddActors[2].add(actor.prim.uid, actor.prim);
  3292. }
  3293. else {
  3294. this._borderIntersecteddActors[2].remove(actor.prim.uid);
  3295. }
  3296. if (wac[2].y >= this._canvasSize.height) {
  3297. this._borderIntersecteddActors[3].add(actor.prim.uid, actor.prim);
  3298. }
  3299. else {
  3300. this._borderIntersecteddActors[3].remove(actor.prim.uid);
  3301. }
  3302. }
  3303. for (var y = sy; y <= ey; y++) {
  3304. var _loop_1 = function (x) {
  3305. var k = x + ":" + y;
  3306. var cx = x, cy = y;
  3307. var ci = actor.presentInClusters.getOrAddWithFactory(k, function (k) {
  3308. var nci = _this._getCluster(cx, cy);
  3309. nci.actors.add(actor.prim.uid, actor);
  3310. _this._maxActorByCluster = Math.max(_this._maxActorByCluster, nci.actors.count);
  3311. ++opCount;
  3312. ++totalClusters;
  3313. return nci;
  3314. });
  3315. newCI.push(ci);
  3316. };
  3317. for (var x = sx; x <= ex; x++) {
  3318. _loop_1(x);
  3319. }
  3320. }
  3321. // Check if there were no change
  3322. if (opCount === 0 && actor.presentInClusters.count === totalClusters) {
  3323. return;
  3324. }
  3325. // Build the array of the cluster where the actor is no longer in
  3326. var clusterToRemove = new Array();
  3327. actor.presentInClusters.forEach(function (k, ci) {
  3328. if (newCI.indexOf(ci) === -1) {
  3329. clusterToRemove.push(k);
  3330. // remove the primitive from the Cluster Info object
  3331. ci.actors.remove(actor.prim.uid);
  3332. }
  3333. });
  3334. // Remove these clusters from the actor's dictionary
  3335. for (var _i = 0, clusterToRemove_1 = clusterToRemove; _i < clusterToRemove_1.length; _i++) {
  3336. var key = clusterToRemove_1[_i];
  3337. actor.presentInClusters.remove(key);
  3338. }
  3339. };
  3340. // 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.
  3341. // Then for a given Actor that is dirty we evaluate the intersection with all the other actors present in the same Cluster(s)
  3342. // So it's basically O(n²), BUT only inside a Cluster and only for dirty Actors.
  3343. BasicPrimitiveCollisionManager.prototype._collisionDetection = function () {
  3344. var _this = this;
  3345. var hash = BasicPrimitiveCollisionManager.CandidatesActors;
  3346. var prev = BasicPrimitiveCollisionManager.PreviousIntersections;
  3347. var opCount = 0;
  3348. this._dirtyActors.forEach(function (k1, ai1) {
  3349. ++opCount;
  3350. // Build the list of candidates
  3351. hash.clear();
  3352. ai1.presentInClusters.forEach(function (k, ci) {
  3353. ++opCount;
  3354. ci.actors.forEach(function (k, v) { return hash.add(k, v); });
  3355. });
  3356. var wab1 = ai1.worldAABB;
  3357. // Save the previous intersections
  3358. prev.clear();
  3359. prev.copyFrom(ai1.intersectWith);
  3360. ai1.intersectWith.clear();
  3361. // For each candidate
  3362. hash.forEach(function (k2, ai2) {
  3363. ++opCount;
  3364. // Check if we're testing against itself
  3365. if (k1 === k2) {
  3366. return;
  3367. }
  3368. var wab2 = ai2.worldAABB;
  3369. if (wab2.z >= wab1.x && wab2.x <= wab1.z && wab2.w >= wab1.y && wab2.y <= wab1.w) {
  3370. if (ai1.prim.intersectOtherPrim(ai2.prim)) {
  3371. ++opCount;
  3372. ai1.intersectWith.add(k2, ai2);
  3373. if (k1 < k2) {
  3374. _this._intersectedActors.add(k1 + ";" + k2, { a: ai1.prim, b: ai2.prim });
  3375. }
  3376. else {
  3377. _this._intersectedActors.add(k2 + ";" + k1, { a: ai2.prim, b: ai1.prim });
  3378. }
  3379. }
  3380. }
  3381. });
  3382. // Check and remove the associations that no longer exist in the main intersection list
  3383. prev.forEach(function (k, ai) {
  3384. if (!ai1.intersectWith.contains(k)) {
  3385. ++opCount;
  3386. _this._intersectedActors.remove((k < k1 ? k : k1) + ";" + (k < k1 ? k1 : k));
  3387. }
  3388. });
  3389. });
  3390. this._debugUpdateOpCount.fetchNewFrame();
  3391. this._debugUpdateOpCount.addCount(opCount, true);
  3392. };
  3393. BasicPrimitiveCollisionManager.prototype._getCluster = function (x, y) {
  3394. return this._clusters[x][y];
  3395. };
  3396. BasicPrimitiveCollisionManager.prototype._updateDebugStats = function () {
  3397. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  3398. var txt = "Primitive Collision Stats\n" +
  3399. (" - PCM Execution Time: " + format(this._debugUpdateTime.lastSecAverage) + "ms\n") +
  3400. (" - Operation Count: " + format(this._debugUpdateOpCount.current) + ", (avg:" + format(this._debugUpdateOpCount.lastSecAverage) + ", t:" + format(this._debugUpdateOpCount.total) + ")\n") +
  3401. (" - Max Actor per Cluster: " + this._maxActorByCluster + "\n") +
  3402. (" - Intersections count: " + this.intersectedActors.count);
  3403. if (!this._debugTextBackground) {
  3404. this._debugTextBackground = new BABYLON.Rectangle2D({
  3405. id: "###DEBUG PMC STATS###", parent: this._owner, marginAlignment: "h: left, v: top", fill: "#C0404080", padding: "10", margin: "10", roundRadius: 10, children: [
  3406. new BABYLON.Text2D(txt, { id: "###DEBUG PMC TEXT###", fontName: "12pt Lucida Console" })
  3407. ]
  3408. });
  3409. }
  3410. else {
  3411. this._debugTextBackground.levelVisible = true;
  3412. var text2d = this._debugTextBackground.children[0];
  3413. text2d.text = txt;
  3414. }
  3415. };
  3416. BasicPrimitiveCollisionManager.prototype._updateAABBDisplay = function () {
  3417. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.5, 0.8, 1.0, 1.0));
  3418. var v = BABYLON.Vector2.Zero();
  3419. this._actors.forEach(function (k, ai) {
  3420. if (ai.isEnabled) {
  3421. var ab = ai.worldAABB;
  3422. v.x = ab.x;
  3423. v.y = ab.y;
  3424. g.startLineStrip(v);
  3425. v.x = ab.z;
  3426. g.pushVertex(v);
  3427. v.y = ab.w;
  3428. g.pushVertex(v);
  3429. v.x = ab.x;
  3430. g.pushVertex(v);
  3431. v.y = ab.y;
  3432. g.endLineStrip(v);
  3433. }
  3434. });
  3435. if (!this._AABBRenderPrim) {
  3436. this._AABBRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: false, id: "###DEBUG PCM AABB###" });
  3437. }
  3438. else {
  3439. this._AABBRenderPrim.wireFrameGroups.set("main", g);
  3440. this._AABBRenderPrim.wireFrameGroupsDirty();
  3441. }
  3442. this._debugRenderAABBDirty = false;
  3443. };
  3444. BasicPrimitiveCollisionManager.prototype._updateClusterDisplay = function (cw, ch) {
  3445. var g = new BABYLON.WireFrameGroup2D("main", new BABYLON.Color4(0.8, 0.1, 0.5, 1.0));
  3446. var v1 = BABYLON.Vector2.Zero();
  3447. var v2 = BABYLON.Vector2.Zero();
  3448. // Vertical lines
  3449. var step = (this._owner.actualWidth - 1) / cw;
  3450. v1.y = 0;
  3451. v2.y = this._owner.actualHeight;
  3452. for (var x = 0; x <= cw; x++) {
  3453. g.pushVertex(v1);
  3454. g.pushVertex(v2);
  3455. v1.x += step;
  3456. v2.x += step;
  3457. }
  3458. // Horizontal lines
  3459. step = (this._owner.actualHeight - 1) / ch;
  3460. v1.x = v1.y = v2.y = 0;
  3461. v2.x = this._owner.actualWidth;
  3462. for (var y = 0; y <= ch; y++) {
  3463. g.pushVertex(v1);
  3464. g.pushVertex(v2);
  3465. v1.y += step;
  3466. v2.y += step;
  3467. }
  3468. if (!this._ClusterRenderPrim) {
  3469. this._ClusterRenderPrim = new BABYLON.WireFrame2D([g], { parent: this._owner, alignToPixel: true, id: "###DEBUG PCM Clusters###" });
  3470. }
  3471. else {
  3472. this._ClusterRenderPrim.wireFrameGroups.set("main", g);
  3473. this._ClusterRenderPrim.wireFrameGroupsDirty();
  3474. }
  3475. };
  3476. // 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
  3477. // ClusterInfo object and we have two method to allocate/free them. This way we always deal with the same objects.
  3478. // The free array never shrink, always grows...For the better...and the worst!
  3479. BasicPrimitiveCollisionManager.prototype._allocClusterInfo = function () {
  3480. if (this._freeClusters.length === 0) {
  3481. for (var i = 0; i < 8; i++) {
  3482. this._freeClusters.push(new ClusterInfo());
  3483. }
  3484. }
  3485. return this._freeClusters.pop();
  3486. };
  3487. BasicPrimitiveCollisionManager.prototype._freeClusterInfo = function (ci) {
  3488. ci.clear();
  3489. this._freeClusters.push(ci);
  3490. };
  3491. return BasicPrimitiveCollisionManager;
  3492. }(PrimitiveCollisionManagerBase));
  3493. BasicPrimitiveCollisionManager.WAABBCorners = null;
  3494. BasicPrimitiveCollisionManager.WAABBCornersCluster = null;
  3495. BasicPrimitiveCollisionManager.CandidatesActors = new BABYLON.StringDictionary();
  3496. BasicPrimitiveCollisionManager.PreviousIntersections = new BABYLON.StringDictionary();
  3497. })(BABYLON || (BABYLON = {}));
  3498. //# sourceMappingURL=babylon.primitiveCollisionManager.js.map
  3499. var __extends = (this && this.__extends) || function (d, b) {
  3500. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3501. function __() { this.constructor = d; }
  3502. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3503. };
  3504. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  3505. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3506. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  3507. 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;
  3508. return c > 3 && r && Object.defineProperty(target, key, r), r;
  3509. };
  3510. var BABYLON;
  3511. (function (BABYLON) {
  3512. var LayoutEngineBase = (function () {
  3513. function LayoutEngineBase() {
  3514. this.layoutDirtyOnPropertyChangedMask = 0;
  3515. }
  3516. LayoutEngineBase.prototype.updateLayout = function (prim) {
  3517. };
  3518. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  3519. get: function () {
  3520. return false;
  3521. },
  3522. enumerable: true,
  3523. configurable: true
  3524. });
  3525. LayoutEngineBase.prototype.isLocked = function () {
  3526. return this._isLocked;
  3527. };
  3528. LayoutEngineBase.prototype.lock = function () {
  3529. if (this._isLocked) {
  3530. return false;
  3531. }
  3532. this._isLocked = true;
  3533. return true;
  3534. };
  3535. return LayoutEngineBase;
  3536. }());
  3537. LayoutEngineBase = __decorate([
  3538. BABYLON.className("LayoutEngineBase", "BABYLON")
  3539. ], LayoutEngineBase);
  3540. BABYLON.LayoutEngineBase = LayoutEngineBase;
  3541. var CanvasLayoutEngine = CanvasLayoutEngine_1 = (function (_super) {
  3542. __extends(CanvasLayoutEngine, _super);
  3543. function CanvasLayoutEngine() {
  3544. var _this = _super.call(this) || this;
  3545. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  3546. return _this;
  3547. }
  3548. Object.defineProperty(CanvasLayoutEngine, "Singleton", {
  3549. get: function () {
  3550. if (!CanvasLayoutEngine_1._singleton) {
  3551. CanvasLayoutEngine_1._singleton = new CanvasLayoutEngine_1();
  3552. }
  3553. return CanvasLayoutEngine_1._singleton;
  3554. },
  3555. enumerable: true,
  3556. configurable: true
  3557. });
  3558. // A very simple (no) layout computing...
  3559. // The Canvas and its direct children gets the Canvas' size as Layout Area
  3560. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  3561. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  3562. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  3563. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3564. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3565. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3566. var child = _a[_i];
  3567. this._doUpdate(child);
  3568. }
  3569. }
  3570. };
  3571. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  3572. // Canvas ?
  3573. if (prim instanceof BABYLON.Canvas2D) {
  3574. prim.layoutArea = prim.actualSize; //.multiplyByFloats(prim.scaleX, prim.scaleY);
  3575. }
  3576. else if (prim.parent instanceof BABYLON.Canvas2D) {
  3577. prim.layoutArea = prim.owner.actualSize; //.multiplyByFloats(prim.owner.scaleX, prim.owner.scaleY);
  3578. }
  3579. else {
  3580. var contentArea = prim.parent.contentArea;
  3581. // Can be null if the parent's content area depend of its children, the computation will be done in many passes
  3582. if (contentArea) {
  3583. prim.layoutArea = contentArea;
  3584. }
  3585. }
  3586. };
  3587. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  3588. get: function () {
  3589. return true;
  3590. },
  3591. enumerable: true,
  3592. configurable: true
  3593. });
  3594. return CanvasLayoutEngine;
  3595. }(LayoutEngineBase));
  3596. CanvasLayoutEngine._singleton = null;
  3597. CanvasLayoutEngine = CanvasLayoutEngine_1 = __decorate([
  3598. BABYLON.className("CanvasLayoutEngine", "BABYLON")
  3599. ], CanvasLayoutEngine);
  3600. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  3601. var StackPanelLayoutEngine = StackPanelLayoutEngine_1 = (function (_super) {
  3602. __extends(StackPanelLayoutEngine, _super);
  3603. function StackPanelLayoutEngine() {
  3604. var _this = _super.call(this) || this;
  3605. _this._isHorizontal = true;
  3606. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  3607. return _this;
  3608. }
  3609. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  3610. get: function () {
  3611. if (!StackPanelLayoutEngine_1._horizontal) {
  3612. StackPanelLayoutEngine_1._horizontal = new StackPanelLayoutEngine_1();
  3613. StackPanelLayoutEngine_1._horizontal.isHorizontal = true;
  3614. StackPanelLayoutEngine_1._horizontal.lock();
  3615. }
  3616. return StackPanelLayoutEngine_1._horizontal;
  3617. },
  3618. enumerable: true,
  3619. configurable: true
  3620. });
  3621. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  3622. get: function () {
  3623. if (!StackPanelLayoutEngine_1._vertical) {
  3624. StackPanelLayoutEngine_1._vertical = new StackPanelLayoutEngine_1();
  3625. StackPanelLayoutEngine_1._vertical.isHorizontal = false;
  3626. StackPanelLayoutEngine_1._vertical.lock();
  3627. }
  3628. return StackPanelLayoutEngine_1._vertical;
  3629. },
  3630. enumerable: true,
  3631. configurable: true
  3632. });
  3633. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  3634. get: function () {
  3635. return this._isHorizontal;
  3636. },
  3637. set: function (val) {
  3638. if (this.isLocked()) {
  3639. return;
  3640. }
  3641. this._isHorizontal = val;
  3642. },
  3643. enumerable: true,
  3644. configurable: true
  3645. });
  3646. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  3647. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3648. var primLayoutArea = prim.layoutArea;
  3649. var isSizeAuto = prim.isSizeAuto;
  3650. // If we're not in autoSize the layoutArea of the prim having the stack panel must be computed in order for us to compute the children' position.
  3651. // If there's at least one auto size (Horizontal or Vertical) we will have to figure the layoutArea ourselves
  3652. if (!primLayoutArea && !isSizeAuto) {
  3653. return;
  3654. }
  3655. // console.log("Compute Stack Panel Layout " + ++StackPanelLayoutEngine.computeCounter);
  3656. var x = 0;
  3657. var y = 0;
  3658. var horizonStackPanel = this.isHorizontal;
  3659. // If the stack panel is horizontal we check if the primitive height is auto or not, if it's auto then we have to compute the required height, otherwise we just take the actualHeight. If the stack panel is vertical we do the same but with width
  3660. var max = 0;
  3661. var stackPanelLayoutArea = StackPanelLayoutEngine_1.stackPanelLayoutArea;
  3662. if (horizonStackPanel) {
  3663. if (prim.isVerticalSizeAuto) {
  3664. max = 0;
  3665. stackPanelLayoutArea.height = 0;
  3666. }
  3667. else {
  3668. max = prim.layoutArea.height;
  3669. stackPanelLayoutArea.height = prim.layoutArea.height;
  3670. stackPanelLayoutArea.width = 0;
  3671. }
  3672. }
  3673. else {
  3674. if (prim.isHorizontalSizeAuto) {
  3675. max = 0;
  3676. stackPanelLayoutArea.width = 0;
  3677. }
  3678. else {
  3679. max = prim.layoutArea.width;
  3680. stackPanelLayoutArea.width = prim.layoutArea.width;
  3681. stackPanelLayoutArea.height = 0;
  3682. }
  3683. }
  3684. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3685. var child = _a[_i];
  3686. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3687. continue;
  3688. }
  3689. if (child._hasMargin) {
  3690. // Calling computeWithAlignment will return us the area taken by "child" which is its layoutArea
  3691. // We also have the dstOffset which will give us the y position in horizontal mode or x position in vertical mode.
  3692. // The alignment offset on the other axis is simply ignored as it doesn't make any sense (e.g. horizontal alignment is ignored in horizontal mode)
  3693. child.margin.computeWithAlignment(stackPanelLayoutArea, child.actualSize, child.marginAlignment, child.actualScale, StackPanelLayoutEngine_1.dstOffset, StackPanelLayoutEngine_1.dstArea, true);
  3694. child.layoutArea = StackPanelLayoutEngine_1.dstArea;
  3695. }
  3696. else {
  3697. child.margin.computeArea(child.actualSize, child.actualScale, StackPanelLayoutEngine_1.dstArea);
  3698. child.layoutArea = StackPanelLayoutEngine_1.dstArea;
  3699. }
  3700. max = Math.max(max, horizonStackPanel ? StackPanelLayoutEngine_1.dstArea.height : StackPanelLayoutEngine_1.dstArea.width);
  3701. }
  3702. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  3703. var child = _c[_b];
  3704. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3705. continue;
  3706. }
  3707. var layoutArea = child.layoutArea;
  3708. if (horizonStackPanel) {
  3709. child.layoutAreaPos = new BABYLON.Vector2(x, 0);
  3710. x += layoutArea.width;
  3711. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  3712. }
  3713. else {
  3714. child.layoutAreaPos = new BABYLON.Vector2(0, y);
  3715. y += layoutArea.height;
  3716. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  3717. }
  3718. }
  3719. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3720. }
  3721. };
  3722. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  3723. get: function () {
  3724. return false;
  3725. },
  3726. enumerable: true,
  3727. configurable: true
  3728. });
  3729. return StackPanelLayoutEngine;
  3730. }(LayoutEngineBase));
  3731. StackPanelLayoutEngine._horizontal = null;
  3732. StackPanelLayoutEngine._vertical = null;
  3733. StackPanelLayoutEngine.stackPanelLayoutArea = BABYLON.Size.Zero();
  3734. StackPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  3735. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  3736. StackPanelLayoutEngine.computeCounter = 0;
  3737. StackPanelLayoutEngine = StackPanelLayoutEngine_1 = __decorate([
  3738. BABYLON.className("StackPanelLayoutEngine", "BABYLON")
  3739. ], StackPanelLayoutEngine);
  3740. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  3741. /**
  3742. * GridData is used specify what row(s) and column(s) a primitive is placed in when its parent is using a Grid Panel Layout.
  3743. */
  3744. var GridData = (function () {
  3745. /**
  3746. * Create a Grid Data that describes where a primitive will be placed in a Grid Panel Layout.
  3747. * @param row the row number of the grid
  3748. * @param column the column number of the grid
  3749. * @param rowSpan the number of rows a primitive will occupy
  3750. * @param columnSpan the number of columns a primitive will occupy
  3751. **/
  3752. function GridData(row, column, rowSpan, columnSpan) {
  3753. this.row = row;
  3754. this.column = column;
  3755. this.rowSpan = (rowSpan == null) ? 1 : rowSpan;
  3756. this.columnSpan = (columnSpan == null) ? 1 : columnSpan;
  3757. }
  3758. return GridData;
  3759. }());
  3760. BABYLON.GridData = GridData;
  3761. var GridDimensionDefinition = (function () {
  3762. function GridDimensionDefinition() {
  3763. }
  3764. GridDimensionDefinition.prototype._parse = function (value, res) {
  3765. var v = value.toLocaleLowerCase().trim();
  3766. if (v.indexOf("auto") === 0) {
  3767. res(null, null, GridDimensionDefinition.Auto);
  3768. }
  3769. else if (v.indexOf("*") !== -1) {
  3770. var i = v.indexOf("*");
  3771. var w = 1;
  3772. if (i > 0) {
  3773. w = parseFloat(v.substr(0, i));
  3774. }
  3775. res(w, null, GridDimensionDefinition.Stars);
  3776. }
  3777. else {
  3778. var w = parseFloat(v);
  3779. res(w, w, GridDimensionDefinition.Pixels);
  3780. }
  3781. };
  3782. return GridDimensionDefinition;
  3783. }());
  3784. GridDimensionDefinition.Pixels = 1;
  3785. GridDimensionDefinition.Stars = 2;
  3786. GridDimensionDefinition.Auto = 3;
  3787. var RowDefinition = (function (_super) {
  3788. __extends(RowDefinition, _super);
  3789. function RowDefinition() {
  3790. return _super !== null && _super.apply(this, arguments) || this;
  3791. }
  3792. return RowDefinition;
  3793. }(GridDimensionDefinition));
  3794. var ColumnDefinition = (function (_super) {
  3795. __extends(ColumnDefinition, _super);
  3796. function ColumnDefinition() {
  3797. return _super !== null && _super.apply(this, arguments) || this;
  3798. }
  3799. return ColumnDefinition;
  3800. }(GridDimensionDefinition));
  3801. var GridPanelLayoutEngine = GridPanelLayoutEngine_1 = (function (_super) {
  3802. __extends(GridPanelLayoutEngine, _super);
  3803. function GridPanelLayoutEngine(settings) {
  3804. var _this = _super.call(this) || this;
  3805. _this._children = [];
  3806. _this._rowBottoms = [];
  3807. _this._columnLefts = [];
  3808. _this._rowHeights = [];
  3809. _this._columnWidths = [];
  3810. _this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId | BABYLON.Prim2DBase.actualSizeProperty.flagId;
  3811. _this._rows = new Array();
  3812. _this._columns = new Array();
  3813. if (settings.rows) {
  3814. var _loop_1 = function (row) {
  3815. var r = new RowDefinition();
  3816. r._parse(row.height, function (v, vp, t) {
  3817. r.height = v;
  3818. r.heightPixels = vp;
  3819. r.heightType = t;
  3820. });
  3821. this_1._rows.push(r);
  3822. };
  3823. var this_1 = this;
  3824. for (var _i = 0, _a = settings.rows; _i < _a.length; _i++) {
  3825. var row = _a[_i];
  3826. _loop_1(row);
  3827. }
  3828. }
  3829. if (settings.columns) {
  3830. var _loop_2 = function (col) {
  3831. var r = new ColumnDefinition();
  3832. r._parse(col.width, function (v, vp, t) {
  3833. r.width = v;
  3834. r.widthPixels = vp;
  3835. r.widthType = t;
  3836. });
  3837. this_2._columns.push(r);
  3838. };
  3839. var this_2 = this;
  3840. for (var _b = 0, _c = settings.columns; _b < _c.length; _b++) {
  3841. var col = _c[_b];
  3842. _loop_2(col);
  3843. }
  3844. }
  3845. return _this;
  3846. }
  3847. GridPanelLayoutEngine.prototype.updateLayout = function (prim) {
  3848. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  3849. if (!prim.layoutArea) {
  3850. return;
  3851. }
  3852. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3853. var child = _a[_i];
  3854. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  3855. continue;
  3856. }
  3857. if (child._hasMargin) {
  3858. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, child.actualScale, GridPanelLayoutEngine_1.dstOffset, GridPanelLayoutEngine_1.dstArea, true);
  3859. }
  3860. else {
  3861. child.margin.computeArea(child.actualSize, child.actualScale, GridPanelLayoutEngine_1.dstArea);
  3862. }
  3863. child.layoutArea = GridPanelLayoutEngine_1.dstArea;
  3864. }
  3865. this._updateGrid(prim);
  3866. var _children = this._children;
  3867. var rl = this._rows.length;
  3868. var cl = this._columns.length;
  3869. var columnWidth = 0;
  3870. var rowHeight = 0;
  3871. var dstArea = GridPanelLayoutEngine_1.dstArea;
  3872. var dstAreaPos = GridPanelLayoutEngine_1.dstAreaPos;
  3873. for (var i = 0; i < _children.length; i++) {
  3874. var children = _children[i];
  3875. if (children) {
  3876. var bottom = this._rowBottoms[i];
  3877. var rowHeight_1 = this._rowHeights[i];
  3878. var oBottom = bottom;
  3879. var oRowHeight = rowHeight_1;
  3880. for (var j = 0; j < children.length; j++) {
  3881. var left = this._columnLefts[j];
  3882. var columnWidth_1 = this._columnWidths[j];
  3883. var child = children[j];
  3884. if (child) {
  3885. var gd = child.layoutData;
  3886. if (gd.columnSpan > 1) {
  3887. for (var k = j + 1; k < gd.columnSpan + j && k < cl; k++) {
  3888. columnWidth_1 += this._columnWidths[k];
  3889. }
  3890. }
  3891. if (gd.rowSpan > 1) {
  3892. for (var k = i + 1; k < gd.rowSpan + i && k < rl; k++) {
  3893. rowHeight_1 += this._rowHeights[k];
  3894. bottom = this._rowBottoms[k];
  3895. }
  3896. }
  3897. dstArea.width = columnWidth_1;
  3898. dstArea.height = rowHeight_1;
  3899. child.layoutArea = dstArea;
  3900. dstAreaPos.x = left;
  3901. dstAreaPos.y = bottom;
  3902. child.layoutAreaPos = dstAreaPos;
  3903. bottom = oBottom;
  3904. rowHeight_1 = oRowHeight;
  3905. }
  3906. }
  3907. }
  3908. }
  3909. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  3910. }
  3911. };
  3912. Object.defineProperty(GridPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  3913. get: function () {
  3914. return false;
  3915. },
  3916. enumerable: true,
  3917. configurable: true
  3918. });
  3919. GridPanelLayoutEngine.prototype._getMaxChildHeightInRow = function (rowNum) {
  3920. var rows = this._rows;
  3921. var cl = this._columns.length;
  3922. var rl = this._rows.length;
  3923. var children = this._children;
  3924. var row = rows[rowNum];
  3925. var maxHeight = 0;
  3926. if (children && children[rowNum]) {
  3927. for (var i = 0; i < cl; i++) {
  3928. var child = children[rowNum][i];
  3929. if (child) {
  3930. var span = child.layoutData.rowSpan;
  3931. if (maxHeight < child.layoutArea.height / span) {
  3932. maxHeight = child.layoutArea.height / span;
  3933. }
  3934. }
  3935. }
  3936. }
  3937. return maxHeight;
  3938. };
  3939. GridPanelLayoutEngine.prototype._getMaxChildWidthInColumn = function (colNum) {
  3940. var columns = this._columns;
  3941. var cl = this._columns.length;
  3942. var rl = this._rows.length;
  3943. var children = this._children;
  3944. var column = columns[colNum];
  3945. var maxWidth = 0;
  3946. if (children) {
  3947. for (var i = 0; i < rl; i++) {
  3948. if (children[i]) {
  3949. var child = children[i][colNum];
  3950. if (child) {
  3951. var span = child.layoutData.columnSpan;
  3952. if (maxWidth < child.layoutArea.width / span) {
  3953. maxWidth = child.layoutArea.width / span;
  3954. }
  3955. }
  3956. }
  3957. }
  3958. }
  3959. return maxWidth;
  3960. };
  3961. GridPanelLayoutEngine.prototype._updateGrid = function (prim) {
  3962. var _children = this._children;
  3963. //remove prim.children from _children
  3964. for (var i_1 = 0; i_1 < _children.length; i_1++) {
  3965. var children = _children[i_1];
  3966. if (children) {
  3967. children.length = 0;
  3968. }
  3969. }
  3970. var childrenThatSpan;
  3971. //add prim.children to _children
  3972. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  3973. var child = _a[_i];
  3974. if (!child.layoutData) {
  3975. continue;
  3976. }
  3977. var gd = child.layoutData;
  3978. if (!_children[gd.row]) {
  3979. _children[gd.row] = [];
  3980. }
  3981. if (gd.columnSpan == 1 && gd.rowSpan == 1) {
  3982. _children[gd.row][gd.column] = child;
  3983. }
  3984. else {
  3985. if (!childrenThatSpan) {
  3986. childrenThatSpan = [];
  3987. }
  3988. //when children span, we need to add them to _children whereever they span to so that
  3989. //_getMaxChildHeightInRow and _getMaxChildWidthInColumn will work correctly.
  3990. childrenThatSpan.push(child);
  3991. for (var i_2 = gd.row; i_2 < gd.row + gd.rowSpan; i_2++) {
  3992. for (var j = gd.column; j < gd.column + gd.columnSpan; j++) {
  3993. _children[i_2][j] = child;
  3994. }
  3995. }
  3996. }
  3997. }
  3998. var rows = this._rows;
  3999. var columns = this._columns;
  4000. var rl = this._rows.length;
  4001. var cl = this._columns.length;
  4002. //get fixed and auto row heights first
  4003. var starIndexes = [];
  4004. var totalStars = 0;
  4005. var rowHeights = 0;
  4006. var columnWidths = 0;
  4007. for (var i_3 = 0; i_3 < rl; i_3++) {
  4008. var row = this._rows[i_3];
  4009. if (row.heightType == GridDimensionDefinition.Auto) {
  4010. this._rowHeights[i_3] = this._getMaxChildHeightInRow(i_3);
  4011. rowHeights += this._rowHeights[i_3];
  4012. }
  4013. else if (row.heightType == GridDimensionDefinition.Pixels) {
  4014. var maxChildHeight = this._getMaxChildHeightInRow(i_3);
  4015. this._rowHeights[i_3] = Math.max(row.heightPixels, maxChildHeight);
  4016. rowHeights += this._rowHeights[i_3];
  4017. }
  4018. else if (row.heightType == GridDimensionDefinition.Stars) {
  4019. starIndexes.push(i_3);
  4020. totalStars += row.height;
  4021. }
  4022. }
  4023. //star row heights
  4024. if (starIndexes.length > 0) {
  4025. var remainingHeight = prim.contentArea.height - rowHeights;
  4026. for (var i_4 = 0; i_4 < starIndexes.length; i_4++) {
  4027. var rowIndex = starIndexes[i_4];
  4028. var starHeight = (this._rows[rowIndex].height / totalStars) * remainingHeight;
  4029. var maxChildHeight = this._getMaxChildHeightInRow(i_4);
  4030. this._rowHeights[rowIndex] = Math.max(starHeight, maxChildHeight);
  4031. }
  4032. }
  4033. //get fixed and auto column widths
  4034. starIndexes.length = 0;
  4035. totalStars = 0;
  4036. for (var i_5 = 0; i_5 < cl; i_5++) {
  4037. var column = this._columns[i_5];
  4038. if (column.widthType == GridDimensionDefinition.Auto) {
  4039. this._columnWidths[i_5] = this._getMaxChildWidthInColumn(i_5);
  4040. columnWidths += this._columnWidths[i_5];
  4041. }
  4042. else if (column.widthType == GridDimensionDefinition.Pixels) {
  4043. var maxChildWidth = this._getMaxChildWidthInColumn(i_5);
  4044. this._columnWidths[i_5] = Math.max(column.widthPixels, maxChildWidth);
  4045. columnWidths += this._columnWidths[i_5];
  4046. }
  4047. else if (column.widthType == GridDimensionDefinition.Stars) {
  4048. starIndexes.push(i_5);
  4049. totalStars += column.width;
  4050. }
  4051. }
  4052. //star column widths
  4053. if (starIndexes.length > 0) {
  4054. var remainingWidth = prim.contentArea.width - columnWidths;
  4055. for (var i_6 = 0; i_6 < starIndexes.length; i_6++) {
  4056. var columnIndex = starIndexes[i_6];
  4057. var starWidth = (this._columns[columnIndex].width / totalStars) * remainingWidth;
  4058. var maxChildWidth = this._getMaxChildWidthInColumn(i_6);
  4059. this._columnWidths[columnIndex] = Math.max(starWidth, maxChildWidth);
  4060. }
  4061. }
  4062. var y = 0;
  4063. this._rowBottoms[rl - 1] = y;
  4064. for (var i_7 = rl - 2; i_7 >= 0; i_7--) {
  4065. y += this._rowHeights[i_7 + 1];
  4066. this._rowBottoms[i_7] = y;
  4067. }
  4068. var x = 0;
  4069. this._columnLefts[0] = x;
  4070. for (var i_8 = 1; i_8 < cl; i_8++) {
  4071. x += this._columnWidths[i_8 - 1];
  4072. this._columnLefts[i_8] = x;
  4073. }
  4074. //remove duplicate references to children that span
  4075. if (childrenThatSpan) {
  4076. for (var i = 0; i < childrenThatSpan.length; i++) {
  4077. var child = childrenThatSpan[i];
  4078. var gd = child.layoutData;
  4079. for (var i_9 = gd.row; i_9 < gd.row + gd.rowSpan; i_9++) {
  4080. for (var j = gd.column; j < gd.column + gd.columnSpan; j++) {
  4081. if (i_9 == gd.row && j == gd.column) {
  4082. continue;
  4083. }
  4084. if (_children[i_9][j] == child) {
  4085. _children[i_9][j] = null;
  4086. }
  4087. }
  4088. }
  4089. }
  4090. }
  4091. };
  4092. return GridPanelLayoutEngine;
  4093. }(LayoutEngineBase));
  4094. GridPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  4095. GridPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  4096. GridPanelLayoutEngine.dstAreaPos = BABYLON.Vector2.Zero();
  4097. GridPanelLayoutEngine = GridPanelLayoutEngine_1 = __decorate([
  4098. BABYLON.className("GridPanelLayoutEngine", "BABYLON")
  4099. ], GridPanelLayoutEngine);
  4100. BABYLON.GridPanelLayoutEngine = GridPanelLayoutEngine;
  4101. var CanvasLayoutEngine_1, StackPanelLayoutEngine_1, GridPanelLayoutEngine_1;
  4102. })(BABYLON || (BABYLON = {}));
  4103. //# sourceMappingURL=babylon.canvas2dLayoutEngine.js.map
  4104. var __extends = (this && this.__extends) || function (d, b) {
  4105. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4106. function __() { this.constructor = d; }
  4107. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4108. };
  4109. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4110. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4111. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4112. 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;
  4113. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4114. };
  4115. var BABYLON;
  4116. (function (BABYLON) {
  4117. /**
  4118. * Base class implementing the ILocable interface.
  4119. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  4120. */
  4121. var LockableBase = (function () {
  4122. function LockableBase() {
  4123. }
  4124. LockableBase.prototype.isLocked = function () {
  4125. return this._isLocked;
  4126. };
  4127. LockableBase.prototype.lock = function () {
  4128. if (this._isLocked) {
  4129. return true;
  4130. }
  4131. this.onLock();
  4132. this._isLocked = true;
  4133. return false;
  4134. };
  4135. /**
  4136. * Protected handler that will be called when the instance is about to be locked.
  4137. */
  4138. LockableBase.prototype.onLock = function () {
  4139. };
  4140. return LockableBase;
  4141. }());
  4142. BABYLON.LockableBase = LockableBase;
  4143. var SolidColorBrush2D = (function (_super) {
  4144. __extends(SolidColorBrush2D, _super);
  4145. function SolidColorBrush2D(color, lock) {
  4146. if (lock === void 0) { lock = false; }
  4147. var _this = _super.call(this) || this;
  4148. _this._color = color;
  4149. if (lock) {
  4150. {
  4151. _this.lock();
  4152. }
  4153. }
  4154. return _this;
  4155. }
  4156. /**
  4157. * Return true if the brush is transparent, false if it's totally opaque
  4158. */
  4159. SolidColorBrush2D.prototype.isTransparent = function () {
  4160. return this._color && this._color.a < 1.0;
  4161. };
  4162. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  4163. /**
  4164. * The color used by this instance to render
  4165. * @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.
  4166. */
  4167. get: function () {
  4168. return this._color;
  4169. },
  4170. set: function (value) {
  4171. if (this.isLocked()) {
  4172. return;
  4173. }
  4174. this._color = value;
  4175. },
  4176. enumerable: true,
  4177. configurable: true
  4178. });
  4179. /**
  4180. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  4181. */
  4182. SolidColorBrush2D.prototype.toString = function () {
  4183. return this._color.toHexString();
  4184. };
  4185. return SolidColorBrush2D;
  4186. }(LockableBase));
  4187. SolidColorBrush2D = __decorate([
  4188. BABYLON.className("SolidColorBrush2D", "BABYLON")
  4189. ], SolidColorBrush2D);
  4190. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  4191. var GradientColorBrush2D = (function (_super) {
  4192. __extends(GradientColorBrush2D, _super);
  4193. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  4194. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  4195. if (rotation === void 0) { rotation = 0; }
  4196. if (scale === void 0) { scale = 1; }
  4197. if (lock === void 0) { lock = false; }
  4198. var _this = _super.call(this) || this;
  4199. _this._color1 = color1;
  4200. _this._color2 = color2;
  4201. _this._translation = translation;
  4202. _this._rotation = rotation;
  4203. _this._scale = scale;
  4204. if (lock) {
  4205. _this.lock();
  4206. }
  4207. return _this;
  4208. }
  4209. /**
  4210. * Return true if the brush is transparent, false if it's totally opaque
  4211. */
  4212. GradientColorBrush2D.prototype.isTransparent = function () {
  4213. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  4214. };
  4215. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  4216. /**
  4217. * First color, the blend will start from this color
  4218. */
  4219. get: function () {
  4220. return this._color1;
  4221. },
  4222. set: function (value) {
  4223. if (this.isLocked()) {
  4224. return;
  4225. }
  4226. this._color1 = value;
  4227. },
  4228. enumerable: true,
  4229. configurable: true
  4230. });
  4231. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  4232. /**
  4233. * Second color, the blend will end to this color
  4234. */
  4235. get: function () {
  4236. return this._color2;
  4237. },
  4238. set: function (value) {
  4239. if (this.isLocked()) {
  4240. return;
  4241. }
  4242. this._color2 = value;
  4243. },
  4244. enumerable: true,
  4245. configurable: true
  4246. });
  4247. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  4248. /**
  4249. * Translation vector to apply on the blend
  4250. * Default is [0;0]
  4251. */
  4252. get: function () {
  4253. return this._translation;
  4254. },
  4255. set: function (value) {
  4256. if (this.isLocked()) {
  4257. return;
  4258. }
  4259. this._translation = value;
  4260. },
  4261. enumerable: true,
  4262. configurable: true
  4263. });
  4264. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  4265. /**
  4266. * Rotation in radian to apply to the brush
  4267. * Default direction of the brush is vertical, you can change this using this property.
  4268. * Default is 0.
  4269. */
  4270. get: function () {
  4271. return this._rotation;
  4272. },
  4273. set: function (value) {
  4274. if (this.isLocked()) {
  4275. return;
  4276. }
  4277. this._rotation = value;
  4278. },
  4279. enumerable: true,
  4280. configurable: true
  4281. });
  4282. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  4283. /**
  4284. * Scale factor to apply to the gradient.
  4285. * Default is 1: no scale.
  4286. */
  4287. get: function () {
  4288. return this._scale;
  4289. },
  4290. set: function (value) {
  4291. if (this.isLocked()) {
  4292. return;
  4293. }
  4294. this._scale = value;
  4295. },
  4296. enumerable: true,
  4297. configurable: true
  4298. });
  4299. /**
  4300. * Return a string describing the brush
  4301. */
  4302. GradientColorBrush2D.prototype.toString = function () {
  4303. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  4304. };
  4305. /**
  4306. * Build a unique key string for the given parameters
  4307. */
  4308. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  4309. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  4310. };
  4311. return GradientColorBrush2D;
  4312. }(LockableBase));
  4313. GradientColorBrush2D = __decorate([
  4314. BABYLON.className("GradientColorBrush2D", "BABYLON")
  4315. ], GradientColorBrush2D);
  4316. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  4317. })(BABYLON || (BABYLON = {}));
  4318. //# sourceMappingURL=babylon.brushes2d.js.map
  4319. var __extends = (this && this.__extends) || function (d, b) {
  4320. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  4321. function __() { this.constructor = d; }
  4322. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4323. };
  4324. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  4325. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  4326. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4327. 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;
  4328. return c > 3 && r && Object.defineProperty(target, key, r), r;
  4329. };
  4330. var BABYLON;
  4331. (function (BABYLON) {
  4332. var Prim2DClassInfo = (function () {
  4333. function Prim2DClassInfo() {
  4334. }
  4335. return Prim2DClassInfo;
  4336. }());
  4337. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  4338. var Prim2DPropInfo = (function () {
  4339. function Prim2DPropInfo() {
  4340. }
  4341. return Prim2DPropInfo;
  4342. }());
  4343. Prim2DPropInfo.PROPKIND_MODEL = 1;
  4344. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  4345. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  4346. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  4347. var ClassTreeInfo = (function () {
  4348. function ClassTreeInfo(baseClass, type, classContentFactory) {
  4349. this._baseClass = baseClass;
  4350. this._type = type;
  4351. this._subClasses = new Array();
  4352. this._levelContent = new BABYLON.StringDictionary();
  4353. this._classContentFactory = classContentFactory;
  4354. }
  4355. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  4356. get: function () {
  4357. if (!this._classContent) {
  4358. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  4359. }
  4360. return this._classContent;
  4361. },
  4362. enumerable: true,
  4363. configurable: true
  4364. });
  4365. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  4366. get: function () {
  4367. return this._type;
  4368. },
  4369. enumerable: true,
  4370. configurable: true
  4371. });
  4372. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  4373. get: function () {
  4374. return this._levelContent;
  4375. },
  4376. enumerable: true,
  4377. configurable: true
  4378. });
  4379. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  4380. get: function () {
  4381. if (!this._fullContent) {
  4382. var dic_1 = new BABYLON.StringDictionary();
  4383. var curLevel = this;
  4384. while (curLevel) {
  4385. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  4386. curLevel = curLevel._baseClass;
  4387. }
  4388. this._fullContent = dic_1;
  4389. }
  4390. return this._fullContent;
  4391. },
  4392. enumerable: true,
  4393. configurable: true
  4394. });
  4395. ClassTreeInfo.prototype.getLevelOf = function (type) {
  4396. // Are we already there?
  4397. if (type === this._type) {
  4398. return this;
  4399. }
  4400. var baseProto = Object.getPrototypeOf(type);
  4401. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  4402. if (!curProtoContent) {
  4403. this.getLevelOf(baseProto);
  4404. }
  4405. return this.getOrAddType(baseProto, type);
  4406. };
  4407. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  4408. // Are we at the level corresponding to the baseType?
  4409. // If so, get or add the level we're looking for
  4410. if (baseType === this._type) {
  4411. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  4412. var subType = _a[_i];
  4413. if (subType.type === type) {
  4414. return subType.node;
  4415. }
  4416. }
  4417. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  4418. var info = { type: type, node: node };
  4419. this._subClasses.push(info);
  4420. return info.node;
  4421. }
  4422. // Recurse down to keep looking for the node corresponding to the baseTypeName
  4423. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  4424. var subType = _c[_b];
  4425. var info = subType.node.getOrAddType(baseType, type);
  4426. if (info) {
  4427. return info;
  4428. }
  4429. }
  4430. return null;
  4431. };
  4432. ClassTreeInfo.get = function (type) {
  4433. var dic = type["__classTreeInfo"];
  4434. if (!dic) {
  4435. return null;
  4436. }
  4437. return dic.getLevelOf(type);
  4438. };
  4439. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  4440. var dic = type["__classTreeInfo"];
  4441. if (!dic) {
  4442. dic = new ClassTreeInfo(null, type, classContentFactory);
  4443. type["__classTreeInfo"] = dic;
  4444. }
  4445. return dic;
  4446. };
  4447. return ClassTreeInfo;
  4448. }());
  4449. BABYLON.ClassTreeInfo = ClassTreeInfo;
  4450. var DataBinding = DataBinding_1 = (function () {
  4451. function DataBinding() {
  4452. this._converter = null;
  4453. this._mode = DataBinding_1.MODE_DEFAULT;
  4454. this._uiElementId = null;
  4455. this._dataSource = null;
  4456. this._currentDataSource = null;
  4457. this._propertyPathName = null;
  4458. this._stringFormat = null;
  4459. this._updateSourceTrigger = DataBinding_1.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  4460. this._boundTo = null;
  4461. this._owner = null;
  4462. this._updateCounter = 0;
  4463. }
  4464. Object.defineProperty(DataBinding.prototype, "converter", {
  4465. /**
  4466. * Provide a callback that will convert the value obtained by the Data Binding to the type of the SmartProperty it's bound to.
  4467. * If no value are set, then it's assumed that the sourceValue is of the same type as the SmartProperty's one.
  4468. * 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.
  4469. * @param sourceValue the source object retrieve by the Data Binding mechanism
  4470. * @returns the object of a compatible type with the SmartProperty it's bound to
  4471. */
  4472. get: function () {
  4473. return this._converter;
  4474. },
  4475. set: function (value) {
  4476. if (this._converter === value) {
  4477. return;
  4478. }
  4479. this._converter = value;
  4480. },
  4481. enumerable: true,
  4482. configurable: true
  4483. });
  4484. Object.defineProperty(DataBinding.prototype, "mode", {
  4485. /**
  4486. * 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
  4487. */
  4488. get: function () {
  4489. if (this._mode === DataBinding_1.MODE_DEFAULT) {
  4490. return this._boundTo.bindingMode;
  4491. }
  4492. return this._mode;
  4493. },
  4494. set: function (value) {
  4495. if (this._mode === value) {
  4496. return;
  4497. }
  4498. this._mode = value;
  4499. },
  4500. enumerable: true,
  4501. configurable: true
  4502. });
  4503. Object.defineProperty(DataBinding.prototype, "uiElementId", {
  4504. /**
  4505. * You can override the Data Source object with this member which is the Id of a uiElement existing in the UI Logical tree.
  4506. * If not set and source no set too, then the dataSource property will be used.
  4507. */
  4508. get: function () {
  4509. return this._uiElementId;
  4510. },
  4511. set: function (value) {
  4512. if (this._uiElementId === value) {
  4513. return;
  4514. }
  4515. this._uiElementId = value;
  4516. },
  4517. enumerable: true,
  4518. configurable: true
  4519. });
  4520. Object.defineProperty(DataBinding.prototype, "dataSource", {
  4521. /**
  4522. * You can override the Data Source object with this member which is the source object to use directly.
  4523. * If not set and uiElement no set too, then the dataSource property of the SmartPropertyBase object will be used.
  4524. */
  4525. get: function () {
  4526. return this._dataSource;
  4527. },
  4528. set: function (value) {
  4529. if (this._dataSource === value) {
  4530. return;
  4531. }
  4532. this._dataSource = value;
  4533. },
  4534. enumerable: true,
  4535. configurable: true
  4536. });
  4537. Object.defineProperty(DataBinding.prototype, "propertyPathName", {
  4538. /**
  4539. * The path & name of the property to get from the source object.
  4540. * 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.
  4541. * If nothing is set then the source object will be used.
  4542. * 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.
  4543. * 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.
  4544. */
  4545. get: function () {
  4546. return this._propertyPathName;
  4547. },
  4548. set: function (value) {
  4549. if (this._propertyPathName === value) {
  4550. return;
  4551. }
  4552. if (this._owner) {
  4553. }
  4554. this._propertyPathName = value;
  4555. if (this._owner) {
  4556. }
  4557. },
  4558. enumerable: true,
  4559. configurable: true
  4560. });
  4561. Object.defineProperty(DataBinding.prototype, "stringFormat", {
  4562. /**
  4563. * 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}`
  4564. */
  4565. get: function () {
  4566. return this._stringFormat;
  4567. },
  4568. set: function (value) {
  4569. if (this._stringFormat === value) {
  4570. return;
  4571. }
  4572. this._stringFormat = value;
  4573. },
  4574. enumerable: true,
  4575. configurable: true
  4576. });
  4577. Object.defineProperty(DataBinding.prototype, "updateSourceTrigger", {
  4578. /**
  4579. * 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.
  4580. */
  4581. get: function () {
  4582. return this._updateSourceTrigger;
  4583. },
  4584. set: function (value) {
  4585. if (this._updateSourceTrigger === value) {
  4586. return;
  4587. }
  4588. this._updateSourceTrigger = value;
  4589. },
  4590. enumerable: true,
  4591. configurable: true
  4592. });
  4593. DataBinding.prototype.canUpdateTarget = function (resetUpdateCounter) {
  4594. if (resetUpdateCounter) {
  4595. this._updateCounter = 0;
  4596. }
  4597. var mode = this.mode;
  4598. if (mode === DataBinding_1.MODE_ONETIME) {
  4599. return this._updateCounter === 0;
  4600. }
  4601. if (mode === DataBinding_1.MODE_ONEWAYTOSOURCE) {
  4602. return false;
  4603. }
  4604. return true;
  4605. };
  4606. DataBinding.prototype.updateTarget = function () {
  4607. var value = this._getActualDataSource();
  4608. var properties = this.propertyPathName.split(".");
  4609. for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
  4610. var propertyName = properties_1[_i];
  4611. value = value[propertyName];
  4612. }
  4613. this._storeBoundValue(this._owner, value);
  4614. };
  4615. DataBinding.prototype._storeBoundValue = function (watcher, value) {
  4616. if ((++this._updateCounter > 1) && (this.mode === DataBinding_1.MODE_ONETIME)) {
  4617. return;
  4618. }
  4619. var newValue = value;
  4620. if (this._converter) {
  4621. newValue = this._converter(value);
  4622. }
  4623. if (this._stringFormat) {
  4624. newValue = this._stringFormat(newValue);
  4625. }
  4626. watcher[this._boundTo.name] = newValue;
  4627. };
  4628. DataBinding.prototype._getActualDataSource = function () {
  4629. if (this.dataSource) {
  4630. return this.dataSource;
  4631. }
  4632. if (this.uiElementId) {
  4633. // TODO Find UIElement
  4634. return null;
  4635. }
  4636. return this._owner.dataSource;
  4637. };
  4638. DataBinding.prototype._registerDataSource = function (updateTarget) {
  4639. var ds = this._getActualDataSource();
  4640. if (ds === this._currentDataSource) {
  4641. return;
  4642. }
  4643. if (this._currentDataSource) {
  4644. BindingHelper.unregisterDataSource(this._currentDataSource, this, 0);
  4645. }
  4646. if (ds) {
  4647. BindingHelper.registerDataSource(ds, this);
  4648. if (updateTarget && this.canUpdateTarget(true)) {
  4649. this.updateTarget();
  4650. }
  4651. }
  4652. this._currentDataSource = ds;
  4653. };
  4654. DataBinding.prototype._unregisterDataSource = function () {
  4655. var ds = this._getActualDataSource();
  4656. if (ds) {
  4657. BindingHelper.unregisterDataSource(ds, this, 0);
  4658. }
  4659. };
  4660. return DataBinding;
  4661. }());
  4662. /**
  4663. * Use the mode specified in the SmartProperty declaration
  4664. */
  4665. DataBinding.MODE_DEFAULT = 1;
  4666. /**
  4667. * Update the binding target only once when the Smart Property's value is first accessed
  4668. */
  4669. DataBinding.MODE_ONETIME = 2;
  4670. /**
  4671. * Update the smart property when the source changes.
  4672. * The source won't be updated if the smart property value is set.
  4673. */
  4674. DataBinding.MODE_ONEWAY = 3;
  4675. /**
  4676. * Only update the source when the target's data is changing.
  4677. */
  4678. DataBinding.MODE_ONEWAYTOSOURCE = 4;
  4679. /**
  4680. * Update the bind target when the source changes and update the source when the Smart Property value is set.
  4681. */
  4682. DataBinding.MODE_TWOWAY = 5;
  4683. /**
  4684. * Use the Update Source Trigger defined in the SmartProperty declaration
  4685. */
  4686. DataBinding.UPDATESOURCETRIGGER_DEFAULT = 1;
  4687. /**
  4688. * Update the source as soon as the Smart Property has a value change
  4689. */
  4690. DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED = 2;
  4691. /**
  4692. * Update the source when the binding target loses focus
  4693. */
  4694. DataBinding.UPDATESOURCETRIGGER_LOSTFOCUS = 3;
  4695. /**
  4696. * Update the source will be made by explicitly calling the UpdateFromDataSource method
  4697. */
  4698. DataBinding.UPDATESOURCETRIGGER_EXPLICIT = 4;
  4699. DataBinding = DataBinding_1 = __decorate([
  4700. BABYLON.className("DataBinding", "BABYLON")
  4701. ], DataBinding);
  4702. BABYLON.DataBinding = DataBinding;
  4703. var SmartPropertyBase = SmartPropertyBase_1 = (function (_super) {
  4704. __extends(SmartPropertyBase, _super);
  4705. function SmartPropertyBase() {
  4706. var _this = _super.call(this) || this;
  4707. _this._dataSource = null;
  4708. _this._dataSourceObserver = null;
  4709. _this._instanceDirtyFlags = 0;
  4710. _this._isDisposed = false;
  4711. _this._bindings = null;
  4712. _this._hasBinding = 0;
  4713. _this._bindingSourceChanged = 0;
  4714. _this._disposeObservable = null;
  4715. return _this;
  4716. }
  4717. Object.defineProperty(SmartPropertyBase.prototype, "disposeObservable", {
  4718. get: function () {
  4719. if (!this._disposeObservable) {
  4720. this._disposeObservable = new BABYLON.Observable();
  4721. }
  4722. return this._disposeObservable;
  4723. },
  4724. enumerable: true,
  4725. configurable: true
  4726. });
  4727. Object.defineProperty(SmartPropertyBase.prototype, "isDisposed", {
  4728. /**
  4729. * Check if the object is disposed or not.
  4730. * @returns true if the object is dispose, false otherwise.
  4731. */
  4732. get: function () {
  4733. return this._isDisposed;
  4734. },
  4735. enumerable: true,
  4736. configurable: true
  4737. });
  4738. /**
  4739. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  4740. * @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.
  4741. */
  4742. SmartPropertyBase.prototype.dispose = function () {
  4743. if (this.isDisposed) {
  4744. return false;
  4745. }
  4746. if (this._disposeObservable && this._disposeObservable.hasObservers()) {
  4747. this._disposeObservable.notifyObservers(this);
  4748. }
  4749. this._isDisposed = true;
  4750. return true;
  4751. };
  4752. /**
  4753. * Check if a given set of properties are dirty or not.
  4754. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  4755. * @return true if at least one property is dirty, false if none of them are.
  4756. */
  4757. SmartPropertyBase.prototype.checkPropertiesDirty = function (flags) {
  4758. return (this._instanceDirtyFlags & flags) !== 0;
  4759. };
  4760. /**
  4761. * Clear a given set of properties.
  4762. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  4763. * @return the new set of property still marked as dirty
  4764. */
  4765. SmartPropertyBase.prototype.clearPropertiesDirty = function (flags) {
  4766. this._instanceDirtyFlags &= ~flags;
  4767. return this._instanceDirtyFlags;
  4768. };
  4769. SmartPropertyBase.prototype._resetPropertiesDirty = function () {
  4770. this._instanceDirtyFlags = 0;
  4771. };
  4772. /**
  4773. * Add an externally attached data from its key.
  4774. * This method call will fail and return false, if such key already exists.
  4775. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  4776. * @param key the unique key that identifies the data
  4777. * @param data the data object to associate to the key for this Engine instance
  4778. * @return true if no such key were already present and the data was added successfully, false otherwise
  4779. */
  4780. SmartPropertyBase.prototype.addExternalData = function (key, data) {
  4781. if (!this._externalData) {
  4782. this._externalData = new BABYLON.StringDictionary();
  4783. }
  4784. return this._externalData.add(key, data);
  4785. };
  4786. /**
  4787. * Get an externally attached data from its key
  4788. * @param key the unique key that identifies the data
  4789. * @return the associated data, if present (can be null), or undefined if not present
  4790. */
  4791. SmartPropertyBase.prototype.getExternalData = function (key) {
  4792. if (!this._externalData) {
  4793. return null;
  4794. }
  4795. return this._externalData.get(key);
  4796. };
  4797. /**
  4798. * Get an externally attached data from its key, create it using a factory if it's not already present
  4799. * @param key the unique key that identifies the data
  4800. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  4801. * @return the associated data, can be null if the factory returned null.
  4802. */
  4803. SmartPropertyBase.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  4804. if (!this._externalData) {
  4805. this._externalData = new BABYLON.StringDictionary();
  4806. }
  4807. return this._externalData.getOrAddWithFactory(key, factory);
  4808. };
  4809. /**
  4810. * Remove an externally attached data from the Engine instance
  4811. * @param key the unique key that identifies the data
  4812. * @return true if the data was successfully removed, false if it doesn't exist
  4813. */
  4814. SmartPropertyBase.prototype.removeExternalData = function (key) {
  4815. if (!this._externalData) {
  4816. return false;
  4817. }
  4818. return this._externalData.remove(key);
  4819. };
  4820. SmartPropertyBase._hookProperty = function (propId, piStore, kind, settings) {
  4821. return function (target, propName, descriptor) {
  4822. if (!settings) {
  4823. settings = {};
  4824. }
  4825. var propInfo = SmartPropertyBase_1._createPropInfo(target, propName, propId, kind, settings);
  4826. if (piStore) {
  4827. piStore(propInfo);
  4828. }
  4829. var getter = descriptor.get, setter = descriptor.set;
  4830. var typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  4831. // Overload the property setter implementation to add our own logic
  4832. descriptor.set = function (val) {
  4833. if (!setter) {
  4834. throw Error("Property '" + propInfo.name + "' of type '" + BABYLON.Tools.getFullClassName(this) + "' has no setter defined but was invoked as if it had one.");
  4835. }
  4836. // check for disposed first, do nothing
  4837. if (this.isDisposed) {
  4838. return;
  4839. }
  4840. var curVal = getter.call(this);
  4841. if (SmartPropertyBase_1._checkUnchanged(curVal, val)) {
  4842. return;
  4843. }
  4844. // Cast the object we're working one
  4845. var prim = this;
  4846. // Change the value
  4847. setter.call(this, val);
  4848. // Notify change, dirty flags update
  4849. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  4850. };
  4851. };
  4852. };
  4853. SmartPropertyBase._createPropInfo = function (target, propName, propId, kind, settings) {
  4854. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  4855. var node = dic.getLevelOf(target);
  4856. var propInfo = node.levelContent.get(propId.toString());
  4857. if (propInfo) {
  4858. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  4859. }
  4860. // Create, setup and add the PropInfo object to our prop dictionary
  4861. propInfo = new Prim2DPropInfo();
  4862. propInfo.id = propId;
  4863. propInfo.flagId = Math.pow(2, propId);
  4864. propInfo.kind = kind;
  4865. propInfo.name = propName;
  4866. propInfo.bindingMode = (settings.bindingMode !== undefined) ? settings.bindingMode : DataBinding.MODE_TWOWAY;
  4867. propInfo.bindingUpdateSourceTrigger = (settings.bindingUpdateSourceTrigger !== undefined) ? settings.bindingUpdateSourceTrigger : DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  4868. propInfo.dirtyBoundingInfo = (settings.dirtyBoundingInfo !== undefined) ? settings.dirtyBoundingInfo : false;
  4869. propInfo.dirtyParentBoundingInfo = (settings.dirtyParentBoundingBox !== undefined) ? settings.dirtyParentBoundingBox : false;
  4870. propInfo.typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  4871. node.levelContent.add(propName, propInfo);
  4872. return propInfo;
  4873. };
  4874. Object.defineProperty(SmartPropertyBase.prototype, "propDic", {
  4875. /**
  4876. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  4877. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  4878. */
  4879. get: function () {
  4880. if (!this._propInfo) {
  4881. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  4882. if (!cti) {
  4883. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  4884. }
  4885. this._propInfo = cti.fullContent;
  4886. }
  4887. return this._propInfo;
  4888. },
  4889. enumerable: true,
  4890. configurable: true
  4891. });
  4892. SmartPropertyBase._checkUnchanged = function (curValue, newValue) {
  4893. // Nothing to nothing: nothing to do!
  4894. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  4895. return true;
  4896. }
  4897. // Check value unchanged
  4898. if ((curValue != null) && (newValue != null)) {
  4899. if (typeof (curValue.equals) == "function") {
  4900. if (curValue.equals(newValue)) {
  4901. return true;
  4902. }
  4903. }
  4904. else {
  4905. if (curValue === newValue) {
  4906. return true;
  4907. }
  4908. }
  4909. }
  4910. return false;
  4911. };
  4912. SmartPropertyBase.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  4913. // Trigger property changed
  4914. var info = SmartPropertyBase_1.propChangeGuarding ? new BABYLON.PropertyChangedInfo() : SmartPropertyPrim.propChangedInfo;
  4915. info.oldValue = curValue;
  4916. info.newValue = newValue;
  4917. info.propertyName = propName;
  4918. var propMask = propInfo ? propInfo.flagId : -1;
  4919. try {
  4920. SmartPropertyBase_1.propChangeGuarding = true;
  4921. this.propertyChanged.notifyObservers(info, propMask);
  4922. }
  4923. finally {
  4924. SmartPropertyBase_1.propChangeGuarding = false;
  4925. }
  4926. };
  4927. SmartPropertyBase.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  4928. if (this.isDisposed) {
  4929. return;
  4930. }
  4931. if (!propInfo) {
  4932. return;
  4933. }
  4934. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  4935. };
  4936. Object.defineProperty(SmartPropertyBase.prototype, "dataSource", {
  4937. /**
  4938. * Set the object from which Smart Properties using Binding will take/update their data from/to.
  4939. * 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.
  4940. */
  4941. get: function () {
  4942. // Don't access to _dataSource directly but via a call to the _getDataSource method which can be overloaded in inherited classes
  4943. return this._getDataSource();
  4944. },
  4945. set: function (value) {
  4946. if (this._dataSource === value) {
  4947. return;
  4948. }
  4949. var oldValue = this._dataSource;
  4950. this._dataSource = value;
  4951. if (this._bindings && value != null) {
  4952. // Register the bindings
  4953. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  4954. var binding = _a[_i];
  4955. if (binding != null) {
  4956. binding._registerDataSource(true);
  4957. }
  4958. }
  4959. }
  4960. this.onPropertyChanged("dataSource", oldValue, value);
  4961. },
  4962. enumerable: true,
  4963. configurable: true
  4964. });
  4965. // Inheriting classes can overload this method to provides additional logic for dataSource access
  4966. SmartPropertyBase.prototype._getDataSource = function () {
  4967. return this._dataSource;
  4968. };
  4969. SmartPropertyBase.prototype.createSimpleDataBinding = function (propInfo, propertyPathName, mode) {
  4970. if (mode === void 0) { mode = DataBinding.MODE_DEFAULT; }
  4971. var binding = new DataBinding();
  4972. binding.propertyPathName = propertyPathName;
  4973. binding.mode = mode;
  4974. return this.createDataBinding(propInfo, binding);
  4975. };
  4976. SmartPropertyBase.prototype.createDataBinding = function (propInfo, binding) {
  4977. if (!this._bindings) {
  4978. this._bindings = new Array();
  4979. }
  4980. if (!binding || binding._owner != null) {
  4981. throw Error("A valid/unused Binding must be passed.");
  4982. }
  4983. // Unregister a potentially existing binding for this property
  4984. this.removeDataBinding(propInfo);
  4985. // register the binding
  4986. binding._owner = this;
  4987. binding._boundTo = propInfo;
  4988. this._bindings[propInfo.id] = binding;
  4989. this._hasBinding |= propInfo.flagId;
  4990. binding._registerDataSource(true);
  4991. return binding;
  4992. };
  4993. SmartPropertyBase.prototype.removeDataBinding = function (propInfo) {
  4994. if ((this._hasBinding & propInfo.flagId) === 0) {
  4995. return false;
  4996. }
  4997. var curBinding = this._bindings[propInfo.id];
  4998. curBinding._unregisterDataSource();
  4999. this._bindings[propInfo.id] = null;
  5000. this._hasBinding &= ~propInfo.flagId;
  5001. return true;
  5002. };
  5003. SmartPropertyBase.prototype.updateFromDataSource = function () {
  5004. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  5005. var binding = _a[_i];
  5006. if (binding) {
  5007. }
  5008. }
  5009. };
  5010. return SmartPropertyBase;
  5011. }(BABYLON.PropertyChangedBase));
  5012. SmartPropertyBase.propChangedInfo = new BABYLON.PropertyChangedInfo();
  5013. SmartPropertyBase.propChangeGuarding = false;
  5014. SmartPropertyBase = SmartPropertyBase_1 = __decorate([
  5015. BABYLON.className("SmartPropertyBase", "BABYLON")
  5016. ], SmartPropertyBase);
  5017. BABYLON.SmartPropertyBase = SmartPropertyBase;
  5018. var BindingInfo = (function () {
  5019. function BindingInfo(binding, level, isLast) {
  5020. this.binding = binding;
  5021. this.level = level;
  5022. this.isLast = isLast;
  5023. }
  5024. return BindingInfo;
  5025. }());
  5026. var MonitoredObjectData = (function () {
  5027. function MonitoredObjectData(monitoredObject) {
  5028. var _this = this;
  5029. this.monitoredObject = monitoredObject;
  5030. this.monitoredIntermediateProperties = new BABYLON.StringDictionary();
  5031. this.observer = this.monitoredObject.propertyChanged.add(function (e, s) { _this.propertyChangedHandler(e.propertyName, e.oldValue, e.newValue); });
  5032. this.boundProperties = new BABYLON.StringDictionary();
  5033. this.monitoredIntermediateMask = 0;
  5034. this.boundPropertiesMask = 0;
  5035. }
  5036. MonitoredObjectData.prototype.propertyChangedHandler = function (propName, oldValue, newValue) {
  5037. var propId = BindingHelper._getPropertyID(this.monitoredObject, propName);
  5038. var propIdStr = propId.toString();
  5039. // Loop through all the registered bindings for this property that had a value change
  5040. if ((this.boundPropertiesMask & propId) !== 0) {
  5041. var bindingInfos = this.boundProperties.get(propIdStr);
  5042. for (var _i = 0, bindingInfos_1 = bindingInfos; _i < bindingInfos_1.length; _i++) {
  5043. var bi = bindingInfos_1[_i];
  5044. if (!bi.isLast) {
  5045. BindingHelper.unregisterDataSource(this.monitoredObject, bi.binding, bi.level);
  5046. BindingHelper.registerDataSource(bi.binding._currentDataSource, bi.binding);
  5047. }
  5048. if (bi.binding.canUpdateTarget(false)) {
  5049. bi.binding.updateTarget();
  5050. }
  5051. }
  5052. }
  5053. };
  5054. return MonitoredObjectData;
  5055. }());
  5056. var BindingHelper = (function () {
  5057. function BindingHelper() {
  5058. }
  5059. BindingHelper.registerDataSource = function (dataSource, binding) {
  5060. var properties = binding.propertyPathName.split(".");
  5061. var ownerMod = null;
  5062. var ownerInterPropId = 0;
  5063. var propertyOwner = dataSource;
  5064. var _loop_1 = function (i) {
  5065. var propName = properties[i];
  5066. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  5067. var propIdStr = propId.toString();
  5068. var mod = void 0;
  5069. if (ownerMod) {
  5070. var o_1 = ownerMod;
  5071. var po_1 = propertyOwner;
  5072. var oii_1 = ownerInterPropId;
  5073. mod = ownerMod.monitoredIntermediateProperties.getOrAddWithFactory(oii_1.toString(), function (k) {
  5074. o_1.monitoredIntermediateMask |= oii_1;
  5075. return BindingHelper._getMonitoredObjectData(po_1);
  5076. });
  5077. }
  5078. else {
  5079. mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  5080. }
  5081. var m = mod;
  5082. var bindingInfos = mod.boundProperties.getOrAddWithFactory(propIdStr, function (k) {
  5083. m.boundPropertiesMask |= propId;
  5084. return new Array();
  5085. });
  5086. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  5087. if (!bi) {
  5088. bindingInfos.push(new BindingInfo(binding, i, (i + 1) === properties.length));
  5089. }
  5090. ownerMod = mod;
  5091. ownerInterPropId = propId;
  5092. propertyOwner = propertyOwner[propName];
  5093. };
  5094. for (var i = 0; i < properties.length; i++) {
  5095. _loop_1(i);
  5096. }
  5097. };
  5098. BindingHelper.unregisterDataSource = function (dataSource, binding, level) {
  5099. var properties = binding.propertyPathName.split(".");
  5100. var propertyOwner = dataSource;
  5101. var mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  5102. for (var i = 0; i < properties.length; i++) {
  5103. var propName = properties[i];
  5104. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  5105. var propIdStr = propId.toString();
  5106. if (i >= level) {
  5107. mod = BindingHelper._unregisterBinding(mod, propId, binding);
  5108. }
  5109. else {
  5110. mod = mod.monitoredIntermediateProperties.get(propIdStr);
  5111. }
  5112. propertyOwner = propertyOwner[propName];
  5113. }
  5114. };
  5115. BindingHelper._unregisterBinding = function (mod, propertyID, binding) {
  5116. var propertyIDStr = propertyID.toString();
  5117. var res = null;
  5118. // Check if the property is registered as an intermediate and remove it
  5119. if ((mod.monitoredIntermediateMask & propertyID) !== 0) {
  5120. res = mod.monitoredIntermediateProperties.get(propertyIDStr);
  5121. mod.monitoredIntermediateProperties.remove(propertyIDStr);
  5122. // Update the mask
  5123. mod.monitoredIntermediateMask &= ~propertyID;
  5124. }
  5125. // Check if the property is registered as a final property and remove it
  5126. if ((mod.boundPropertiesMask & propertyID) !== 0) {
  5127. var bindingInfos = mod.boundProperties.get(propertyIDStr);
  5128. // Find the binding and remove it
  5129. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  5130. if (bi) {
  5131. var bii = bindingInfos.indexOf(bi);
  5132. bindingInfos.splice(bii, 1);
  5133. }
  5134. // If the array is empty, update the mask
  5135. if (bindingInfos.length === 0) {
  5136. mod.boundPropertiesMask &= ~propertyID;
  5137. }
  5138. }
  5139. // Check if the MOD is empty and unregister the observer and remove it from the list of MODs
  5140. if (mod.boundPropertiesMask === 0 && mod.monitoredIntermediateMask === 0) {
  5141. // Unregister the observer on Property Change
  5142. mod.monitoredObject.propertyChanged.remove(mod.observer);
  5143. // Remove the MOD from the dic
  5144. var objectId = BindingHelper._getObjectId(mod.monitoredObject);
  5145. BindingHelper._monitoredObjects.remove(objectId);
  5146. }
  5147. return res;
  5148. };
  5149. BindingHelper._getMonitoredObjectData = function (object) {
  5150. var objectId = BindingHelper._getObjectId(object);
  5151. var mod = BindingHelper._monitoredObjects.getOrAddWithFactory(objectId, function (k) { return new MonitoredObjectData(object); });
  5152. return mod;
  5153. };
  5154. BindingHelper._getObjectId = function (obj) {
  5155. var id = obj["__bindingHelperObjectId__"];
  5156. if (id == null) {
  5157. id = BABYLON.Tools.RandomId();
  5158. obj["__bindingHelperObjectId__"] = id;
  5159. return id;
  5160. }
  5161. return id;
  5162. };
  5163. BindingHelper._getObjectTypePropertyIDs = function (obj) {
  5164. var fullName = BABYLON.Tools.getFullClassName(obj);
  5165. if (!fullName) {
  5166. throw Error("Types involved in Data Binding must be decorated with the @className decorator");
  5167. }
  5168. var d = BindingHelper._propertiesID.getOrAddWithFactory(fullName, function () { return new BABYLON.StringDictionary(); });
  5169. return d;
  5170. };
  5171. BindingHelper._getPropertyID = function (object, propName) {
  5172. var otd = BindingHelper._getObjectTypePropertyIDs(object);
  5173. // Make sure we have a WatchedPropertyData for this property of this object type. This will contains the flagIg of the watched property.
  5174. // We use this flagId to flag for each watched instance which properties are watched, as final or intermediate and which directions are used
  5175. var propData = otd.getOrAddWithFactory(propName, function (k) { return 1 << otd.count; });
  5176. return propData;
  5177. };
  5178. return BindingHelper;
  5179. }());
  5180. BindingHelper._propertiesID = new BABYLON.StringDictionary();
  5181. BindingHelper._monitoredObjects = new BABYLON.StringDictionary();
  5182. var SmartPropertyPrim = SmartPropertyPrim_1 = (function (_super) {
  5183. __extends(SmartPropertyPrim, _super);
  5184. function SmartPropertyPrim() {
  5185. var _this = _super.call(this) || this;
  5186. _this._flags = 0;
  5187. _this._uid = null;
  5188. _this._modelKey = null;
  5189. _this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  5190. _this._boundingInfo = new BABYLON.BoundingInfo2D();
  5191. _this.animations = new Array();
  5192. return _this;
  5193. }
  5194. /**
  5195. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  5196. * @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.
  5197. */
  5198. SmartPropertyPrim.prototype.dispose = function () {
  5199. if (this.isDisposed) {
  5200. return false;
  5201. }
  5202. _super.prototype.dispose.call(this);
  5203. // Don't set to null, it may upset somebody...
  5204. this.animations.splice(0);
  5205. return true;
  5206. };
  5207. Object.defineProperty(SmartPropertyPrim.prototype, "uid", {
  5208. /**
  5209. * return a unique identifier for the Canvas2D
  5210. */
  5211. get: function () {
  5212. if (!this._uid) {
  5213. this._uid = BABYLON.Tools.RandomId();
  5214. }
  5215. return this._uid;
  5216. },
  5217. enumerable: true,
  5218. configurable: true
  5219. });
  5220. /**
  5221. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  5222. * Look at Sprite2D for more information
  5223. */
  5224. SmartPropertyPrim.prototype.getAnimatables = function () {
  5225. return new Array();
  5226. };
  5227. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  5228. /**
  5229. * Property giving the Model Key associated to the property.
  5230. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  5231. * @returns the model key string.
  5232. */
  5233. get: function () {
  5234. var _this = this;
  5235. // No need to compute it?
  5236. if (!this._isFlagSet(SmartPropertyPrim_1.flagModelDirty) && this._modelKey) {
  5237. return this._modelKey;
  5238. }
  5239. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  5240. var propDic = this.propDic;
  5241. propDic.forEach(function (k, v) {
  5242. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  5243. var propVal = _this[v.name];
  5244. // 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
  5245. if (propVal && propVal.constructor === Array) {
  5246. var firstVal = propVal[0];
  5247. if (!firstVal) {
  5248. propVal = 0;
  5249. }
  5250. else {
  5251. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  5252. }
  5253. }
  5254. var value = "[null]";
  5255. if (propVal != null) {
  5256. if (v.typeLevelCompare) {
  5257. value = BABYLON.Tools.getClassName(propVal);
  5258. }
  5259. else {
  5260. // String Dictionaries' content are too complex, with use a Random GUID to make the model unique
  5261. if (propVal instanceof BABYLON.StringDictionary) {
  5262. value = BABYLON.Tools.RandomId();
  5263. }
  5264. else if (propVal instanceof BABYLON.BaseTexture) {
  5265. value = propVal.uid;
  5266. }
  5267. else {
  5268. value = propVal.toString();
  5269. }
  5270. }
  5271. }
  5272. modelKey += v.name + ":" + value + ";";
  5273. }
  5274. });
  5275. this._clearFlags(SmartPropertyPrim_1.flagModelDirty);
  5276. this._modelKey = modelKey;
  5277. return modelKey;
  5278. },
  5279. enumerable: true,
  5280. configurable: true
  5281. });
  5282. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  5283. /**
  5284. * States if the Primitive is dirty and should be rendered again next time.
  5285. * @returns true is dirty, false otherwise
  5286. */
  5287. get: function () {
  5288. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim_1.flagModelDirty | SmartPropertyPrim_1.flagModelUpdate | SmartPropertyPrim_1.flagPositioningDirty | SmartPropertyPrim_1.flagLayoutDirty);
  5289. },
  5290. enumerable: true,
  5291. configurable: true
  5292. });
  5293. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  5294. this._setFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  5295. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  5296. if (this instanceof BABYLON.Prim2DBase) {
  5297. var curprim = this;
  5298. while (curprim) {
  5299. curprim._setFlags(SmartPropertyPrim_1.flagBoundingInfoDirty);
  5300. if (curprim.isSizeAuto) {
  5301. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  5302. if (curprim._isFlagSet(SmartPropertyPrim_1.flagUsePositioning)) {
  5303. curprim._setFlags(SmartPropertyPrim_1.flagPositioningDirty);
  5304. }
  5305. }
  5306. if (curprim instanceof BABYLON.Group2D) {
  5307. if (curprim.isRenderableGroup) {
  5308. break;
  5309. }
  5310. }
  5311. curprim = curprim.parent;
  5312. }
  5313. }
  5314. };
  5315. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  5316. _super.prototype._handlePropChanged.call(this, curValue, newValue, propName, propInfo, typeLevelCompare);
  5317. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  5318. if (propInfo.dirtyBoundingInfo) {
  5319. this._boundingBoxDirty();
  5320. }
  5321. else if (propInfo.dirtyParentBoundingInfo) {
  5322. var p = this._parent;
  5323. if (p != null) {
  5324. p._boundingBoxDirty();
  5325. }
  5326. }
  5327. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  5328. if (this instanceof BABYLON.Group2D && this._renderableData) {
  5329. this.handleGroupChanged(propInfo);
  5330. }
  5331. // Check for parent layout dirty
  5332. if (this instanceof BABYLON.Prim2DBase) {
  5333. var p = this._parent;
  5334. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  5335. p._setLayoutDirty();
  5336. }
  5337. var that = this;
  5338. if (that.layoutEngine && (that.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  5339. this._setLayoutDirty();
  5340. }
  5341. }
  5342. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  5343. var instanceDirty = false;
  5344. if (typeLevelCompare && curValue != null && newValue != null) {
  5345. var cvProto = curValue.__proto__;
  5346. var nvProto = newValue.__proto__;
  5347. instanceDirty = (cvProto === nvProto);
  5348. }
  5349. // Set the dirty flags
  5350. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  5351. if (!this.isDirty) {
  5352. this.onPrimBecomesDirty();
  5353. this._setFlags(SmartPropertyPrim_1.flagModelDirty);
  5354. }
  5355. }
  5356. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  5357. var propMask = propInfo.flagId;
  5358. this.onPrimitivePropertyDirty(propMask);
  5359. }
  5360. };
  5361. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  5362. this.onPrimBecomesDirty();
  5363. this._instanceDirtyFlags |= propFlagId;
  5364. };
  5365. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  5366. };
  5367. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  5368. _super.prototype._resetPropertiesDirty.call(this);
  5369. this._clearFlags(SmartPropertyPrim_1.flagPrimInDirtyList | SmartPropertyPrim_1.flagNeedRefresh);
  5370. };
  5371. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  5372. /**
  5373. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  5374. */
  5375. get: function () {
  5376. if (this._isFlagSet(SmartPropertyPrim_1.flagLevelBoundingInfoDirty)) {
  5377. if (this.updateLevelBoundingInfo()) {
  5378. this._boundingInfo.dirtyWorldAABB();
  5379. this._clearFlags(SmartPropertyPrim_1.flagLevelBoundingInfoDirty);
  5380. }
  5381. else {
  5382. this._levelBoundingInfo.clear();
  5383. }
  5384. }
  5385. return this._levelBoundingInfo;
  5386. },
  5387. enumerable: true,
  5388. configurable: true
  5389. });
  5390. /**
  5391. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  5392. */
  5393. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  5394. return false;
  5395. };
  5396. /**
  5397. * Property method called when the Primitive becomes dirty
  5398. */
  5399. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  5400. };
  5401. /**
  5402. * Check if a given flag is set
  5403. * @param flag the flag value
  5404. * @return true if set, false otherwise
  5405. */
  5406. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  5407. return (this._flags & flag) !== 0;
  5408. };
  5409. /**
  5410. * Check if all given flags are set
  5411. * @param flags the flags ORed
  5412. * @return true if all the flags are set, false otherwise
  5413. */
  5414. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  5415. return (this._flags & flags) === flags;
  5416. };
  5417. /**
  5418. * Check if at least one flag of the given flags is set
  5419. * @param flags the flags ORed
  5420. * @return true if at least one flag is set, false otherwise
  5421. */
  5422. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  5423. return (this._flags & flags) !== 0;
  5424. };
  5425. /**
  5426. * Clear the given flags
  5427. * @param flags the flags to clear
  5428. */
  5429. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  5430. this._flags &= ~flags;
  5431. };
  5432. /**
  5433. * Set the given flags to true state
  5434. * @param flags the flags ORed to set
  5435. * @return the flags state before this call
  5436. */
  5437. SmartPropertyPrim.prototype._setFlags = function (flags) {
  5438. var cur = this._flags;
  5439. this._flags |= flags;
  5440. return cur;
  5441. };
  5442. /**
  5443. * Change the state of the given flags
  5444. * @param flags the flags ORed to change
  5445. * @param state true to set them, false to clear them
  5446. */
  5447. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  5448. if (state) {
  5449. this._flags |= flags;
  5450. }
  5451. else {
  5452. this._flags &= ~flags;
  5453. }
  5454. };
  5455. return SmartPropertyPrim;
  5456. }(SmartPropertyBase));
  5457. SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT = 0;
  5458. SmartPropertyPrim.flagNoPartOfLayout = 0x0000001; // set if the primitive's position/size must not be computed by Layout Engine
  5459. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  5460. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  5461. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  5462. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  5463. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  5464. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  5465. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  5466. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  5467. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  5468. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  5469. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  5470. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  5471. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  5472. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  5473. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  5474. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  5475. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  5476. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  5477. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  5478. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  5479. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0200000; // set if the layout bounding info is dirty
  5480. SmartPropertyPrim.flagCollisionActor = 0x0400000; // set if the primitive is part of the collision engine
  5481. SmartPropertyPrim.flagModelUpdate = 0x0800000; // set if the primitive's model data is to update
  5482. SmartPropertyPrim.flagLocalTransformDirty = 0x1000000; // set if the local transformation matrix must be recomputed
  5483. SmartPropertyPrim.flagUsePositioning = 0x2000000; // set if the primitive rely on the positioning engine (padding or margin is used)
  5484. SmartPropertyPrim.flagComputingPositioning = 0x4000000; // set if the positioning engine is computing the primitive, used to avoid re entrance
  5485. SmartPropertyPrim = SmartPropertyPrim_1 = __decorate([
  5486. BABYLON.className("SmartPropertyPrim", "BABYLON")
  5487. ], SmartPropertyPrim);
  5488. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  5489. function dependencyProperty(propId, piStore, mode, updateSourceTrigger) {
  5490. if (mode === void 0) { mode = DataBinding.MODE_TWOWAY; }
  5491. if (updateSourceTrigger === void 0) { updateSourceTrigger = DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED; }
  5492. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { bindingMode: mode, bindingUpdateSourceTrigger: updateSourceTrigger });
  5493. }
  5494. BABYLON.dependencyProperty = dependencyProperty;
  5495. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  5496. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  5497. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  5498. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  5499. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_MODEL, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  5500. }
  5501. BABYLON.modelLevelProperty = modelLevelProperty;
  5502. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  5503. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  5504. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  5505. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  5506. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_INSTANCE, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  5507. }
  5508. BABYLON.instanceLevelProperty = instanceLevelProperty;
  5509. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  5510. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  5511. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  5512. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  5513. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  5514. }
  5515. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  5516. var DataBinding_1, SmartPropertyBase_1, SmartPropertyPrim_1;
  5517. })(BABYLON || (BABYLON = {}));
  5518. //# sourceMappingURL=babylon.smartPropertyPrim.js.map
  5519. var __extends = (this && this.__extends) || function (d, b) {
  5520. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  5521. function __() { this.constructor = d; }
  5522. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5523. };
  5524. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  5525. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  5526. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  5527. 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;
  5528. return c > 3 && r && Object.defineProperty(target, key, r), r;
  5529. };
  5530. var BABYLON;
  5531. (function (BABYLON) {
  5532. var PrepareRender2DContext = (function () {
  5533. function PrepareRender2DContext() {
  5534. this.forceRefreshPrimitive = false;
  5535. }
  5536. return PrepareRender2DContext;
  5537. }());
  5538. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  5539. var Render2DContext = (function () {
  5540. function Render2DContext(renderMode) {
  5541. this._renderMode = renderMode;
  5542. this.useInstancing = false;
  5543. this.groupInfoPartData = null;
  5544. this.partDataStartIndex = this.partDataEndIndex = null;
  5545. this.instancedBuffers = null;
  5546. }
  5547. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  5548. /**
  5549. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  5550. */
  5551. get: function () {
  5552. return this._renderMode;
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  5558. /**
  5559. * The set of primitives to render is opaque.
  5560. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  5561. */
  5562. get: function () {
  5563. return Render2DContext._renderModeOpaque;
  5564. },
  5565. enumerable: true,
  5566. configurable: true
  5567. });
  5568. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  5569. /**
  5570. * The set of primitives to render is using Alpha Test (aka masking).
  5571. * 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.
  5572. */
  5573. get: function () {
  5574. return Render2DContext._renderModeAlphaTest;
  5575. },
  5576. enumerable: true,
  5577. configurable: true
  5578. });
  5579. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  5580. /**
  5581. * The set of primitives to render is transparent.
  5582. * 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.
  5583. */
  5584. get: function () {
  5585. return Render2DContext._renderModeTransparent;
  5586. },
  5587. enumerable: true,
  5588. configurable: true
  5589. });
  5590. return Render2DContext;
  5591. }());
  5592. Render2DContext._renderModeOpaque = 1;
  5593. Render2DContext._renderModeAlphaTest = 2;
  5594. Render2DContext._renderModeTransparent = 3;
  5595. BABYLON.Render2DContext = Render2DContext;
  5596. /**
  5597. * This class store information for the pointerEventObservable Observable.
  5598. * 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.
  5599. */
  5600. var PrimitivePointerInfo = (function () {
  5601. function PrimitivePointerInfo() {
  5602. this.primitivePointerPos = BABYLON.Vector2.Zero();
  5603. this.tilt = BABYLON.Vector2.Zero();
  5604. this.cancelBubble = false;
  5605. }
  5606. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  5607. // 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.
  5608. /**
  5609. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  5610. * Bubbles: yes
  5611. */
  5612. get: function () {
  5613. return PrimitivePointerInfo._pointerOver;
  5614. },
  5615. enumerable: true,
  5616. configurable: true
  5617. });
  5618. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  5619. /**
  5620. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  5621. * Bubbles: no
  5622. */
  5623. get: function () {
  5624. return PrimitivePointerInfo._pointerEnter;
  5625. },
  5626. enumerable: true,
  5627. configurable: true
  5628. });
  5629. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  5630. /**
  5631. * 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.
  5632. * Bubbles: yes
  5633. */
  5634. get: function () {
  5635. return PrimitivePointerInfo._pointerDown;
  5636. },
  5637. enumerable: true,
  5638. configurable: true
  5639. });
  5640. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  5641. /**
  5642. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  5643. * Bubbles: yes
  5644. */
  5645. get: function () {
  5646. return PrimitivePointerInfo._pointerMouseWheel;
  5647. },
  5648. enumerable: true,
  5649. configurable: true
  5650. });
  5651. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  5652. /**
  5653. * 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.
  5654. * Bubbles: yes
  5655. */
  5656. get: function () {
  5657. return PrimitivePointerInfo._pointerMove;
  5658. },
  5659. enumerable: true,
  5660. configurable: true
  5661. });
  5662. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  5663. /**
  5664. * 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.
  5665. * Bubbles: yes
  5666. */
  5667. get: function () {
  5668. return PrimitivePointerInfo._pointerUp;
  5669. },
  5670. enumerable: true,
  5671. configurable: true
  5672. });
  5673. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  5674. /**
  5675. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  5676. * Bubbles: yes
  5677. */
  5678. get: function () {
  5679. return PrimitivePointerInfo._pointerOut;
  5680. },
  5681. enumerable: true,
  5682. configurable: true
  5683. });
  5684. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  5685. /**
  5686. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  5687. * Bubbles: no
  5688. */
  5689. get: function () {
  5690. return PrimitivePointerInfo._pointerLeave;
  5691. },
  5692. enumerable: true,
  5693. configurable: true
  5694. });
  5695. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  5696. /**
  5697. * 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.
  5698. * Bubbles: yes
  5699. */
  5700. get: function () {
  5701. return PrimitivePointerInfo._pointerGotCapture;
  5702. },
  5703. enumerable: true,
  5704. configurable: true
  5705. });
  5706. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  5707. /**
  5708. * This event type is raised after pointer capture is released for a pointer.
  5709. * Bubbles: yes
  5710. */
  5711. get: function () {
  5712. return PrimitivePointerInfo._pointerLostCapture;
  5713. },
  5714. enumerable: true,
  5715. configurable: true
  5716. });
  5717. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  5718. get: function () {
  5719. return PrimitivePointerInfo._mouseWheelPrecision;
  5720. },
  5721. enumerable: true,
  5722. configurable: true
  5723. });
  5724. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  5725. this.relatedTarget = prim;
  5726. this.relatedTargetPointerPos = primPointerPos;
  5727. };
  5728. PrimitivePointerInfo.getEventTypeName = function (mask) {
  5729. switch (mask) {
  5730. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  5731. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  5732. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  5733. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  5734. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  5735. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  5736. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  5737. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  5738. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  5739. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  5740. }
  5741. };
  5742. return PrimitivePointerInfo;
  5743. }());
  5744. PrimitivePointerInfo._pointerOver = 0x0001;
  5745. PrimitivePointerInfo._pointerEnter = 0x0002;
  5746. PrimitivePointerInfo._pointerDown = 0x0004;
  5747. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  5748. PrimitivePointerInfo._pointerMove = 0x0010;
  5749. PrimitivePointerInfo._pointerUp = 0x0020;
  5750. PrimitivePointerInfo._pointerOut = 0x0040;
  5751. PrimitivePointerInfo._pointerLeave = 0x0080;
  5752. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  5753. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  5754. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  5755. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  5756. /**
  5757. * Defines the horizontal and vertical alignment information for a Primitive.
  5758. */
  5759. var PrimitiveAlignment = PrimitiveAlignment_1 = (function () {
  5760. function PrimitiveAlignment(changeCallback) {
  5761. this._changedCallback = changeCallback;
  5762. this._horizontal = PrimitiveAlignment_1.AlignLeft;
  5763. this._vertical = PrimitiveAlignment_1.AlignBottom;
  5764. }
  5765. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  5766. /**
  5767. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  5768. */
  5769. get: function () { return PrimitiveAlignment_1._AlignLeft; },
  5770. enumerable: true,
  5771. configurable: true
  5772. });
  5773. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  5774. /**
  5775. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  5776. */
  5777. get: function () { return PrimitiveAlignment_1._AlignTop; },
  5778. enumerable: true,
  5779. configurable: true
  5780. });
  5781. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  5782. /**
  5783. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  5784. */
  5785. get: function () { return PrimitiveAlignment_1._AlignRight; },
  5786. enumerable: true,
  5787. configurable: true
  5788. });
  5789. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  5790. /**
  5791. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  5792. */
  5793. get: function () { return PrimitiveAlignment_1._AlignBottom; },
  5794. enumerable: true,
  5795. configurable: true
  5796. });
  5797. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  5798. /**
  5799. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  5800. */
  5801. get: function () { return PrimitiveAlignment_1._AlignCenter; },
  5802. enumerable: true,
  5803. configurable: true
  5804. });
  5805. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  5806. /**
  5807. * The content is stretched toward the opposite edges of the Primitive
  5808. */
  5809. get: function () { return PrimitiveAlignment_1._AlignStretch; },
  5810. enumerable: true,
  5811. configurable: true
  5812. });
  5813. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  5814. /**
  5815. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  5816. */
  5817. get: function () {
  5818. return this._horizontal;
  5819. },
  5820. set: function (value) {
  5821. if (this._horizontal === value) {
  5822. return;
  5823. }
  5824. this._horizontal = value;
  5825. this.onChangeCallback();
  5826. },
  5827. enumerable: true,
  5828. configurable: true
  5829. });
  5830. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  5831. /**
  5832. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  5833. */
  5834. get: function () {
  5835. return this._vertical;
  5836. },
  5837. set: function (value) {
  5838. if (this._vertical === value) {
  5839. return;
  5840. }
  5841. this._vertical = value;
  5842. this.onChangeCallback();
  5843. },
  5844. enumerable: true,
  5845. configurable: true
  5846. });
  5847. PrimitiveAlignment.prototype.onChangeCallback = function () {
  5848. if (this._changedCallback) {
  5849. this._changedCallback();
  5850. }
  5851. };
  5852. /**
  5853. * Set the horizontal alignment from a string value.
  5854. * @param text can be either: 'left','right','center','stretch'
  5855. */
  5856. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  5857. var v = text.trim().toLocaleLowerCase();
  5858. switch (v) {
  5859. case "left":
  5860. this.horizontal = PrimitiveAlignment_1.AlignLeft;
  5861. return;
  5862. case "right":
  5863. this.horizontal = PrimitiveAlignment_1.AlignRight;
  5864. return;
  5865. case "center":
  5866. this.horizontal = PrimitiveAlignment_1.AlignCenter;
  5867. return;
  5868. case "stretch":
  5869. this.horizontal = PrimitiveAlignment_1.AlignStretch;
  5870. return;
  5871. }
  5872. };
  5873. /**
  5874. * Set the vertical alignment from a string value.
  5875. * @param text can be either: 'top','bottom','center','stretch'
  5876. */
  5877. PrimitiveAlignment.prototype.setVertical = function (text) {
  5878. var v = text.trim().toLocaleLowerCase();
  5879. switch (v) {
  5880. case "top":
  5881. this.vertical = PrimitiveAlignment_1.AlignTop;
  5882. return;
  5883. case "bottom":
  5884. this.vertical = PrimitiveAlignment_1.AlignBottom;
  5885. return;
  5886. case "center":
  5887. this.vertical = PrimitiveAlignment_1.AlignCenter;
  5888. return;
  5889. case "stretch":
  5890. this.vertical = PrimitiveAlignment_1.AlignStretch;
  5891. return;
  5892. }
  5893. };
  5894. /**
  5895. * Set the horizontal and or vertical alignments from a string value.
  5896. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  5897. */
  5898. PrimitiveAlignment.prototype.fromString = function (value) {
  5899. var m = value.trim().split(",");
  5900. if (m.length === 1) {
  5901. this.setHorizontal(m[0]);
  5902. this.setVertical(m[0]);
  5903. }
  5904. else {
  5905. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  5906. var v = m_1[_i];
  5907. v = v.toLocaleLowerCase().trim();
  5908. // Horizontal
  5909. var i = v.indexOf("h:");
  5910. if (i === -1) {
  5911. i = v.indexOf("horizontal:");
  5912. }
  5913. if (i !== -1) {
  5914. v = v.substr(v.indexOf(":") + 1);
  5915. this.setHorizontal(v);
  5916. continue;
  5917. }
  5918. // Vertical
  5919. i = v.indexOf("v:");
  5920. if (i === -1) {
  5921. i = v.indexOf("vertical:");
  5922. }
  5923. if (i !== -1) {
  5924. v = v.substr(v.indexOf(":") + 1);
  5925. this.setVertical(v);
  5926. continue;
  5927. }
  5928. }
  5929. }
  5930. };
  5931. PrimitiveAlignment.prototype.copyFrom = function (pa) {
  5932. this._horizontal = pa._horizontal;
  5933. this._vertical = pa._vertical;
  5934. this.onChangeCallback();
  5935. };
  5936. PrimitiveAlignment.prototype.clone = function () {
  5937. var pa = new PrimitiveAlignment_1();
  5938. pa._horizontal = this._horizontal;
  5939. pa._vertical = this._vertical;
  5940. return pa;
  5941. };
  5942. Object.defineProperty(PrimitiveAlignment.prototype, "isDefault", {
  5943. get: function () {
  5944. return this.horizontal === PrimitiveAlignment_1.AlignLeft && this.vertical === PrimitiveAlignment_1.AlignBottom;
  5945. },
  5946. enumerable: true,
  5947. configurable: true
  5948. });
  5949. return PrimitiveAlignment;
  5950. }());
  5951. PrimitiveAlignment._AlignLeft = 1;
  5952. PrimitiveAlignment._AlignTop = 1; // Same as left
  5953. PrimitiveAlignment._AlignRight = 2;
  5954. PrimitiveAlignment._AlignBottom = 2; // Same as right
  5955. PrimitiveAlignment._AlignCenter = 3;
  5956. PrimitiveAlignment._AlignStretch = 4;
  5957. PrimitiveAlignment = PrimitiveAlignment_1 = __decorate([
  5958. BABYLON.className("PrimitiveAlignment", "BABYLON")
  5959. ], PrimitiveAlignment);
  5960. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  5961. /**
  5962. * Stores information about a Primitive that was intersected
  5963. */
  5964. var PrimitiveIntersectedInfo = (function () {
  5965. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  5966. this.prim = prim;
  5967. this.intersectionLocation = intersectionLocation;
  5968. }
  5969. return PrimitiveIntersectedInfo;
  5970. }());
  5971. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  5972. /**
  5973. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  5974. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  5975. */
  5976. var PrimitiveThickness = PrimitiveThickness_1 = (function () {
  5977. function PrimitiveThickness(parentAccess, changedCallback) {
  5978. this._parentAccess = parentAccess;
  5979. this._changedCallback = changedCallback;
  5980. this._pixels = new Array(4);
  5981. this._percentages = new Array(4);
  5982. this._setType(0, PrimitiveThickness_1.Auto);
  5983. this._setType(1, PrimitiveThickness_1.Auto);
  5984. this._setType(2, PrimitiveThickness_1.Auto);
  5985. this._setType(3, PrimitiveThickness_1.Auto);
  5986. this._pixels[0] = 0;
  5987. this._pixels[1] = 0;
  5988. this._pixels[2] = 0;
  5989. this._pixels[3] = 0;
  5990. }
  5991. /**
  5992. * Set the thickness from a string value
  5993. * @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.
  5994. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  5995. */
  5996. PrimitiveThickness.prototype.fromString = function (thickness) {
  5997. this._clear();
  5998. var m = thickness.trim().split(",");
  5999. // Special case, one value to apply to all edges
  6000. if (m.length === 1 && thickness.indexOf(":") === -1) {
  6001. this._setStringValue(m[0], 0, false);
  6002. this._setStringValue(m[0], 1, false);
  6003. this._setStringValue(m[0], 2, false);
  6004. this._setStringValue(m[0], 3, false);
  6005. this.onChangeCallback();
  6006. return;
  6007. }
  6008. var res = false;
  6009. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  6010. var cm = m_2[_i];
  6011. res = this._extractString(cm, false) || res;
  6012. }
  6013. if (!res) {
  6014. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  6015. }
  6016. // Check the margin that weren't set and set them in auto
  6017. if ((this._flags & 0x000F) === 0)
  6018. this._flags |= PrimitiveThickness_1.Pixel << 0;
  6019. if ((this._flags & 0x00F0) === 0)
  6020. this._flags |= PrimitiveThickness_1.Pixel << 4;
  6021. if ((this._flags & 0x0F00) === 0)
  6022. this._flags |= PrimitiveThickness_1.Pixel << 8;
  6023. if ((this._flags & 0xF000) === 0)
  6024. this._flags |= PrimitiveThickness_1.Pixel << 12;
  6025. this.onChangeCallback();
  6026. };
  6027. /**
  6028. * Set the thickness from multiple string
  6029. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6030. * @param top the top thickness to set
  6031. * @param left the left thickness to set
  6032. * @param right the right thickness to set
  6033. * @param bottom the bottom thickness to set
  6034. */
  6035. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  6036. this._clear();
  6037. this._setStringValue(top, 0, false);
  6038. this._setStringValue(left, 1, false);
  6039. this._setStringValue(right, 2, false);
  6040. this._setStringValue(bottom, 3, false);
  6041. this.onChangeCallback();
  6042. return this;
  6043. };
  6044. /**
  6045. * Set the thickness from pixel values
  6046. * @param top the top thickness in pixels to set
  6047. * @param left the left thickness in pixels to set
  6048. * @param right the right thickness in pixels to set
  6049. * @param bottom the bottom thickness in pixels to set
  6050. */
  6051. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  6052. this._clear();
  6053. this._pixels[0] = top;
  6054. this._pixels[1] = left;
  6055. this._pixels[2] = right;
  6056. this._pixels[3] = bottom;
  6057. this.onChangeCallback();
  6058. return this;
  6059. };
  6060. /**
  6061. * Apply the same pixel value to all edges
  6062. * @param margin the value to set, in pixels.
  6063. */
  6064. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  6065. this._clear();
  6066. this._pixels[0] = margin;
  6067. this._pixels[1] = margin;
  6068. this._pixels[2] = margin;
  6069. this._pixels[3] = margin;
  6070. this.onChangeCallback();
  6071. return this;
  6072. };
  6073. PrimitiveThickness.prototype.copyFrom = function (pt) {
  6074. this._clear();
  6075. for (var i = 0; i < 4; i++) {
  6076. this._pixels[i] = pt._pixels[i];
  6077. this._percentages[i] = pt._percentages[i];
  6078. }
  6079. this._flags = pt._flags;
  6080. this.onChangeCallback();
  6081. };
  6082. /**
  6083. * Set all edges in auto
  6084. */
  6085. PrimitiveThickness.prototype.auto = function () {
  6086. this._clear();
  6087. this._flags = (PrimitiveThickness_1.Auto << 0) | (PrimitiveThickness_1.Auto << 4) | (PrimitiveThickness_1.Auto << 8) | (PrimitiveThickness_1.Auto << 12);
  6088. this._pixels[0] = 0;
  6089. this._pixels[1] = 0;
  6090. this._pixels[2] = 0;
  6091. this._pixels[3] = 0;
  6092. this.onChangeCallback();
  6093. return this;
  6094. };
  6095. PrimitiveThickness.prototype._clear = function () {
  6096. this._flags = 0;
  6097. this._pixels[0] = 0;
  6098. this._pixels[1] = 0;
  6099. this._pixels[2] = 0;
  6100. this._pixels[3] = 0;
  6101. this._percentages[0] = null;
  6102. this._percentages[1] = null;
  6103. this._percentages[2] = null;
  6104. this._percentages[3] = null;
  6105. };
  6106. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  6107. var v = value.trim().toLocaleLowerCase();
  6108. if (v.indexOf("top:") === 0) {
  6109. v = v.substr(4).trim();
  6110. return this._setStringValue(v, 0, emitChanged);
  6111. }
  6112. if (v.indexOf("left:") === 0) {
  6113. v = v.substr(5).trim();
  6114. return this._setStringValue(v, 1, emitChanged);
  6115. }
  6116. if (v.indexOf("right:") === 0) {
  6117. v = v.substr(6).trim();
  6118. return this._setStringValue(v, 2, emitChanged);
  6119. }
  6120. if (v.indexOf("bottom:") === 0) {
  6121. v = v.substr(7).trim();
  6122. return this._setStringValue(v, 3, emitChanged);
  6123. }
  6124. return false;
  6125. };
  6126. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  6127. // Check for auto
  6128. var v = value.trim().toLocaleLowerCase();
  6129. if (v === "auto") {
  6130. if (this._isType(index, PrimitiveThickness_1.Auto)) {
  6131. return true;
  6132. }
  6133. this._setType(index, PrimitiveThickness_1.Auto);
  6134. this._pixels[index] = 0;
  6135. if (emitChanged) {
  6136. this.onChangeCallback();
  6137. }
  6138. }
  6139. else if (v === "inherit") {
  6140. if (this._isType(index, PrimitiveThickness_1.Inherit)) {
  6141. return true;
  6142. }
  6143. this._setType(index, PrimitiveThickness_1.Inherit);
  6144. this._pixels[index] = null;
  6145. if (emitChanged) {
  6146. this.onChangeCallback();
  6147. }
  6148. }
  6149. else {
  6150. var pI = v.indexOf("%");
  6151. // Check for percentage
  6152. if (pI !== -1) {
  6153. var n_1 = v.substr(0, pI);
  6154. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  6155. if (this._isType(index, PrimitiveThickness_1.Percentage) && (this._percentages[index] === number_1)) {
  6156. return true;
  6157. }
  6158. this._setType(index, PrimitiveThickness_1.Percentage);
  6159. if (isNaN(number_1)) {
  6160. return false;
  6161. }
  6162. this._percentages[index] = number_1;
  6163. if (emitChanged) {
  6164. this.onChangeCallback();
  6165. }
  6166. return true;
  6167. }
  6168. // Check for pixel
  6169. var n = void 0;
  6170. pI = v.indexOf("px");
  6171. if (pI !== -1) {
  6172. n = v.substr(0, pI).trim();
  6173. }
  6174. else {
  6175. n = v;
  6176. }
  6177. var number = Number(n);
  6178. if (this._isType(index, PrimitiveThickness_1.Pixel) && (this._pixels[index] === number)) {
  6179. return true;
  6180. }
  6181. if (isNaN(number)) {
  6182. return false;
  6183. }
  6184. this._pixels[index] = number;
  6185. this._setType(index, PrimitiveThickness_1.Pixel);
  6186. if (emitChanged) {
  6187. this.onChangeCallback();
  6188. }
  6189. return true;
  6190. }
  6191. };
  6192. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  6193. // 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
  6194. value = Math.round(value);
  6195. if (this._isType(index, PrimitiveThickness_1.Pixel) && this._pixels[index] === value) {
  6196. return;
  6197. }
  6198. this._setType(index, PrimitiveThickness_1.Pixel);
  6199. this._pixels[index] = value;
  6200. if (emitChanged) {
  6201. this.onChangeCallback();
  6202. }
  6203. };
  6204. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  6205. // Clip Value to bounds
  6206. value = Math.min(1, value);
  6207. value = Math.max(0, value);
  6208. value = Math.round(value * 100) / 100; // 0.01 precision
  6209. if (this._isType(index, PrimitiveThickness_1.Percentage) && this._percentages[index] === value) {
  6210. return;
  6211. }
  6212. this._setType(index, PrimitiveThickness_1.Percentage);
  6213. this._percentages[index] = value;
  6214. if (emitChanged) {
  6215. this.onChangeCallback();
  6216. }
  6217. };
  6218. PrimitiveThickness.prototype._getStringValue = function (index) {
  6219. var f = (this._flags >> (index * 4)) & 0xF;
  6220. switch (f) {
  6221. case PrimitiveThickness_1.Auto:
  6222. return "auto";
  6223. case PrimitiveThickness_1.Pixel:
  6224. return this._pixels[index] + "px";
  6225. case PrimitiveThickness_1.Percentage:
  6226. return this._percentages[index] * 100 + "%";
  6227. case PrimitiveThickness_1.Inherit:
  6228. return "inherit";
  6229. }
  6230. return "";
  6231. };
  6232. PrimitiveThickness.prototype._isType = function (index, type) {
  6233. var f = (this._flags >> (index * 4)) & 0xF;
  6234. return f === type;
  6235. };
  6236. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  6237. var t = (this._flags >> (index * 4)) & 0xF;
  6238. if (processInherit && (t === PrimitiveThickness_1.Inherit)) {
  6239. var p = this._parentAccess();
  6240. if (p) {
  6241. return p._getType(index, true);
  6242. }
  6243. return PrimitiveThickness_1.Auto;
  6244. }
  6245. return t;
  6246. };
  6247. PrimitiveThickness.prototype._setType = function (index, type) {
  6248. this._flags &= ~(0xF << (index * 4));
  6249. this._flags |= type << (index * 4);
  6250. };
  6251. PrimitiveThickness.prototype.setTop = function (value) {
  6252. if (typeof value === "string") {
  6253. this._setStringValue(value, 0, true);
  6254. }
  6255. else {
  6256. this.topPixels = value;
  6257. }
  6258. };
  6259. PrimitiveThickness.prototype.setLeft = function (value) {
  6260. if (typeof value === "string") {
  6261. this._setStringValue(value, 1, true);
  6262. }
  6263. else {
  6264. this.leftPixels = value;
  6265. }
  6266. };
  6267. PrimitiveThickness.prototype.setRight = function (value) {
  6268. if (typeof value === "string") {
  6269. this._setStringValue(value, 2, true);
  6270. }
  6271. else {
  6272. this.rightPixels = value;
  6273. }
  6274. };
  6275. PrimitiveThickness.prototype.setBottom = function (value) {
  6276. if (typeof value === "string") {
  6277. this._setStringValue(value, 3, true);
  6278. }
  6279. else {
  6280. this.bottomPixels = value;
  6281. }
  6282. };
  6283. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  6284. /**
  6285. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6286. */
  6287. get: function () {
  6288. return this._getStringValue(0);
  6289. },
  6290. set: function (value) {
  6291. this._setStringValue(value, 0, true);
  6292. },
  6293. enumerable: true,
  6294. configurable: true
  6295. });
  6296. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  6297. /**
  6298. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6299. */
  6300. get: function () {
  6301. return this._getStringValue(1);
  6302. },
  6303. set: function (value) {
  6304. this._setStringValue(value, 1, true);
  6305. },
  6306. enumerable: true,
  6307. configurable: true
  6308. });
  6309. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  6310. /**
  6311. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6312. */
  6313. get: function () {
  6314. return this._getStringValue(2);
  6315. },
  6316. set: function (value) {
  6317. this._setStringValue(value, 2, true);
  6318. },
  6319. enumerable: true,
  6320. configurable: true
  6321. });
  6322. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  6323. /**
  6324. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  6325. */
  6326. get: function () {
  6327. return this._getStringValue(3);
  6328. },
  6329. set: function (value) {
  6330. this._setStringValue(value, 3, true);
  6331. },
  6332. enumerable: true,
  6333. configurable: true
  6334. });
  6335. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  6336. /**
  6337. * Get/set the top thickness in pixel.
  6338. */
  6339. get: function () {
  6340. return this._pixels[0];
  6341. },
  6342. set: function (value) {
  6343. this._setPixels(value, 0, true);
  6344. },
  6345. enumerable: true,
  6346. configurable: true
  6347. });
  6348. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  6349. /**
  6350. * Get/set the left thickness in pixel.
  6351. */
  6352. get: function () {
  6353. return this._pixels[1];
  6354. },
  6355. set: function (value) {
  6356. this._setPixels(value, 1, true);
  6357. },
  6358. enumerable: true,
  6359. configurable: true
  6360. });
  6361. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  6362. /**
  6363. * Get/set the right thickness in pixel.
  6364. */
  6365. get: function () {
  6366. return this._pixels[2];
  6367. },
  6368. set: function (value) {
  6369. this._setPixels(value, 2, true);
  6370. },
  6371. enumerable: true,
  6372. configurable: true
  6373. });
  6374. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  6375. /**
  6376. * Get/set the bottom thickness in pixel.
  6377. */
  6378. get: function () {
  6379. return this._pixels[3];
  6380. },
  6381. set: function (value) {
  6382. this._setPixels(value, 3, true);
  6383. },
  6384. enumerable: true,
  6385. configurable: true
  6386. });
  6387. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  6388. /**
  6389. * Get/set the top thickness in percentage.
  6390. * The get will return a valid value only if the edge type is percentage.
  6391. * The Set will change the edge mode if needed
  6392. */
  6393. get: function () {
  6394. return this._percentages[0];
  6395. },
  6396. set: function (value) {
  6397. this._setPercentage(value, 0, true);
  6398. },
  6399. enumerable: true,
  6400. configurable: true
  6401. });
  6402. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  6403. /**
  6404. * Get/set the left thickness in percentage.
  6405. * The get will return a valid value only if the edge mode is percentage.
  6406. * The Set will change the edge mode if needed
  6407. */
  6408. get: function () {
  6409. return this._percentages[1];
  6410. },
  6411. set: function (value) {
  6412. this._setPercentage(value, 1, true);
  6413. },
  6414. enumerable: true,
  6415. configurable: true
  6416. });
  6417. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  6418. /**
  6419. * Get/set the right thickness in percentage.
  6420. * The get will return a valid value only if the edge mode is percentage.
  6421. * The Set will change the edge mode if needed
  6422. */
  6423. get: function () {
  6424. return this._percentages[2];
  6425. },
  6426. set: function (value) {
  6427. this._setPercentage(value, 2, true);
  6428. },
  6429. enumerable: true,
  6430. configurable: true
  6431. });
  6432. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  6433. /**
  6434. * Get/set the bottom thickness in percentage.
  6435. * The get will return a valid value only if the edge mode is percentage.
  6436. * The Set will change the edge mode if needed
  6437. */
  6438. get: function () {
  6439. return this._percentages[3];
  6440. },
  6441. set: function (value) {
  6442. this._setPercentage(value, 3, true);
  6443. },
  6444. enumerable: true,
  6445. configurable: true
  6446. });
  6447. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  6448. /**
  6449. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  6450. */
  6451. get: function () {
  6452. return this._getType(0, false);
  6453. },
  6454. set: function (mode) {
  6455. this._setType(0, mode);
  6456. },
  6457. enumerable: true,
  6458. configurable: true
  6459. });
  6460. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  6461. /**
  6462. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  6463. */
  6464. get: function () {
  6465. return this._getType(1, false);
  6466. },
  6467. set: function (mode) {
  6468. this._setType(1, mode);
  6469. },
  6470. enumerable: true,
  6471. configurable: true
  6472. });
  6473. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  6474. /**
  6475. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  6476. */
  6477. get: function () {
  6478. return this._getType(2, false);
  6479. },
  6480. set: function (mode) {
  6481. this._setType(2, mode);
  6482. },
  6483. enumerable: true,
  6484. configurable: true
  6485. });
  6486. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  6487. /**
  6488. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  6489. */
  6490. get: function () {
  6491. return this._getType(3, false);
  6492. },
  6493. set: function (mode) {
  6494. this._setType(3, mode);
  6495. },
  6496. enumerable: true,
  6497. configurable: true
  6498. });
  6499. Object.defineProperty(PrimitiveThickness.prototype, "isDefault", {
  6500. get: function () {
  6501. return this._flags === 0x1111;
  6502. },
  6503. enumerable: true,
  6504. configurable: true
  6505. });
  6506. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  6507. var type = this._getType(index, false);
  6508. if (type === PrimitiveThickness_1.Inherit) {
  6509. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  6510. return;
  6511. }
  6512. if (type !== PrimitiveThickness_1.Percentage) {
  6513. return;
  6514. }
  6515. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  6516. this._pixels[index] = pixels;
  6517. if (emitChanged) {
  6518. this.onChangeCallback();
  6519. }
  6520. };
  6521. PrimitiveThickness.prototype.onChangeCallback = function () {
  6522. if (this._changedCallback) {
  6523. this._changedCallback();
  6524. }
  6525. };
  6526. /**
  6527. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  6528. * @param sourceArea the source area where the content must be sized/positioned
  6529. * @param contentSize the content size to position/resize
  6530. * @param alignment the alignment setting
  6531. * @param dstOffset the position of the content, x, y, z, w are left, bottom, right, top
  6532. * @param dstArea the new size of the content
  6533. */
  6534. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, contentScale, dstOffset, dstArea, computeLayoutArea, computeAxis) {
  6535. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  6536. if (computeAxis === void 0) { computeAxis = PrimitiveThickness_1.ComputeAll; }
  6537. // Fetch some data
  6538. var topType = this._getType(0, true);
  6539. var leftType = this._getType(1, true);
  6540. var rightType = this._getType(2, true);
  6541. var bottomType = this._getType(3, true);
  6542. var hasWidth = contentSize && (contentSize.width != null);
  6543. var hasHeight = contentSize && (contentSize.height != null);
  6544. var sx = contentScale.x;
  6545. var sy = contentScale.y;
  6546. var width = hasWidth ? contentSize.width : 0;
  6547. var height = hasHeight ? contentSize.height : 0;
  6548. var isTopAuto = topType === PrimitiveThickness_1.Auto;
  6549. var isLeftAuto = leftType === PrimitiveThickness_1.Auto;
  6550. var isRightAuto = rightType === PrimitiveThickness_1.Auto;
  6551. var isBottomAuto = bottomType === PrimitiveThickness_1.Auto;
  6552. if (computeAxis & PrimitiveThickness_1.ComputeH) {
  6553. switch (alignment.horizontal) {
  6554. case PrimitiveAlignment.AlignLeft:
  6555. {
  6556. var leftPixels = 0;
  6557. if (!isLeftAuto) {
  6558. this._computePixels(1, sourceArea, true);
  6559. leftPixels = this.leftPixels;
  6560. }
  6561. var rightPixels = 0;
  6562. if (!isRightAuto) {
  6563. this._computePixels(2, sourceArea, true);
  6564. rightPixels = this.rightPixels;
  6565. }
  6566. dstOffset.x = leftPixels;
  6567. dstArea.width = width;
  6568. dstOffset.z = rightPixels;
  6569. if (computeLayoutArea) {
  6570. dstArea.width += leftPixels + rightPixels;
  6571. }
  6572. break;
  6573. }
  6574. case PrimitiveAlignment.AlignRight:
  6575. {
  6576. var leftPixels = 0;
  6577. if (!isLeftAuto) {
  6578. this._computePixels(1, sourceArea, true);
  6579. leftPixels = this.leftPixels;
  6580. }
  6581. var rightPixels = 0;
  6582. if (!isRightAuto) {
  6583. this._computePixels(2, sourceArea, true);
  6584. rightPixels = this.rightPixels;
  6585. }
  6586. dstOffset.x = Math.round(sourceArea.width - ((width * sx) + rightPixels));
  6587. dstArea.width = width;
  6588. dstOffset.z = leftPixels;
  6589. if (computeLayoutArea) {
  6590. dstArea.width += leftPixels + rightPixels;
  6591. }
  6592. break;
  6593. }
  6594. case PrimitiveAlignment.AlignStretch:
  6595. {
  6596. if (isLeftAuto) {
  6597. dstOffset.x = 0;
  6598. }
  6599. else {
  6600. this._computePixels(1, sourceArea, true);
  6601. dstOffset.x = this.leftPixels;
  6602. }
  6603. var rightPixels = 0;
  6604. if (!isRightAuto) {
  6605. this._computePixels(2, sourceArea, true);
  6606. rightPixels = this.rightPixels;
  6607. }
  6608. if (computeLayoutArea) {
  6609. dstArea.width = sourceArea.width;
  6610. }
  6611. else {
  6612. dstArea.width = sourceArea.width - (dstOffset.x + rightPixels);
  6613. }
  6614. dstOffset.z = this.rightPixels;
  6615. break;
  6616. }
  6617. case PrimitiveAlignment.AlignCenter:
  6618. {
  6619. if (!isLeftAuto) {
  6620. this._computePixels(1, sourceArea, true);
  6621. }
  6622. if (!isRightAuto) {
  6623. this._computePixels(2, sourceArea, true);
  6624. }
  6625. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  6626. var center = ((sourceArea.width - (width * sx)) / 2);
  6627. dstOffset.x = Math.round(center + offset);
  6628. if (computeLayoutArea) {
  6629. dstArea.width = width + this.leftPixels + this.rightPixels;
  6630. }
  6631. else {
  6632. dstArea.width = width;
  6633. }
  6634. dstOffset.z = Math.round(center - offset);
  6635. break;
  6636. }
  6637. }
  6638. }
  6639. if (computeAxis & PrimitiveThickness_1.ComputeV) {
  6640. switch (alignment.vertical) {
  6641. case PrimitiveAlignment.AlignBottom:
  6642. {
  6643. var bottomPixels = 0;
  6644. if (!isBottomAuto) {
  6645. this._computePixels(3, sourceArea, true);
  6646. bottomPixels = this.bottomPixels;
  6647. }
  6648. var topPixels = 0;
  6649. if (!isTopAuto) {
  6650. this._computePixels(0, sourceArea, true);
  6651. topPixels = this.topPixels;
  6652. }
  6653. dstOffset.y = bottomPixels;
  6654. dstArea.height = height;
  6655. dstOffset.w = topPixels;
  6656. if (computeLayoutArea) {
  6657. dstArea.height += bottomPixels + topPixels;
  6658. }
  6659. break;
  6660. }
  6661. case PrimitiveAlignment.AlignTop:
  6662. {
  6663. var bottomPixels = 0;
  6664. if (!isBottomAuto) {
  6665. this._computePixels(3, sourceArea, true);
  6666. bottomPixels = this.bottomPixels;
  6667. }
  6668. var topPixels = 0;
  6669. if (!isTopAuto) {
  6670. this._computePixels(0, sourceArea, true);
  6671. topPixels = this.topPixels;
  6672. }
  6673. dstOffset.y = Math.round(sourceArea.height - ((height * sy) + topPixels));
  6674. dstArea.height = height;
  6675. dstOffset.w = bottomPixels;
  6676. if (computeLayoutArea) {
  6677. dstArea.height += bottomPixels + topPixels;
  6678. }
  6679. // console.log(`Compute Alignment Source Area: ${sourceArea}, Content Size: ${contentSize}`);
  6680. break;
  6681. }
  6682. case PrimitiveAlignment.AlignStretch:
  6683. {
  6684. if (isBottomAuto) {
  6685. dstOffset.y = 0;
  6686. }
  6687. else {
  6688. this._computePixels(3, sourceArea, true);
  6689. dstOffset.y = this.bottomPixels;
  6690. }
  6691. var top_1 = 0;
  6692. if (!isTopAuto) {
  6693. this._computePixels(0, sourceArea, true);
  6694. top_1 = this.topPixels;
  6695. }
  6696. if (computeLayoutArea) {
  6697. dstArea.height = sourceArea.height;
  6698. }
  6699. else {
  6700. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  6701. }
  6702. dstOffset.w = this.topPixels;
  6703. break;
  6704. }
  6705. case PrimitiveAlignment.AlignCenter:
  6706. {
  6707. if (!isTopAuto) {
  6708. this._computePixels(0, sourceArea, true);
  6709. }
  6710. if (!isBottomAuto) {
  6711. this._computePixels(3, sourceArea, true);
  6712. }
  6713. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  6714. var center = (sourceArea.height - (height * sy)) / 2;
  6715. dstOffset.y = Math.round(center + offset);
  6716. if (computeLayoutArea) {
  6717. dstArea.height = height + this.bottomPixels + this.topPixels;
  6718. }
  6719. else {
  6720. dstArea.height = height;
  6721. }
  6722. dstOffset.w = Math.round(center - offset);
  6723. break;
  6724. }
  6725. }
  6726. }
  6727. };
  6728. /**
  6729. * Compute an area and its position considering this thickness properties based on a given source area
  6730. * @param sourceArea the source area
  6731. * @param dstOffset the position of the resulting area
  6732. * @param dstArea the size of the resulting area
  6733. */
  6734. PrimitiveThickness.prototype.compute = function (sourceArea, sourceAreaScale, dstOffset, dstArea, computeLayoutArea) {
  6735. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  6736. this._computePixels(0, sourceArea, true);
  6737. this._computePixels(1, sourceArea, true);
  6738. this._computePixels(2, sourceArea, true);
  6739. this._computePixels(3, sourceArea, true);
  6740. var sx = sourceAreaScale.x;
  6741. var sy = sourceAreaScale.y;
  6742. dstOffset.x = this.leftPixels;
  6743. if (computeLayoutArea) {
  6744. dstArea.width = (sourceArea.width * sx) + (dstOffset.x + this.rightPixels);
  6745. }
  6746. else {
  6747. dstArea.width = (sourceArea.width * sx) - (dstOffset.x + this.rightPixels);
  6748. }
  6749. dstOffset.y = this.bottomPixels;
  6750. if (computeLayoutArea) {
  6751. dstArea.height = (sourceArea.height * sy) + (dstOffset.y + this.topPixels);
  6752. }
  6753. else {
  6754. dstArea.height = (sourceArea.height * sy) - (dstOffset.y + this.topPixels);
  6755. }
  6756. dstOffset.z = this.rightPixels;
  6757. dstOffset.w = this.topPixels;
  6758. };
  6759. /**
  6760. * Compute an area considering this thickness properties based on a given source area
  6761. * @param sourceArea the source area
  6762. * @param result the resulting area
  6763. */
  6764. PrimitiveThickness.prototype.computeArea = function (sourceArea, sourceScale, result) {
  6765. this._computePixels(0, sourceArea, true);
  6766. this._computePixels(1, sourceArea, true);
  6767. this._computePixels(2, sourceArea, true);
  6768. this._computePixels(3, sourceArea, true);
  6769. result.width = this.leftPixels + (sourceArea.width * sourceScale.x) + this.rightPixels;
  6770. result.height = this.bottomPixels + (sourceArea.height * sourceScale.y) + this.topPixels;
  6771. };
  6772. PrimitiveThickness.prototype.enlarge = function (sourceArea, sourceScale, dstOffset, enlargedArea) {
  6773. this._computePixels(0, sourceArea, true);
  6774. this._computePixels(1, sourceArea, true);
  6775. this._computePixels(2, sourceArea, true);
  6776. this._computePixels(3, sourceArea, true);
  6777. dstOffset.x = this.leftPixels;
  6778. enlargedArea.width = (sourceArea.width * sourceScale.x) + (dstOffset.x + this.rightPixels);
  6779. dstOffset.y = this.bottomPixels;
  6780. enlargedArea.height = (sourceArea.height * sourceScale.y) + (dstOffset.y + this.topPixels);
  6781. dstOffset.z = this.rightPixels;
  6782. dstOffset.w = this.topPixels;
  6783. };
  6784. return PrimitiveThickness;
  6785. }());
  6786. PrimitiveThickness.Auto = 0x1;
  6787. PrimitiveThickness.Inherit = 0x2;
  6788. PrimitiveThickness.Percentage = 0x4;
  6789. PrimitiveThickness.Pixel = 0x8;
  6790. PrimitiveThickness.ComputeH = 0x1;
  6791. PrimitiveThickness.ComputeV = 0x2;
  6792. PrimitiveThickness.ComputeAll = 0x03;
  6793. PrimitiveThickness = PrimitiveThickness_1 = __decorate([
  6794. BABYLON.className("PrimitiveThickness", "BABYLON")
  6795. ], PrimitiveThickness);
  6796. BABYLON.PrimitiveThickness = PrimitiveThickness;
  6797. /**
  6798. * Main class used for the Primitive Intersection API
  6799. */
  6800. var IntersectInfo2D = (function () {
  6801. function IntersectInfo2D() {
  6802. this.findFirstOnly = false;
  6803. this.intersectHidden = false;
  6804. this.pickPosition = BABYLON.Vector2.Zero();
  6805. }
  6806. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  6807. /**
  6808. * true if at least one primitive intersected during the test
  6809. */
  6810. get: function () {
  6811. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  6817. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  6818. var cur = _a[_i];
  6819. if (cur.prim === prim) {
  6820. return cur.intersectionLocation;
  6821. }
  6822. }
  6823. return null;
  6824. };
  6825. // Internals, don't use
  6826. IntersectInfo2D.prototype._exit = function (firstLevel) {
  6827. if (firstLevel) {
  6828. this._globalPickPosition = null;
  6829. }
  6830. };
  6831. return IntersectInfo2D;
  6832. }());
  6833. BABYLON.IntersectInfo2D = IntersectInfo2D;
  6834. var Prim2DBase = Prim2DBase_1 = (function (_super) {
  6835. __extends(Prim2DBase, _super);
  6836. function Prim2DBase(settings) {
  6837. var _this = this;
  6838. // Avoid checking every time if the object exists
  6839. if (settings == null) {
  6840. settings = {};
  6841. }
  6842. // BASE CLASS CALL
  6843. _this = _super.call(this) || this;
  6844. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  6845. var owner;
  6846. var parent;
  6847. if (Prim2DBase_1._isCanvasInit) {
  6848. owner = _this;
  6849. parent = null;
  6850. _this._canvasPreInit(settings);
  6851. }
  6852. else {
  6853. if (settings.parent != null) {
  6854. parent = settings.parent;
  6855. owner = settings.parent.owner;
  6856. if (!owner) {
  6857. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  6858. }
  6859. 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)) {
  6860. 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");
  6861. }
  6862. }
  6863. }
  6864. // Fields initialization
  6865. _this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  6866. _this._size = null; //Size.Zero();
  6867. _this._scale = new BABYLON.Vector2(1, 1);
  6868. _this._postScale = new BABYLON.Vector2(1, 1);
  6869. _this._actualSize = null;
  6870. _this._internalSize = BABYLON.Size.Zero();
  6871. _this._layoutArea = null;
  6872. _this._layoutAreaPos = null;
  6873. _this._layoutBoundingInfo = null;
  6874. _this._marginOffset = BABYLON.Vector4.Zero();
  6875. _this._paddingOffset = BABYLON.Vector4.Zero();
  6876. _this._parentPaddingOffset = BABYLON.Vector2.Zero();
  6877. _this._parentContentArea = BABYLON.Size.Zero();
  6878. _this._lastAutoSizeArea = BABYLON.Size.Zero();
  6879. _this._contentArea = BABYLON.Size.Zero();
  6880. _this._marginSize = null;
  6881. _this._pointerEventObservable = new BABYLON.Observable();
  6882. _this._owner = owner;
  6883. _this._parent = null;
  6884. _this._margin = null;
  6885. _this._padding = null;
  6886. _this._marginAlignment = null;
  6887. _this._id = settings.id;
  6888. _this._children = new Array();
  6889. _this._localTransform = new BABYLON.Matrix();
  6890. _this._localLayoutTransform = new BABYLON.Matrix();
  6891. _this._globalTransform = null;
  6892. _this._invGlobalTransform = null;
  6893. _this._globalTransformProcessStep = 0;
  6894. _this._globalTransformStep = 0;
  6895. _this._renderGroup = null;
  6896. _this._primLinearPosition = 0;
  6897. _this._manualZOrder = null;
  6898. _this._zOrder = 0;
  6899. _this._zMax = 0;
  6900. _this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  6901. _this._actualOpacity = 0;
  6902. _this._actualScale = BABYLON.Vector2.Zero();
  6903. _this._displayDebugAreas = false;
  6904. _this._debugAreaGroup = null;
  6905. _this._primTriArray = null;
  6906. _this._primTriArrayDirty = true;
  6907. if (owner) {
  6908. _this.onSetOwner();
  6909. }
  6910. _this._levelBoundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  6911. _this._boundingInfo.worldMatrixAccess = function () { return _this.globalTransform; };
  6912. var isPickable = true;
  6913. var isContainer = true;
  6914. if (settings.isPickable !== undefined) {
  6915. isPickable = settings.isPickable;
  6916. }
  6917. if (settings.isContainer !== undefined) {
  6918. isContainer = settings.isContainer;
  6919. }
  6920. if (settings.dontInheritParentScale) {
  6921. _this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  6922. }
  6923. _this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  6924. if (settings.opacity != null) {
  6925. _this._opacity = settings.opacity;
  6926. }
  6927. else {
  6928. _this._opacity = 1;
  6929. }
  6930. _this._updateRenderMode();
  6931. if (settings.childrenFlatZOrder) {
  6932. _this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  6933. }
  6934. // If the parent is given, initialize the hierarchy/owner related data
  6935. if (parent != null) {
  6936. parent.addChild(_this);
  6937. _this._hierarchyDepth = parent._hierarchyDepth + 1;
  6938. _this._patchHierarchy(parent.owner);
  6939. }
  6940. // If it's a group, detect its own states
  6941. if (_this.owner && _this instanceof BABYLON.Group2D) {
  6942. var group = _this;
  6943. group.detectGroupStates();
  6944. }
  6945. // Time to insert children if some are specified
  6946. if (settings.children != null) {
  6947. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  6948. var child = _a[_i];
  6949. _this.addChild(child);
  6950. // Good time to patch the hierarchy, it won't go very far if there's no need to
  6951. if (_this.owner != null && _this._hierarchyDepth != null) {
  6952. child._patchHierarchy(_this.owner);
  6953. }
  6954. }
  6955. }
  6956. if (settings.zOrder != null) {
  6957. _this.zOrder = settings.zOrder;
  6958. }
  6959. // Set the model related properties
  6960. if (settings.position != null) {
  6961. _this.position = settings.position;
  6962. }
  6963. else if (settings.x != null || settings.y != null) {
  6964. _this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  6965. }
  6966. else {
  6967. _this._position = null;
  6968. }
  6969. _this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  6970. if (settings.scale != null) {
  6971. _this.scale = settings.scale;
  6972. }
  6973. else {
  6974. if (settings.scaleX != null) {
  6975. _this.scaleX = settings.scaleX;
  6976. }
  6977. if (settings.scaleY != null) {
  6978. _this.scaleY = settings.scaleY;
  6979. }
  6980. }
  6981. _this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  6982. _this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  6983. // Layout Engine
  6984. if (settings.layoutEngine != null) {
  6985. if (typeof settings.layoutEngine === "string") {
  6986. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  6987. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  6988. _this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  6989. }
  6990. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  6991. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  6992. }
  6993. else if (name_1.indexOf("verticalstackpanel") === 0) {
  6994. _this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  6995. }
  6996. }
  6997. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  6998. _this.layoutEngine = settings.layoutEngine;
  6999. }
  7000. }
  7001. // Set the layout/margin stuffs
  7002. if (settings.marginTop) {
  7003. _this.margin.setTop(settings.marginTop);
  7004. }
  7005. if (settings.marginLeft) {
  7006. _this.margin.setLeft(settings.marginLeft);
  7007. }
  7008. if (settings.marginRight) {
  7009. _this.margin.setRight(settings.marginRight);
  7010. }
  7011. if (settings.marginBottom) {
  7012. _this.margin.setBottom(settings.marginBottom);
  7013. }
  7014. if (settings.margin) {
  7015. if (typeof settings.margin === "string") {
  7016. _this.margin.fromString(settings.margin);
  7017. }
  7018. else {
  7019. _this.margin.fromUniformPixels(settings.margin);
  7020. }
  7021. }
  7022. if (settings.marginHAlignment) {
  7023. _this.marginAlignment.horizontal = settings.marginHAlignment;
  7024. }
  7025. if (settings.marginVAlignment) {
  7026. _this.marginAlignment.vertical = settings.marginVAlignment;
  7027. }
  7028. if (settings.marginAlignment) {
  7029. _this.marginAlignment.fromString(settings.marginAlignment);
  7030. }
  7031. if (settings.paddingTop) {
  7032. _this.padding.setTop(settings.paddingTop);
  7033. }
  7034. if (settings.paddingLeft) {
  7035. _this.padding.setLeft(settings.paddingLeft);
  7036. }
  7037. if (settings.paddingRight) {
  7038. _this.padding.setRight(settings.paddingRight);
  7039. }
  7040. if (settings.paddingBottom) {
  7041. _this.padding.setBottom(settings.paddingBottom);
  7042. }
  7043. if (settings.padding) {
  7044. if (typeof settings.padding === "string") {
  7045. _this.padding.fromString(settings.padding);
  7046. }
  7047. else {
  7048. _this.padding.fromUniformPixels(settings.padding);
  7049. }
  7050. }
  7051. if (settings.layoutData) {
  7052. _this.layoutData = settings.layoutData;
  7053. }
  7054. _this._updatePositioningState();
  7055. // Dirty layout and positioning
  7056. _this._parentLayoutDirty();
  7057. _this._positioningDirty();
  7058. // Add in the PCM
  7059. if (settings.levelCollision || settings.deepCollision) {
  7060. _this._actorInfo = _this.owner._primitiveCollisionManager._addActor(_this, settings.deepCollision === true);
  7061. _this._setFlags(BABYLON.SmartPropertyPrim.flagCollisionActor);
  7062. }
  7063. else {
  7064. _this._actorInfo = null;
  7065. }
  7066. return _this;
  7067. }
  7068. Object.defineProperty(Prim2DBase.prototype, "intersectWithObservable", {
  7069. /**
  7070. * Return the ChangedDictionary observable of the StringDictionary containing the primitives intersecting with this one
  7071. */
  7072. get: function () {
  7073. if (!this._actorInfo) {
  7074. return null;
  7075. }
  7076. return this._actorInfo.intersectWith.dictionaryChanged;
  7077. },
  7078. enumerable: true,
  7079. configurable: true
  7080. });
  7081. Object.defineProperty(Prim2DBase.prototype, "intersectWith", {
  7082. /**
  7083. * Return the ObservableStringDictionary containing all the primitives intersecting with this one.
  7084. * The key is the primitive uid, the value is the ActorInfo object
  7085. * @returns {}
  7086. */
  7087. get: function () {
  7088. if (!this._actorInfo) {
  7089. return null;
  7090. }
  7091. return this._actorInfo.intersectWith;
  7092. },
  7093. enumerable: true,
  7094. configurable: true
  7095. });
  7096. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  7097. get: function () {
  7098. if (!this._actionManager) {
  7099. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  7100. }
  7101. return this._actionManager;
  7102. },
  7103. enumerable: true,
  7104. configurable: true
  7105. });
  7106. /**
  7107. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  7108. * @param predicate the predicate to test on each parent
  7109. * @return the first primitive where the predicate was successful
  7110. */
  7111. Prim2DBase.prototype.traverseUp = function (predicate) {
  7112. var p = this;
  7113. while (p != null) {
  7114. if (predicate(p)) {
  7115. return p;
  7116. }
  7117. p = p._parent;
  7118. }
  7119. return null;
  7120. };
  7121. Object.defineProperty(Prim2DBase.prototype, "owner", {
  7122. /**
  7123. * Retrieve the owner Canvas2D
  7124. */
  7125. get: function () {
  7126. return this._owner;
  7127. },
  7128. enumerable: true,
  7129. configurable: true
  7130. });
  7131. Object.defineProperty(Prim2DBase.prototype, "parent", {
  7132. /**
  7133. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  7134. */
  7135. get: function () {
  7136. return this._parent;
  7137. },
  7138. enumerable: true,
  7139. configurable: true
  7140. });
  7141. Object.defineProperty(Prim2DBase.prototype, "children", {
  7142. /**
  7143. * The array of direct children primitives
  7144. */
  7145. get: function () {
  7146. return this._children;
  7147. },
  7148. enumerable: true,
  7149. configurable: true
  7150. });
  7151. Object.defineProperty(Prim2DBase.prototype, "id", {
  7152. /**
  7153. * The identifier of this primitive, may not be unique, it's for information purpose only
  7154. */
  7155. get: function () {
  7156. return this._id;
  7157. },
  7158. set: function (value) {
  7159. if (this._id === value) {
  7160. return;
  7161. }
  7162. var oldValue = this._id;
  7163. this.onPropertyChanged("id", oldValue, this._id);
  7164. },
  7165. enumerable: true,
  7166. configurable: true
  7167. });
  7168. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  7169. get: function () {
  7170. // If we don't use positioning engine the actual position is the position
  7171. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  7172. return this.position;
  7173. }
  7174. // We use the positioning engine, if the variable is fetched, it's up to date, return it
  7175. if (this._actualPosition != null) {
  7176. return this._actualPosition;
  7177. }
  7178. this._updatePositioning();
  7179. return this._actualPosition;
  7180. },
  7181. /**
  7182. * DO NOT INVOKE for internal purpose only
  7183. */
  7184. set: function (val) {
  7185. if (!this._actualPosition) {
  7186. this._actualPosition = val.clone();
  7187. }
  7188. else {
  7189. this._actualPosition.copyFrom(val);
  7190. }
  7191. },
  7192. enumerable: true,
  7193. configurable: true
  7194. });
  7195. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  7196. /**
  7197. * Shortcut to actualPosition.x
  7198. */
  7199. get: function () {
  7200. return this.actualPosition.x;
  7201. },
  7202. set: function (val) {
  7203. this._actualPosition.x = val;
  7204. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  7205. },
  7206. enumerable: true,
  7207. configurable: true
  7208. });
  7209. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  7210. /**
  7211. * Shortcut to actualPosition.y
  7212. */
  7213. get: function () {
  7214. return this.actualPosition.y;
  7215. },
  7216. set: function (val) {
  7217. this._actualPosition.y = val;
  7218. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualPosition);
  7219. },
  7220. enumerable: true,
  7221. configurable: true
  7222. });
  7223. Object.defineProperty(Prim2DBase.prototype, "position", {
  7224. /**
  7225. * Position of the primitive, relative to its parent.
  7226. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  7227. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  7228. * Setting this property may have no effect is specific alignment are in effect.
  7229. */
  7230. get: function () {
  7231. if (!this._position) {
  7232. this._position = BABYLON.Vector2.Zero();
  7233. }
  7234. return this._position;
  7235. },
  7236. set: function (value) {
  7237. if (!this._checkPositionChange()) {
  7238. return;
  7239. }
  7240. if (!value) {
  7241. this._position = null;
  7242. }
  7243. else {
  7244. if (!this._position) {
  7245. this._position = value.clone();
  7246. }
  7247. else {
  7248. this._position.copyFrom(value);
  7249. }
  7250. }
  7251. this._actualPosition = null;
  7252. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  7253. },
  7254. enumerable: true,
  7255. configurable: true
  7256. });
  7257. Object.defineProperty(Prim2DBase.prototype, "x", {
  7258. /**
  7259. * Direct access to the position.x value of the primitive
  7260. * Use this property when you only want to change one component of the position property
  7261. */
  7262. get: function () {
  7263. if (!this._position) {
  7264. return null;
  7265. }
  7266. return this._position.x;
  7267. },
  7268. set: function (value) {
  7269. if (!this._checkPositionChange()) {
  7270. return;
  7271. }
  7272. if (value == null) {
  7273. throw new Error("Can't set a null x in primitive " + this.id + ", only the position can be turned to null");
  7274. }
  7275. if (!this._position) {
  7276. this._position = BABYLON.Vector2.Zero();
  7277. }
  7278. if (this._position.x === value) {
  7279. return;
  7280. }
  7281. this._position.x = value;
  7282. this._actualPosition = null;
  7283. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  7284. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  7285. },
  7286. enumerable: true,
  7287. configurable: true
  7288. });
  7289. Object.defineProperty(Prim2DBase.prototype, "y", {
  7290. /**
  7291. * Direct access to the position.y value of the primitive
  7292. * Use this property when you only want to change one component of the position property
  7293. */
  7294. get: function () {
  7295. if (!this._position) {
  7296. return null;
  7297. }
  7298. return this._position.y;
  7299. },
  7300. set: function (value) {
  7301. if (!this._checkPositionChange()) {
  7302. return;
  7303. }
  7304. if (value == null) {
  7305. throw new Error("Can't set a null y in primitive " + this.id + ", only the position can be turned to null");
  7306. }
  7307. if (!this._position) {
  7308. this._position = BABYLON.Vector2.Zero();
  7309. }
  7310. if (this._position.y === value) {
  7311. return;
  7312. }
  7313. this._position.y = value;
  7314. this._actualPosition = null;
  7315. this._triggerPropertyChanged(Prim2DBase_1.positionProperty, value);
  7316. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, value);
  7317. },
  7318. enumerable: true,
  7319. configurable: true
  7320. });
  7321. Object.defineProperty(Prim2DBase.prototype, "size", {
  7322. /**
  7323. * Size of the primitive or its bounding area
  7324. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  7325. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  7326. */
  7327. get: function () {
  7328. return this.internalGetSize();
  7329. },
  7330. set: function (value) {
  7331. this.internalSetSize(value);
  7332. },
  7333. enumerable: true,
  7334. configurable: true
  7335. });
  7336. Prim2DBase.prototype.internalGetSize = function () {
  7337. if (!this._size || this._size.width == null || this._size.height == null) {
  7338. var bbr = Prim2DBase_1.boundinbBoxReentrency;
  7339. if (bbr !== -1 && bbr <= (this.hierarchyDepth || 0)) {
  7340. return Prim2DBase_1.nullSize;
  7341. }
  7342. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  7343. return this._internalSize;
  7344. }
  7345. Prim2DBase_1.boundinbBoxReentrency = this.hierarchyDepth || 0;
  7346. var b = this.layoutBoundingInfo;
  7347. Prim2DBase_1.boundinbBoxReentrency = -1;
  7348. Prim2DBase_1._size.copyFrom(this._internalSize);
  7349. b.sizeToRef(this._internalSize);
  7350. if (!this._internalSize.equals(Prim2DBase_1._size)) {
  7351. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, this._internalSize);
  7352. this._positioningDirty();
  7353. }
  7354. return this._internalSize || Prim2DBase_1._nullSize;
  7355. }
  7356. return this._size || Prim2DBase_1._nullSize;
  7357. };
  7358. Prim2DBase.prototype.internalSetSize = function (value) {
  7359. if (!value) {
  7360. this._size = null;
  7361. }
  7362. else {
  7363. if (!this._size) {
  7364. this._size = value.clone();
  7365. }
  7366. else {
  7367. this._size.copyFrom(value);
  7368. }
  7369. }
  7370. this._actualSize = null;
  7371. this._updatePositioningState();
  7372. this._positioningDirty();
  7373. };
  7374. Object.defineProperty(Prim2DBase.prototype, "width", {
  7375. /**
  7376. * Direct access to the size.width value of the primitive
  7377. * Use this property when you only want to change one component of the size property
  7378. */
  7379. get: function () {
  7380. if (!this.size) {
  7381. return null;
  7382. }
  7383. return this.size.width;
  7384. },
  7385. set: function (value) {
  7386. if (this.size && this.size.width === value) {
  7387. return;
  7388. }
  7389. if (!this.size) {
  7390. this.size = new BABYLON.Size(value, 0);
  7391. }
  7392. else {
  7393. this.size.width = value;
  7394. }
  7395. this._actualSize = null;
  7396. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  7397. this._positioningDirty();
  7398. },
  7399. enumerable: true,
  7400. configurable: true
  7401. });
  7402. Object.defineProperty(Prim2DBase.prototype, "height", {
  7403. /**
  7404. * Direct access to the size.height value of the primitive
  7405. * Use this property when you only want to change one component of the size property
  7406. */
  7407. get: function () {
  7408. if (!this.size) {
  7409. return null;
  7410. }
  7411. return this.size.height;
  7412. },
  7413. set: function (value) {
  7414. if (this.size && this.size.height === value) {
  7415. return;
  7416. }
  7417. if (!this.size) {
  7418. this.size = new BABYLON.Size(0, value);
  7419. }
  7420. else {
  7421. this.size.height = value;
  7422. }
  7423. this._actualSize = null;
  7424. this._triggerPropertyChanged(Prim2DBase_1.sizeProperty, value);
  7425. this._positioningDirty();
  7426. },
  7427. enumerable: true,
  7428. configurable: true
  7429. });
  7430. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  7431. get: function () {
  7432. return this._rotation;
  7433. },
  7434. set: function (value) {
  7435. this._rotation = value;
  7436. },
  7437. enumerable: true,
  7438. configurable: true
  7439. });
  7440. Object.defineProperty(Prim2DBase.prototype, "scale", {
  7441. get: function () {
  7442. return this._scale.x;
  7443. },
  7444. set: function (value) {
  7445. this._scale.x = this._scale.y = value;
  7446. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7447. this._spreadActualScaleDirty();
  7448. this._positioningDirty();
  7449. },
  7450. enumerable: true,
  7451. configurable: true
  7452. });
  7453. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  7454. /**
  7455. * Return the size of the primitive as it's being rendered into the target.
  7456. * 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.
  7457. * BEWARE: don't use the setter, it's for internal purpose only
  7458. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  7459. */
  7460. get: function () {
  7461. // If we don't use positioning engine the actual size is the size
  7462. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  7463. return this.size;
  7464. }
  7465. // We use the positioning engine, if the variable is fetched, it's up to date, return it
  7466. if (this._actualSize) {
  7467. return this._actualSize;
  7468. }
  7469. this._updatePositioning();
  7470. return this._actualSize;
  7471. },
  7472. set: function (value) {
  7473. if (this._actualSize && this._actualSize.equals(value)) {
  7474. return;
  7475. }
  7476. if (!this._actualSize) {
  7477. this._actualSize = value.clone();
  7478. }
  7479. else {
  7480. this._actualSize.copyFrom(value);
  7481. }
  7482. },
  7483. enumerable: true,
  7484. configurable: true
  7485. });
  7486. Object.defineProperty(Prim2DBase.prototype, "actualWidth", {
  7487. /**
  7488. * Shortcut to actualSize.width
  7489. */
  7490. get: function () {
  7491. return this.actualSize.width;
  7492. },
  7493. set: function (val) {
  7494. this._actualSize.width = val;
  7495. this._triggerPropertyChanged(Prim2DBase_1.actualSizeProperty, this._actualSize);
  7496. },
  7497. enumerable: true,
  7498. configurable: true
  7499. });
  7500. Object.defineProperty(Prim2DBase.prototype, "actualHeight", {
  7501. /**
  7502. * Shortcut to actualPosition.height
  7503. */
  7504. get: function () {
  7505. return this.actualSize.height;
  7506. },
  7507. set: function (val) {
  7508. this._actualSize.height = val;
  7509. this._triggerPropertyChanged(Prim2DBase_1.actualPositionProperty, this._actualSize);
  7510. },
  7511. enumerable: true,
  7512. configurable: true
  7513. });
  7514. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  7515. get: function () {
  7516. if (this._manualZOrder != null) {
  7517. return this._manualZOrder;
  7518. }
  7519. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  7520. this._updateZOrder();
  7521. }
  7522. return (1 - this._zOrder);
  7523. },
  7524. enumerable: true,
  7525. configurable: true
  7526. });
  7527. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  7528. /**
  7529. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  7530. * The Primitive's size won't be less than specified.
  7531. * The default value depends of the Primitive type
  7532. */
  7533. get: function () {
  7534. return this._minSize;
  7535. },
  7536. set: function (value) {
  7537. if (this._minSize && value && this._minSize.equals(value)) {
  7538. return;
  7539. }
  7540. if (!this._minSize) {
  7541. this._minSize = value.clone();
  7542. }
  7543. else {
  7544. this._minSize.copyFrom(value);
  7545. }
  7546. this._parentLayoutDirty();
  7547. },
  7548. enumerable: true,
  7549. configurable: true
  7550. });
  7551. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  7552. /**
  7553. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  7554. * The Primitive's size won't be more than specified.
  7555. * The default value depends of the Primitive type
  7556. */
  7557. get: function () {
  7558. return this._maxSize;
  7559. },
  7560. set: function (value) {
  7561. if (this._maxSize && value && this._maxSize.equals(value)) {
  7562. return;
  7563. }
  7564. if (!this._maxSize) {
  7565. this._maxSize = value.clone();
  7566. }
  7567. else {
  7568. this._maxSize.copyFrom(value);
  7569. }
  7570. this._parentLayoutDirty();
  7571. },
  7572. enumerable: true,
  7573. configurable: true
  7574. });
  7575. Object.defineProperty(Prim2DBase.prototype, "origin", {
  7576. /**
  7577. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  7578. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  7579. * For instance:
  7580. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  7581. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  7582. * 0,1 means the center is top/left
  7583. * @returns The normalized center.
  7584. */
  7585. get: function () {
  7586. return this._origin;
  7587. },
  7588. set: function (value) {
  7589. if (!this._origin) {
  7590. this._origin = value.clone();
  7591. }
  7592. else {
  7593. this._origin.copyFrom(value);
  7594. }
  7595. },
  7596. enumerable: true,
  7597. configurable: true
  7598. });
  7599. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  7600. get: function () {
  7601. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  7602. },
  7603. set: function (value) {
  7604. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  7605. },
  7606. enumerable: true,
  7607. configurable: true
  7608. });
  7609. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  7610. get: function () {
  7611. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  7612. },
  7613. set: function (value) {
  7614. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  7615. },
  7616. enumerable: true,
  7617. configurable: true
  7618. });
  7619. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  7620. get: function () {
  7621. return this._manualZOrder;
  7622. },
  7623. set: function (value) {
  7624. if (this._manualZOrder === value) {
  7625. return;
  7626. }
  7627. this._manualZOrder = value;
  7628. this.onZOrderChanged();
  7629. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  7630. this._actualZOrderChangedObservable.notifyObservers(value);
  7631. }
  7632. },
  7633. enumerable: true,
  7634. configurable: true
  7635. });
  7636. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  7637. get: function () {
  7638. return this._manualZOrder != null;
  7639. },
  7640. enumerable: true,
  7641. configurable: true
  7642. });
  7643. Object.defineProperty(Prim2DBase.prototype, "margin", {
  7644. get: function () {
  7645. var _this = this;
  7646. if (!this._margin) {
  7647. this._margin = new PrimitiveThickness(function () {
  7648. if (!_this.parent) {
  7649. return null;
  7650. }
  7651. return _this.parent.margin;
  7652. }, function () { return _this._positioningDirty(); });
  7653. this._updatePositioningState();
  7654. }
  7655. return this._margin;
  7656. },
  7657. set: function (value) {
  7658. if (!value) {
  7659. this._margin = null;
  7660. }
  7661. else {
  7662. this.margin.copyFrom(value);
  7663. }
  7664. this._updatePositioningState();
  7665. },
  7666. enumerable: true,
  7667. configurable: true
  7668. });
  7669. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  7670. /**
  7671. * Check for both margin and marginAlignment, return true if at least one of them is specified with a non default value
  7672. */
  7673. get: function () {
  7674. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(Prim2DBase.prototype, "padding", {
  7680. get: function () {
  7681. var _this = this;
  7682. if (!this._padding) {
  7683. this._padding = new PrimitiveThickness(function () {
  7684. if (!_this.parent) {
  7685. return null;
  7686. }
  7687. return _this.parent.padding;
  7688. }, function () { return _this._positioningDirty(); });
  7689. this._updatePositioningState();
  7690. }
  7691. return this._padding;
  7692. },
  7693. set: function (value) {
  7694. if (!value) {
  7695. this._padding = null;
  7696. }
  7697. else {
  7698. this.padding.copyFrom(value);
  7699. }
  7700. this._updatePositioningState();
  7701. },
  7702. enumerable: true,
  7703. configurable: true
  7704. });
  7705. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  7706. get: function () {
  7707. return this._padding !== null && !this._padding.isDefault;
  7708. },
  7709. enumerable: true,
  7710. configurable: true
  7711. });
  7712. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  7713. get: function () {
  7714. var _this = this;
  7715. if (!this._marginAlignment) {
  7716. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  7717. this._updatePositioningState();
  7718. }
  7719. return this._marginAlignment;
  7720. },
  7721. set: function (value) {
  7722. if (!value) {
  7723. this._marginAlignment = null;
  7724. }
  7725. else {
  7726. this.marginAlignment.copyFrom(value);
  7727. }
  7728. this._updatePositioningState();
  7729. },
  7730. enumerable: true,
  7731. configurable: true
  7732. });
  7733. Object.defineProperty(Prim2DBase.prototype, "_hasMarginAlignment", {
  7734. /**
  7735. * Check if there a marginAlignment specified (non null and not default)
  7736. */
  7737. get: function () {
  7738. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  7739. },
  7740. enumerable: true,
  7741. configurable: true
  7742. });
  7743. Prim2DBase.prototype._updatePositioningState = function () {
  7744. var value = this._hasMargin || this._hasPadding || this.isSizeAuto;
  7745. // console.log(`${this.id} with parent ${this._parent ? this._parent.id : "[none]"} state: ${value} `);
  7746. this._changeFlags(BABYLON.SmartPropertyPrim.flagUsePositioning, value);
  7747. };
  7748. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  7749. get: function () {
  7750. return this._opacity;
  7751. },
  7752. set: function (value) {
  7753. if (value < 0) {
  7754. value = 0;
  7755. }
  7756. else if (value > 1) {
  7757. value = 1;
  7758. }
  7759. if (this._opacity === value) {
  7760. return;
  7761. }
  7762. this._opacity = value;
  7763. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  7764. this._spreadActualOpacityChanged();
  7765. this._updateRenderMode();
  7766. },
  7767. enumerable: true,
  7768. configurable: true
  7769. });
  7770. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  7771. get: function () {
  7772. return this._scale.x;
  7773. },
  7774. set: function (value) {
  7775. this._scale.x = value;
  7776. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7777. this._spreadActualScaleDirty();
  7778. this._positioningDirty();
  7779. },
  7780. enumerable: true,
  7781. configurable: true
  7782. });
  7783. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  7784. get: function () {
  7785. return this._scale.y;
  7786. },
  7787. set: function (value) {
  7788. this._scale.y = value;
  7789. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7790. this._spreadActualScaleDirty();
  7791. this._positioningDirty();
  7792. },
  7793. enumerable: true,
  7794. configurable: true
  7795. });
  7796. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  7797. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7798. var child = _a[_i];
  7799. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7800. child._spreadActualScaleDirty();
  7801. }
  7802. };
  7803. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  7804. /**
  7805. * 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
  7806. */
  7807. get: function () {
  7808. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  7809. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  7810. var sx = this.scaleX;
  7811. var sy = this.scaleY;
  7812. while (cur) {
  7813. sx *= cur.scaleX;
  7814. sy *= cur.scaleY;
  7815. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  7816. }
  7817. this._actualScale.copyFromFloats(sx, sy);
  7818. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  7819. }
  7820. return this._actualScale;
  7821. },
  7822. enumerable: true,
  7823. configurable: true
  7824. });
  7825. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  7826. /**
  7827. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  7828. */
  7829. get: function () {
  7830. return this.actualScale.x;
  7831. },
  7832. enumerable: true,
  7833. configurable: true
  7834. });
  7835. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  7836. /**
  7837. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  7838. */
  7839. get: function () {
  7840. return this.actualScale.y;
  7841. },
  7842. enumerable: true,
  7843. configurable: true
  7844. });
  7845. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  7846. /**
  7847. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  7848. */
  7849. get: function () {
  7850. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  7851. var cur = this.parent;
  7852. var op = this.opacity;
  7853. while (cur) {
  7854. op *= cur.opacity;
  7855. cur = cur.parent;
  7856. }
  7857. this._actualOpacity = op;
  7858. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  7859. }
  7860. return this._actualOpacity;
  7861. },
  7862. enumerable: true,
  7863. configurable: true
  7864. });
  7865. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  7866. /**
  7867. * Get/set the layout engine to use for this primitive.
  7868. * The default layout engine is the CanvasLayoutEngine.
  7869. */
  7870. get: function () {
  7871. if (!this._layoutEngine) {
  7872. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  7873. }
  7874. return this._layoutEngine;
  7875. },
  7876. set: function (value) {
  7877. if (this._layoutEngine === value) {
  7878. return;
  7879. }
  7880. this._changeLayoutEngine(value);
  7881. },
  7882. enumerable: true,
  7883. configurable: true
  7884. });
  7885. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  7886. /**
  7887. * Get/set the layout are of this primitive.
  7888. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  7889. * The setter should only be called by a Layout Engine class.
  7890. */
  7891. get: function () {
  7892. return this._layoutArea;
  7893. },
  7894. set: function (val) {
  7895. if (this._layoutArea && this._layoutArea.equals(val)) {
  7896. return;
  7897. }
  7898. this._positioningDirty();
  7899. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  7900. if (this.parent) {
  7901. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7902. }
  7903. if (!this._layoutArea) {
  7904. this._layoutArea = val.clone();
  7905. }
  7906. else {
  7907. this._layoutArea.copyFrom(val);
  7908. }
  7909. },
  7910. enumerable: true,
  7911. configurable: true
  7912. });
  7913. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  7914. /**
  7915. * Get/set the layout area position (relative to the parent primitive).
  7916. * The setter should only be called by a Layout Engine class.
  7917. */
  7918. get: function () {
  7919. return this._layoutAreaPos;
  7920. },
  7921. set: function (val) {
  7922. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  7923. return;
  7924. }
  7925. if (this.parent) {
  7926. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  7927. }
  7928. this._positioningDirty();
  7929. if (!this._layoutAreaPos) {
  7930. this._layoutAreaPos = val.clone();
  7931. }
  7932. else {
  7933. this._layoutAreaPos.copyFrom(val);
  7934. }
  7935. this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
  7936. },
  7937. enumerable: true,
  7938. configurable: true
  7939. });
  7940. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  7941. /**
  7942. * Define if the Primitive can be subject to intersection test or not (default is true)
  7943. */
  7944. get: function () {
  7945. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  7946. },
  7947. set: function (value) {
  7948. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  7949. },
  7950. enumerable: true,
  7951. configurable: true
  7952. });
  7953. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  7954. /**
  7955. * Define if the Primitive acts as a container or not
  7956. * A container will encapsulate its children for interaction event.
  7957. * If it's not a container events will be process down to children if the primitive is not pickable.
  7958. * Default value is true
  7959. */
  7960. get: function () {
  7961. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  7962. },
  7963. set: function (value) {
  7964. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  7965. },
  7966. enumerable: true,
  7967. configurable: true
  7968. });
  7969. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  7970. /**
  7971. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  7972. */
  7973. get: function () {
  7974. return this._hierarchyDepth;
  7975. },
  7976. enumerable: true,
  7977. configurable: true
  7978. });
  7979. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  7980. /**
  7981. * Retrieve the Group that is responsible to render this primitive
  7982. */
  7983. get: function () {
  7984. return this._renderGroup;
  7985. },
  7986. enumerable: true,
  7987. configurable: true
  7988. });
  7989. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  7990. /**
  7991. * Get the global transformation matrix of the primitive
  7992. */
  7993. get: function () {
  7994. if (this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  7995. this.updateCachedStates(false);
  7996. }
  7997. return this._globalTransform;
  7998. },
  7999. enumerable: true,
  8000. configurable: true
  8001. });
  8002. /**
  8003. * return the global position of the primitive, relative to its canvas
  8004. */
  8005. Prim2DBase.prototype.getGlobalPosition = function () {
  8006. var v = new BABYLON.Vector2(0, 0);
  8007. this.getGlobalPositionByRef(v);
  8008. return v;
  8009. };
  8010. /**
  8011. * return the global position of the primitive, relative to its canvas
  8012. * @param v the valid Vector2 object where the global position will be stored
  8013. */
  8014. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  8015. v.x = this.globalTransform.m[12];
  8016. v.y = this.globalTransform.m[13];
  8017. };
  8018. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  8019. /**
  8020. * Get invert of the global transformation matrix of the primitive
  8021. */
  8022. get: function () {
  8023. this._updateLocalTransform();
  8024. return this._invGlobalTransform;
  8025. },
  8026. enumerable: true,
  8027. configurable: true
  8028. });
  8029. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  8030. /**
  8031. * Get the local transformation of the primitive
  8032. */
  8033. get: function () {
  8034. this._updateLocalTransform();
  8035. return this._localTransform;
  8036. },
  8037. enumerable: true,
  8038. configurable: true
  8039. });
  8040. Object.defineProperty(Prim2DBase.prototype, "localLayoutTransform", {
  8041. get: function () {
  8042. this._updateLocalTransform();
  8043. return this._localLayoutTransform;
  8044. },
  8045. enumerable: true,
  8046. configurable: true
  8047. });
  8048. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  8049. /**
  8050. * Get the boundingInfo associated to the primitive and its children.
  8051. * The value is supposed to be always up to date
  8052. */
  8053. get: function () {
  8054. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  8055. if (this.owner) {
  8056. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  8057. }
  8058. var sizedByContent = this.isSizedByContent;
  8059. if (sizedByContent) {
  8060. this._boundingInfo.clear();
  8061. }
  8062. else {
  8063. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  8064. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  8065. return this._boundingInfo;
  8066. }
  8067. }
  8068. var bi = this._boundingInfo;
  8069. var tps = new BABYLON.BoundingInfo2D();
  8070. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8071. var curChild = _a[_i];
  8072. var bb = curChild.boundingInfo;
  8073. bb.transformToRef(curChild.localTransform, tps);
  8074. bi.unionToRef(tps, bi);
  8075. }
  8076. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  8077. }
  8078. return this._boundingInfo;
  8079. },
  8080. enumerable: true,
  8081. configurable: true
  8082. });
  8083. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  8084. /**
  8085. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  8086. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  8087. */
  8088. get: function () {
  8089. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  8090. if (this._owner) {
  8091. this._owner.addLayoutBoundingInfoUpdateCounter(1);
  8092. }
  8093. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  8094. this.owner.addUpdateLayoutCounter(1);
  8095. this._layoutEngine.updateLayout(this);
  8096. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  8097. }
  8098. var lbb = new BABYLON.BoundingInfo2D();
  8099. var sizedByContent = this.isSizedByContent;
  8100. if (sizedByContent) {
  8101. lbb.clear();
  8102. }
  8103. else {
  8104. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.marginSize, lbb);
  8105. }
  8106. var tps = Prim2DBase_1._tpsBB;
  8107. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8108. var curChild = _a[_i];
  8109. if (curChild._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  8110. continue;
  8111. }
  8112. var bb = curChild.layoutBoundingInfo;
  8113. bb.transformToRef(curChild.localLayoutTransform, tps);
  8114. lbb.unionToRef(tps, lbb);
  8115. }
  8116. // Update content area
  8117. Prim2DBase_1._curContentArea.copyFrom(this._contentArea);
  8118. var size = Prim2DBase_1._size2;
  8119. lbb.sizeToRef(this._contentArea);
  8120. lbb.sizeToRef(size);
  8121. if (!Prim2DBase_1._curContentArea.equals(this._contentArea)) {
  8122. this._setLayoutDirty();
  8123. }
  8124. // Apply padding
  8125. if (this._hasPadding) {
  8126. var padding = this.padding;
  8127. size.width += padding.leftPixels + padding.rightPixels;
  8128. size.height += padding.bottomPixels + padding.topPixels;
  8129. this._paddingOffset.copyFromFloats(padding.leftPixels, padding.bottomPixels, padding.rightPixels, padding.topPixels);
  8130. this._getActualSizeFromContentToRef(size, this._paddingOffset, size);
  8131. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, lbb);
  8132. }
  8133. else {
  8134. this._paddingOffset.copyFromFloats(0, 0, 0, 0);
  8135. }
  8136. // Check if the layoutBoundingInfo changed
  8137. var changed = false;
  8138. if (!this._layoutBoundingInfo) {
  8139. this._layoutBoundingInfo = lbb.clone();
  8140. changed = true;
  8141. }
  8142. else if (!this._layoutBoundingInfo.equals(lbb)) {
  8143. this._layoutBoundingInfo.copyFrom(lbb);
  8144. changed = true;
  8145. }
  8146. if (changed) {
  8147. var p = this._parent;
  8148. while (p) {
  8149. if (p.isSizedByContent) {
  8150. p._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  8151. p.onPrimitivePropertyDirty(Prim2DBase_1.actualSizeProperty.flagId);
  8152. }
  8153. else {
  8154. break;
  8155. }
  8156. p = p._parent;
  8157. }
  8158. this.onPrimitivePropertyDirty(Prim2DBase_1.actualSizeProperty.flagId);
  8159. }
  8160. //console.log(`Compute BoundingLayout of ${this.id}, extent: ${this._layoutBoundingInfo.extent}`);
  8161. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  8162. }
  8163. return this._layoutBoundingInfo;
  8164. },
  8165. enumerable: true,
  8166. configurable: true
  8167. });
  8168. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  8169. /**
  8170. * Determine if the size is automatically computed or fixed because manually specified.
  8171. * Use the actualSize property to get the final/real size of the primitive
  8172. * @returns true if the size is automatically computed, false if it were manually specified.
  8173. */
  8174. get: function () {
  8175. var size = this._size;
  8176. return size == null || (size.width == null && size.height == null);
  8177. },
  8178. enumerable: true,
  8179. configurable: true
  8180. });
  8181. Object.defineProperty(Prim2DBase.prototype, "isHorizontalSizeAuto", {
  8182. /**
  8183. * Determine if the horizontal size is automatically computed or fixed because manually specified.
  8184. * Use the actualSize property to get the final/real size of the primitive
  8185. * @returns true if the horizontal size is automatically computed, false if it were manually specified.
  8186. */
  8187. get: function () {
  8188. var size = this._size;
  8189. return size == null || size.width == null;
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. Object.defineProperty(Prim2DBase.prototype, "isVerticalSizeAuto", {
  8195. /**
  8196. * Determine if the vertical size is automatically computed or fixed because manually specified.
  8197. * Use the actualSize property to get the final/real size of the primitive
  8198. * @returns true if the vertical size is automatically computed, false if it were manually specified.
  8199. */
  8200. get: function () {
  8201. var size = this._size;
  8202. return size == null || size.height == null;
  8203. },
  8204. enumerable: true,
  8205. configurable: true
  8206. });
  8207. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  8208. /**
  8209. * Return true if this prim has an auto size which is set by the children's global bounding box
  8210. */
  8211. get: function () {
  8212. return (this._size == null) && (this._children.length > 0);
  8213. },
  8214. enumerable: true,
  8215. configurable: true
  8216. });
  8217. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  8218. /**
  8219. * Determine if the position is automatically computed or fixed because manually specified.
  8220. * Use the actualPosition property to get the final/real position of the primitive
  8221. * @returns true if the position is automatically computed, false if it were manually specified.
  8222. */
  8223. get: function () {
  8224. return this._position == null;
  8225. },
  8226. enumerable: true,
  8227. configurable: true
  8228. });
  8229. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  8230. /**
  8231. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  8232. */
  8233. get: function () {
  8234. return this._pointerEventObservable;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  8240. get: function () {
  8241. if (!this._actualZOrderChangedObservable) {
  8242. this._actualZOrderChangedObservable = new BABYLON.Observable();
  8243. }
  8244. return this._actualZOrderChangedObservable;
  8245. },
  8246. enumerable: true,
  8247. configurable: true
  8248. });
  8249. Object.defineProperty(Prim2DBase.prototype, "displayDebugAreas", {
  8250. get: function () {
  8251. return this._displayDebugAreas;
  8252. },
  8253. set: function (value) {
  8254. if (this._displayDebugAreas === value) {
  8255. return;
  8256. }
  8257. if (value === false) {
  8258. this._debugAreaGroup.dispose();
  8259. this._debugAreaGroup = null;
  8260. }
  8261. else {
  8262. var layoutFill = "#F0808040"; // Red - Layout area
  8263. var layoutBorder = "#F08080FF";
  8264. var marginFill = "#F0F04040"; // Yellow - Margin area
  8265. var marginBorder = "#F0F040FF";
  8266. var paddingFill = "#F040F040"; // Magenta - Padding Area
  8267. var paddingBorder = "#F040F0FF";
  8268. var contentFill = "#40F0F040"; // Cyan - Content area
  8269. var contentBorder = "#40F0F0FF";
  8270. var s = new BABYLON.Size(10, 10);
  8271. var p = BABYLON.Vector2.Zero();
  8272. this._debugAreaGroup = new BABYLON.Group2D({ dontInheritParentScale: true,
  8273. parent: (this.parent != null) ? this.parent : this, id: "###DEBUG AREA GROUP###", children: [
  8274. new BABYLON.Group2D({
  8275. id: "###Layout Area###", position: p, size: s, children: [
  8276. new BABYLON.Rectangle2D({ id: "###Layout Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: layoutBorder }),
  8277. new BABYLON.Rectangle2D({ id: "###Layout Top###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  8278. new BABYLON.Rectangle2D({ id: "###Layout Left###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  8279. new BABYLON.Rectangle2D({ id: "###Layout Right###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  8280. new BABYLON.Rectangle2D({ id: "###Layout Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill })
  8281. ]
  8282. }),
  8283. new BABYLON.Group2D({
  8284. id: "###Margin Area###", position: p, size: s, children: [
  8285. new BABYLON.Rectangle2D({ id: "###Margin Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: marginBorder }),
  8286. new BABYLON.Rectangle2D({ id: "###Margin Top###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  8287. new BABYLON.Rectangle2D({ id: "###Margin Left###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  8288. new BABYLON.Rectangle2D({ id: "###Margin Right###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  8289. new BABYLON.Rectangle2D({ id: "###Margin Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill })
  8290. ]
  8291. }),
  8292. new BABYLON.Group2D({
  8293. id: "###Padding Area###", position: p, size: s, children: [
  8294. new BABYLON.Rectangle2D({ id: "###Padding Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: paddingBorder }),
  8295. new BABYLON.Rectangle2D({ id: "###Padding Top###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  8296. new BABYLON.Rectangle2D({ id: "###Padding Left###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  8297. new BABYLON.Rectangle2D({ id: "###Padding Right###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  8298. new BABYLON.Rectangle2D({ id: "###Padding Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill })
  8299. ]
  8300. }),
  8301. new BABYLON.Group2D({
  8302. id: "###Content Area###", position: p, size: s, children: [
  8303. new BABYLON.Rectangle2D({ id: "###Content Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: contentBorder }),
  8304. new BABYLON.Rectangle2D({ id: "###Content Top###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  8305. new BABYLON.Rectangle2D({ id: "###Content Left###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  8306. new BABYLON.Rectangle2D({ id: "###Content Right###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  8307. new BABYLON.Rectangle2D({ id: "###Content Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill })
  8308. ]
  8309. })
  8310. ]
  8311. });
  8312. this._debugAreaGroup._setFlags(BABYLON.SmartPropertyPrim.flagNoPartOfLayout);
  8313. this._updateDebugArea();
  8314. }
  8315. this._displayDebugAreas = value;
  8316. },
  8317. enumerable: true,
  8318. configurable: true
  8319. });
  8320. Prim2DBase.prototype._updateDebugArea = function () {
  8321. if (Prim2DBase_1._updatingDebugArea === true) {
  8322. return;
  8323. }
  8324. Prim2DBase_1._updatingDebugArea = true;
  8325. var areaNames = ["Layout", "Margin", "Padding", "Content"];
  8326. var areaZones = ["Area", "Frame", "Top", "Left", "Right", "Bottom"];
  8327. var prims = new Array(4);
  8328. // Get all the primitives used to display the areas
  8329. for (var i = 0; i < 4; i++) {
  8330. prims[i] = new Array(6);
  8331. for (var j = 0; j < 6; j++) {
  8332. prims[i][j] = this._debugAreaGroup.findById("###" + areaNames[i] + " " + areaZones[j] + "###");
  8333. if (j > 1) {
  8334. prims[i][j].levelVisible = false;
  8335. }
  8336. }
  8337. }
  8338. // Update the visibility status of layout/margin/padding
  8339. var hasLayout = this._layoutAreaPos != null;
  8340. var hasPos = (this.actualPosition.x !== 0) || (this.actualPosition.y !== 0);
  8341. var hasMargin = this._hasMargin;
  8342. var hasPadding = this._hasPadding;
  8343. prims[0][0].levelVisible = hasLayout;
  8344. prims[1][0].levelVisible = hasMargin;
  8345. prims[2][0].levelVisible = hasPadding;
  8346. prims[3][0].levelVisible = true;
  8347. // Current offset
  8348. var curOffset = BABYLON.Vector2.Zero();
  8349. // Store the area info of the layout area
  8350. var curAreaIndex = 0;
  8351. // Store data about each area
  8352. var areaInfo = new Array(4);
  8353. var storeAreaInfo = function (pos, size) {
  8354. var min = pos.clone();
  8355. var max = pos.clone();
  8356. if (size.width > 0) {
  8357. max.x += size.width;
  8358. }
  8359. if (size.height > 0) {
  8360. max.y += size.height;
  8361. }
  8362. areaInfo[curAreaIndex++] = { off: pos, size: size, min: min, max: max };
  8363. };
  8364. var isCanvas = this instanceof BABYLON.Canvas2D;
  8365. var marginH = this._marginOffset.x + this._marginOffset.z;
  8366. var marginV = this._marginOffset.y + this._marginOffset.w;
  8367. var actualSize = this.actualSize.multiplyByFloats(isCanvas ? 1 : this.scaleX, isCanvas ? 1 : this.scaleY);
  8368. var w = hasLayout ? (this.layoutAreaPos.x + this.layoutArea.width) : (marginH + actualSize.width);
  8369. var h = hasLayout ? (this.layoutAreaPos.y + this.layoutArea.height) : (marginV + actualSize.height);
  8370. var pos = (!hasLayout && !hasMargin && !hasPadding && hasPos) ? this.actualPosition : BABYLON.Vector2.Zero();
  8371. storeAreaInfo(pos, new BABYLON.Size(w, h));
  8372. // Compute the layout related data
  8373. if (hasLayout) {
  8374. var layoutOffset = this.layoutAreaPos.clone();
  8375. storeAreaInfo(layoutOffset, (hasMargin || hasPadding) ? this.layoutArea.clone() : actualSize.clone());
  8376. curOffset = layoutOffset.clone();
  8377. }
  8378. // Compute margin data
  8379. if (hasMargin) {
  8380. var marginOffset = curOffset.clone();
  8381. marginOffset.x += this._marginOffset.x;
  8382. marginOffset.y += this._marginOffset.y;
  8383. var marginArea = actualSize;
  8384. storeAreaInfo(marginOffset, marginArea);
  8385. curOffset = marginOffset.clone();
  8386. }
  8387. if (hasPadding) {
  8388. var contentOffset = curOffset.clone();
  8389. contentOffset.x += this._paddingOffset.x;
  8390. contentOffset.y += this._paddingOffset.y;
  8391. var contentArea = this.contentArea;
  8392. storeAreaInfo(contentOffset, contentArea);
  8393. curOffset = curOffset.add(contentOffset);
  8394. }
  8395. // Helper function that set the pos and size of a given prim
  8396. var setArea = function (i, j, pos, size) {
  8397. prims[i][j].position = pos;
  8398. prims[i][j].size = size;
  8399. };
  8400. var setFullRect = function (i, pos, size) {
  8401. var plist = prims[i];
  8402. plist[2].levelVisible = true;
  8403. plist[3].levelVisible = false;
  8404. plist[4].levelVisible = false;
  8405. plist[5].levelVisible = false;
  8406. setArea(i, 1, pos, size);
  8407. setArea(i, 2, pos, size);
  8408. };
  8409. var setQuadRect = function (i, areaIndex) {
  8410. var plist = prims[i];
  8411. plist[2].levelVisible = true;
  8412. plist[3].levelVisible = true;
  8413. plist[4].levelVisible = true;
  8414. plist[5].levelVisible = true;
  8415. var ca = areaInfo[areaIndex];
  8416. var na = areaInfo[areaIndex + 1];
  8417. var tp = new BABYLON.Vector2(ca.min.x, na.max.y);
  8418. var ts = new BABYLON.Size(ca.size.width, ca.max.y - tp.y);
  8419. var lp = new BABYLON.Vector2(ca.min.x, na.min.y);
  8420. var ls = new BABYLON.Size(na.min.x - ca.min.x, na.max.y - na.min.y);
  8421. var rp = new BABYLON.Vector2(na.max.x, na.min.y);
  8422. var rs = new BABYLON.Size(ca.max.x - na.max.x, na.max.y - na.min.y);
  8423. var bp = new BABYLON.Vector2(ca.min.x, ca.min.y);
  8424. var bs = new BABYLON.Size(ca.size.width, na.min.y - ca.min.y);
  8425. // Frame
  8426. plist[1].position = ca.off;
  8427. plist[1].size = ca.size;
  8428. // Top rect
  8429. plist[2].position = tp;
  8430. plist[2].size = ts;
  8431. // Left rect
  8432. plist[3].position = lp;
  8433. plist[3].size = ls;
  8434. // Right rect
  8435. plist[4].position = rp;
  8436. plist[4].size = rs;
  8437. // Bottom rect
  8438. plist[5].position = bp;
  8439. plist[5].size = bs;
  8440. };
  8441. var areaCount = curAreaIndex;
  8442. curAreaIndex = 0;
  8443. // Available zones
  8444. var availableZones = [false, hasLayout, hasMargin, hasPadding, true];
  8445. for (var k = 1; k < 5; k++) {
  8446. if (availableZones[k]) {
  8447. var ai = areaInfo[curAreaIndex];
  8448. setArea(k - 1, 0, BABYLON.Vector2.Zero(), ai.size);
  8449. // setArea(k-1, 1, Vector2.Zero(), ai.size);
  8450. if (k === 4) {
  8451. setFullRect(k - 1, ai.off, ai.size);
  8452. }
  8453. else {
  8454. setQuadRect(k - 1, curAreaIndex);
  8455. }
  8456. ++curAreaIndex;
  8457. }
  8458. }
  8459. Prim2DBase_1._updatingDebugArea = false;
  8460. };
  8461. Prim2DBase.prototype.findById = function (id) {
  8462. if (this._id === id) {
  8463. return this;
  8464. }
  8465. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8466. var child = _a[_i];
  8467. var r = child.findById(id);
  8468. if (r != null) {
  8469. return r;
  8470. }
  8471. }
  8472. };
  8473. Prim2DBase.prototype.onZOrderChanged = function () {
  8474. };
  8475. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  8476. return false;
  8477. };
  8478. /**
  8479. * Capture all the Events of the given PointerId for this primitive.
  8480. * Don't forget to call releasePointerEventsCapture when done.
  8481. * @param pointerId the Id of the pointer to capture the events from.
  8482. */
  8483. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  8484. return this.owner._setPointerCapture(pointerId, this);
  8485. };
  8486. /**
  8487. * Release a captured pointer made with setPointerEventCapture.
  8488. * @param pointerId the Id of the pointer to release the capture from.
  8489. */
  8490. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  8491. return this.owner._releasePointerCapture(pointerId, this);
  8492. };
  8493. /**
  8494. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  8495. * @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.
  8496. */
  8497. Prim2DBase.prototype.intersect = function (intersectInfo) {
  8498. if (!intersectInfo) {
  8499. return false;
  8500. }
  8501. // If this is null it means this method is call for the first level, initialize stuffs
  8502. var firstLevel = !intersectInfo._globalPickPosition;
  8503. if (firstLevel) {
  8504. // 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).
  8505. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  8506. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  8507. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  8508. intersectInfo.intersectedPrimitives = new Array();
  8509. intersectInfo.topMostIntersectedPrimitive = null;
  8510. }
  8511. if (!Prim2DBase_1._bypassGroup2DExclusion && this instanceof BABYLON.Group2D && this.isCachedGroup && !this.isRenderableGroup) {
  8512. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8513. intersectInfo._exit(firstLevel);
  8514. return false;
  8515. }
  8516. if (!intersectInfo.intersectHidden && !this.isVisible) {
  8517. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8518. intersectInfo._exit(firstLevel);
  8519. return false;
  8520. }
  8521. var id = this.id;
  8522. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  8523. try {
  8524. Prim2DBase_1._bypassGroup2DExclusion = true;
  8525. var ownerGroup = this.getExternalData("__cachedGroup__");
  8526. return ownerGroup.intersect(intersectInfo);
  8527. }
  8528. finally {
  8529. Prim2DBase_1._bypassGroup2DExclusion = false;
  8530. }
  8531. }
  8532. // 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).
  8533. var isIntersectionTest = false;
  8534. if (this instanceof BABYLON.Group2D) {
  8535. var g = this;
  8536. isIntersectionTest = g.isCachedGroup;
  8537. }
  8538. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  8539. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8540. intersectInfo._exit(firstLevel);
  8541. return false;
  8542. }
  8543. // Fast rejection test with boundingInfo
  8544. var boundingIntersected = true;
  8545. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  8546. if (this.isContainer) {
  8547. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  8548. intersectInfo._exit(firstLevel);
  8549. return false;
  8550. }
  8551. boundingIntersected = false;
  8552. }
  8553. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  8554. var levelIntersectRes = false;
  8555. if (this.isPickable) {
  8556. levelIntersectRes = boundingIntersected && this.levelIntersect(intersectInfo);
  8557. if (levelIntersectRes) {
  8558. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  8559. intersectInfo.intersectedPrimitives.push(pii);
  8560. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  8561. intersectInfo.topMostIntersectedPrimitive = pii;
  8562. }
  8563. // If we must stop at the first intersection, we're done, quit!
  8564. if (intersectInfo.findFirstOnly) {
  8565. intersectInfo._exit(firstLevel);
  8566. return true;
  8567. }
  8568. }
  8569. }
  8570. // Recurse to children if needed
  8571. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  8572. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8573. var curChild = _a[_i];
  8574. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  8575. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  8576. continue;
  8577. }
  8578. // Must compute the localPickLocation for the children level
  8579. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  8580. // If we got an intersection with the child and we only need to find the first one, quit!
  8581. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  8582. intersectInfo._exit(firstLevel);
  8583. return true;
  8584. }
  8585. }
  8586. }
  8587. intersectInfo._exit(firstLevel);
  8588. return intersectInfo.isIntersected;
  8589. };
  8590. Prim2DBase.prototype.intersectOtherPrim = function (other) {
  8591. var setA = this.triList;
  8592. var setB = other.triList;
  8593. return BABYLON.Tri2DArray.doesIntersect(setA, setB, other.globalTransform.multiply(this.globalTransform.clone().invert()));
  8594. };
  8595. Object.defineProperty(Prim2DBase.prototype, "triList", {
  8596. get: function () {
  8597. if (this._primTriArrayDirty) {
  8598. this.updateTriArray();
  8599. this._primTriArrayDirty = false;
  8600. }
  8601. return this._primTriArray;
  8602. },
  8603. enumerable: true,
  8604. configurable: true
  8605. });
  8606. // 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
  8607. Prim2DBase.prototype.updateTriArray = function () {
  8608. if (this._primTriArray == null) {
  8609. this._primTriArray = new BABYLON.Tri2DArray(2);
  8610. }
  8611. else {
  8612. this._primTriArray.clear(2);
  8613. }
  8614. var size = this.actualSize;
  8615. var lb = new BABYLON.Vector2(0, 0);
  8616. var rt = new BABYLON.Vector2(size.width, size.height);
  8617. var lt = new BABYLON.Vector2(0, size.height);
  8618. var rb = new BABYLON.Vector2(size.width, 0);
  8619. this._primTriArray.storeTriangle(0, lb, lt, rt);
  8620. this._primTriArray.storeTriangle(1, lb, rt, rb);
  8621. };
  8622. /**
  8623. * Move a child object into a new position regarding its siblings to change its rendering order.
  8624. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  8625. * @param child the object to move
  8626. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  8627. */
  8628. Prim2DBase.prototype.moveChild = function (child, previous) {
  8629. if (child.parent !== this) {
  8630. return false;
  8631. }
  8632. var childIndex = this._children.indexOf(child);
  8633. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  8634. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  8635. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  8636. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  8637. }
  8638. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  8639. return true;
  8640. };
  8641. /**
  8642. * Move the given child so it's displayed on the top of all its siblings
  8643. * @param child the primitive to move to the top
  8644. */
  8645. Prim2DBase.prototype.moveChildToTop = function (child) {
  8646. return this.moveChild(child, this._children[this._children.length - 1]);
  8647. };
  8648. /**
  8649. * Move the given child so it's displayed on the bottom of all its siblings
  8650. * @param child the primitive to move to the top
  8651. */
  8652. Prim2DBase.prototype.moveChildToBottom = function (child) {
  8653. return this.moveChild(child, null);
  8654. };
  8655. /**
  8656. * Move this primitive to be at the top among all its sibling
  8657. */
  8658. Prim2DBase.prototype.moveToTop = function () {
  8659. if (this.parent == null) {
  8660. return false;
  8661. }
  8662. return this.parent.moveChildToTop(this);
  8663. };
  8664. /**
  8665. * Move this primitive to be at the bottom among all its sibling
  8666. */
  8667. Prim2DBase.prototype.moveToBottom = function () {
  8668. if (this.parent == null) {
  8669. return false;
  8670. }
  8671. return this.parent.moveChildToBottom(this);
  8672. };
  8673. Prim2DBase.prototype.addChild = function (child) {
  8674. child._parent = this;
  8675. this._boundingBoxDirty();
  8676. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  8677. if (flat) {
  8678. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  8679. child._setZOrder(this._zOrder, true);
  8680. child._zMax = this._zOrder;
  8681. }
  8682. else {
  8683. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  8684. }
  8685. var length = this._children.push(child);
  8686. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  8687. };
  8688. /**
  8689. * Dispose the primitive, remove it from its parent.
  8690. */
  8691. Prim2DBase.prototype.dispose = function () {
  8692. if (!_super.prototype.dispose.call(this)) {
  8693. return false;
  8694. }
  8695. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagCollisionActor)) {
  8696. this.owner._primitiveCollisionManager._removeActor(this);
  8697. this._actorInfo = null;
  8698. }
  8699. if (this._pointerEventObservable) {
  8700. this._pointerEventObservable.clear();
  8701. this._pointerEventObservable = null;
  8702. }
  8703. if (this._actionManager) {
  8704. this._actionManager.dispose();
  8705. this._actionManager = null;
  8706. }
  8707. this.owner.scene.stopAnimation(this);
  8708. // If there's a parent, remove this object from its parent list
  8709. if (this._parent) {
  8710. if (this instanceof BABYLON.Group2D) {
  8711. var g = this;
  8712. if (g.isRenderableGroup) {
  8713. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  8714. if (parentRenderable != null) {
  8715. var l = parentRenderable._renderableData._childrenRenderableGroups;
  8716. var i_1 = l.indexOf(g);
  8717. if (i_1 !== -1) {
  8718. l.splice(i_1, 1);
  8719. }
  8720. }
  8721. }
  8722. }
  8723. var i = this._parent._children.indexOf(this);
  8724. if (i !== undefined) {
  8725. this._parent._children.splice(i, 1);
  8726. }
  8727. this._parent = null;
  8728. }
  8729. // Recurse dispose to children
  8730. if (this._children) {
  8731. while (this._children.length > 0) {
  8732. this._children[this._children.length - 1].dispose();
  8733. }
  8734. }
  8735. return true;
  8736. };
  8737. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  8738. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  8739. this._renderGroup._addPrimToDirtyList(this);
  8740. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  8741. }
  8742. };
  8743. Prim2DBase.prototype._needPrepare = function () {
  8744. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagModelUpdate | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  8745. };
  8746. Prim2DBase.prototype._prepareRender = function (context) {
  8747. this._prepareRenderPre(context);
  8748. this._prepareRenderPost(context);
  8749. };
  8750. Prim2DBase.prototype._prepareRenderPre = function (context) {
  8751. };
  8752. Prim2DBase.prototype._prepareRenderPost = function (context) {
  8753. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  8754. if (this instanceof BABYLON.Group2D) {
  8755. var self = this;
  8756. if (self.isRenderableGroup) {
  8757. return;
  8758. }
  8759. }
  8760. // Check if we need to recurse the prepare to children primitives
  8761. // - must have children
  8762. // - the global transform of this level have changed, or
  8763. // - the visible state of primitive has changed
  8764. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  8765. this.checkPropertiesDirty(Prim2DBase_1.isVisibleProperty.flagId))) {
  8766. this._children.forEach(function (c) {
  8767. // As usual stop the recursion if we meet a renderable group
  8768. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  8769. c._prepareRender(context);
  8770. }
  8771. });
  8772. }
  8773. // Finally reset the dirty flags as we've processed everything
  8774. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  8775. this._instanceDirtyFlags = 0;
  8776. };
  8777. Prim2DBase.prototype._canvasPreInit = function (settings) {
  8778. };
  8779. Prim2DBase.CheckParent = function (parent) {
  8780. //if (!Prim2DBase._isCanvasInit && !parent) {
  8781. // 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)");
  8782. //}
  8783. };
  8784. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  8785. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  8786. var cur = list_1[_i];
  8787. cur.updateCachedStates(recurse);
  8788. }
  8789. };
  8790. Prim2DBase.prototype._parentLayoutDirty = function () {
  8791. if (!this._parent || this._parent.isDisposed) {
  8792. return;
  8793. }
  8794. this._parent._setLayoutDirty();
  8795. };
  8796. Prim2DBase.prototype._setLayoutDirty = function () {
  8797. this.onPrimBecomesDirty();
  8798. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  8799. };
  8800. Prim2DBase.prototype._checkPositionChange = function () {
  8801. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  8802. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  8803. return false;
  8804. }
  8805. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  8806. if (this instanceof BABYLON.Group2D && this.trackedNode == null) {
  8807. console.log("You can't set the position/x/y of " + this.id + " properties while positioning engine is used (margin, margin alignment and/or padding are set");
  8808. return false;
  8809. }
  8810. }
  8811. return true;
  8812. };
  8813. Prim2DBase.prototype._positioningDirty = function () {
  8814. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  8815. return;
  8816. }
  8817. this.onPrimBecomesDirty();
  8818. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  8819. };
  8820. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  8821. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8822. var child = _a[_i];
  8823. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  8824. child._updateRenderMode();
  8825. child.onPrimBecomesDirty();
  8826. child._spreadActualOpacityChanged();
  8827. }
  8828. };
  8829. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  8830. this._layoutEngine = engine;
  8831. };
  8832. Prim2DBase.prototype._updateLocalTransform = function () {
  8833. 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;
  8834. if (this.checkPropertiesDirty(tflags) || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  8835. if (this.owner) {
  8836. this.owner.addupdateLocalTransformCounter(1);
  8837. }
  8838. // Check for positioning update
  8839. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  8840. this._updatePositioning();
  8841. }
  8842. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  8843. var local;
  8844. var pos = this._position ? this.position : (this.layoutAreaPos || Prim2DBase_1._v0);
  8845. var scale = new BABYLON.Vector3(this._scale.x, this._scale.y, 1);
  8846. var postScale = this._postScale;
  8847. var canvasScale = Prim2DBase_1._iv3;
  8848. var hasCanvasScale = false;
  8849. if (this._parent instanceof BABYLON.Canvas2D) {
  8850. hasCanvasScale = true;
  8851. canvasScale = this._parent._canvasLevelScale || Prim2DBase_1._iv3;
  8852. }
  8853. var globalScale = scale.multiplyByFloats(postScale.x * canvasScale.x, postScale.y * canvasScale.y, 1);
  8854. if (this._origin.x === 0 && this._origin.y === 0) {
  8855. // ###MATRIX PART###
  8856. {
  8857. local = BABYLON.Matrix.Compose(globalScale, rot, new BABYLON.Vector3(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0));
  8858. this._localTransform = local;
  8859. this._localLayoutTransform = BABYLON.Matrix.Compose(globalScale, rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  8860. }
  8861. }
  8862. else {
  8863. // ###MATRIX PART###
  8864. {
  8865. // -Origin offset
  8866. var t0 = Prim2DBase_1._t0;
  8867. var t1 = Prim2DBase_1._t1;
  8868. var t2 = Prim2DBase_1._t2;
  8869. var as = Prim2DBase_1._ts0;
  8870. as.copyFrom(this.actualSize);
  8871. as.width /= postScale.x;
  8872. as.height /= postScale.y;
  8873. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, t0);
  8874. // -Origin * rotation
  8875. rot.toRotationMatrix(t1);
  8876. t0.multiplyToRef(t1, t2);
  8877. // -Origin * rotation * scale
  8878. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, t0);
  8879. t2.multiplyToRef(t0, t1);
  8880. // -Origin * rotation * scale * Origin
  8881. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x), (as.height * this._origin.y), 0, t2);
  8882. t1.multiplyToRef(t2, t0);
  8883. // -Origin * rotation * scale * Origin * postScale
  8884. BABYLON.Matrix.ScalingToRef(postScale.x, postScale.y, 1, t1);
  8885. t0.multiplyToRef(t1, t2);
  8886. // -Origin * rotation * scale * Origin * postScale * Position
  8887. BABYLON.Matrix.TranslationToRef(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0, t0);
  8888. t2.multiplyToRef(t0, this._localTransform);
  8889. if (hasCanvasScale) {
  8890. BABYLON.Matrix.ScalingToRef(canvasScale.x, canvasScale.y, canvasScale.z, Prim2DBase_1._t1);
  8891. this._localTransform.multiplyToRef(Prim2DBase_1._t1, this._localTransform);
  8892. }
  8893. this._localLayoutTransform = BABYLON.Matrix.Compose(globalScale, rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  8894. }
  8895. }
  8896. this.clearPropertiesDirty(tflags);
  8897. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  8898. this._clearFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
  8899. return true;
  8900. }
  8901. return false;
  8902. };
  8903. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  8904. if (this.isDisposed) {
  8905. return;
  8906. }
  8907. this.owner.addCachedGroupRenderCounter(1);
  8908. // Check if the parent is synced
  8909. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  8910. this._parent.updateCachedStates(false);
  8911. }
  8912. // Update Z-Order if needed
  8913. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  8914. this._updateZOrder();
  8915. }
  8916. // Update actualSize only if there' not positioning to recompute and the size changed
  8917. // Otherwise positioning will take care of it.
  8918. var sizeDirty = this.checkPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  8919. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  8920. var size = this.size;
  8921. this.onPropertyChanged("actualSize", size, size, Prim2DBase_1.actualSizeProperty.flagId);
  8922. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  8923. }
  8924. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  8925. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  8926. // Check for layout update
  8927. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  8928. this.owner.addUpdateLayoutCounter(1);
  8929. this._layoutEngine.updateLayout(this);
  8930. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  8931. }
  8932. var autoContentChanged = false;
  8933. if (this.isSizeAuto) {
  8934. if (!this._lastAutoSizeArea) {
  8935. autoContentChanged = this.actualSize !== null;
  8936. }
  8937. else {
  8938. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  8939. }
  8940. }
  8941. // Check for positioning update
  8942. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  8943. this._updatePositioning();
  8944. if (sizeDirty) {
  8945. this.clearPropertiesDirty(Prim2DBase_1.sizeProperty.flagId);
  8946. }
  8947. positioningComputed = true;
  8948. }
  8949. if (positioningComputed && this._parent) {
  8950. this._parentContentArea.copyFrom(this._parent.contentArea);
  8951. }
  8952. // Check if we must update this prim
  8953. if ((this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty))) {
  8954. this.owner.addUpdateGlobalTransformCounter(1);
  8955. var curVisibleState = this.isVisible;
  8956. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  8957. // Detect a change of visibility
  8958. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  8959. // Get/compute the localTransform
  8960. var localDirty = this._updateLocalTransform();
  8961. var parentPaddingChanged = false;
  8962. var parentPaddingOffset = Prim2DBase_1._v0;
  8963. if (this._parent) {
  8964. parentPaddingOffset = new BABYLON.Vector2(this._parent._paddingOffset.x, this._parent._paddingOffset.y);
  8965. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  8966. }
  8967. // Check if there are changes in the parent that will force us to update the global matrix
  8968. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  8969. // Check if we have to update the globalTransform
  8970. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  8971. //###MATRIX PART###
  8972. {
  8973. var globalTransform = this._parent ? this._parent._globalTransform : null;
  8974. var localTransform = void 0;
  8975. Prim2DBase_1._transMtx.copyFrom(this._localTransform);
  8976. Prim2DBase_1._transMtx.m[12] += parentPaddingOffset.x;
  8977. Prim2DBase_1._transMtx.m[13] += parentPaddingOffset.y;
  8978. localTransform = Prim2DBase_1._transMtx;
  8979. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  8980. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  8981. }
  8982. this._levelBoundingInfo.dirtyWorldAABB();
  8983. this._boundingInfo.dirtyWorldAABB();
  8984. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  8985. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  8986. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  8987. }
  8988. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  8989. }
  8990. if (recurse) {
  8991. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  8992. var child = _a[_i];
  8993. // Stop the recursion if we meet a renderable group
  8994. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  8995. }
  8996. }
  8997. };
  8998. Prim2DBase.prototype._updatePositioning = function () {
  8999. var _this = this;
  9000. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9001. // Just in case, if may happen and if we don't clear some computation will keep going on forever
  9002. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  9003. return;
  9004. }
  9005. var success = true;
  9006. // Check if re-entrance is occurring
  9007. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagComputingPositioning) /* || (hasMargin && !this._layoutArea)*/) {
  9008. if (!this._actualSize) {
  9009. this._actualSize = this.size.clone() || BABYLON.Size.Zero();
  9010. this._contentArea.copyFrom(this._actualSize);
  9011. }
  9012. if (!this._marginSize) {
  9013. this._marginSize = this._actualSize.clone();
  9014. }
  9015. if (!this._actualPosition) {
  9016. this._actualPosition = BABYLON.Vector2.Zero();
  9017. }
  9018. return;
  9019. }
  9020. if (this.owner) {
  9021. this.owner.addUpdatePositioningCounter(1);
  9022. }
  9023. // Set the flag to avoid re-entrance
  9024. this._setFlags(BABYLON.SmartPropertyPrim.flagComputingPositioning);
  9025. try {
  9026. var isSizeAuto = this.isSizeAuto;
  9027. var isVSizeAuto = this.isVerticalSizeAuto;
  9028. var isHSizeAuto = this.isHorizontalSizeAuto;
  9029. var ma = this._marginAlignment ? this._marginAlignment.clone() : new PrimitiveAlignment();
  9030. var csize = this.size;
  9031. // 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
  9032. if (!this._hasMarginAlignment && (!isSizeAuto && (csize.width == null || csize.height == null))) {
  9033. if (isSizeAuto || this.actualSize.width == null) {
  9034. ma.horizontal = PrimitiveAlignment.AlignStretch;
  9035. }
  9036. if (isSizeAuto || this.actualSize.height == null) {
  9037. ma.vertical = PrimitiveAlignment.AlignStretch;
  9038. }
  9039. }
  9040. var hasMargin = (this._margin !== null && !this._margin.isDefault) || (ma !== null && !ma.isDefault);
  9041. var newSize = Prim2DBase_1._size;
  9042. var hasH = false;
  9043. var hasV = false;
  9044. var size = this.size || Prim2DBase_1._nullSize;
  9045. var paddingApplied_1 = false;
  9046. var hasPadding = this._hasPadding;
  9047. var autoSizeComputed_1 = false;
  9048. //let contentAreaComputed = false;
  9049. // Compute the size
  9050. // The size is the size of the prim or the computed one if there's a marginAlignment of Stretch
  9051. if (hasMargin) {
  9052. var layoutArea = this.layoutArea;
  9053. if (layoutArea /*&& layoutArea.width >= size.width */ && ma.horizontal === PrimitiveAlignment.AlignStretch) {
  9054. this.margin.computeWithAlignment(layoutArea, size, ma, this.actualScale, this._marginOffset, newSize, false, PrimitiveThickness.ComputeH);
  9055. hasH = true;
  9056. }
  9057. if (layoutArea /*&& layoutArea.height >= size.height */ && ma.vertical === PrimitiveAlignment.AlignStretch) {
  9058. this.margin.computeWithAlignment(layoutArea, size, ma, this.actualScale, this._marginOffset, newSize, false, PrimitiveThickness.ComputeV);
  9059. hasV = true;
  9060. }
  9061. }
  9062. var computeAutoSize = function () {
  9063. if (autoSizeComputed_1) {
  9064. return;
  9065. }
  9066. var bi = _this.layoutBoundingInfo;
  9067. bi.sizeToRef(Prim2DBase_1._size2);
  9068. autoSizeComputed_1 = true;
  9069. paddingApplied_1 = true;
  9070. };
  9071. if (!hasH) {
  9072. // If the Horizontal size is Auto, we have to compute it from its content and padding
  9073. if (isHSizeAuto) {
  9074. computeAutoSize();
  9075. newSize.width = Prim2DBase_1._size2.width;
  9076. }
  9077. else {
  9078. newSize.width = size.width;
  9079. }
  9080. }
  9081. if (!hasV) {
  9082. // If the Vertical size is Auto, we have to compute it from its content and padding
  9083. if (isVSizeAuto) {
  9084. computeAutoSize();
  9085. newSize.height = Prim2DBase_1._size2.height;
  9086. }
  9087. else {
  9088. newSize.height = size.height;
  9089. }
  9090. }
  9091. if (!isVSizeAuto || !isHSizeAuto) {
  9092. Prim2DBase_1._curContentArea.copyFrom(this._contentArea);
  9093. if (hasPadding) {
  9094. this._getInitialContentAreaToRef(newSize, Prim2DBase_1._icZone, Prim2DBase_1._icArea);
  9095. Prim2DBase_1._icArea.width = Math.max(0, Prim2DBase_1._icArea.width);
  9096. Prim2DBase_1._icArea.height = Math.max(0, Prim2DBase_1._icArea.height);
  9097. this.padding.compute(Prim2DBase_1._icArea, this.actualScale, this._paddingOffset, Prim2DBase_1._size2);
  9098. if (!isHSizeAuto) {
  9099. this._paddingOffset.x += Prim2DBase_1._icZone.x;
  9100. this._paddingOffset.z -= Prim2DBase_1._icZone.z;
  9101. this._contentArea.width = Prim2DBase_1._size2.width;
  9102. }
  9103. if (!isVSizeAuto) {
  9104. this._paddingOffset.y += Prim2DBase_1._icZone.y;
  9105. this._paddingOffset.w -= Prim2DBase_1._icZone.w;
  9106. this._contentArea.height = Prim2DBase_1._size2.height;
  9107. }
  9108. }
  9109. else {
  9110. this._contentArea.copyFrom(newSize);
  9111. }
  9112. if (!Prim2DBase_1._curContentArea.equals(this._contentArea)) {
  9113. this._setLayoutDirty();
  9114. }
  9115. paddingApplied_1 = true;
  9116. }
  9117. // Finally we apply margin to determine the position
  9118. if (hasMargin) {
  9119. var layoutArea = this.layoutArea;
  9120. var mo = this._marginOffset;
  9121. var margin = this.margin;
  9122. // We compute margin only if the layoutArea is as big as the contentSize, sometime this code is triggered when the layoutArea is
  9123. // not yet set and computing alignment would result into a bad size.
  9124. // So we make sure with compute alignment only if the layoutArea is good
  9125. if (layoutArea && layoutArea.width >= newSize.width && layoutArea.height >= newSize.height) {
  9126. margin.computeWithAlignment(layoutArea, newSize, ma, new BABYLON.Vector2(1, 1) /*this.actualScale*/, mo, Prim2DBase_1._size2);
  9127. }
  9128. else {
  9129. mo.copyFromFloats(0, 0, 0, 0);
  9130. }
  9131. var mw = newSize.width + margin.leftPixels + margin.rightPixels;
  9132. var mh = newSize.height + margin.bottomPixels + margin.topPixels;
  9133. if (!this._marginSize) {
  9134. this._marginSize = new BABYLON.Size(mw, mh);
  9135. }
  9136. else {
  9137. this._marginSize.copyFromFloats(mw, mh);
  9138. }
  9139. }
  9140. else {
  9141. if (!this._marginSize) {
  9142. this._marginSize = newSize.clone();
  9143. }
  9144. else {
  9145. this._marginSize.copyFrom(newSize);
  9146. }
  9147. }
  9148. var lap = this.layoutAreaPos;
  9149. this.actualPosition = new BABYLON.Vector2(this._marginOffset.x + (lap ? lap.x : 0), this._marginOffset.y + (lap ? lap.y : 0));
  9150. this.actualSize = Prim2DBase_1._size.clone();
  9151. this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty);
  9152. if (isSizeAuto) {
  9153. this._lastAutoSizeArea = this.actualSize;
  9154. }
  9155. if (this.displayDebugAreas) {
  9156. this._updateDebugArea();
  9157. }
  9158. }
  9159. finally {
  9160. this._clearFlags(BABYLON.SmartPropertyPrim.flagComputingPositioning);
  9161. // Remove dirty flag
  9162. if (success) {
  9163. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  9164. }
  9165. }
  9166. };
  9167. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  9168. /**
  9169. * Get the content are of this primitive, this area is computed the primitive size and using the padding property.
  9170. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  9171. */
  9172. get: function () {
  9173. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9174. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  9175. this._updatePositioning();
  9176. }
  9177. return this._contentArea;
  9178. }
  9179. else {
  9180. return this.size;
  9181. }
  9182. },
  9183. enumerable: true,
  9184. configurable: true
  9185. });
  9186. Object.defineProperty(Prim2DBase.prototype, "marginSize", {
  9187. get: function () {
  9188. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagUsePositioning)) {
  9189. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  9190. this._updatePositioning();
  9191. }
  9192. return this._marginSize;
  9193. }
  9194. else {
  9195. return this.size;
  9196. }
  9197. },
  9198. enumerable: true,
  9199. configurable: true
  9200. });
  9201. Prim2DBase.prototype._patchHierarchy = function (owner) {
  9202. if (this._owner == null) {
  9203. this._owner = owner;
  9204. this.onSetOwner();
  9205. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  9206. }
  9207. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  9208. if (this._renderGroup != null) {
  9209. return;
  9210. }
  9211. if (this instanceof BABYLON.Group2D) {
  9212. var group = this;
  9213. group.detectGroupStates();
  9214. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  9215. group.owner._registerTrackedNode(this);
  9216. }
  9217. }
  9218. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  9219. if (this._parent) {
  9220. this._parentLayoutDirty();
  9221. }
  9222. // Make sure the prim is in the dirtyList if it should be
  9223. if (this._renderGroup && this.isDirty) {
  9224. var list = this._renderGroup._renderableData._primDirtyList;
  9225. var i = list.indexOf(this);
  9226. if (i === -1) {
  9227. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  9228. list.push(this);
  9229. }
  9230. }
  9231. // Recurse
  9232. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9233. var child = _a[_i];
  9234. child._hierarchyDepth = this._hierarchyDepth + 1;
  9235. child._patchHierarchy(owner);
  9236. }
  9237. };
  9238. Prim2DBase.prototype.onSetOwner = function () {
  9239. };
  9240. Prim2DBase.prototype._updateZOrder = function () {
  9241. var prevLinPos = this._primLinearPosition;
  9242. var startI = 0;
  9243. var startZ = this._zOrder;
  9244. // 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
  9245. var childrenCount = this._children.length;
  9246. if (this._firstZDirtyIndex > 0) {
  9247. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  9248. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  9249. prevLinPos = prevPrim._primLinearPosition;
  9250. startI = this._firstZDirtyIndex - 1;
  9251. startZ = prevPrim._zOrder;
  9252. }
  9253. }
  9254. var startPos = prevLinPos;
  9255. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  9256. Prim2DBase_1._totalCount = 0;
  9257. for (var i = startI; i < childrenCount; i++) {
  9258. var child = this._children[i];
  9259. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  9260. }
  9261. // Compute the new Z-Order for all the primitives
  9262. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  9263. var zDelta = (this._zMax - startZ) / (Prim2DBase_1._totalCount * (Prim2DBase_1._zRebuildReentrency ? 1 : 1.2));
  9264. // 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.
  9265. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  9266. // 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...
  9267. if (Prim2DBase_1._zRebuildReentrency) {
  9268. var p = this._parent;
  9269. if (p == null) {
  9270. // 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...)
  9271. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  9272. Prim2DBase_1._zRebuildReentrency = false;
  9273. return;
  9274. }
  9275. p._firstZDirtyIndex = 0;
  9276. return p._updateZOrder();
  9277. }
  9278. Prim2DBase_1._zRebuildReentrency = true;
  9279. this._firstZDirtyIndex = 0;
  9280. this._updateZOrder();
  9281. Prim2DBase_1._zRebuildReentrency = false;
  9282. }
  9283. for (var i = startI; i < childrenCount; i++) {
  9284. var child = this._children[i];
  9285. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  9286. }
  9287. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  9288. for (var _i = 0, _a = Prim2DBase_1._zOrderChangedNotifList; _i < _a.length; _i++) {
  9289. var p = _a[_i];
  9290. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  9291. }
  9292. Prim2DBase_1._zOrderChangedNotifList.splice(0);
  9293. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  9294. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9295. };
  9296. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  9297. if (this.isManualZOrder) {
  9298. return prevLinPos;
  9299. }
  9300. this._primLinearPosition = ++prevLinPos;
  9301. Prim2DBase_1._totalCount++;
  9302. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  9303. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  9304. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9305. var child = _a[_i];
  9306. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  9307. }
  9308. }
  9309. return prevLinPos;
  9310. };
  9311. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  9312. if (this.isManualZOrder) {
  9313. return null;
  9314. }
  9315. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  9316. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  9317. this._setZOrder(newZ, false);
  9318. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  9319. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  9320. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9321. }
  9322. var curZ = newZ;
  9323. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  9324. if (isFlat) {
  9325. if (this._children.length > 0) {
  9326. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  9327. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9328. var child = _a[_i];
  9329. child._updatePrimitiveFlatZOrder(this._zOrder);
  9330. }
  9331. }
  9332. }
  9333. else {
  9334. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  9335. var child = _c[_b];
  9336. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  9337. if (r != null) {
  9338. curZ = r;
  9339. }
  9340. }
  9341. }
  9342. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  9343. return curZ;
  9344. };
  9345. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  9346. if (this.isManualZOrder) {
  9347. return;
  9348. }
  9349. this._setZOrder(newZ, false);
  9350. this._zMax = newZ;
  9351. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  9352. this._firstZDirtyIndex = Prim2DBase_1._bigInt;
  9353. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  9354. }
  9355. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9356. var child = _a[_i];
  9357. child._updatePrimitiveFlatZOrder(newZ);
  9358. }
  9359. };
  9360. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  9361. if (newZ !== this._zOrder) {
  9362. this._zOrder = newZ;
  9363. this.onPrimBecomesDirty();
  9364. this.onZOrderChanged();
  9365. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  9366. if (directEmit) {
  9367. this._actualZOrderChangedObservable.notifyObservers(newZ);
  9368. }
  9369. else {
  9370. Prim2DBase_1._zOrderChangedNotifList.push(this);
  9371. }
  9372. }
  9373. }
  9374. };
  9375. Prim2DBase.prototype._updateRenderMode = function () {
  9376. };
  9377. /**
  9378. * This method is used to alter the contentArea of the Primitive before margin is applied.
  9379. * 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.
  9380. * @param primSize the current size of the primitive
  9381. * @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
  9382. * @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!
  9383. */
  9384. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  9385. initialContentArea.copyFrom(primSize);
  9386. initialContentPosition.x = initialContentPosition.y = initialContentPosition.z = initialContentPosition.w = 0;
  9387. };
  9388. /**
  9389. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  9390. * Check the Rectangle2D implementation for a concrete application.
  9391. * @param primSize the current size of the primitive
  9392. * @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!
  9393. */
  9394. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, paddingOffset, newPrimSize) {
  9395. newPrimSize.copyFrom(primSize);
  9396. };
  9397. Object.defineProperty(Prim2DBase.prototype, "layoutData", {
  9398. /**
  9399. * Get/set the layout data to use for this primitive.
  9400. */
  9401. get: function () {
  9402. return this._layoutData;
  9403. },
  9404. set: function (value) {
  9405. if (this._layoutData === value) {
  9406. return;
  9407. }
  9408. this._layoutData = value;
  9409. },
  9410. enumerable: true,
  9411. configurable: true
  9412. });
  9413. return Prim2DBase;
  9414. }(BABYLON.SmartPropertyPrim));
  9415. Prim2DBase.PRIM2DBASE_PROPCOUNT = 25;
  9416. Prim2DBase._bigInt = Math.pow(2, 30);
  9417. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  9418. Prim2DBase._nullSize = BABYLON.Size.Zero();
  9419. Prim2DBase.boundinbBoxReentrency = -1;
  9420. Prim2DBase.nullSize = BABYLON.Size.Zero();
  9421. Prim2DBase._bMinMax = BABYLON.Vector4.Zero();
  9422. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  9423. Prim2DBase._bSize = BABYLON.Size.Zero();
  9424. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  9425. Prim2DBase._tpsBB2 = new BABYLON.BoundingInfo2D();
  9426. Prim2DBase._updatingDebugArea = false;
  9427. Prim2DBase._bypassGroup2DExclusion = false;
  9428. Prim2DBase._isCanvasInit = false;
  9429. Prim2DBase._t0 = new BABYLON.Matrix();
  9430. Prim2DBase._t1 = new BABYLON.Matrix();
  9431. Prim2DBase._t2 = new BABYLON.Matrix();
  9432. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  9433. Prim2DBase._v30 = BABYLON.Vector3.Zero(); // Must stay with the value 0,0,0
  9434. Prim2DBase._iv3 = new BABYLON.Vector3(1, 1, 1); // Must stay identity vector
  9435. Prim2DBase._ts0 = BABYLON.Size.Zero();
  9436. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  9437. Prim2DBase._transTT = BABYLON.Transform2D.Zero();
  9438. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  9439. Prim2DBase._icZone = BABYLON.Vector4.Zero();
  9440. Prim2DBase._icArea = BABYLON.Size.Zero();
  9441. Prim2DBase._size = BABYLON.Size.Zero();
  9442. Prim2DBase._size2 = BABYLON.Size.Zero();
  9443. Prim2DBase._curContentArea = BABYLON.Size.Zero();
  9444. Prim2DBase._zOrderChangedNotifList = new Array();
  9445. Prim2DBase._zRebuildReentrency = false;
  9446. Prim2DBase._totalCount = 0;
  9447. __decorate([
  9448. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase_1.actualPositionProperty = pi; }, false, false, true)
  9449. ], Prim2DBase.prototype, "actualPosition", null);
  9450. __decorate([
  9451. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 1, function (pi) { return Prim2DBase_1.actualXProperty = pi; }, false, false, true)
  9452. ], Prim2DBase.prototype, "actualX", null);
  9453. __decorate([
  9454. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 2, function (pi) { return Prim2DBase_1.actualYProperty = pi; }, false, false, true)
  9455. ], Prim2DBase.prototype, "actualY", null);
  9456. __decorate([
  9457. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 3, function (pi) { return Prim2DBase_1.positionProperty = pi; }, false, false, true)
  9458. ], Prim2DBase.prototype, "position", null);
  9459. __decorate([
  9460. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 4, function (pi) { return Prim2DBase_1.xProperty = pi; }, false, false, true)
  9461. ], Prim2DBase.prototype, "x", null);
  9462. __decorate([
  9463. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 5, function (pi) { return Prim2DBase_1.yProperty = pi; }, false, false, true)
  9464. ], Prim2DBase.prototype, "y", null);
  9465. __decorate([
  9466. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 6, function (pi) { return Prim2DBase_1.sizeProperty = pi; }, false, true)
  9467. ], Prim2DBase.prototype, "size", null);
  9468. __decorate([
  9469. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 7, function (pi) { return Prim2DBase_1.widthProperty = pi; }, false, true)
  9470. ], Prim2DBase.prototype, "width", null);
  9471. __decorate([
  9472. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 8, function (pi) { return Prim2DBase_1.heightProperty = pi; }, false, true)
  9473. ], Prim2DBase.prototype, "height", null);
  9474. __decorate([
  9475. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 9, function (pi) { return Prim2DBase_1.rotationProperty = pi; }, false, true)
  9476. ], Prim2DBase.prototype, "rotation", null);
  9477. __decorate([
  9478. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 10, function (pi) { return Prim2DBase_1.scaleProperty = pi; }, false, true)
  9479. ], Prim2DBase.prototype, "scale", null);
  9480. __decorate([
  9481. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 11, function (pi) { return Prim2DBase_1.actualSizeProperty = pi; }, false, true)
  9482. ], Prim2DBase.prototype, "actualSize", null);
  9483. __decorate([
  9484. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 12, function (pi) { return Prim2DBase_1.actualWidthProperty = pi; }, false, true)
  9485. ], Prim2DBase.prototype, "actualWidth", null);
  9486. __decorate([
  9487. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 13, function (pi) { return Prim2DBase_1.actualHeightProperty = pi; }, false, true)
  9488. ], Prim2DBase.prototype, "actualHeight", null);
  9489. __decorate([
  9490. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 14, function (pi) { return Prim2DBase_1.originProperty = pi; }, false, true)
  9491. ], Prim2DBase.prototype, "origin", null);
  9492. __decorate([
  9493. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 15, function (pi) { return Prim2DBase_1.levelVisibleProperty = pi; })
  9494. ], Prim2DBase.prototype, "levelVisible", null);
  9495. __decorate([
  9496. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 16, function (pi) { return Prim2DBase_1.isVisibleProperty = pi; })
  9497. ], Prim2DBase.prototype, "isVisible", null);
  9498. __decorate([
  9499. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 17, function (pi) { return Prim2DBase_1.zOrderProperty = pi; })
  9500. ], Prim2DBase.prototype, "zOrder", null);
  9501. __decorate([
  9502. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 18, function (pi) { return Prim2DBase_1.marginProperty = pi; })
  9503. ], Prim2DBase.prototype, "margin", null);
  9504. __decorate([
  9505. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 19, function (pi) { return Prim2DBase_1.paddingProperty = pi; })
  9506. ], Prim2DBase.prototype, "padding", null);
  9507. __decorate([
  9508. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 20, function (pi) { return Prim2DBase_1.marginAlignmentProperty = pi; })
  9509. ], Prim2DBase.prototype, "marginAlignment", null);
  9510. __decorate([
  9511. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 21, function (pi) { return Prim2DBase_1.opacityProperty = pi; })
  9512. ], Prim2DBase.prototype, "opacity", null);
  9513. __decorate([
  9514. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 22, function (pi) { return Prim2DBase_1.scaleXProperty = pi; }, false, true)
  9515. ], Prim2DBase.prototype, "scaleX", null);
  9516. __decorate([
  9517. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 23, function (pi) { return Prim2DBase_1.scaleYProperty = pi; }, false, true)
  9518. ], Prim2DBase.prototype, "scaleY", null);
  9519. __decorate([
  9520. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 24, function (pi) { return Prim2DBase_1.actualScaleProperty = pi; }, false, true)
  9521. ], Prim2DBase.prototype, "actualScale", null);
  9522. Prim2DBase = Prim2DBase_1 = __decorate([
  9523. BABYLON.className("Prim2DBase", "BABYLON")
  9524. ], Prim2DBase);
  9525. BABYLON.Prim2DBase = Prim2DBase;
  9526. var PrimitiveAlignment_1, PrimitiveThickness_1, Prim2DBase_1;
  9527. })(BABYLON || (BABYLON = {}));
  9528. //# sourceMappingURL=babylon.prim2dBase.js.map
  9529. var __extends = (this && this.__extends) || function (d, b) {
  9530. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9531. function __() { this.constructor = d; }
  9532. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9533. };
  9534. var BABYLON;
  9535. (function (BABYLON) {
  9536. var GroupInstanceInfo = (function () {
  9537. function GroupInstanceInfo(owner, mrc, partCount) {
  9538. this._partCount = partCount;
  9539. this.owner = owner;
  9540. this.modelRenderCache = mrc;
  9541. this.modelRenderCache.addRef();
  9542. this.partIndexFromId = new BABYLON.StringDictionary();
  9543. this._usedShaderCategories = new Array(partCount);
  9544. this._strides = new Array(partCount);
  9545. this._opaqueData = null;
  9546. this._alphaTestData = null;
  9547. this._transparentData = null;
  9548. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  9549. }
  9550. GroupInstanceInfo.prototype.dispose = function () {
  9551. if (this._isDisposed) {
  9552. return false;
  9553. }
  9554. if (this.modelRenderCache) {
  9555. this.modelRenderCache.dispose();
  9556. this.modelRenderCache = null;
  9557. }
  9558. var engine = this.owner.owner.engine;
  9559. if (this._opaqueData) {
  9560. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  9561. this._opaqueData = null;
  9562. }
  9563. if (this._alphaTestData) {
  9564. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  9565. this._alphaTestData = null;
  9566. }
  9567. if (this._transparentData) {
  9568. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  9569. this._transparentData = null;
  9570. }
  9571. this.partIndexFromId = null;
  9572. this._isDisposed = true;
  9573. return true;
  9574. };
  9575. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  9576. get: function () {
  9577. return this._opaqueData != null;
  9578. },
  9579. enumerable: true,
  9580. configurable: true
  9581. });
  9582. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  9583. get: function () {
  9584. return this._alphaTestData != null;
  9585. },
  9586. enumerable: true,
  9587. configurable: true
  9588. });
  9589. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  9590. get: function () {
  9591. return this._transparentData != null;
  9592. },
  9593. enumerable: true,
  9594. configurable: true
  9595. });
  9596. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  9597. get: function () {
  9598. if (!this._opaqueData) {
  9599. this._opaqueData = new Array(this._partCount);
  9600. for (var i = 0; i < this._partCount; i++) {
  9601. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  9602. }
  9603. }
  9604. return this._opaqueData;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  9610. get: function () {
  9611. if (!this._alphaTestData) {
  9612. this._alphaTestData = new Array(this._partCount);
  9613. for (var i = 0; i < this._partCount; i++) {
  9614. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  9615. }
  9616. }
  9617. return this._alphaTestData;
  9618. },
  9619. enumerable: true,
  9620. configurable: true
  9621. });
  9622. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  9623. get: function () {
  9624. if (!this._transparentData) {
  9625. this._transparentData = new Array(this._partCount);
  9626. for (var i = 0; i < this._partCount; i++) {
  9627. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  9628. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  9629. }
  9630. }
  9631. return this._transparentData;
  9632. },
  9633. enumerable: true,
  9634. configurable: true
  9635. });
  9636. GroupInstanceInfo.prototype.sortTransparentData = function () {
  9637. if (!this.transparentOrderDirty) {
  9638. return;
  9639. }
  9640. for (var i = 0; i < this._transparentData.length; i++) {
  9641. var td = this._transparentData[i];
  9642. td._partData.sort();
  9643. }
  9644. this.transparentOrderDirty = false;
  9645. };
  9646. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  9647. get: function () {
  9648. return this._usedShaderCategories;
  9649. },
  9650. enumerable: true,
  9651. configurable: true
  9652. });
  9653. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  9654. get: function () {
  9655. return this._strides;
  9656. },
  9657. enumerable: true,
  9658. configurable: true
  9659. });
  9660. return GroupInstanceInfo;
  9661. }());
  9662. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  9663. var TransparentSegment = (function () {
  9664. function TransparentSegment() {
  9665. this.groupInsanceInfo = null;
  9666. this.startZ = 0;
  9667. this.endZ = 0;
  9668. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  9669. this.endDataIndex = 0;
  9670. this.partBuffers = null;
  9671. }
  9672. TransparentSegment.prototype.dispose = function (engine) {
  9673. if (this.partBuffers) {
  9674. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  9675. this.partBuffers.splice(0);
  9676. this.partBuffers = null;
  9677. }
  9678. };
  9679. return TransparentSegment;
  9680. }());
  9681. BABYLON.TransparentSegment = TransparentSegment;
  9682. var GroupInfoPartData = (function () {
  9683. function GroupInfoPartData(stride) {
  9684. this._partData = null;
  9685. this._partBuffer = null;
  9686. this._partBufferSize = 0;
  9687. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  9688. this._isDisposed = false;
  9689. }
  9690. GroupInfoPartData.prototype.dispose = function (engine) {
  9691. if (this._isDisposed) {
  9692. return false;
  9693. }
  9694. if (this._partBuffer) {
  9695. engine._releaseBuffer(this._partBuffer);
  9696. this._partBuffer = null;
  9697. }
  9698. this._partData = null;
  9699. this._isDisposed = true;
  9700. };
  9701. return GroupInfoPartData;
  9702. }());
  9703. BABYLON.GroupInfoPartData = GroupInfoPartData;
  9704. var TransparentGroupInfoPartData = (function (_super) {
  9705. __extends(TransparentGroupInfoPartData, _super);
  9706. function TransparentGroupInfoPartData(stride, zoff) {
  9707. var _this = _super.call(this, stride) || this;
  9708. _this._partData.compareValueOffset = zoff;
  9709. _this._partData.sortingAscending = false;
  9710. return _this;
  9711. }
  9712. return TransparentGroupInfoPartData;
  9713. }(GroupInfoPartData));
  9714. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  9715. var ModelRenderCache = (function () {
  9716. function ModelRenderCache(engine, modelKey) {
  9717. this._engine = engine;
  9718. this._modelKey = modelKey;
  9719. this._nextKey = 1;
  9720. this._refCounter = 1;
  9721. this._partData = null;
  9722. }
  9723. ModelRenderCache.prototype.dispose = function () {
  9724. if (--this._refCounter !== 0) {
  9725. return false;
  9726. }
  9727. // Remove the Model Render Cache from the global dictionary
  9728. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  9729. if (edata) {
  9730. edata.DisposeModelRenderCache(this);
  9731. }
  9732. return true;
  9733. };
  9734. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  9735. get: function () {
  9736. return this._refCounter <= 0;
  9737. },
  9738. enumerable: true,
  9739. configurable: true
  9740. });
  9741. ModelRenderCache.prototype.addRef = function () {
  9742. return ++this._refCounter;
  9743. };
  9744. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  9745. get: function () {
  9746. return this._modelKey;
  9747. },
  9748. enumerable: true,
  9749. configurable: true
  9750. });
  9751. ModelRenderCache.prototype.updateModelRenderCache = function (prim) {
  9752. return false;
  9753. };
  9754. /**
  9755. * Render the model instances
  9756. * @param instanceInfo
  9757. * @param context
  9758. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  9759. */
  9760. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  9761. return true;
  9762. };
  9763. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  9764. for (var i = 0; i < this._partData.length; i++) {
  9765. if (this._partData[i]._partId === partId) {
  9766. return i;
  9767. }
  9768. }
  9769. return null;
  9770. };
  9771. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  9772. var i = this.getPartIndexFromId(partId);
  9773. if (i === null) {
  9774. return null;
  9775. }
  9776. var ci = this._partsClassInfo[i];
  9777. var categories = this._partData[i]._partUsedCategories;
  9778. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  9779. return res;
  9780. };
  9781. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  9782. var pd = this._partData[partIndex];
  9783. var offset = (pd._partDataStride / 4) * elementCount;
  9784. var pci = this._partsClassInfo[partIndex];
  9785. var self = this;
  9786. pci.fullContent.forEach(function (k, v) {
  9787. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  9788. switch (v.dataType) {
  9789. case 4 /* float */:
  9790. {
  9791. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  9792. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  9793. break;
  9794. }
  9795. case 0 /* Vector2 */:
  9796. {
  9797. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  9798. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  9799. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  9800. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  9801. break;
  9802. }
  9803. case 5 /* Color3 */:
  9804. case 1 /* Vector3 */:
  9805. {
  9806. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  9807. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  9808. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  9809. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  9810. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  9811. break;
  9812. }
  9813. case 6 /* Color4 */:
  9814. case 2 /* Vector4 */:
  9815. {
  9816. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  9817. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  9818. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  9819. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  9820. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  9821. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  9822. break;
  9823. }
  9824. default:
  9825. }
  9826. }
  9827. });
  9828. };
  9829. return ModelRenderCache;
  9830. }());
  9831. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  9832. // let i = this.getPartIndexFromId(partId);
  9833. // if (i === null) {
  9834. // return null;
  9835. // }
  9836. // let pci = this._partsClassInfo[i];
  9837. // pci.fullContent.forEach((k, v) => {
  9838. // if (uniforms.indexOf(v.attributeName) !== -1) {
  9839. // v.uniformLocation = effect.getUniform(v.attributeName);
  9840. // }
  9841. // });
  9842. //}
  9843. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  9844. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  9845. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  9846. BABYLON.ModelRenderCache = ModelRenderCache;
  9847. var ModelRenderCachePartData = (function () {
  9848. function ModelRenderCachePartData() {
  9849. }
  9850. return ModelRenderCachePartData;
  9851. }());
  9852. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  9853. })(BABYLON || (BABYLON = {}));
  9854. //# sourceMappingURL=babylon.modelRenderCache.js.map
  9855. var __extends = (this && this.__extends) || function (d, b) {
  9856. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9857. function __() { this.constructor = d; }
  9858. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9859. };
  9860. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  9861. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  9862. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  9863. 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;
  9864. return c > 3 && r && Object.defineProperty(target, key, r), r;
  9865. };
  9866. var BABYLON;
  9867. (function (BABYLON) {
  9868. var InstanceClassInfo = (function () {
  9869. function InstanceClassInfo(base) {
  9870. this._baseInfo = base;
  9871. this._nextOffset = new BABYLON.StringDictionary();
  9872. this._attributes = new Array();
  9873. }
  9874. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  9875. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  9876. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  9877. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  9878. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  9879. if (push) {
  9880. this._attributes.push(propInfo);
  9881. }
  9882. };
  9883. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  9884. var catInline = ";" + categories.join(";") + ";";
  9885. var res = new Array();
  9886. var curInfo = this;
  9887. while (curInfo) {
  9888. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  9889. var attrib = _a[_i];
  9890. // 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
  9891. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  9892. var index = effect.getAttributeLocationByName(attrib.attributeName);
  9893. if (index === -1) {
  9894. throw new Error("Attribute " + attrib.attributeName + " was not found in Effect: " + effect.name + ". It's certainly no longer used in the Effect's Shaders");
  9895. }
  9896. var iai = new BABYLON.InstancingAttributeInfo();
  9897. iai.index = index;
  9898. 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)
  9899. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  9900. iai.attributeName = attrib.attributeName;
  9901. res.push(iai);
  9902. }
  9903. }
  9904. curInfo = curInfo._baseInfo;
  9905. }
  9906. return res;
  9907. };
  9908. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  9909. var res = new Array();
  9910. var curInfo = this;
  9911. while (curInfo) {
  9912. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  9913. var attrib = _a[_i];
  9914. // 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
  9915. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  9916. res.push(attrib.attributeName);
  9917. }
  9918. }
  9919. curInfo = curInfo._baseInfo;
  9920. }
  9921. return res;
  9922. };
  9923. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  9924. var curOffset = 0;
  9925. var curBase = this._baseInfo;
  9926. while (curBase) {
  9927. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  9928. curBase = curBase._baseInfo;
  9929. }
  9930. return curOffset;
  9931. };
  9932. return InstanceClassInfo;
  9933. }());
  9934. BABYLON.InstanceClassInfo = InstanceClassInfo;
  9935. var InstancePropInfo = (function () {
  9936. function InstancePropInfo() {
  9937. this.instanceOffset = new BABYLON.StringDictionary();
  9938. }
  9939. InstancePropInfo.prototype.setSize = function (val) {
  9940. if (val instanceof BABYLON.Vector2) {
  9941. this.size = 8;
  9942. this.dataType = 0 /* Vector2 */;
  9943. return;
  9944. }
  9945. if (val instanceof BABYLON.Vector3) {
  9946. this.size = 12;
  9947. this.dataType = 1 /* Vector3 */;
  9948. return;
  9949. }
  9950. if (val instanceof BABYLON.Vector4) {
  9951. this.size = 16;
  9952. this.dataType = 2 /* Vector4 */;
  9953. return;
  9954. }
  9955. if (val instanceof BABYLON.Matrix) {
  9956. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  9957. }
  9958. if (typeof (val) === "number") {
  9959. this.size = 4;
  9960. this.dataType = 4 /* float */;
  9961. return;
  9962. }
  9963. if (val instanceof BABYLON.Color3) {
  9964. this.size = 12;
  9965. this.dataType = 5 /* Color3 */;
  9966. return;
  9967. }
  9968. if (val instanceof BABYLON.Color4) {
  9969. this.size = 16;
  9970. this.dataType = 6 /* Color4 */;
  9971. return;
  9972. }
  9973. if (val instanceof BABYLON.Size) {
  9974. this.size = 8;
  9975. this.dataType = 7 /* Size */;
  9976. return;
  9977. }
  9978. return;
  9979. };
  9980. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  9981. switch (this.dataType) {
  9982. case 0 /* Vector2 */:
  9983. {
  9984. var v = val;
  9985. array[offset + 0] = v.x;
  9986. array[offset + 1] = v.y;
  9987. break;
  9988. }
  9989. case 1 /* Vector3 */:
  9990. {
  9991. var v = val;
  9992. array[offset + 0] = v.x;
  9993. array[offset + 1] = v.y;
  9994. array[offset + 2] = v.z;
  9995. break;
  9996. }
  9997. case 2 /* Vector4 */:
  9998. {
  9999. var v = val;
  10000. array[offset + 0] = v.x;
  10001. array[offset + 1] = v.y;
  10002. array[offset + 2] = v.z;
  10003. array[offset + 3] = v.w;
  10004. break;
  10005. }
  10006. case 5 /* Color3 */:
  10007. {
  10008. var v = val;
  10009. array[offset + 0] = v.r;
  10010. array[offset + 1] = v.g;
  10011. array[offset + 2] = v.b;
  10012. break;
  10013. }
  10014. case 6 /* Color4 */:
  10015. {
  10016. var v = val;
  10017. array[offset + 0] = v.r;
  10018. array[offset + 1] = v.g;
  10019. array[offset + 2] = v.b;
  10020. array[offset + 3] = v.a;
  10021. break;
  10022. }
  10023. case 4 /* float */:
  10024. {
  10025. var v = val;
  10026. array[offset] = v;
  10027. break;
  10028. }
  10029. case 3 /* Matrix */:
  10030. {
  10031. var v = val;
  10032. for (var i = 0; i < 16; i++) {
  10033. array[offset + i] = v.m[i];
  10034. }
  10035. break;
  10036. }
  10037. case 7 /* Size */:
  10038. {
  10039. var s = val;
  10040. array[offset + 0] = s.width;
  10041. array[offset + 1] = s.height;
  10042. break;
  10043. }
  10044. }
  10045. };
  10046. return InstancePropInfo;
  10047. }());
  10048. BABYLON.InstancePropInfo = InstancePropInfo;
  10049. function instanceData(category, shaderAttributeName) {
  10050. return function (target, propName, descriptor) {
  10051. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  10052. var node = dic.getLevelOf(target);
  10053. var instanceDataName = propName;
  10054. shaderAttributeName = shaderAttributeName || instanceDataName;
  10055. var info = node.levelContent.get(instanceDataName);
  10056. if (info) {
  10057. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  10058. }
  10059. info = new InstancePropInfo();
  10060. info.attributeName = shaderAttributeName;
  10061. info.category = category || null;
  10062. if (info.category) {
  10063. info.delimitedCategory = ";" + info.category + ";";
  10064. }
  10065. node.levelContent.add(instanceDataName, info);
  10066. descriptor.get = function () {
  10067. return null;
  10068. };
  10069. descriptor.set = function (val) {
  10070. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  10071. // Quit if it's the case, otherwise we could overwrite data somewhere...
  10072. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  10073. return;
  10074. }
  10075. if (!info.size) {
  10076. info.setSize(val);
  10077. node.classContent.mapProperty(info, true);
  10078. }
  10079. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  10080. node.classContent.mapProperty(info, false);
  10081. }
  10082. var obj = this;
  10083. if (obj.dataBuffer && obj.dataElements) {
  10084. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  10085. info.writeData(obj.dataBuffer.buffer, offset, val);
  10086. }
  10087. };
  10088. };
  10089. }
  10090. BABYLON.instanceData = instanceData;
  10091. var InstanceDataBase = (function () {
  10092. function InstanceDataBase(partId, dataElementCount) {
  10093. this.id = partId;
  10094. this.curElement = 0;
  10095. this._dataElementCount = dataElementCount;
  10096. this.renderMode = 0;
  10097. this.arrayLengthChanged = false;
  10098. }
  10099. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  10100. get: function () {
  10101. return null;
  10102. },
  10103. set: function (value) {
  10104. },
  10105. enumerable: true,
  10106. configurable: true
  10107. });
  10108. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  10109. get: function () {
  10110. return null;
  10111. },
  10112. set: function (value) {
  10113. },
  10114. enumerable: true,
  10115. configurable: true
  10116. });
  10117. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  10118. get: function () {
  10119. return null;
  10120. },
  10121. set: function (value) {
  10122. },
  10123. enumerable: true,
  10124. configurable: true
  10125. });
  10126. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  10127. get: function () {
  10128. return null;
  10129. },
  10130. set: function (value) {
  10131. },
  10132. enumerable: true,
  10133. configurable: true
  10134. });
  10135. InstanceDataBase.prototype.getClassTreeInfo = function () {
  10136. if (!this.typeInfo) {
  10137. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  10138. }
  10139. return this.typeInfo;
  10140. };
  10141. InstanceDataBase.prototype.allocElements = function () {
  10142. if (!this.dataBuffer || this.dataElements) {
  10143. return;
  10144. }
  10145. var res = new Array(this.dataElementCount);
  10146. for (var i = 0; i < this.dataElementCount; i++) {
  10147. res[i] = this.dataBuffer.allocElement();
  10148. }
  10149. this.dataElements = res;
  10150. };
  10151. InstanceDataBase.prototype.freeElements = function () {
  10152. if (!this.dataElements) {
  10153. return;
  10154. }
  10155. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  10156. var ei = _a[_i];
  10157. this.dataBuffer.freeElement(ei);
  10158. }
  10159. this.dataElements = null;
  10160. };
  10161. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  10162. get: function () {
  10163. return this._dataElementCount;
  10164. },
  10165. set: function (value) {
  10166. if (value === this._dataElementCount) {
  10167. return;
  10168. }
  10169. this.arrayLengthChanged = true;
  10170. this.freeElements();
  10171. this._dataElementCount = value;
  10172. this.allocElements();
  10173. },
  10174. enumerable: true,
  10175. configurable: true
  10176. });
  10177. return InstanceDataBase;
  10178. }());
  10179. __decorate([
  10180. instanceData()
  10181. ], InstanceDataBase.prototype, "zBias", null);
  10182. __decorate([
  10183. instanceData()
  10184. ], InstanceDataBase.prototype, "transformX", null);
  10185. __decorate([
  10186. instanceData()
  10187. ], InstanceDataBase.prototype, "transformY", null);
  10188. __decorate([
  10189. instanceData()
  10190. ], InstanceDataBase.prototype, "opacity", null);
  10191. BABYLON.InstanceDataBase = InstanceDataBase;
  10192. var RenderablePrim2D = RenderablePrim2D_1 = (function (_super) {
  10193. __extends(RenderablePrim2D, _super);
  10194. function RenderablePrim2D(settings) {
  10195. var _this = _super.call(this, settings) || this;
  10196. _this._transparentPrimitiveInfo = null;
  10197. return _this;
  10198. }
  10199. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  10200. get: function () {
  10201. return this._useTextureAlpha() || this._isPrimAlphaTest();
  10202. },
  10203. enumerable: true,
  10204. configurable: true
  10205. });
  10206. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  10207. get: function () {
  10208. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  10209. },
  10210. enumerable: true,
  10211. configurable: true
  10212. });
  10213. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  10214. get: function () {
  10215. return this._renderMode;
  10216. },
  10217. enumerable: true,
  10218. configurable: true
  10219. });
  10220. /**
  10221. * Dispose the primitive and its resources, remove it from its parent
  10222. */
  10223. RenderablePrim2D.prototype.dispose = function () {
  10224. if (!_super.prototype.dispose.call(this)) {
  10225. return false;
  10226. }
  10227. if (this.renderGroup) {
  10228. this.renderGroup._setCacheGroupDirty();
  10229. }
  10230. if (this._transparentPrimitiveInfo) {
  10231. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  10232. this._transparentPrimitiveInfo = null;
  10233. }
  10234. if (this._instanceDataParts) {
  10235. this._cleanupInstanceDataParts();
  10236. }
  10237. if (this._modelRenderCache) {
  10238. this._modelRenderCache.dispose();
  10239. this._modelRenderCache = null;
  10240. }
  10241. if (this._instanceDataParts) {
  10242. this._instanceDataParts.forEach(function (p) {
  10243. p.freeElements();
  10244. });
  10245. this._instanceDataParts = null;
  10246. }
  10247. return true;
  10248. };
  10249. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  10250. var gii = null;
  10251. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  10252. var part = _a[_i];
  10253. part.freeElements();
  10254. gii = part.groupInstanceInfo;
  10255. }
  10256. if (gii) {
  10257. var usedCount = 0;
  10258. if (gii.hasOpaqueData) {
  10259. var od = gii.opaqueData[0];
  10260. usedCount += od._partData.usedElementCount;
  10261. gii.opaqueDirty = true;
  10262. }
  10263. if (gii.hasAlphaTestData) {
  10264. var atd = gii.alphaTestData[0];
  10265. usedCount += atd._partData.usedElementCount;
  10266. gii.alphaTestDirty = true;
  10267. }
  10268. if (gii.hasTransparentData) {
  10269. var td = gii.transparentData[0];
  10270. usedCount += td._partData.usedElementCount;
  10271. gii.transparentDirty = true;
  10272. }
  10273. if (usedCount === 0 && gii.modelRenderCache != null) {
  10274. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  10275. gii.dispose();
  10276. }
  10277. if (this._modelRenderCache) {
  10278. this._modelRenderCache.dispose();
  10279. this._modelRenderCache = null;
  10280. }
  10281. }
  10282. this._instanceDataParts = null;
  10283. };
  10284. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  10285. _super.prototype._prepareRenderPre.call(this, context);
  10286. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  10287. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  10288. this._cleanupInstanceDataParts();
  10289. }
  10290. // Need to create the model?
  10291. var setupModelRenderCache = false;
  10292. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  10293. setupModelRenderCache = this._createModelRenderCache();
  10294. }
  10295. var gii = null;
  10296. var newInstance = false;
  10297. // Need to create the instance data parts?
  10298. if (!this._instanceDataParts) {
  10299. // Yes, flag it for later, more processing will have to be done
  10300. newInstance = true;
  10301. gii = this._createModelDataParts();
  10302. }
  10303. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  10304. if (setupModelRenderCache) {
  10305. this.setupModelRenderCache(this._modelRenderCache);
  10306. }
  10307. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelUpdate)) {
  10308. if (this._modelRenderCache.updateModelRenderCache(this)) {
  10309. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  10310. }
  10311. }
  10312. // 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.
  10313. // 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.
  10314. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  10315. this._updateInstanceDataParts(gii);
  10316. }
  10317. };
  10318. RenderablePrim2D.prototype._createModelRenderCache = function () {
  10319. var _this = this;
  10320. var setupModelRenderCache = false;
  10321. if (this._modelRenderCache) {
  10322. this._modelRenderCache.dispose();
  10323. }
  10324. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  10325. var mrc = _this.createModelRenderCache(key);
  10326. setupModelRenderCache = true;
  10327. return mrc;
  10328. });
  10329. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  10330. // if this is still false it means the MRC already exists, so we add a reference to it
  10331. if (!setupModelRenderCache) {
  10332. this._modelRenderCache.addRef();
  10333. }
  10334. return setupModelRenderCache;
  10335. };
  10336. RenderablePrim2D.prototype._createModelDataParts = function () {
  10337. var _this = this;
  10338. // Create the instance data parts of the primitive and store them
  10339. var parts = this.createInstanceDataParts();
  10340. this._instanceDataParts = parts;
  10341. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  10342. if (!this._modelRenderCache._partData) {
  10343. this._setupModelRenderCache(parts);
  10344. }
  10345. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  10346. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  10347. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  10348. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  10349. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  10350. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  10351. var part = _this._instanceDataParts[j];
  10352. res.partIndexFromId.add(part.id.toString(), j);
  10353. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  10354. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  10355. }
  10356. return res;
  10357. });
  10358. // Get the GroupInfoDataPart corresponding to the render category of the part
  10359. var rm = 0;
  10360. var gipd = null;
  10361. if (this.isTransparent) {
  10362. gipd = gii.transparentData;
  10363. rm = BABYLON.Render2DContext.RenderModeTransparent;
  10364. }
  10365. else if (this.isAlphaTest) {
  10366. gipd = gii.alphaTestData;
  10367. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  10368. }
  10369. else {
  10370. gipd = gii.opaqueData;
  10371. rm = BABYLON.Render2DContext.RenderModeOpaque;
  10372. }
  10373. // For each instance data part of the primitive, allocate the instanced element it needs for render
  10374. for (var i = 0; i < parts.length; i++) {
  10375. var part = parts[i];
  10376. part.dataBuffer = gipd[i]._partData;
  10377. part.allocElements();
  10378. part.renderMode = rm;
  10379. part.groupInstanceInfo = gii;
  10380. }
  10381. return gii;
  10382. };
  10383. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  10384. var ctiArray = new Array();
  10385. this._modelRenderCache._partData = new Array();
  10386. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  10387. var dataPart = parts_1[_i];
  10388. var pd = new BABYLON.ModelRenderCachePartData();
  10389. this._modelRenderCache._partData.push(pd);
  10390. var cat = this.getUsedShaderCategories(dataPart);
  10391. var cti = dataPart.getClassTreeInfo();
  10392. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  10393. var curVisible = this.isVisible;
  10394. this.isVisible = true;
  10395. // 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.
  10396. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  10397. var joinCat = ";" + cat.join(";") + ";";
  10398. pd._partJoinedUsedCategories = joinCat;
  10399. InstanceClassInfo._CurCategories = joinCat;
  10400. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  10401. if (!this.refreshInstanceDataPart(dataPart)) {
  10402. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  10403. }
  10404. this.afterRefreshForLayoutConstruction(dataPart, obj);
  10405. this.isVisible = curVisible;
  10406. var size = 0;
  10407. cti.fullContent.forEach(function (k, v) {
  10408. if (!v.category || cat.indexOf(v.category) !== -1) {
  10409. if (v.attributeName === "zBias") {
  10410. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  10411. }
  10412. if (!v.size) {
  10413. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  10414. }
  10415. else {
  10416. size += v.size;
  10417. }
  10418. }
  10419. });
  10420. pd._partDataStride = size;
  10421. pd._partUsedCategories = cat;
  10422. pd._partId = dataPart.id;
  10423. ctiArray.push(cti);
  10424. }
  10425. this._modelRenderCache._partsClassInfo = ctiArray;
  10426. };
  10427. RenderablePrim2D.prototype.onZOrderChanged = function () {
  10428. if (this.isTransparent && this._transparentPrimitiveInfo) {
  10429. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  10430. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  10431. // Flag the transparentData dirty has will have to sort it again
  10432. gii.transparentOrderDirty = true;
  10433. }
  10434. };
  10435. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  10436. return false;
  10437. };
  10438. RenderablePrim2D.prototype._useTextureAlpha = function () {
  10439. return false;
  10440. };
  10441. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  10442. return false;
  10443. };
  10444. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  10445. return false;
  10446. };
  10447. RenderablePrim2D.prototype._isPrimTransparent = function () {
  10448. return false;
  10449. };
  10450. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  10451. // Fetch the GroupInstanceInfo if we don't already have it
  10452. var rd = this.renderGroup._renderableData;
  10453. if (!gii) {
  10454. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  10455. }
  10456. var isTransparent = this.isTransparent;
  10457. var isAlphaTest = this.isAlphaTest;
  10458. var wereTransparent = false;
  10459. // Check a render mode change
  10460. var rmChanged = false;
  10461. if (this._instanceDataParts.length > 0) {
  10462. var firstPart = this._instanceDataParts[0];
  10463. var partRM = firstPart.renderMode;
  10464. var curRM = this.renderMode;
  10465. if (partRM !== curRM) {
  10466. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  10467. rmChanged = true;
  10468. var gipd = void 0;
  10469. switch (curRM) {
  10470. case BABYLON.Render2DContext.RenderModeTransparent:
  10471. gipd = gii.transparentData;
  10472. break;
  10473. case BABYLON.Render2DContext.RenderModeAlphaTest:
  10474. gipd = gii.alphaTestData;
  10475. break;
  10476. default:
  10477. gipd = gii.opaqueData;
  10478. }
  10479. for (var i = 0; i < this._instanceDataParts.length; i++) {
  10480. var part = this._instanceDataParts[i];
  10481. part.freeElements();
  10482. part.dataBuffer = gipd[i]._partData;
  10483. part.renderMode = curRM;
  10484. }
  10485. }
  10486. }
  10487. // Handle changes related to ZOffset
  10488. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  10489. if (isTransparent || wereTransparent) {
  10490. // Handle visibility change, which is also triggered when the primitive just got created
  10491. if (visChanged || rmChanged) {
  10492. if (this.isVisible && !wereTransparent) {
  10493. if (!this._transparentPrimitiveInfo) {
  10494. // Add the primitive to the list of transparent ones in the group that render is
  10495. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  10496. }
  10497. }
  10498. else {
  10499. if (this._transparentPrimitiveInfo) {
  10500. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  10501. this._transparentPrimitiveInfo = null;
  10502. }
  10503. }
  10504. gii.transparentOrderDirty = true;
  10505. }
  10506. }
  10507. var rebuildTrans = false;
  10508. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  10509. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  10510. var part = _a[_i];
  10511. var justAllocated = false;
  10512. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  10513. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  10514. part.allocElements();
  10515. justAllocated = true;
  10516. }
  10517. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  10518. // Will return false if the instance should not be rendered (not visible or other any reasons)
  10519. part.arrayLengthChanged = false;
  10520. if (!this.refreshInstanceDataPart(part)) {
  10521. // Free the data element
  10522. if (part.dataElements) {
  10523. part.freeElements();
  10524. }
  10525. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  10526. if (this.isVisible) {
  10527. rd._primNewDirtyList.push(this);
  10528. }
  10529. }
  10530. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  10531. }
  10532. this._instanceDirtyFlags = 0;
  10533. // Make the appropriate data dirty
  10534. if (isTransparent) {
  10535. gii.transparentDirty = true;
  10536. if (rebuildTrans) {
  10537. rd._transparentListChanged = true;
  10538. }
  10539. }
  10540. else if (isAlphaTest) {
  10541. gii.alphaTestDirty = true;
  10542. }
  10543. else {
  10544. gii.opaqueDirty = true;
  10545. }
  10546. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  10547. };
  10548. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  10549. var minOff = BABYLON.Prim2DBase._bigInt;
  10550. var maxOff = 0;
  10551. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  10552. var part = _a[_i];
  10553. if (part && part.dataElements) {
  10554. part.dataBuffer.pack();
  10555. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  10556. var el = _c[_b];
  10557. minOff = Math.min(minOff, el.offset);
  10558. maxOff = Math.max(maxOff, el.offset);
  10559. }
  10560. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  10561. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  10562. }
  10563. }
  10564. };
  10565. // This internal method is mainly used for transparency processing
  10566. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  10567. var length = this._instanceDataParts.length;
  10568. for (var i = 0; i < length; i++) {
  10569. var part = this._instanceDataParts[i];
  10570. if (part) {
  10571. var stride = part.dataBuffer.stride;
  10572. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  10573. // check if it's the last in the DFA
  10574. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  10575. return null;
  10576. }
  10577. // Return the Z of the next primitive that lies in the DFA
  10578. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  10579. }
  10580. }
  10581. return null;
  10582. };
  10583. // This internal method is mainly used for transparency processing
  10584. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  10585. var length = this._instanceDataParts.length;
  10586. for (var i = 0; i < length; i++) {
  10587. var part = this._instanceDataParts[i];
  10588. if (part) {
  10589. var stride = part.dataBuffer.stride;
  10590. var firstElementOffset = part.dataElements[0].offset;
  10591. // check if it's the first in the DFA
  10592. if (firstElementOffset === 0) {
  10593. return null;
  10594. }
  10595. // Return the Z of the previous primitive that lies in the DFA
  10596. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  10597. }
  10598. }
  10599. return null;
  10600. };
  10601. /**
  10602. * Transform a given point using the Primitive's origin setting.
  10603. * This method requires the Primitive's actualSize to be accurate
  10604. * @param p the point to transform
  10605. * @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.
  10606. * @param res an allocated Vector2 that will receive the transformed content
  10607. */
  10608. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  10609. var actualSize = this.actualSize;
  10610. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  10611. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  10612. };
  10613. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  10614. this.transformPointWithOriginByRef(p, originOffset, res);
  10615. return res;
  10616. };
  10617. /**
  10618. * Get the info for a given effect based on the dataPart metadata
  10619. * @param dataPartId partId in part list to get the info
  10620. * @param vertexBufferAttributes vertex buffer attributes to manually add
  10621. * @param uniforms uniforms to manually add
  10622. * @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
  10623. */
  10624. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  10625. if (uniforms === void 0) { uniforms = null; }
  10626. if (useInstanced === void 0) { useInstanced = null; }
  10627. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  10628. if (!dataPart) {
  10629. return null;
  10630. }
  10631. var instancedArray = this.owner.supportInstancedArray;
  10632. if (useInstanced != null) {
  10633. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  10634. if (useInstanced && instancedArray === false) {
  10635. return null;
  10636. }
  10637. // Use the caller's setting
  10638. instancedArray = useInstanced;
  10639. }
  10640. var cti = dataPart.getClassTreeInfo();
  10641. var categories = this.getUsedShaderCategories(dataPart);
  10642. var att = cti.classContent.getShaderAttributes(categories);
  10643. var defines = "";
  10644. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  10645. if (instancedArray) {
  10646. defines += "#define Instanced\n";
  10647. }
  10648. return {
  10649. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  10650. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  10651. defines: defines
  10652. };
  10653. };
  10654. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  10655. get: function () {
  10656. return this._modelRenderCache;
  10657. },
  10658. enumerable: true,
  10659. configurable: true
  10660. });
  10661. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  10662. return null;
  10663. };
  10664. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  10665. };
  10666. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  10667. return null;
  10668. };
  10669. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  10670. return [];
  10671. };
  10672. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  10673. };
  10674. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  10675. };
  10676. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  10677. return true;
  10678. };
  10679. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  10680. if (!this.isVisible) {
  10681. return false;
  10682. }
  10683. part.isVisible = this.isVisible;
  10684. // 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)
  10685. if (part.dataElementCount === 1) {
  10686. part.curElement = 0;
  10687. this.updateInstanceDataPart(part);
  10688. }
  10689. return true;
  10690. };
  10691. /**
  10692. * Update the instanceDataBase level properties of a part
  10693. * @param part the part to update
  10694. * @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).
  10695. */
  10696. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  10697. if (positionOffset === void 0) { positionOffset = null; }
  10698. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  10699. var scl = RenderablePrim2D_1._s;
  10700. var rot = RenderablePrim2D_1._r;
  10701. var trn = RenderablePrim2D_1._t;
  10702. t.decompose(scl, rot, trn);
  10703. var pas = this.actualScale;
  10704. scl.x = pas.x;
  10705. scl.y = pas.y;
  10706. scl.z = 1;
  10707. t = BABYLON.Matrix.Compose(this.applyActualScaleOnTransform() ? scl : RenderablePrim2D_1._iV3, rot, trn);
  10708. var size = this.renderGroup.viewportSize;
  10709. var zBias = this.actualZOffset;
  10710. var offX = 0;
  10711. var offY = 0;
  10712. // If there's an offset, apply the global transformation matrix on it to get a global offset
  10713. if (positionOffset) {
  10714. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  10715. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  10716. }
  10717. // 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
  10718. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  10719. // So for X:
  10720. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  10721. // - 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].
  10722. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  10723. var w = size.width;
  10724. var h = size.height;
  10725. var invZBias = 1 / zBias;
  10726. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0, ((t.m[12] + offX) * 2 / w) - 1);
  10727. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0, ((t.m[13] + offY) * 2 / h) - 1);
  10728. part.transformX = tx;
  10729. part.transformY = ty;
  10730. part.opacity = this.actualOpacity;
  10731. // 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)
  10732. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  10733. };
  10734. RenderablePrim2D.prototype._updateRenderMode = function () {
  10735. if (this.isTransparent) {
  10736. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  10737. }
  10738. else if (this.isAlphaTest) {
  10739. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  10740. }
  10741. else {
  10742. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  10743. }
  10744. };
  10745. return RenderablePrim2D;
  10746. }(BABYLON.Prim2DBase));
  10747. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  10748. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  10749. RenderablePrim2D._s = BABYLON.Vector3.Zero();
  10750. RenderablePrim2D._r = BABYLON.Quaternion.Identity();
  10751. RenderablePrim2D._t = BABYLON.Vector3.Zero();
  10752. RenderablePrim2D._iV3 = new BABYLON.Vector3(1, 1, 1); // Must stay identity vector3
  10753. __decorate([
  10754. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D_1.isAlphaTestProperty = pi; })
  10755. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  10756. __decorate([
  10757. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D_1.isTransparentProperty = pi; })
  10758. ], RenderablePrim2D.prototype, "isTransparent", null);
  10759. RenderablePrim2D = RenderablePrim2D_1 = __decorate([
  10760. BABYLON.className("RenderablePrim2D", "BABYLON")
  10761. ], RenderablePrim2D);
  10762. BABYLON.RenderablePrim2D = RenderablePrim2D;
  10763. var RenderablePrim2D_1;
  10764. })(BABYLON || (BABYLON = {}));
  10765. //# sourceMappingURL=babylon.renderablePrim2d.js.map
  10766. var __extends = (this && this.__extends) || function (d, b) {
  10767. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  10768. function __() { this.constructor = d; }
  10769. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  10770. };
  10771. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  10772. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  10773. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  10774. 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;
  10775. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10776. };
  10777. var BABYLON;
  10778. (function (BABYLON) {
  10779. var Shape2D = Shape2D_1 = (function (_super) {
  10780. __extends(Shape2D, _super);
  10781. function Shape2D(settings) {
  10782. var _this = _super.call(this, settings) || this;
  10783. if (!settings) {
  10784. settings = {};
  10785. }
  10786. var borderBrush = null;
  10787. if (settings.border) {
  10788. if (typeof (settings.border) === "string") {
  10789. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  10790. }
  10791. else {
  10792. borderBrush = settings.border;
  10793. }
  10794. }
  10795. var fillBrush = null;
  10796. if (settings.fill) {
  10797. if (typeof (settings.fill) === "string") {
  10798. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  10799. }
  10800. else {
  10801. fillBrush = settings.fill;
  10802. }
  10803. }
  10804. _this._isTransparent = false;
  10805. _this._oldTransparent = false;
  10806. _this.border = borderBrush;
  10807. _this.fill = fillBrush;
  10808. _this._updateTransparencyStatus();
  10809. _this.borderThickness = settings.borderThickness;
  10810. return _this;
  10811. }
  10812. Object.defineProperty(Shape2D.prototype, "border", {
  10813. get: function () {
  10814. return this._border;
  10815. },
  10816. set: function (value) {
  10817. this._border = value;
  10818. this._updateTransparencyStatus();
  10819. },
  10820. enumerable: true,
  10821. configurable: true
  10822. });
  10823. Object.defineProperty(Shape2D.prototype, "fill", {
  10824. /**
  10825. * Get/set the brush to render the Fill part of the Primitive
  10826. */
  10827. get: function () {
  10828. return this._fill;
  10829. },
  10830. set: function (value) {
  10831. this._fill = value;
  10832. this._updateTransparencyStatus();
  10833. },
  10834. enumerable: true,
  10835. configurable: true
  10836. });
  10837. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  10838. get: function () {
  10839. return this._borderThickness;
  10840. },
  10841. set: function (value) {
  10842. this._borderThickness = value;
  10843. },
  10844. enumerable: true,
  10845. configurable: true
  10846. });
  10847. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  10848. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  10849. // Fill Part
  10850. if (dataPart.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  10851. var fill = this.fill;
  10852. if (fill instanceof BABYLON.SolidColorBrush2D) {
  10853. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLSOLID);
  10854. }
  10855. if (fill instanceof BABYLON.GradientColorBrush2D) {
  10856. cat.push(Shape2D_1.SHAPE2D_CATEGORY_FILLGRADIENT);
  10857. }
  10858. }
  10859. // Border Part
  10860. if (dataPart.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  10861. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDER);
  10862. var border = this.border;
  10863. if (border instanceof BABYLON.SolidColorBrush2D) {
  10864. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERSOLID);
  10865. }
  10866. if (border instanceof BABYLON.GradientColorBrush2D) {
  10867. cat.push(Shape2D_1.SHAPE2D_CATEGORY_BORDERGRADIENT);
  10868. }
  10869. }
  10870. return cat;
  10871. };
  10872. Shape2D.prototype.applyActualScaleOnTransform = function () {
  10873. return false;
  10874. };
  10875. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  10876. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  10877. return false;
  10878. }
  10879. // Fill Part
  10880. if (part.id === Shape2D_1.SHAPE2D_FILLPARTID) {
  10881. var d = part;
  10882. if (this.fill) {
  10883. var fill = this.fill;
  10884. if (fill instanceof BABYLON.SolidColorBrush2D) {
  10885. d.fillSolidColor = fill.color;
  10886. }
  10887. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  10888. d.fillGradientColor1 = fill.color1;
  10889. d.fillGradientColor2 = fill.color2;
  10890. 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));
  10891. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  10892. d.fillGradientTY = ty;
  10893. }
  10894. }
  10895. }
  10896. else if (part.id === Shape2D_1.SHAPE2D_BORDERPARTID) {
  10897. var d = part;
  10898. if (this.border) {
  10899. d.borderThickness = this.borderThickness;
  10900. var border = this.border;
  10901. if (border instanceof BABYLON.SolidColorBrush2D) {
  10902. d.borderSolidColor = border.color;
  10903. }
  10904. else if (border instanceof BABYLON.GradientColorBrush2D) {
  10905. d.borderGradientColor1 = border.color1;
  10906. d.borderGradientColor2 = border.color2;
  10907. 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));
  10908. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  10909. d.borderGradientTY = ty;
  10910. }
  10911. }
  10912. }
  10913. return true;
  10914. };
  10915. Shape2D.prototype._updateTransparencyStatus = function () {
  10916. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  10917. if (this._isTransparent !== this._oldTransparent) {
  10918. this._oldTransparent = this._isTransparent;
  10919. this._updateRenderMode();
  10920. }
  10921. };
  10922. Shape2D.prototype._mustUpdateInstance = function () {
  10923. var res = this._oldTransparent !== this._isTransparent;
  10924. if (res) {
  10925. this._updateRenderMode();
  10926. this._oldTransparent = this._isTransparent;
  10927. }
  10928. return res;
  10929. };
  10930. Shape2D.prototype._isPrimTransparent = function () {
  10931. return this._isTransparent;
  10932. };
  10933. return Shape2D;
  10934. }(BABYLON.RenderablePrim2D));
  10935. Shape2D.SHAPE2D_BORDERPARTID = 1;
  10936. Shape2D.SHAPE2D_FILLPARTID = 2;
  10937. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  10938. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  10939. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  10940. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  10941. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  10942. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  10943. __decorate([
  10944. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D_1.borderProperty = pi; }, true)
  10945. ], Shape2D.prototype, "border", null);
  10946. __decorate([
  10947. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D_1.fillProperty = pi; }, true)
  10948. ], Shape2D.prototype, "fill", null);
  10949. __decorate([
  10950. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D_1.borderThicknessProperty = pi; })
  10951. ], Shape2D.prototype, "borderThickness", null);
  10952. Shape2D = Shape2D_1 = __decorate([
  10953. BABYLON.className("Shape2D", "BABYLON")
  10954. ], Shape2D);
  10955. BABYLON.Shape2D = Shape2D;
  10956. var Shape2DInstanceData = (function (_super) {
  10957. __extends(Shape2DInstanceData, _super);
  10958. function Shape2DInstanceData() {
  10959. return _super !== null && _super.apply(this, arguments) || this;
  10960. }
  10961. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  10962. // FILL ATTRIBUTES
  10963. get: function () {
  10964. return null;
  10965. },
  10966. set: function (value) {
  10967. },
  10968. enumerable: true,
  10969. configurable: true
  10970. });
  10971. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  10972. get: function () {
  10973. return null;
  10974. },
  10975. set: function (value) {
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  10981. get: function () {
  10982. return null;
  10983. },
  10984. set: function (value) {
  10985. },
  10986. enumerable: true,
  10987. configurable: true
  10988. });
  10989. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  10990. get: function () {
  10991. return null;
  10992. },
  10993. set: function (value) {
  10994. },
  10995. enumerable: true,
  10996. configurable: true
  10997. });
  10998. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  10999. // BORDER ATTRIBUTES
  11000. get: function () {
  11001. return null;
  11002. },
  11003. set: function (value) {
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  11009. get: function () {
  11010. return null;
  11011. },
  11012. set: function (value) {
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  11018. get: function () {
  11019. return null;
  11020. },
  11021. set: function (value) {
  11022. },
  11023. enumerable: true,
  11024. configurable: true
  11025. });
  11026. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  11027. get: function () {
  11028. return null;
  11029. },
  11030. set: function (value) {
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  11036. get: function () {
  11037. return null;
  11038. },
  11039. set: function (value) {
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. return Shape2DInstanceData;
  11045. }(BABYLON.InstanceDataBase));
  11046. __decorate([
  11047. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  11048. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  11049. __decorate([
  11050. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  11051. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  11052. __decorate([
  11053. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  11054. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  11055. __decorate([
  11056. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  11057. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  11058. __decorate([
  11059. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  11060. ], Shape2DInstanceData.prototype, "borderThickness", null);
  11061. __decorate([
  11062. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  11063. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  11064. __decorate([
  11065. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  11066. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  11067. __decorate([
  11068. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  11069. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  11070. __decorate([
  11071. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  11072. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  11073. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  11074. var Shape2D_1;
  11075. })(BABYLON || (BABYLON = {}));
  11076. //# sourceMappingURL=babylon.shape2d.js.map
  11077. var __extends = (this && this.__extends) || function (d, b) {
  11078. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  11079. function __() { this.constructor = d; }
  11080. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11081. };
  11082. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  11083. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  11084. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  11085. 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;
  11086. return c > 3 && r && Object.defineProperty(target, key, r), r;
  11087. };
  11088. var BABYLON;
  11089. (function (BABYLON) {
  11090. var Group2D = Group2D_1 = (function (_super) {
  11091. __extends(Group2D, _super);
  11092. /**
  11093. * Create an Logical or Renderable Group.
  11094. * @param settings a combination of settings, possible ones are
  11095. * - 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)
  11096. * - children: an array of direct children
  11097. * - id a text identifier, for information purpose
  11098. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  11099. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  11100. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  11101. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  11102. * - trackNode: if you want the ScreenSpaceCanvas to track the position of a given Scene Node, use this setting to specify the Node to track
  11103. * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
  11104. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  11105. * - zOrder: override the zOrder with the specified value
  11106. * - origin: define the normalized origin point location, default [0.5;0.5]
  11107. * - 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.
  11108. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  11109. * - 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).
  11110. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  11111. * - 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.
  11112. * - 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.
  11113. * - 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!
  11114. * - 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.
  11115. * - 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).
  11116. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  11117. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11118. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11119. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11120. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11121. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  11122. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  11123. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  11124. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  11125. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11126. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11127. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11128. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  11129. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  11130. */
  11131. function Group2D(settings) {
  11132. var _this = this;
  11133. if (settings == null) {
  11134. settings = {};
  11135. }
  11136. if (settings.origin == null) {
  11137. settings.origin = new BABYLON.Vector2(0, 0);
  11138. }
  11139. _this = _super.call(this, settings) || this;
  11140. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  11141. _this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  11142. _this._trackedNodeOffset = (settings.trackNodeOffset == null) ? null : settings.trackNodeOffset;
  11143. if (_this._trackedNode && _this.owner) {
  11144. _this.owner._registerTrackedNode(_this);
  11145. }
  11146. _this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  11147. var rd = _this._renderableData;
  11148. if (rd) {
  11149. rd._noResizeOnScale = (_this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  11150. }
  11151. _this.size = size;
  11152. _this._viewportPosition = BABYLON.Vector2.Zero();
  11153. _this._viewportSize = BABYLON.Size.Zero();
  11154. return _this;
  11155. }
  11156. Group2D._createCachedCanvasGroup = function (owner) {
  11157. 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 });
  11158. return g;
  11159. };
  11160. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  11161. this._bindCacheTarget();
  11162. if (vertexData) {
  11163. var uv = vertexData.uvs;
  11164. var nodeuv = this._renderableData._cacheNodeUVs;
  11165. for (var i = 0; i < 4; i++) {
  11166. uv[i * 2 + 0] = nodeuv[i].x;
  11167. uv[i * 2 + 1] = nodeuv[i].y;
  11168. }
  11169. }
  11170. if (material) {
  11171. material.diffuseTexture = this._renderableData._cacheTexture;
  11172. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  11173. }
  11174. this._renderableData._cacheTexture.hasAlpha = true;
  11175. this._unbindCacheTarget();
  11176. };
  11177. Object.defineProperty(Group2D.prototype, "cachedRect", {
  11178. /**
  11179. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  11180. * 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.
  11181. */
  11182. get: function () {
  11183. if (!this._renderableData) {
  11184. return null;
  11185. }
  11186. return this._renderableData._cacheNode;
  11187. },
  11188. enumerable: true,
  11189. configurable: true
  11190. });
  11191. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  11192. /**
  11193. * The UVs into the MapTexture that map the cached group
  11194. */
  11195. get: function () {
  11196. if (!this._renderableData) {
  11197. return null;
  11198. }
  11199. return this._renderableData._cacheNodeUVs;
  11200. },
  11201. enumerable: true,
  11202. configurable: true
  11203. });
  11204. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  11205. get: function () {
  11206. if (!this._renderableData) {
  11207. return null;
  11208. }
  11209. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  11210. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  11211. }
  11212. return this._renderableData._cacheNodeUVsChangedObservable;
  11213. },
  11214. enumerable: true,
  11215. configurable: true
  11216. });
  11217. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  11218. /**
  11219. * Access the texture that maintains a cached version of the Group2D.
  11220. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  11221. */
  11222. get: function () {
  11223. if (!this._renderableData) {
  11224. return null;
  11225. }
  11226. return this._renderableData._cacheTexture;
  11227. },
  11228. enumerable: true,
  11229. configurable: true
  11230. });
  11231. /**
  11232. * Call this method to remove this Group and its children from the Canvas
  11233. */
  11234. Group2D.prototype.dispose = function () {
  11235. if (!_super.prototype.dispose.call(this)) {
  11236. return false;
  11237. }
  11238. if (this._trackedNode != null) {
  11239. this.owner._unregisterTrackedNode(this);
  11240. this._trackedNode = null;
  11241. }
  11242. if (this._renderableData) {
  11243. this._renderableData.dispose(this.owner);
  11244. this._renderableData = null;
  11245. }
  11246. return true;
  11247. };
  11248. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  11249. /**
  11250. * @returns Returns true if the Group render content, false if it's a logical group only
  11251. */
  11252. get: function () {
  11253. return this._isRenderableGroup;
  11254. },
  11255. enumerable: true,
  11256. configurable: true
  11257. });
  11258. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  11259. /**
  11260. * @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
  11261. */
  11262. get: function () {
  11263. return this._isCachedGroup;
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. Object.defineProperty(Group2D.prototype, "size", {
  11269. get: function () {
  11270. return this.internalGetSize();
  11271. },
  11272. /**
  11273. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  11274. * 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.
  11275. */
  11276. set: function (val) {
  11277. this.internalSetSize(val);
  11278. },
  11279. enumerable: true,
  11280. configurable: true
  11281. });
  11282. Object.defineProperty(Group2D.prototype, "viewportSize", {
  11283. get: function () {
  11284. return this._viewportSize;
  11285. },
  11286. enumerable: true,
  11287. configurable: true
  11288. });
  11289. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  11290. /**
  11291. * 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.
  11292. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  11293. * 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.
  11294. */
  11295. get: function () {
  11296. return this._cacheBehavior;
  11297. },
  11298. enumerable: true,
  11299. configurable: true
  11300. });
  11301. Group2D.prototype._addPrimToDirtyList = function (prim) {
  11302. this._renderableData._primDirtyList.push(prim);
  11303. };
  11304. Group2D.prototype._renderCachedCanvas = function () {
  11305. this.owner._addGroupRenderCount(1);
  11306. this.updateCachedStates(true);
  11307. var context = new BABYLON.PrepareRender2DContext();
  11308. this._prepareGroupRender(context);
  11309. this._groupRender();
  11310. };
  11311. Object.defineProperty(Group2D.prototype, "trackedNode", {
  11312. /**
  11313. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  11314. */
  11315. get: function () {
  11316. return this._trackedNode;
  11317. },
  11318. set: function (val) {
  11319. if (val != null) {
  11320. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  11321. this.owner._registerTrackedNode(this);
  11322. }
  11323. this._trackedNode = val;
  11324. }
  11325. else {
  11326. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  11327. this.owner._unregisterTrackedNode(this);
  11328. }
  11329. this._trackedNode = null;
  11330. }
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Object.defineProperty(Group2D.prototype, "trackedNodeOffset", {
  11336. /**
  11337. * Get/set the offset of the tracked node in the tracked node's local space.
  11338. */
  11339. get: function () {
  11340. return this._trackedNodeOffset;
  11341. },
  11342. set: function (val) {
  11343. if (!this._trackedNodeOffset) {
  11344. this._trackedNodeOffset = val.clone();
  11345. }
  11346. else {
  11347. this._trackedNodeOffset.copyFrom(val);
  11348. }
  11349. },
  11350. enumerable: true,
  11351. configurable: true
  11352. });
  11353. Group2D.prototype.levelIntersect = function (intersectInfo) {
  11354. // 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
  11355. return true;
  11356. };
  11357. Group2D.prototype.updateLevelBoundingInfo = function () {
  11358. var size;
  11359. // If the size is set by the user, the boundingInfo is computed from this value
  11360. if (this.size) {
  11361. size = this.size;
  11362. }
  11363. else {
  11364. size = new BABYLON.Size(0, 0);
  11365. }
  11366. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  11367. return true;
  11368. };
  11369. // Method called only on renderable groups to prepare the rendering
  11370. Group2D.prototype._prepareGroupRender = function (context) {
  11371. var sortedDirtyList = null;
  11372. // Update the Global Transformation and visibility status of the changed primitives
  11373. var rd = this._renderableData;
  11374. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  11375. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  11376. this.updateCachedStatesOf(sortedDirtyList, true);
  11377. }
  11378. var s = this.actualSize;
  11379. var a = this.actualScale;
  11380. var hwsl = 1 / this.owner.engine.getHardwareScalingLevel();
  11381. var sw = Math.ceil(s.width * a.x * hwsl);
  11382. var sh = Math.ceil(s.height * a.y * hwsl);
  11383. // 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.
  11384. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  11385. if ((this instanceof BABYLON.Canvas2D || this.id === "__cachedCanvasGroup__") && this.owner.designSize != null) {
  11386. sw = this.owner.engine.getRenderWidth();
  11387. sh = this.owner.engine.getRenderHeight();
  11388. }
  11389. // Setup the size of the rendering viewport
  11390. // 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
  11391. if (!this._isCachedGroup) {
  11392. // Compute the WebGL viewport's location/size
  11393. var t = this._globalTransform.getTranslation();
  11394. var rs = this.owner._renderingSize.multiplyByFloats(hwsl, hwsl);
  11395. sh = Math.min(sh, rs.height - t.y);
  11396. sw = Math.min(sw, rs.width - t.x);
  11397. var x = t.x;
  11398. var y = t.y;
  11399. // 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
  11400. this._viewportPosition.x = x;
  11401. this._viewportPosition.y = y;
  11402. }
  11403. // 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.
  11404. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  11405. context.forceRefreshPrimitive = true;
  11406. this._viewportSize.width = sw;
  11407. this._viewportSize.height = sh;
  11408. }
  11409. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  11410. // If the group is cached, set the dirty flag to true because of the incoming changes
  11411. this._cacheGroupDirty = this._isCachedGroup;
  11412. rd._primNewDirtyList.splice(0);
  11413. // If it's a force refresh, prepare all the children
  11414. if (context.forceRefreshPrimitive) {
  11415. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11416. var p = _a[_i];
  11417. p._prepareRender(context);
  11418. }
  11419. }
  11420. else {
  11421. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  11422. // the hierarchyDepth in order to prepare primitives from top to bottom
  11423. if (!sortedDirtyList) {
  11424. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  11425. }
  11426. sortedDirtyList.forEach(function (p) {
  11427. // 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.
  11428. // 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.
  11429. if (!p.isDisposed && p._needPrepare()) {
  11430. p._prepareRender(context);
  11431. }
  11432. });
  11433. }
  11434. // Everything is updated, clear the dirty list
  11435. rd._primDirtyList.forEach(function (p) {
  11436. if (rd._primNewDirtyList.indexOf(p) === -1) {
  11437. p._resetPropertiesDirty();
  11438. }
  11439. else {
  11440. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  11441. }
  11442. });
  11443. rd._primDirtyList.splice(0);
  11444. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  11445. }
  11446. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  11447. rd._childrenRenderableGroups.forEach(function (g) {
  11448. g._prepareGroupRender(context);
  11449. });
  11450. };
  11451. Group2D.prototype._groupRender = function () {
  11452. var _this = this;
  11453. var engine = this.owner.engine;
  11454. var failedCount = 0;
  11455. // First recurse to children render group to render them (in their cache or on screen)
  11456. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  11457. var childGroup = _a[_i];
  11458. childGroup._groupRender();
  11459. }
  11460. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  11461. if (!this.isCachedGroup || this._cacheGroupDirty) {
  11462. this.owner._addGroupRenderCount(1);
  11463. if (this.isCachedGroup) {
  11464. this._bindCacheTarget();
  11465. }
  11466. else {
  11467. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  11468. }
  11469. var curAlphaTest = engine.getAlphaTesting() === true;
  11470. var curDepthWrite = engine.getDepthWrite() === true;
  11471. // ===================================================================
  11472. // First pass, update the InstancedArray and render Opaque primitives
  11473. // Disable Alpha Testing, Enable Depth Write
  11474. engine.setAlphaTesting(false);
  11475. engine.setDepthWrite(true);
  11476. // For each different model of primitive to render
  11477. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  11478. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  11479. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  11480. var renderCount = _this._prepareContext(engine, context_1, v);
  11481. // If null is returned, there's no opaque data to render
  11482. if (renderCount === null) {
  11483. return;
  11484. }
  11485. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  11486. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  11487. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  11488. var renderFailed = !v.modelRenderCache.render(v, context_1);
  11489. // Update dirty flag/related
  11490. v.opaqueDirty = renderFailed;
  11491. failedCount += renderFailed ? 1 : 0;
  11492. }
  11493. });
  11494. // =======================================================================
  11495. // Second pass, update the InstancedArray and render AlphaTest primitives
  11496. // Enable Alpha Testing, Enable Depth Write
  11497. engine.setAlphaTesting(true);
  11498. engine.setDepthWrite(true);
  11499. // For each different model of primitive to render
  11500. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  11501. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  11502. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  11503. var renderCount = _this._prepareContext(engine, context_1, v);
  11504. // If null is returned, there's no opaque data to render
  11505. if (renderCount === null) {
  11506. return;
  11507. }
  11508. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  11509. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  11510. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  11511. var renderFailed = !v.modelRenderCache.render(v, context_1);
  11512. // Update dirty flag/related
  11513. v.opaqueDirty = renderFailed;
  11514. failedCount += renderFailed ? 1 : 0;
  11515. }
  11516. });
  11517. // =======================================================================
  11518. // Third pass, transparent primitive rendering
  11519. // Enable Alpha Testing, Disable Depth Write
  11520. engine.setAlphaTesting(true);
  11521. engine.setDepthWrite(false);
  11522. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  11523. if (this._renderableData._transparentListChanged) {
  11524. this._updateTransparentData();
  11525. }
  11526. // From this point on we have up to date data to render, so let's go
  11527. failedCount += this._renderTransparentData();
  11528. // =======================================================================
  11529. // Unbind target/restore viewport setting, clear dirty flag, and quit
  11530. // The group's content is no longer dirty
  11531. this._cacheGroupDirty = failedCount !== 0;
  11532. if (this.isCachedGroup) {
  11533. this._unbindCacheTarget();
  11534. }
  11535. else {
  11536. if (curVP) {
  11537. engine.setViewport(curVP);
  11538. }
  11539. }
  11540. // Restore saved states
  11541. engine.setAlphaTesting(curAlphaTest);
  11542. engine.setDepthWrite(curDepthWrite);
  11543. }
  11544. };
  11545. Group2D.prototype._setCacheGroupDirty = function () {
  11546. this._cacheGroupDirty = true;
  11547. };
  11548. Group2D.prototype._updateTransparentData = function () {
  11549. this.owner._addUpdateTransparentDataCount(1);
  11550. var rd = this._renderableData;
  11551. // Sort all the primitive from their depth, max (bottom) to min (top)
  11552. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  11553. var checkAndAddPrimInSegment = function (seg, tpiI) {
  11554. var tpi = rd._transparentPrimitives[tpiI];
  11555. // Fast rejection: if gii are different
  11556. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  11557. return false;
  11558. }
  11559. //let tpiZ = tpi._primitive.actualZOffset;
  11560. // We've made it so far, the tpi can be part of the segment, add it
  11561. tpi._transparentSegment = seg;
  11562. tpi._primitive._updateTransparentSegmentIndices(seg);
  11563. return true;
  11564. };
  11565. // Free the existing TransparentSegments
  11566. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  11567. var ts = _a[_i];
  11568. ts.dispose(this.owner.engine);
  11569. }
  11570. rd._transparentSegments.splice(0);
  11571. var prevSeg = null;
  11572. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  11573. var tpi = rd._transparentPrimitives[tpiI];
  11574. // Check if the Data in which the primitive is stored is not sorted properly
  11575. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  11576. tpi._groupInstanceInfo.sortTransparentData();
  11577. }
  11578. // Reset the segment, we have to create/rebuild it
  11579. tpi._transparentSegment = null;
  11580. // If there's a previous valid segment, check if this prim can be part of it
  11581. if (prevSeg) {
  11582. checkAndAddPrimInSegment(prevSeg, tpiI);
  11583. }
  11584. // If we couldn't insert in the adjacent segments, he have to create one
  11585. if (!tpi._transparentSegment) {
  11586. var ts = new BABYLON.TransparentSegment();
  11587. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  11588. var prim = tpi._primitive;
  11589. ts.startZ = prim.actualZOffset;
  11590. prim._updateTransparentSegmentIndices(ts);
  11591. ts.endZ = ts.startZ;
  11592. tpi._transparentSegment = ts;
  11593. rd._transparentSegments.push(ts);
  11594. }
  11595. // Update prevSeg
  11596. prevSeg = tpi._transparentSegment;
  11597. }
  11598. //rd._firstChangedPrim = null;
  11599. rd._transparentListChanged = false;
  11600. };
  11601. Group2D.prototype._renderTransparentData = function () {
  11602. var failedCount = 0;
  11603. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  11604. var rd = this._renderableData;
  11605. var useInstanced = this.owner.supportInstancedArray;
  11606. var length = rd._transparentSegments.length;
  11607. for (var i = 0; i < length; i++) {
  11608. context.instancedBuffers = null;
  11609. var ts = rd._transparentSegments[i];
  11610. var gii = ts.groupInsanceInfo;
  11611. var mrc = gii.modelRenderCache;
  11612. var engine = this.owner.engine;
  11613. var count = ts.endDataIndex - ts.startDataIndex;
  11614. // Use Instanced Array if it's supported and if there's at least minPartCountToUseInstancedArray prims to draw.
  11615. // We don't want to create an Instanced Buffer for less that minPartCountToUseInstancedArray prims
  11616. if (useInstanced && count >= this.owner.minPartCountToUseInstancedArray) {
  11617. if (!ts.partBuffers) {
  11618. var buffers = new Array();
  11619. for (var j = 0; j < gii.transparentData.length; j++) {
  11620. var gitd = gii.transparentData[j];
  11621. var dfa = gitd._partData;
  11622. var data = dfa.pack();
  11623. var stride = dfa.stride;
  11624. var neededSize = count * stride * 4;
  11625. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  11626. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  11627. engine.updateArrayBuffer(segData);
  11628. buffers.push(buffer);
  11629. }
  11630. ts.partBuffers = buffers;
  11631. }
  11632. else if (gii.transparentDirty) {
  11633. for (var j = 0; j < gii.transparentData.length; j++) {
  11634. var gitd = gii.transparentData[j];
  11635. var dfa = gitd._partData;
  11636. var data = dfa.pack();
  11637. var stride = dfa.stride;
  11638. var buffer = ts.partBuffers[j];
  11639. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  11640. engine.bindArrayBuffer(buffer);
  11641. engine.updateArrayBuffer(segData);
  11642. }
  11643. }
  11644. context.useInstancing = true;
  11645. context.instancesCount = count;
  11646. context.instancedBuffers = ts.partBuffers;
  11647. context.groupInfoPartData = gii.transparentData;
  11648. var renderFailed = !mrc.render(gii, context);
  11649. failedCount += renderFailed ? 1 : 0;
  11650. }
  11651. else {
  11652. context.useInstancing = false;
  11653. context.partDataStartIndex = ts.startDataIndex;
  11654. context.partDataEndIndex = ts.endDataIndex;
  11655. context.groupInfoPartData = gii.transparentData;
  11656. var renderFailed = !mrc.render(gii, context);
  11657. failedCount += renderFailed ? 1 : 0;
  11658. }
  11659. }
  11660. return failedCount;
  11661. };
  11662. Group2D.prototype._prepareContext = function (engine, context, gii) {
  11663. var gipd = null;
  11664. var setDirty;
  11665. var getDirty;
  11666. // Render Mode specifics
  11667. switch (context.renderMode) {
  11668. case BABYLON.Render2DContext.RenderModeOpaque:
  11669. {
  11670. if (!gii.hasOpaqueData) {
  11671. return null;
  11672. }
  11673. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  11674. getDirty = function () { return gii.opaqueDirty; };
  11675. context.groupInfoPartData = gii.opaqueData;
  11676. gipd = gii.opaqueData;
  11677. break;
  11678. }
  11679. case BABYLON.Render2DContext.RenderModeAlphaTest:
  11680. {
  11681. if (!gii.hasAlphaTestData) {
  11682. return null;
  11683. }
  11684. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  11685. getDirty = function () { return gii.alphaTestDirty; };
  11686. context.groupInfoPartData = gii.alphaTestData;
  11687. gipd = gii.alphaTestData;
  11688. break;
  11689. }
  11690. default:
  11691. throw new Error("_prepareContext is only for opaque or alphaTest");
  11692. }
  11693. var renderCount = 0;
  11694. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  11695. // Skip it if instanced arrays are not supported
  11696. if (this.owner.supportInstancedArray) {
  11697. // Flag for instancing
  11698. context.useInstancing = true;
  11699. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  11700. for (var i = 0; i < gipd.length; i++) {
  11701. var pid = gipd[i];
  11702. // If the instances of the model was changed, pack the data
  11703. var array = pid._partData;
  11704. var instanceData_1 = array.pack();
  11705. renderCount += array.usedElementCount;
  11706. // Compute the size the instance buffer should have
  11707. var neededSize = array.usedElementCount * array.stride * 4;
  11708. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  11709. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  11710. if (pid._partBuffer) {
  11711. engine.deleteInstancesBuffer(pid._partBuffer);
  11712. }
  11713. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  11714. pid._partBufferSize = neededSize;
  11715. setDirty(false);
  11716. // Update the WebGL buffer to match the new content of the instances data
  11717. engine.updateArrayBuffer(instanceData_1);
  11718. }
  11719. else if (getDirty()) {
  11720. // Update the WebGL buffer to match the new content of the instances data
  11721. engine.bindArrayBuffer(pid._partBuffer);
  11722. engine.updateArrayBuffer(instanceData_1);
  11723. }
  11724. }
  11725. setDirty(false);
  11726. }
  11727. else {
  11728. context.partDataStartIndex = 0;
  11729. // Find the first valid object to get the count
  11730. if (context.groupInfoPartData.length > 0) {
  11731. var i = 0;
  11732. while (!context.groupInfoPartData[i]) {
  11733. i++;
  11734. }
  11735. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  11736. }
  11737. }
  11738. return renderCount;
  11739. };
  11740. Group2D.prototype._setRenderingScale = function (scale) {
  11741. if (this._renderableData._renderingScale === scale) {
  11742. return;
  11743. }
  11744. this._renderableData._renderingScale = scale;
  11745. };
  11746. Group2D.prototype._bindCacheTarget = function () {
  11747. var curWidth;
  11748. var curHeight;
  11749. var rd = this._renderableData;
  11750. var rs = rd._renderingScale;
  11751. var noResizeScale = rd._noResizeOnScale;
  11752. var isCanvas = this.parent == null;
  11753. var scale;
  11754. if (noResizeScale) {
  11755. scale = isCanvas ? Group2D_1._uV : this.parent.actualScale;
  11756. }
  11757. else {
  11758. scale = this.actualScale;
  11759. }
  11760. if (isCanvas && this.owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS && this.owner.isScreenSpace) {
  11761. if (this.owner.designSize || this.owner.fitRenderingDevice) {
  11762. Group2D_1._s.width = this.owner.engine.getRenderWidth();
  11763. Group2D_1._s.height = this.owner.engine.getRenderHeight();
  11764. }
  11765. else {
  11766. Group2D_1._s.copyFrom(this.owner.size);
  11767. }
  11768. }
  11769. else {
  11770. Group2D_1._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  11771. Group2D_1._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  11772. }
  11773. var sizeChanged = !Group2D_1._s.equals(rd._cacheSize);
  11774. if (rd._cacheNode) {
  11775. var size = rd._cacheNode.contentSize;
  11776. // Check if we have to deallocate because the size is too small
  11777. if ((size.width < Group2D_1._s.width) || (size.height < Group2D_1._s.height)) {
  11778. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  11779. // For World space: no over-provisioning
  11780. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  11781. curWidth = Math.floor(Group2D_1._s.width * overprovisioning);
  11782. curHeight = Math.floor(Group2D_1._s.height * overprovisioning);
  11783. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  11784. rd._cacheTexture.freeRect(rd._cacheNode);
  11785. rd._cacheNode = null;
  11786. }
  11787. }
  11788. if (!rd._cacheNode) {
  11789. // Check if we have to allocate a rendering zone in the global cache texture
  11790. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  11791. rd._cacheNode = res.node;
  11792. rd._cacheTexture = res.texture;
  11793. if (rd._cacheRenderSprite) {
  11794. rd._cacheRenderSprite.dispose();
  11795. }
  11796. rd._cacheRenderSprite = res.sprite;
  11797. sizeChanged = true;
  11798. }
  11799. if (sizeChanged) {
  11800. rd._cacheSize.copyFrom(Group2D_1._s);
  11801. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  11802. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  11803. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  11804. }
  11805. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  11806. }
  11807. var n = rd._cacheNode;
  11808. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D_1._s, true);
  11809. };
  11810. Group2D.prototype._unbindCacheTarget = function () {
  11811. if (this._renderableData._cacheTexture) {
  11812. this._renderableData._cacheTexture.unbindTexture();
  11813. }
  11814. };
  11815. Group2D.prototype._spreadActualScaleDirty = function () {
  11816. if (this._renderableData && this._renderableData._cacheRenderSprite) {
  11817. this.handleGroupChanged(BABYLON.Prim2DBase.actualScaleProperty);
  11818. }
  11819. _super.prototype._spreadActualScaleDirty.call(this);
  11820. };
  11821. Group2D.prototype.handleGroupChanged = function (prop) {
  11822. // This method is only for cachedGroup
  11823. var rd = this._renderableData;
  11824. if (!rd) {
  11825. return;
  11826. }
  11827. var cachedSprite = rd._cacheRenderSprite;
  11828. if (!this.isCachedGroup || !cachedSprite) {
  11829. return;
  11830. }
  11831. // For now we only support these property changes
  11832. // TODO: add more! :)
  11833. switch (prop.id) {
  11834. case BABYLON.Prim2DBase.actualPositionProperty.id:
  11835. cachedSprite.actualPosition = this.actualPosition.clone();
  11836. if (cachedSprite.position != null) {
  11837. cachedSprite.position = cachedSprite.actualPosition.clone();
  11838. }
  11839. break;
  11840. case BABYLON.Prim2DBase.rotationProperty.id:
  11841. cachedSprite.rotation = this.rotation;
  11842. break;
  11843. case BABYLON.Prim2DBase.scaleProperty.id:
  11844. cachedSprite.scale = this.scale;
  11845. break;
  11846. case BABYLON.Prim2DBase.originProperty.id:
  11847. cachedSprite.origin = this.origin.clone();
  11848. break;
  11849. case Group2D_1.actualSizeProperty.id:
  11850. cachedSprite.size = this.actualSize.clone();
  11851. break;
  11852. }
  11853. };
  11854. Group2D.prototype.detectGroupStates = function () {
  11855. var isCanvas = this instanceof BABYLON.Canvas2D;
  11856. var canvasStrat = this.owner.cachingStrategy;
  11857. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  11858. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  11859. this._isRenderableGroup = isCanvas;
  11860. this._isCachedGroup = false;
  11861. }
  11862. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  11863. if (isCanvas) {
  11864. this._isRenderableGroup = true;
  11865. this._isCachedGroup = true;
  11866. }
  11867. else {
  11868. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  11869. this._isCachedGroup = false;
  11870. }
  11871. }
  11872. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  11873. if (isCanvas) {
  11874. this._isRenderableGroup = true;
  11875. this._isCachedGroup = false;
  11876. }
  11877. else {
  11878. if (this.hierarchyDepth === 1) {
  11879. this._isRenderableGroup = true;
  11880. this._isCachedGroup = true;
  11881. }
  11882. else {
  11883. this._isRenderableGroup = false;
  11884. this._isCachedGroup = false;
  11885. }
  11886. }
  11887. }
  11888. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  11889. if (isCanvas) {
  11890. this._isRenderableGroup = true;
  11891. this._isCachedGroup = false;
  11892. }
  11893. else {
  11894. var gcb = this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_OPTIONMASK;
  11895. if ((gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D_1.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  11896. this._isRenderableGroup = gcb === Group2D_1.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  11897. this._isCachedGroup = false;
  11898. }
  11899. if (gcb === Group2D_1.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  11900. this._isRenderableGroup = true;
  11901. this._isCachedGroup = true;
  11902. }
  11903. }
  11904. }
  11905. if (this._isRenderableGroup) {
  11906. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  11907. if (!this._renderableData) {
  11908. this._renderableData = new RenderableGroupData();
  11909. }
  11910. }
  11911. // If the group is tagged as renderable we add it to the renderable tree
  11912. if (this._isCachedGroup) {
  11913. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D_1.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  11914. var cur = this.parent;
  11915. while (cur) {
  11916. if (cur instanceof Group2D_1 && cur._isRenderableGroup) {
  11917. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  11918. cur._renderableData._childrenRenderableGroups.push(this);
  11919. }
  11920. break;
  11921. }
  11922. cur = cur.parent;
  11923. }
  11924. }
  11925. };
  11926. Object.defineProperty(Group2D.prototype, "_cachedTexture", {
  11927. get: function () {
  11928. if (this._renderableData) {
  11929. return this._renderableData._cacheTexture;
  11930. }
  11931. return null;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. return Group2D;
  11937. }(BABYLON.Prim2DBase));
  11938. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  11939. /**
  11940. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  11941. */
  11942. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  11943. /**
  11944. * When used, this group's content won't be cached, no matter which strategy used.
  11945. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  11946. */
  11947. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  11948. /**
  11949. * When used, the group's content will be cached in the nearest cached parent group/canvas
  11950. */
  11951. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  11952. /**
  11953. * 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
  11954. */
  11955. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  11956. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  11957. Group2D._uV = new BABYLON.Vector2(1, 1);
  11958. Group2D._s = BABYLON.Size.Zero();
  11959. Group2D._unS = new BABYLON.Vector2(1, 1);
  11960. __decorate([
  11961. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D_1.sizeProperty = pi; }, false, true)
  11962. ], Group2D.prototype, "size", null);
  11963. Group2D = Group2D_1 = __decorate([
  11964. BABYLON.className("Group2D", "BABYLON")
  11965. ], Group2D);
  11966. BABYLON.Group2D = Group2D;
  11967. var RenderableGroupData = (function () {
  11968. function RenderableGroupData() {
  11969. this._primDirtyList = new Array();
  11970. this._primNewDirtyList = new Array();
  11971. this._childrenRenderableGroups = new Array();
  11972. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  11973. this._transparentPrimitives = new Array();
  11974. this._transparentSegments = new Array();
  11975. this._transparentListChanged = false;
  11976. this._cacheNode = null;
  11977. this._cacheTexture = null;
  11978. this._cacheRenderSprite = null;
  11979. this._renderingScale = 1;
  11980. this._cacheNodeUVs = null;
  11981. this._cacheNodeUVsChangedObservable = null;
  11982. this._cacheSize = BABYLON.Size.Zero();
  11983. this._useMipMap = false;
  11984. this._anisotropicLevel = 1;
  11985. this._noResizeOnScale = false;
  11986. }
  11987. RenderableGroupData.prototype.dispose = function (owner) {
  11988. var engine = owner.engine;
  11989. if (this._cacheRenderSprite) {
  11990. this._cacheRenderSprite.dispose();
  11991. this._cacheRenderSprite = null;
  11992. }
  11993. if (this._cacheTexture && this._cacheNode) {
  11994. this._cacheTexture.freeRect(this._cacheNode);
  11995. this._cacheTexture = null;
  11996. this._cacheNode = null;
  11997. }
  11998. if (this._primDirtyList) {
  11999. this._primDirtyList.splice(0);
  12000. this._primDirtyList = null;
  12001. }
  12002. if (this._renderGroupInstancesInfo) {
  12003. this._renderGroupInstancesInfo.forEach(function (k, v) {
  12004. v.dispose();
  12005. });
  12006. this._renderGroupInstancesInfo = null;
  12007. }
  12008. if (this._cacheNodeUVsChangedObservable) {
  12009. this._cacheNodeUVsChangedObservable.clear();
  12010. this._cacheNodeUVsChangedObservable = null;
  12011. }
  12012. if (this._transparentSegments) {
  12013. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  12014. var ts = _a[_i];
  12015. ts.dispose(engine);
  12016. }
  12017. this._transparentSegments.splice(0);
  12018. this._transparentSegments = null;
  12019. }
  12020. };
  12021. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  12022. var tpi = new TransparentPrimitiveInfo();
  12023. tpi._primitive = prim;
  12024. tpi._groupInstanceInfo = gii;
  12025. tpi._transparentSegment = null;
  12026. this._transparentPrimitives.push(tpi);
  12027. this._transparentListChanged = true;
  12028. return tpi;
  12029. };
  12030. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  12031. var index = this._transparentPrimitives.indexOf(tpi);
  12032. if (index !== -1) {
  12033. this._transparentPrimitives.splice(index, 1);
  12034. this._transparentListChanged = true;
  12035. }
  12036. };
  12037. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  12038. this._transparentListChanged = true;
  12039. //this.updateSmallestZChangedPrim(tpi);
  12040. };
  12041. return RenderableGroupData;
  12042. }());
  12043. BABYLON.RenderableGroupData = RenderableGroupData;
  12044. var TransparentPrimitiveInfo = (function () {
  12045. function TransparentPrimitiveInfo() {
  12046. }
  12047. return TransparentPrimitiveInfo;
  12048. }());
  12049. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  12050. var Group2D_1;
  12051. })(BABYLON || (BABYLON = {}));
  12052. //# sourceMappingURL=babylon.group2d.js.map
  12053. var __extends = (this && this.__extends) || function (d, b) {
  12054. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12055. function __() { this.constructor = d; }
  12056. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12057. };
  12058. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12059. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12060. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12061. 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;
  12062. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12063. };
  12064. var BABYLON;
  12065. (function (BABYLON) {
  12066. var WireFrame2DRenderCache = (function (_super) {
  12067. __extends(WireFrame2DRenderCache, _super);
  12068. function WireFrame2DRenderCache() {
  12069. var _this = _super !== null && _super.apply(this, arguments) || this;
  12070. _this.effectsReady = false;
  12071. _this.vb = null;
  12072. _this.vtxCount = 0;
  12073. _this.instancingAttributes = null;
  12074. _this.effect = null;
  12075. _this.effectInstanced = null;
  12076. return _this;
  12077. }
  12078. WireFrame2DRenderCache.prototype.render = function (instanceInfo, context) {
  12079. // Do nothing if the shader is still loading/preparing
  12080. if (!this.effectsReady) {
  12081. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  12082. return false;
  12083. }
  12084. this.effectsReady = true;
  12085. }
  12086. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  12087. var canvas = instanceInfo.owner.owner;
  12088. var engine = canvas.engine;
  12089. var cur = engine.getAlphaMode();
  12090. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  12091. engine.enableEffect(effect);
  12092. engine.bindBuffersDirectly(this.vb, null, [2, 4], 24, effect);
  12093. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12094. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12095. }
  12096. var pid = context.groupInfoPartData[0];
  12097. if (context.useInstancing) {
  12098. if (!this.instancingAttributes) {
  12099. this.instancingAttributes = this.loadInstancingAttributes(WireFrame2D.WIREFRAME2D_MAINPARTID, effect);
  12100. }
  12101. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  12102. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12103. canvas._addDrawCallCount(1, context.renderMode);
  12104. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  12105. engine.drawUnIndexed(false, 0, this.vtxCount, count);
  12106. // engine.draw(true, 0, 6, count);
  12107. engine.unbindInstanceAttributes();
  12108. }
  12109. else {
  12110. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12111. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12112. this.setupUniforms(effect, 0, pid._partData, i);
  12113. engine.drawUnIndexed(false, 0, this.vtxCount);
  12114. }
  12115. }
  12116. engine.setAlphaMode(cur, true);
  12117. return true;
  12118. };
  12119. WireFrame2DRenderCache.prototype.updateModelRenderCache = function (prim) {
  12120. var w = prim;
  12121. w._updateVertexBuffer(this);
  12122. return true;
  12123. };
  12124. WireFrame2DRenderCache.prototype.dispose = function () {
  12125. if (!_super.prototype.dispose.call(this)) {
  12126. return false;
  12127. }
  12128. if (this.vb) {
  12129. this._engine._releaseBuffer(this.vb);
  12130. this.vb = null;
  12131. }
  12132. this.effect = null;
  12133. this.effectInstanced = null;
  12134. return true;
  12135. };
  12136. return WireFrame2DRenderCache;
  12137. }(BABYLON.ModelRenderCache));
  12138. BABYLON.WireFrame2DRenderCache = WireFrame2DRenderCache;
  12139. var WireFrameVertex2D = (function () {
  12140. function WireFrameVertex2D(p, c) {
  12141. if (c === void 0) { c = null; }
  12142. this.fromVector2(p);
  12143. if (c != null) {
  12144. this.fromColor4(c);
  12145. }
  12146. else {
  12147. this.r = this.g = this.b = this.a = 1;
  12148. }
  12149. }
  12150. WireFrameVertex2D.prototype.fromVector2 = function (p) {
  12151. this.x = p.x;
  12152. this.y = p.y;
  12153. };
  12154. WireFrameVertex2D.prototype.fromColor3 = function (c) {
  12155. this.r = c.r;
  12156. this.g = c.g;
  12157. this.b = c.b;
  12158. this.a = 1;
  12159. };
  12160. WireFrameVertex2D.prototype.fromColor4 = function (c) {
  12161. this.r = c.r;
  12162. this.g = c.g;
  12163. this.b = c.b;
  12164. this.a = c.a;
  12165. };
  12166. return WireFrameVertex2D;
  12167. }());
  12168. WireFrameVertex2D = __decorate([
  12169. BABYLON.className("WireFrameVertex2D", "BABYLON")
  12170. ], WireFrameVertex2D);
  12171. BABYLON.WireFrameVertex2D = WireFrameVertex2D;
  12172. var WireFrameGroup2D = (function () {
  12173. /**
  12174. * Construct a WireFrameGroup2D object
  12175. * @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.
  12176. * @param defaultColor specify the default color that will be used when a vertex is pushed, white will be used if not specified.
  12177. */
  12178. function WireFrameGroup2D(id, defaultColor) {
  12179. if (id === void 0) { id = null; }
  12180. if (defaultColor === void 0) { defaultColor = null; }
  12181. this._id = (id == null) ? BABYLON.Tools.RandomId() : id;
  12182. this._uid = BABYLON.Tools.RandomId();
  12183. this._defaultColor = (defaultColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : defaultColor;
  12184. this._buildingStrip = false;
  12185. this._vertices = new Array();
  12186. }
  12187. Object.defineProperty(WireFrameGroup2D.prototype, "uid", {
  12188. get: function () {
  12189. return this._uid;
  12190. },
  12191. enumerable: true,
  12192. configurable: true
  12193. });
  12194. Object.defineProperty(WireFrameGroup2D.prototype, "id", {
  12195. /**
  12196. * Retrieve the ID of the group
  12197. */
  12198. get: function () {
  12199. return this._id;
  12200. },
  12201. enumerable: true,
  12202. configurable: true
  12203. });
  12204. /**
  12205. * Push a vertex in the array of vertices.
  12206. * 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.
  12207. * @param p Position of the vertex
  12208. * @param c Color of the vertex, if null the default color of the group will be used
  12209. */
  12210. WireFrameGroup2D.prototype.pushVertex = function (p, c) {
  12211. if (c === void 0) { c = null; }
  12212. var v = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  12213. this._vertices.push(v);
  12214. if (this._buildingStrip) {
  12215. var v2 = new WireFrameVertex2D(p, (c == null) ? this._defaultColor : c);
  12216. this._vertices.push(v2);
  12217. }
  12218. };
  12219. /**
  12220. * 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!!!
  12221. * @param p Position of the vertex
  12222. * @param c Color of the vertex, if null the default color of the group will be used
  12223. */
  12224. WireFrameGroup2D.prototype.startLineStrip = function (p, c) {
  12225. if (c === void 0) { c = null; }
  12226. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  12227. this._buildingStrip = true;
  12228. };
  12229. /**
  12230. * Close the Strip by storing a last vertex
  12231. * @param p Position of the vertex
  12232. * @param c Color of the vertex, if null the default color of the group will be used
  12233. */
  12234. WireFrameGroup2D.prototype.endLineStrip = function (p, c) {
  12235. if (c === void 0) { c = null; }
  12236. this._buildingStrip = false;
  12237. this.pushVertex(p, (c == null) ? this._defaultColor : c);
  12238. };
  12239. Object.defineProperty(WireFrameGroup2D.prototype, "vertices", {
  12240. /**
  12241. * Access to the array of Vertices, you can manipulate its content but BEWARE of what you're doing!
  12242. */
  12243. get: function () {
  12244. return this._vertices;
  12245. },
  12246. enumerable: true,
  12247. configurable: true
  12248. });
  12249. return WireFrameGroup2D;
  12250. }());
  12251. WireFrameGroup2D = __decorate([
  12252. BABYLON.className("WireFrameGroup2D", "BABYLON")
  12253. ], WireFrameGroup2D);
  12254. BABYLON.WireFrameGroup2D = WireFrameGroup2D;
  12255. var WireFrame2D = WireFrame2D_1 = (function (_super) {
  12256. __extends(WireFrame2D, _super);
  12257. /**
  12258. * Create an WireFrame 2D primitive
  12259. * @param wireFrameGroups an array of WireFrameGroup.
  12260. * @param settings a combination of settings, possible ones are
  12261. * - 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)
  12262. * - children: an array of direct children
  12263. * - id a text identifier, for information purpose
  12264. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  12265. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12266. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12267. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  12268. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12269. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12270. * - zOrder: override the zOrder with the specified value
  12271. * - origin: define the normalized origin point location, default [0.5;0.5]
  12272. * - alignToPixel: the rendered lines will be aligned to the rendering device' pixels
  12273. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  12274. * - 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.
  12275. * - 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.
  12276. * - 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!
  12277. * - 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.
  12278. * - 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).
  12279. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12280. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12281. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12282. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12283. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12284. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12285. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12286. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12287. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12288. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12289. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12290. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12291. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12292. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12293. */
  12294. function WireFrame2D(wireFrameGroups, settings) {
  12295. var _this = this;
  12296. if (!settings) {
  12297. settings = {};
  12298. }
  12299. _this = _super.call(this, settings) || this;
  12300. _this._wireFrameGroups = new BABYLON.StringDictionary();
  12301. for (var _i = 0, wireFrameGroups_1 = wireFrameGroups; _i < wireFrameGroups_1.length; _i++) {
  12302. var wfg = wireFrameGroups_1[_i];
  12303. _this._wireFrameGroups.add(wfg.id, wfg);
  12304. }
  12305. _this._vtxTransparent = false;
  12306. if (settings.size != null) {
  12307. _this.size = settings.size;
  12308. }
  12309. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  12310. return _this;
  12311. }
  12312. Object.defineProperty(WireFrame2D.prototype, "wireFrameGroups", {
  12313. get: function () {
  12314. return this._wireFrameGroups;
  12315. },
  12316. enumerable: true,
  12317. configurable: true
  12318. });
  12319. /**
  12320. * If you change the content of the wireFrameGroups you MUST call this method for the changes to be reflected during rendering
  12321. */
  12322. WireFrame2D.prototype.wireFrameGroupsDirty = function () {
  12323. this._setFlags(BABYLON.SmartPropertyPrim.flagModelUpdate);
  12324. this.onPrimBecomesDirty();
  12325. };
  12326. Object.defineProperty(WireFrame2D.prototype, "size", {
  12327. get: function () {
  12328. if (this._size == null) {
  12329. this._computeMinMaxTrans();
  12330. }
  12331. return this._size;
  12332. },
  12333. set: function (value) {
  12334. this.internalSetSize(value);
  12335. },
  12336. enumerable: true,
  12337. configurable: true
  12338. });
  12339. WireFrame2D.prototype.updateLevelBoundingInfo = function () {
  12340. var v = this._computeMinMaxTrans();
  12341. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(v.x, v.z, v.y, v.w, this._levelBoundingInfo);
  12342. return true;
  12343. };
  12344. WireFrame2D.prototype.levelIntersect = function (intersectInfo) {
  12345. // TODO !
  12346. return true;
  12347. };
  12348. Object.defineProperty(WireFrame2D.prototype, "alignToPixel", {
  12349. /**
  12350. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  12351. */
  12352. get: function () {
  12353. return this._alignToPixel;
  12354. },
  12355. set: function (value) {
  12356. this._alignToPixel = value;
  12357. },
  12358. enumerable: true,
  12359. configurable: true
  12360. });
  12361. WireFrame2D.prototype.createModelRenderCache = function (modelKey) {
  12362. var renderCache = new WireFrame2DRenderCache(this.owner.engine, modelKey);
  12363. return renderCache;
  12364. };
  12365. WireFrame2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  12366. var renderCache = modelRenderCache;
  12367. var engine = this.owner.engine;
  12368. // Create the VertexBuffer
  12369. this._updateVertexBuffer(renderCache);
  12370. // 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
  12371. var ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], true);
  12372. if (ei) {
  12373. renderCache.effectInstanced = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12374. }
  12375. ei = this.getDataPartEffectInfo(WireFrame2D_1.WIREFRAME2D_MAINPARTID, ["pos", "col"], [], false);
  12376. renderCache.effect = engine.createEffect("wireframe2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12377. return renderCache;
  12378. };
  12379. WireFrame2D.prototype._updateVertexBuffer = function (mrc) {
  12380. var engine = this.owner.engine;
  12381. if (mrc.vb != null) {
  12382. engine._releaseBuffer(mrc.vb);
  12383. }
  12384. var vtxCount = 0;
  12385. this._wireFrameGroups.forEach(function (k, v) { return vtxCount += v.vertices.length; });
  12386. var vb = new Float32Array(vtxCount * 6);
  12387. var i = 0;
  12388. this._wireFrameGroups.forEach(function (k, v) {
  12389. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  12390. var vtx = _a[_i];
  12391. vb[i++] = vtx.x;
  12392. vb[i++] = vtx.y;
  12393. vb[i++] = vtx.r;
  12394. vb[i++] = vtx.g;
  12395. vb[i++] = vtx.b;
  12396. vb[i++] = vtx.a;
  12397. }
  12398. });
  12399. mrc.vb = engine.createVertexBuffer(vb);
  12400. mrc.vtxCount = vtxCount;
  12401. };
  12402. WireFrame2D.prototype.refreshInstanceDataPart = function (part) {
  12403. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  12404. return false;
  12405. }
  12406. if (part.id === WireFrame2D_1.WIREFRAME2D_MAINPARTID) {
  12407. var d = this._instanceDataParts[0];
  12408. d.properties = new BABYLON.Vector3(this.alignToPixel ? 1 : 0, 2 / this.renderGroup.actualWidth, 2 / this.renderGroup.actualHeight);
  12409. }
  12410. return true;
  12411. };
  12412. WireFrame2D.prototype._computeMinMaxTrans = function () {
  12413. var xmin = Number.MAX_VALUE;
  12414. var xmax = Number.MIN_VALUE;
  12415. var ymin = Number.MAX_VALUE;
  12416. var ymax = Number.MIN_VALUE;
  12417. var transparent = false;
  12418. this._wireFrameGroups.forEach(function (k, v) {
  12419. for (var _i = 0, _a = v.vertices; _i < _a.length; _i++) {
  12420. var vtx = _a[_i];
  12421. xmin = Math.min(xmin, vtx.x);
  12422. xmax = Math.max(xmax, vtx.x);
  12423. ymin = Math.min(ymin, vtx.y);
  12424. ymax = Math.max(ymax, vtx.y);
  12425. if (vtx.a < 1) {
  12426. transparent = true;
  12427. }
  12428. }
  12429. });
  12430. this._vtxTransparent = transparent;
  12431. this._size = new BABYLON.Size(xmax - xmin, ymax - ymin);
  12432. return new BABYLON.Vector4(xmin, ymin, xmax, ymax);
  12433. };
  12434. WireFrame2D.prototype.createInstanceDataParts = function () {
  12435. return [new WireFrame2DInstanceData(WireFrame2D_1.WIREFRAME2D_MAINPARTID)];
  12436. };
  12437. return WireFrame2D;
  12438. }(BABYLON.RenderablePrim2D));
  12439. WireFrame2D.WIREFRAME2D_MAINPARTID = 1;
  12440. __decorate([
  12441. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return WireFrame2D_1.wireFrameGroupsProperty = pi; })
  12442. ], WireFrame2D.prototype, "wireFrameGroups", null);
  12443. WireFrame2D = WireFrame2D_1 = __decorate([
  12444. BABYLON.className("WireFrame2D", "BABYLON")
  12445. ], WireFrame2D);
  12446. BABYLON.WireFrame2D = WireFrame2D;
  12447. var WireFrame2DInstanceData = (function (_super) {
  12448. __extends(WireFrame2DInstanceData, _super);
  12449. function WireFrame2DInstanceData(partId) {
  12450. return _super.call(this, partId, 1) || this;
  12451. }
  12452. Object.defineProperty(WireFrame2DInstanceData.prototype, "properties", {
  12453. // the properties is for now the alignedToPixel value
  12454. get: function () {
  12455. return null;
  12456. },
  12457. set: function (value) {
  12458. },
  12459. enumerable: true,
  12460. configurable: true
  12461. });
  12462. return WireFrame2DInstanceData;
  12463. }(BABYLON.InstanceDataBase));
  12464. __decorate([
  12465. BABYLON.instanceData()
  12466. ], WireFrame2DInstanceData.prototype, "properties", null);
  12467. BABYLON.WireFrame2DInstanceData = WireFrame2DInstanceData;
  12468. var WireFrame2D_1;
  12469. })(BABYLON || (BABYLON = {}));
  12470. //# sourceMappingURL=babylon.wireFrame2d.js.map
  12471. var __extends = (this && this.__extends) || function (d, b) {
  12472. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12473. function __() { this.constructor = d; }
  12474. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12475. };
  12476. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12477. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12478. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12479. 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;
  12480. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12481. };
  12482. var BABYLON;
  12483. (function (BABYLON) {
  12484. var Rectangle2DRenderCache = (function (_super) {
  12485. __extends(Rectangle2DRenderCache, _super);
  12486. function Rectangle2DRenderCache(engine, modelKey) {
  12487. var _this = _super.call(this, engine, modelKey) || this;
  12488. _this.effectsReady = false;
  12489. _this.fillVB = null;
  12490. _this.fillIB = null;
  12491. _this.fillIndicesCount = 0;
  12492. _this.instancingFillAttributes = null;
  12493. _this.effectFill = null;
  12494. _this.effectFillInstanced = null;
  12495. _this.borderVB = null;
  12496. _this.borderIB = null;
  12497. _this.borderIndicesCount = 0;
  12498. _this.instancingBorderAttributes = null;
  12499. _this.effectBorder = null;
  12500. _this.effectBorderInstanced = null;
  12501. return _this;
  12502. }
  12503. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  12504. // Do nothing if the shader is still loading/preparing
  12505. if (!this.effectsReady) {
  12506. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  12507. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  12508. return false;
  12509. }
  12510. this.effectsReady = true;
  12511. }
  12512. var canvas = instanceInfo.owner.owner;
  12513. var engine = canvas.engine;
  12514. var depthFunction = 0;
  12515. if (this.effectFill && this.effectBorder) {
  12516. depthFunction = engine.getDepthFunction();
  12517. engine.setDepthFunctionToLessOrEqual();
  12518. }
  12519. var curAlphaMode = engine.getAlphaMode();
  12520. if (this.effectFill) {
  12521. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  12522. var pid = context.groupInfoPartData[partIndex];
  12523. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12524. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12525. }
  12526. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  12527. engine.enableEffect(effect);
  12528. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  12529. if (context.useInstancing) {
  12530. if (!this.instancingFillAttributes) {
  12531. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  12532. }
  12533. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  12534. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12535. canvas._addDrawCallCount(1, context.renderMode);
  12536. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  12537. engine.draw(true, 0, this.fillIndicesCount, count);
  12538. engine.unbindInstanceAttributes();
  12539. }
  12540. else {
  12541. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12542. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12543. this.setupUniforms(effect, partIndex, pid._partData, i);
  12544. engine.draw(true, 0, this.fillIndicesCount);
  12545. }
  12546. }
  12547. }
  12548. if (this.effectBorder) {
  12549. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  12550. var pid = context.groupInfoPartData[partIndex];
  12551. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  12552. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  12553. }
  12554. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  12555. engine.enableEffect(effect);
  12556. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  12557. if (context.useInstancing) {
  12558. if (!this.instancingBorderAttributes) {
  12559. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  12560. }
  12561. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  12562. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  12563. canvas._addDrawCallCount(1, context.renderMode);
  12564. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  12565. engine.draw(true, 0, this.borderIndicesCount, count);
  12566. engine.unbindInstanceAttributes();
  12567. }
  12568. else {
  12569. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  12570. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  12571. this.setupUniforms(effect, partIndex, pid._partData, i);
  12572. engine.draw(true, 0, this.borderIndicesCount);
  12573. }
  12574. }
  12575. }
  12576. engine.setAlphaMode(curAlphaMode, true);
  12577. if (this.effectFill && this.effectBorder) {
  12578. engine.setDepthFunction(depthFunction);
  12579. }
  12580. return true;
  12581. };
  12582. Rectangle2DRenderCache.prototype.dispose = function () {
  12583. if (!_super.prototype.dispose.call(this)) {
  12584. return false;
  12585. }
  12586. if (this.fillVB) {
  12587. this._engine._releaseBuffer(this.fillVB);
  12588. this.fillVB = null;
  12589. }
  12590. if (this.fillIB) {
  12591. this._engine._releaseBuffer(this.fillIB);
  12592. this.fillIB = null;
  12593. }
  12594. this.effectFill = null;
  12595. this.effectFillInstanced = null;
  12596. this.effectBorder = null;
  12597. this.effectBorderInstanced = null;
  12598. if (this.borderVB) {
  12599. this._engine._releaseBuffer(this.borderVB);
  12600. this.borderVB = null;
  12601. }
  12602. if (this.borderIB) {
  12603. this._engine._releaseBuffer(this.borderIB);
  12604. this.borderIB = null;
  12605. }
  12606. return true;
  12607. };
  12608. return Rectangle2DRenderCache;
  12609. }(BABYLON.ModelRenderCache));
  12610. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  12611. var Rectangle2DInstanceData = (function (_super) {
  12612. __extends(Rectangle2DInstanceData, _super);
  12613. function Rectangle2DInstanceData(partId) {
  12614. return _super.call(this, partId, 1) || this;
  12615. }
  12616. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  12617. get: function () {
  12618. return null;
  12619. },
  12620. set: function (value) {
  12621. },
  12622. enumerable: true,
  12623. configurable: true
  12624. });
  12625. return Rectangle2DInstanceData;
  12626. }(BABYLON.Shape2DInstanceData));
  12627. __decorate([
  12628. BABYLON.instanceData()
  12629. ], Rectangle2DInstanceData.prototype, "properties", null);
  12630. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  12631. var Rectangle2D = Rectangle2D_1 = (function (_super) {
  12632. __extends(Rectangle2D, _super);
  12633. /**
  12634. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  12635. * @param settings a combination of settings, possible ones are
  12636. * - 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)
  12637. * - children: an array of direct children
  12638. * - id a text identifier, for information purpose
  12639. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  12640. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  12641. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  12642. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  12643. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  12644. * - zOrder: override the zOrder with the specified value
  12645. * - origin: define the normalized origin point location, default [0.5;0.5]
  12646. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  12647. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  12648. * - 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)
  12649. * - 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)
  12650. * - borderThickness: the thickness of the drawn border, default is 1.
  12651. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  12652. * - 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.
  12653. * - 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.
  12654. * - 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!
  12655. * - 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.
  12656. * - 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).
  12657. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  12658. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12659. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12660. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12661. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12662. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  12663. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  12664. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  12665. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  12666. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12667. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12668. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12669. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12670. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12671. */
  12672. function Rectangle2D(settings) {
  12673. var _this = this;
  12674. // Avoid checking every time if the object exists
  12675. if (settings == null) {
  12676. settings = {};
  12677. }
  12678. _this = _super.call(this, settings) || this;
  12679. if (settings.size != null) {
  12680. _this.size = settings.size;
  12681. }
  12682. else if (settings.width || settings.height) {
  12683. var size = new BABYLON.Size(settings.width, settings.height);
  12684. _this.size = size;
  12685. }
  12686. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  12687. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  12688. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  12689. //this.size = size;
  12690. _this.roundRadius = roundRadius;
  12691. _this.borderThickness = borderThickness;
  12692. return _this;
  12693. }
  12694. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  12695. get: function () {
  12696. return this._notRounded;
  12697. },
  12698. set: function (value) {
  12699. this._notRounded = value;
  12700. },
  12701. enumerable: true,
  12702. configurable: true
  12703. });
  12704. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  12705. get: function () {
  12706. return this._roundRadius;
  12707. },
  12708. set: function (value) {
  12709. this._roundRadius = value;
  12710. this.notRounded = value === 0;
  12711. this._positioningDirty();
  12712. },
  12713. enumerable: true,
  12714. configurable: true
  12715. });
  12716. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  12717. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  12718. if (this.notRounded) {
  12719. return true;
  12720. }
  12721. // 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.
  12722. // 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)
  12723. // 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.
  12724. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  12725. var size = this.size;
  12726. Rectangle2D_1._i0.x = intersectInfo._localPickPosition.x;
  12727. Rectangle2D_1._i0.y = intersectInfo._localPickPosition.y;
  12728. var rr = this.roundRadius;
  12729. var rrs = rr * rr;
  12730. // Check if the point is in the bottom/left quarter area
  12731. Rectangle2D_1._i1.x = rr;
  12732. Rectangle2D_1._i1.y = rr;
  12733. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  12734. // Compute the intersection point in the quarter local space
  12735. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  12736. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  12737. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  12738. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  12739. }
  12740. // Check if the point is in the top/left quarter area
  12741. Rectangle2D_1._i1.x = rr;
  12742. Rectangle2D_1._i1.y = size.height - rr;
  12743. if (Rectangle2D_1._i0.x <= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  12744. // Compute the intersection point in the quarter local space
  12745. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  12746. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  12747. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  12748. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  12749. }
  12750. // Check if the point is in the top/right quarter area
  12751. Rectangle2D_1._i1.x = size.width - rr;
  12752. Rectangle2D_1._i1.y = size.height - rr;
  12753. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y >= Rectangle2D_1._i1.y) {
  12754. // Compute the intersection point in the quarter local space
  12755. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  12756. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  12757. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  12758. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  12759. }
  12760. // Check if the point is in the bottom/right quarter area
  12761. Rectangle2D_1._i1.x = size.width - rr;
  12762. Rectangle2D_1._i1.y = rr;
  12763. if (Rectangle2D_1._i0.x >= Rectangle2D_1._i1.x && Rectangle2D_1._i0.y <= Rectangle2D_1._i1.y) {
  12764. // Compute the intersection point in the quarter local space
  12765. Rectangle2D_1._i2.x = Rectangle2D_1._i0.x - Rectangle2D_1._i1.x;
  12766. Rectangle2D_1._i2.y = Rectangle2D_1._i0.y - Rectangle2D_1._i1.y;
  12767. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  12768. return Rectangle2D_1._i2.lengthSquared() <= rrs;
  12769. }
  12770. // At any other locations the point is guarantied to be inside
  12771. return true;
  12772. };
  12773. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  12774. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  12775. return true;
  12776. };
  12777. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  12778. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  12779. return renderCache;
  12780. };
  12781. Rectangle2D.prototype.updateTriArray = function () {
  12782. // Not Rounded = sharp edge rect, the default implementation is the right one!
  12783. if (this.notRounded) {
  12784. _super.prototype.updateTriArray.call(this);
  12785. return;
  12786. }
  12787. // Rounded Corner? It's more complicated! :)
  12788. var subDiv = Rectangle2D_1.roundSubdivisions * 4;
  12789. if (this._primTriArray == null) {
  12790. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  12791. }
  12792. else {
  12793. this._primTriArray.clear(subDiv);
  12794. }
  12795. var size = this.actualSize;
  12796. var w = size.width;
  12797. var h = size.height;
  12798. var r = this.roundRadius;
  12799. var rsub0 = subDiv * 0.25;
  12800. var rsub1 = subDiv * 0.50;
  12801. var rsub2 = subDiv * 0.75;
  12802. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  12803. var twopi = Math.PI * 2;
  12804. var nru = r / w;
  12805. var nrv = r / h;
  12806. var computePos = function (index, p) {
  12807. // right/bottom
  12808. if (index < rsub0) {
  12809. p.x = 1.0 - nru;
  12810. p.y = nrv;
  12811. }
  12812. else if (index < rsub1) {
  12813. p.x = nru;
  12814. p.y = nrv;
  12815. }
  12816. else if (index < rsub2) {
  12817. p.x = nru;
  12818. p.y = 1.0 - nrv;
  12819. }
  12820. else {
  12821. p.x = 1.0 - nru;
  12822. p.y = 1.0 - nrv;
  12823. }
  12824. var angle = twopi - (index * twopi / (subDiv - 0.5));
  12825. p.x += Math.cos(angle) * nru;
  12826. p.y += Math.sin(angle) * nrv;
  12827. p.x *= w;
  12828. p.y *= h;
  12829. };
  12830. console.log("Genetre TriList for " + this.id);
  12831. var first = BABYLON.Vector2.Zero();
  12832. var cur = BABYLON.Vector2.Zero();
  12833. computePos(0, first);
  12834. var prev = first.clone();
  12835. for (var index = 1; index < subDiv; index++) {
  12836. computePos(index, cur);
  12837. this._primTriArray.storeTriangle(index - 1, center, prev, cur);
  12838. console.log(index - 1 + ", " + center + ", " + prev + ", " + cur);
  12839. prev.copyFrom(cur);
  12840. }
  12841. this._primTriArray.storeTriangle(subDiv - 1, center, first, prev);
  12842. console.log(subDiv - 1 + ", " + center + ", " + prev + ", " + first);
  12843. };
  12844. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  12845. var renderCache = modelRenderCache;
  12846. var engine = this.owner.engine;
  12847. // Need to create WebGL resources for fill part?
  12848. if (this.fill) {
  12849. var vbSize = ((this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4) + 1;
  12850. var vb = new Float32Array(vbSize);
  12851. for (var i = 0; i < vbSize; i++) {
  12852. vb[i] = i;
  12853. }
  12854. renderCache.fillVB = engine.createVertexBuffer(vb);
  12855. var triCount = vbSize - 1;
  12856. var ib = new Float32Array(triCount * 3);
  12857. for (var i = 0; i < triCount; i++) {
  12858. ib[i * 3 + 0] = 0;
  12859. ib[i * 3 + 2] = i + 1;
  12860. ib[i * 3 + 1] = i + 2;
  12861. }
  12862. ib[triCount * 3 - 2] = 1;
  12863. renderCache.fillIB = engine.createIndexBuffer(ib);
  12864. renderCache.fillIndicesCount = triCount * 3;
  12865. // 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
  12866. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  12867. if (ei) {
  12868. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12869. }
  12870. // Get the non instanced version
  12871. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  12872. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12873. }
  12874. // Need to create WebGL resource for border part?
  12875. if (this.border) {
  12876. var vbSize = (this.notRounded ? 1 : Rectangle2D_1.roundSubdivisions) * 4 * 2;
  12877. var vb = new Float32Array(vbSize);
  12878. for (var i = 0; i < vbSize; i++) {
  12879. vb[i] = i;
  12880. }
  12881. renderCache.borderVB = engine.createVertexBuffer(vb);
  12882. var triCount = vbSize;
  12883. var rs = triCount / 2;
  12884. var ib = new Float32Array(triCount * 3);
  12885. for (var i = 0; i < rs; i++) {
  12886. var r0 = i;
  12887. var r1 = (i + 1) % rs;
  12888. ib[i * 6 + 0] = rs + r1;
  12889. ib[i * 6 + 1] = rs + r0;
  12890. ib[i * 6 + 2] = r0;
  12891. ib[i * 6 + 3] = r1;
  12892. ib[i * 6 + 4] = rs + r1;
  12893. ib[i * 6 + 5] = r0;
  12894. }
  12895. renderCache.borderIB = engine.createIndexBuffer(ib);
  12896. renderCache.borderIndicesCount = triCount * 3;
  12897. // 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
  12898. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  12899. if (ei) {
  12900. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12901. }
  12902. // Get the non instanced version
  12903. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  12904. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  12905. }
  12906. return renderCache;
  12907. };
  12908. // 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
  12909. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  12910. // Fall back to default implementation if there's no round Radius
  12911. if (this._notRounded) {
  12912. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  12913. }
  12914. else {
  12915. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  12916. initialContentPosition.x = initialContentPosition.y = rr;
  12917. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  12918. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  12919. initialContentPosition.z = primSize.width - (initialContentPosition.x + initialContentArea.width);
  12920. initialContentPosition.w = primSize.height - (initialContentPosition.y + initialContentArea.height);
  12921. }
  12922. };
  12923. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, paddingOffset, newPrimSize) {
  12924. // Fall back to default implementation if there's no round Radius
  12925. if (this._notRounded) {
  12926. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, paddingOffset, newPrimSize);
  12927. }
  12928. else {
  12929. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  12930. newPrimSize.copyFrom(primSize);
  12931. newPrimSize.width += rr * 2;
  12932. newPrimSize.height += rr * 2;
  12933. paddingOffset.x += rr;
  12934. paddingOffset.y += rr;
  12935. paddingOffset.z += rr;
  12936. paddingOffset.w += rr;
  12937. }
  12938. };
  12939. Rectangle2D.prototype.createInstanceDataParts = function () {
  12940. var res = new Array();
  12941. if (this.border) {
  12942. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  12943. }
  12944. if (this.fill) {
  12945. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  12946. }
  12947. return res;
  12948. };
  12949. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  12950. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  12951. return false;
  12952. }
  12953. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  12954. var d = part;
  12955. var size = this.actualSize;
  12956. var s = this.actualScale;
  12957. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  12958. }
  12959. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  12960. var d = part;
  12961. var size = this.actualSize;
  12962. var s = this.actualScale;
  12963. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  12964. }
  12965. return true;
  12966. };
  12967. return Rectangle2D;
  12968. }(BABYLON.Shape2D));
  12969. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  12970. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  12971. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  12972. Rectangle2D.roundSubdivisions = 16;
  12973. __decorate([
  12974. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D_1.notRoundedProperty = pi; })
  12975. ], Rectangle2D.prototype, "notRounded", null);
  12976. __decorate([
  12977. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D_1.roundRadiusProperty = pi; })
  12978. ], Rectangle2D.prototype, "roundRadius", null);
  12979. Rectangle2D = Rectangle2D_1 = __decorate([
  12980. BABYLON.className("Rectangle2D", "BABYLON")
  12981. ], Rectangle2D);
  12982. BABYLON.Rectangle2D = Rectangle2D;
  12983. var Rectangle2D_1;
  12984. })(BABYLON || (BABYLON = {}));
  12985. var __extends = (this && this.__extends) || function (d, b) {
  12986. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  12987. function __() { this.constructor = d; }
  12988. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12989. };
  12990. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  12991. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  12992. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  12993. 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;
  12994. return c > 3 && r && Object.defineProperty(target, key, r), r;
  12995. };
  12996. var BABYLON;
  12997. (function (BABYLON) {
  12998. var Ellipse2DRenderCache = (function (_super) {
  12999. __extends(Ellipse2DRenderCache, _super);
  13000. function Ellipse2DRenderCache(engine, modelKey) {
  13001. var _this = _super.call(this, engine, modelKey) || this;
  13002. _this.effectsReady = false;
  13003. _this.fillVB = null;
  13004. _this.fillIB = null;
  13005. _this.fillIndicesCount = 0;
  13006. _this.instancingFillAttributes = null;
  13007. _this.effectFillInstanced = null;
  13008. _this.effectFill = null;
  13009. _this.borderVB = null;
  13010. _this.borderIB = null;
  13011. _this.borderIndicesCount = 0;
  13012. _this.instancingBorderAttributes = null;
  13013. _this.effectBorderInstanced = null;
  13014. _this.effectBorder = null;
  13015. return _this;
  13016. }
  13017. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  13018. // Do nothing if the shader is still loading/preparing
  13019. if (!this.effectsReady) {
  13020. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  13021. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  13022. return false;
  13023. }
  13024. this.effectsReady = true;
  13025. }
  13026. var canvas = instanceInfo.owner.owner;
  13027. var engine = canvas.engine;
  13028. var depthFunction = 0;
  13029. if (this.effectFill && this.effectBorder) {
  13030. depthFunction = engine.getDepthFunction();
  13031. engine.setDepthFunctionToLessOrEqual();
  13032. }
  13033. var curAlphaMode = engine.getAlphaMode();
  13034. if (this.effectFill) {
  13035. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  13036. var pid = context.groupInfoPartData[partIndex];
  13037. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13038. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13039. }
  13040. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  13041. engine.enableEffect(effect);
  13042. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  13043. if (context.useInstancing) {
  13044. if (!this.instancingFillAttributes) {
  13045. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  13046. }
  13047. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13048. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13049. canvas._addDrawCallCount(1, context.renderMode);
  13050. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  13051. engine.draw(true, 0, this.fillIndicesCount, count);
  13052. engine.unbindInstanceAttributes();
  13053. }
  13054. else {
  13055. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13056. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13057. this.setupUniforms(effect, partIndex, pid._partData, i);
  13058. engine.draw(true, 0, this.fillIndicesCount);
  13059. }
  13060. }
  13061. }
  13062. if (this.effectBorder) {
  13063. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  13064. var pid = context.groupInfoPartData[partIndex];
  13065. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13066. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13067. }
  13068. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  13069. engine.enableEffect(effect);
  13070. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  13071. if (context.useInstancing) {
  13072. if (!this.instancingBorderAttributes) {
  13073. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  13074. }
  13075. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  13076. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13077. canvas._addDrawCallCount(1, context.renderMode);
  13078. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  13079. engine.draw(true, 0, this.borderIndicesCount, count);
  13080. engine.unbindInstanceAttributes();
  13081. }
  13082. else {
  13083. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13084. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13085. this.setupUniforms(effect, partIndex, pid._partData, i);
  13086. engine.draw(true, 0, this.borderIndicesCount);
  13087. }
  13088. }
  13089. }
  13090. engine.setAlphaMode(curAlphaMode, true);
  13091. if (this.effectFill && this.effectBorder) {
  13092. engine.setDepthFunction(depthFunction);
  13093. }
  13094. return true;
  13095. };
  13096. Ellipse2DRenderCache.prototype.dispose = function () {
  13097. if (!_super.prototype.dispose.call(this)) {
  13098. return false;
  13099. }
  13100. if (this.fillVB) {
  13101. this._engine._releaseBuffer(this.fillVB);
  13102. this.fillVB = null;
  13103. }
  13104. if (this.fillIB) {
  13105. this._engine._releaseBuffer(this.fillIB);
  13106. this.fillIB = null;
  13107. }
  13108. this.effectFill = null;
  13109. this.effectFillInstanced = null;
  13110. this.effectBorder = null;
  13111. this.effectBorderInstanced = null;
  13112. if (this.borderVB) {
  13113. this._engine._releaseBuffer(this.borderVB);
  13114. this.borderVB = null;
  13115. }
  13116. if (this.borderIB) {
  13117. this._engine._releaseBuffer(this.borderIB);
  13118. this.borderIB = null;
  13119. }
  13120. return true;
  13121. };
  13122. return Ellipse2DRenderCache;
  13123. }(BABYLON.ModelRenderCache));
  13124. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  13125. var Ellipse2DInstanceData = (function (_super) {
  13126. __extends(Ellipse2DInstanceData, _super);
  13127. function Ellipse2DInstanceData(partId) {
  13128. return _super.call(this, partId, 1) || this;
  13129. }
  13130. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  13131. get: function () {
  13132. return null;
  13133. },
  13134. set: function (value) {
  13135. },
  13136. enumerable: true,
  13137. configurable: true
  13138. });
  13139. return Ellipse2DInstanceData;
  13140. }(BABYLON.Shape2DInstanceData));
  13141. __decorate([
  13142. BABYLON.instanceData()
  13143. ], Ellipse2DInstanceData.prototype, "properties", null);
  13144. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  13145. var Ellipse2D = Ellipse2D_1 = (function (_super) {
  13146. __extends(Ellipse2D, _super);
  13147. /**
  13148. * Create an Ellipse 2D Shape primitive
  13149. * @param settings a combination of settings, possible ones are
  13150. * - 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)
  13151. * - children: an array of direct children
  13152. * - id: a text identifier, for information purpose
  13153. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13154. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13155. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13156. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13157. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13158. * - zOrder: override the zOrder with the specified value
  13159. * - origin: define the normalized origin point location, default [0.5;0.5]
  13160. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  13161. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  13162. * - 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)
  13163. * - 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)
  13164. * - borderThickness: the thickness of the drawn border, default is 1.
  13165. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  13166. * - 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.
  13167. * - 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.
  13168. * - 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!
  13169. * - 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.
  13170. * - 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).
  13171. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13172. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13173. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13174. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13175. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13176. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13177. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13178. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13179. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13180. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13181. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13182. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13183. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13184. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13185. */
  13186. function Ellipse2D(settings) {
  13187. var _this = this;
  13188. // Avoid checking every time if the object exists
  13189. if (settings == null) {
  13190. settings = {};
  13191. }
  13192. _this = _super.call(this, settings) || this;
  13193. if (settings.size != null) {
  13194. _this.size = settings.size;
  13195. }
  13196. else if (settings.width || settings.height) {
  13197. var size = new BABYLON.Size(settings.width, settings.height);
  13198. _this.size = size;
  13199. }
  13200. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  13201. _this.subdivisions = sub;
  13202. return _this;
  13203. }
  13204. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  13205. get: function () {
  13206. return this._subdivisions;
  13207. },
  13208. set: function (value) {
  13209. this._subdivisions = value;
  13210. },
  13211. enumerable: true,
  13212. configurable: true
  13213. });
  13214. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  13215. var w = this.size.width / 2;
  13216. var h = this.size.height / 2;
  13217. var x = intersectInfo._localPickPosition.x - w;
  13218. var y = intersectInfo._localPickPosition.y - h;
  13219. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  13220. };
  13221. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  13222. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  13223. return true;
  13224. };
  13225. Ellipse2D.prototype.updateTriArray = function () {
  13226. var subDiv = this._subdivisions;
  13227. if (this._primTriArray == null) {
  13228. this._primTriArray = new BABYLON.Tri2DArray(subDiv);
  13229. }
  13230. else {
  13231. this._primTriArray.clear(subDiv);
  13232. }
  13233. var size = this.actualSize;
  13234. var center = new BABYLON.Vector2(0.5 * size.width, 0.5 * size.height);
  13235. var v1 = BABYLON.Vector2.Zero();
  13236. var v2 = BABYLON.Vector2.Zero();
  13237. for (var i = 0; i < subDiv; i++) {
  13238. var angle1 = Math.PI * 2 * (i - 1) / subDiv;
  13239. var angle2 = Math.PI * 2 * i / subDiv;
  13240. v1.x = ((Math.cos(angle1) / 2.0) + 0.5) * size.width;
  13241. v1.y = ((Math.sin(angle1) / 2.0) + 0.5) * size.height;
  13242. v2.x = ((Math.cos(angle2) / 2.0) + 0.5) * size.width;
  13243. v2.y = ((Math.sin(angle2) / 2.0) + 0.5) * size.height;
  13244. this._primTriArray.storeTriangle(i, center, v1, v2);
  13245. }
  13246. };
  13247. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  13248. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  13249. return renderCache;
  13250. };
  13251. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  13252. var renderCache = modelRenderCache;
  13253. var engine = this.owner.engine;
  13254. // Need to create WebGL resources for fill part?
  13255. if (this.fill) {
  13256. var vbSize = this.subdivisions + 1;
  13257. var vb = new Float32Array(vbSize);
  13258. for (var i = 0; i < vbSize; i++) {
  13259. vb[i] = i;
  13260. }
  13261. renderCache.fillVB = engine.createVertexBuffer(vb);
  13262. var triCount = vbSize - 1;
  13263. var ib = new Float32Array(triCount * 3);
  13264. for (var i = 0; i < triCount; i++) {
  13265. ib[i * 3 + 0] = 0;
  13266. ib[i * 3 + 2] = i + 2;
  13267. ib[i * 3 + 1] = i + 1;
  13268. }
  13269. ib[triCount * 3 - 1] = 1;
  13270. renderCache.fillIB = engine.createIndexBuffer(ib);
  13271. renderCache.fillIndicesCount = triCount * 3;
  13272. // 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
  13273. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  13274. if (ei) {
  13275. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  13276. }
  13277. // Get the non instanced version
  13278. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  13279. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  13280. }
  13281. // Need to create WebGL resource for border part?
  13282. if (this.border) {
  13283. var vbSize = this.subdivisions * 2;
  13284. var vb = new Float32Array(vbSize);
  13285. for (var i = 0; i < vbSize; i++) {
  13286. vb[i] = i;
  13287. }
  13288. renderCache.borderVB = engine.createVertexBuffer(vb);
  13289. var triCount = vbSize;
  13290. var rs = triCount / 2;
  13291. var ib = new Float32Array(triCount * 3);
  13292. for (var i = 0; i < rs; i++) {
  13293. var r0 = i;
  13294. var r1 = (i + 1) % rs;
  13295. ib[i * 6 + 0] = rs + r1;
  13296. ib[i * 6 + 1] = rs + r0;
  13297. ib[i * 6 + 2] = r0;
  13298. ib[i * 6 + 3] = r1;
  13299. ib[i * 6 + 4] = rs + r1;
  13300. ib[i * 6 + 5] = r0;
  13301. }
  13302. renderCache.borderIB = engine.createIndexBuffer(ib);
  13303. renderCache.borderIndicesCount = (triCount * 3);
  13304. // 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
  13305. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  13306. if (ei) {
  13307. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13308. }
  13309. // Get the non instanced version
  13310. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  13311. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  13312. }
  13313. return renderCache;
  13314. };
  13315. Ellipse2D.prototype.createInstanceDataParts = function () {
  13316. var res = new Array();
  13317. if (this.border) {
  13318. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  13319. }
  13320. if (this.fill) {
  13321. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  13322. }
  13323. return res;
  13324. };
  13325. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  13326. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  13327. return false;
  13328. }
  13329. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  13330. var d = part;
  13331. var size = this.actualSize;
  13332. var s = this.actualScale;
  13333. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  13334. }
  13335. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  13336. var d = part;
  13337. var size = this.actualSize;
  13338. var s = this.actualScale;
  13339. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  13340. }
  13341. return true;
  13342. };
  13343. return Ellipse2D;
  13344. }(BABYLON.Shape2D));
  13345. __decorate([
  13346. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D_1.subdivisionsProperty = pi; })
  13347. ], Ellipse2D.prototype, "subdivisions", null);
  13348. Ellipse2D = Ellipse2D_1 = __decorate([
  13349. BABYLON.className("Ellipse2D", "BABYLON")
  13350. ], Ellipse2D);
  13351. BABYLON.Ellipse2D = Ellipse2D;
  13352. var Ellipse2D_1;
  13353. })(BABYLON || (BABYLON = {}));
  13354. var __extends = (this && this.__extends) || function (d, b) {
  13355. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  13356. function __() { this.constructor = d; }
  13357. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13358. };
  13359. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13360. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13361. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13362. 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;
  13363. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13364. };
  13365. var BABYLON;
  13366. (function (BABYLON) {
  13367. var Sprite2DRenderCache = (function (_super) {
  13368. __extends(Sprite2DRenderCache, _super);
  13369. function Sprite2DRenderCache() {
  13370. var _this = _super !== null && _super.apply(this, arguments) || this;
  13371. _this.effectsReady = false;
  13372. _this.vb = null;
  13373. _this.ib = null;
  13374. _this.instancingAttributes = null;
  13375. _this.texture = null;
  13376. _this.effect = null;
  13377. _this.effectInstanced = null;
  13378. return _this;
  13379. }
  13380. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  13381. // Do nothing if the shader is still loading/preparing
  13382. if (!this.effectsReady) {
  13383. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  13384. return false;
  13385. }
  13386. this.effectsReady = true;
  13387. }
  13388. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  13389. var canvas = instanceInfo.owner.owner;
  13390. var engine = canvas.engine;
  13391. var cur = engine.getAlphaMode();
  13392. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  13393. engine.enableEffect(effect);
  13394. effect.setTexture("diffuseSampler", this.texture);
  13395. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  13396. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  13397. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  13398. }
  13399. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  13400. var pid = context.groupInfoPartData[0];
  13401. if (context.useInstancing) {
  13402. if (!this.instancingAttributes) {
  13403. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  13404. }
  13405. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  13406. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  13407. canvas._addDrawCallCount(1, context.renderMode);
  13408. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  13409. engine.draw(true, 0, 6, count);
  13410. engine.unbindInstanceAttributes();
  13411. }
  13412. else {
  13413. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  13414. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  13415. this.setupUniforms(effect, 0, pid._partData, i);
  13416. engine.draw(true, 0, 6);
  13417. }
  13418. }
  13419. engine.setAlphaMode(cur, true);
  13420. return true;
  13421. };
  13422. Sprite2DRenderCache.prototype.dispose = function () {
  13423. if (!_super.prototype.dispose.call(this)) {
  13424. return false;
  13425. }
  13426. if (this.vb) {
  13427. this._engine._releaseBuffer(this.vb);
  13428. this.vb = null;
  13429. }
  13430. if (this.ib) {
  13431. this._engine._releaseBuffer(this.ib);
  13432. this.ib = null;
  13433. }
  13434. //if (this.texture) {
  13435. // this.texture.dispose();
  13436. // this.texture = null;
  13437. //}
  13438. this.effect = null;
  13439. this.effectInstanced = null;
  13440. return true;
  13441. };
  13442. return Sprite2DRenderCache;
  13443. }(BABYLON.ModelRenderCache));
  13444. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  13445. var Sprite2D = Sprite2D_1 = (function (_super) {
  13446. __extends(Sprite2D, _super);
  13447. /**
  13448. * Create an 2D Sprite primitive
  13449. * @param texture the texture that stores the sprite to render
  13450. * @param settings a combination of settings, possible ones are
  13451. * - 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)
  13452. * - children: an array of direct children
  13453. * - id a text identifier, for information purpose
  13454. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  13455. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  13456. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  13457. * - size: the size of the sprite displayed in the canvas, if not specified the spriteSize will be used
  13458. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  13459. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  13460. * - zOrder: override the zOrder with the specified value
  13461. * - origin: define the normalized origin point location, default [0.5;0.5]
  13462. * - 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.
  13463. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  13464. * - 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.
  13465. * - 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
  13466. * - invertY: if true the texture Y will be inverted, default is false.
  13467. * - 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.
  13468. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  13469. * - 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.
  13470. * - 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.
  13471. * - 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!
  13472. * - 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.
  13473. * - 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).
  13474. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  13475. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13476. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13477. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13478. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13479. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  13480. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  13481. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  13482. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  13483. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13484. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13485. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13486. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  13487. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  13488. */
  13489. function Sprite2D(texture, settings) {
  13490. var _this = this;
  13491. if (!settings) {
  13492. settings = {};
  13493. }
  13494. _this = _super.call(this, settings) || this;
  13495. _this.texture = texture;
  13496. // This is removed to let the user the possibility to setup the addressing mode he wants
  13497. //this.texture.wrapU = Texture.CLAMP_ADDRESSMODE;
  13498. //this.texture.wrapV = Texture.CLAMP_ADDRESSMODE;
  13499. _this._useSize = false;
  13500. _this._spriteSize = (settings.spriteSize != null) ? settings.spriteSize.clone() : null;
  13501. _this._spriteLocation = (settings.spriteLocation != null) ? settings.spriteLocation.clone() : new BABYLON.Vector2(0, 0);
  13502. if (settings.size != null) {
  13503. _this.size = settings.size;
  13504. }
  13505. _this.spriteFrame = 0;
  13506. _this.invertY = (settings.invertY == null) ? false : settings.invertY;
  13507. _this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  13508. _this.useAlphaFromTexture = true;
  13509. _this._scale9 = (settings.scale9 != null) ? settings.scale9.clone() : null;
  13510. // 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.
  13511. // The fucking delayed texture sprite bug is fixed!
  13512. if (settings.spriteSize == null) {
  13513. _this.spriteSize = new BABYLON.Size(10, 10);
  13514. }
  13515. if (settings.spriteSize == null || !texture.isReady()) {
  13516. if (texture.isReady()) {
  13517. var s = texture.getBaseSize();
  13518. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  13519. _this._updateSpriteScaleFactor();
  13520. }
  13521. else {
  13522. texture.onLoadObservable.add(function () {
  13523. if (settings.spriteSize == null) {
  13524. var s = texture.getBaseSize();
  13525. _this.spriteSize = new BABYLON.Size(s.width, s.height);
  13526. }
  13527. _this._updateSpriteScaleFactor();
  13528. _this._positioningDirty();
  13529. _this._setLayoutDirty();
  13530. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D_1.textureProperty.flagId; // To make sure the sprite is issued again for render
  13531. });
  13532. }
  13533. }
  13534. return _this;
  13535. }
  13536. Object.defineProperty(Sprite2D.prototype, "texture", {
  13537. get: function () {
  13538. return this._texture;
  13539. },
  13540. set: function (value) {
  13541. this._texture = value;
  13542. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  13543. },
  13544. enumerable: true,
  13545. configurable: true
  13546. });
  13547. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  13548. get: function () {
  13549. return this._useAlphaFromTexture;
  13550. },
  13551. set: function (value) {
  13552. if (this._useAlphaFromTexture === value) {
  13553. return;
  13554. }
  13555. this._useAlphaFromTexture = value;
  13556. this._updateRenderMode();
  13557. },
  13558. enumerable: true,
  13559. configurable: true
  13560. });
  13561. Object.defineProperty(Sprite2D.prototype, "size", {
  13562. get: function () {
  13563. if (this._size == null) {
  13564. return this.spriteSize;
  13565. }
  13566. return this.internalGetSize();
  13567. },
  13568. set: function (value) {
  13569. this._useSize = value != null;
  13570. this.internalSetSize(value);
  13571. this._updateSpriteScaleFactor();
  13572. },
  13573. enumerable: true,
  13574. configurable: true
  13575. });
  13576. Object.defineProperty(Sprite2D.prototype, "spriteSize", {
  13577. get: function () {
  13578. return this._spriteSize;
  13579. },
  13580. set: function (value) {
  13581. if (!this._spriteSize) {
  13582. this._spriteSize = value.clone();
  13583. }
  13584. else {
  13585. this._spriteSize.copyFrom(value);
  13586. }
  13587. this._updateSpriteScaleFactor();
  13588. },
  13589. enumerable: true,
  13590. configurable: true
  13591. });
  13592. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  13593. get: function () {
  13594. return this._spriteLocation;
  13595. },
  13596. set: function (value) {
  13597. if (!this._spriteLocation) {
  13598. this._spriteLocation = value.clone();
  13599. }
  13600. else {
  13601. this._spriteLocation.copyFrom(value);
  13602. }
  13603. },
  13604. enumerable: true,
  13605. configurable: true
  13606. });
  13607. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  13608. get: function () {
  13609. return this._spriteFrame;
  13610. },
  13611. set: function (value) {
  13612. this._spriteFrame = value;
  13613. },
  13614. enumerable: true,
  13615. configurable: true
  13616. });
  13617. Object.defineProperty(Sprite2D.prototype, "invertY", {
  13618. get: function () {
  13619. return this._invertY;
  13620. },
  13621. set: function (value) {
  13622. this._invertY = value;
  13623. },
  13624. enumerable: true,
  13625. configurable: true
  13626. });
  13627. Object.defineProperty(Sprite2D.prototype, "isScale9", {
  13628. get: function () {
  13629. return this._scale9 !== null;
  13630. },
  13631. enumerable: true,
  13632. configurable: true
  13633. });
  13634. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  13635. //@instanceLevelProperty(RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, pi => Sprite2D.spriteScaleFactorProperty = pi)
  13636. ///**
  13637. // * Get/set the sprite location (in pixels) in the texture
  13638. // */
  13639. //public get spriteScaleFactor(): Vector2 {
  13640. // return this._spriteScaleFactor;
  13641. //}
  13642. //public set spriteScaleFactor(value: Vector2) {
  13643. // this._spriteScaleFactor = value;
  13644. //}
  13645. /**
  13646. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  13647. */
  13648. get: function () {
  13649. return this._alignToPixel;
  13650. },
  13651. set: function (value) {
  13652. this._alignToPixel = value;
  13653. },
  13654. enumerable: true,
  13655. configurable: true
  13656. });
  13657. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  13658. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  13659. return true;
  13660. };
  13661. /**
  13662. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  13663. */
  13664. Sprite2D.prototype.getAnimatables = function () {
  13665. var res = new Array();
  13666. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  13667. res.push(this.texture);
  13668. }
  13669. return res;
  13670. };
  13671. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  13672. // 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
  13673. return true;
  13674. };
  13675. Object.defineProperty(Sprite2D.prototype, "isSizeAuto", {
  13676. get: function () {
  13677. return this.size == null;
  13678. },
  13679. enumerable: true,
  13680. configurable: true
  13681. });
  13682. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  13683. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  13684. return renderCache;
  13685. };
  13686. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  13687. var renderCache = modelRenderCache;
  13688. var engine = this.owner.engine;
  13689. var vb = new Float32Array(4);
  13690. for (var i = 0; i < 4; i++) {
  13691. vb[i] = i;
  13692. }
  13693. renderCache.vb = engine.createVertexBuffer(vb);
  13694. var ib = new Float32Array(6);
  13695. ib[0] = 0;
  13696. ib[1] = 2;
  13697. ib[2] = 1;
  13698. ib[3] = 0;
  13699. ib[4] = 3;
  13700. ib[5] = 2;
  13701. renderCache.ib = engine.createIndexBuffer(ib);
  13702. renderCache.texture = this.texture;
  13703. // 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
  13704. var ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  13705. if (ei) {
  13706. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13707. }
  13708. ei = this.getDataPartEffectInfo(Sprite2D_1.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  13709. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  13710. return renderCache;
  13711. };
  13712. Sprite2D.prototype.getUsedShaderCategories = function (dataPart) {
  13713. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  13714. if (dataPart.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  13715. var useScale9 = this._scale9 != null;
  13716. if (useScale9) {
  13717. cat.push(Sprite2D_1.SHAPE2D_CATEGORY_SCALE9);
  13718. }
  13719. }
  13720. return cat;
  13721. };
  13722. Sprite2D.prototype.createInstanceDataParts = function () {
  13723. return [new Sprite2DInstanceData(Sprite2D_1.SPRITE2D_MAINPARTID)];
  13724. };
  13725. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  13726. Sprite2D_1.layoutConstructMode = true;
  13727. };
  13728. // if obj contains something, we restore the _text property
  13729. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  13730. Sprite2D_1.layoutConstructMode = false;
  13731. };
  13732. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  13733. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  13734. return false;
  13735. }
  13736. if (!this.texture.isReady() && !Sprite2D_1.layoutConstructMode) {
  13737. return false;
  13738. }
  13739. if (part.id === Sprite2D_1.SPRITE2D_MAINPARTID) {
  13740. var d = this._instanceDataParts[0];
  13741. if (Sprite2D_1.layoutConstructMode) {
  13742. d.topLeftUV = BABYLON.Vector2.Zero();
  13743. d.sizeUV = BABYLON.Vector2.Zero();
  13744. d.properties = BABYLON.Vector3.Zero();
  13745. d.textureSize = BABYLON.Vector2.Zero();
  13746. d.scaleFactor = BABYLON.Vector2.Zero();
  13747. if (this.isScale9) {
  13748. d.scale9 = BABYLON.Vector4.Zero();
  13749. }
  13750. }
  13751. else {
  13752. var ts = this.texture.getBaseSize();
  13753. var ss = this.spriteSize;
  13754. var sl = this.spriteLocation;
  13755. var ssf = this.actualScale;
  13756. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  13757. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  13758. d.sizeUV = suv;
  13759. d.scaleFactor = ssf;
  13760. Sprite2D_1._prop.x = this.spriteFrame;
  13761. Sprite2D_1._prop.y = this.invertY ? 1 : 0;
  13762. Sprite2D_1._prop.z = this.alignToPixel ? 1 : 0;
  13763. d.properties = Sprite2D_1._prop;
  13764. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  13765. var scale9 = this._scale9;
  13766. if (scale9 != null) {
  13767. 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);
  13768. d.scale9 = normalizedScale9;
  13769. }
  13770. }
  13771. }
  13772. return true;
  13773. };
  13774. Sprite2D.prototype._mustUpdateInstance = function () {
  13775. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  13776. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  13777. if (res) {
  13778. this._updateRenderMode();
  13779. }
  13780. return res;
  13781. };
  13782. Sprite2D.prototype._useTextureAlpha = function () {
  13783. return this.texture != null && this.texture.hasAlpha;
  13784. };
  13785. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  13786. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  13787. };
  13788. Sprite2D.prototype._updateSpriteScaleFactor = function () {
  13789. if (!this._useSize) {
  13790. return;
  13791. }
  13792. var sS = this.spriteSize;
  13793. var s = this.size;
  13794. if (s == null || sS == null) {
  13795. return;
  13796. }
  13797. this._postScale.x = s.width / sS.width;
  13798. this._postScale.y = s.height / sS.height;
  13799. };
  13800. return Sprite2D;
  13801. }(BABYLON.RenderablePrim2D));
  13802. Sprite2D.SPRITE2D_MAINPARTID = 1;
  13803. Sprite2D.SHAPE2D_CATEGORY_SCALE9 = "Scale9";
  13804. Sprite2D._prop = BABYLON.Vector3.Zero();
  13805. Sprite2D.layoutConstructMode = false;
  13806. __decorate([
  13807. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D_1.textureProperty = pi; })
  13808. ], Sprite2D.prototype, "texture", null);
  13809. __decorate([
  13810. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D_1.useAlphaFromTextureProperty = pi; })
  13811. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  13812. __decorate([
  13813. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D_1.spriteSizeProperty = pi; }, false, true)
  13814. ], Sprite2D.prototype, "spriteSize", null);
  13815. __decorate([
  13816. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D_1.spriteLocationProperty = pi; })
  13817. ], Sprite2D.prototype, "spriteLocation", null);
  13818. __decorate([
  13819. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D_1.spriteFrameProperty = pi; })
  13820. ], Sprite2D.prototype, "spriteFrame", null);
  13821. __decorate([
  13822. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D_1.invertYProperty = pi; })
  13823. ], Sprite2D.prototype, "invertY", null);
  13824. __decorate([
  13825. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 8, function (pi) { return Sprite2D_1.spriteScale9Property = pi; })
  13826. ], Sprite2D.prototype, "isScale9", null);
  13827. Sprite2D = Sprite2D_1 = __decorate([
  13828. BABYLON.className("Sprite2D", "BABYLON")
  13829. ], Sprite2D);
  13830. BABYLON.Sprite2D = Sprite2D;
  13831. var Sprite2DInstanceData = (function (_super) {
  13832. __extends(Sprite2DInstanceData, _super);
  13833. function Sprite2DInstanceData(partId) {
  13834. return _super.call(this, partId, 1) || this;
  13835. }
  13836. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  13837. get: function () {
  13838. return null;
  13839. },
  13840. set: function (value) {
  13841. },
  13842. enumerable: true,
  13843. configurable: true
  13844. });
  13845. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  13846. get: function () {
  13847. return null;
  13848. },
  13849. set: function (value) {
  13850. },
  13851. enumerable: true,
  13852. configurable: true
  13853. });
  13854. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  13855. get: function () {
  13856. return null;
  13857. },
  13858. set: function (value) {
  13859. },
  13860. enumerable: true,
  13861. configurable: true
  13862. });
  13863. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  13864. get: function () {
  13865. return null;
  13866. },
  13867. set: function (value) {
  13868. },
  13869. enumerable: true,
  13870. configurable: true
  13871. });
  13872. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  13873. // 3 floats being:
  13874. // - x: frame number to display
  13875. // - y: invertY setting
  13876. // - z: alignToPixel setting
  13877. get: function () {
  13878. return null;
  13879. },
  13880. set: function (value) {
  13881. },
  13882. enumerable: true,
  13883. configurable: true
  13884. });
  13885. Object.defineProperty(Sprite2DInstanceData.prototype, "scale9", {
  13886. get: function () {
  13887. return null;
  13888. },
  13889. set: function (value) {
  13890. },
  13891. enumerable: true,
  13892. configurable: true
  13893. });
  13894. return Sprite2DInstanceData;
  13895. }(BABYLON.InstanceDataBase));
  13896. __decorate([
  13897. BABYLON.instanceData()
  13898. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  13899. __decorate([
  13900. BABYLON.instanceData()
  13901. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  13902. __decorate([
  13903. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  13904. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  13905. __decorate([
  13906. BABYLON.instanceData()
  13907. ], Sprite2DInstanceData.prototype, "textureSize", null);
  13908. __decorate([
  13909. BABYLON.instanceData()
  13910. ], Sprite2DInstanceData.prototype, "properties", null);
  13911. __decorate([
  13912. BABYLON.instanceData(Sprite2D.SHAPE2D_CATEGORY_SCALE9)
  13913. ], Sprite2DInstanceData.prototype, "scale9", null);
  13914. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  13915. var Sprite2D_1;
  13916. })(BABYLON || (BABYLON = {}));
  13917. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  13918. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  13919. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  13920. 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;
  13921. return c > 3 && r && Object.defineProperty(target, key, r), r;
  13922. };
  13923. var BABYLON;
  13924. (function (BABYLON) {
  13925. /**
  13926. * This class will contains information about a sub picture present in an Atlas Picture.
  13927. */
  13928. var AtlasSubPictureInfo = (function () {
  13929. function AtlasSubPictureInfo() {
  13930. }
  13931. return AtlasSubPictureInfo;
  13932. }());
  13933. BABYLON.AtlasSubPictureInfo = AtlasSubPictureInfo;
  13934. /**
  13935. * This class represent an Atlas Picture, it contains the information of all the sub pictures and the Texture that stores the bitmap.
  13936. * You get an instance of this class using methods of the AtlasPictureInfoFactory
  13937. */
  13938. var AtlasPictureInfo = (function () {
  13939. function AtlasPictureInfo() {
  13940. }
  13941. /**
  13942. * Creates many sprite from the Atlas Picture
  13943. * @param filterCallback a predicate if true is returned then the corresponding sub picture will be used to create a sprite.
  13944. * The Predicate has many parameters:
  13945. * - index: just an index incremented at each sub picture submitted for Sprite creation
  13946. * - name: the sub picture's name
  13947. * - aspi: the AtlasSubPictureInfo corresponding to the submitted sub picture
  13948. * - settings: the Sprite2D creation settings, you can alter this JSON object but BEWARE, the alterations will be kept for subsequent Sprite2D creations!
  13949. * @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.
  13950. */
  13951. AtlasPictureInfo.prototype.createSprites = function (filterCallback, spriteSettings) {
  13952. var _this = this;
  13953. var res = new Array();
  13954. var index = 0;
  13955. this.subPictures.forEach(function (k, v) {
  13956. if (!filterCallback || filterCallback(index++, k, v, spriteSettings)) {
  13957. var s = _this.createSprite(k, spriteSettings);
  13958. if (s) {
  13959. res.push(s);
  13960. }
  13961. }
  13962. });
  13963. return res;
  13964. };
  13965. /**
  13966. * Create one Sprite from a sub picture
  13967. * @param subPictureName the name of the sub picture to use
  13968. * @param spriteSettings the Sprite2D settings to use for the Sprite instance creation
  13969. */
  13970. AtlasPictureInfo.prototype.createSprite = function (subPictureName, spriteSettings) {
  13971. var spi = this.subPictures.get(subPictureName);
  13972. if (!spi) {
  13973. return null;
  13974. }
  13975. if (!spriteSettings) {
  13976. spriteSettings = {};
  13977. }
  13978. var s = spriteSettings;
  13979. s.id = subPictureName;
  13980. s.spriteLocation = spi.location;
  13981. s.spriteSize = spi.size;
  13982. var sprite = new BABYLON.Sprite2D(this.texture, spriteSettings);
  13983. return sprite;
  13984. };
  13985. return AtlasPictureInfo;
  13986. }());
  13987. BABYLON.AtlasPictureInfo = AtlasPictureInfo;
  13988. /**
  13989. * This if the Factory class containing static method to create Atlas Pictures Info objects or add new loaders
  13990. */
  13991. var AtlasPictureInfoFactory = (function () {
  13992. function AtlasPictureInfoFactory() {
  13993. }
  13994. /**
  13995. * Add a custom loader
  13996. * @param fileExtension must be the file extension (without the dot) of the file that is loaded by this loader (e.g.: json)
  13997. * @param plugin the instance of the loader
  13998. */
  13999. AtlasPictureInfoFactory.addLoader = function (fileExtension, plugin) {
  14000. var a = AtlasPictureInfoFactory.plugins.getOrAddWithFactory(fileExtension.toLocaleLowerCase(), function () { return new Array(); });
  14001. a.push(plugin);
  14002. };
  14003. /**
  14004. * Load an Atlas Picture Info object from a data file at a given url and with a given texture
  14005. * @param texture the texture containing the atlas bitmap
  14006. * @param url the URL of the Atlas Info data file
  14007. * @param onLoad a callback that will be called when the AtlasPictureInfo object will be loaded and ready
  14008. * @param onError a callback that will be called in case of error
  14009. */
  14010. AtlasPictureInfoFactory.loadFromUrl = function (texture, url, onLoad, onError) {
  14011. if (onError === void 0) { onError = null; }
  14012. BABYLON.Tools.LoadFile(url, function (data) {
  14013. var ext = url.split('.').pop().split(/\#|\?/)[0];
  14014. var plugins = AtlasPictureInfoFactory.plugins.get(ext.toLocaleLowerCase());
  14015. if (!plugins) {
  14016. if (onError) {
  14017. onError("couldn't find a plugin for this file extension", -1);
  14018. }
  14019. return;
  14020. }
  14021. for (var _i = 0, plugins_1 = plugins; _i < plugins_1.length; _i++) {
  14022. var p = plugins_1[_i];
  14023. var ret = p.loadFile(data);
  14024. if (ret) {
  14025. if (ret.api) {
  14026. ret.api.texture = texture;
  14027. if (onLoad) {
  14028. onLoad(ret.api);
  14029. }
  14030. }
  14031. else if (onError) {
  14032. onError(ret.errorMsg, ret.errorCode);
  14033. }
  14034. return;
  14035. }
  14036. }
  14037. if (onError) {
  14038. onError("No plugin to load this Atlas Data file format", -1);
  14039. }
  14040. }, null, null, null, function () {
  14041. if (onError) {
  14042. onError("Couldn't load file", -1);
  14043. }
  14044. });
  14045. return null;
  14046. };
  14047. return AtlasPictureInfoFactory;
  14048. }());
  14049. AtlasPictureInfoFactory.plugins = new BABYLON.StringDictionary();
  14050. BABYLON.AtlasPictureInfoFactory = AtlasPictureInfoFactory;
  14051. // Loader class for the TexturePacker's JSON Array data format
  14052. var JSONArrayLoader = JSONArrayLoader_1 = (function () {
  14053. function JSONArrayLoader() {
  14054. }
  14055. JSONArrayLoader.prototype.loadFile = function (content) {
  14056. var errorMsg = null;
  14057. var errorCode = 0;
  14058. var root = null;
  14059. var api = null;
  14060. try {
  14061. var frames_1;
  14062. var meta = void 0;
  14063. try {
  14064. root = JSON.parse(content);
  14065. frames_1 = root.frames;
  14066. meta = root.meta;
  14067. if (!frames_1 || !meta) {
  14068. throw Error("Not a JSON Array file format");
  14069. }
  14070. }
  14071. catch (ex1) {
  14072. return null;
  14073. }
  14074. api = new AtlasPictureInfo();
  14075. api.atlasSize = new BABYLON.Size(meta.size.w, meta.size.h);
  14076. api.subPictures = new BABYLON.StringDictionary();
  14077. for (var _i = 0, frames_2 = frames_1; _i < frames_2.length; _i++) {
  14078. var f = frames_2[_i];
  14079. var aspi = new AtlasSubPictureInfo();
  14080. aspi.name = f.filename;
  14081. aspi.location = new BABYLON.Vector2(f.frame.x, api.atlasSize.height - (f.frame.y + f.frame.h));
  14082. aspi.size = new BABYLON.Size(f.frame.w, f.frame.h);
  14083. api.subPictures.add(aspi.name, aspi);
  14084. }
  14085. }
  14086. catch (ex2) {
  14087. errorMsg = "Unknown Exception: " + ex2;
  14088. errorCode = -2;
  14089. }
  14090. return { api: api, errorMsg: errorMsg, errorCode: errorCode };
  14091. };
  14092. return JSONArrayLoader;
  14093. }());
  14094. JSONArrayLoader = JSONArrayLoader_1 = __decorate([
  14095. AtlasLoaderPlugin("json", new JSONArrayLoader_1())
  14096. ], JSONArrayLoader);
  14097. /**
  14098. * Use this decorator when you declare an Atlas Loader Class for the loader to register itself automatically.
  14099. * @param fileExtension the extension of the file that the plugin is loading (there can be many plugin for the same extension)
  14100. * @param plugin an instance of the plugin class to add to the AtlasPictureInfoFactory
  14101. */
  14102. function AtlasLoaderPlugin(fileExtension, plugin) {
  14103. return function () {
  14104. AtlasPictureInfoFactory.addLoader(fileExtension, plugin);
  14105. };
  14106. }
  14107. BABYLON.AtlasLoaderPlugin = AtlasLoaderPlugin;
  14108. var JSONArrayLoader_1;
  14109. })(BABYLON || (BABYLON = {}));
  14110. var __extends = (this && this.__extends) || function (d, b) {
  14111. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14112. function __() { this.constructor = d; }
  14113. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14114. };
  14115. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  14116. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  14117. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14118. 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;
  14119. return c > 3 && r && Object.defineProperty(target, key, r), r;
  14120. };
  14121. var BABYLON;
  14122. (function (BABYLON) {
  14123. var Text2DRenderCache = (function (_super) {
  14124. __extends(Text2DRenderCache, _super);
  14125. function Text2DRenderCache() {
  14126. var _this = _super !== null && _super.apply(this, arguments) || this;
  14127. _this.effectsReady = false;
  14128. _this.vb = null;
  14129. _this.ib = null;
  14130. _this.instancingAttributes = null;
  14131. _this.fontTexture = null;
  14132. _this.effect = null;
  14133. _this.effectInstanced = null;
  14134. return _this;
  14135. }
  14136. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  14137. // Do nothing if the shader is still loading/preparing
  14138. if (!this.effectsReady) {
  14139. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  14140. return false;
  14141. }
  14142. this.effectsReady = true;
  14143. }
  14144. var canvas = instanceInfo.owner.owner;
  14145. var engine = canvas.engine;
  14146. this.fontTexture.update();
  14147. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  14148. engine.enableEffect(effect);
  14149. effect.setTexture("diffuseSampler", this.fontTexture);
  14150. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  14151. var sdf = this.fontTexture.isSignedDistanceField;
  14152. // Enable alpha mode only if the texture is not using SDF, SDF is rendered in AlphaTest mode, which mean no alpha blend
  14153. var curAlphaMode;
  14154. if (!sdf) {
  14155. curAlphaMode = engine.getAlphaMode();
  14156. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  14157. }
  14158. var pid = context.groupInfoPartData[0];
  14159. if (context.useInstancing) {
  14160. if (!this.instancingAttributes) {
  14161. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  14162. }
  14163. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  14164. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  14165. canvas._addDrawCallCount(1, context.renderMode);
  14166. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  14167. engine.draw(true, 0, 6, count);
  14168. engine.unbindInstanceAttributes();
  14169. }
  14170. else {
  14171. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  14172. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  14173. this.setupUniforms(effect, 0, pid._partData, i);
  14174. engine.draw(true, 0, 6);
  14175. }
  14176. }
  14177. if (!sdf) {
  14178. engine.setAlphaMode(curAlphaMode, true);
  14179. }
  14180. return true;
  14181. };
  14182. Text2DRenderCache.prototype.dispose = function () {
  14183. if (!_super.prototype.dispose.call(this)) {
  14184. return false;
  14185. }
  14186. if (this.vb) {
  14187. this._engine._releaseBuffer(this.vb);
  14188. this.vb = null;
  14189. }
  14190. if (this.ib) {
  14191. this._engine._releaseBuffer(this.ib);
  14192. this.ib = null;
  14193. }
  14194. if (this.fontTexture) {
  14195. this.fontTexture.decCachedFontTextureCounter();
  14196. this.fontTexture = null;
  14197. }
  14198. this.effect = null;
  14199. this.effectInstanced = null;
  14200. return true;
  14201. };
  14202. return Text2DRenderCache;
  14203. }(BABYLON.ModelRenderCache));
  14204. BABYLON.Text2DRenderCache = Text2DRenderCache;
  14205. var Text2DInstanceData = (function (_super) {
  14206. __extends(Text2DInstanceData, _super);
  14207. function Text2DInstanceData(partId, dataElementCount) {
  14208. return _super.call(this, partId, dataElementCount) || this;
  14209. }
  14210. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  14211. get: function () {
  14212. return null;
  14213. },
  14214. set: function (value) {
  14215. },
  14216. enumerable: true,
  14217. configurable: true
  14218. });
  14219. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  14220. get: function () {
  14221. return null;
  14222. },
  14223. set: function (value) {
  14224. },
  14225. enumerable: true,
  14226. configurable: true
  14227. });
  14228. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  14229. get: function () {
  14230. return null;
  14231. },
  14232. set: function (value) {
  14233. },
  14234. enumerable: true,
  14235. configurable: true
  14236. });
  14237. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  14238. get: function () {
  14239. return null;
  14240. },
  14241. set: function (value) {
  14242. },
  14243. enumerable: true,
  14244. configurable: true
  14245. });
  14246. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  14247. get: function () {
  14248. return null;
  14249. },
  14250. set: function (value) {
  14251. },
  14252. enumerable: true,
  14253. configurable: true
  14254. });
  14255. return Text2DInstanceData;
  14256. }(BABYLON.InstanceDataBase));
  14257. __decorate([
  14258. BABYLON.instanceData()
  14259. ], Text2DInstanceData.prototype, "topLeftUV", null);
  14260. __decorate([
  14261. BABYLON.instanceData()
  14262. ], Text2DInstanceData.prototype, "sizeUV", null);
  14263. __decorate([
  14264. BABYLON.instanceData()
  14265. ], Text2DInstanceData.prototype, "textureSize", null);
  14266. __decorate([
  14267. BABYLON.instanceData()
  14268. ], Text2DInstanceData.prototype, "color", null);
  14269. __decorate([
  14270. BABYLON.instanceData()
  14271. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  14272. BABYLON.Text2DInstanceData = Text2DInstanceData;
  14273. var Text2D = Text2D_1 = (function (_super) {
  14274. __extends(Text2D, _super);
  14275. /**
  14276. * Create a Text primitive
  14277. * @param text the text to display
  14278. * @param settings a combination of settings, possible ones are
  14279. * - 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)
  14280. * - children: an array of direct children
  14281. * - id a text identifier, for information purpose
  14282. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  14283. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  14284. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  14285. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  14286. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  14287. * - zOrder: override the zOrder with the specified value
  14288. * - origin: define the normalized origin point location, default [0.5;0.5]
  14289. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  14290. * - 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.
  14291. * - 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.
  14292. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  14293. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  14294. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  14295. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  14296. * - 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.
  14297. * - 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.
  14298. * - 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!
  14299. * - 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.
  14300. * - 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).
  14301. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  14302. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14303. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14304. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14305. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14306. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  14307. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  14308. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  14309. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  14310. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14311. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14312. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14313. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  14314. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  14315. * - textAlignmentH: align text horizontally (Text2D.AlignLeft, Text2D.AlignCenter, Text2D.AlignRight)
  14316. * - textAlignmentV: align text vertically (Text2D.AlignTop, Text2D.AlignCenter, Text2D.AlignBottom)
  14317. * - textAlignment: a string defining the text alignment, text can be: [<h:|horizontal:><left|right|center>], [<v:|vertical:><top|bottom|center>]
  14318. * - wordWrap: if true the text will wrap inside content area
  14319. */
  14320. function Text2D(text, settings) {
  14321. var _this = this;
  14322. if (!settings) {
  14323. settings = {};
  14324. }
  14325. _this = _super.call(this, settings) || this;
  14326. if (settings.bitmapFontTexture != null) {
  14327. _this._fontTexture = settings.bitmapFontTexture;
  14328. _this._fontName = null;
  14329. _this._fontSuperSample = false;
  14330. _this._fontSDF = false;
  14331. var ft = _this._fontTexture;
  14332. if (ft != null && !ft.isReady()) {
  14333. ft.onLoadObservable.add(function () {
  14334. _this._positioningDirty();
  14335. _this._setLayoutDirty();
  14336. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId; // To make sure the Text2D is issued again for render
  14337. });
  14338. }
  14339. }
  14340. else {
  14341. _this._fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  14342. _this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  14343. _this._fontSDF = (settings.fontSignedDistanceField != null && settings.fontSignedDistanceField);
  14344. }
  14345. _this._defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor.clone();
  14346. _this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  14347. _this._textSize = null;
  14348. _this.text = text;
  14349. if (settings.size != null) {
  14350. _this.size = settings.size;
  14351. _this._sizeSetByUser = true;
  14352. }
  14353. else {
  14354. _this.size = null;
  14355. }
  14356. _this.textAlignmentH = (settings.textAlignmentH == null) ? Text2D_1.AlignLeft : settings.textAlignmentH;
  14357. _this.textAlignmentV = (settings.textAlignmentV == null) ? Text2D_1.AlignTop : settings.textAlignmentV;
  14358. _this.textAlignment = (settings.textAlignment == null) ? "" : settings.textAlignment;
  14359. _this._wordWrap = (settings.wordWrap == null) ? false : settings.wordWrap;
  14360. _this._updateRenderMode();
  14361. return _this;
  14362. }
  14363. Object.defineProperty(Text2D, "AlignLeft", {
  14364. /**
  14365. * Alignment is made relative to the left edge of the Content Area. Valid for horizontal alignment only.
  14366. */
  14367. get: function () { return Text2D_1._AlignLeft; },
  14368. enumerable: true,
  14369. configurable: true
  14370. });
  14371. Object.defineProperty(Text2D, "AlignTop", {
  14372. /**
  14373. * Alignment is made relative to the top edge of the Content Area. Valid for vertical alignment only.
  14374. */
  14375. get: function () { return Text2D_1._AlignTop; },
  14376. enumerable: true,
  14377. configurable: true
  14378. });
  14379. Object.defineProperty(Text2D, "AlignRight", {
  14380. /**
  14381. * Alignment is made relative to the right edge of the Content Area. Valid for horizontal alignment only.
  14382. */
  14383. get: function () { return Text2D_1._AlignRight; },
  14384. enumerable: true,
  14385. configurable: true
  14386. });
  14387. Object.defineProperty(Text2D, "AlignBottom", {
  14388. /**
  14389. * Alignment is made relative to the bottom edge of the Content Area. Valid for vertical alignment only.
  14390. */
  14391. get: function () { return Text2D_1._AlignBottom; },
  14392. enumerable: true,
  14393. configurable: true
  14394. });
  14395. Object.defineProperty(Text2D, "AlignCenter", {
  14396. /**
  14397. * Alignment is made to center the text from equal distance to the opposite edges of the Content Area
  14398. */
  14399. get: function () { return Text2D_1._AlignCenter; },
  14400. enumerable: true,
  14401. configurable: true
  14402. });
  14403. Object.defineProperty(Text2D.prototype, "fontName", {
  14404. get: function () {
  14405. return this._fontName;
  14406. },
  14407. set: function (value) {
  14408. if (this._fontName) {
  14409. throw new Error("Font Name change is not supported right now.");
  14410. }
  14411. this._fontName = value;
  14412. },
  14413. enumerable: true,
  14414. configurable: true
  14415. });
  14416. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  14417. get: function () {
  14418. return this._defaultFontColor;
  14419. },
  14420. set: function (value) {
  14421. if (!this._defaultFontColor) {
  14422. this._defaultFontColor = value.clone();
  14423. }
  14424. else {
  14425. this._defaultFontColor.copyFrom(value);
  14426. }
  14427. },
  14428. enumerable: true,
  14429. configurable: true
  14430. });
  14431. Object.defineProperty(Text2D.prototype, "text", {
  14432. get: function () {
  14433. return this._text;
  14434. },
  14435. set: function (value) {
  14436. if (!value) {
  14437. value = "";
  14438. }
  14439. this._text = value;
  14440. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  14441. if (!this._sizeSetByUser) {
  14442. this._size = null;
  14443. }
  14444. this._updateCharCount();
  14445. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  14446. var s = this.textSize;
  14447. },
  14448. enumerable: true,
  14449. configurable: true
  14450. });
  14451. Object.defineProperty(Text2D.prototype, "size", {
  14452. get: function () {
  14453. if (this._size != null) {
  14454. return this._size;
  14455. }
  14456. return this.textSize;
  14457. },
  14458. set: function (value) {
  14459. this.internalSetSize(value);
  14460. },
  14461. enumerable: true,
  14462. configurable: true
  14463. });
  14464. Object.defineProperty(Text2D.prototype, "fontSuperSample", {
  14465. get: function () {
  14466. return this._fontTexture && this._fontTexture.isSuperSampled;
  14467. },
  14468. enumerable: true,
  14469. configurable: true
  14470. });
  14471. Object.defineProperty(Text2D.prototype, "fontSignedDistanceField", {
  14472. get: function () {
  14473. return this._fontTexture && this._fontTexture.isSignedDistanceField;
  14474. },
  14475. enumerable: true,
  14476. configurable: true
  14477. });
  14478. Object.defineProperty(Text2D.prototype, "isSizeAuto", {
  14479. get: function () {
  14480. return false;
  14481. },
  14482. enumerable: true,
  14483. configurable: true
  14484. });
  14485. Object.defineProperty(Text2D.prototype, "isVerticalSizeAuto", {
  14486. get: function () {
  14487. return false;
  14488. },
  14489. enumerable: true,
  14490. configurable: true
  14491. });
  14492. Object.defineProperty(Text2D.prototype, "isHorizontalSizeAuto", {
  14493. get: function () {
  14494. return false;
  14495. },
  14496. enumerable: true,
  14497. configurable: true
  14498. });
  14499. Object.defineProperty(Text2D.prototype, "textSize", {
  14500. /**
  14501. * Get the area that bounds the text associated to the primitive
  14502. */
  14503. get: function () {
  14504. if (!this._textSize) {
  14505. if (this.owner && this._text) {
  14506. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  14507. if (!newSize.equals(this._textSize)) {
  14508. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  14509. this._positioningDirty();
  14510. }
  14511. this._textSize = newSize;
  14512. }
  14513. else {
  14514. return Text2D_1.nullSize;
  14515. }
  14516. }
  14517. return this._textSize;
  14518. },
  14519. enumerable: true,
  14520. configurable: true
  14521. });
  14522. Text2D.prototype.onSetOwner = function () {
  14523. if (!this._textSize) {
  14524. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  14525. this._setLayoutDirty();
  14526. this._positioningDirty();
  14527. this._actualSize = null;
  14528. }
  14529. };
  14530. Object.defineProperty(Text2D.prototype, "fontTexture", {
  14531. get: function () {
  14532. if (this._fontTexture) {
  14533. return this._fontTexture;
  14534. }
  14535. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  14536. return null;
  14537. }
  14538. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  14539. return this._fontTexture;
  14540. },
  14541. enumerable: true,
  14542. configurable: true
  14543. });
  14544. /**
  14545. * Dispose the primitive, remove it from its parent
  14546. */
  14547. Text2D.prototype.dispose = function () {
  14548. if (!_super.prototype.dispose.call(this)) {
  14549. return false;
  14550. }
  14551. if (this._fontTexture) {
  14552. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample, this._fontSDF);
  14553. this._fontTexture = null;
  14554. }
  14555. return true;
  14556. };
  14557. Text2D.prototype.updateLevelBoundingInfo = function () {
  14558. if (!this.owner || !this._text) {
  14559. return false;
  14560. }
  14561. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  14562. return true;
  14563. };
  14564. Object.defineProperty(Text2D.prototype, "textAlignment", {
  14565. /**
  14566. * You can get/set the text alignment through this property
  14567. */
  14568. get: function () {
  14569. return this._textAlignment;
  14570. },
  14571. set: function (value) {
  14572. this._textAlignment = value;
  14573. this._setTextAlignmentfromString(value);
  14574. },
  14575. enumerable: true,
  14576. configurable: true
  14577. });
  14578. Text2D.prototype.levelIntersect = function (intersectInfo) {
  14579. // 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...
  14580. return true;
  14581. };
  14582. Text2D.prototype.createModelRenderCache = function (modelKey) {
  14583. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  14584. return renderCache;
  14585. };
  14586. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  14587. var renderCache = modelRenderCache;
  14588. var engine = this.owner.engine;
  14589. renderCache.fontTexture = this.fontTexture;
  14590. renderCache.fontTexture.incCachedFontTextureCounter();
  14591. var vb = new Float32Array(4);
  14592. for (var i = 0; i < 4; i++) {
  14593. vb[i] = i;
  14594. }
  14595. renderCache.vb = engine.createVertexBuffer(vb);
  14596. var ib = new Float32Array(6);
  14597. ib[0] = 0;
  14598. ib[1] = 2;
  14599. ib[2] = 1;
  14600. ib[3] = 0;
  14601. ib[4] = 3;
  14602. ib[5] = 2;
  14603. renderCache.ib = engine.createIndexBuffer(ib);
  14604. // 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
  14605. var ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, true);
  14606. if (ei) {
  14607. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  14608. }
  14609. ei = this.getDataPartEffectInfo(Text2D_1.TEXT2D_MAINPARTID, ["index"], null, false);
  14610. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  14611. return renderCache;
  14612. };
  14613. Text2D.prototype.createInstanceDataParts = function () {
  14614. return [new Text2DInstanceData(Text2D_1.TEXT2D_MAINPARTID, this._charCount)];
  14615. };
  14616. // Looks like a hack!? Yes! Because that's what it is!
  14617. // 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
  14618. // 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)
  14619. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  14620. if (!this._charCount) {
  14621. var curText = this._text;
  14622. this.text = "A";
  14623. return curText;
  14624. }
  14625. };
  14626. // if obj contains something, we restore the _text property
  14627. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  14628. if (obj !== undefined) {
  14629. this.text = obj;
  14630. }
  14631. };
  14632. Text2D.prototype.getUsedShaderCategories = function (dataPart) {
  14633. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  14634. if (this._fontSDF) {
  14635. cat.push(Text2D_1.TEXT2D_CATEGORY_SDF);
  14636. }
  14637. return cat;
  14638. };
  14639. Text2D.prototype.refreshInstanceDataPart = function (part) {
  14640. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  14641. return false;
  14642. }
  14643. if (part.id === Text2D_1.TEXT2D_MAINPARTID) {
  14644. var d = part;
  14645. var texture = this.fontTexture;
  14646. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  14647. var ts = texture.getSize();
  14648. var offset = BABYLON.Vector2.Zero();
  14649. var lh = this.fontTexture.lineHeight;
  14650. d.dataElementCount = this._charCount;
  14651. d.curElement = 0;
  14652. var lineLengths = [];
  14653. var charWidths = [];
  14654. var charsPerLine = [];
  14655. var numCharsCurrenLine = 0;
  14656. var contentAreaWidth = this.contentArea.width;
  14657. var contentAreaHeight = this.contentArea.height;
  14658. var numCharsCurrentWord = 0;
  14659. var widthCurrentWord = 0;
  14660. var numWordsPerLine = 0;
  14661. var text = this.text;
  14662. var tabWidth = this._tabulationSize * texture.spaceWidth;
  14663. // First pass: analyze the text to build data like pixel length of each lines, width of each char, number of char per line
  14664. for (var i_1 = 0; i_1 < text.length; i_1++) {
  14665. var char = text[i_1];
  14666. numCharsCurrenLine++;
  14667. charWidths[i_1] = 0;
  14668. // Line feed
  14669. if (this._isWhiteSpaceCharVert(char)) {
  14670. lineLengths.push(offset.x);
  14671. charsPerLine.push(numCharsCurrenLine - 1);
  14672. numCharsCurrenLine = 1;
  14673. offset.x = 0;
  14674. if (widthCurrentWord > 0) {
  14675. numWordsPerLine++;
  14676. }
  14677. numWordsPerLine = 0;
  14678. numCharsCurrentWord = 0;
  14679. widthCurrentWord = 0;
  14680. continue;
  14681. }
  14682. var ci = texture.getChar(char);
  14683. var charWidth = 0;
  14684. if (char === "\t") {
  14685. charWidth = tabWidth;
  14686. }
  14687. else {
  14688. charWidth = ci.xAdvance;
  14689. }
  14690. offset.x += charWidth;
  14691. charWidths[i_1] = charWidth;
  14692. if (this._isWhiteSpaceCharHoriz(char)) {
  14693. if (widthCurrentWord > 0) {
  14694. numWordsPerLine++;
  14695. }
  14696. numCharsCurrentWord = 0;
  14697. widthCurrentWord = 0;
  14698. }
  14699. else {
  14700. widthCurrentWord += ci.xAdvance;
  14701. numCharsCurrentWord++;
  14702. }
  14703. if (this._wordWrap && numWordsPerLine > 0 && offset.x > contentAreaWidth) {
  14704. lineLengths.push(offset.x - widthCurrentWord);
  14705. numCharsCurrenLine -= numCharsCurrentWord;
  14706. var j = i_1 - numCharsCurrentWord;
  14707. //skip white space at the end of this line
  14708. while (this._isWhiteSpaceCharHoriz(text[j])) {
  14709. lineLengths[lineLengths.length - 1] -= charWidths[j];
  14710. j--;
  14711. }
  14712. charsPerLine.push(numCharsCurrenLine);
  14713. if (this._isWhiteSpaceCharHoriz(text[i_1])) {
  14714. //skip white space at the beginning of next line
  14715. var numSpaces = 0;
  14716. while (this._isWhiteSpaceCharHoriz(text[i_1 + numSpaces])) {
  14717. numSpaces++;
  14718. charWidths[i_1 + numSpaces] = 0;
  14719. }
  14720. i_1 += numSpaces - 1;
  14721. offset.x = 0;
  14722. numCharsCurrenLine = numSpaces - 1;
  14723. }
  14724. else {
  14725. numCharsCurrenLine = numCharsCurrentWord;
  14726. offset.x = widthCurrentWord;
  14727. }
  14728. numWordsPerLine = 0;
  14729. }
  14730. }
  14731. lineLengths.push(offset.x);
  14732. charsPerLine.push(numCharsCurrenLine);
  14733. //skip white space at the end
  14734. var i = text.length - 1;
  14735. while (this._isWhiteSpaceCharHoriz(text[i])) {
  14736. lineLengths[lineLengths.length - 1] -= charWidths[i];
  14737. i--;
  14738. }
  14739. var charNum = 0;
  14740. var maxLineLen = 0;
  14741. var alignH = this.textAlignmentH;
  14742. var alignV = this.textAlignmentV;
  14743. offset.x = 0;
  14744. if (alignH == Text2D_1.AlignRight || alignH == Text2D_1.AlignCenter) {
  14745. for (var i_2 = 0; i_2 < lineLengths.length; i_2++) {
  14746. if (lineLengths[i_2] > maxLineLen) {
  14747. maxLineLen = lineLengths[i_2];
  14748. }
  14749. }
  14750. }
  14751. var textHeight = lineLengths.length * lh;
  14752. var offsetX = this.padding.leftPixels;
  14753. if (alignH == Text2D_1.AlignRight) {
  14754. offsetX += contentAreaWidth - maxLineLen;
  14755. }
  14756. else if (alignH == Text2D_1.AlignCenter) {
  14757. offsetX += (contentAreaWidth - maxLineLen) * .5;
  14758. }
  14759. offset.x += offsetX;
  14760. offset.y += contentAreaHeight + textHeight - lh;
  14761. offset.y += this.padding.bottomPixels;
  14762. if (alignV == Text2D_1.AlignBottom) {
  14763. offset.y -= contentAreaHeight;
  14764. }
  14765. else if (alignV == Text2D_1.AlignCenter) {
  14766. offset.y -= (contentAreaHeight - textHeight) * .5 + lineLengths.length * lh;
  14767. }
  14768. else {
  14769. offset.y -= lineLengths.length * lh;
  14770. }
  14771. var lineHeight = texture.lineHeight;
  14772. for (var i_3 = 0; i_3 < lineLengths.length; i_3++) {
  14773. var numChars = charsPerLine[i_3];
  14774. var lineLength = lineLengths[i_3];
  14775. if (alignH == Text2D_1.AlignRight) {
  14776. offset.x += maxLineLen - lineLength;
  14777. }
  14778. else if (alignH == Text2D_1.AlignCenter) {
  14779. offset.x += (maxLineLen - lineLength) * .5;
  14780. }
  14781. for (var j = 0; j < numChars; j++) {
  14782. var char = text[charNum];
  14783. var charWidth = charWidths[charNum];
  14784. if (char !== "\t" && !this._isWhiteSpaceCharVert(char)) {
  14785. //make sure space char gets processed here or overlapping can occur when text is set
  14786. var ci = texture.getChar(char);
  14787. this.updateInstanceDataPart(d, new BABYLON.Vector2(offset.x + ci.xOffset, offset.y + ci.yOffset));
  14788. d.topLeftUV = ci.topLeftUV;
  14789. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  14790. d.sizeUV = suv;
  14791. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  14792. d.color = this.defaultFontColor;
  14793. d.superSampleFactor = superSampleFactor;
  14794. ++d.curElement;
  14795. }
  14796. offset.x += charWidth;
  14797. charNum++;
  14798. }
  14799. offset.x = offsetX;
  14800. offset.y -= lineHeight;
  14801. }
  14802. }
  14803. return true;
  14804. };
  14805. Text2D.prototype._isWhiteSpaceCharHoriz = function (char) {
  14806. if (char === " " || char === "\t") {
  14807. return true;
  14808. }
  14809. };
  14810. Text2D.prototype._isWhiteSpaceCharVert = function (char) {
  14811. if (char === "\n" || char === "\r") {
  14812. return true;
  14813. }
  14814. };
  14815. Text2D.prototype._updateCharCount = function () {
  14816. var count = 0;
  14817. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  14818. var char = _a[_i];
  14819. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  14820. continue;
  14821. }
  14822. ++count;
  14823. }
  14824. this._charCount = count;
  14825. };
  14826. Text2D.prototype._setTextAlignmentfromString = function (value) {
  14827. var m = value.trim().split(",");
  14828. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  14829. var v = m_1[_i];
  14830. v = v.toLocaleLowerCase().trim();
  14831. // Horizontal
  14832. var i = v.indexOf("h:");
  14833. if (i === -1) {
  14834. i = v.indexOf("horizontal:");
  14835. }
  14836. if (i !== -1) {
  14837. v = v.substr(v.indexOf(":") + 1);
  14838. this._setTextAlignmentHorizontal(v);
  14839. continue;
  14840. }
  14841. // Vertical
  14842. i = v.indexOf("v:");
  14843. if (i === -1) {
  14844. i = v.indexOf("vertical:");
  14845. }
  14846. if (i !== -1) {
  14847. v = v.substr(v.indexOf(":") + 1);
  14848. this._setTextAlignmentVertical(v);
  14849. continue;
  14850. }
  14851. }
  14852. };
  14853. Text2D.prototype._setTextAlignmentHorizontal = function (text) {
  14854. var v = text.trim().toLocaleLowerCase();
  14855. switch (v) {
  14856. case "left":
  14857. this.textAlignmentH = Text2D_1.AlignLeft;
  14858. return;
  14859. case "right":
  14860. this.textAlignmentH = Text2D_1.AlignRight;
  14861. return;
  14862. case "center":
  14863. this.textAlignmentH = Text2D_1.AlignCenter;
  14864. return;
  14865. }
  14866. };
  14867. Text2D.prototype._setTextAlignmentVertical = function (text) {
  14868. var v = text.trim().toLocaleLowerCase();
  14869. switch (v) {
  14870. case "top":
  14871. this.textAlignmentV = Text2D_1.AlignTop;
  14872. return;
  14873. case "bottom":
  14874. this.textAlignmentV = Text2D_1.AlignBottom;
  14875. return;
  14876. case "center":
  14877. this.textAlignmentV = Text2D_1.AlignCenter;
  14878. return;
  14879. }
  14880. };
  14881. Text2D.prototype._useTextureAlpha = function () {
  14882. return this._fontSDF;
  14883. };
  14884. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  14885. return !this._fontSDF;
  14886. };
  14887. return Text2D;
  14888. }(BABYLON.RenderablePrim2D));
  14889. Text2D.TEXT2D_MAINPARTID = 1;
  14890. Text2D.TEXT2D_CATEGORY_SDF = "SignedDistanceField";
  14891. Text2D._AlignLeft = 1;
  14892. Text2D._AlignTop = 1; // Same as left
  14893. Text2D._AlignRight = 2;
  14894. Text2D._AlignBottom = 2; // Same as right
  14895. Text2D._AlignCenter = 3;
  14896. __decorate([
  14897. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D_1.fontProperty = pi; }, false, true)
  14898. ], Text2D.prototype, "fontName", null);
  14899. __decorate([
  14900. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D_1.defaultFontColorProperty = pi; })
  14901. ], Text2D.prototype, "defaultFontColor", null);
  14902. __decorate([
  14903. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D_1.textProperty = pi; }, false, true)
  14904. ], Text2D.prototype, "text", null);
  14905. __decorate([
  14906. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D_1.sizeProperty = pi; })
  14907. ], Text2D.prototype, "size", null);
  14908. __decorate([
  14909. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  14910. ], Text2D.prototype, "fontSuperSample", null);
  14911. __decorate([
  14912. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Text2D_1.fontSuperSampleProperty = pi; }, false, false)
  14913. ], Text2D.prototype, "fontSignedDistanceField", null);
  14914. Text2D = Text2D_1 = __decorate([
  14915. BABYLON.className("Text2D", "BABYLON")
  14916. ], Text2D);
  14917. BABYLON.Text2D = Text2D;
  14918. var Text2D_1;
  14919. })(BABYLON || (BABYLON = {}));
  14920. var __extends = (this && this.__extends) || function (d, b) {
  14921. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  14922. function __() { this.constructor = d; }
  14923. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14924. };
  14925. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  14926. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  14927. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  14928. 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;
  14929. return c > 3 && r && Object.defineProperty(target, key, r), r;
  14930. };
  14931. var BABYLON;
  14932. (function (BABYLON) {
  14933. var Lines2DRenderCache = (function (_super) {
  14934. __extends(Lines2DRenderCache, _super);
  14935. function Lines2DRenderCache(engine, modelKey) {
  14936. var _this = _super.call(this, engine, modelKey) || this;
  14937. _this.effectsReady = false;
  14938. _this.fillVB = null;
  14939. _this.fillIB = null;
  14940. _this.fillIndicesCount = 0;
  14941. _this.instancingFillAttributes = null;
  14942. _this.effectFill = null;
  14943. _this.effectFillInstanced = null;
  14944. _this.borderVB = null;
  14945. _this.borderIB = null;
  14946. _this.borderIndicesCount = 0;
  14947. _this.instancingBorderAttributes = null;
  14948. _this.effectBorder = null;
  14949. _this.effectBorderInstanced = null;
  14950. return _this;
  14951. }
  14952. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  14953. // Do nothing if the shader is still loading/preparing
  14954. if (!this.effectsReady) {
  14955. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  14956. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  14957. return false;
  14958. }
  14959. this.effectsReady = true;
  14960. }
  14961. var canvas = instanceInfo.owner.owner;
  14962. var engine = canvas.engine;
  14963. engine.setState(false, undefined, true);
  14964. var depthFunction = 0;
  14965. if (this.effectFill && this.effectBorder) {
  14966. depthFunction = engine.getDepthFunction();
  14967. engine.setDepthFunctionToLessOrEqual();
  14968. }
  14969. var curAlphaMode = engine.getAlphaMode();
  14970. if (this.effectFill) {
  14971. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  14972. var pid = context.groupInfoPartData[partIndex];
  14973. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  14974. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  14975. }
  14976. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  14977. engine.enableEffect(effect);
  14978. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  14979. if (context.useInstancing) {
  14980. if (!this.instancingFillAttributes) {
  14981. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  14982. }
  14983. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  14984. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  14985. canvas._addDrawCallCount(1, context.renderMode);
  14986. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  14987. engine.draw(true, 0, this.fillIndicesCount, count);
  14988. engine.unbindInstanceAttributes();
  14989. }
  14990. else {
  14991. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  14992. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  14993. this.setupUniforms(effect, partIndex, pid._partData, i);
  14994. engine.draw(true, 0, this.fillIndicesCount);
  14995. }
  14996. }
  14997. }
  14998. if (this.effectBorder) {
  14999. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  15000. var pid = context.groupInfoPartData[partIndex];
  15001. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  15002. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  15003. }
  15004. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  15005. engine.enableEffect(effect);
  15006. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  15007. if (context.useInstancing) {
  15008. if (!this.instancingBorderAttributes) {
  15009. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  15010. }
  15011. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  15012. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  15013. canvas._addDrawCallCount(1, context.renderMode);
  15014. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  15015. engine.draw(true, 0, this.borderIndicesCount, count);
  15016. engine.unbindInstanceAttributes();
  15017. }
  15018. else {
  15019. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  15020. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  15021. this.setupUniforms(effect, partIndex, pid._partData, i);
  15022. engine.draw(true, 0, this.borderIndicesCount);
  15023. }
  15024. }
  15025. }
  15026. engine.setAlphaMode(curAlphaMode, true);
  15027. if (this.effectFill && this.effectBorder) {
  15028. engine.setDepthFunction(depthFunction);
  15029. }
  15030. return true;
  15031. };
  15032. Lines2DRenderCache.prototype.dispose = function () {
  15033. if (!_super.prototype.dispose.call(this)) {
  15034. return false;
  15035. }
  15036. if (this.fillVB) {
  15037. this._engine._releaseBuffer(this.fillVB);
  15038. this.fillVB = null;
  15039. }
  15040. if (this.fillIB) {
  15041. this._engine._releaseBuffer(this.fillIB);
  15042. this.fillIB = null;
  15043. }
  15044. this.effectFill = null;
  15045. this.effectFillInstanced = null;
  15046. this.effectBorder = null;
  15047. this.effectBorderInstanced = null;
  15048. if (this.borderVB) {
  15049. this._engine._releaseBuffer(this.borderVB);
  15050. this.borderVB = null;
  15051. }
  15052. if (this.borderIB) {
  15053. this._engine._releaseBuffer(this.borderIB);
  15054. this.borderIB = null;
  15055. }
  15056. return true;
  15057. };
  15058. return Lines2DRenderCache;
  15059. }(BABYLON.ModelRenderCache));
  15060. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  15061. var Lines2DInstanceData = (function (_super) {
  15062. __extends(Lines2DInstanceData, _super);
  15063. function Lines2DInstanceData(partId) {
  15064. return _super.call(this, partId, 1) || this;
  15065. }
  15066. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  15067. get: function () {
  15068. return null;
  15069. },
  15070. set: function (value) {
  15071. },
  15072. enumerable: true,
  15073. configurable: true
  15074. });
  15075. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  15076. get: function () {
  15077. return null;
  15078. },
  15079. set: function (value) {
  15080. },
  15081. enumerable: true,
  15082. configurable: true
  15083. });
  15084. return Lines2DInstanceData;
  15085. }(BABYLON.Shape2DInstanceData));
  15086. __decorate([
  15087. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  15088. ], Lines2DInstanceData.prototype, "boundingMin", null);
  15089. __decorate([
  15090. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  15091. ], Lines2DInstanceData.prototype, "boundingMax", null);
  15092. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  15093. var Lines2D = Lines2D_1 = (function (_super) {
  15094. __extends(Lines2D, _super);
  15095. /**
  15096. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  15097. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  15098. * @param settings a combination of settings, possible ones are
  15099. * - 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)
  15100. * - children: an array of direct children
  15101. * - id a text identifier, for information purpose
  15102. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  15103. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  15104. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  15105. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  15106. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  15107. * - zOrder: override the zOrder with the specified value
  15108. * - origin: define the normalized origin point location, default [0.5;0.5]
  15109. * - 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.
  15110. * - 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.
  15111. * - 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.
  15112. * - 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.
  15113. * - 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)
  15114. * - 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)
  15115. * - borderThickness: the thickness of the drawn border, default is 1.
  15116. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  15117. * - 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.
  15118. * - 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.
  15119. * - 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!
  15120. * - 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.
  15121. * - 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).
  15122. * - layoutData: a instance of a class implementing the ILayoutData interface that contain data to pass to the primitive parent's layout engine
  15123. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15124. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15125. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15126. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15127. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  15128. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  15129. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  15130. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  15131. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15132. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15133. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15134. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  15135. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  15136. */
  15137. function Lines2D(points, settings) {
  15138. var _this = this;
  15139. if (!settings) {
  15140. settings = {};
  15141. }
  15142. _this = _super.call(this, settings) || this;
  15143. _this._fillVB = null;
  15144. _this._fillIB = null;
  15145. _this._borderVB = null;
  15146. _this._borderIB = null;
  15147. _this._size = BABYLON.Size.Zero();
  15148. _this._boundingMin = null;
  15149. _this._boundingMax = null;
  15150. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  15151. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  15152. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  15153. var closed = (settings.closed == null) ? false : settings.closed;
  15154. _this.points = points;
  15155. _this.fillThickness = fillThickness;
  15156. _this.startCap = startCap;
  15157. _this.endCap = endCap;
  15158. _this.closed = closed;
  15159. return _this;
  15160. }
  15161. Object.defineProperty(Lines2D, "NoCap", {
  15162. /**
  15163. * No Cap to apply on the extremity
  15164. */
  15165. get: function () { return Lines2D_1._noCap; },
  15166. enumerable: true,
  15167. configurable: true
  15168. });
  15169. Object.defineProperty(Lines2D, "RoundCap", {
  15170. /**
  15171. * A round cap, will use the line thickness as diameter
  15172. */
  15173. get: function () { return Lines2D_1._roundCap; },
  15174. enumerable: true,
  15175. configurable: true
  15176. });
  15177. Object.defineProperty(Lines2D, "TriangleCap", {
  15178. /**
  15179. * Creates a triangle at the extremity.
  15180. */
  15181. get: function () { return Lines2D_1._triangleCap; },
  15182. enumerable: true,
  15183. configurable: true
  15184. });
  15185. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  15186. /**
  15187. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  15188. */
  15189. get: function () { return Lines2D_1._squareAnchorCap; },
  15190. enumerable: true,
  15191. configurable: true
  15192. });
  15193. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  15194. /**
  15195. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  15196. */
  15197. get: function () { return Lines2D_1._roundAnchorCap; },
  15198. enumerable: true,
  15199. configurable: true
  15200. });
  15201. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  15202. /**
  15203. * Creates a diamond anchor at the extremity.
  15204. */
  15205. get: function () { return Lines2D_1._diamondAnchorCap; },
  15206. enumerable: true,
  15207. configurable: true
  15208. });
  15209. Object.defineProperty(Lines2D, "ArrowCap", {
  15210. /**
  15211. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  15212. */
  15213. get: function () { return Lines2D_1._arrowCap; },
  15214. enumerable: true,
  15215. configurable: true
  15216. });
  15217. Object.defineProperty(Lines2D.prototype, "points", {
  15218. get: function () {
  15219. return this._points;
  15220. },
  15221. set: function (value) {
  15222. this._points = value;
  15223. this._primTriArrayDirty = true;
  15224. this._boundingBoxDirty();
  15225. },
  15226. enumerable: true,
  15227. configurable: true
  15228. });
  15229. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  15230. get: function () {
  15231. return this._fillThickness;
  15232. },
  15233. set: function (value) {
  15234. this._fillThickness = value;
  15235. },
  15236. enumerable: true,
  15237. configurable: true
  15238. });
  15239. Object.defineProperty(Lines2D.prototype, "closed", {
  15240. get: function () {
  15241. return this._closed;
  15242. },
  15243. set: function (value) {
  15244. this._closed = value;
  15245. },
  15246. enumerable: true,
  15247. configurable: true
  15248. });
  15249. Object.defineProperty(Lines2D.prototype, "startCap", {
  15250. get: function () {
  15251. return this._startCap;
  15252. },
  15253. set: function (value) {
  15254. this._startCap = value;
  15255. },
  15256. enumerable: true,
  15257. configurable: true
  15258. });
  15259. Object.defineProperty(Lines2D.prototype, "endCap", {
  15260. get: function () {
  15261. return this._endCap;
  15262. },
  15263. set: function (value) {
  15264. this._endCap = value;
  15265. },
  15266. enumerable: true,
  15267. configurable: true
  15268. });
  15269. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  15270. var p = intersectInfo._localPickPosition;
  15271. this.updateTriArray();
  15272. return this._primTriArray.doesContain(p);
  15273. };
  15274. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  15275. get: function () {
  15276. if (!this._boundingMin) {
  15277. this._computeLines2D();
  15278. }
  15279. return this._boundingMin;
  15280. },
  15281. enumerable: true,
  15282. configurable: true
  15283. });
  15284. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  15285. get: function () {
  15286. if (!this._boundingMax) {
  15287. this._computeLines2D();
  15288. }
  15289. return this._boundingMax;
  15290. },
  15291. enumerable: true,
  15292. configurable: true
  15293. });
  15294. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  15295. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  15296. // Remove the BORDER category, we don't use it in the VertexShader
  15297. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  15298. if (i !== -1) {
  15299. res.splice(i, 1);
  15300. }
  15301. return res;
  15302. };
  15303. Lines2D.prototype.updateLevelBoundingInfo = function () {
  15304. if (!this._size) {
  15305. return false;
  15306. }
  15307. if (!this._boundingMin) {
  15308. this._computeLines2D();
  15309. }
  15310. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  15311. return true;
  15312. };
  15313. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  15314. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  15315. return renderCache;
  15316. };
  15317. ///////////////////////////////////////////////////////////////////////////////////
  15318. // Methods for Lines building
  15319. Lines2D.prototype._perp = function (v, res) {
  15320. res.x = v.y;
  15321. res.y = -v.x;
  15322. };
  15323. ;
  15324. Lines2D.prototype._direction = function (a, b, res) {
  15325. a.subtractToRef(b, res);
  15326. res.normalize();
  15327. };
  15328. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  15329. a.addToRef(b, tangent);
  15330. tangent.normalize();
  15331. miter.x = -tangent.y;
  15332. miter.y = tangent.x;
  15333. Lines2D_1._miterTps.x = -a.y;
  15334. Lines2D_1._miterTps.y = a.x;
  15335. return 1 / BABYLON.Vector2.Dot(miter, Lines2D_1._miterTps);
  15336. };
  15337. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  15338. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  15339. if (d === 0)
  15340. return false;
  15341. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  15342. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  15343. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  15344. return false;
  15345. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  15346. return false;
  15347. return true;
  15348. };
  15349. Lines2D.prototype._updateMinMax = function (array, offset) {
  15350. if (offset >= array.length) {
  15351. return;
  15352. }
  15353. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  15354. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  15355. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  15356. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  15357. };
  15358. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  15359. var borderMode = borderThickness != null && !isNaN(borderThickness);
  15360. var off = index * (borderMode ? 8 : 4);
  15361. // 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)
  15362. if (off >= array.length) {
  15363. return;
  15364. }
  15365. // Store start/end normal, we need it for the cap construction
  15366. if (index === 0) {
  15367. this._perp(n, Lines2D_1._startDir);
  15368. }
  15369. else if (index === max - 1) {
  15370. this._perp(n, Lines2D_1._endDir);
  15371. Lines2D_1._endDir.x *= -1;
  15372. Lines2D_1._endDir.y *= -1;
  15373. }
  15374. var swap = false;
  15375. array[off + 0] = p.x + n.x * halfThickness;
  15376. array[off + 1] = p.y + n.y * halfThickness;
  15377. array[off + 2] = p.x + n.x * -halfThickness;
  15378. array[off + 3] = p.y + n.y * -halfThickness;
  15379. this._updateMinMax(array, off);
  15380. this._updateMinMax(array, off + 2);
  15381. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  15382. // 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
  15383. if (detectFlip != 0) {
  15384. // Flip if intersect
  15385. var flipOff = detectFlip * (borderMode ? 8 : 4);
  15386. 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])) {
  15387. swap = true;
  15388. var tps = array[off + 0];
  15389. array[off + 0] = array[off + 2];
  15390. array[off + 2] = tps;
  15391. tps = array[off + 1];
  15392. array[off + 1] = array[off + 3];
  15393. array[off + 3] = tps;
  15394. }
  15395. }
  15396. if (borderMode) {
  15397. var t = halfThickness + borderThickness;
  15398. array[off + 4] = p.x + n.x * (swap ? -t : t);
  15399. array[off + 5] = p.y + n.y * (swap ? -t : t);
  15400. array[off + 6] = p.x + n.x * (swap ? t : -t);
  15401. array[off + 7] = p.y + n.y * (swap ? t : -t);
  15402. this._updateMinMax(array, off + 4);
  15403. this._updateMinMax(array, off + 6);
  15404. }
  15405. if (contour) {
  15406. off += borderMode ? 4 : 0;
  15407. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  15408. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  15409. }
  15410. };
  15411. Lines2D.prototype._getCapSize = function (type, border) {
  15412. if (border === void 0) { border = false; }
  15413. var sd = Lines2D_1._roundCapSubDiv;
  15414. // If no array given, we call this to get the size
  15415. var vbsize = 0, ibsize = 0;
  15416. switch (type) {
  15417. case Lines2D_1.NoCap:
  15418. {
  15419. // If the line is not close and we're computing border, we add the size to generate the edge border
  15420. if (!this.closed && border) {
  15421. vbsize = 4;
  15422. ibsize = 6;
  15423. }
  15424. else {
  15425. vbsize = ibsize = 0;
  15426. }
  15427. break;
  15428. }
  15429. case Lines2D_1.RoundCap:
  15430. {
  15431. if (border) {
  15432. vbsize = sd;
  15433. ibsize = (sd - 2) * 3;
  15434. }
  15435. else {
  15436. vbsize = (sd / 2) + 1;
  15437. ibsize = (sd / 2) * 3;
  15438. }
  15439. break;
  15440. }
  15441. case Lines2D_1.ArrowCap:
  15442. {
  15443. if (border) {
  15444. vbsize = 12;
  15445. ibsize = 24;
  15446. }
  15447. else {
  15448. vbsize = 3;
  15449. ibsize = 3;
  15450. }
  15451. break;
  15452. }
  15453. case Lines2D_1.TriangleCap:
  15454. {
  15455. if (border) {
  15456. vbsize = 6;
  15457. ibsize = 12;
  15458. }
  15459. else {
  15460. vbsize = 3;
  15461. ibsize = 3;
  15462. }
  15463. break;
  15464. }
  15465. case Lines2D_1.DiamondAnchorCap:
  15466. {
  15467. if (border) {
  15468. vbsize = 10;
  15469. ibsize = 24;
  15470. }
  15471. else {
  15472. vbsize = 5;
  15473. ibsize = 9;
  15474. }
  15475. break;
  15476. }
  15477. case Lines2D_1.SquareAnchorCap:
  15478. {
  15479. if (border) {
  15480. vbsize = 12;
  15481. ibsize = 30;
  15482. }
  15483. else {
  15484. vbsize = 4;
  15485. ibsize = 6;
  15486. }
  15487. break;
  15488. }
  15489. case Lines2D_1.RoundAnchorCap:
  15490. {
  15491. if (border) {
  15492. vbsize = sd * 2;
  15493. ibsize = (sd - 1) * 6;
  15494. }
  15495. else {
  15496. vbsize = sd + 1;
  15497. ibsize = (sd + 1) * 3;
  15498. }
  15499. break;
  15500. }
  15501. }
  15502. return { vbsize: vbsize * 2, ibsize: ibsize };
  15503. };
  15504. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  15505. var c = Math.cos(rotation);
  15506. var s = Math.sin(rotation);
  15507. Lines2D_1._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  15508. Lines2D_1._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  15509. var offset = baseOffset + (index * 2);
  15510. vb[offset + 0] = Lines2D_1._tpsV.x;
  15511. vb[offset + 1] = Lines2D_1._tpsV.y;
  15512. if (contour) {
  15513. contour.push(Lines2D_1._tpsV.x);
  15514. contour.push(Lines2D_1._tpsV.y);
  15515. }
  15516. this._updateMinMax(vb, offset);
  15517. return (baseOffset + index * 2) / 2;
  15518. };
  15519. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  15520. ib[baseOffset + index] = vertexIndex;
  15521. };
  15522. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  15523. // 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
  15524. var sd = Lines2D_1._roundCapSubDiv;
  15525. var dir = new BABYLON.Vector2(1, 0);
  15526. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  15527. var ht = thickness / 2;
  15528. var t = thickness;
  15529. var borderMode = borderThickness != null;
  15530. var bt = borderThickness;
  15531. switch (type) {
  15532. case Lines2D_1.NoCap:
  15533. if (borderMode && !this.closed) {
  15534. var vi = 0;
  15535. var ii = 0;
  15536. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  15537. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  15538. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  15539. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  15540. this._storeIndex(ib, ibi, ii++, v1);
  15541. this._storeIndex(ib, ibi, ii++, v2);
  15542. this._storeIndex(ib, ibi, ii++, v3);
  15543. this._storeIndex(ib, ibi, ii++, v1);
  15544. this._storeIndex(ib, ibi, ii++, v3);
  15545. this._storeIndex(ib, ibi, ii++, v4);
  15546. }
  15547. break;
  15548. case Lines2D_1.ArrowCap:
  15549. ht *= 2;
  15550. case Lines2D_1.TriangleCap:
  15551. {
  15552. if (borderMode) {
  15553. var f = type === Lines2D_1.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  15554. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  15555. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  15556. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  15557. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  15558. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  15559. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  15560. var ii = 0;
  15561. this._storeIndex(ib, ibi, ii++, v1);
  15562. this._storeIndex(ib, ibi, ii++, v4);
  15563. this._storeIndex(ib, ibi, ii++, v5);
  15564. this._storeIndex(ib, ibi, ii++, v1);
  15565. this._storeIndex(ib, ibi, ii++, v5);
  15566. this._storeIndex(ib, ibi, ii++, v2);
  15567. this._storeIndex(ib, ibi, ii++, v6);
  15568. this._storeIndex(ib, ibi, ii++, v3);
  15569. this._storeIndex(ib, ibi, ii++, v2);
  15570. this._storeIndex(ib, ibi, ii++, v6);
  15571. this._storeIndex(ib, ibi, ii++, v2);
  15572. this._storeIndex(ib, ibi, ii++, v5);
  15573. if (type === Lines2D_1.ArrowCap) {
  15574. var rht = thickness / 2;
  15575. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  15576. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  15577. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  15578. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  15579. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  15580. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  15581. this._storeIndex(ib, ibi, ii++, v7);
  15582. this._storeIndex(ib, ibi, ii++, v8);
  15583. this._storeIndex(ib, ibi, ii++, v9);
  15584. this._storeIndex(ib, ibi, ii++, v7);
  15585. this._storeIndex(ib, ibi, ii++, v9);
  15586. this._storeIndex(ib, ibi, ii++, v4);
  15587. this._storeIndex(ib, ibi, ii++, v10);
  15588. this._storeIndex(ib, ibi, ii++, v12);
  15589. this._storeIndex(ib, ibi, ii++, v11);
  15590. this._storeIndex(ib, ibi, ii++, v10);
  15591. this._storeIndex(ib, ibi, ii++, v6);
  15592. this._storeIndex(ib, ibi, ii++, v12);
  15593. }
  15594. }
  15595. else {
  15596. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  15597. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  15598. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  15599. this._storeIndex(ib, ibi, 0, v1);
  15600. this._storeIndex(ib, ibi, 1, v2);
  15601. this._storeIndex(ib, ibi, 2, v3);
  15602. }
  15603. break;
  15604. }
  15605. case Lines2D_1.RoundCap:
  15606. {
  15607. if (borderMode) {
  15608. var curA = -Math.PI / 2;
  15609. var incA = Math.PI / (sd / 2 - 1);
  15610. var ii = 0;
  15611. for (var i = 0; i < (sd / 2); i++) {
  15612. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  15613. 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);
  15614. if (i > 0) {
  15615. this._storeIndex(ib, ibi, ii++, v1 - 2);
  15616. this._storeIndex(ib, ibi, ii++, v2 - 2);
  15617. this._storeIndex(ib, ibi, ii++, v2);
  15618. this._storeIndex(ib, ibi, ii++, v1 - 2);
  15619. this._storeIndex(ib, ibi, ii++, v2);
  15620. this._storeIndex(ib, ibi, ii++, v1);
  15621. }
  15622. curA += incA;
  15623. }
  15624. }
  15625. else {
  15626. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  15627. var curA = -Math.PI / 2;
  15628. var incA = Math.PI / (sd / 2 - 1);
  15629. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  15630. curA += incA;
  15631. for (var i = 1; i < (sd / 2); i++) {
  15632. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  15633. this._storeIndex(ib, ibi, i * 3 + 0, c);
  15634. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  15635. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  15636. curA += incA;
  15637. }
  15638. }
  15639. break;
  15640. }
  15641. case Lines2D_1.SquareAnchorCap:
  15642. {
  15643. var vi = 0;
  15644. var c = borderMode ? null : contour;
  15645. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  15646. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  15647. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  15648. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  15649. if (borderMode) {
  15650. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  15651. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  15652. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  15653. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  15654. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  15655. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  15656. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  15657. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  15658. var ii = 0;
  15659. this._storeIndex(ib, ibi, ii++, v6);
  15660. this._storeIndex(ib, ibi, ii++, v1);
  15661. this._storeIndex(ib, ibi, ii++, v5);
  15662. this._storeIndex(ib, ibi, ii++, v6);
  15663. this._storeIndex(ib, ibi, ii++, v7);
  15664. this._storeIndex(ib, ibi, ii++, v1);
  15665. this._storeIndex(ib, ibi, ii++, v1);
  15666. this._storeIndex(ib, ibi, ii++, v7);
  15667. this._storeIndex(ib, ibi, ii++, v8);
  15668. this._storeIndex(ib, ibi, ii++, v1);
  15669. this._storeIndex(ib, ibi, ii++, v8);
  15670. this._storeIndex(ib, ibi, ii++, v2);
  15671. this._storeIndex(ib, ibi, ii++, v2);
  15672. this._storeIndex(ib, ibi, ii++, v8);
  15673. this._storeIndex(ib, ibi, ii++, v9);
  15674. this._storeIndex(ib, ibi, ii++, v2);
  15675. this._storeIndex(ib, ibi, ii++, v9);
  15676. this._storeIndex(ib, ibi, ii++, v3);
  15677. this._storeIndex(ib, ibi, ii++, v3);
  15678. this._storeIndex(ib, ibi, ii++, v9);
  15679. this._storeIndex(ib, ibi, ii++, v10);
  15680. this._storeIndex(ib, ibi, ii++, v3);
  15681. this._storeIndex(ib, ibi, ii++, v10);
  15682. this._storeIndex(ib, ibi, ii++, v4);
  15683. this._storeIndex(ib, ibi, ii++, v10);
  15684. this._storeIndex(ib, ibi, ii++, v11);
  15685. this._storeIndex(ib, ibi, ii++, v4);
  15686. this._storeIndex(ib, ibi, ii++, v11);
  15687. this._storeIndex(ib, ibi, ii++, v12);
  15688. this._storeIndex(ib, ibi, ii++, v4);
  15689. }
  15690. else {
  15691. this._storeIndex(ib, ibi, 0, v1);
  15692. this._storeIndex(ib, ibi, 1, v2);
  15693. this._storeIndex(ib, ibi, 2, v3);
  15694. this._storeIndex(ib, ibi, 3, v1);
  15695. this._storeIndex(ib, ibi, 4, v3);
  15696. this._storeIndex(ib, ibi, 5, v4);
  15697. }
  15698. break;
  15699. }
  15700. case Lines2D_1.RoundAnchorCap:
  15701. {
  15702. var cpos = Math.sqrt(t * t - ht * ht);
  15703. var center = new BABYLON.Vector2(cpos, 0);
  15704. var curA = BABYLON.Tools.ToRadians(-150);
  15705. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  15706. if (borderMode) {
  15707. var ii = 0;
  15708. for (var i = 0; i < sd; i++) {
  15709. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  15710. 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);
  15711. if (i > 0) {
  15712. this._storeIndex(ib, ibi, ii++, v1 - 2);
  15713. this._storeIndex(ib, ibi, ii++, v2 - 2);
  15714. this._storeIndex(ib, ibi, ii++, v2);
  15715. this._storeIndex(ib, ibi, ii++, v1 - 2);
  15716. this._storeIndex(ib, ibi, ii++, v2);
  15717. this._storeIndex(ib, ibi, ii++, v1);
  15718. }
  15719. curA += incA;
  15720. }
  15721. }
  15722. else {
  15723. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  15724. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  15725. curA += incA;
  15726. for (var i = 1; i < sd; i++) {
  15727. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  15728. this._storeIndex(ib, ibi, i * 3 + 0, c);
  15729. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  15730. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  15731. curA += incA;
  15732. }
  15733. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  15734. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  15735. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  15736. }
  15737. break;
  15738. }
  15739. case Lines2D_1.DiamondAnchorCap:
  15740. {
  15741. var vi = 0;
  15742. var c = borderMode ? null : contour;
  15743. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  15744. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  15745. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  15746. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  15747. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  15748. if (borderMode) {
  15749. var f = Math.sqrt(bt * bt * 2);
  15750. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  15751. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  15752. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  15753. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  15754. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  15755. var ii = 0;
  15756. this._storeIndex(ib, ibi, ii++, v6);
  15757. this._storeIndex(ib, ibi, ii++, v7);
  15758. this._storeIndex(ib, ibi, ii++, v1);
  15759. this._storeIndex(ib, ibi, ii++, v1);
  15760. this._storeIndex(ib, ibi, ii++, v7);
  15761. this._storeIndex(ib, ibi, ii++, v2);
  15762. this._storeIndex(ib, ibi, ii++, v2);
  15763. this._storeIndex(ib, ibi, ii++, v7);
  15764. this._storeIndex(ib, ibi, ii++, v8);
  15765. this._storeIndex(ib, ibi, ii++, v2);
  15766. this._storeIndex(ib, ibi, ii++, v8);
  15767. this._storeIndex(ib, ibi, ii++, v3);
  15768. this._storeIndex(ib, ibi, ii++, v3);
  15769. this._storeIndex(ib, ibi, ii++, v8);
  15770. this._storeIndex(ib, ibi, ii++, v9);
  15771. this._storeIndex(ib, ibi, ii++, v3);
  15772. this._storeIndex(ib, ibi, ii++, v9);
  15773. this._storeIndex(ib, ibi, ii++, v4);
  15774. this._storeIndex(ib, ibi, ii++, v4);
  15775. this._storeIndex(ib, ibi, ii++, v9);
  15776. this._storeIndex(ib, ibi, ii++, v10);
  15777. this._storeIndex(ib, ibi, ii++, v4);
  15778. this._storeIndex(ib, ibi, ii++, v10);
  15779. this._storeIndex(ib, ibi, ii++, v5);
  15780. }
  15781. else {
  15782. this._storeIndex(ib, ibi, 0, v1);
  15783. this._storeIndex(ib, ibi, 1, v2);
  15784. this._storeIndex(ib, ibi, 2, v3);
  15785. this._storeIndex(ib, ibi, 3, v1);
  15786. this._storeIndex(ib, ibi, 4, v3);
  15787. this._storeIndex(ib, ibi, 5, v5);
  15788. this._storeIndex(ib, ibi, 6, v5);
  15789. this._storeIndex(ib, ibi, 7, v3);
  15790. this._storeIndex(ib, ibi, 8, v4);
  15791. }
  15792. break;
  15793. }
  15794. }
  15795. return null;
  15796. };
  15797. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  15798. var lineA = BABYLON.Vector2.Zero();
  15799. var lineB = BABYLON.Vector2.Zero();
  15800. var tangent = BABYLON.Vector2.Zero();
  15801. var miter = BABYLON.Vector2.Zero();
  15802. var curNormal = null;
  15803. if (this.closed) {
  15804. this.points.push(this.points[0]);
  15805. }
  15806. var total = this.points.length;
  15807. for (var i = 1; i < total; i++) {
  15808. var last = this.points[i - 1];
  15809. var cur = this.points[i];
  15810. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  15811. this._direction(cur, last, lineA);
  15812. if (!curNormal) {
  15813. curNormal = BABYLON.Vector2.Zero();
  15814. this._perp(lineA, curNormal);
  15815. }
  15816. if (i === 1) {
  15817. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  15818. }
  15819. if (!next) {
  15820. this._perp(lineA, curNormal);
  15821. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  15822. }
  15823. else {
  15824. this._direction(next, cur, lineB);
  15825. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  15826. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  15827. }
  15828. }
  15829. if (this.points.length > 2 && this.closed) {
  15830. var last2 = this.points[total - 2];
  15831. var cur2 = this.points[0];
  15832. var next2 = this.points[1];
  15833. this._direction(cur2, last2, lineA);
  15834. this._direction(next2, cur2, lineB);
  15835. this._perp(lineA, curNormal);
  15836. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  15837. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  15838. // Patch contour
  15839. if (contour) {
  15840. var off = (bt == null) ? 0 : 4;
  15841. contour[0].x = vb[off + 0];
  15842. contour[0].y = vb[off + 1];
  15843. contour[1].x = vb[off + 2];
  15844. contour[1].y = vb[off + 3];
  15845. }
  15846. }
  15847. // Remove the point we added at the beginning
  15848. if (this.closed) {
  15849. this.points.splice(total - 1);
  15850. }
  15851. };
  15852. // Methods for Lines building
  15853. ///////////////////////////////////////////////////////////////////////////////////
  15854. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  15855. var renderCache = modelRenderCache;
  15856. var engine = this.owner.engine;
  15857. if (this._fillVB === null) {
  15858. this._computeLines2D();
  15859. }
  15860. // Need to create WebGL resources for fill part?
  15861. if (this.fill) {
  15862. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  15863. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  15864. renderCache.fillIndicesCount = this._fillIB.length;
  15865. // 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
  15866. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  15867. if (ei) {
  15868. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  15869. }
  15870. // Get the non instanced version
  15871. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  15872. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  15873. }
  15874. // Need to create WebGL resources for border part?
  15875. if (this.border) {
  15876. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  15877. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  15878. renderCache.borderIndicesCount = this._borderIB.length;
  15879. // 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
  15880. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  15881. if (ei) {
  15882. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  15883. }
  15884. // Get the non instanced version
  15885. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  15886. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  15887. }
  15888. this._fillVB = null;
  15889. this._fillIB = null;
  15890. this._borderVB = null;
  15891. this._borderIB = null;
  15892. return renderCache;
  15893. };
  15894. Lines2D.prototype.updateTriArray = function () {
  15895. if (this._primTriArrayDirty) {
  15896. this._computeLines2D();
  15897. }
  15898. };
  15899. Lines2D.prototype._computeLines2D = function () {
  15900. var _this = this;
  15901. // Init min/max because their being computed here
  15902. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  15903. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  15904. var contour = new Array();
  15905. var startCapContour = new Array();
  15906. var endCapContour = new Array();
  15907. // Need to create WebGL resources for fill part?
  15908. if (this.fill) {
  15909. var startCapInfo = this._getCapSize(this.startCap);
  15910. var endCapInfo = this._getCapSize(this.endCap);
  15911. var count = this.points.length;
  15912. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  15913. this._fillVB = new Float32Array(vbSize);
  15914. var vb = this._fillVB;
  15915. var ht = this.fillThickness / 2;
  15916. var total = this.points.length;
  15917. this._buildLine(vb, this.border ? null : contour, ht);
  15918. var max = total * 2;
  15919. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  15920. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  15921. var ib = this._fillIB;
  15922. for (var i = 0; i < triCount; i += 2) {
  15923. ib[i * 3 + 0] = i + 0;
  15924. ib[i * 3 + 1] = i + 1;
  15925. ib[i * 3 + 2] = (i + 2) % max;
  15926. ib[i * 3 + 3] = i + 1;
  15927. ib[i * 3 + 4] = (i + 3) % max;
  15928. ib[i * 3 + 5] = (i + 2) % max;
  15929. }
  15930. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D_1._startDir, this.border ? null : startCapContour);
  15931. 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);
  15932. }
  15933. // Need to create WebGL resources for border part?
  15934. if (this.border) {
  15935. var startCapInfo = this._getCapSize(this.startCap, true);
  15936. var endCapInfo = this._getCapSize(this.endCap, true);
  15937. var count = this.points.length;
  15938. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  15939. this._borderVB = new Float32Array(vbSize);
  15940. var vb = this._borderVB;
  15941. var ht = this.fillThickness / 2;
  15942. var bt = this.borderThickness;
  15943. var total = this.points.length;
  15944. this._buildLine(vb, contour, ht, bt);
  15945. var max = total * 2 * 2;
  15946. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  15947. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  15948. var ib = this._borderIB;
  15949. for (var i = 0; i < triCount; i += 4) {
  15950. ib[i * 3 + 0] = i + 0;
  15951. ib[i * 3 + 1] = i + 2;
  15952. ib[i * 3 + 2] = (i + 6) % max;
  15953. ib[i * 3 + 3] = i + 0;
  15954. ib[i * 3 + 4] = (i + 6) % max;
  15955. ib[i * 3 + 5] = (i + 4) % max;
  15956. ib[i * 3 + 6] = i + 3;
  15957. ib[i * 3 + 7] = i + 1;
  15958. ib[i * 3 + 8] = (i + 5) % max;
  15959. ib[i * 3 + 9] = i + 3;
  15960. ib[i * 3 + 10] = (i + 5) % max;
  15961. ib[i * 3 + 11] = (i + 7) % max;
  15962. }
  15963. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D_1._startDir, startCapContour);
  15964. 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);
  15965. }
  15966. var startCapTri;
  15967. if (startCapContour.length > 0) {
  15968. startCapTri = Earcut.earcut(startCapContour, null, 2);
  15969. }
  15970. var endCapTri;
  15971. if (endCapContour.length > 0) {
  15972. endCapTri = Earcut.earcut(endCapContour, null, 2);
  15973. }
  15974. // Build the Tri2DArray using the contour info from the shape and the caps (if any)
  15975. {
  15976. var pl = this.points.length;
  15977. // Count the number of needed triangles
  15978. var count = ((this.closed ? pl : (pl - 1)) * 2) + (startCapTri != null ? ((startCapTri.length + endCapTri.length) / 3) : 0);
  15979. // Init/Clear the TriArray
  15980. if (!this._primTriArray) {
  15981. this._primTriArray = new BABYLON.Tri2DArray(count);
  15982. }
  15983. else {
  15984. this._primTriArray.clear(count);
  15985. }
  15986. var pta_1 = this._primTriArray;
  15987. var l = this.closed ? pl + 1 : pl;
  15988. this.transformPointWithOriginToRef(contour[0], null, Lines2D_1._prevA);
  15989. this.transformPointWithOriginToRef(contour[1], null, Lines2D_1._prevB);
  15990. var si_1 = 0;
  15991. for (var i = 1; i < l; i++) {
  15992. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 0], null, Lines2D_1._curA);
  15993. this.transformPointWithOriginToRef(contour[(i % pl) * 2 + 1], null, Lines2D_1._curB);
  15994. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curA);
  15995. pta_1.storeTriangle(si_1++, Lines2D_1._curA, Lines2D_1._prevB, Lines2D_1._curB);
  15996. Lines2D_1._prevA.x = Lines2D_1._curA.x;
  15997. Lines2D_1._prevA.y = Lines2D_1._curA.y;
  15998. Lines2D_1._prevB.x = Lines2D_1._curB.x;
  15999. Lines2D_1._prevB.y = Lines2D_1._curB.y;
  16000. }
  16001. var capIntersect = function (tri, points) {
  16002. var l = tri.length;
  16003. for (var i = 0; i < l; i += 3) {
  16004. Lines2D_1._curA.x = points[tri[i + 0] * 2 + 0];
  16005. Lines2D_1._curA.y = points[tri[i + 0] * 2 + 1];
  16006. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._curB);
  16007. Lines2D_1._curA.x = points[tri[i + 1] * 2 + 0];
  16008. Lines2D_1._curA.y = points[tri[i + 1] * 2 + 1];
  16009. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevA);
  16010. Lines2D_1._curA.x = points[tri[i + 2] * 2 + 0];
  16011. Lines2D_1._curA.y = points[tri[i + 2] * 2 + 1];
  16012. _this.transformPointWithOriginToRef(Lines2D_1._curA, null, Lines2D_1._prevB);
  16013. pta_1.storeTriangle(si_1++, Lines2D_1._prevA, Lines2D_1._prevB, Lines2D_1._curB);
  16014. }
  16015. return false;
  16016. };
  16017. if (startCapTri) {
  16018. if (startCapTri) {
  16019. capIntersect(startCapTri, startCapContour);
  16020. }
  16021. if (endCapTri) {
  16022. capIntersect(endCapTri, endCapContour);
  16023. }
  16024. }
  16025. this._primTriArrayDirty = false;
  16026. }
  16027. var bs = this._boundingMax.subtract(this._boundingMin);
  16028. this._size.width = bs.x;
  16029. this._size.height = bs.y;
  16030. };
  16031. Object.defineProperty(Lines2D.prototype, "size", {
  16032. get: function () {
  16033. if (this._size == null) {
  16034. this._computeLines2D();
  16035. }
  16036. return this._size;
  16037. },
  16038. enumerable: true,
  16039. configurable: true
  16040. });
  16041. Lines2D.prototype.createInstanceDataParts = function () {
  16042. var res = new Array();
  16043. if (this.border) {
  16044. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  16045. }
  16046. if (this.fill) {
  16047. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  16048. }
  16049. return res;
  16050. };
  16051. Lines2D.prototype.applyActualScaleOnTransform = function () {
  16052. return true;
  16053. };
  16054. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  16055. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  16056. return false;
  16057. }
  16058. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  16059. var d = part;
  16060. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  16061. d.boundingMin = this.boundingMin;
  16062. d.boundingMax = this.boundingMax;
  16063. }
  16064. }
  16065. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  16066. var d = part;
  16067. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  16068. d.boundingMin = this.boundingMin;
  16069. d.boundingMax = this.boundingMax;
  16070. }
  16071. }
  16072. return true;
  16073. };
  16074. return Lines2D;
  16075. }(BABYLON.Shape2D));
  16076. Lines2D._prevA = BABYLON.Vector2.Zero();
  16077. Lines2D._prevB = BABYLON.Vector2.Zero();
  16078. Lines2D._curA = BABYLON.Vector2.Zero();
  16079. Lines2D._curB = BABYLON.Vector2.Zero();
  16080. Lines2D._miterTps = BABYLON.Vector2.Zero();
  16081. Lines2D._startDir = BABYLON.Vector2.Zero();
  16082. Lines2D._endDir = BABYLON.Vector2.Zero();
  16083. Lines2D._tpsV = BABYLON.Vector2.Zero();
  16084. Lines2D._noCap = 0;
  16085. Lines2D._roundCap = 1;
  16086. Lines2D._triangleCap = 2;
  16087. Lines2D._squareAnchorCap = 3;
  16088. Lines2D._roundAnchorCap = 4;
  16089. Lines2D._diamondAnchorCap = 5;
  16090. Lines2D._arrowCap = 6;
  16091. Lines2D._roundCapSubDiv = 36;
  16092. __decorate([
  16093. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D_1.pointsProperty = pi; })
  16094. ], Lines2D.prototype, "points", null);
  16095. __decorate([
  16096. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D_1.fillThicknessProperty = pi; })
  16097. ], Lines2D.prototype, "fillThickness", null);
  16098. __decorate([
  16099. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D_1.closedProperty = pi; })
  16100. ], Lines2D.prototype, "closed", null);
  16101. __decorate([
  16102. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D_1.startCapProperty = pi; })
  16103. ], Lines2D.prototype, "startCap", null);
  16104. __decorate([
  16105. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D_1.endCapProperty = pi; })
  16106. ], Lines2D.prototype, "endCap", null);
  16107. Lines2D = Lines2D_1 = __decorate([
  16108. BABYLON.className("Lines2D", "BABYLON")
  16109. ], Lines2D);
  16110. BABYLON.Lines2D = Lines2D;
  16111. var Lines2D_1;
  16112. })(BABYLON || (BABYLON = {}));
  16113. var __extends = (this && this.__extends) || function (d, b) {
  16114. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  16115. function __() { this.constructor = d; }
  16116. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  16117. };
  16118. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  16119. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  16120. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  16121. 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;
  16122. return c > 3 && r && Object.defineProperty(target, key, r), r;
  16123. };
  16124. var BABYLON;
  16125. (function (BABYLON) {
  16126. // This class contains data that lifetime is bounding to the Babylon Engine object
  16127. var Canvas2DEngineBoundData = (function () {
  16128. function Canvas2DEngineBoundData() {
  16129. this._modelCache = new BABYLON.StringDictionary();
  16130. }
  16131. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  16132. return this._modelCache.getOrAddWithFactory(key, factory);
  16133. };
  16134. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  16135. if (!modelRenderCache.isDisposed) {
  16136. return false;
  16137. }
  16138. this._modelCache.remove(modelRenderCache.modelKey);
  16139. return true;
  16140. };
  16141. return Canvas2DEngineBoundData;
  16142. }());
  16143. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  16144. var Canvas2D = Canvas2D_1 = (function (_super) {
  16145. __extends(Canvas2D, _super);
  16146. function Canvas2D(scene, settings) {
  16147. var _this = _super.call(this, settings) || this;
  16148. /**
  16149. * 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.
  16150. * Beware that you have to take under consideration the origin and unitScaleFactor in your calculations! Good luck!
  16151. */
  16152. _this.worldSpaceToNodeLocal = function (worldPos) {
  16153. var node = _this._worldSpaceNode;
  16154. if (!node) {
  16155. return;
  16156. }
  16157. var mtx = node.getWorldMatrix().clone();
  16158. mtx.invert();
  16159. var usf = _this.unitScaleFactor;
  16160. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  16161. var res = new BABYLON.Vector2(v.x, v.y);
  16162. var size = _this.actualSize;
  16163. res.x += (size.width / usf) * 0.5; // res is centered, make it relative to bottom/left
  16164. res.y += (size.height / usf) * 0.5;
  16165. res.x *= usf; // multiply by the unitScaleFactor, which defines if the canvas is nth time bigger than the original world plane
  16166. res.y *= usf;
  16167. return res;
  16168. };
  16169. /**
  16170. * 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
  16171. */
  16172. _this.worldSpaceCacheChanged = function () {
  16173. var plane = _this.worldSpaceCanvasNode;
  16174. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  16175. vd.uvs = new Float32Array(8);
  16176. var material = plane.material;
  16177. var tex = _this._renderableData._cacheTexture;
  16178. if (material.diffuseTexture !== tex) {
  16179. material.diffuseTexture = tex;
  16180. tex.hasAlpha = true;
  16181. }
  16182. var nodeuv = _this._renderableData._cacheNodeUVs;
  16183. for (var i = 0; i < 4; i++) {
  16184. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  16185. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  16186. }
  16187. vd.applyToMesh(plane);
  16188. };
  16189. _this._notifDebugMode = false;
  16190. /**
  16191. * Instanced Array will be create if there's at least this number of parts/prim that can fit into it
  16192. */
  16193. _this.minPartCountToUseInstancedArray = 5;
  16194. _this._mapCounter = 0;
  16195. _this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  16196. _this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  16197. _this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  16198. _this._groupRenderCounter = new BABYLON.PerfCounter();
  16199. _this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  16200. _this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  16201. _this._updateCachedStateCounter = new BABYLON.PerfCounter();
  16202. _this._updateLayoutCounter = new BABYLON.PerfCounter();
  16203. _this._updatePositioningCounter = new BABYLON.PerfCounter();
  16204. _this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  16205. _this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  16206. _this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  16207. _this._layoutBoundingInfoUpdateCounter = new BABYLON.PerfCounter();
  16208. _this._cachedCanvasGroup = null;
  16209. _this._renderingGroupObserver = null;
  16210. _this._beforeRenderObserver = null;
  16211. _this._afterRenderObserver = null;
  16212. _this._profileInfoText = null;
  16213. BABYLON.Prim2DBase._isCanvasInit = false;
  16214. if (!settings) {
  16215. settings = {};
  16216. }
  16217. if (_this._cachingStrategy !== Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  16218. _this._background = new BABYLON.Rectangle2D({ parent: _this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  16219. _this._background.zOrder = 1.0;
  16220. _this._background.isPickable = false;
  16221. _this._background.origin = BABYLON.Vector2.Zero();
  16222. _this._background.levelVisible = false;
  16223. if (settings.backgroundRoundRadius != null) {
  16224. _this.backgroundRoundRadius = settings.backgroundRoundRadius;
  16225. }
  16226. if (settings.backgroundBorder != null) {
  16227. if (typeof (settings.backgroundBorder) === "string") {
  16228. _this.backgroundBorder = Canvas2D_1.GetBrushFromString(settings.backgroundBorder);
  16229. }
  16230. else {
  16231. _this.backgroundBorder = settings.backgroundBorder;
  16232. }
  16233. }
  16234. if (settings.backgroundBorderThickNess != null) {
  16235. _this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  16236. }
  16237. if (settings.backgroundFill != null) {
  16238. if (typeof (settings.backgroundFill) === "string") {
  16239. _this.backgroundFill = Canvas2D_1.GetBrushFromString(settings.backgroundFill);
  16240. }
  16241. else {
  16242. _this.backgroundFill = settings.backgroundFill;
  16243. }
  16244. }
  16245. // Put a handler to resize the background whenever the canvas is resizing
  16246. _this.propertyChanged.add(function (e, s) {
  16247. if (e.propertyName === "size") {
  16248. _this._background.size = _this.size;
  16249. }
  16250. }, BABYLON.Group2D.sizeProperty.flagId);
  16251. _this._background._patchHierarchy(_this);
  16252. }
  16253. var engine = scene.getEngine();
  16254. _this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  16255. _this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  16256. _this._capturedPointers = new BABYLON.StringDictionary();
  16257. _this._pickStartingPosition = BABYLON.Vector2.Zero();
  16258. _this._hierarchyLevelMaxSiblingCount = 50;
  16259. _this._hierarchyDepth = 0;
  16260. _this._zOrder = 0;
  16261. _this._zMax = 1;
  16262. _this._scene = scene;
  16263. _this._engine = engine;
  16264. _this._renderingSize = new BABYLON.Size(0, 0);
  16265. _this._curHWScale = 0;
  16266. _this._canvasLevelScale = new BABYLON.Vector3(1, 1, 1);
  16267. _this._designSize = settings.designSize || null;
  16268. _this._designUseHorizAxis = settings.designUseHorizAxis === true;
  16269. if (!_this._trackedGroups) {
  16270. _this._trackedGroups = new Array();
  16271. }
  16272. _this._maxAdaptiveWorldSpaceCanvasSize = null;
  16273. _this._groupCacheMaps = new BABYLON.StringDictionary();
  16274. _this._patchHierarchy(_this);
  16275. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  16276. _this._fitRenderingDevice = !settings.size;
  16277. if (!settings.size) {
  16278. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  16279. }
  16280. // Register scene dispose to also dispose the canvas when it'll happens
  16281. scene.onDisposeObservable.add(function (d, s) {
  16282. _this.dispose();
  16283. });
  16284. if (_this._isScreenSpace) {
  16285. if (settings.renderingPhase) {
  16286. if (!settings.renderingPhase.camera || settings.renderingPhase.renderingGroupID == null) {
  16287. throw Error("You have to specify a valid camera and renderingGroup");
  16288. }
  16289. _this._renderingGroupObserver = _this._scene.onRenderingGroupObservable.add(function (e, s) {
  16290. if ((_this._scene.activeCamera === settings.renderingPhase.camera) && (e.renderStage === BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT)) {
  16291. _this._engine.clear(null, false, true, true);
  16292. _this._render();
  16293. }
  16294. }, Math.pow(2, settings.renderingPhase.renderingGroupID));
  16295. }
  16296. else {
  16297. _this._afterRenderObserver = _this._scene.onAfterRenderObservable.add(function (d, s) {
  16298. _this._engine.clear(null, false, true, true);
  16299. _this._render();
  16300. });
  16301. }
  16302. }
  16303. else {
  16304. _this._beforeRenderObserver = _this._scene.onBeforeRenderObservable.add(function (d, s) {
  16305. _this._render();
  16306. });
  16307. }
  16308. _this._supprtInstancedArray = _this._engine.getCaps().instancedArrays !== null;
  16309. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  16310. // Setup the canvas for interaction (or not)
  16311. _this._setupInteraction(enableInteraction);
  16312. // Initialize the Primitive Collision Manager
  16313. if (settings.enableCollisionManager) {
  16314. var enableBorders = settings.collisionManagerUseBorders;
  16315. _this._primitiveCollisionManager = (settings.customCollisionManager == null) ? BABYLON.PrimitiveCollisionManagerBase.allocBasicPCM(_this, enableBorders) : settings.customCollisionManager(_this, enableBorders);
  16316. }
  16317. // Register this instance
  16318. Canvas2D_1._INSTANCES.push(_this);
  16319. return _this;
  16320. }
  16321. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  16322. get: function () {
  16323. return this._drawCallsOpaqueCounter;
  16324. },
  16325. enumerable: true,
  16326. configurable: true
  16327. });
  16328. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  16329. get: function () {
  16330. return this._drawCallsAlphaTestCounter;
  16331. },
  16332. enumerable: true,
  16333. configurable: true
  16334. });
  16335. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  16336. get: function () {
  16337. return this._drawCallsTransparentCounter;
  16338. },
  16339. enumerable: true,
  16340. configurable: true
  16341. });
  16342. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  16343. get: function () {
  16344. return this._groupRenderCounter;
  16345. },
  16346. enumerable: true,
  16347. configurable: true
  16348. });
  16349. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  16350. get: function () {
  16351. return this._updateTransparentDataCounter;
  16352. },
  16353. enumerable: true,
  16354. configurable: true
  16355. });
  16356. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  16357. get: function () {
  16358. return this._cachedGroupRenderCounter;
  16359. },
  16360. enumerable: true,
  16361. configurable: true
  16362. });
  16363. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  16364. get: function () {
  16365. return this._updateCachedStateCounter;
  16366. },
  16367. enumerable: true,
  16368. configurable: true
  16369. });
  16370. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  16371. get: function () {
  16372. return this._updateLayoutCounter;
  16373. },
  16374. enumerable: true,
  16375. configurable: true
  16376. });
  16377. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  16378. get: function () {
  16379. return this._updatePositioningCounter;
  16380. },
  16381. enumerable: true,
  16382. configurable: true
  16383. });
  16384. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  16385. get: function () {
  16386. return this._updateLocalTransformCounter;
  16387. },
  16388. enumerable: true,
  16389. configurable: true
  16390. });
  16391. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  16392. get: function () {
  16393. return this._updateGlobalTransformCounter;
  16394. },
  16395. enumerable: true,
  16396. configurable: true
  16397. });
  16398. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  16399. get: function () {
  16400. return this._boundingInfoRecomputeCounter;
  16401. },
  16402. enumerable: true,
  16403. configurable: true
  16404. });
  16405. Object.defineProperty(Canvas2D.prototype, "layoutBoundingInfoUpdateCounter", {
  16406. get: function () {
  16407. return this._layoutBoundingInfoUpdateCounter;
  16408. },
  16409. enumerable: true,
  16410. configurable: true
  16411. });
  16412. Object.defineProperty(Canvas2D, "instances", {
  16413. get: function () {
  16414. return Canvas2D_1._INSTANCES;
  16415. },
  16416. enumerable: true,
  16417. configurable: true
  16418. });
  16419. Object.defineProperty(Canvas2D.prototype, "primitiveCollisionManager", {
  16420. get: function () {
  16421. return this._primitiveCollisionManager;
  16422. },
  16423. enumerable: true,
  16424. configurable: true
  16425. });
  16426. Canvas2D.prototype._canvasPreInit = function (settings) {
  16427. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D_1.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  16428. this._cachingStrategy = cachingStrategy;
  16429. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  16430. };
  16431. Canvas2D.prototype._setupInteraction = function (enable) {
  16432. var _this = this;
  16433. // No change detection
  16434. if (enable === this._interactionEnabled) {
  16435. return;
  16436. }
  16437. // Set the new state
  16438. this._interactionEnabled = enable;
  16439. // ScreenSpace mode
  16440. if (this._isScreenSpace) {
  16441. // Disable interaction
  16442. if (!enable) {
  16443. if (this._scenePrePointerObserver) {
  16444. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  16445. this._scenePrePointerObserver = null;
  16446. }
  16447. return;
  16448. }
  16449. // Enable Interaction
  16450. // Register the observable
  16451. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  16452. if (_this.isVisible === false) {
  16453. return;
  16454. }
  16455. var hs = 1 / _this.engine.getHardwareScalingLevel();
  16456. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  16457. _this._handlePointerEventForInteraction(e, localPos, s);
  16458. });
  16459. }
  16460. else {
  16461. var scene = this.scene;
  16462. if (enable) {
  16463. scene.constantlyUpdateMeshUnderPointer = true;
  16464. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  16465. if (_this.isVisible === false) {
  16466. return;
  16467. }
  16468. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  16469. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  16470. _this._handlePointerEventForInteraction(e, localPos, s);
  16471. }
  16472. else if (_this._actualIntersectionList && _this._actualIntersectionList.length > 0) {
  16473. _this._handlePointerEventForInteraction(e, null, s);
  16474. }
  16475. });
  16476. }
  16477. else {
  16478. if (this._scenePointerObserver) {
  16479. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  16480. this._scenePointerObserver = null;
  16481. }
  16482. }
  16483. }
  16484. };
  16485. /**
  16486. * Internal method, you should use the Prim2DBase version instead
  16487. */
  16488. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  16489. if (this.isPointerCaptured(pointerId)) {
  16490. return false;
  16491. }
  16492. // Try to capture the pointer on the HTML side
  16493. try {
  16494. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  16495. }
  16496. catch (e) {
  16497. }
  16498. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  16499. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  16500. this._capturedPointers.add(pointerId.toString(), primitive);
  16501. return true;
  16502. };
  16503. /**
  16504. * Internal method, you should use the Prim2DBase version instead
  16505. */
  16506. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  16507. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  16508. return false;
  16509. }
  16510. // Try to release the pointer on the HTML side
  16511. try {
  16512. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  16513. }
  16514. catch (e) {
  16515. }
  16516. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  16517. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  16518. this._capturedPointers.remove(pointerId.toString());
  16519. return true;
  16520. };
  16521. /**
  16522. * Determine if the given pointer is captured or not
  16523. * @param pointerId the Id of the pointer
  16524. * @return true if it's captured, false otherwise
  16525. */
  16526. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  16527. return this._capturedPointers.contains(pointerId.toString());
  16528. };
  16529. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  16530. // Avoid unnecessary lookup
  16531. if (this._capturedPointers.count === 0) {
  16532. return null;
  16533. }
  16534. return this._capturedPointers.get(pointerId.toString());
  16535. };
  16536. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  16537. // Dispose check
  16538. if (this.isDisposed) {
  16539. return;
  16540. }
  16541. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  16542. if (localPosition) {
  16543. if (!this._updatePointerInfo(eventData, localPosition)) {
  16544. return;
  16545. }
  16546. }
  16547. else {
  16548. this._primPointerInfo.canvasPointerPos = null;
  16549. }
  16550. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  16551. // 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.
  16552. // 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.
  16553. this._updateIntersectionList(localPosition ? this._primPointerInfo.canvasPointerPos : null, capturedPrim !== null, true);
  16554. // 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
  16555. this._updateOverStatus(true);
  16556. // Check if we have nothing to raise
  16557. if (!this._actualOverPrimitive && !capturedPrim) {
  16558. return;
  16559. }
  16560. // Update the relatedTarget info with the over primitive or the captured one (if any)
  16561. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  16562. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  16563. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  16564. // Analyze the pointer event type and fire proper events on the primitive
  16565. var skip = false;
  16566. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  16567. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  16568. }
  16569. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  16570. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  16571. }
  16572. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  16573. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  16574. }
  16575. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  16576. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  16577. }
  16578. eventState.skipNextObservers = skip;
  16579. };
  16580. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  16581. var s = this.scale;
  16582. var pii = this._primPointerInfo;
  16583. pii.cancelBubble = false;
  16584. if (!pii.canvasPointerPos) {
  16585. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  16586. }
  16587. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  16588. if (!camera || !camera.viewport) {
  16589. return false;
  16590. }
  16591. var engine = this._scene.getEngine();
  16592. if (this._isScreenSpace) {
  16593. var cameraViewport = camera.viewport;
  16594. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  16595. // Moving coordinates to local viewport world
  16596. var x = localPosition.x - viewport.x;
  16597. var y = localPosition.y - viewport.y;
  16598. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  16599. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  16600. }
  16601. else {
  16602. pii.canvasPointerPos.x = localPosition.x / s;
  16603. pii.canvasPointerPos.y = localPosition.y / s;
  16604. }
  16605. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  16606. pii.mouseWheelDelta = 0;
  16607. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  16608. var event = eventData.event;
  16609. if (event.wheelDelta) {
  16610. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  16611. }
  16612. else if (event.detail) {
  16613. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  16614. }
  16615. }
  16616. else {
  16617. var pe = eventData.event;
  16618. pii.ctrlKey = pe.ctrlKey;
  16619. pii.altKey = pe.altKey;
  16620. pii.shiftKey = pe.shiftKey;
  16621. pii.metaKey = pe.metaKey;
  16622. pii.button = pe.button;
  16623. pii.buttons = pe.buttons;
  16624. pii.pointerId = pe.pointerId;
  16625. pii.width = pe.width;
  16626. pii.height = pe.height;
  16627. pii.presssure = pe.pressure;
  16628. pii.tilt.x = pe.tiltX;
  16629. pii.tilt.y = pe.tiltY;
  16630. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  16631. }
  16632. return true;
  16633. };
  16634. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
  16635. if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
  16636. return;
  16637. }
  16638. var ii = Canvas2D_1._interInfo;
  16639. var outCase = mouseLocalPos == null;
  16640. if (!outCase) {
  16641. // 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
  16642. if (!this._globalTransform) {
  16643. this.updateCachedStates(true);
  16644. }
  16645. ii.pickPosition.x = mouseLocalPos.x;
  16646. ii.pickPosition.y = mouseLocalPos.y;
  16647. ii.findFirstOnly = false;
  16648. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  16649. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  16650. // Reset intersection info as we don't hit anything
  16651. ii.intersectedPrimitives = new Array();
  16652. ii.topMostIntersectedPrimitive = null;
  16653. }
  16654. else {
  16655. // The pointer is inside the Canvas, do an intersection test
  16656. this.intersect(ii);
  16657. // Sort primitives to get them from top to bottom
  16658. ii.intersectedPrimitives = ii.intersectedPrimitives.sort(function (a, b) { return a.prim.actualZOffset - b.prim.actualZOffset; });
  16659. }
  16660. }
  16661. {
  16662. // Update prev/actual intersection info, fire "overPrim" property change if needed
  16663. this._previousIntersectionList = this._actualIntersectionList;
  16664. this._actualIntersectionList = outCase ? new Array() : ii.intersectedPrimitives;
  16665. this._previousOverPrimitive = this._actualOverPrimitive;
  16666. this._actualOverPrimitive = outCase ? null : ii.topMostIntersectedPrimitive;
  16667. var prev = (this._previousOverPrimitive != null) ? this._previousOverPrimitive.prim : null;
  16668. var actual = (this._actualOverPrimitive != null) ? this._actualOverPrimitive.prim : null;
  16669. if (prev !== actual) {
  16670. this.onPropertyChanged("overPrim", this._previousOverPrimitive ? this._previousOverPrimitive.prim : null, this._actualOverPrimitive ? this._actualOverPrimitive.prim : null);
  16671. }
  16672. }
  16673. this._intersectionRenderId = this.scene.getRenderId();
  16674. };
  16675. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  16676. Canvas2D.prototype._updateOverStatus = function (force) {
  16677. if ((!force && (this.scene.getRenderId() === this._hoverStatusRenderId)) || !this._actualIntersectionList) {
  16678. return;
  16679. }
  16680. if (this._previousIntersectionList == null) {
  16681. this._previousIntersectionList = [];
  16682. }
  16683. // Detect a change of over
  16684. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  16685. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  16686. if (prevPrim !== actualPrim) {
  16687. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  16688. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  16689. // See the NOTE section of: https://www.w3.org/TR/pointerevents/#setting-pointer-capture
  16690. if (capturedPrim) {
  16691. if (capturedPrim === prevPrim) {
  16692. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  16693. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  16694. }
  16695. else if (capturedPrim === actualPrim) {
  16696. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  16697. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  16698. }
  16699. }
  16700. else {
  16701. var _loop_1 = function (prev) {
  16702. if (!BABYLON.Tools.first(this_1._actualIntersectionList, function (pii) { return pii.prim === prev.prim; })) {
  16703. this_1._primPointerInfo.updateRelatedTarget(prev.prim, prev.intersectionLocation);
  16704. this_1._bubbleNotifyPrimPointerObserver(prev.prim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  16705. }
  16706. };
  16707. var this_1 = this;
  16708. // Check for Out & Leave
  16709. for (var _i = 0, _a = this._previousIntersectionList; _i < _a.length; _i++) {
  16710. var prev = _a[_i];
  16711. _loop_1(prev);
  16712. }
  16713. var _loop_2 = function (actual) {
  16714. if (!BABYLON.Tools.first(this_2._previousIntersectionList, function (pii) { return pii.prim === actual.prim; })) {
  16715. this_2._primPointerInfo.updateRelatedTarget(actual.prim, actual.intersectionLocation);
  16716. this_2._bubbleNotifyPrimPointerObserver(actual.prim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  16717. }
  16718. };
  16719. var this_2 = this;
  16720. // Check for Over & Enter
  16721. for (var _b = 0, _c = this._actualIntersectionList; _b < _c.length; _b++) {
  16722. var actual = _c[_b];
  16723. _loop_2(actual);
  16724. }
  16725. }
  16726. }
  16727. this._hoverStatusRenderId = this.scene.getRenderId();
  16728. };
  16729. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  16730. if (this._primPointerInfo.isCaptured) {
  16731. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  16732. }
  16733. else {
  16734. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  16735. var pii = _a[_i];
  16736. if (pii.prim === prim) {
  16737. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  16738. return;
  16739. }
  16740. }
  16741. }
  16742. };
  16743. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  16744. if (!this._notifDebugMode) {
  16745. return;
  16746. }
  16747. var debug = "";
  16748. for (var i = 0; i < prim.hierarchyDepth; i++) {
  16749. debug += " ";
  16750. }
  16751. var pii = this._primPointerInfo;
  16752. 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;
  16753. console.log(debug);
  16754. };
  16755. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  16756. var ppi = this._primPointerInfo;
  16757. var event = eventData ? eventData.event : null;
  16758. var cur = prim;
  16759. while (cur && !cur.isDisposed) {
  16760. this._updatePrimPointerPos(cur);
  16761. // For the first level we have to fire Enter or Leave for corresponding Over or Out
  16762. if (cur === prim) {
  16763. // Fire the proper notification
  16764. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  16765. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerEnter);
  16766. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  16767. }
  16768. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  16769. this._debugExecObserver(prim, BABYLON.PrimitivePointerInfo.PointerLeave);
  16770. prim._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  16771. }
  16772. }
  16773. // Exec the observers
  16774. this._debugExecObserver(cur, mask);
  16775. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  16776. eventData.skipOnPointerObservable = true;
  16777. return false;
  16778. }
  16779. this._triggerActionManager(cur, ppi, mask, event);
  16780. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  16781. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  16782. if (ppi.cancelBubble) {
  16783. return false;
  16784. }
  16785. // Loop to the parent
  16786. cur = cur.parent;
  16787. }
  16788. return true;
  16789. };
  16790. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  16791. var _this = this;
  16792. // 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
  16793. if (!this._globalTransform) {
  16794. this.updateCachedStates(true);
  16795. }
  16796. // Process Trigger related to PointerDown
  16797. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  16798. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  16799. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  16800. this._pickStartingTime = new Date().getTime();
  16801. this._pickedDownPrim = null;
  16802. if (prim.actionManager) {
  16803. this._pickedDownPrim = prim;
  16804. if (prim.actionManager.hasPickTriggers) {
  16805. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  16806. switch (eventData.button) {
  16807. case 0:
  16808. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  16809. break;
  16810. case 1:
  16811. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  16812. break;
  16813. case 2:
  16814. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  16815. break;
  16816. }
  16817. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  16818. }
  16819. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16820. window.setTimeout(function () {
  16821. var ppi = _this._primPointerInfo;
  16822. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  16823. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
  16824. _this._updateOverStatus(false);
  16825. var ii = new BABYLON.IntersectInfo2D();
  16826. ii.pickPosition = ppi.canvasPointerPos.clone();
  16827. ii.findFirstOnly = false;
  16828. _this.intersect(ii);
  16829. if (ii.isPrimIntersected(prim) !== null) {
  16830. if (prim.actionManager) {
  16831. 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)) {
  16832. _this._pickStartingTime = 0;
  16833. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  16834. }
  16835. }
  16836. }
  16837. }, BABYLON.ActionManager.LongPressDelay);
  16838. }
  16839. }
  16840. }
  16841. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  16842. this._pickStartingTime = 0;
  16843. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  16844. if (prim.actionManager) {
  16845. // OnPickUpTrigger
  16846. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  16847. // OnPickTrigger
  16848. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  16849. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  16850. }
  16851. }
  16852. // OnPickOutTrigger
  16853. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  16854. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  16855. }
  16856. }
  16857. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  16858. if (prim.actionManager) {
  16859. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  16860. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  16861. }
  16862. }
  16863. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  16864. if (prim.actionManager) {
  16865. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  16866. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  16867. }
  16868. }
  16869. };
  16870. /**
  16871. * Don't forget to call the dispose method when you're done with the Canvas instance.
  16872. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  16873. */
  16874. Canvas2D.prototype.dispose = function () {
  16875. if (!_super.prototype.dispose.call(this)) {
  16876. return false;
  16877. }
  16878. if (this._profilingCanvas) {
  16879. this._profilingCanvas.dispose();
  16880. this._profilingCanvas = null;
  16881. }
  16882. if (this.interactionEnabled) {
  16883. this._setupInteraction(false);
  16884. }
  16885. if (this._renderingGroupObserver) {
  16886. this._scene.onRenderingGroupObservable.remove(this._renderingGroupObserver);
  16887. this._renderingGroupObserver = null;
  16888. }
  16889. if (this._beforeRenderObserver) {
  16890. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  16891. this._beforeRenderObserver = null;
  16892. }
  16893. if (this._afterRenderObserver) {
  16894. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  16895. this._afterRenderObserver = null;
  16896. }
  16897. if (this._groupCacheMaps) {
  16898. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  16899. this._groupCacheMaps = null;
  16900. }
  16901. // Unregister this instance
  16902. var index = Canvas2D_1._INSTANCES.indexOf(this);
  16903. if (index > -1) {
  16904. Canvas2D_1._INSTANCES.splice(index, 1);
  16905. }
  16906. return true;
  16907. };
  16908. Object.defineProperty(Canvas2D.prototype, "scene", {
  16909. /**
  16910. * Accessor to the Scene that owns the Canvas
  16911. * @returns The instance of the Scene object
  16912. */
  16913. get: function () {
  16914. return this._scene;
  16915. },
  16916. enumerable: true,
  16917. configurable: true
  16918. });
  16919. Object.defineProperty(Canvas2D.prototype, "engine", {
  16920. /**
  16921. * Accessor to the Engine that drives the Scene used by this Canvas
  16922. * @returns The instance of the Engine object
  16923. */
  16924. get: function () {
  16925. return this._engine;
  16926. },
  16927. enumerable: true,
  16928. configurable: true
  16929. });
  16930. Object.defineProperty(Canvas2D.prototype, "renderObservable", {
  16931. /**
  16932. * And observable called during the Canvas rendering process.
  16933. * This observable is called twice per render, each time with a different mask:
  16934. * - 1: before render is executed
  16935. * - 2: after render is executed
  16936. */
  16937. get: function () {
  16938. if (!this._renderObservable) {
  16939. this._renderObservable = new BABYLON.Observable();
  16940. }
  16941. return this._renderObservable;
  16942. },
  16943. enumerable: true,
  16944. configurable: true
  16945. });
  16946. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  16947. /**
  16948. * Accessor of the Caching Strategy used by this Canvas.
  16949. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  16950. * @returns the value corresponding to the used strategy.
  16951. */
  16952. get: function () {
  16953. return this._cachingStrategy;
  16954. },
  16955. enumerable: true,
  16956. configurable: true
  16957. });
  16958. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  16959. /**
  16960. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  16961. * @returns {}
  16962. */
  16963. get: function () {
  16964. return this._isScreenSpace;
  16965. },
  16966. enumerable: true,
  16967. configurable: true
  16968. });
  16969. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  16970. /**
  16971. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  16972. */
  16973. get: function () {
  16974. return this._worldSpaceNode;
  16975. },
  16976. set: function (val) {
  16977. this._worldSpaceNode = val;
  16978. },
  16979. enumerable: true,
  16980. configurable: true
  16981. });
  16982. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  16983. /**
  16984. * Check if the WebGL Instanced Array extension is supported or not
  16985. */
  16986. get: function () {
  16987. return this._supprtInstancedArray;
  16988. },
  16989. enumerable: true,
  16990. configurable: true
  16991. });
  16992. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  16993. /**
  16994. * Property that defines the fill object used to draw the background of the Canvas.
  16995. * Note that Canvas with a Caching Strategy of
  16996. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  16997. */
  16998. get: function () {
  16999. if (!this._background || !this._background.isVisible) {
  17000. return null;
  17001. }
  17002. return this._background.fill;
  17003. },
  17004. set: function (value) {
  17005. this.checkBackgroundAvailability();
  17006. if (value === this._background.fill) {
  17007. return;
  17008. }
  17009. this._background.fill = value;
  17010. this._background.levelVisible = true;
  17011. },
  17012. enumerable: true,
  17013. configurable: true
  17014. });
  17015. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  17016. /**
  17017. * Property that defines the border object used to draw the background of the Canvas.
  17018. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  17019. */
  17020. get: function () {
  17021. if (!this._background || !this._background.isVisible) {
  17022. return null;
  17023. }
  17024. return this._background.border;
  17025. },
  17026. set: function (value) {
  17027. this.checkBackgroundAvailability();
  17028. if (value === this._background.border) {
  17029. return;
  17030. }
  17031. this._background.border = value;
  17032. this._background.levelVisible = true;
  17033. },
  17034. enumerable: true,
  17035. configurable: true
  17036. });
  17037. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  17038. /**
  17039. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  17040. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  17041. */
  17042. get: function () {
  17043. if (!this._background || !this._background.isVisible) {
  17044. return null;
  17045. }
  17046. return this._background.borderThickness;
  17047. },
  17048. set: function (value) {
  17049. this.checkBackgroundAvailability();
  17050. if (value === this._background.borderThickness) {
  17051. return;
  17052. }
  17053. this._background.borderThickness = value;
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  17059. /**
  17060. * You can set the roundRadius of the background
  17061. * @returns The current roundRadius
  17062. */
  17063. get: function () {
  17064. if (!this._background || !this._background.isVisible) {
  17065. return null;
  17066. }
  17067. return this._background.roundRadius;
  17068. },
  17069. set: function (value) {
  17070. this.checkBackgroundAvailability();
  17071. if (value === this._background.roundRadius) {
  17072. return;
  17073. }
  17074. this._background.roundRadius = value;
  17075. this._background.levelVisible = true;
  17076. },
  17077. enumerable: true,
  17078. configurable: true
  17079. });
  17080. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  17081. /**
  17082. * Enable/Disable interaction for this Canvas
  17083. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  17084. */
  17085. get: function () {
  17086. return this._interactionEnabled;
  17087. },
  17088. set: function (enable) {
  17089. this._setupInteraction(enable);
  17090. },
  17091. enumerable: true,
  17092. configurable: true
  17093. });
  17094. Object.defineProperty(Canvas2D.prototype, "fitRenderingDevice", {
  17095. get: function () {
  17096. return this._fitRenderingDevice;
  17097. },
  17098. enumerable: true,
  17099. configurable: true
  17100. });
  17101. Object.defineProperty(Canvas2D.prototype, "designSize", {
  17102. get: function () {
  17103. return this._designSize;
  17104. },
  17105. enumerable: true,
  17106. configurable: true
  17107. });
  17108. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  17109. get: function () {
  17110. return this._designUseHorizAxis;
  17111. },
  17112. enumerable: true,
  17113. configurable: true
  17114. });
  17115. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizeAxis", {
  17116. set: function (value) {
  17117. this._designUseHorizAxis = value;
  17118. },
  17119. enumerable: true,
  17120. configurable: true
  17121. });
  17122. Object.defineProperty(Canvas2D.prototype, "overPrim", {
  17123. /**
  17124. * Return
  17125. */
  17126. get: function () {
  17127. if (this._actualIntersectionList && this._actualIntersectionList.length > 0) {
  17128. return this._actualIntersectionList[0].prim;
  17129. }
  17130. return null;
  17131. },
  17132. enumerable: true,
  17133. configurable: true
  17134. });
  17135. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  17136. /**
  17137. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  17138. * @returns {}
  17139. */
  17140. get: function () {
  17141. return this.__engineData;
  17142. },
  17143. enumerable: true,
  17144. configurable: true
  17145. });
  17146. Object.defineProperty(Canvas2D.prototype, "unitScaleFactor", {
  17147. get: function () {
  17148. return this._unitScaleFactor;
  17149. },
  17150. enumerable: true,
  17151. configurable: true
  17152. });
  17153. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  17154. if (this._profilingCanvas) {
  17155. return this._profilingCanvas;
  17156. }
  17157. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  17158. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D_1.CACHESTRATEGY_DONTCACHE, children: [
  17159. new BABYLON.Rectangle2D({
  17160. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  17161. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "12pt Lucida Console", fontSignedDistanceField: true })
  17162. ]
  17163. })
  17164. ]
  17165. });
  17166. this._profileInfoText = canvas.findById("ProfileInfoText");
  17167. this._profilingCanvas = canvas;
  17168. return canvas;
  17169. };
  17170. Canvas2D.prototype.checkBackgroundAvailability = function () {
  17171. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_TOPLEVELGROUPS) {
  17172. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  17173. }
  17174. };
  17175. Canvas2D.prototype._initPerfMetrics = function () {
  17176. this._drawCallsOpaqueCounter.fetchNewFrame();
  17177. this._drawCallsAlphaTestCounter.fetchNewFrame();
  17178. this._drawCallsTransparentCounter.fetchNewFrame();
  17179. this._groupRenderCounter.fetchNewFrame();
  17180. this._updateTransparentDataCounter.fetchNewFrame();
  17181. this._cachedGroupRenderCounter.fetchNewFrame();
  17182. this._updateCachedStateCounter.fetchNewFrame();
  17183. this._updateLayoutCounter.fetchNewFrame();
  17184. this._updatePositioningCounter.fetchNewFrame();
  17185. this._updateLocalTransformCounter.fetchNewFrame();
  17186. this._updateGlobalTransformCounter.fetchNewFrame();
  17187. this._boundingInfoRecomputeCounter.fetchNewFrame();
  17188. this._layoutBoundingInfoUpdateCounter.fetchNewFrame();
  17189. };
  17190. Canvas2D.prototype._fetchPerfMetrics = function () {
  17191. this._drawCallsOpaqueCounter.addCount(0, true);
  17192. this._drawCallsAlphaTestCounter.addCount(0, true);
  17193. this._drawCallsTransparentCounter.addCount(0, true);
  17194. this._groupRenderCounter.addCount(0, true);
  17195. this._updateTransparentDataCounter.addCount(0, true);
  17196. this._cachedGroupRenderCounter.addCount(0, true);
  17197. this._updateCachedStateCounter.addCount(0, true);
  17198. this._updateLayoutCounter.addCount(0, true);
  17199. this._updatePositioningCounter.addCount(0, true);
  17200. this._updateLocalTransformCounter.addCount(0, true);
  17201. this._updateGlobalTransformCounter.addCount(0, true);
  17202. this._boundingInfoRecomputeCounter.addCount(0, true);
  17203. this._layoutBoundingInfoUpdateCounter.addCount(0, true);
  17204. };
  17205. Canvas2D.prototype._updateProfileCanvas = function () {
  17206. if (this._profileInfoText == null) {
  17207. return;
  17208. }
  17209. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  17210. var p = "Draw Calls:\n" +
  17211. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  17212. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  17213. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  17214. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  17215. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  17216. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  17217. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  17218. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  17219. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  17220. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  17221. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  17222. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n") +
  17223. (" - LayoutBoundingInfo Recompute: " + this.layoutBoundingInfoUpdateCounter.current + ", (avg:" + format(this.layoutBoundingInfoUpdateCounter.lastSecAverage) + ", t:" + format(this.layoutBoundingInfoUpdateCounter.total) + ")");
  17224. this._profileInfoText.text = p;
  17225. };
  17226. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  17227. switch (renderMode) {
  17228. case BABYLON.Render2DContext.RenderModeOpaque:
  17229. this._drawCallsOpaqueCounter.addCount(count, false);
  17230. return;
  17231. case BABYLON.Render2DContext.RenderModeAlphaTest:
  17232. this._drawCallsAlphaTestCounter.addCount(count, false);
  17233. return;
  17234. case BABYLON.Render2DContext.RenderModeTransparent:
  17235. this._drawCallsTransparentCounter.addCount(count, false);
  17236. return;
  17237. }
  17238. };
  17239. Canvas2D.prototype._addGroupRenderCount = function (count) {
  17240. if (this._groupRenderCounter) {
  17241. this._groupRenderCounter.addCount(count, false);
  17242. }
  17243. };
  17244. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  17245. if (this._updateTransparentDataCounter) {
  17246. this._updateTransparentDataCounter.addCount(count, false);
  17247. }
  17248. };
  17249. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  17250. if (this._cachedGroupRenderCounter) {
  17251. this._cachedGroupRenderCounter.addCount(count, false);
  17252. }
  17253. };
  17254. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  17255. if (this._updateCachedStateCounter) {
  17256. this._updateCachedStateCounter.addCount(count, false);
  17257. }
  17258. };
  17259. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  17260. if (this._updateLayoutCounter) {
  17261. this._updateLayoutCounter.addCount(count, false);
  17262. }
  17263. };
  17264. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  17265. if (this._updatePositioningCounter) {
  17266. this._updatePositioningCounter.addCount(count, false);
  17267. }
  17268. };
  17269. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  17270. if (this._updateLocalTransformCounter) {
  17271. this._updateLocalTransformCounter.addCount(count, false);
  17272. }
  17273. };
  17274. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  17275. if (this._updateGlobalTransformCounter) {
  17276. this._updateGlobalTransformCounter.addCount(count, false);
  17277. }
  17278. };
  17279. Canvas2D.prototype.addLayoutBoundingInfoUpdateCounter = function (count) {
  17280. if (this._layoutBoundingInfoUpdateCounter) {
  17281. this._layoutBoundingInfoUpdateCounter.addCount(count, false);
  17282. }
  17283. };
  17284. Canvas2D.prototype._updateTrackedNodes = function () {
  17285. // Get the used camera
  17286. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  17287. // Compute some matrix stuff
  17288. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  17289. var rh = this.engine.getRenderHeight();
  17290. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  17291. var tmpVec3 = Canvas2D_1._tmpVec3;
  17292. var tmpMtx = Canvas2D_1._tmpMtx;
  17293. // Compute the screen position of each group that track a given scene node
  17294. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  17295. var group = _a[_i];
  17296. if (group.isDisposed) {
  17297. continue;
  17298. }
  17299. var node = group.trackedNode;
  17300. var worldMtx = node.getWorldMatrix();
  17301. if (group.trackedNodeOffset) {
  17302. BABYLON.Vector3.TransformCoordinatesToRef(group.trackedNodeOffset, worldMtx, tmpVec3);
  17303. tmpMtx.copyFrom(worldMtx);
  17304. worldMtx = tmpMtx;
  17305. worldMtx.setTranslation(tmpVec3);
  17306. }
  17307. var proj = BABYLON.Vector3.Project(Canvas2D_1._v, worldMtx, Canvas2D_1._m, v);
  17308. // Set the visibility state accordingly, if the position is outside the frustum (well on the Z planes only...) set the group to hidden
  17309. group.levelVisible = proj.z >= 0 && proj.z < 1.0;
  17310. var s = this.scale;
  17311. group.x = Math.round(proj.x / s);
  17312. group.y = Math.round((rh - proj.y) / s);
  17313. }
  17314. // If it's a WorldSpaceCanvas and it's tracking a node, let's update the WSC transformation data
  17315. if (this._trackNode) {
  17316. var rot = null;
  17317. var scale = null;
  17318. var worldmtx = this._trackNode.getWorldMatrix();
  17319. var pos = worldmtx.getTranslation().add(this._trackNodeOffset);
  17320. var wsc = this;
  17321. var wsn = wsc.worldSpaceCanvasNode;
  17322. if (this._trackNodeBillboard) {
  17323. var viewMtx = cam.getViewMatrix().clone().invert();
  17324. viewMtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  17325. rot = Canvas2D_1.tR.clone();
  17326. }
  17327. worldmtx.decompose(Canvas2D_1.tS, Canvas2D_1.tR, Canvas2D_1.tT);
  17328. var mtx = BABYLON.Matrix.Compose(Canvas2D_1.tS, Canvas2D_1.tR, BABYLON.Vector3.Zero());
  17329. pos = worldmtx.getTranslation().add(BABYLON.Vector3.TransformCoordinates(this._trackNodeOffset, mtx));
  17330. if (Canvas2D_1.tS.lengthSquared() !== 1) {
  17331. scale = Canvas2D_1.tS.clone();
  17332. }
  17333. if (!this._trackNodeBillboard) {
  17334. rot = Canvas2D_1.tR.clone();
  17335. }
  17336. if (wsn instanceof BABYLON.AbstractMesh) {
  17337. wsn.position = pos;
  17338. wsn.rotationQuaternion = rot;
  17339. if (scale) {
  17340. wsn.scaling = scale;
  17341. }
  17342. }
  17343. else {
  17344. throw new Error("Can't Track another Scene Node Type than AbstractMesh right now, call me lazy!");
  17345. }
  17346. }
  17347. };
  17348. /**
  17349. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  17350. */
  17351. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  17352. this._updateCanvasState(forceRecompute);
  17353. };
  17354. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  17355. if (this._globalTransformStep < 2) {
  17356. return;
  17357. }
  17358. var n = this.worldSpaceCanvasNode;
  17359. var bi = n.getBoundingInfo().boundingBox;
  17360. var v = bi.vectorsWorld;
  17361. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  17362. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D_1._m);
  17363. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  17364. var projPoints = new Array(4);
  17365. for (var i = 0; i < 4; i++) {
  17366. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D_1._mI, Canvas2D_1._m, vp);
  17367. }
  17368. var left = projPoints[3].subtract(projPoints[0]).length();
  17369. var top = projPoints[3].subtract(projPoints[1]).length();
  17370. var right = projPoints[1].subtract(projPoints[2]).length();
  17371. var bottom = projPoints[2].subtract(projPoints[0]).length();
  17372. var w = Math.round(Math.max(top, bottom));
  17373. var h = Math.round(Math.max(right, left));
  17374. var isW = w > h;
  17375. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  17376. var edge = Math.max(w, h);
  17377. if (edge < 256) {
  17378. edge = 256;
  17379. }
  17380. else {
  17381. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  17382. }
  17383. // Clip values if needed
  17384. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  17385. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  17386. if (newScale !== this.scale) {
  17387. var scale = newScale;
  17388. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  17389. this._setRenderingScale(scale);
  17390. }
  17391. };
  17392. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  17393. // Check if the update has already been made for this render Frame
  17394. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  17395. return;
  17396. }
  17397. // Detect a change of HWRendering scale
  17398. var hwsl = this.engine.getHardwareScalingLevel();
  17399. var hwslChanged = this._curHWScale !== hwsl;
  17400. if (hwslChanged) {
  17401. this._curHWScale = hwsl;
  17402. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  17403. var child = _a[_i];
  17404. child._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  17405. }
  17406. this._setLayoutDirty();
  17407. }
  17408. // Detect a change of rendering size
  17409. var renderingSizeChanged = false;
  17410. var newWidth = this.engine.getRenderWidth() * hwsl;
  17411. if (newWidth !== this._renderingSize.width) {
  17412. renderingSizeChanged = true;
  17413. }
  17414. this._renderingSize.width = newWidth;
  17415. var newHeight = this.engine.getRenderHeight() * hwsl;
  17416. if (newHeight !== this._renderingSize.height) {
  17417. renderingSizeChanged = true;
  17418. }
  17419. this._renderingSize.height = newHeight;
  17420. // If the canvas fit the rendering size and it changed, update
  17421. if (renderingSizeChanged && this._fitRenderingDevice) {
  17422. this.size = this._renderingSize.clone();
  17423. if (this._background) {
  17424. this._background.size = this.size;
  17425. }
  17426. // Dirty the Layout at the Canvas level to recompute as the size changed
  17427. this._setLayoutDirty();
  17428. }
  17429. // If there's a design size, update the scale according to the renderingSize
  17430. if (this._designSize) {
  17431. var scale = void 0;
  17432. if (this._designUseHorizAxis) {
  17433. scale = this._renderingSize.width / (this._designSize.width * hwsl);
  17434. }
  17435. else {
  17436. scale = this._renderingSize.height / (this._designSize.height * hwsl);
  17437. }
  17438. this.size = this._designSize.clone();
  17439. this._canvasLevelScale.copyFromFloats(scale, scale, 1);
  17440. }
  17441. else if (this._curHWScale !== 1) {
  17442. var ratio = 1 / this._curHWScale;
  17443. this._canvasLevelScale.copyFromFloats(ratio, ratio, 1);
  17444. }
  17445. var context = new BABYLON.PrepareRender2DContext();
  17446. ++this._globalTransformProcessStep;
  17447. this._setFlags(BABYLON.SmartPropertyPrim.flagLocalTransformDirty | BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  17448. this.updateCachedStates(false);
  17449. this._prepareGroupRender(context);
  17450. this._updateRenderId = this.scene.getRenderId();
  17451. };
  17452. /**
  17453. * Method that renders the Canvas, you should not invoke
  17454. */
  17455. Canvas2D.prototype._render = function () {
  17456. this._initPerfMetrics();
  17457. if (this._renderObservable && this._renderObservable.hasObservers()) {
  17458. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_PRE);
  17459. }
  17460. this._updateCanvasState(false);
  17461. this._updateTrackedNodes();
  17462. // Nothing to do is the Canvas is not visible
  17463. if (this.isVisible === false) {
  17464. return;
  17465. }
  17466. if (!this._isScreenSpace) {
  17467. this._updateAdaptiveSizeWorldCanvas();
  17468. }
  17469. this._updateCanvasState(false);
  17470. if (this._primitiveCollisionManager) {
  17471. this._primitiveCollisionManager._update();
  17472. }
  17473. if (this._primPointerInfo.canvasPointerPos) {
  17474. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
  17475. this._updateOverStatus(false);
  17476. }
  17477. this.engine.setState(false, undefined, true);
  17478. this._groupRender();
  17479. if (!this._isScreenSpace) {
  17480. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  17481. this.worldSpaceCacheChanged();
  17482. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  17483. }
  17484. }
  17485. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  17486. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  17487. this._cachedCanvasGroup._renderCachedCanvas();
  17488. }
  17489. this._fetchPerfMetrics();
  17490. this._updateProfileCanvas();
  17491. if (this._renderObservable && this._renderObservable.hasObservers()) {
  17492. this._renderObservable.notifyObservers(this, Canvas2D_1.RENDEROBSERVABLE_POST);
  17493. }
  17494. };
  17495. /**
  17496. * Internal method that allocate a cache for the given group.
  17497. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  17498. * @param group The group to allocate the cache of.
  17499. * @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.
  17500. */
  17501. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  17502. if (useMipMap === void 0) { useMipMap = false; }
  17503. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  17504. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  17505. var rd = group._renderableData;
  17506. var noResizeScale = rd._noResizeOnScale;
  17507. var isCanvas = parent == null;
  17508. var scale;
  17509. if (noResizeScale) {
  17510. scale = isCanvas ? Canvas2D_1._unS : group.parent.actualScale;
  17511. }
  17512. else {
  17513. scale = group.actualScale;
  17514. }
  17515. // Determine size
  17516. var size = group.actualSize;
  17517. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  17518. var originalSize = size.clone();
  17519. if (minSize) {
  17520. size.width = Math.max(minSize.width, size.width);
  17521. size.height = Math.max(minSize.height, size.height);
  17522. }
  17523. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  17524. // Try to find a spot in one of the cached texture
  17525. var res = null;
  17526. var map;
  17527. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  17528. var _map = mapArray_1[_i];
  17529. map = _map;
  17530. var node = map.allocateRect(size);
  17531. if (node) {
  17532. res = { node: node, texture: map };
  17533. break;
  17534. }
  17535. }
  17536. // Couldn't find a map that could fit the rect, create a new map for it
  17537. if (!res) {
  17538. var mapSize = new BABYLON.Size(Canvas2D_1._groupTextureCacheSize, Canvas2D_1._groupTextureCacheSize);
  17539. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  17540. if (size.width > mapSize.width || size.height > mapSize.height) {
  17541. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  17542. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  17543. }
  17544. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  17545. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  17546. map.hasAlpha = true;
  17547. map.anisotropicFilteringLevel = 4;
  17548. mapArray.splice(0, 0, map);
  17549. var node = map.allocateRect(size);
  17550. res = { node: node, texture: map };
  17551. }
  17552. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  17553. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  17554. if (group !== this || this._isScreenSpace) {
  17555. var node = res.node;
  17556. // 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
  17557. var sprite = void 0;
  17558. if (this._cachingStrategy === Canvas2D_1.CACHESTRATEGY_CANVAS) {
  17559. if (this._cachedCanvasGroup) {
  17560. this._cachedCanvasGroup.dispose();
  17561. }
  17562. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  17563. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: originalSize, spriteLocation: node.pos });
  17564. sprite.zOrder = 1;
  17565. sprite.origin = BABYLON.Vector2.Zero();
  17566. }
  17567. else {
  17568. 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 });
  17569. sprite.origin = group.origin.clone();
  17570. sprite.addExternalData("__cachedGroup__", group);
  17571. sprite.pointerEventObservable.add(function (e, s) {
  17572. if (group.pointerEventObservable !== null) {
  17573. group.pointerEventObservable.notifyObservers(e, s.mask);
  17574. }
  17575. });
  17576. res.sprite = sprite;
  17577. }
  17578. if (sprite && noResizeScale) {
  17579. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  17580. sprite.scaleX = relScale.x;
  17581. sprite.scaleY = relScale.y;
  17582. }
  17583. }
  17584. return res;
  17585. };
  17586. /**
  17587. * Internal method used to register a Scene Node to track position for the given group
  17588. * Do not invoke this method, for internal purpose only.
  17589. * @param group the group to track its associated Scene Node
  17590. */
  17591. Canvas2D.prototype._registerTrackedNode = function (group) {
  17592. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  17593. return;
  17594. }
  17595. if (!this._trackedGroups) {
  17596. this._trackedGroups = new Array();
  17597. }
  17598. this._trackedGroups.push(group);
  17599. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  17600. };
  17601. /**
  17602. * Internal method used to unregister a tracked Scene Node
  17603. * Do not invoke this method, it's for internal purpose only.
  17604. * @param group the group to unregister its tracked Scene Node from.
  17605. */
  17606. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  17607. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  17608. return;
  17609. }
  17610. var i = this._trackedGroups.indexOf(group);
  17611. if (i !== -1) {
  17612. this._trackedGroups.splice(i, 1);
  17613. }
  17614. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  17615. };
  17616. /**
  17617. * Get a Solid Color Brush instance matching the given color.
  17618. * @param color The color to retrieve
  17619. * @return A shared instance of the SolidColorBrush2D class that use the given color
  17620. */
  17621. Canvas2D.GetSolidColorBrush = function (color) {
  17622. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  17623. };
  17624. /**
  17625. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  17626. * @param color The color to retrieve
  17627. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  17628. */
  17629. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  17630. return Canvas2D_1._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  17631. };
  17632. /**
  17633. * Get a Gradient Color Brush
  17634. * @param color1 starting color
  17635. * @param color2 engine color
  17636. * @param translation translation vector to apply. default is [0;0]
  17637. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  17638. * @param scale scaling factor to apply. default is 1.
  17639. */
  17640. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  17641. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  17642. if (rotation === void 0) { rotation = 0; }
  17643. if (scale === void 0) { scale = 1; }
  17644. return Canvas2D_1._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  17645. };
  17646. /**
  17647. * Create a solid or gradient brush from a string value.
  17648. * @param brushString should be either
  17649. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  17650. * - "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.
  17651. */
  17652. Canvas2D.GetBrushFromString = function (brushString) {
  17653. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  17654. brushString = brushString.trim();
  17655. var split = brushString.split(",");
  17656. // Solid, formatted as: "[solid:]#FF808080"
  17657. if (split.length === 1) {
  17658. var value = null;
  17659. if (brushString.indexOf("solid:") === 0) {
  17660. value = brushString.substr(6).trim();
  17661. }
  17662. else if (brushString.indexOf("#") === 0) {
  17663. value = brushString;
  17664. }
  17665. else {
  17666. return null;
  17667. }
  17668. return Canvas2D_1.GetSolidColorBrushFromHex(value);
  17669. }
  17670. else {
  17671. if (split[0].indexOf("gradient:") === 0) {
  17672. split[0] = split[0].substr(9).trim();
  17673. }
  17674. try {
  17675. var start = BABYLON.Color4.FromHexString(split[0].trim());
  17676. var end = BABYLON.Color4.FromHexString(split[1].trim());
  17677. var t = BABYLON.Vector2.Zero();
  17678. if (split.length > 2) {
  17679. var v = split[2].trim();
  17680. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  17681. return null;
  17682. }
  17683. var sep = v.indexOf(":");
  17684. var x = parseFloat(v.substr(1, sep));
  17685. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  17686. t = new BABYLON.Vector2(x, y);
  17687. }
  17688. var r = 0;
  17689. if (split.length > 3) {
  17690. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  17691. }
  17692. var s = 1;
  17693. if (split.length > 4) {
  17694. s = parseFloat(split[4].trim());
  17695. }
  17696. return Canvas2D_1.GetGradientColorBrush(start, end, t, r, s);
  17697. }
  17698. catch (e) {
  17699. return null;
  17700. }
  17701. }
  17702. };
  17703. return Canvas2D;
  17704. }(BABYLON.Group2D));
  17705. /**
  17706. * 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.
  17707. * This strategy doesn't allow primitives added directly as children of the Canvas.
  17708. * 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.
  17709. */
  17710. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  17711. /**
  17712. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  17713. * 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.
  17714. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  17715. * 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.
  17716. */
  17717. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  17718. /**
  17719. * 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).
  17720. */
  17721. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  17722. /**
  17723. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  17724. * 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).
  17725. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  17726. */
  17727. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  17728. /**
  17729. * Observable Mask to be notified before rendering is made
  17730. */
  17731. Canvas2D.RENDEROBSERVABLE_PRE = 1;
  17732. /**
  17733. * Observable Mask to be notified after rendering is made
  17734. */
  17735. Canvas2D.RENDEROBSERVABLE_POST = 2;
  17736. Canvas2D._INSTANCES = [];
  17737. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  17738. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  17739. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  17740. Canvas2D._m = BABYLON.Matrix.Identity();
  17741. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  17742. Canvas2D.tS = BABYLON.Vector3.Zero();
  17743. Canvas2D.tT = BABYLON.Vector3.Zero();
  17744. Canvas2D.tR = BABYLON.Quaternion.Identity();
  17745. Canvas2D._tmpMtx = BABYLON.Matrix.Identity();
  17746. Canvas2D._tmpVec3 = BABYLON.Vector3.Zero();
  17747. /**
  17748. * Define the default size used for both the width and height of a MapTexture to allocate.
  17749. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  17750. */
  17751. Canvas2D._groupTextureCacheSize = 1024;
  17752. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  17753. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  17754. Canvas2D = Canvas2D_1 = __decorate([
  17755. BABYLON.className("Canvas2D", "BABYLON")
  17756. ], Canvas2D);
  17757. BABYLON.Canvas2D = Canvas2D;
  17758. var WorldSpaceCanvas2D = (function (_super) {
  17759. __extends(WorldSpaceCanvas2D, _super);
  17760. /**
  17761. * 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.
  17762. * 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.
  17763. * @param scene the Scene that owns the Canvas
  17764. * @param size the dimension of the Canvas in World Space
  17765. * @param settings a combination of settings, possible ones are
  17766. * - children: an array of direct children primitives
  17767. * - id: a text identifier, for information purpose only, default is null.
  17768. * - 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).
  17769. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  17770. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  17771. * - 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
  17772. * - trackNodeOffset: if you use trackNode you may want to specify a 3D Offset to apply to shift the Canvas
  17773. * - trackNodeBillboard: if true the WorldSpaceCanvas will always face the screen
  17774. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  17775. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  17776. * - 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).
  17777. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  17778. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  17779. * - 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.
  17780. * - 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.
  17781. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  17782. * - 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.
  17783. * - 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.
  17784. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  17785. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  17786. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  17787. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  17788. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  17789. */
  17790. function WorldSpaceCanvas2D(scene, size, settings) {
  17791. var _this = this;
  17792. BABYLON.Prim2DBase._isCanvasInit = true;
  17793. var s = settings;
  17794. s.isScreenSpace = false;
  17795. if (settings.unitScaleFactor != null) {
  17796. s.size = size.multiplyByFloats(settings.unitScaleFactor, settings.unitScaleFactor);
  17797. }
  17798. else {
  17799. s.size = size.clone();
  17800. }
  17801. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  17802. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  17803. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  17804. }
  17805. _this = _super.call(this, scene, settings) || this;
  17806. BABYLON.Prim2DBase._isCanvasInit = false;
  17807. _this._unitScaleFactor = (settings.unitScaleFactor != null) ? settings.unitScaleFactor : 1;
  17808. _this._renderableData._useMipMap = true;
  17809. _this._renderableData._anisotropicLevel = 8;
  17810. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  17811. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  17812. //}
  17813. _this._trackNode = (settings.trackNode != null) ? settings.trackNode : null;
  17814. _this._trackNodeOffset = (settings.trackNodeOffset != null) ? settings.trackNodeOffset : BABYLON.Vector3.Zero();
  17815. _this._trackNodeBillboard = (settings.trackNodeBillboard != null) ? settings.trackNodeBillboard : true;
  17816. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  17817. _this._customWorldSpaceNode = !createWorldSpaceNode;
  17818. var id = settings ? settings.id || null : null;
  17819. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  17820. var capMaxTextSize = _this.engine.getCaps().maxRenderTextureSize;
  17821. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 1K if allowed otherwise the max allowed
  17822. if (settings.maxAdaptiveCanvasSize == null) {
  17823. _this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  17824. }
  17825. else {
  17826. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  17827. _this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  17828. }
  17829. if (createWorldSpaceNode) {
  17830. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, _this);
  17831. var vertexData = BABYLON.VertexData.CreatePlane({
  17832. width: size.width,
  17833. height: size.height,
  17834. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  17835. });
  17836. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  17837. _this.applyCachedTexture(vertexData, mtl);
  17838. vertexData.applyToMesh(plane, true);
  17839. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  17840. mtl.disableLighting = true;
  17841. mtl.useAlphaFromDiffuseTexture = true;
  17842. if (settings && settings.sideOrientation) {
  17843. mtl.backFaceCulling = (settings.sideOrientation === BABYLON.Mesh.DEFAULTSIDE || settings.sideOrientation === BABYLON.Mesh.FRONTSIDE);
  17844. }
  17845. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  17846. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  17847. plane.material = mtl;
  17848. _this._worldSpaceNode = plane;
  17849. }
  17850. else {
  17851. _this._worldSpaceNode = settings.customWorldSpaceNode;
  17852. _this.applyCachedTexture(null, null);
  17853. }
  17854. _this.propertyChanged.add(function (e, st) {
  17855. if (e.propertyName !== "isVisible") {
  17856. return;
  17857. }
  17858. var mesh = _this._worldSpaceNode;
  17859. if (mesh) {
  17860. mesh.isVisible = e.newValue;
  17861. }
  17862. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  17863. return _this;
  17864. }
  17865. WorldSpaceCanvas2D.prototype.dispose = function () {
  17866. if (!_super.prototype.dispose.call(this)) {
  17867. return false;
  17868. }
  17869. if (!this._customWorldSpaceNode && this._worldSpaceNode) {
  17870. this._worldSpaceNode.dispose();
  17871. this._worldSpaceNode = null;
  17872. }
  17873. };
  17874. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNode", {
  17875. get: function () {
  17876. return this._trackNode;
  17877. },
  17878. set: function (value) {
  17879. if (this._trackNode === value) {
  17880. return;
  17881. }
  17882. this._trackNode = value;
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeOffset", {
  17888. get: function () {
  17889. return this._trackNodeOffset;
  17890. },
  17891. set: function (value) {
  17892. if (!this._trackNodeOffset) {
  17893. this._trackNodeOffset = value.clone();
  17894. }
  17895. else {
  17896. this._trackNodeOffset.copyFrom(value);
  17897. }
  17898. },
  17899. enumerable: true,
  17900. configurable: true
  17901. });
  17902. Object.defineProperty(WorldSpaceCanvas2D.prototype, "trackNodeBillboard", {
  17903. get: function () {
  17904. return this._trackNodeBillboard;
  17905. },
  17906. set: function (value) {
  17907. this._trackNodeBillboard = value;
  17908. },
  17909. enumerable: true,
  17910. configurable: true
  17911. });
  17912. return WorldSpaceCanvas2D;
  17913. }(Canvas2D));
  17914. WorldSpaceCanvas2D = __decorate([
  17915. BABYLON.className("WorldSpaceCanvas2D", "BABYLON")
  17916. ], WorldSpaceCanvas2D);
  17917. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  17918. var ScreenSpaceCanvas2D = (function (_super) {
  17919. __extends(ScreenSpaceCanvas2D, _super);
  17920. /**
  17921. * 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.
  17922. * 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.
  17923. * All caching strategies will be available.
  17924. * 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]
  17925. * @param scene the Scene that owns the Canvas
  17926. * @param settings a combination of settings, possible ones are
  17927. * - children: an array of direct children primitives
  17928. * - id: a text identifier, for information purpose only
  17929. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  17930. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  17931. * - 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]
  17932. * - width: the width of the Canvas. you can alternatively use the size setting.
  17933. * - height: the height of the Canvas. you can alternatively use the size setting.
  17934. * - 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
  17935. * - 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.
  17936. * - 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.
  17937. * - 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.
  17938. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  17939. * - 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.
  17940. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  17941. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  17942. * - 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.
  17943. * - 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.
  17944. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  17945. * - 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.
  17946. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  17947. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  17948. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  17949. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  17950. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  17951. */
  17952. function ScreenSpaceCanvas2D(scene, settings) {
  17953. var _this = this;
  17954. BABYLON.Prim2DBase._isCanvasInit = true;
  17955. _this = _super.call(this, scene, settings) || this;
  17956. return _this;
  17957. }
  17958. return ScreenSpaceCanvas2D;
  17959. }(Canvas2D));
  17960. ScreenSpaceCanvas2D = __decorate([
  17961. BABYLON.className("ScreenSpaceCanvas2D", "BABYLON")
  17962. ], ScreenSpaceCanvas2D);
  17963. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  17964. var Canvas2D_1;
  17965. })(BABYLON || (BABYLON = {}));
  17966. var __extends = (this && this.__extends) || function (d, b) {
  17967. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17968. function __() { this.constructor = d; }
  17969. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17970. };
  17971. var BABYLON;
  17972. (function (BABYLON) {
  17973. /**
  17974. * This is the class that is used to display a World Space Canvas into a 3D scene
  17975. */
  17976. var WorldSpaceCanvas2DNode = (function (_super) {
  17977. __extends(WorldSpaceCanvas2DNode, _super);
  17978. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  17979. var _this = _super.call(this, name, scene) || this;
  17980. _this._canvas = canvas;
  17981. return _this;
  17982. }
  17983. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  17984. _super.prototype.dispose.call(this);
  17985. if (this._canvas) {
  17986. this._canvas.dispose();
  17987. this._canvas = null;
  17988. }
  17989. };
  17990. return WorldSpaceCanvas2DNode;
  17991. }(BABYLON.Mesh));
  17992. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  17993. })(BABYLON || (BABYLON = {}));
  17994. var __extends = (this && this.__extends) || function (d, b) {
  17995. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  17996. function __() { this.constructor = d; }
  17997. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  17998. };
  17999. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18000. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18001. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18002. 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;
  18003. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18004. };
  18005. var BABYLON;
  18006. (function (BABYLON) {
  18007. var Command = (function () {
  18008. function Command(execute, canExecute) {
  18009. if (!execute) {
  18010. throw Error("At least an execute lambda must be given at Command creation time");
  18011. }
  18012. this._canExecuteChanged = null;
  18013. this._lastCanExecuteResult = null;
  18014. this.execute = execute;
  18015. this.canExecute = canExecute;
  18016. }
  18017. Command.prototype.canExecute = function (parameter) {
  18018. var res = true;
  18019. if (this._canExecute) {
  18020. res = this._canExecute(parameter);
  18021. }
  18022. if (res !== this._lastCanExecuteResult) {
  18023. if (this._canExecuteChanged && this._canExecuteChanged.hasObservers()) {
  18024. this._canExecuteChanged.notifyObservers(null);
  18025. }
  18026. this._lastCanExecuteResult = res;
  18027. }
  18028. return res;
  18029. };
  18030. Command.prototype.execute = function (parameter) {
  18031. this._execute(parameter);
  18032. };
  18033. Object.defineProperty(Command.prototype, "canExecuteChanged", {
  18034. get: function () {
  18035. if (!this._canExecuteChanged) {
  18036. this._canExecuteChanged = new BABYLON.Observable();
  18037. }
  18038. return this._canExecuteChanged;
  18039. },
  18040. enumerable: true,
  18041. configurable: true
  18042. });
  18043. return Command;
  18044. }());
  18045. BABYLON.Command = Command;
  18046. var UIElement = (function (_super) {
  18047. __extends(UIElement, _super);
  18048. function UIElement(settings) {
  18049. var _this = _super.call(this) || this;
  18050. if (!settings) {
  18051. throw Error("A settings object must be passed with at least either a parent or owner parameter");
  18052. }
  18053. var type = BABYLON.Tools.getFullClassName(_this);
  18054. _this._ownerWindow = null;
  18055. _this._parent = null;
  18056. _this._visualPlaceholder = null;
  18057. _this._visualTemplateRoot = null;
  18058. _this._visualChildrenPlaceholder = null;
  18059. _this._hierarchyDepth = 0;
  18060. _this._renderingTemplateName = (settings.templateName != null) ? settings.templateName : GUIManager.DefaultTemplateName;
  18061. _this._style = (settings.styleName != null) ? GUIManager.getStyle(type, settings.styleName) : null;
  18062. _this._flags = 0;
  18063. _this._id = (settings.id != null) ? settings.id : null;
  18064. _this._uid = null;
  18065. _this._width = (settings.width != null) ? settings.width : null;
  18066. _this._height = (settings.height != null) ? settings.height : null;
  18067. _this._minWidth = (settings.minWidth != null) ? settings.minWidth : 0;
  18068. _this._minHeight = (settings.minHeight != null) ? settings.minHeight : 0;
  18069. _this._maxWidth = (settings.maxWidth != null) ? settings.maxWidth : Number.MAX_VALUE;
  18070. _this._maxHeight = (settings.maxHeight != null) ? settings.maxHeight : Number.MAX_VALUE;
  18071. _this._margin = null;
  18072. _this._padding = null;
  18073. _this._marginAlignment = null;
  18074. _this._setFlags(UIElement.flagIsVisible | UIElement.flagIsEnabled);
  18075. // Default Margin Alignment for UIElement is stretch for horizontal/vertical and not left/bottom (which is the default for Canvas2D Primitives)
  18076. //this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  18077. //this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  18078. // Set the layout/margin stuffs
  18079. if (settings.marginTop) {
  18080. _this.margin.setTop(settings.marginTop);
  18081. }
  18082. if (settings.marginLeft) {
  18083. _this.margin.setLeft(settings.marginLeft);
  18084. }
  18085. if (settings.marginRight) {
  18086. _this.margin.setRight(settings.marginRight);
  18087. }
  18088. if (settings.marginBottom) {
  18089. _this.margin.setBottom(settings.marginBottom);
  18090. }
  18091. if (settings.margin) {
  18092. if (typeof settings.margin === "string") {
  18093. _this.margin.fromString(settings.margin);
  18094. }
  18095. else {
  18096. _this.margin.fromUniformPixels(settings.margin);
  18097. }
  18098. }
  18099. if (settings.marginHAlignment) {
  18100. _this.marginAlignment.horizontal = settings.marginHAlignment;
  18101. }
  18102. if (settings.marginVAlignment) {
  18103. _this.marginAlignment.vertical = settings.marginVAlignment;
  18104. }
  18105. if (settings.marginAlignment) {
  18106. _this.marginAlignment.fromString(settings.marginAlignment);
  18107. }
  18108. if (settings.paddingTop) {
  18109. _this.padding.setTop(settings.paddingTop);
  18110. }
  18111. if (settings.paddingLeft) {
  18112. _this.padding.setLeft(settings.paddingLeft);
  18113. }
  18114. if (settings.paddingRight) {
  18115. _this.padding.setRight(settings.paddingRight);
  18116. }
  18117. if (settings.paddingBottom) {
  18118. _this.padding.setBottom(settings.paddingBottom);
  18119. }
  18120. if (settings.padding) {
  18121. _this.padding.fromString(settings.padding);
  18122. }
  18123. if (settings.paddingHAlignment) {
  18124. _this.paddingAlignment.horizontal = settings.paddingHAlignment;
  18125. }
  18126. if (settings.paddingVAlignment) {
  18127. _this.paddingAlignment.vertical = settings.paddingVAlignment;
  18128. }
  18129. if (settings.paddingAlignment) {
  18130. _this.paddingAlignment.fromString(settings.paddingAlignment);
  18131. }
  18132. if (settings.parent != null) {
  18133. _this._parent = settings.parent;
  18134. _this._hierarchyDepth = _this._parent._hierarchyDepth + 1;
  18135. }
  18136. return _this;
  18137. }
  18138. Object.defineProperty(UIElement, "enabledState", {
  18139. get: function () {
  18140. return UIElement._enableState;
  18141. },
  18142. enumerable: true,
  18143. configurable: true
  18144. });
  18145. Object.defineProperty(UIElement, "disabledState", {
  18146. get: function () {
  18147. return UIElement._disabledState;
  18148. },
  18149. enumerable: true,
  18150. configurable: true
  18151. });
  18152. Object.defineProperty(UIElement, "mouseOverState", {
  18153. get: function () {
  18154. return UIElement._mouseOverState;
  18155. },
  18156. enumerable: true,
  18157. configurable: true
  18158. });
  18159. UIElement.prototype.dispose = function () {
  18160. if (this.isDisposed) {
  18161. return false;
  18162. }
  18163. if (this._renderingTemplate) {
  18164. this._renderingTemplate.detach();
  18165. this._renderingTemplate = null;
  18166. }
  18167. _super.prototype.dispose.call(this);
  18168. // Don't set to null, it may upset somebody...
  18169. this.animations.splice(0);
  18170. return true;
  18171. };
  18172. /**
  18173. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  18174. * Look at Sprite2D for more information
  18175. */
  18176. UIElement.prototype.getAnimatables = function () {
  18177. return new Array();
  18178. };
  18179. // TODO
  18180. // PROPERTIES
  18181. // Style
  18182. // Id
  18183. // Parent/Children
  18184. // ActualWidth/Height, MinWidth/Height, MaxWidth/Height,
  18185. // Alignment/Margin
  18186. // Visibility, IsVisible
  18187. // IsEnabled (is false, control is disabled, no interaction and a specific render state)
  18188. // CacheMode of Visual Elements
  18189. // Focusable/IsFocused
  18190. // IsPointerCaptured, CapturePointer, IsPointerDirectlyOver, IsPointerOver. De-correlate mouse, stylus, touch?
  18191. // ContextMenu
  18192. // Cursor
  18193. // DesiredSize
  18194. // IsInputEnable ?
  18195. // Opacity, OpacityMask ?
  18196. // SnapToDevicePixels
  18197. // Tag
  18198. // ToolTip
  18199. // METHODS
  18200. // BringIntoView (for scrollable content, to move the scroll to bring the given element visible in the parent's area)
  18201. // Capture/ReleaseCapture (mouse, touch, stylus)
  18202. // Focus
  18203. // PointFrom/ToScreen to translate coordinates
  18204. // EVENTS
  18205. // ContextMenuOpening/Closing/Changed
  18206. // DragEnter/LeaveOver, Drop
  18207. // Got/LostFocus
  18208. // IsEnabledChanged
  18209. // IsPointerOver/DirectlyOverChanged
  18210. // IsVisibleChanged
  18211. // KeyDown/Up
  18212. // LayoutUpdated ?
  18213. // Pointer related events
  18214. // SizeChanged
  18215. // ToolTipOpening/Closing
  18216. UIElement.prototype.findById = function (id) {
  18217. if (this._id === id) {
  18218. return this;
  18219. }
  18220. var children = this._getChildren();
  18221. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  18222. var child = children_1[_i];
  18223. var r = child.findById(id);
  18224. if (r != null) {
  18225. return r;
  18226. }
  18227. }
  18228. };
  18229. Object.defineProperty(UIElement.prototype, "ownerWindow", {
  18230. get: function () {
  18231. return this._ownerWindow;
  18232. },
  18233. enumerable: true,
  18234. configurable: true
  18235. });
  18236. Object.defineProperty(UIElement.prototype, "style", {
  18237. get: function () {
  18238. if (!this.style) {
  18239. return GUIManager.DefaultStyleName;
  18240. }
  18241. return this._style.name;
  18242. },
  18243. set: function (value) {
  18244. if (this._style && (this._style.name === value)) {
  18245. return;
  18246. }
  18247. var newStyle = null;
  18248. if (value) {
  18249. newStyle = GUIManager.getStyle(BABYLON.Tools.getFullClassName(this), value);
  18250. if (!newStyle) {
  18251. throw Error("Couldn't find Style " + value + " for UIElement " + BABYLON.Tools.getFullClassName(this));
  18252. }
  18253. }
  18254. if (this._style) {
  18255. this._style.removeStyle(this);
  18256. }
  18257. if (newStyle) {
  18258. newStyle.applyStyle(this);
  18259. }
  18260. this._style = newStyle;
  18261. },
  18262. enumerable: true,
  18263. configurable: true
  18264. });
  18265. Object.defineProperty(UIElement.prototype, "id", {
  18266. /**
  18267. * A string that identifies the UIElement.
  18268. * The id is optional and there's possible collision with other UIElement's id as the uniqueness is not supported.
  18269. */
  18270. get: function () {
  18271. return this._id;
  18272. },
  18273. set: function (value) {
  18274. if (this._id === value) {
  18275. return;
  18276. }
  18277. this._id = value;
  18278. },
  18279. enumerable: true,
  18280. configurable: true
  18281. });
  18282. Object.defineProperty(UIElement.prototype, "uid", {
  18283. /**
  18284. * Return a unique id automatically generated.
  18285. * This property is mainly used for serialization to ensure a perfect way of identifying a UIElement
  18286. */
  18287. get: function () {
  18288. if (!this._uid) {
  18289. this._uid = BABYLON.Tools.RandomId();
  18290. }
  18291. return this._uid;
  18292. },
  18293. enumerable: true,
  18294. configurable: true
  18295. });
  18296. Object.defineProperty(UIElement.prototype, "hierarchyDepth", {
  18297. get: function () {
  18298. return this._hierarchyDepth;
  18299. },
  18300. enumerable: true,
  18301. configurable: true
  18302. });
  18303. Object.defineProperty(UIElement.prototype, "parent", {
  18304. get: function () {
  18305. return this._parent;
  18306. },
  18307. set: function (value) {
  18308. this._parent = value;
  18309. },
  18310. enumerable: true,
  18311. configurable: true
  18312. });
  18313. Object.defineProperty(UIElement.prototype, "width", {
  18314. get: function () {
  18315. return this._width;
  18316. },
  18317. set: function (value) {
  18318. this._width = value;
  18319. },
  18320. enumerable: true,
  18321. configurable: true
  18322. });
  18323. Object.defineProperty(UIElement.prototype, "height", {
  18324. get: function () {
  18325. return this._height;
  18326. },
  18327. set: function (value) {
  18328. this._height = value;
  18329. },
  18330. enumerable: true,
  18331. configurable: true
  18332. });
  18333. Object.defineProperty(UIElement.prototype, "minWidth", {
  18334. get: function () {
  18335. return this._minWidth;
  18336. },
  18337. set: function (value) {
  18338. this._minWidth = value;
  18339. },
  18340. enumerable: true,
  18341. configurable: true
  18342. });
  18343. Object.defineProperty(UIElement.prototype, "minHheight", {
  18344. get: function () {
  18345. return this._minHeight;
  18346. },
  18347. enumerable: true,
  18348. configurable: true
  18349. });
  18350. Object.defineProperty(UIElement.prototype, "minHeight", {
  18351. set: function (value) {
  18352. this._minHeight = value;
  18353. },
  18354. enumerable: true,
  18355. configurable: true
  18356. });
  18357. Object.defineProperty(UIElement.prototype, "maxWidth", {
  18358. get: function () {
  18359. return this._maxWidth;
  18360. },
  18361. set: function (value) {
  18362. this._maxWidth = value;
  18363. },
  18364. enumerable: true,
  18365. configurable: true
  18366. });
  18367. Object.defineProperty(UIElement.prototype, "maxHeight", {
  18368. get: function () {
  18369. return this._maxHeight;
  18370. },
  18371. set: function (value) {
  18372. this._maxHeight = value;
  18373. },
  18374. enumerable: true,
  18375. configurable: true
  18376. });
  18377. Object.defineProperty(UIElement.prototype, "actualWidth", {
  18378. get: function () {
  18379. return this._actualWidth;
  18380. },
  18381. set: function (value) {
  18382. this._actualWidth = value;
  18383. },
  18384. enumerable: true,
  18385. configurable: true
  18386. });
  18387. Object.defineProperty(UIElement.prototype, "actualHeight", {
  18388. get: function () {
  18389. return this._actualHeight;
  18390. },
  18391. set: function (value) {
  18392. this._actualHeight = value;
  18393. },
  18394. enumerable: true,
  18395. configurable: true
  18396. });
  18397. Object.defineProperty(UIElement.prototype, "margin", {
  18398. get: function () {
  18399. var _this = this;
  18400. if (!this._margin) {
  18401. this._margin = new BABYLON.PrimitiveThickness(function () {
  18402. if (!_this.parent) {
  18403. return null;
  18404. }
  18405. return _this.parent.margin;
  18406. });
  18407. }
  18408. return this._margin;
  18409. },
  18410. set: function (value) {
  18411. this.margin.copyFrom(value);
  18412. },
  18413. enumerable: true,
  18414. configurable: true
  18415. });
  18416. Object.defineProperty(UIElement.prototype, "_hasMargin", {
  18417. get: function () {
  18418. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  18419. },
  18420. enumerable: true,
  18421. configurable: true
  18422. });
  18423. Object.defineProperty(UIElement.prototype, "padding", {
  18424. get: function () {
  18425. var _this = this;
  18426. if (!this._padding) {
  18427. this._padding = new BABYLON.PrimitiveThickness(function () {
  18428. if (!_this.parent) {
  18429. return null;
  18430. }
  18431. return _this.parent.padding;
  18432. });
  18433. }
  18434. return this._padding;
  18435. },
  18436. set: function (value) {
  18437. this.padding.copyFrom(value);
  18438. },
  18439. enumerable: true,
  18440. configurable: true
  18441. });
  18442. Object.defineProperty(UIElement.prototype, "_hasPadding", {
  18443. get: function () {
  18444. return this._padding !== null && !this._padding.isDefault;
  18445. },
  18446. enumerable: true,
  18447. configurable: true
  18448. });
  18449. Object.defineProperty(UIElement.prototype, "marginAlignment", {
  18450. get: function () {
  18451. if (!this._marginAlignment) {
  18452. this._marginAlignment = new BABYLON.PrimitiveAlignment();
  18453. }
  18454. return this._marginAlignment;
  18455. },
  18456. set: function (value) {
  18457. this.marginAlignment.copyFrom(value);
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. Object.defineProperty(UIElement.prototype, "_hasMarginAlignment", {
  18463. /**
  18464. * Check if there a marginAlignment specified (non null and not default)
  18465. */
  18466. get: function () {
  18467. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  18468. },
  18469. enumerable: true,
  18470. configurable: true
  18471. });
  18472. Object.defineProperty(UIElement.prototype, "paddingAlignment", {
  18473. get: function () {
  18474. if (!this._paddingAlignment) {
  18475. this._paddingAlignment = new BABYLON.PrimitiveAlignment();
  18476. }
  18477. return this._paddingAlignment;
  18478. },
  18479. set: function (value) {
  18480. this.paddingAlignment.copyFrom(value);
  18481. },
  18482. enumerable: true,
  18483. configurable: true
  18484. });
  18485. Object.defineProperty(UIElement.prototype, "_hasPaddingAlignment", {
  18486. /**
  18487. * Check if there a marginAlignment specified (non null and not default)
  18488. */
  18489. get: function () {
  18490. return (this._paddingAlignment !== null && !this._paddingAlignment.isDefault);
  18491. },
  18492. enumerable: true,
  18493. configurable: true
  18494. });
  18495. Object.defineProperty(UIElement.prototype, "isVisible", {
  18496. get: function () {
  18497. return this._isFlagSet(UIElement.flagIsVisible);
  18498. },
  18499. set: function (value) {
  18500. if (this.isVisible === value) {
  18501. return;
  18502. }
  18503. this._visualPlaceholder.levelVisible = value;
  18504. this._changeFlags(UIElement.flagIsVisible, value);
  18505. },
  18506. enumerable: true,
  18507. configurable: true
  18508. });
  18509. Object.defineProperty(UIElement.prototype, "isEnabled", {
  18510. get: function () {
  18511. return this._isFlagSet(UIElement.flagIsEnabled);
  18512. },
  18513. set: function (value) {
  18514. this._changeFlags(UIElement.flagIsEnabled, value);
  18515. },
  18516. enumerable: true,
  18517. configurable: true
  18518. });
  18519. Object.defineProperty(UIElement.prototype, "isFocused", {
  18520. get: function () {
  18521. return this._isFlagSet(UIElement.flagIsFocus);
  18522. },
  18523. set: function (value) {
  18524. // If the UIElement doesn't accept focus, set it on its parent
  18525. if (!this.isFocusable) {
  18526. var p = this.parent;
  18527. if (!p) {
  18528. return;
  18529. }
  18530. p.isFocused = value;
  18531. }
  18532. // If the focus is being set, notify the Focus Manager
  18533. if (value) {
  18534. this.ownerWindow.focusManager.setFocusOn(this, this.getFocusScope());
  18535. }
  18536. this._changeFlags(UIElement.flagIsFocus, value);
  18537. },
  18538. enumerable: true,
  18539. configurable: true
  18540. });
  18541. Object.defineProperty(UIElement.prototype, "isMouseOver", {
  18542. get: function () {
  18543. return this._isFlagSet(UIElement.flagIsMouseOver);
  18544. },
  18545. set: function (value) {
  18546. this._changeFlags(UIElement.flagIsMouseOver, value);
  18547. },
  18548. enumerable: true,
  18549. configurable: true
  18550. });
  18551. Object.defineProperty(UIElement.prototype, "isFocusScope", {
  18552. get: function () {
  18553. return this._isFlagSet(UIElement.flagIsFocusScope);
  18554. },
  18555. set: function (value) {
  18556. this._changeFlags(UIElement.flagIsFocusScope, value);
  18557. },
  18558. enumerable: true,
  18559. configurable: true
  18560. });
  18561. Object.defineProperty(UIElement.prototype, "isFocusable", {
  18562. get: function () {
  18563. return this._isFlagSet(UIElement.flagIsFocusable);
  18564. },
  18565. set: function (value) {
  18566. this._changeFlags(UIElement.flagIsFocusable, value);
  18567. },
  18568. enumerable: true,
  18569. configurable: true
  18570. });
  18571. // 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)
  18572. UIElement.prototype.getFocusScope = function () {
  18573. if (this.isFocusScope) {
  18574. return this;
  18575. }
  18576. var p = this.parent;
  18577. if (!p) {
  18578. return null;
  18579. }
  18580. return p.getFocusScope();
  18581. };
  18582. /**
  18583. * Check if a given flag is set
  18584. * @param flag the flag value
  18585. * @return true if set, false otherwise
  18586. */
  18587. UIElement.prototype._isFlagSet = function (flag) {
  18588. return (this._flags & flag) !== 0;
  18589. };
  18590. /**
  18591. * Check if all given flags are set
  18592. * @param flags the flags ORed
  18593. * @return true if all the flags are set, false otherwise
  18594. */
  18595. UIElement.prototype._areAllFlagsSet = function (flags) {
  18596. return (this._flags & flags) === flags;
  18597. };
  18598. /**
  18599. * Check if at least one flag of the given flags is set
  18600. * @param flags the flags ORed
  18601. * @return true if at least one flag is set, false otherwise
  18602. */
  18603. UIElement.prototype._areSomeFlagsSet = function (flags) {
  18604. return (this._flags & flags) !== 0;
  18605. };
  18606. /**
  18607. * Clear the given flags
  18608. * @param flags the flags to clear
  18609. */
  18610. UIElement.prototype._clearFlags = function (flags) {
  18611. this._flags &= ~flags;
  18612. };
  18613. /**
  18614. * Set the given flags to true state
  18615. * @param flags the flags ORed to set
  18616. * @return the flags state before this call
  18617. */
  18618. UIElement.prototype._setFlags = function (flags) {
  18619. var cur = this._flags;
  18620. this._flags |= flags;
  18621. return cur;
  18622. };
  18623. /**
  18624. * Change the state of the given flags
  18625. * @param flags the flags ORed to change
  18626. * @param state true to set them, false to clear them
  18627. */
  18628. UIElement.prototype._changeFlags = function (flags, state) {
  18629. if (state) {
  18630. this._flags |= flags;
  18631. }
  18632. else {
  18633. this._flags &= ~flags;
  18634. }
  18635. };
  18636. UIElement.prototype._assignTemplate = function (templateName) {
  18637. if (!templateName) {
  18638. templateName = GUIManager.DefaultTemplateName;
  18639. }
  18640. var className = BABYLON.Tools.getFullClassName(this);
  18641. if (!className) {
  18642. throw Error("Couldn't access class name of this UIElement, you have to decorate the type with the className decorator");
  18643. }
  18644. var factory = GUIManager.getRenderingTemplate(className, templateName);
  18645. if (!factory) {
  18646. throw Error("Couldn't get the renderingTemplate " + templateName + " of class " + className);
  18647. }
  18648. this._renderingTemplateName = templateName;
  18649. this._renderingTemplate = factory();
  18650. this._renderingTemplate.attach(this);
  18651. };
  18652. UIElement.prototype._createVisualTree = function () {
  18653. var parentPrim = this.ownerWindow.canvas;
  18654. if (this.parent) {
  18655. parentPrim = this.parent.visualChildrenPlaceholder;
  18656. }
  18657. if (!this._renderingTemplate) {
  18658. this._assignTemplate(this._renderingTemplateName);
  18659. }
  18660. this._visualPlaceholder = new BABYLON.Group2D({ parent: parentPrim, id: "GUI " + BABYLON.Tools.getClassName(this) + " RootGroup of " + this.id });
  18661. var p = this._visualPlaceholder;
  18662. p.addExternalData("_GUIOwnerElement_", this);
  18663. p.dataSource = this;
  18664. p.createSimpleDataBinding(BABYLON.Prim2DBase.widthProperty, "width", BABYLON.DataBinding.MODE_ONEWAY);
  18665. p.createSimpleDataBinding(BABYLON.Prim2DBase.heightProperty, "height", BABYLON.DataBinding.MODE_ONEWAY);
  18666. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualWidthProperty, "actualWidth", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  18667. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualHeightProperty, "actualHeight", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  18668. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "margin", BABYLON.DataBinding.MODE_ONEWAY);
  18669. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "marginAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  18670. this.createVisualTree();
  18671. };
  18672. UIElement.prototype._patchUIElement = function (ownerWindow, parent) {
  18673. if (ownerWindow) {
  18674. if (!this._ownerWindow) {
  18675. ownerWindow._registerVisualToBuild(this);
  18676. }
  18677. this._ownerWindow = ownerWindow;
  18678. }
  18679. this._parent = parent;
  18680. if (parent) {
  18681. this._hierarchyDepth = parent.hierarchyDepth + 1;
  18682. }
  18683. var children = this._getChildren();
  18684. if (children) {
  18685. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  18686. var curChild = children_2[_i];
  18687. curChild._patchUIElement(ownerWindow, this);
  18688. }
  18689. }
  18690. };
  18691. // 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.
  18692. UIElement.prototype._getDataSource = function () {
  18693. var levelDS = _super.prototype._getDataSource.call(this);
  18694. if (levelDS != null) {
  18695. return levelDS;
  18696. }
  18697. var p = this.parent;
  18698. if (p != null) {
  18699. return p.dataSource;
  18700. }
  18701. return null;
  18702. };
  18703. UIElement.prototype.createVisualTree = function () {
  18704. var res = this._renderingTemplate.createVisualTree(this, this._visualPlaceholder);
  18705. this._visualTemplateRoot = res.root;
  18706. this._visualChildrenPlaceholder = res.contentPlaceholder;
  18707. };
  18708. Object.defineProperty(UIElement.prototype, "visualPlaceholder", {
  18709. get: function () {
  18710. return this._visualPlaceholder;
  18711. },
  18712. enumerable: true,
  18713. configurable: true
  18714. });
  18715. Object.defineProperty(UIElement.prototype, "visualTemplateRoot", {
  18716. get: function () {
  18717. return this._visualTemplateRoot;
  18718. },
  18719. enumerable: true,
  18720. configurable: true
  18721. });
  18722. Object.defineProperty(UIElement.prototype, "visualChildrenPlaceholder", {
  18723. get: function () {
  18724. return this._visualChildrenPlaceholder;
  18725. },
  18726. enumerable: true,
  18727. configurable: true
  18728. });
  18729. Object.defineProperty(UIElement.prototype, "_position", {
  18730. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  18731. ,
  18732. enumerable: true,
  18733. configurable: true
  18734. });
  18735. return UIElement;
  18736. }(BABYLON.SmartPropertyBase));
  18737. UIElement.UIELEMENT_PROPCOUNT = 16;
  18738. UIElement.flagVisualToBuild = 0x0000001;
  18739. UIElement.flagIsVisible = 0x0000002;
  18740. UIElement.flagIsFocus = 0x0000004;
  18741. UIElement.flagIsFocusScope = 0x0000008;
  18742. UIElement.flagIsFocusable = 0x0000010;
  18743. UIElement.flagIsEnabled = 0x0000020;
  18744. UIElement.flagIsMouseOver = 0x0000040;
  18745. UIElement._enableState = "Enabled";
  18746. UIElement._disabledState = "Disabled";
  18747. UIElement._mouseOverState = "MouseOver";
  18748. __decorate([
  18749. BABYLON.dependencyProperty(0, function (pi) { return UIElement.parentProperty = pi; })
  18750. ], UIElement.prototype, "parent", null);
  18751. __decorate([
  18752. BABYLON.dependencyProperty(1, function (pi) { return UIElement.widthProperty = pi; })
  18753. ], UIElement.prototype, "width", null);
  18754. __decorate([
  18755. BABYLON.dependencyProperty(2, function (pi) { return UIElement.heightProperty = pi; })
  18756. ], UIElement.prototype, "height", null);
  18757. __decorate([
  18758. BABYLON.dependencyProperty(3, function (pi) { return UIElement.minWidthProperty = pi; })
  18759. ], UIElement.prototype, "minWidth", null);
  18760. __decorate([
  18761. BABYLON.dependencyProperty(4, function (pi) { return UIElement.minHeightProperty = pi; })
  18762. ], UIElement.prototype, "minHheight", null);
  18763. __decorate([
  18764. BABYLON.dependencyProperty(5, function (pi) { return UIElement.maxWidthProperty = pi; })
  18765. ], UIElement.prototype, "maxWidth", null);
  18766. __decorate([
  18767. BABYLON.dependencyProperty(6, function (pi) { return UIElement.maxHeightProperty = pi; })
  18768. ], UIElement.prototype, "maxHeight", null);
  18769. __decorate([
  18770. BABYLON.dependencyProperty(7, function (pi) { return UIElement.actualWidthProperty = pi; })
  18771. ], UIElement.prototype, "actualWidth", null);
  18772. __decorate([
  18773. BABYLON.dependencyProperty(8, function (pi) { return UIElement.actualHeightProperty = pi; })
  18774. ], UIElement.prototype, "actualHeight", null);
  18775. __decorate([
  18776. BABYLON.dynamicLevelProperty(9, function (pi) { return UIElement.marginProperty = pi; })
  18777. ], UIElement.prototype, "margin", null);
  18778. __decorate([
  18779. BABYLON.dynamicLevelProperty(10, function (pi) { return UIElement.paddingProperty = pi; })
  18780. ], UIElement.prototype, "padding", null);
  18781. __decorate([
  18782. BABYLON.dynamicLevelProperty(11, function (pi) { return UIElement.marginAlignmentProperty = pi; })
  18783. ], UIElement.prototype, "marginAlignment", null);
  18784. __decorate([
  18785. BABYLON.dynamicLevelProperty(12, function (pi) { return UIElement.paddingAlignmentProperty = pi; })
  18786. ], UIElement.prototype, "paddingAlignment", null);
  18787. __decorate([
  18788. BABYLON.dynamicLevelProperty(13, function (pi) { return UIElement.isEnabledProperty = pi; })
  18789. ], UIElement.prototype, "isEnabled", null);
  18790. __decorate([
  18791. BABYLON.dynamicLevelProperty(14, function (pi) { return UIElement.isFocusedProperty = pi; })
  18792. ], UIElement.prototype, "isFocused", null);
  18793. __decorate([
  18794. BABYLON.dynamicLevelProperty(15, function (pi) { return UIElement.isMouseOverProperty = pi; })
  18795. ], UIElement.prototype, "isMouseOver", null);
  18796. BABYLON.UIElement = UIElement;
  18797. var UIElementStyle = (function () {
  18798. function UIElementStyle() {
  18799. }
  18800. Object.defineProperty(UIElementStyle.prototype, "name", {
  18801. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  18802. ,
  18803. enumerable: true,
  18804. configurable: true
  18805. });
  18806. return UIElementStyle;
  18807. }());
  18808. BABYLON.UIElementStyle = UIElementStyle;
  18809. var GUIManager = (function () {
  18810. function GUIManager() {
  18811. }
  18812. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18813. // DATA TEMPLATE MANAGER
  18814. GUIManager.registerDataTemplate = function (className, factory) {
  18815. };
  18816. // DATA TEMPLATE MANAGER
  18817. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18818. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18819. // STYLE MANAGER
  18820. GUIManager.getStyle = function (uiElType, styleName) {
  18821. var styles = GUIManager.stylesByUIElement.get(uiElType);
  18822. if (!styles) {
  18823. throw Error("The type " + uiElType + " is unknown, no style were registered for it.");
  18824. }
  18825. var style = styles.get(styleName);
  18826. if (!style) {
  18827. throw Error("Couldn't find Template " + styleName + " of UIElement type " + uiElType);
  18828. }
  18829. return style;
  18830. };
  18831. GUIManager.registerStyle = function (uiElType, templateName, style) {
  18832. var templates = GUIManager.stylesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  18833. if (templates.contains(templateName)) {
  18834. templates[templateName] = style;
  18835. }
  18836. else {
  18837. templates.add(templateName, style);
  18838. }
  18839. };
  18840. Object.defineProperty(GUIManager, "DefaultStyleName", {
  18841. get: function () {
  18842. return GUIManager._defaultStyleName;
  18843. },
  18844. set: function (value) {
  18845. GUIManager._defaultStyleName = value;
  18846. },
  18847. enumerable: true,
  18848. configurable: true
  18849. });
  18850. // STYLE MANAGER
  18851. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18852. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18853. // RENDERING TEMPLATE MANAGER
  18854. GUIManager.getRenderingTemplate = function (uiElType, templateName) {
  18855. var templates = GUIManager.renderingTemplatesByUIElement.get(uiElType);
  18856. if (!templates) {
  18857. throw Error("The type " + uiElType + " is unknown, no Rendering Template were registered for it.");
  18858. }
  18859. var templateFactory = templates.get(templateName);
  18860. if (!templateFactory) {
  18861. throw Error("Couldn't find Template " + templateName + " of UI Element type " + uiElType);
  18862. }
  18863. return templateFactory;
  18864. };
  18865. GUIManager.registerRenderingTemplate = function (uiElType, templateName, factory) {
  18866. var templates = GUIManager.renderingTemplatesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  18867. if (templates.contains(templateName)) {
  18868. templates[templateName] = factory;
  18869. }
  18870. else {
  18871. templates.add(templateName, factory);
  18872. }
  18873. };
  18874. Object.defineProperty(GUIManager, "DefaultTemplateName", {
  18875. get: function () {
  18876. return GUIManager._defaultTemplateName;
  18877. },
  18878. set: function (value) {
  18879. GUIManager._defaultTemplateName = value;
  18880. },
  18881. enumerable: true,
  18882. configurable: true
  18883. });
  18884. return GUIManager;
  18885. }());
  18886. GUIManager.stylesByUIElement = new BABYLON.StringDictionary();
  18887. GUIManager.renderingTemplatesByUIElement = new BABYLON.StringDictionary();
  18888. // RENDERING TEMPLATE MANAGER
  18889. /////////////////////////////////////////////////////////////////////////////////////////////////////
  18890. GUIManager._defaultTemplateName = "Default";
  18891. GUIManager._defaultStyleName = "Default";
  18892. BABYLON.GUIManager = GUIManager;
  18893. var UIElementRenderingTemplateBase = (function () {
  18894. function UIElementRenderingTemplateBase() {
  18895. }
  18896. UIElementRenderingTemplateBase.prototype.attach = function (owner) {
  18897. this._owner = owner;
  18898. };
  18899. UIElementRenderingTemplateBase.prototype.detach = function () {
  18900. };
  18901. Object.defineProperty(UIElementRenderingTemplateBase.prototype, "owner", {
  18902. get: function () {
  18903. return this._owner;
  18904. },
  18905. enumerable: true,
  18906. configurable: true
  18907. });
  18908. return UIElementRenderingTemplateBase;
  18909. }());
  18910. BABYLON.UIElementRenderingTemplateBase = UIElementRenderingTemplateBase;
  18911. function registerWindowRenderingTemplate(uiElType, templateName, factory) {
  18912. return function () {
  18913. GUIManager.registerRenderingTemplate(uiElType, templateName, factory);
  18914. };
  18915. }
  18916. BABYLON.registerWindowRenderingTemplate = registerWindowRenderingTemplate;
  18917. })(BABYLON || (BABYLON = {}));
  18918. var __extends = (this && this.__extends) || function (d, b) {
  18919. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  18920. function __() { this.constructor = d; }
  18921. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  18922. };
  18923. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  18924. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  18925. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  18926. 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;
  18927. return c > 3 && r && Object.defineProperty(target, key, r), r;
  18928. };
  18929. var BABYLON;
  18930. (function (BABYLON) {
  18931. var StackPanel = StackPanel_1 = (function (_super) {
  18932. __extends(StackPanel, _super);
  18933. function StackPanel(settings) {
  18934. var _this = this;
  18935. if (!settings) {
  18936. settings = {};
  18937. }
  18938. _this = _super.call(this, settings) || this;
  18939. _this.isOrientationHorizontal = (settings.isOrientationHorizontal == null) ? true : settings.isOrientationHorizontal;
  18940. _this._children = new Array();
  18941. if (settings.children != null) {
  18942. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  18943. var child = _a[_i];
  18944. _this._children.push(child);
  18945. }
  18946. }
  18947. return _this;
  18948. }
  18949. Object.defineProperty(StackPanel.prototype, "isOrientationHorizontal", {
  18950. get: function () {
  18951. return this._isOrientationHorizontal;
  18952. },
  18953. set: function (value) {
  18954. this._isOrientationHorizontal = value;
  18955. },
  18956. enumerable: true,
  18957. configurable: true
  18958. });
  18959. StackPanel.prototype.createVisualTree = function () {
  18960. _super.prototype.createVisualTree.call(this);
  18961. // A StackPanel Control has a Group2D, child of the visualPlaceHolder, which is the Children placeholder.
  18962. // The Children UIElement Tree will be create inside this placeholder.
  18963. this._childrenPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "StackPanel Children Placeholder of " + this.id });
  18964. var p = this._childrenPlaceholder;
  18965. p.layoutEngine = this.isOrientationHorizontal ? BABYLON.StackPanelLayoutEngine.Horizontal : BABYLON.StackPanelLayoutEngine.Vertical;
  18966. // 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.
  18967. p.dataSource = this;
  18968. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  18969. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  18970. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  18971. // But it's not the case for a StackPanel, the placeholder of UIElement Children (the content)
  18972. this._visualChildrenPlaceholder = this._childrenPlaceholder;
  18973. };
  18974. Object.defineProperty(StackPanel.prototype, "children", {
  18975. get: function () {
  18976. return this._children;
  18977. },
  18978. enumerable: true,
  18979. configurable: true
  18980. });
  18981. StackPanel.prototype._getChildren = function () {
  18982. return this.children;
  18983. };
  18984. return StackPanel;
  18985. }(BABYLON.UIElement));
  18986. StackPanel.STACKPANEL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3;
  18987. __decorate([
  18988. BABYLON.dependencyProperty(StackPanel_1.STACKPANEL_PROPCOUNT + 0, function (pi) { return StackPanel_1.orientationHorizontalProperty = pi; })
  18989. ], StackPanel.prototype, "isOrientationHorizontal", null);
  18990. StackPanel = StackPanel_1 = __decorate([
  18991. BABYLON.className("StackPanel", "BABYLON")
  18992. ], StackPanel);
  18993. BABYLON.StackPanel = StackPanel;
  18994. var DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = (function (_super) {
  18995. __extends(DefaultStackPanelRenderingTemplate, _super);
  18996. function DefaultStackPanelRenderingTemplate() {
  18997. return _super !== null && _super.apply(this, arguments) || this;
  18998. }
  18999. DefaultStackPanelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19000. return { root: visualPlaceholder, contentPlaceholder: visualPlaceholder };
  19001. };
  19002. DefaultStackPanelRenderingTemplate.prototype.attach = function (owner) {
  19003. _super.prototype.attach.call(this, owner);
  19004. };
  19005. return DefaultStackPanelRenderingTemplate;
  19006. }(BABYLON.UIElementRenderingTemplateBase));
  19007. DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate_1 = __decorate([
  19008. BABYLON.registerWindowRenderingTemplate("BABYLON.StackPanel", "Default", function () { return new DefaultStackPanelRenderingTemplate_1(); })
  19009. ], DefaultStackPanelRenderingTemplate);
  19010. BABYLON.DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate;
  19011. var StackPanel_1, DefaultStackPanelRenderingTemplate_1;
  19012. })(BABYLON || (BABYLON = {}));
  19013. var __extends = (this && this.__extends) || function (d, b) {
  19014. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19015. function __() { this.constructor = d; }
  19016. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19017. };
  19018. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19019. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19020. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19021. 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;
  19022. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19023. };
  19024. var BABYLON;
  19025. (function (BABYLON) {
  19026. var Control = Control_1 = (function (_super) {
  19027. __extends(Control, _super);
  19028. function Control(settings) {
  19029. return _super.call(this, settings) || this;
  19030. }
  19031. Object.defineProperty(Control.prototype, "background", {
  19032. get: function () {
  19033. if (!this._background) {
  19034. this._background = new BABYLON.ObservableStringDictionary(false);
  19035. }
  19036. return this._background;
  19037. },
  19038. set: function (value) {
  19039. this.background.copyFrom(value);
  19040. },
  19041. enumerable: true,
  19042. configurable: true
  19043. });
  19044. Object.defineProperty(Control.prototype, "border", {
  19045. get: function () {
  19046. return this._border;
  19047. },
  19048. set: function (value) {
  19049. this._border = value;
  19050. },
  19051. enumerable: true,
  19052. configurable: true
  19053. });
  19054. Object.defineProperty(Control.prototype, "borderThickness", {
  19055. get: function () {
  19056. return this._borderThickness;
  19057. },
  19058. set: function (value) {
  19059. this._borderThickness = value;
  19060. },
  19061. enumerable: true,
  19062. configurable: true
  19063. });
  19064. Object.defineProperty(Control.prototype, "fontName", {
  19065. get: function () {
  19066. return this._fontName;
  19067. },
  19068. set: function (value) {
  19069. this._fontName = value;
  19070. },
  19071. enumerable: true,
  19072. configurable: true
  19073. });
  19074. Object.defineProperty(Control.prototype, "foreground", {
  19075. get: function () {
  19076. return this._foreground;
  19077. },
  19078. set: function (value) {
  19079. this._foreground = value;
  19080. },
  19081. enumerable: true,
  19082. configurable: true
  19083. });
  19084. return Control;
  19085. }(BABYLON.UIElement));
  19086. Control.CONTROL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 5;
  19087. __decorate([
  19088. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 0, function (pi) { return Control_1.backgroundProperty = pi; })
  19089. ], Control.prototype, "background", null);
  19090. __decorate([
  19091. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 1, function (pi) { return Control_1.borderProperty = pi; })
  19092. ], Control.prototype, "border", null);
  19093. __decorate([
  19094. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 2, function (pi) { return Control_1.borderThicknessProperty = pi; })
  19095. ], Control.prototype, "borderThickness", null);
  19096. __decorate([
  19097. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3, function (pi) { return Control_1.fontNameProperty = pi; })
  19098. ], Control.prototype, "fontName", null);
  19099. __decorate([
  19100. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 4, function (pi) { return Control_1.foregroundProperty = pi; })
  19101. ], Control.prototype, "foreground", null);
  19102. Control = Control_1 = __decorate([
  19103. BABYLON.className("Control", "BABYLON")
  19104. ], Control);
  19105. BABYLON.Control = Control;
  19106. var Control_1;
  19107. })(BABYLON || (BABYLON = {}));
  19108. var __extends = (this && this.__extends) || function (d, b) {
  19109. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19110. function __() { this.constructor = d; }
  19111. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19112. };
  19113. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19114. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19115. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19116. 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;
  19117. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19118. };
  19119. var BABYLON;
  19120. (function (BABYLON) {
  19121. var ContentControl = ContentControl_1 = (function (_super) {
  19122. __extends(ContentControl, _super);
  19123. function ContentControl(settings) {
  19124. var _this = this;
  19125. if (!settings) {
  19126. settings = {};
  19127. }
  19128. _this = _super.call(this, settings) || this;
  19129. if (settings.content != null) {
  19130. _this._content = settings.content;
  19131. }
  19132. return _this;
  19133. }
  19134. ContentControl.prototype.dispose = function () {
  19135. if (this.isDisposed) {
  19136. return false;
  19137. }
  19138. if (this.content && this.content.dispose) {
  19139. this.content.dispose();
  19140. this.content = null;
  19141. }
  19142. if (this.__contentUIElement) {
  19143. this.__contentUIElement.dispose();
  19144. this.__contentUIElement = null;
  19145. }
  19146. _super.prototype.dispose.call(this);
  19147. return true;
  19148. };
  19149. Object.defineProperty(ContentControl.prototype, "content", {
  19150. get: function () {
  19151. return this._content;
  19152. },
  19153. set: function (value) {
  19154. this._content = value;
  19155. },
  19156. enumerable: true,
  19157. configurable: true
  19158. });
  19159. Object.defineProperty(ContentControl.prototype, "_contentUIElement", {
  19160. get: function () {
  19161. if (!this.__contentUIElement) {
  19162. this._buildContentUIElement();
  19163. }
  19164. return this.__contentUIElement;
  19165. },
  19166. enumerable: true,
  19167. configurable: true
  19168. });
  19169. ContentControl.prototype._createVisualTree = function () {
  19170. // Base implementation will create the Group2D for the Visual Placeholder and its Visual Tree
  19171. _super.prototype._createVisualTree.call(this);
  19172. // A Content Control has a Group2D, child of the visualPlaceHolder, which is the Content placeholder.
  19173. // The Content UIElement Tree will be create inside this placeholder.
  19174. this._contentPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "ContentControl Content Placeholder of " + this.id });
  19175. var p = this._contentPlaceholder;
  19176. // 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.
  19177. p.dataSource = this;
  19178. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  19179. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  19180. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  19181. // But it's not the case for a ContentControl, the placeholder of UIElement Children (the content)
  19182. this._visualChildrenPlaceholder = this._contentPlaceholder;
  19183. };
  19184. ContentControl.prototype._buildContentUIElement = function () {
  19185. var c = this._content;
  19186. this.__contentUIElement = null;
  19187. // Already a UIElement
  19188. if (c instanceof BABYLON.UIElement) {
  19189. this.__contentUIElement = c;
  19190. }
  19191. else if ((typeof c === "string") || (typeof c === "boolean") || (typeof c === "number")) {
  19192. var l = new BABYLON.Label({ parent: this, id: "Content of " + this.id });
  19193. var binding = new BABYLON.DataBinding();
  19194. binding.propertyPathName = "content";
  19195. binding.stringFormat = function (v) { return "" + v; };
  19196. binding.dataSource = this;
  19197. l.createDataBinding(BABYLON.Label.textProperty, binding);
  19198. this.__contentUIElement = l;
  19199. }
  19200. else {
  19201. }
  19202. if (this.__contentUIElement) {
  19203. this.__contentUIElement._patchUIElement(this.ownerWindow, this);
  19204. }
  19205. };
  19206. ContentControl.prototype._getChildren = function () {
  19207. var children = new Array();
  19208. if (this.content) {
  19209. children.push(this._contentUIElement);
  19210. }
  19211. return children;
  19212. };
  19213. return ContentControl;
  19214. }(BABYLON.Control));
  19215. ContentControl.CONTENTCONTROL_PROPCOUNT = BABYLON.Control.CONTROL_PROPCOUNT + 2;
  19216. __decorate([
  19217. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return ContentControl_1.contentProperty = pi; })
  19218. ], ContentControl.prototype, "content", null);
  19219. ContentControl = ContentControl_1 = __decorate([
  19220. BABYLON.className("ContentControl", "BABYLON")
  19221. ], ContentControl);
  19222. BABYLON.ContentControl = ContentControl;
  19223. var ContentControl_1;
  19224. })(BABYLON || (BABYLON = {}));
  19225. var __extends = (this && this.__extends) || function (d, b) {
  19226. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19227. function __() { this.constructor = d; }
  19228. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19229. };
  19230. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19231. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19232. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19233. 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;
  19234. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19235. };
  19236. var BABYLON;
  19237. (function (BABYLON) {
  19238. var FocusScopeData = (function () {
  19239. function FocusScopeData(focusScope) {
  19240. this.focusScope = focusScope;
  19241. this.focusedElement = null;
  19242. }
  19243. return FocusScopeData;
  19244. }());
  19245. var FocusManager = (function () {
  19246. function FocusManager() {
  19247. this._focusScopes = new BABYLON.StringDictionary();
  19248. this._rootScope = new FocusScopeData(null);
  19249. this._activeScope = null;
  19250. }
  19251. FocusManager.prototype.setFocusOn = function (el, focusScope) {
  19252. var fsd = (focusScope != null) ? this._focusScopes.getOrAddWithFactory(focusScope.uid, function (k) { return new FocusScopeData(focusScope); }) : this._rootScope;
  19253. if (fsd.focusedElement !== el) {
  19254. // Remove focus from current
  19255. if (fsd.focusedElement) {
  19256. fsd.focusedElement.isFocused = false;
  19257. }
  19258. fsd.focusedElement = el;
  19259. }
  19260. if (this._activeScope !== fsd) {
  19261. this._activeScope = fsd;
  19262. }
  19263. };
  19264. return FocusManager;
  19265. }());
  19266. BABYLON.FocusManager = FocusManager;
  19267. var GUISceneData = (function () {
  19268. function GUISceneData(scene) {
  19269. this.scene = scene;
  19270. this.screenSpaceCanvas = new BABYLON.ScreenSpaceCanvas2D(scene, { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE });
  19271. this.focusManager = new FocusManager();
  19272. }
  19273. return GUISceneData;
  19274. }());
  19275. var Window = Window_1 = (function (_super) {
  19276. __extends(Window, _super);
  19277. function Window(scene, settings) {
  19278. var _this = this;
  19279. if (!settings) {
  19280. settings = {};
  19281. }
  19282. _this = _super.call(this, settings) || this;
  19283. // Per default a Window is focus scope
  19284. _this.isFocusScope = true;
  19285. _this.isActive = false;
  19286. if (!_this._UIElementVisualToBuildList) {
  19287. _this._UIElementVisualToBuildList = new Array();
  19288. }
  19289. // Patch the owner and also the parent property through the whole tree
  19290. _this._patchUIElement(_this, null);
  19291. // Screen Space UI
  19292. if (!settings.worldPosition && !settings.worldRotation) {
  19293. _this._sceneData = Window_1.getSceneData(scene);
  19294. _this._canvas = _this._sceneData.screenSpaceCanvas;
  19295. _this._isWorldSpaceCanvas = false;
  19296. _this._left = (settings.left != null) ? settings.left : 0;
  19297. _this._bottom = (settings.bottom != null) ? settings.bottom : 0;
  19298. }
  19299. else {
  19300. var w = (settings.width == null) ? 100 : settings.width;
  19301. var h = (settings.height == null) ? 100 : settings.height;
  19302. var wpos = (settings.worldPosition == null) ? BABYLON.Vector3.Zero() : settings.worldPosition;
  19303. var wrot = (settings.worldRotation == null) ? BABYLON.Quaternion.Identity() : settings.worldRotation;
  19304. _this._canvas = new BABYLON.WorldSpaceCanvas2D(scene, new BABYLON.Size(w, h), { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE, worldPosition: wpos, worldRotation: wrot });
  19305. _this._isWorldSpaceCanvas = true;
  19306. }
  19307. _this._renderObserver = _this._canvas.renderObservable.add(function (e, s) { return _this._canvasPreRender(); }, BABYLON.Canvas2D.RENDEROBSERVABLE_PRE);
  19308. _this._disposeObserver = _this._canvas.disposeObservable.add(function (e, s) { return _this._canvasDisposed(); });
  19309. _this._canvas.propertyChanged.add(function (e, s) {
  19310. if (e.propertyName === "overPrim") {
  19311. _this._overPrimChanged(e.oldValue, e.newValue);
  19312. }
  19313. });
  19314. _this._mouseOverUIElement = null;
  19315. return _this;
  19316. }
  19317. Object.defineProperty(Window.prototype, "canvas", {
  19318. get: function () {
  19319. return this._canvas;
  19320. },
  19321. enumerable: true,
  19322. configurable: true
  19323. });
  19324. Object.defineProperty(Window.prototype, "left", {
  19325. get: function () {
  19326. return this._left;
  19327. },
  19328. set: function (value) {
  19329. var old = new BABYLON.Vector2(this._left, this._bottom);
  19330. this._left = value;
  19331. this.onPropertyChanged("_position", old, this._position);
  19332. },
  19333. enumerable: true,
  19334. configurable: true
  19335. });
  19336. Object.defineProperty(Window.prototype, "bottom", {
  19337. get: function () {
  19338. return this._bottom;
  19339. },
  19340. set: function (value) {
  19341. var old = new BABYLON.Vector2(this._left, this._bottom);
  19342. this._bottom = value;
  19343. this.onPropertyChanged("_position", old, this._position);
  19344. },
  19345. enumerable: true,
  19346. configurable: true
  19347. });
  19348. Object.defineProperty(Window.prototype, "position", {
  19349. get: function () {
  19350. return this._position;
  19351. },
  19352. set: function (value) {
  19353. this._left = value.x;
  19354. this._bottom = value.y;
  19355. },
  19356. enumerable: true,
  19357. configurable: true
  19358. });
  19359. Object.defineProperty(Window.prototype, "isActive", {
  19360. get: function () {
  19361. return this._isActive;
  19362. },
  19363. set: function (value) {
  19364. this._isActive = value;
  19365. },
  19366. enumerable: true,
  19367. configurable: true
  19368. });
  19369. Object.defineProperty(Window.prototype, "focusManager", {
  19370. get: function () {
  19371. return this._sceneData.focusManager;
  19372. },
  19373. enumerable: true,
  19374. configurable: true
  19375. });
  19376. Object.defineProperty(Window.prototype, "_position", {
  19377. get: function () {
  19378. return new BABYLON.Vector2(this.left, this.bottom);
  19379. },
  19380. enumerable: true,
  19381. configurable: true
  19382. });
  19383. Window.prototype.createVisualTree = function () {
  19384. _super.prototype.createVisualTree.call(this);
  19385. var p = this._visualPlaceholder;
  19386. p.createSimpleDataBinding(BABYLON.Group2D.positionProperty, "position");
  19387. };
  19388. Window.prototype._registerVisualToBuild = function (uiel) {
  19389. if (uiel._isFlagSet(BABYLON.UIElement.flagVisualToBuild)) {
  19390. return;
  19391. }
  19392. if (!this._UIElementVisualToBuildList) {
  19393. this._UIElementVisualToBuildList = new Array();
  19394. }
  19395. this._UIElementVisualToBuildList.push(uiel);
  19396. uiel._setFlags(BABYLON.UIElement.flagVisualToBuild);
  19397. };
  19398. Window.prototype._overPrimChanged = function (oldPrim, newPrim) {
  19399. var curOverEl = this._mouseOverUIElement;
  19400. var newOverEl = null;
  19401. var curGroup = newPrim ? newPrim.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  19402. while (curGroup) {
  19403. var uiel = curGroup.getExternalData("_GUIOwnerElement_");
  19404. if (uiel) {
  19405. newOverEl = uiel;
  19406. break;
  19407. }
  19408. curGroup = curGroup.parent ? curGroup.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  19409. }
  19410. if (curOverEl === newOverEl) {
  19411. return;
  19412. }
  19413. if (curOverEl) {
  19414. curOverEl.isMouseOver = false;
  19415. }
  19416. if (newOverEl) {
  19417. newOverEl.isMouseOver = true;
  19418. }
  19419. this._mouseOverUIElement = newOverEl;
  19420. };
  19421. Window.prototype._canvasPreRender = function () {
  19422. // Check if we have visual to create
  19423. if (this._UIElementVisualToBuildList.length > 0) {
  19424. // Sort the UI Element to get the highest (so lowest hierarchy depth) in the hierarchy tree first
  19425. var sortedElementList = this._UIElementVisualToBuildList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  19426. for (var _i = 0, sortedElementList_1 = sortedElementList; _i < sortedElementList_1.length; _i++) {
  19427. var el = sortedElementList_1[_i];
  19428. el._createVisualTree();
  19429. }
  19430. this._UIElementVisualToBuildList.splice(0);
  19431. }
  19432. };
  19433. Window.prototype._canvasDisposed = function () {
  19434. this._canvas.disposeObservable.remove(this._disposeObserver);
  19435. this._canvas.renderObservable.remove(this._renderObserver);
  19436. };
  19437. Window.getSceneData = function (scene) {
  19438. return Window_1._sceneData.getOrAddWithFactory(scene.uid, function (k) { return new GUISceneData(scene); });
  19439. };
  19440. return Window;
  19441. }(BABYLON.ContentControl));
  19442. Window.WINDOW_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 4;
  19443. Window._sceneData = new BABYLON.StringDictionary();
  19444. __decorate([
  19445. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 0, function (pi) { return Window_1.leftProperty = pi; })
  19446. ], Window.prototype, "left", null);
  19447. __decorate([
  19448. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 1, function (pi) { return Window_1.bottomProperty = pi; })
  19449. ], Window.prototype, "bottom", null);
  19450. __decorate([
  19451. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 2, function (pi) { return Window_1.positionProperty = pi; })
  19452. ], Window.prototype, "position", null);
  19453. __decorate([
  19454. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3, function (pi) { return Window_1.isActiveProperty = pi; })
  19455. ], Window.prototype, "isActive", null);
  19456. Window = Window_1 = __decorate([
  19457. BABYLON.className("Window", "BABYLON")
  19458. ], Window);
  19459. BABYLON.Window = Window;
  19460. var DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = (function (_super) {
  19461. __extends(DefaultWindowRenderingTemplate, _super);
  19462. function DefaultWindowRenderingTemplate() {
  19463. return _super !== null && _super.apply(this, arguments) || this;
  19464. }
  19465. DefaultWindowRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19466. var r = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#808080FF" });
  19467. return { root: r, contentPlaceholder: r };
  19468. };
  19469. return DefaultWindowRenderingTemplate;
  19470. }(BABYLON.UIElementRenderingTemplateBase));
  19471. DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate_1 = __decorate([
  19472. BABYLON.registerWindowRenderingTemplate("BABYLON.Window", "Default", function () { return new DefaultWindowRenderingTemplate_1(); })
  19473. ], DefaultWindowRenderingTemplate);
  19474. BABYLON.DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate;
  19475. var Window_1, DefaultWindowRenderingTemplate_1;
  19476. })(BABYLON || (BABYLON = {}));
  19477. var __extends = (this && this.__extends) || function (d, b) {
  19478. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19479. function __() { this.constructor = d; }
  19480. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19481. };
  19482. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19483. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19484. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19485. 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;
  19486. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19487. };
  19488. var BABYLON;
  19489. (function (BABYLON) {
  19490. var Label = Label_1 = (function (_super) {
  19491. __extends(Label, _super);
  19492. function Label(settings) {
  19493. var _this = this;
  19494. if (!settings) {
  19495. settings = {};
  19496. }
  19497. _this = _super.call(this, settings) || this;
  19498. if (settings.text != null) {
  19499. _this.text = settings.text;
  19500. }
  19501. return _this;
  19502. }
  19503. Object.defineProperty(Label.prototype, "_position", {
  19504. get: function () {
  19505. return BABYLON.Vector2.Zero();
  19506. },
  19507. enumerable: true,
  19508. configurable: true
  19509. });
  19510. Label.prototype._getChildren = function () {
  19511. return Label_1._emptyArray;
  19512. };
  19513. Label.prototype.createVisualTree = function () {
  19514. _super.prototype.createVisualTree.call(this);
  19515. var p = this._visualChildrenPlaceholder;
  19516. };
  19517. Object.defineProperty(Label.prototype, "text", {
  19518. get: function () {
  19519. return this._text;
  19520. },
  19521. set: function (value) {
  19522. this._text = value;
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. return Label;
  19528. }(BABYLON.Control));
  19529. Label._emptyArray = new Array();
  19530. __decorate([
  19531. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return Label_1.textProperty = pi; })
  19532. ], Label.prototype, "text", null);
  19533. Label = Label_1 = __decorate([
  19534. BABYLON.className("Label", "BABYLON")
  19535. ], Label);
  19536. BABYLON.Label = Label;
  19537. var DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = (function (_super) {
  19538. __extends(DefaultLabelRenderingTemplate, _super);
  19539. function DefaultLabelRenderingTemplate() {
  19540. return _super !== null && _super.apply(this, arguments) || this;
  19541. }
  19542. DefaultLabelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19543. var r = new BABYLON.Text2D("", { parent: visualPlaceholder });
  19544. r.createSimpleDataBinding(BABYLON.Text2D.textProperty, "text");
  19545. r.dataSource = owner;
  19546. return { root: r, contentPlaceholder: r };
  19547. };
  19548. return DefaultLabelRenderingTemplate;
  19549. }(BABYLON.UIElementRenderingTemplateBase));
  19550. DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate_1 = __decorate([
  19551. BABYLON.registerWindowRenderingTemplate("BABYLON.Label", "Default", function () { return new DefaultLabelRenderingTemplate_1(); })
  19552. ], DefaultLabelRenderingTemplate);
  19553. BABYLON.DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate;
  19554. var Label_1, DefaultLabelRenderingTemplate_1;
  19555. })(BABYLON || (BABYLON = {}));
  19556. var __extends = (this && this.__extends) || function (d, b) {
  19557. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  19558. function __() { this.constructor = d; }
  19559. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  19560. };
  19561. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  19562. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  19563. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  19564. 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;
  19565. return c > 3 && r && Object.defineProperty(target, key, r), r;
  19566. };
  19567. var BABYLON;
  19568. (function (BABYLON) {
  19569. var Button = Button_1 = (function (_super) {
  19570. __extends(Button, _super);
  19571. function Button(settings) {
  19572. var _this = this;
  19573. if (!settings) {
  19574. settings = {};
  19575. }
  19576. _this = _super.call(this, settings) || this;
  19577. if (settings.paddingAlignment == null) {
  19578. _this.paddingAlignment.horizontal = BABYLON.PrimitiveAlignment.AlignCenter;
  19579. _this.paddingAlignment.vertical = BABYLON.PrimitiveAlignment.AlignCenter;
  19580. }
  19581. _this._normalStateBackground = new BABYLON.ObservableStringDictionary(false);
  19582. _this._normalStateBorder = new BABYLON.ObservableStringDictionary(false);
  19583. _this._defaultStateBackground = new BABYLON.ObservableStringDictionary(false);
  19584. _this._defaultStateBorder = new BABYLON.ObservableStringDictionary(false);
  19585. _this._normalStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#337AB7FF"));
  19586. _this._normalStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#7BA9D0FF"));
  19587. _this._normalStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#286090FF"));
  19588. _this._normalStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#1E496EFF"));
  19589. _this._normalStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E6DA4FF"));
  19590. _this._normalStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#77A0C4FF"));
  19591. _this._normalStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#204D74FF"));
  19592. _this._normalStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E5D9EFF"));
  19593. _this._defaultStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  19594. _this._defaultStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  19595. _this._defaultStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#E6E6E6FF"));
  19596. _this._defaultStateBackground.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#D4D4D4FF"));
  19597. _this._defaultStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#CCCCCCFF"));
  19598. _this._defaultStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#DEDEDEFF"));
  19599. _this._defaultStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#ADADADFF"));
  19600. _this._defaultStateBorder.add(Button_1.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#6C8EC5FF"));
  19601. return _this;
  19602. }
  19603. Object.defineProperty(Button, "pushedState", {
  19604. get: function () {
  19605. return Button_1._pushedState;
  19606. },
  19607. enumerable: true,
  19608. configurable: true
  19609. });
  19610. Object.defineProperty(Button.prototype, "isPushed", {
  19611. get: function () {
  19612. return this._isPushed;
  19613. },
  19614. set: function (value) {
  19615. this._isPushed = value;
  19616. },
  19617. enumerable: true,
  19618. configurable: true
  19619. });
  19620. Object.defineProperty(Button.prototype, "isDefault", {
  19621. get: function () {
  19622. return this._isDefault;
  19623. },
  19624. set: function (value) {
  19625. this._isDefault = value;
  19626. },
  19627. enumerable: true,
  19628. configurable: true
  19629. });
  19630. Object.defineProperty(Button.prototype, "isOutline", {
  19631. get: function () {
  19632. return this._isOutline;
  19633. },
  19634. set: function (value) {
  19635. this._isOutline = value;
  19636. },
  19637. enumerable: true,
  19638. configurable: true
  19639. });
  19640. Object.defineProperty(Button.prototype, "clickObservable", {
  19641. get: function () {
  19642. if (!this._clickObservable) {
  19643. this._clickObservable = new BABYLON.Observable();
  19644. }
  19645. return this._clickObservable;
  19646. },
  19647. enumerable: true,
  19648. configurable: true
  19649. });
  19650. Button.prototype._raiseClick = function () {
  19651. if (this._clickObservable && this._clickObservable.hasObservers()) {
  19652. this._clickObservable.notifyObservers(this);
  19653. }
  19654. };
  19655. Button.prototype.createVisualTree = function () {
  19656. var _this = this;
  19657. _super.prototype.createVisualTree.call(this);
  19658. var p = this._visualPlaceholder;
  19659. p.pointerEventObservable.add(function (e, s) {
  19660. // check if input must be discarded
  19661. if (!_this.isVisible || !_this.isEnabled) {
  19662. return;
  19663. }
  19664. // We reject an event coming from the placeholder because it means it's on an empty spot, so it's not valid.
  19665. if (e.relatedTarget === _this._visualPlaceholder) {
  19666. return;
  19667. }
  19668. if (s.mask === BABYLON.PrimitivePointerInfo.PointerUp) {
  19669. _this._raiseClick();
  19670. _this.isPushed = false;
  19671. }
  19672. else if (s.mask === BABYLON.PrimitivePointerInfo.PointerDown) {
  19673. _this.isPushed = true;
  19674. _this.isFocused = true;
  19675. }
  19676. }, BABYLON.PrimitivePointerInfo.PointerUp | BABYLON.PrimitivePointerInfo.PointerDown);
  19677. };
  19678. Object.defineProperty(Button.prototype, "normalStateBackground", {
  19679. get: function () {
  19680. return this._normalStateBackground;
  19681. },
  19682. enumerable: true,
  19683. configurable: true
  19684. });
  19685. Object.defineProperty(Button.prototype, "defaultStateBackground", {
  19686. get: function () {
  19687. return this._defaultStateBackground;
  19688. },
  19689. enumerable: true,
  19690. configurable: true
  19691. });
  19692. Object.defineProperty(Button.prototype, "normalStateBorder", {
  19693. get: function () {
  19694. return this._normalStateBorder;
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(Button.prototype, "defaultStateBorder", {
  19700. get: function () {
  19701. return this._defaultStateBorder;
  19702. },
  19703. enumerable: true,
  19704. configurable: true
  19705. });
  19706. return Button;
  19707. }(BABYLON.ContentControl));
  19708. Button.BUTTON_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3;
  19709. Button._pushedState = "Pushed";
  19710. __decorate([
  19711. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 0, function (pi) { return Button_1.isPushedProperty = pi; })
  19712. ], Button.prototype, "isPushed", null);
  19713. __decorate([
  19714. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 1, function (pi) { return Button_1.isDefaultProperty = pi; })
  19715. ], Button.prototype, "isDefault", null);
  19716. __decorate([
  19717. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 2, function (pi) { return Button_1.isOutlineProperty = pi; })
  19718. ], Button.prototype, "isOutline", null);
  19719. Button = Button_1 = __decorate([
  19720. BABYLON.className("Button", "BABYLON")
  19721. ], Button);
  19722. BABYLON.Button = Button;
  19723. var DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = (function (_super) {
  19724. __extends(DefaultButtonRenderingTemplate, _super);
  19725. function DefaultButtonRenderingTemplate() {
  19726. return _super !== null && _super.apply(this, arguments) || this;
  19727. }
  19728. DefaultButtonRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  19729. this._rect = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#FF8080FF", border: "#FF8080FF", roundRadius: 10, borderThickness: 2 });
  19730. this.stateChange();
  19731. return { root: this._rect, contentPlaceholder: this._rect };
  19732. };
  19733. DefaultButtonRenderingTemplate.prototype.attach = function (owner) {
  19734. var _this = this;
  19735. _super.prototype.attach.call(this, owner);
  19736. this.owner.propertyChanged.add(function (e, s) { return _this.stateChange(); }, BABYLON.UIElement.isEnabledProperty.flagId |
  19737. BABYLON.UIElement.isFocusedProperty.flagId |
  19738. BABYLON.UIElement.isMouseOverProperty.flagId |
  19739. Button.isDefaultProperty.flagId |
  19740. Button.isOutlineProperty.flagId |
  19741. Button.isPushedProperty.flagId);
  19742. // Register for brush change and update the Visual
  19743. var button = owner;
  19744. button.normalStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  19745. button.normalStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  19746. button.defaultStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  19747. button.defaultStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  19748. };
  19749. DefaultButtonRenderingTemplate.prototype.stateChange = function () {
  19750. //console.log("state changed");
  19751. var b = this.owner;
  19752. var state = BABYLON.UIElement.enabledState;
  19753. var bg = b.isDefault ? b.defaultStateBackground.get(state) : b.normalStateBackground.get(state);
  19754. var bd = b.isDefault ? b.defaultStateBorder.get(state) : b.normalStateBorder.get(state);
  19755. if (b.isPushed) {
  19756. state = Button.pushedState;
  19757. if (b.isDefault) {
  19758. bg = b.defaultStateBackground.get(state);
  19759. bd = b.defaultStateBorder.get(state);
  19760. }
  19761. else {
  19762. bg = b.normalStateBackground.get(state);
  19763. bd = b.normalStateBorder.get(state);
  19764. }
  19765. }
  19766. else if (b.isMouseOver) {
  19767. state = BABYLON.UIElement.mouseOverState;
  19768. if (b.isDefault) {
  19769. bg = b.defaultStateBackground.get(state);
  19770. bd = b.defaultStateBorder.get(state);
  19771. }
  19772. else {
  19773. bg = b.normalStateBackground.get(state);
  19774. bd = b.normalStateBorder.get(state);
  19775. }
  19776. }
  19777. else if (!b.isEnabled) {
  19778. state = BABYLON.UIElement.disabledState;
  19779. if (b.isDefault) {
  19780. bg = b.defaultStateBackground.get(state);
  19781. bd = b.defaultStateBorder.get(state);
  19782. }
  19783. else {
  19784. bg = b.normalStateBackground.get(state);
  19785. bd = b.normalStateBorder.get(state);
  19786. }
  19787. }
  19788. this._rect.fill = bg;
  19789. this._rect.border = bd;
  19790. };
  19791. return DefaultButtonRenderingTemplate;
  19792. }(BABYLON.UIElementRenderingTemplateBase));
  19793. DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate_1 = __decorate([
  19794. BABYLON.registerWindowRenderingTemplate("BABYLON.Button", "Default", function () { return new DefaultButtonRenderingTemplate_1(); })
  19795. ], DefaultButtonRenderingTemplate);
  19796. BABYLON.DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate;
  19797. var Button_1, DefaultButtonRenderingTemplate_1;
  19798. })(BABYLON || (BABYLON = {}));