babylon.canvas2d.max.js 727 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. 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;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. if (typeof BABYLON === "undefined") {
  14. throw "BabylonJS is a required dependency, please include it first!"
  15. };
  16. var BABYLON;
  17. (function (BABYLON) {
  18. var PropertyChangedInfo = (function () {
  19. function PropertyChangedInfo() {
  20. }
  21. return PropertyChangedInfo;
  22. }());
  23. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  24. /**
  25. * The purpose of this class is to provide a base implementation of the IPropertyChanged interface for the user to avoid rewriting a code needlessly.
  26. * 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.
  27. * 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)
  28. */
  29. var PropertyChangedBase = (function () {
  30. function PropertyChangedBase() {
  31. this._propertyChanged = null;
  32. }
  33. /**
  34. * Protected method to call when there's a change of value in a property set
  35. * @param propName the name of the concerned property
  36. * @param oldValue its old value
  37. * @param newValue its new value
  38. * @param mask an optional observable mask
  39. */
  40. PropertyChangedBase.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  41. if (this.propertyChanged.hasObservers()) {
  42. var pci = PropertyChangedBase.calling ? new PropertyChangedInfo() : PropertyChangedBase.pci;
  43. pci.oldValue = oldValue;
  44. pci.newValue = newValue;
  45. pci.propertyName = propName;
  46. try {
  47. PropertyChangedBase.calling = true;
  48. this.propertyChanged.notifyObservers(pci, mask);
  49. }
  50. finally {
  51. PropertyChangedBase.calling = false;
  52. }
  53. }
  54. };
  55. Object.defineProperty(PropertyChangedBase.prototype, "propertyChanged", {
  56. /**
  57. * An observable that is triggered when a property (using of the XXXXLevelProperty decorator) has its value changing.
  58. * 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)
  59. */
  60. get: function () {
  61. if (!this._propertyChanged) {
  62. this._propertyChanged = new BABYLON.Observable();
  63. }
  64. return this._propertyChanged;
  65. },
  66. enumerable: true,
  67. configurable: true
  68. });
  69. PropertyChangedBase.pci = new PropertyChangedInfo();
  70. PropertyChangedBase.calling = false;
  71. return PropertyChangedBase;
  72. }());
  73. BABYLON.PropertyChangedBase = PropertyChangedBase;
  74. })(BABYLON || (BABYLON = {}));
  75. var BABYLON;
  76. (function (BABYLON) {
  77. /**
  78. * Class for the ObservableArray.onArrayChanged observable
  79. */
  80. var ArrayChanged = (function () {
  81. function ArrayChanged() {
  82. this.action = 0;
  83. this.newItems = new Array();
  84. this.removedItems = new Array();
  85. this.changedItems = new Array();
  86. this.newStartingIndex = -1;
  87. this.removedStartingIndex = -1;
  88. }
  89. Object.defineProperty(ArrayChanged, "clearAction", {
  90. /**
  91. * The content of the array was totally cleared
  92. */
  93. get: function () {
  94. return ArrayChanged._clearAction;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(ArrayChanged, "newItemsAction", {
  100. /**
  101. * A new item was added, the newItems field contains the key/value pairs
  102. */
  103. get: function () {
  104. return ArrayChanged._newItemsAction;
  105. },
  106. enumerable: true,
  107. configurable: true
  108. });
  109. Object.defineProperty(ArrayChanged, "removedItemsAction", {
  110. /**
  111. * An existing item was removed, the removedKey field contains its key
  112. */
  113. get: function () {
  114. return ArrayChanged._removedItemsAction;
  115. },
  116. enumerable: true,
  117. configurable: true
  118. });
  119. Object.defineProperty(ArrayChanged, "changedItemAction", {
  120. /**
  121. * One or many items in the array were changed, the
  122. */
  123. get: function () {
  124. return ArrayChanged._changedItemAction;
  125. },
  126. enumerable: true,
  127. configurable: true
  128. });
  129. Object.defineProperty(ArrayChanged, "replacedArrayAction", {
  130. /**
  131. * The array's content was totally changed
  132. * Depending on the method that used this mode the ChangedArray object may contains more information
  133. */
  134. get: function () {
  135. return ArrayChanged._replacedArrayAction;
  136. },
  137. enumerable: true,
  138. configurable: true
  139. });
  140. Object.defineProperty(ArrayChanged, "lengthChangedAction", {
  141. /**
  142. * The length of the array changed
  143. */
  144. get: function () {
  145. return ArrayChanged._lengthChangedAction;
  146. },
  147. enumerable: true,
  148. configurable: true
  149. });
  150. ArrayChanged.prototype.clear = function () {
  151. this.action = 0;
  152. this.newItems.splice(0);
  153. this.removedItems.splice(0);
  154. this.changedItems.splice(0);
  155. this.removedStartingIndex = this.removedStartingIndex = this.changedStartingIndex = 0;
  156. };
  157. ArrayChanged._clearAction = 0x1;
  158. ArrayChanged._newItemsAction = 0x2;
  159. ArrayChanged._removedItemsAction = 0x4;
  160. ArrayChanged._replacedArrayAction = 0x8;
  161. ArrayChanged._lengthChangedAction = 0x10;
  162. ArrayChanged._changedItemAction = 0x20;
  163. return ArrayChanged;
  164. }());
  165. BABYLON.ArrayChanged = ArrayChanged;
  166. var OAWatchedObjectChangedInfo = (function () {
  167. function OAWatchedObjectChangedInfo() {
  168. }
  169. return OAWatchedObjectChangedInfo;
  170. }());
  171. BABYLON.OAWatchedObjectChangedInfo = OAWatchedObjectChangedInfo;
  172. /**
  173. * This class mimics the Javascript Array and TypeScript Array<T> classes, adding new features concerning the Observable pattern.
  174. *
  175. */
  176. var ObservableArray = (function (_super) {
  177. __extends(ObservableArray, _super);
  178. /**
  179. * Create an Observable Array.
  180. * @param watchObjectsPropertyChange
  181. * @param array and optional array that will be encapsulated by this ObservableArray instance. That's right, it's NOT a copy!
  182. */
  183. function ObservableArray(watchObjectsPropertyChange, array) {
  184. _super.call(this);
  185. this.dci = new ArrayChanged();
  186. this._callingArrayChanged = false;
  187. this._array = (array != null) ? array : new Array();
  188. this.dci = new ArrayChanged();
  189. this._callingArrayChanged = false;
  190. this._arrayChanged = null;
  191. this._callingWatchedObjectChanged = false;
  192. this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  193. this._watchedObjectList = this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  194. this._woci = new OAWatchedObjectChangedInfo();
  195. }
  196. Object.defineProperty(ObservableArray.prototype, "length", {
  197. /**
  198. * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array.
  199. */
  200. get: function () {
  201. return this._array.length;
  202. },
  203. set: function (value) {
  204. if (value === this._array.length) {
  205. return;
  206. }
  207. var oldLength = this._array.length;
  208. this._array.length = value;
  209. this.onPropertyChanged("length", oldLength, this._array.length);
  210. },
  211. enumerable: true,
  212. configurable: true
  213. });
  214. ObservableArray.prototype.getAt = function (index) {
  215. return this._array[index];
  216. };
  217. ObservableArray.prototype.setAt = function (index, value) {
  218. if (index < 0) {
  219. return false;
  220. }
  221. var insertion = (index >= this._array.length) || this._array[index] === undefined;
  222. var oldLength = 0;
  223. if (insertion) {
  224. oldLength = this._array.length;
  225. }
  226. else if (this._watchObjectsPropertyChange) {
  227. this._removeWatchedElement(this._array[index]);
  228. }
  229. this._array[index] = value;
  230. if (this._watchObjectsPropertyChange) {
  231. this._addWatchedElement(value);
  232. }
  233. if (insertion) {
  234. this.onPropertyChanged("length", oldLength, this._array.length);
  235. }
  236. var ac = this.getArrayChangedObject();
  237. if (ac) {
  238. ac.action = insertion ? ArrayChanged.newItemsAction : ArrayChanged.changedItemAction;
  239. if (insertion) {
  240. ac.newItems.splice(0, ac.newItems.length, { index: index, value: value });
  241. ac.newStartingIndex = index;
  242. ac.changedItems.splice(0);
  243. }
  244. else {
  245. ac.newItems.splice(0);
  246. ac.changedStartingIndex = index;
  247. ac.changedItems.splice(0, ac.changedItems.length, { index: index, value: value });
  248. }
  249. ac.removedItems.splice(0);
  250. ac.removedStartingIndex = -1;
  251. this.callArrayChanged(ac);
  252. }
  253. };
  254. /**
  255. * Returns a string representation of an array.
  256. */
  257. ObservableArray.prototype.toString = function () {
  258. return this._array.toString();
  259. };
  260. ObservableArray.prototype.toLocaleString = function () {
  261. return this._array.toLocaleString();
  262. };
  263. /**
  264. * Appends new elements to an array, and returns the new length of the array.
  265. * @param items New elements of the Array.
  266. */
  267. ObservableArray.prototype.push = function () {
  268. var items = [];
  269. for (var _i = 0; _i < arguments.length; _i++) {
  270. items[_i - 0] = arguments[_i];
  271. }
  272. var oldLength = this._array.length;
  273. var n = (_a = this._array).push.apply(_a, items);
  274. if (this._watchObjectsPropertyChange) {
  275. this._addWatchedElement.apply(this, items);
  276. }
  277. this.onPropertyChanged("length", oldLength, this._array.length);
  278. var ac = this.getArrayChangedObject();
  279. if (ac) {
  280. ac.action = ArrayChanged.newItemsAction;
  281. ac.newStartingIndex = oldLength;
  282. this.feedNotifArray.apply(this, [ac.newItems, oldLength].concat(items));
  283. this.callArrayChanged(ac);
  284. }
  285. return n;
  286. var _a;
  287. };
  288. /**
  289. * Removes the last element from an array and returns it.
  290. */
  291. ObservableArray.prototype.pop = function () {
  292. var firstRemove = this._array.length - 1;
  293. var res = this._array.pop();
  294. if (res && this._watchObjectsPropertyChange) {
  295. this._removeWatchedElement(res);
  296. }
  297. if (firstRemove !== -1) {
  298. this.onPropertyChanged("length", this._array.length + 1, this._array.length);
  299. var ac = this.getArrayChangedObject();
  300. if (ac) {
  301. ac.action = ArrayChanged.removedItemsAction;
  302. ac.removedStartingIndex = firstRemove;
  303. this.feedNotifArray(ac.removedItems, firstRemove, res);
  304. }
  305. }
  306. return res;
  307. };
  308. /**
  309. * Combines two or more arrays.
  310. * @param items Additional items to add to the end of array1.
  311. */
  312. ObservableArray.prototype.concat = function () {
  313. var items = [];
  314. for (var _i = 0; _i < arguments.length; _i++) {
  315. items[_i - 0] = arguments[_i];
  316. }
  317. return new ObservableArray(this._watchObjectsPropertyChange, (_a = this._array).concat.apply(_a, items));
  318. var _a;
  319. };
  320. /**
  321. * Adds all the elements of an array separated by the specified separator string.
  322. * @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.
  323. */
  324. ObservableArray.prototype.join = function (separator) {
  325. return this._array.join(separator);
  326. };
  327. /**
  328. * Reverses the elements in an Array.
  329. * The arrayChanged action is
  330. */
  331. ObservableArray.prototype.reverse = function () {
  332. var res = this._array.reverse();
  333. var ac = this.getArrayChangedObject();
  334. ac.action = ArrayChanged.replacedArrayAction;
  335. return res;
  336. };
  337. /**
  338. * Removes the first element from an array and returns it, shift all subsequents element one element before.
  339. * The ArrayChange action is replacedArrayAction, the whole array changes and must be reevaluate as such, the removed element is in removedItems.
  340. *
  341. */
  342. ObservableArray.prototype.shift = function () {
  343. var oldLength = this._array.length;
  344. var res = this._array.shift();
  345. if (this._watchedObjectChanged && res != null) {
  346. this._removeWatchedElement(res);
  347. }
  348. if (oldLength !== 0) {
  349. this.onPropertyChanged("length", oldLength, this._array.length);
  350. var ac = this.getArrayChangedObject();
  351. if (ac) {
  352. ac.action = ArrayChanged.replacedArrayAction;
  353. ac.removedItems.splice(0, ac.removedItems.length, { index: 0, value: res });
  354. ac.newItems.splice(0);
  355. ac.changedItems.splice(0);
  356. ac.removedStartingIndex = 0;
  357. this.callArrayChanged(ac);
  358. }
  359. }
  360. return res;
  361. };
  362. /**
  363. * Returns a section of an array.
  364. * @param start The beginning of the specified portion of the array.
  365. * @param end The end of the specified portion of the array.
  366. */
  367. ObservableArray.prototype.slice = function (start, end) {
  368. return new ObservableArray(this._watchObjectsPropertyChange, this._array.slice(start, end));
  369. };
  370. /**
  371. * Sorts an array.
  372. * @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.
  373. * On the contrary of the Javascript Array's implementation, this method returns nothing
  374. */
  375. ObservableArray.prototype.sort = function (compareFn) {
  376. var oldLength = this._array.length;
  377. this._array.sort(compareFn);
  378. if (oldLength !== 0) {
  379. var ac = this.getArrayChangedObject();
  380. if (ac) {
  381. ac.clear();
  382. ac.action = ArrayChanged.replacedArrayAction;
  383. this.callArrayChanged(ac);
  384. }
  385. }
  386. };
  387. /**
  388. * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
  389. * @param start The zero-based location in the array from which to start removing elements.
  390. * @param deleteCount The number of elements to remove.
  391. * @param items Elements to insert into the array in place of the deleted elements.
  392. */
  393. ObservableArray.prototype.splice = function (start, deleteCount) {
  394. var items = [];
  395. for (var _i = 2; _i < arguments.length; _i++) {
  396. items[_i - 2] = arguments[_i];
  397. }
  398. var oldLength = this._array.length;
  399. if (this._watchObjectsPropertyChange) {
  400. for (var i = start; i < start + deleteCount; i++) {
  401. var val = this._array[i];
  402. if (this._watchObjectsPropertyChange && val != null) {
  403. this._removeWatchedElement(val);
  404. }
  405. }
  406. }
  407. var res = (_a = this._array).splice.apply(_a, [start, deleteCount].concat(items));
  408. if (this._watchObjectsPropertyChange) {
  409. this._addWatchedElement.apply(this, items);
  410. }
  411. if (oldLength !== this._array.length) {
  412. this.onPropertyChanged("length", oldLength, this._array.length);
  413. }
  414. var ac = this.getArrayChangedObject();
  415. if (ac) {
  416. ac.clear();
  417. ac.action = ArrayChanged.replacedArrayAction;
  418. this.callArrayChanged(ac);
  419. }
  420. return res;
  421. var _a;
  422. };
  423. /**
  424. * Inserts new elements at the start of an array.
  425. * @param items Elements to insert at the start of the Array.
  426. * The ChangedArray action is replacedArrayAction, newItems contains the list of the added items
  427. */
  428. ObservableArray.prototype.unshift = function () {
  429. var items = [];
  430. for (var _i = 0; _i < arguments.length; _i++) {
  431. items[_i - 0] = arguments[_i];
  432. }
  433. var oldLength = this._array.length;
  434. var res = (_a = this._array).unshift.apply(_a, items);
  435. if (this._watchObjectsPropertyChange) {
  436. this._addWatchedElement.apply(this, items);
  437. }
  438. this.onPropertyChanged("length", oldLength, this._array.length);
  439. var ac = this.getArrayChangedObject();
  440. if (ac) {
  441. ac.clear();
  442. ac.action = ArrayChanged.replacedArrayAction;
  443. ac.newStartingIndex = 0,
  444. this.feedNotifArray.apply(this, [ac.newItems, 0].concat(items));
  445. this.callArrayChanged(ac);
  446. }
  447. return res;
  448. var _a;
  449. };
  450. /**
  451. * Returns the index of the first occurrence of a value in an array.
  452. * @param searchElement The value to locate in the array.
  453. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0.
  454. */
  455. ObservableArray.prototype.indexOf = function (searchElement, fromIndex) {
  456. return this._array.indexOf(searchElement, fromIndex);
  457. };
  458. /**
  459. * Returns the index of the last occurrence of a specified value in an array.
  460. * @param searchElement The value to locate in the array.
  461. * @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.
  462. */
  463. ObservableArray.prototype.lastIndexOf = function (searchElement, fromIndex) {
  464. return this._array.lastIndexOf(searchElement, fromIndex);
  465. };
  466. /**
  467. * Determines whether all the members of an array satisfy the specified test.
  468. * @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.
  469. * @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.
  470. */
  471. ObservableArray.prototype.every = function (callbackfn, thisArg) {
  472. return this._array.every(callbackfn, thisArg);
  473. };
  474. /**
  475. * Determines whether the specified callback function returns true for any element of an array.
  476. * @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.
  477. * @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.
  478. */
  479. ObservableArray.prototype.some = function (callbackfn, thisArg) {
  480. return this._array.some(callbackfn, thisArg);
  481. };
  482. /**
  483. * Performs the specified action for each element in an array.
  484. * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array.
  485. * @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.
  486. */
  487. ObservableArray.prototype.forEach = function (callbackfn, thisArg) {
  488. return this._array.forEach(callbackfn, thisArg);
  489. };
  490. /**
  491. * Calls a defined callback function on each element of an array, and returns an array that contains the results.
  492. * @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.
  493. * @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.
  494. */
  495. ObservableArray.prototype.map = function (callbackfn, thisArg) {
  496. return this._array.map(callbackfn, thisArg);
  497. };
  498. /**
  499. * Returns the elements of an array that meet the condition specified in a callback function.
  500. * @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.
  501. * @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.
  502. */
  503. ObservableArray.prototype.filter = function (callbackfn, thisArg) {
  504. return this._array.filter(callbackfn, thisArg);
  505. };
  506. /**
  507. * 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.
  508. * @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.
  509. * @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.
  510. */
  511. ObservableArray.prototype.reduce = function (callbackfn, initialValue) {
  512. return this._array.reduce(callbackfn);
  513. };
  514. /**
  515. * 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.
  516. * @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.
  517. * @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.
  518. */
  519. ObservableArray.prototype.reduceRight = function (callbackfn, initialValue) {
  520. return this._array.reduceRight(callbackfn);
  521. };
  522. Object.defineProperty(ObservableArray.prototype, "arrayChanged", {
  523. get: function () {
  524. if (!this._arrayChanged) {
  525. this._arrayChanged = new BABYLON.Observable();
  526. }
  527. return this._arrayChanged;
  528. },
  529. enumerable: true,
  530. configurable: true
  531. });
  532. ObservableArray.prototype.getArrayChangedObject = function () {
  533. if (this._arrayChanged && this._arrayChanged.hasObservers()) {
  534. var ac = this._callingArrayChanged ? new ArrayChanged() : this.dci;
  535. return ac;
  536. }
  537. return null;
  538. };
  539. ObservableArray.prototype.feedNotifArray = function (array, startindIndex) {
  540. var items = [];
  541. for (var _i = 2; _i < arguments.length; _i++) {
  542. items[_i - 2] = arguments[_i];
  543. }
  544. array.splice(0);
  545. for (var i = 0; i < items.length; i++) {
  546. var value = this._array[i + startindIndex];
  547. if (value !== undefined) {
  548. array.push({ index: i + startindIndex, value: value });
  549. }
  550. }
  551. };
  552. ObservableArray.prototype.callArrayChanged = function (ac) {
  553. try {
  554. this._callingArrayChanged = true;
  555. this.arrayChanged.notifyObservers(ac, ac.action);
  556. }
  557. finally {
  558. this._callingArrayChanged = false;
  559. }
  560. };
  561. Object.defineProperty(ObservableArray.prototype, "watchedObjectChanged", {
  562. get: function () {
  563. if (!this._watchedObjectChanged) {
  564. this._watchedObjectChanged = new BABYLON.Observable();
  565. }
  566. return this._watchedObjectChanged;
  567. },
  568. enumerable: true,
  569. configurable: true
  570. });
  571. ObservableArray.prototype._addWatchedElement = function () {
  572. var _this = this;
  573. var items = [];
  574. for (var _i = 0; _i < arguments.length; _i++) {
  575. items[_i - 0] = arguments[_i];
  576. }
  577. var _loop_1 = function(curItem) {
  578. if (curItem["propertyChanged"]) {
  579. var key_1 = curItem["__ObsArrayObjID__"];
  580. // The object may already be part of another ObsArray, so there already be a valid ID
  581. if (!key_1) {
  582. key_1 = BABYLON.Tools.RandomId();
  583. curItem["__ObsArrayObjID__"] = key_1;
  584. }
  585. this_1._watchedObjectList.add(key_1, curItem.propertyChanged.add(function (e, d) {
  586. _this.onWatchedObjectChanged(key_1, curItem, e);
  587. }));
  588. }
  589. };
  590. var this_1 = this;
  591. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  592. var curItem = items_1[_a];
  593. _loop_1(curItem);
  594. }
  595. };
  596. ObservableArray.prototype._removeWatchedElement = function () {
  597. var items = [];
  598. for (var _i = 0; _i < arguments.length; _i++) {
  599. items[_i - 0] = arguments[_i];
  600. }
  601. for (var _a = 0, items_2 = items; _a < items_2.length; _a++) {
  602. var curItem = items_2[_a];
  603. var key = curItem["__ObsArrayObjID__"];
  604. if (key != null) {
  605. var observer = this._watchedObjectList.getAndRemove(key);
  606. curItem.propertyChanged.remove(observer);
  607. }
  608. }
  609. };
  610. ObservableArray.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  611. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  612. var woci = this._callingWatchedObjectChanged ? new OAWatchedObjectChangedInfo() : this._woci;
  613. woci.object = object;
  614. woci.propertyChanged = propChanged;
  615. try {
  616. this._callingWatchedObjectChanged = true;
  617. this.watchedObjectChanged.notifyObservers(woci);
  618. }
  619. finally {
  620. this._callingWatchedObjectChanged = false;
  621. }
  622. }
  623. };
  624. return ObservableArray;
  625. }(BABYLON.PropertyChangedBase));
  626. BABYLON.ObservableArray = ObservableArray;
  627. })(BABYLON || (BABYLON = {}));
  628. var BABYLON;
  629. (function (BABYLON) {
  630. /**
  631. * Class for the ObservableStringDictionary.onDictionaryChanged observable
  632. */
  633. var DictionaryChanged = (function () {
  634. function DictionaryChanged() {
  635. }
  636. Object.defineProperty(DictionaryChanged, "clearAction", {
  637. /**
  638. * The content of the dictionary was totally cleared
  639. */
  640. get: function () {
  641. return DictionaryChanged._clearAction;
  642. },
  643. enumerable: true,
  644. configurable: true
  645. });
  646. Object.defineProperty(DictionaryChanged, "newItemAction", {
  647. /**
  648. * A new item was added, the newItem field contains the key/value pair
  649. */
  650. get: function () {
  651. return DictionaryChanged._newItemAction;
  652. },
  653. enumerable: true,
  654. configurable: true
  655. });
  656. Object.defineProperty(DictionaryChanged, "removedItemAction", {
  657. /**
  658. * An existing item was removed, the removedKey field contains its key
  659. */
  660. get: function () {
  661. return DictionaryChanged._removedItemAction;
  662. },
  663. enumerable: true,
  664. configurable: true
  665. });
  666. Object.defineProperty(DictionaryChanged, "itemValueChangedAction", {
  667. /**
  668. * An existing item had a value change, the changedItem field contains the key/value
  669. */
  670. get: function () {
  671. return DictionaryChanged._itemValueChangedAction;
  672. },
  673. enumerable: true,
  674. configurable: true
  675. });
  676. Object.defineProperty(DictionaryChanged, "replacedAction", {
  677. /**
  678. * The dictionary's content was reset and replaced by the content of another dictionary.
  679. * DictionaryChanged<T> contains no further information about this action
  680. */
  681. get: function () {
  682. return DictionaryChanged._replacedAction;
  683. },
  684. enumerable: true,
  685. configurable: true
  686. });
  687. DictionaryChanged._clearAction = 0x1;
  688. DictionaryChanged._newItemAction = 0x2;
  689. DictionaryChanged._removedItemAction = 0x4;
  690. DictionaryChanged._itemValueChangedAction = 0x8;
  691. DictionaryChanged._replacedAction = 0x10;
  692. return DictionaryChanged;
  693. }());
  694. BABYLON.DictionaryChanged = DictionaryChanged;
  695. var OSDWatchedObjectChangedInfo = (function () {
  696. function OSDWatchedObjectChangedInfo() {
  697. }
  698. return OSDWatchedObjectChangedInfo;
  699. }());
  700. BABYLON.OSDWatchedObjectChangedInfo = OSDWatchedObjectChangedInfo;
  701. var ObservableStringDictionary = (function (_super) {
  702. __extends(ObservableStringDictionary, _super);
  703. function ObservableStringDictionary(watchObjectsPropertyChange) {
  704. _super.call(this);
  705. this._propertyChanged = null;
  706. this._dictionaryChanged = null;
  707. this.dci = new DictionaryChanged();
  708. this._callingDicChanged = false;
  709. this._watchedObjectChanged = null;
  710. this._callingWatchedObjectChanged = false;
  711. this._woci = new OSDWatchedObjectChangedInfo();
  712. this._watchObjectsPropertyChange = watchObjectsPropertyChange;
  713. this._watchedObjectList = this._watchObjectsPropertyChange ? new BABYLON.StringDictionary() : null;
  714. }
  715. /**
  716. * This will clear this dictionary and copy the content from the 'source' one.
  717. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  718. * @param source the dictionary to take the content from and copy to this dictionary
  719. */
  720. ObservableStringDictionary.prototype.copyFrom = function (source) {
  721. var _this = this;
  722. var oldCount = this.count;
  723. // Don't rely on this class' implementation for clear/add otherwise tons of notification will be thrown
  724. _super.prototype.clear.call(this);
  725. source.forEach(function (t, v) { return _this._add(t, v, false, _this._watchObjectsPropertyChange); });
  726. this.onDictionaryChanged(DictionaryChanged.replacedAction, null, null, null);
  727. this.onPropertyChanged("count", oldCount, this.count);
  728. };
  729. /**
  730. * Get a value from its key or add it if it doesn't exist.
  731. * This method will ensure you that a given key/data will be present in the dictionary.
  732. * @param key the given key to get the matching value from
  733. * @param factory the factory that will create the value if the key is not present in the dictionary.
  734. * The factory will only be invoked if there's no data for the given key.
  735. * @return the value corresponding to the key.
  736. */
  737. ObservableStringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  738. var _this = this;
  739. var val = _super.prototype.getOrAddWithFactory.call(this, key, function (k) {
  740. var v = factory(key);
  741. _this._add(key, v, true, _this._watchObjectsPropertyChange);
  742. return v;
  743. });
  744. return val;
  745. };
  746. /**
  747. * Add a new key and its corresponding value
  748. * @param key the key to add
  749. * @param value the value corresponding to the key
  750. * @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
  751. */
  752. ObservableStringDictionary.prototype.add = function (key, value) {
  753. return this._add(key, value, true, true);
  754. };
  755. ObservableStringDictionary.prototype.getAndRemove = function (key) {
  756. var val = _super.prototype.get.call(this, key);
  757. this._remove(key, true, val);
  758. return val;
  759. };
  760. ObservableStringDictionary.prototype._add = function (key, value, fireNotif, registerWatcher) {
  761. if (_super.prototype.add.call(this, key, value)) {
  762. if (fireNotif) {
  763. this.onDictionaryChanged(DictionaryChanged.newItemAction, { key: key, value: value }, null, null);
  764. this.onPropertyChanged("count", this.count - 1, this.count);
  765. }
  766. if (registerWatcher) {
  767. this._addWatchedElement(key, value);
  768. }
  769. return true;
  770. }
  771. return false;
  772. };
  773. ObservableStringDictionary.prototype._addWatchedElement = function (key, el) {
  774. var _this = this;
  775. if (el["propertyChanged"]) {
  776. this._watchedObjectList.add(key, el.propertyChanged.add(function (e, d) {
  777. _this.onWatchedObjectChanged(key, el, e);
  778. }));
  779. }
  780. };
  781. ObservableStringDictionary.prototype._removeWatchedElement = function (key, el) {
  782. var observer = this._watchedObjectList.getAndRemove(key);
  783. if (el["propertyChanged"]) {
  784. el.propertyChanged.remove(observer);
  785. }
  786. };
  787. ObservableStringDictionary.prototype.set = function (key, value) {
  788. var oldValue = this.get(key);
  789. if (this._watchObjectsPropertyChange) {
  790. this._removeWatchedElement(key, oldValue);
  791. }
  792. if (_super.prototype.set.call(this, key, value)) {
  793. this.onDictionaryChanged(DictionaryChanged.itemValueChangedAction, null, null, { key: key, oldValue: oldValue, newValue: value });
  794. this._addWatchedElement(key, value);
  795. return true;
  796. }
  797. return false;
  798. };
  799. /**
  800. * Remove a key/value from the dictionary.
  801. * @param key the key to remove
  802. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  803. */
  804. ObservableStringDictionary.prototype.remove = function (key) {
  805. return this._remove(key, true);
  806. };
  807. ObservableStringDictionary.prototype._remove = function (key, fireNotif, element) {
  808. if (!element) {
  809. element = this.get(key);
  810. }
  811. if (!element) {
  812. return false;
  813. }
  814. if (_super.prototype.remove.call(this, key) === undefined) {
  815. return false;
  816. }
  817. this.onDictionaryChanged(DictionaryChanged.removedItemAction, null, key, null);
  818. this.onPropertyChanged("count", this.count + 1, this.count);
  819. if (this._watchObjectsPropertyChange) {
  820. this._removeWatchedElement(key, element);
  821. }
  822. return true;
  823. };
  824. /**
  825. * Clear the whole content of the dictionary
  826. */
  827. ObservableStringDictionary.prototype.clear = function () {
  828. var _this = this;
  829. this._watchedObjectList.forEach(function (k, v) {
  830. var el = _this.get(k);
  831. _this._removeWatchedElement(k, el);
  832. });
  833. this._watchedObjectList.clear();
  834. var oldCount = this.count;
  835. _super.prototype.clear.call(this);
  836. this.onDictionaryChanged(DictionaryChanged.clearAction, null, null, null);
  837. this.onPropertyChanged("count", oldCount, 0);
  838. };
  839. Object.defineProperty(ObservableStringDictionary.prototype, "propertyChanged", {
  840. get: function () {
  841. if (!this._propertyChanged) {
  842. this._propertyChanged = new BABYLON.Observable();
  843. }
  844. return this._propertyChanged;
  845. },
  846. enumerable: true,
  847. configurable: true
  848. });
  849. ObservableStringDictionary.prototype.onPropertyChanged = function (propName, oldValue, newValue, mask) {
  850. if (this._propertyChanged && this._propertyChanged.hasObservers()) {
  851. var pci = ObservableStringDictionary.callingPropChanged ? new BABYLON.PropertyChangedInfo() : ObservableStringDictionary.pci;
  852. pci.oldValue = oldValue;
  853. pci.newValue = newValue;
  854. pci.propertyName = propName;
  855. try {
  856. ObservableStringDictionary.callingPropChanged = true;
  857. this.propertyChanged.notifyObservers(pci, mask);
  858. }
  859. finally {
  860. ObservableStringDictionary.callingPropChanged = false;
  861. }
  862. }
  863. };
  864. Object.defineProperty(ObservableStringDictionary.prototype, "dictionaryChanged", {
  865. get: function () {
  866. if (!this._dictionaryChanged) {
  867. this._dictionaryChanged = new BABYLON.Observable();
  868. }
  869. return this._dictionaryChanged;
  870. },
  871. enumerable: true,
  872. configurable: true
  873. });
  874. ObservableStringDictionary.prototype.onDictionaryChanged = function (action, newItem, removedKey, changedItem) {
  875. if (this._dictionaryChanged && this._dictionaryChanged.hasObservers()) {
  876. var dci = this._callingDicChanged ? new DictionaryChanged() : this.dci;
  877. dci.action = action;
  878. dci.newItem = newItem;
  879. dci.removedKey = removedKey;
  880. dci.changedItem = changedItem;
  881. try {
  882. this._callingDicChanged = true;
  883. this.dictionaryChanged.notifyObservers(dci, action);
  884. }
  885. finally {
  886. this._callingDicChanged = false;
  887. }
  888. }
  889. };
  890. Object.defineProperty(ObservableStringDictionary.prototype, "watchedObjectChanged", {
  891. get: function () {
  892. if (!this._watchedObjectChanged) {
  893. this._watchedObjectChanged = new BABYLON.Observable();
  894. }
  895. return this._watchedObjectChanged;
  896. },
  897. enumerable: true,
  898. configurable: true
  899. });
  900. ObservableStringDictionary.prototype.onWatchedObjectChanged = function (key, object, propChanged) {
  901. if (this._watchedObjectChanged && this._watchedObjectChanged.hasObservers()) {
  902. var woci = this._callingWatchedObjectChanged ? new OSDWatchedObjectChangedInfo() : this._woci;
  903. woci.key = key;
  904. woci.object = object;
  905. woci.propertyChanged = propChanged;
  906. try {
  907. this._callingWatchedObjectChanged = true;
  908. this.watchedObjectChanged.notifyObservers(woci);
  909. }
  910. finally {
  911. this._callingWatchedObjectChanged = false;
  912. }
  913. }
  914. };
  915. ObservableStringDictionary.pci = new BABYLON.PropertyChangedInfo();
  916. ObservableStringDictionary.callingPropChanged = false;
  917. return ObservableStringDictionary;
  918. }(BABYLON.StringDictionary));
  919. BABYLON.ObservableStringDictionary = ObservableStringDictionary;
  920. })(BABYLON || (BABYLON = {}));
  921. var BABYLON;
  922. (function (BABYLON) {
  923. /**
  924. * Stores 2D Bounding Information.
  925. * This class handles a circle area and a bounding rectangle one.
  926. */
  927. var BoundingInfo2D = (function () {
  928. function BoundingInfo2D() {
  929. this.radius = 0;
  930. this.center = BABYLON.Vector2.Zero();
  931. this.extent = BABYLON.Vector2.Zero();
  932. }
  933. /**
  934. * Create a BoundingInfo2D object from a given size
  935. * @param size the size that will be used to set the extend, radius will be computed from it.
  936. */
  937. BoundingInfo2D.CreateFromSize = function (size) {
  938. var r = new BoundingInfo2D();
  939. BoundingInfo2D.CreateFromSizeToRef(size, r);
  940. return r;
  941. };
  942. /**
  943. * Create a BoundingInfo2D object from a given radius
  944. * @param radius the radius to use, the extent will be computed from it.
  945. */
  946. BoundingInfo2D.CreateFromRadius = function (radius) {
  947. var r = new BoundingInfo2D();
  948. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  949. return r;
  950. };
  951. /**
  952. * Create a BoundingInfo2D object from a list of points.
  953. * The resulted object will be the smallest bounding area that includes all the given points.
  954. * @param points an array of points to compute the bounding object from.
  955. */
  956. BoundingInfo2D.CreateFromPoints = function (points) {
  957. var r = new BoundingInfo2D();
  958. BoundingInfo2D.CreateFromPointsToRef(points, r);
  959. return r;
  960. };
  961. /**
  962. * Update a BoundingInfo2D object using the given Size as input
  963. * @param size the bounding data will be computed from this size.
  964. * @param b must be a valid/allocated object, it will contain the result of the operation
  965. */
  966. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  967. if (!size) {
  968. size = BABYLON.Size.Zero();
  969. }
  970. b.center.x = +size.width / 2;
  971. b.center.y = +size.height / 2;
  972. b.extent.x = b.center.x;
  973. b.extent.y = b.center.y;
  974. b.radius = b.extent.length();
  975. };
  976. /**
  977. * Update a BoundingInfo2D object using the given radius as input
  978. * @param radius the bounding data will be computed from this radius
  979. * @param b must be a valid/allocated object, it will contain the result of the operation
  980. */
  981. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  982. b.center.x = b.center.y = 0;
  983. var r = +radius;
  984. b.extent.x = r;
  985. b.extent.y = r;
  986. b.radius = r;
  987. };
  988. /**
  989. * Update a BoundingInfo2D object using the given points array as input
  990. * @param points the point array to use to update the bounding data
  991. * @param b must be a valid/allocated object, it will contain the result of the operation
  992. */
  993. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  994. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  995. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  996. var p = points_1[_i];
  997. xmin = Math.min(p.x, xmin);
  998. xmax = Math.max(p.x, xmax);
  999. ymin = Math.min(p.y, ymin);
  1000. ymax = Math.max(p.y, ymax);
  1001. }
  1002. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  1003. };
  1004. /**
  1005. * Update a BoundingInfo2D object using the given min/max values as input
  1006. * @param xmin the smallest x coordinate
  1007. * @param xmax the biggest x coordinate
  1008. * @param ymin the smallest y coordinate
  1009. * @param ymax the buggest y coordinate
  1010. * @param b must be a valid/allocated object, it will contain the result of the operation
  1011. */
  1012. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  1013. var w = xmax - xmin;
  1014. var h = ymax - ymin;
  1015. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  1016. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  1017. b.radius = b.extent.length();
  1018. };
  1019. /**
  1020. * Duplicate this instance and return a new one
  1021. * @return the duplicated instance
  1022. */
  1023. BoundingInfo2D.prototype.clone = function () {
  1024. var r = new BoundingInfo2D();
  1025. r.center = this.center.clone();
  1026. r.radius = this.radius;
  1027. r.extent = this.extent.clone();
  1028. return r;
  1029. };
  1030. BoundingInfo2D.prototype.clear = function () {
  1031. this.center.copyFromFloats(0, 0);
  1032. this.radius = 0;
  1033. this.extent.copyFromFloats(0, 0);
  1034. };
  1035. BoundingInfo2D.prototype.copyFrom = function (src) {
  1036. this.center.copyFrom(src.center);
  1037. this.radius = src.radius;
  1038. this.extent.copyFrom(src.extent);
  1039. };
  1040. /**
  1041. * return the max extend of the bounding info
  1042. */
  1043. BoundingInfo2D.prototype.max = function () {
  1044. var r = BABYLON.Vector2.Zero();
  1045. this.maxToRef(r);
  1046. return r;
  1047. };
  1048. /**
  1049. * Update a vector2 with the max extend of the bounding info
  1050. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  1051. */
  1052. BoundingInfo2D.prototype.maxToRef = function (result) {
  1053. result.x = this.center.x + this.extent.x;
  1054. result.y = this.center.y + this.extent.y;
  1055. };
  1056. /**
  1057. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  1058. * @param matrix the transformation matrix to apply
  1059. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  1060. */
  1061. BoundingInfo2D.prototype.transform = function (matrix) {
  1062. var r = new BoundingInfo2D();
  1063. this.transformToRef(matrix, r);
  1064. return r;
  1065. };
  1066. /**
  1067. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  1068. * @param other the second BoundingInfo2D to compute the union with this one
  1069. * @return a new instance containing the result of the union
  1070. */
  1071. BoundingInfo2D.prototype.union = function (other) {
  1072. var r = new BoundingInfo2D();
  1073. this.unionToRef(other, r);
  1074. return r;
  1075. };
  1076. /**
  1077. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  1078. * 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.
  1079. * @param matrix The matrix to use to compute the transformation
  1080. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  1081. */
  1082. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  1083. // Construct a bounding box based on the extent values
  1084. var p = BoundingInfo2D._transform;
  1085. p[0].x = this.center.x + this.extent.x;
  1086. p[0].y = this.center.y + this.extent.y;
  1087. p[1].x = this.center.x + this.extent.x;
  1088. p[1].y = this.center.y - this.extent.y;
  1089. p[2].x = this.center.x - this.extent.x;
  1090. p[2].y = this.center.y - this.extent.y;
  1091. p[3].x = this.center.x - this.extent.x;
  1092. p[3].y = this.center.y + this.extent.y;
  1093. // Transform the four points of the bounding box with the matrix
  1094. for (var i = 0; i < 4; i++) {
  1095. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  1096. }
  1097. BoundingInfo2D.CreateFromPointsToRef(p, result);
  1098. };
  1099. /**
  1100. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  1101. * 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.
  1102. * @param other the second object used to compute the union
  1103. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  1104. */
  1105. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  1106. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  1107. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  1108. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  1109. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  1110. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  1111. };
  1112. /**
  1113. * Check if the given point is inside the BoundingInfo.
  1114. * The test is first made on the radius, then inside the rectangle described by the extent
  1115. * @param pickPosition the position to test
  1116. * @return true if the point is inside, false otherwise
  1117. */
  1118. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  1119. // is it inside the radius?
  1120. var pickLocal = pickPosition.subtract(this.center);
  1121. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  1122. // is it inside the rectangle?
  1123. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  1124. }
  1125. return false;
  1126. };
  1127. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  1128. return BoundingInfo2D;
  1129. }());
  1130. BABYLON.BoundingInfo2D = BoundingInfo2D;
  1131. })(BABYLON || (BABYLON = {}));
  1132. var BABYLON;
  1133. (function (BABYLON) {
  1134. var LayoutEngineBase = (function () {
  1135. function LayoutEngineBase() {
  1136. this.layoutDirtyOnPropertyChangedMask = 0;
  1137. }
  1138. LayoutEngineBase.prototype.updateLayout = function (prim) {
  1139. };
  1140. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  1141. get: function () {
  1142. return false;
  1143. },
  1144. enumerable: true,
  1145. configurable: true
  1146. });
  1147. LayoutEngineBase.prototype.isLocked = function () {
  1148. return this._isLocked;
  1149. };
  1150. LayoutEngineBase.prototype.lock = function () {
  1151. if (this._isLocked) {
  1152. return false;
  1153. }
  1154. this._isLocked = true;
  1155. return true;
  1156. };
  1157. LayoutEngineBase = __decorate([
  1158. BABYLON.className("LayoutEngineBase", "BABYLON")
  1159. ], LayoutEngineBase);
  1160. return LayoutEngineBase;
  1161. }());
  1162. BABYLON.LayoutEngineBase = LayoutEngineBase;
  1163. var CanvasLayoutEngine = (function (_super) {
  1164. __extends(CanvasLayoutEngine, _super);
  1165. function CanvasLayoutEngine() {
  1166. _super.apply(this, arguments);
  1167. }
  1168. // A very simple (no) layout computing...
  1169. // The Canvas and its direct children gets the Canvas' size as Layout Area
  1170. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  1171. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  1172. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  1173. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  1174. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  1175. var child = _a[_i];
  1176. this._doUpdate(child);
  1177. }
  1178. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  1179. }
  1180. };
  1181. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  1182. // Canvas ?
  1183. if (prim instanceof BABYLON.Canvas2D) {
  1184. prim.layoutArea = prim.actualSize; //.multiplyByFloats(prim.scaleX, prim.scaleY);
  1185. }
  1186. else if (prim.parent instanceof BABYLON.Canvas2D) {
  1187. prim.layoutArea = prim.owner.actualSize; //.multiplyByFloats(prim.owner.scaleX, prim.owner.scaleY);
  1188. }
  1189. else {
  1190. prim.layoutArea = prim.parent.contentArea;
  1191. }
  1192. };
  1193. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  1194. get: function () {
  1195. return true;
  1196. },
  1197. enumerable: true,
  1198. configurable: true
  1199. });
  1200. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  1201. CanvasLayoutEngine = __decorate([
  1202. BABYLON.className("CanvasLayoutEngine", "BABYLON")
  1203. ], CanvasLayoutEngine);
  1204. return CanvasLayoutEngine;
  1205. }(LayoutEngineBase));
  1206. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  1207. var StackPanelLayoutEngine = (function (_super) {
  1208. __extends(StackPanelLayoutEngine, _super);
  1209. function StackPanelLayoutEngine() {
  1210. _super.call(this);
  1211. this._isHorizontal = true;
  1212. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  1213. }
  1214. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  1215. get: function () {
  1216. if (!StackPanelLayoutEngine._horizontal) {
  1217. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  1218. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  1219. StackPanelLayoutEngine._horizontal.lock();
  1220. }
  1221. return StackPanelLayoutEngine._horizontal;
  1222. },
  1223. enumerable: true,
  1224. configurable: true
  1225. });
  1226. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  1227. get: function () {
  1228. if (!StackPanelLayoutEngine._vertical) {
  1229. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  1230. StackPanelLayoutEngine._vertical.isHorizontal = false;
  1231. StackPanelLayoutEngine._vertical.lock();
  1232. }
  1233. return StackPanelLayoutEngine._vertical;
  1234. },
  1235. enumerable: true,
  1236. configurable: true
  1237. });
  1238. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  1239. get: function () {
  1240. return this._isHorizontal;
  1241. },
  1242. set: function (val) {
  1243. if (this.isLocked()) {
  1244. return;
  1245. }
  1246. this._isHorizontal = val;
  1247. },
  1248. enumerable: true,
  1249. configurable: true
  1250. });
  1251. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  1252. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  1253. var x = 0;
  1254. var y = 0;
  1255. var h = this.isHorizontal;
  1256. var max = 0;
  1257. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  1258. var child = _a[_i];
  1259. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  1260. continue;
  1261. }
  1262. var layoutArea = void 0;
  1263. if (child._hasMargin) {
  1264. child.margin.computeWithAlignment(prim.layoutArea, child.actualSize, child.marginAlignment, StackPanelLayoutEngine.dstOffset, StackPanelLayoutEngine.dstArea, true);
  1265. layoutArea = StackPanelLayoutEngine.dstArea.clone();
  1266. child.layoutArea = layoutArea;
  1267. }
  1268. else {
  1269. layoutArea = child.layoutArea;
  1270. child.margin.computeArea(child.actualSize, layoutArea);
  1271. }
  1272. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  1273. }
  1274. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  1275. var child = _c[_b];
  1276. if (child._isFlagSet(BABYLON.SmartPropertyPrim.flagNoPartOfLayout)) {
  1277. continue;
  1278. }
  1279. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  1280. var layoutArea = child.layoutArea;
  1281. if (h) {
  1282. x += layoutArea.width;
  1283. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  1284. }
  1285. else {
  1286. y += layoutArea.height;
  1287. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  1288. }
  1289. }
  1290. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  1291. }
  1292. };
  1293. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  1294. get: function () {
  1295. return false;
  1296. },
  1297. enumerable: true,
  1298. configurable: true
  1299. });
  1300. StackPanelLayoutEngine._horizontal = null;
  1301. StackPanelLayoutEngine._vertical = null;
  1302. StackPanelLayoutEngine.dstOffset = BABYLON.Vector4.Zero();
  1303. StackPanelLayoutEngine.dstArea = BABYLON.Size.Zero();
  1304. StackPanelLayoutEngine = __decorate([
  1305. BABYLON.className("StackPanelLayoutEngine", "BABYLON")
  1306. ], StackPanelLayoutEngine);
  1307. return StackPanelLayoutEngine;
  1308. }(LayoutEngineBase));
  1309. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  1310. })(BABYLON || (BABYLON = {}));
  1311. var BABYLON;
  1312. (function (BABYLON) {
  1313. /**
  1314. * Base class implementing the ILocable interface.
  1315. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  1316. */
  1317. var LockableBase = (function () {
  1318. function LockableBase() {
  1319. }
  1320. LockableBase.prototype.isLocked = function () {
  1321. return this._isLocked;
  1322. };
  1323. LockableBase.prototype.lock = function () {
  1324. if (this._isLocked) {
  1325. return true;
  1326. }
  1327. this.onLock();
  1328. this._isLocked = true;
  1329. return false;
  1330. };
  1331. /**
  1332. * Protected handler that will be called when the instance is about to be locked.
  1333. */
  1334. LockableBase.prototype.onLock = function () {
  1335. };
  1336. return LockableBase;
  1337. }());
  1338. BABYLON.LockableBase = LockableBase;
  1339. var SolidColorBrush2D = (function (_super) {
  1340. __extends(SolidColorBrush2D, _super);
  1341. function SolidColorBrush2D(color, lock) {
  1342. if (lock === void 0) { lock = false; }
  1343. _super.call(this);
  1344. this._color = color;
  1345. if (lock) {
  1346. {
  1347. this.lock();
  1348. }
  1349. }
  1350. }
  1351. /**
  1352. * Return true if the brush is transparent, false if it's totally opaque
  1353. */
  1354. SolidColorBrush2D.prototype.isTransparent = function () {
  1355. return this._color && this._color.a < 1.0;
  1356. };
  1357. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  1358. /**
  1359. * The color used by this instance to render
  1360. * @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.
  1361. */
  1362. get: function () {
  1363. return this._color;
  1364. },
  1365. set: function (value) {
  1366. if (this.isLocked()) {
  1367. return;
  1368. }
  1369. this._color = value;
  1370. },
  1371. enumerable: true,
  1372. configurable: true
  1373. });
  1374. /**
  1375. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  1376. */
  1377. SolidColorBrush2D.prototype.toString = function () {
  1378. return this._color.toHexString();
  1379. };
  1380. SolidColorBrush2D = __decorate([
  1381. BABYLON.className("SolidColorBrush2D", "BABYLON")
  1382. ], SolidColorBrush2D);
  1383. return SolidColorBrush2D;
  1384. }(LockableBase));
  1385. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  1386. var GradientColorBrush2D = (function (_super) {
  1387. __extends(GradientColorBrush2D, _super);
  1388. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  1389. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  1390. if (rotation === void 0) { rotation = 0; }
  1391. if (scale === void 0) { scale = 1; }
  1392. if (lock === void 0) { lock = false; }
  1393. _super.call(this);
  1394. this._color1 = color1;
  1395. this._color2 = color2;
  1396. this._translation = translation;
  1397. this._rotation = rotation;
  1398. this._scale = scale;
  1399. if (lock) {
  1400. this.lock();
  1401. }
  1402. }
  1403. /**
  1404. * Return true if the brush is transparent, false if it's totally opaque
  1405. */
  1406. GradientColorBrush2D.prototype.isTransparent = function () {
  1407. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  1408. };
  1409. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  1410. /**
  1411. * First color, the blend will start from this color
  1412. */
  1413. get: function () {
  1414. return this._color1;
  1415. },
  1416. set: function (value) {
  1417. if (this.isLocked()) {
  1418. return;
  1419. }
  1420. this._color1 = value;
  1421. },
  1422. enumerable: true,
  1423. configurable: true
  1424. });
  1425. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  1426. /**
  1427. * Second color, the blend will end to this color
  1428. */
  1429. get: function () {
  1430. return this._color2;
  1431. },
  1432. set: function (value) {
  1433. if (this.isLocked()) {
  1434. return;
  1435. }
  1436. this._color2 = value;
  1437. },
  1438. enumerable: true,
  1439. configurable: true
  1440. });
  1441. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  1442. /**
  1443. * Translation vector to apply on the blend
  1444. * Default is [0;0]
  1445. */
  1446. get: function () {
  1447. return this._translation;
  1448. },
  1449. set: function (value) {
  1450. if (this.isLocked()) {
  1451. return;
  1452. }
  1453. this._translation = value;
  1454. },
  1455. enumerable: true,
  1456. configurable: true
  1457. });
  1458. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  1459. /**
  1460. * Rotation in radian to apply to the brush
  1461. * Default direction of the brush is vertical, you can change this using this property.
  1462. * Default is 0.
  1463. */
  1464. get: function () {
  1465. return this._rotation;
  1466. },
  1467. set: function (value) {
  1468. if (this.isLocked()) {
  1469. return;
  1470. }
  1471. this._rotation = value;
  1472. },
  1473. enumerable: true,
  1474. configurable: true
  1475. });
  1476. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  1477. /**
  1478. * Scale factor to apply to the gradient.
  1479. * Default is 1: no scale.
  1480. */
  1481. get: function () {
  1482. return this._scale;
  1483. },
  1484. set: function (value) {
  1485. if (this.isLocked()) {
  1486. return;
  1487. }
  1488. this._scale = value;
  1489. },
  1490. enumerable: true,
  1491. configurable: true
  1492. });
  1493. /**
  1494. * Return a string describing the brush
  1495. */
  1496. GradientColorBrush2D.prototype.toString = function () {
  1497. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  1498. };
  1499. /**
  1500. * Build a unique key string for the given parameters
  1501. */
  1502. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  1503. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  1504. };
  1505. GradientColorBrush2D = __decorate([
  1506. BABYLON.className("GradientColorBrush2D", "BABYLON")
  1507. ], GradientColorBrush2D);
  1508. return GradientColorBrush2D;
  1509. }(LockableBase));
  1510. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  1511. })(BABYLON || (BABYLON = {}));
  1512. var BABYLON;
  1513. (function (BABYLON) {
  1514. var Prim2DClassInfo = (function () {
  1515. function Prim2DClassInfo() {
  1516. }
  1517. return Prim2DClassInfo;
  1518. }());
  1519. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  1520. var Prim2DPropInfo = (function () {
  1521. function Prim2DPropInfo() {
  1522. }
  1523. Prim2DPropInfo.PROPKIND_MODEL = 1;
  1524. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  1525. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  1526. return Prim2DPropInfo;
  1527. }());
  1528. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  1529. var ClassTreeInfo = (function () {
  1530. function ClassTreeInfo(baseClass, type, classContentFactory) {
  1531. this._baseClass = baseClass;
  1532. this._type = type;
  1533. this._subClasses = new Array();
  1534. this._levelContent = new BABYLON.StringDictionary();
  1535. this._classContentFactory = classContentFactory;
  1536. }
  1537. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  1538. get: function () {
  1539. if (!this._classContent) {
  1540. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  1541. }
  1542. return this._classContent;
  1543. },
  1544. enumerable: true,
  1545. configurable: true
  1546. });
  1547. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  1548. get: function () {
  1549. return this._type;
  1550. },
  1551. enumerable: true,
  1552. configurable: true
  1553. });
  1554. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  1555. get: function () {
  1556. return this._levelContent;
  1557. },
  1558. enumerable: true,
  1559. configurable: true
  1560. });
  1561. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  1562. get: function () {
  1563. if (!this._fullContent) {
  1564. var dic_1 = new BABYLON.StringDictionary();
  1565. var curLevel = this;
  1566. while (curLevel) {
  1567. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  1568. curLevel = curLevel._baseClass;
  1569. }
  1570. this._fullContent = dic_1;
  1571. }
  1572. return this._fullContent;
  1573. },
  1574. enumerable: true,
  1575. configurable: true
  1576. });
  1577. ClassTreeInfo.prototype.getLevelOf = function (type) {
  1578. // Are we already there?
  1579. if (type === this._type) {
  1580. return this;
  1581. }
  1582. var baseProto = Object.getPrototypeOf(type);
  1583. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  1584. if (!curProtoContent) {
  1585. this.getLevelOf(baseProto);
  1586. }
  1587. return this.getOrAddType(baseProto, type);
  1588. };
  1589. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  1590. // Are we at the level corresponding to the baseType?
  1591. // If so, get or add the level we're looking for
  1592. if (baseType === this._type) {
  1593. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  1594. var subType = _a[_i];
  1595. if (subType.type === type) {
  1596. return subType.node;
  1597. }
  1598. }
  1599. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  1600. var info = { type: type, node: node };
  1601. this._subClasses.push(info);
  1602. return info.node;
  1603. }
  1604. // Recurse down to keep looking for the node corresponding to the baseTypeName
  1605. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  1606. var subType = _c[_b];
  1607. var info = subType.node.getOrAddType(baseType, type);
  1608. if (info) {
  1609. return info;
  1610. }
  1611. }
  1612. return null;
  1613. };
  1614. ClassTreeInfo.get = function (type) {
  1615. var dic = type["__classTreeInfo"];
  1616. if (!dic) {
  1617. return null;
  1618. }
  1619. return dic.getLevelOf(type);
  1620. };
  1621. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  1622. var dic = type["__classTreeInfo"];
  1623. if (!dic) {
  1624. dic = new ClassTreeInfo(null, type, classContentFactory);
  1625. type["__classTreeInfo"] = dic;
  1626. }
  1627. return dic;
  1628. };
  1629. return ClassTreeInfo;
  1630. }());
  1631. BABYLON.ClassTreeInfo = ClassTreeInfo;
  1632. var DataBinding = (function () {
  1633. function DataBinding() {
  1634. this._converter = null;
  1635. this._mode = DataBinding.MODE_DEFAULT;
  1636. this._uiElementId = null;
  1637. this._dataSource = null;
  1638. this._currentDataSource = null;
  1639. this._propertyPathName = null;
  1640. this._stringFormat = null;
  1641. this._updateSourceTrigger = DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  1642. this._boundTo = null;
  1643. this._owner = null;
  1644. this._updateCounter = 0;
  1645. }
  1646. Object.defineProperty(DataBinding.prototype, "converter", {
  1647. /**
  1648. * Provide a callback that will convert the value obtained by the Data Binding to the type of the SmartProperty it's bound to.
  1649. * If no value are set, then it's assumed that the sourceValue is of the same type as the SmartProperty's one.
  1650. * 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.
  1651. * @param sourceValue the source object retrieve by the Data Binding mechanism
  1652. * @returns the object of a compatible type with the SmartProperty it's bound to
  1653. */
  1654. get: function () {
  1655. return this._converter;
  1656. },
  1657. set: function (value) {
  1658. if (this._converter === value) {
  1659. return;
  1660. }
  1661. this._converter = value;
  1662. },
  1663. enumerable: true,
  1664. configurable: true
  1665. });
  1666. Object.defineProperty(DataBinding.prototype, "mode", {
  1667. /**
  1668. * 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
  1669. */
  1670. get: function () {
  1671. if (this._mode === DataBinding.MODE_DEFAULT) {
  1672. return this._boundTo.bindingMode;
  1673. }
  1674. return this._mode;
  1675. },
  1676. set: function (value) {
  1677. if (this._mode === value) {
  1678. return;
  1679. }
  1680. this._mode = value;
  1681. },
  1682. enumerable: true,
  1683. configurable: true
  1684. });
  1685. Object.defineProperty(DataBinding.prototype, "uiElementId", {
  1686. /**
  1687. * You can override the Data Source object with this member which is the Id of a uiElement existing in the UI Logical tree.
  1688. * If not set and source no set too, then the dataSource property will be used.
  1689. */
  1690. get: function () {
  1691. return this._uiElementId;
  1692. },
  1693. set: function (value) {
  1694. if (this._uiElementId === value) {
  1695. return;
  1696. }
  1697. this._uiElementId = value;
  1698. },
  1699. enumerable: true,
  1700. configurable: true
  1701. });
  1702. Object.defineProperty(DataBinding.prototype, "dataSource", {
  1703. /**
  1704. * You can override the Data Source object with this member which is the source object to use directly.
  1705. * If not set and uiElement no set too, then the dataSource property of the SmartPropertyBase object will be used.
  1706. */
  1707. get: function () {
  1708. return this._dataSource;
  1709. },
  1710. set: function (value) {
  1711. if (this._dataSource === value) {
  1712. return;
  1713. }
  1714. this._dataSource = value;
  1715. },
  1716. enumerable: true,
  1717. configurable: true
  1718. });
  1719. Object.defineProperty(DataBinding.prototype, "propertyPathName", {
  1720. /**
  1721. * The path & name of the property to get from the source object.
  1722. * 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.
  1723. * If nothing is set then the source object will be used.
  1724. * 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.
  1725. * 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.
  1726. */
  1727. get: function () {
  1728. return this._propertyPathName;
  1729. },
  1730. set: function (value) {
  1731. if (this._propertyPathName === value) {
  1732. return;
  1733. }
  1734. if (this._owner) {
  1735. }
  1736. this._propertyPathName = value;
  1737. if (this._owner) {
  1738. }
  1739. },
  1740. enumerable: true,
  1741. configurable: true
  1742. });
  1743. Object.defineProperty(DataBinding.prototype, "stringFormat", {
  1744. /**
  1745. * 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}`
  1746. */
  1747. get: function () {
  1748. return this._stringFormat;
  1749. },
  1750. set: function (value) {
  1751. if (this._stringFormat === value) {
  1752. return;
  1753. }
  1754. this._stringFormat = value;
  1755. },
  1756. enumerable: true,
  1757. configurable: true
  1758. });
  1759. Object.defineProperty(DataBinding.prototype, "updateSourceTrigger", {
  1760. /**
  1761. * 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.
  1762. */
  1763. get: function () {
  1764. return this._updateSourceTrigger;
  1765. },
  1766. set: function (value) {
  1767. if (this._updateSourceTrigger === value) {
  1768. return;
  1769. }
  1770. this._updateSourceTrigger = value;
  1771. },
  1772. enumerable: true,
  1773. configurable: true
  1774. });
  1775. DataBinding.prototype.canUpdateTarget = function (resetUpdateCounter) {
  1776. if (resetUpdateCounter) {
  1777. this._updateCounter = 0;
  1778. }
  1779. var mode = this.mode;
  1780. if (mode === DataBinding.MODE_ONETIME) {
  1781. return this._updateCounter === 0;
  1782. }
  1783. if (mode === DataBinding.MODE_ONEWAYTOSOURCE) {
  1784. return false;
  1785. }
  1786. return true;
  1787. };
  1788. DataBinding.prototype.updateTarget = function () {
  1789. var value = this._getActualDataSource();
  1790. var properties = this.propertyPathName.split(".");
  1791. for (var _i = 0, properties_1 = properties; _i < properties_1.length; _i++) {
  1792. var propertyName = properties_1[_i];
  1793. value = value[propertyName];
  1794. }
  1795. this._storeBoundValue(this._owner, value);
  1796. };
  1797. DataBinding.prototype._storeBoundValue = function (watcher, value) {
  1798. if ((++this._updateCounter > 1) && (this.mode === DataBinding.MODE_ONETIME)) {
  1799. return;
  1800. }
  1801. var newValue = value;
  1802. if (this._converter) {
  1803. newValue = this._converter(value);
  1804. }
  1805. if (this._stringFormat) {
  1806. newValue = this._stringFormat(newValue);
  1807. }
  1808. watcher[this._boundTo.name] = newValue;
  1809. };
  1810. DataBinding.prototype._getActualDataSource = function () {
  1811. if (this.dataSource) {
  1812. return this.dataSource;
  1813. }
  1814. if (this.uiElementId) {
  1815. // TODO Find UIElement
  1816. return null;
  1817. }
  1818. return this._owner.dataSource;
  1819. };
  1820. DataBinding.prototype._registerDataSource = function (updateTarget) {
  1821. var ds = this._getActualDataSource();
  1822. if (ds === this._currentDataSource) {
  1823. return;
  1824. }
  1825. if (this._currentDataSource) {
  1826. BindingHelper.unregisterDataSource(this._currentDataSource, this, 0);
  1827. }
  1828. if (ds) {
  1829. BindingHelper.registerDataSource(ds, this);
  1830. if (updateTarget && this.canUpdateTarget(true)) {
  1831. this.updateTarget();
  1832. }
  1833. }
  1834. this._currentDataSource = ds;
  1835. };
  1836. DataBinding.prototype._unregisterDataSource = function () {
  1837. var ds = this._getActualDataSource();
  1838. if (ds) {
  1839. BindingHelper.unregisterDataSource(ds, this, 0);
  1840. }
  1841. };
  1842. /**
  1843. * Use the mode specified in the SmartProperty declaration
  1844. */
  1845. DataBinding.MODE_DEFAULT = 1;
  1846. /**
  1847. * Update the binding target only once when the Smart Property's value is first accessed
  1848. */
  1849. DataBinding.MODE_ONETIME = 2;
  1850. /**
  1851. * Update the smart property when the source changes.
  1852. * The source won't be updated if the smart property value is set.
  1853. */
  1854. DataBinding.MODE_ONEWAY = 3;
  1855. /**
  1856. * Only update the source when the target's data is changing.
  1857. */
  1858. DataBinding.MODE_ONEWAYTOSOURCE = 4;
  1859. /**
  1860. * Update the bind target when the source changes and update the source when the Smart Property value is set.
  1861. */
  1862. DataBinding.MODE_TWOWAY = 5;
  1863. /**
  1864. * Use the Update Source Trigger defined in the SmartProperty declaration
  1865. */
  1866. DataBinding.UPDATESOURCETRIGGER_DEFAULT = 1;
  1867. /**
  1868. * Update the source as soon as the Smart Property has a value change
  1869. */
  1870. DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED = 2;
  1871. /**
  1872. * Update the source when the binding target loses focus
  1873. */
  1874. DataBinding.UPDATESOURCETRIGGER_LOSTFOCUS = 3;
  1875. /**
  1876. * Update the source will be made by explicitly calling the UpdateFromDataSource method
  1877. */
  1878. DataBinding.UPDATESOURCETRIGGER_EXPLICIT = 4;
  1879. DataBinding = __decorate([
  1880. BABYLON.className("DataBinding", "BABYLON")
  1881. ], DataBinding);
  1882. return DataBinding;
  1883. }());
  1884. BABYLON.DataBinding = DataBinding;
  1885. var SmartPropertyBase = (function (_super) {
  1886. __extends(SmartPropertyBase, _super);
  1887. function SmartPropertyBase() {
  1888. _super.call(this);
  1889. this._dataSource = null;
  1890. this._dataSourceObserver = null;
  1891. this._instanceDirtyFlags = 0;
  1892. this._isDisposed = false;
  1893. this._bindings = null;
  1894. this._hasBinding = 0;
  1895. this._bindingSourceChanged = 0;
  1896. this._disposeObservable = null;
  1897. }
  1898. Object.defineProperty(SmartPropertyBase.prototype, "disposeObservable", {
  1899. get: function () {
  1900. if (!this._disposeObservable) {
  1901. this._disposeObservable = new BABYLON.Observable();
  1902. }
  1903. return this._disposeObservable;
  1904. },
  1905. enumerable: true,
  1906. configurable: true
  1907. });
  1908. Object.defineProperty(SmartPropertyBase.prototype, "isDisposed", {
  1909. /**
  1910. * Check if the object is disposed or not.
  1911. * @returns true if the object is dispose, false otherwise.
  1912. */
  1913. get: function () {
  1914. return this._isDisposed;
  1915. },
  1916. enumerable: true,
  1917. configurable: true
  1918. });
  1919. /**
  1920. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  1921. * @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.
  1922. */
  1923. SmartPropertyBase.prototype.dispose = function () {
  1924. if (this.isDisposed) {
  1925. return false;
  1926. }
  1927. if (this._disposeObservable && this._disposeObservable.hasObservers()) {
  1928. this._disposeObservable.notifyObservers(this);
  1929. }
  1930. this._isDisposed = true;
  1931. return true;
  1932. };
  1933. /**
  1934. * Check if a given set of properties are dirty or not.
  1935. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  1936. * @return true if at least one property is dirty, false if none of them are.
  1937. */
  1938. SmartPropertyBase.prototype.checkPropertiesDirty = function (flags) {
  1939. return (this._instanceDirtyFlags & flags) !== 0;
  1940. };
  1941. /**
  1942. * Clear a given set of properties.
  1943. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  1944. * @return the new set of property still marked as dirty
  1945. */
  1946. SmartPropertyBase.prototype.clearPropertiesDirty = function (flags) {
  1947. this._instanceDirtyFlags &= ~flags;
  1948. return this._instanceDirtyFlags;
  1949. };
  1950. SmartPropertyBase.prototype._resetPropertiesDirty = function () {
  1951. this._instanceDirtyFlags = 0;
  1952. };
  1953. /**
  1954. * Add an externally attached data from its key.
  1955. * This method call will fail and return false, if such key already exists.
  1956. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  1957. * @param key the unique key that identifies the data
  1958. * @param data the data object to associate to the key for this Engine instance
  1959. * @return true if no such key were already present and the data was added successfully, false otherwise
  1960. */
  1961. SmartPropertyBase.prototype.addExternalData = function (key, data) {
  1962. if (!this._externalData) {
  1963. this._externalData = new BABYLON.StringDictionary();
  1964. }
  1965. return this._externalData.add(key, data);
  1966. };
  1967. /**
  1968. * Get an externally attached data from its key
  1969. * @param key the unique key that identifies the data
  1970. * @return the associated data, if present (can be null), or undefined if not present
  1971. */
  1972. SmartPropertyBase.prototype.getExternalData = function (key) {
  1973. if (!this._externalData) {
  1974. return null;
  1975. }
  1976. return this._externalData.get(key);
  1977. };
  1978. /**
  1979. * Get an externally attached data from its key, create it using a factory if it's not already present
  1980. * @param key the unique key that identifies the data
  1981. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  1982. * @return the associated data, can be null if the factory returned null.
  1983. */
  1984. SmartPropertyBase.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  1985. if (!this._externalData) {
  1986. this._externalData = new BABYLON.StringDictionary();
  1987. }
  1988. return this._externalData.getOrAddWithFactory(key, factory);
  1989. };
  1990. /**
  1991. * Remove an externally attached data from the Engine instance
  1992. * @param key the unique key that identifies the data
  1993. * @return true if the data was successfully removed, false if it doesn't exist
  1994. */
  1995. SmartPropertyBase.prototype.removeExternalData = function (key) {
  1996. if (!this._externalData) {
  1997. return false;
  1998. }
  1999. return this._externalData.remove(key);
  2000. };
  2001. SmartPropertyBase._hookProperty = function (propId, piStore, kind, settings) {
  2002. return function (target, propName, descriptor) {
  2003. if (!settings) {
  2004. settings = {};
  2005. }
  2006. var propInfo = SmartPropertyBase._createPropInfo(target, propName, propId, kind, settings);
  2007. if (piStore) {
  2008. piStore(propInfo);
  2009. }
  2010. var getter = descriptor.get, setter = descriptor.set;
  2011. var typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  2012. // Overload the property setter implementation to add our own logic
  2013. descriptor.set = function (val) {
  2014. if (!setter) {
  2015. throw Error("Property '" + propInfo.name + "' of type '" + BABYLON.Tools.getFullClassName(this) + "' has no setter defined but was invoked as if it had one.");
  2016. }
  2017. // check for disposed first, do nothing
  2018. if (this.isDisposed) {
  2019. return;
  2020. }
  2021. var curVal = getter.call(this);
  2022. if (SmartPropertyBase._checkUnchanged(curVal, val)) {
  2023. return;
  2024. }
  2025. // Cast the object we're working one
  2026. var prim = this;
  2027. // Change the value
  2028. setter.call(this, val);
  2029. // Notify change, dirty flags update
  2030. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  2031. };
  2032. };
  2033. };
  2034. SmartPropertyBase._createPropInfo = function (target, propName, propId, kind, settings) {
  2035. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  2036. var node = dic.getLevelOf(target);
  2037. var propInfo = node.levelContent.get(propId.toString());
  2038. if (propInfo) {
  2039. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  2040. }
  2041. // Create, setup and add the PropInfo object to our prop dictionary
  2042. propInfo = new Prim2DPropInfo();
  2043. propInfo.id = propId;
  2044. propInfo.flagId = Math.pow(2, propId);
  2045. propInfo.kind = kind;
  2046. propInfo.name = propName;
  2047. propInfo.bindingMode = (settings.bindingMode !== undefined) ? settings.bindingMode : DataBinding.MODE_TWOWAY;
  2048. propInfo.bindingUpdateSourceTrigger = (settings.bindingUpdateSourceTrigger !== undefined) ? settings.bindingUpdateSourceTrigger : DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED;
  2049. propInfo.dirtyBoundingInfo = (settings.dirtyBoundingInfo !== undefined) ? settings.dirtyBoundingInfo : false;
  2050. propInfo.dirtyParentBoundingInfo = (settings.dirtyParentBoundingBox !== undefined) ? settings.dirtyParentBoundingBox : false;
  2051. propInfo.typeLevelCompare = (settings.typeLevelCompare !== undefined) ? settings.typeLevelCompare : false;
  2052. node.levelContent.add(propName, propInfo);
  2053. return propInfo;
  2054. };
  2055. Object.defineProperty(SmartPropertyBase.prototype, "propDic", {
  2056. /**
  2057. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  2058. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  2059. */
  2060. get: function () {
  2061. if (!this._propInfo) {
  2062. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  2063. if (!cti) {
  2064. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  2065. }
  2066. this._propInfo = cti.fullContent;
  2067. }
  2068. return this._propInfo;
  2069. },
  2070. enumerable: true,
  2071. configurable: true
  2072. });
  2073. SmartPropertyBase._checkUnchanged = function (curValue, newValue) {
  2074. // Nothing to nothing: nothing to do!
  2075. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  2076. return true;
  2077. }
  2078. // Check value unchanged
  2079. if ((curValue != null) && (newValue != null)) {
  2080. if (typeof (curValue.equals) == "function") {
  2081. if (curValue.equals(newValue)) {
  2082. return true;
  2083. }
  2084. }
  2085. else {
  2086. if (curValue === newValue) {
  2087. return true;
  2088. }
  2089. }
  2090. }
  2091. return false;
  2092. };
  2093. SmartPropertyBase.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  2094. // Trigger property changed
  2095. var info = SmartPropertyBase.propChangeGuarding ? new BABYLON.PropertyChangedInfo() : SmartPropertyPrim.propChangedInfo;
  2096. info.oldValue = curValue;
  2097. info.newValue = newValue;
  2098. info.propertyName = propName;
  2099. var propMask = propInfo ? propInfo.flagId : -1;
  2100. try {
  2101. SmartPropertyBase.propChangeGuarding = true;
  2102. this.propertyChanged.notifyObservers(info, propMask);
  2103. }
  2104. finally {
  2105. SmartPropertyBase.propChangeGuarding = false;
  2106. }
  2107. };
  2108. SmartPropertyBase.prototype._triggerPropertyChanged = function (propInfo, newValue) {
  2109. if (this.isDisposed) {
  2110. return;
  2111. }
  2112. if (!propInfo) {
  2113. return;
  2114. }
  2115. this._handlePropChanged(undefined, newValue, propInfo.name, propInfo, propInfo.typeLevelCompare);
  2116. };
  2117. Object.defineProperty(SmartPropertyBase.prototype, "dataSource", {
  2118. /**
  2119. * Set the object from which Smart Properties using Binding will take/update their data from/to.
  2120. * 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.
  2121. */
  2122. get: function () {
  2123. // Don't access to _dataSource directly but via a call to the _getDataSource method which can be overloaded in inherited classes
  2124. return this._getDataSource();
  2125. },
  2126. set: function (value) {
  2127. if (this._dataSource === value) {
  2128. return;
  2129. }
  2130. var oldValue = this._dataSource;
  2131. this._dataSource = value;
  2132. if (this._bindings && value != null) {
  2133. // Register the bindings
  2134. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  2135. var binding = _a[_i];
  2136. if (binding != null) {
  2137. binding._registerDataSource(true);
  2138. }
  2139. }
  2140. }
  2141. this.onPropertyChanged("dataSource", oldValue, value);
  2142. },
  2143. enumerable: true,
  2144. configurable: true
  2145. });
  2146. // Inheriting classes can overload this method to provides additional logic for dataSource access
  2147. SmartPropertyBase.prototype._getDataSource = function () {
  2148. return this._dataSource;
  2149. };
  2150. SmartPropertyBase.prototype.createSimpleDataBinding = function (propInfo, propertyPathName, mode) {
  2151. if (mode === void 0) { mode = DataBinding.MODE_DEFAULT; }
  2152. var binding = new DataBinding();
  2153. binding.propertyPathName = propertyPathName;
  2154. binding.mode = mode;
  2155. return this.createDataBinding(propInfo, binding);
  2156. };
  2157. SmartPropertyBase.prototype.createDataBinding = function (propInfo, binding) {
  2158. if (!this._bindings) {
  2159. this._bindings = new Array();
  2160. }
  2161. if (!binding || binding._owner != null) {
  2162. throw Error("A valid/unused Binding must be passed.");
  2163. }
  2164. // Unregister a potentially existing binding for this property
  2165. this.removeDataBinding(propInfo);
  2166. // register the binding
  2167. binding._owner = this;
  2168. binding._boundTo = propInfo;
  2169. this._bindings[propInfo.id] = binding;
  2170. this._hasBinding |= propInfo.flagId;
  2171. binding._registerDataSource(true);
  2172. return binding;
  2173. };
  2174. SmartPropertyBase.prototype.removeDataBinding = function (propInfo) {
  2175. if ((this._hasBinding & propInfo.flagId) === 0) {
  2176. return false;
  2177. }
  2178. var curBinding = this._bindings[propInfo.id];
  2179. curBinding._unregisterDataSource();
  2180. this._bindings[propInfo.id] = null;
  2181. this._hasBinding &= ~propInfo.flagId;
  2182. return true;
  2183. };
  2184. SmartPropertyBase.prototype.updateFromDataSource = function () {
  2185. for (var _i = 0, _a = this._bindings; _i < _a.length; _i++) {
  2186. var binding = _a[_i];
  2187. if (binding) {
  2188. }
  2189. }
  2190. };
  2191. SmartPropertyBase.propChangedInfo = new BABYLON.PropertyChangedInfo();
  2192. SmartPropertyBase.propChangeGuarding = false;
  2193. SmartPropertyBase = __decorate([
  2194. BABYLON.className("SmartPropertyBase", "BABYLON")
  2195. ], SmartPropertyBase);
  2196. return SmartPropertyBase;
  2197. }(BABYLON.PropertyChangedBase));
  2198. BABYLON.SmartPropertyBase = SmartPropertyBase;
  2199. var BindingInfo = (function () {
  2200. function BindingInfo(binding, level, isLast) {
  2201. this.binding = binding;
  2202. this.level = level;
  2203. this.isLast = isLast;
  2204. }
  2205. return BindingInfo;
  2206. }());
  2207. var MonitoredObjectData = (function () {
  2208. function MonitoredObjectData(monitoredObject) {
  2209. var _this = this;
  2210. this.monitoredObject = monitoredObject;
  2211. this.monitoredIntermediateProperties = new BABYLON.StringDictionary();
  2212. this.observer = this.monitoredObject.propertyChanged.add(function (e, s) { _this.propertyChangedHandler(e.propertyName, e.oldValue, e.newValue); });
  2213. this.boundProperties = new BABYLON.StringDictionary();
  2214. this.monitoredIntermediateMask = 0;
  2215. this.boundPropertiesMask = 0;
  2216. }
  2217. MonitoredObjectData.prototype.propertyChangedHandler = function (propName, oldValue, newValue) {
  2218. var propId = BindingHelper._getPropertyID(this.monitoredObject, propName);
  2219. var propIdStr = propId.toString();
  2220. // Loop through all the registered bindings for this property that had a value change
  2221. if ((this.boundPropertiesMask & propId) !== 0) {
  2222. var bindingInfos = this.boundProperties.get(propIdStr);
  2223. for (var _i = 0, bindingInfos_1 = bindingInfos; _i < bindingInfos_1.length; _i++) {
  2224. var bi = bindingInfos_1[_i];
  2225. if (!bi.isLast) {
  2226. BindingHelper.unregisterDataSource(this.monitoredObject, bi.binding, bi.level);
  2227. BindingHelper.registerDataSource(bi.binding._currentDataSource, bi.binding);
  2228. }
  2229. if (bi.binding.canUpdateTarget(false)) {
  2230. bi.binding.updateTarget();
  2231. }
  2232. }
  2233. }
  2234. };
  2235. return MonitoredObjectData;
  2236. }());
  2237. var BindingHelper = (function () {
  2238. function BindingHelper() {
  2239. }
  2240. BindingHelper.registerDataSource = function (dataSource, binding) {
  2241. var properties = binding.propertyPathName.split(".");
  2242. var ownerMod = null;
  2243. var ownerInterPropId = 0;
  2244. var propertyOwner = dataSource;
  2245. var _loop_1 = function(i) {
  2246. var propName = properties[i];
  2247. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  2248. var propIdStr = propId.toString();
  2249. var mod = void 0;
  2250. if (ownerMod) {
  2251. var o_1 = ownerMod;
  2252. var po_1 = propertyOwner;
  2253. var oii_1 = ownerInterPropId;
  2254. mod = ownerMod.monitoredIntermediateProperties.getOrAddWithFactory(oii_1.toString(), function (k) {
  2255. o_1.monitoredIntermediateMask |= oii_1;
  2256. return BindingHelper._getMonitoredObjectData(po_1);
  2257. });
  2258. }
  2259. else {
  2260. mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  2261. }
  2262. var m = mod;
  2263. var bindingInfos = mod.boundProperties.getOrAddWithFactory(propIdStr, function (k) {
  2264. m.boundPropertiesMask |= propId;
  2265. return new Array();
  2266. });
  2267. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  2268. if (!bi) {
  2269. bindingInfos.push(new BindingInfo(binding, i, (i + 1) === properties.length));
  2270. }
  2271. ownerMod = mod;
  2272. ownerInterPropId = propId;
  2273. propertyOwner = propertyOwner[propName];
  2274. };
  2275. for (var i = 0; i < properties.length; i++) {
  2276. _loop_1(i);
  2277. }
  2278. };
  2279. BindingHelper.unregisterDataSource = function (dataSource, binding, level) {
  2280. var properties = binding.propertyPathName.split(".");
  2281. var propertyOwner = dataSource;
  2282. var mod = BindingHelper._getMonitoredObjectData(propertyOwner);
  2283. for (var i = 0; i < properties.length; i++) {
  2284. var propName = properties[i];
  2285. var propId = BindingHelper._getPropertyID(propertyOwner, propName);
  2286. var propIdStr = propId.toString();
  2287. if (i >= level) {
  2288. mod = BindingHelper._unregisterBinding(mod, propId, binding);
  2289. }
  2290. else {
  2291. mod = mod.monitoredIntermediateProperties.get(propIdStr);
  2292. }
  2293. propertyOwner = propertyOwner[propName];
  2294. }
  2295. };
  2296. BindingHelper._unregisterBinding = function (mod, propertyID, binding) {
  2297. var propertyIDStr = propertyID.toString();
  2298. var res = null;
  2299. // Check if the property is registered as an intermediate and remove it
  2300. if ((mod.monitoredIntermediateMask & propertyID) !== 0) {
  2301. res = mod.monitoredIntermediateProperties.get(propertyIDStr);
  2302. mod.monitoredIntermediateProperties.remove(propertyIDStr);
  2303. // Update the mask
  2304. mod.monitoredIntermediateMask &= ~propertyID;
  2305. }
  2306. // Check if the property is registered as a final property and remove it
  2307. if ((mod.boundPropertiesMask & propertyID) !== 0) {
  2308. var bindingInfos = mod.boundProperties.get(propertyIDStr);
  2309. // Find the binding and remove it
  2310. var bi = BABYLON.Tools.first(bindingInfos, function (cbi) { return cbi.binding === binding; });
  2311. if (bi) {
  2312. var bii = bindingInfos.indexOf(bi);
  2313. bindingInfos.splice(bii, 1);
  2314. }
  2315. // If the array is empty, update the mask
  2316. if (bindingInfos.length === 0) {
  2317. mod.boundPropertiesMask &= ~propertyID;
  2318. }
  2319. }
  2320. // Check if the MOD is empty and unregister the observer and remove it from the list of MODs
  2321. if (mod.boundPropertiesMask === 0 && mod.monitoredIntermediateMask === 0) {
  2322. // Unregister the observer on Property Change
  2323. mod.monitoredObject.propertyChanged.remove(mod.observer);
  2324. // Remove the MOD from the dic
  2325. var objectId = BindingHelper._getObjectId(mod.monitoredObject);
  2326. BindingHelper._monitoredObjects.remove(objectId);
  2327. }
  2328. return res;
  2329. };
  2330. BindingHelper._getMonitoredObjectData = function (object) {
  2331. var objectId = BindingHelper._getObjectId(object);
  2332. var mod = BindingHelper._monitoredObjects.getOrAddWithFactory(objectId, function (k) { return new MonitoredObjectData(object); });
  2333. return mod;
  2334. };
  2335. BindingHelper._getObjectId = function (obj) {
  2336. var id = obj["__bindingHelperObjectId__"];
  2337. if (id == null) {
  2338. id = BABYLON.Tools.RandomId();
  2339. obj["__bindingHelperObjectId__"] = id;
  2340. return id;
  2341. }
  2342. return id;
  2343. };
  2344. BindingHelper._getObjectTypePropertyIDs = function (obj) {
  2345. var fullName = BABYLON.Tools.getFullClassName(obj);
  2346. if (!fullName) {
  2347. throw Error("Types involved in Data Binding must be decorated with the @className decorator");
  2348. }
  2349. var d = BindingHelper._propertiesID.getOrAddWithFactory(fullName, function () { return new BABYLON.StringDictionary(); });
  2350. return d;
  2351. };
  2352. BindingHelper._getPropertyID = function (object, propName) {
  2353. var otd = BindingHelper._getObjectTypePropertyIDs(object);
  2354. // Make sure we have a WatchedPropertyData for this property of this object type. This will contains the flagIg of the watched property.
  2355. // We use this flagId to flag for each watched instance which properties are watched, as final or intermediate and which directions are used
  2356. var propData = otd.getOrAddWithFactory(propName, function (k) { return 1 << otd.count; });
  2357. return propData;
  2358. };
  2359. BindingHelper._propertiesID = new BABYLON.StringDictionary();
  2360. BindingHelper._monitoredObjects = new BABYLON.StringDictionary();
  2361. return BindingHelper;
  2362. }());
  2363. var SmartPropertyPrim = (function (_super) {
  2364. __extends(SmartPropertyPrim, _super);
  2365. function SmartPropertyPrim() {
  2366. _super.call(this);
  2367. this._flags = 0;
  2368. this._modelKey = null;
  2369. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  2370. this._boundingInfo = new BABYLON.BoundingInfo2D();
  2371. this.animations = new Array();
  2372. }
  2373. /**
  2374. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  2375. * @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.
  2376. */
  2377. SmartPropertyPrim.prototype.dispose = function () {
  2378. if (this.isDisposed) {
  2379. return false;
  2380. }
  2381. _super.prototype.dispose.call(this);
  2382. // Don't set to null, it may upset somebody...
  2383. this.animations.splice(0);
  2384. return true;
  2385. };
  2386. /**
  2387. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  2388. * Look at Sprite2D for more information
  2389. */
  2390. SmartPropertyPrim.prototype.getAnimatables = function () {
  2391. return new Array();
  2392. };
  2393. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  2394. /**
  2395. * Property giving the Model Key associated to the property.
  2396. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  2397. * @returns the model key string.
  2398. */
  2399. get: function () {
  2400. var _this = this;
  2401. // No need to compute it?
  2402. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  2403. return this._modelKey;
  2404. }
  2405. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  2406. var propDic = this.propDic;
  2407. propDic.forEach(function (k, v) {
  2408. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  2409. var propVal = _this[v.name];
  2410. // 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
  2411. if (propVal && propVal.constructor === Array) {
  2412. var firstVal = propVal[0];
  2413. if (!firstVal) {
  2414. propVal = 0;
  2415. }
  2416. else {
  2417. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  2418. }
  2419. }
  2420. var value = "[null]";
  2421. if (propVal != null) {
  2422. if (v.typeLevelCompare) {
  2423. value = BABYLON.Tools.getClassName(propVal);
  2424. }
  2425. else {
  2426. if (propVal instanceof BABYLON.BaseTexture) {
  2427. value = propVal.uid;
  2428. }
  2429. else {
  2430. value = propVal.toString();
  2431. }
  2432. }
  2433. }
  2434. modelKey += v.name + ":" + value + ";";
  2435. }
  2436. });
  2437. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  2438. this._modelKey = modelKey;
  2439. return modelKey;
  2440. },
  2441. enumerable: true,
  2442. configurable: true
  2443. });
  2444. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  2445. /**
  2446. * States if the Primitive is dirty and should be rendered again next time.
  2447. * @returns true is dirty, false otherwise
  2448. */
  2449. get: function () {
  2450. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  2451. },
  2452. enumerable: true,
  2453. configurable: true
  2454. });
  2455. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  2456. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  2457. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  2458. if (this instanceof BABYLON.Prim2DBase) {
  2459. var curprim = this;
  2460. while (curprim) {
  2461. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  2462. if (curprim.isSizeAuto) {
  2463. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  2464. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  2465. }
  2466. if (curprim instanceof BABYLON.Group2D) {
  2467. if (curprim.isRenderableGroup) {
  2468. break;
  2469. }
  2470. }
  2471. curprim = curprim.parent;
  2472. }
  2473. }
  2474. };
  2475. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  2476. _super.prototype._handlePropChanged.call(this, curValue, newValue, propName, propInfo, typeLevelCompare);
  2477. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  2478. if (propInfo.dirtyBoundingInfo) {
  2479. this._boundingBoxDirty();
  2480. }
  2481. else if (propInfo.dirtyParentBoundingInfo) {
  2482. var p = this._parent;
  2483. if (p != null) {
  2484. p._boundingBoxDirty();
  2485. }
  2486. }
  2487. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  2488. if (this instanceof BABYLON.Group2D && this._renderableData) {
  2489. this.handleGroupChanged(propInfo);
  2490. }
  2491. // Check for parent layout dirty
  2492. if (this instanceof BABYLON.Prim2DBase) {
  2493. var p = this._parent;
  2494. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  2495. p._setLayoutDirty();
  2496. }
  2497. }
  2498. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  2499. var instanceDirty = false;
  2500. if (typeLevelCompare && curValue != null && newValue != null) {
  2501. var cvProto = curValue.__proto__;
  2502. var nvProto = newValue.__proto__;
  2503. instanceDirty = (cvProto === nvProto);
  2504. }
  2505. // Set the dirty flags
  2506. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  2507. if (!this.isDirty) {
  2508. this._setFlags(SmartPropertyPrim.flagModelDirty);
  2509. }
  2510. }
  2511. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  2512. var propMask = propInfo.flagId;
  2513. this.onPrimitivePropertyDirty(propMask);
  2514. }
  2515. };
  2516. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  2517. this.onPrimBecomesDirty();
  2518. this._instanceDirtyFlags |= propFlagId;
  2519. };
  2520. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  2521. };
  2522. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  2523. _super.prototype._resetPropertiesDirty.call(this);
  2524. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList | SmartPropertyPrim.flagNeedRefresh);
  2525. };
  2526. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  2527. /**
  2528. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  2529. */
  2530. get: function () {
  2531. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  2532. this.updateLevelBoundingInfo();
  2533. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  2534. }
  2535. return this._levelBoundingInfo;
  2536. },
  2537. enumerable: true,
  2538. configurable: true
  2539. });
  2540. /**
  2541. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  2542. */
  2543. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  2544. };
  2545. /**
  2546. * Property method called when the Primitive becomes dirty
  2547. */
  2548. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  2549. };
  2550. /**
  2551. * Check if a given flag is set
  2552. * @param flag the flag value
  2553. * @return true if set, false otherwise
  2554. */
  2555. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  2556. return (this._flags & flag) !== 0;
  2557. };
  2558. /**
  2559. * Check if all given flags are set
  2560. * @param flags the flags ORed
  2561. * @return true if all the flags are set, false otherwise
  2562. */
  2563. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  2564. return (this._flags & flags) === flags;
  2565. };
  2566. /**
  2567. * Check if at least one flag of the given flags is set
  2568. * @param flags the flags ORed
  2569. * @return true if at least one flag is set, false otherwise
  2570. */
  2571. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  2572. return (this._flags & flags) !== 0;
  2573. };
  2574. /**
  2575. * Clear the given flags
  2576. * @param flags the flags to clear
  2577. */
  2578. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  2579. this._flags &= ~flags;
  2580. };
  2581. /**
  2582. * Set the given flags to true state
  2583. * @param flags the flags ORed to set
  2584. * @return the flags state before this call
  2585. */
  2586. SmartPropertyPrim.prototype._setFlags = function (flags) {
  2587. var cur = this._flags;
  2588. this._flags |= flags;
  2589. return cur;
  2590. };
  2591. /**
  2592. * Change the state of the given flags
  2593. * @param flags the flags ORed to change
  2594. * @param state true to set them, false to clear them
  2595. */
  2596. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  2597. if (state) {
  2598. this._flags |= flags;
  2599. }
  2600. else {
  2601. this._flags &= ~flags;
  2602. }
  2603. };
  2604. SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT = 0;
  2605. SmartPropertyPrim.flagNoPartOfLayout = 0x0000001; // set if the primitive's position/size must not be computed by Layout Engine
  2606. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  2607. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  2608. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  2609. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  2610. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  2611. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  2612. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  2613. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  2614. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  2615. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  2616. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  2617. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  2618. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  2619. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  2620. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  2621. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  2622. SmartPropertyPrim.flagNeedRefresh = 0x0020000; // set if the primitive wasn't successful at refresh
  2623. SmartPropertyPrim.flagActualScaleDirty = 0x0040000; // set if the actualScale property needs to be recomputed
  2624. SmartPropertyPrim.flagDontInheritParentScale = 0x0080000; // set if the actualScale must not use its parent's scale to be computed
  2625. SmartPropertyPrim.flagGlobalTransformDirty = 0x0100000; // set if the global transform must be recomputed due to a local transform change
  2626. SmartPropertyPrim.flagLayoutBoundingInfoDirty = 0x0200000; // set if the layout bounding info is dirty
  2627. SmartPropertyPrim = __decorate([
  2628. BABYLON.className("SmartPropertyPrim", "BABYLON")
  2629. ], SmartPropertyPrim);
  2630. return SmartPropertyPrim;
  2631. }(SmartPropertyBase));
  2632. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  2633. function dependencyProperty(propId, piStore, mode, updateSourceTrigger) {
  2634. if (mode === void 0) { mode = DataBinding.MODE_TWOWAY; }
  2635. if (updateSourceTrigger === void 0) { updateSourceTrigger = DataBinding.UPDATESOURCETRIGGER_PROPERTYCHANGED; }
  2636. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { bindingMode: mode, bindingUpdateSourceTrigger: updateSourceTrigger });
  2637. }
  2638. BABYLON.dependencyProperty = dependencyProperty;
  2639. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  2640. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  2641. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  2642. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  2643. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_MODEL, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  2644. }
  2645. BABYLON.modelLevelProperty = modelLevelProperty;
  2646. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  2647. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  2648. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  2649. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  2650. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_INSTANCE, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  2651. }
  2652. BABYLON.instanceLevelProperty = instanceLevelProperty;
  2653. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  2654. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  2655. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  2656. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  2657. return SmartPropertyBase._hookProperty(propId, piStore, Prim2DPropInfo.PROPKIND_DYNAMIC, { typeLevelCompare: typeLevelCompare, dirtyBoundingInfo: dirtyBoundingInfo, dirtyParentBoundingBox: dirtyParentBoundingBox });
  2658. }
  2659. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  2660. })(BABYLON || (BABYLON = {}));
  2661. var BABYLON;
  2662. (function (BABYLON) {
  2663. var PrepareRender2DContext = (function () {
  2664. function PrepareRender2DContext() {
  2665. this.forceRefreshPrimitive = false;
  2666. }
  2667. return PrepareRender2DContext;
  2668. }());
  2669. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  2670. var Render2DContext = (function () {
  2671. function Render2DContext(renderMode) {
  2672. this._renderMode = renderMode;
  2673. this.useInstancing = false;
  2674. this.groupInfoPartData = null;
  2675. this.partDataStartIndex = this.partDataEndIndex = null;
  2676. this.instancedBuffers = null;
  2677. }
  2678. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  2679. /**
  2680. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  2681. */
  2682. get: function () {
  2683. return this._renderMode;
  2684. },
  2685. enumerable: true,
  2686. configurable: true
  2687. });
  2688. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  2689. /**
  2690. * The set of primitives to render is opaque.
  2691. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  2692. */
  2693. get: function () {
  2694. return Render2DContext._renderModeOpaque;
  2695. },
  2696. enumerable: true,
  2697. configurable: true
  2698. });
  2699. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  2700. /**
  2701. * The set of primitives to render is using Alpha Test (aka masking).
  2702. * 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.
  2703. */
  2704. get: function () {
  2705. return Render2DContext._renderModeAlphaTest;
  2706. },
  2707. enumerable: true,
  2708. configurable: true
  2709. });
  2710. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  2711. /**
  2712. * The set of primitives to render is transparent.
  2713. * 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.
  2714. */
  2715. get: function () {
  2716. return Render2DContext._renderModeTransparent;
  2717. },
  2718. enumerable: true,
  2719. configurable: true
  2720. });
  2721. Render2DContext._renderModeOpaque = 1;
  2722. Render2DContext._renderModeAlphaTest = 2;
  2723. Render2DContext._renderModeTransparent = 3;
  2724. return Render2DContext;
  2725. }());
  2726. BABYLON.Render2DContext = Render2DContext;
  2727. /**
  2728. * This class store information for the pointerEventObservable Observable.
  2729. * 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.
  2730. */
  2731. var PrimitivePointerInfo = (function () {
  2732. function PrimitivePointerInfo() {
  2733. this.primitivePointerPos = BABYLON.Vector2.Zero();
  2734. this.tilt = BABYLON.Vector2.Zero();
  2735. this.cancelBubble = false;
  2736. }
  2737. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  2738. // 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.
  2739. /**
  2740. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  2741. * Bubbles: yes
  2742. */
  2743. get: function () {
  2744. return PrimitivePointerInfo._pointerOver;
  2745. },
  2746. enumerable: true,
  2747. configurable: true
  2748. });
  2749. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  2750. /**
  2751. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  2752. * Bubbles: no
  2753. */
  2754. get: function () {
  2755. return PrimitivePointerInfo._pointerEnter;
  2756. },
  2757. enumerable: true,
  2758. configurable: true
  2759. });
  2760. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  2761. /**
  2762. * 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.
  2763. * Bubbles: yes
  2764. */
  2765. get: function () {
  2766. return PrimitivePointerInfo._pointerDown;
  2767. },
  2768. enumerable: true,
  2769. configurable: true
  2770. });
  2771. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  2772. /**
  2773. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  2774. * Bubbles: yes
  2775. */
  2776. get: function () {
  2777. return PrimitivePointerInfo._pointerMouseWheel;
  2778. },
  2779. enumerable: true,
  2780. configurable: true
  2781. });
  2782. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  2783. /**
  2784. * 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.
  2785. * Bubbles: yes
  2786. */
  2787. get: function () {
  2788. return PrimitivePointerInfo._pointerMove;
  2789. },
  2790. enumerable: true,
  2791. configurable: true
  2792. });
  2793. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  2794. /**
  2795. * 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.
  2796. * Bubbles: yes
  2797. */
  2798. get: function () {
  2799. return PrimitivePointerInfo._pointerUp;
  2800. },
  2801. enumerable: true,
  2802. configurable: true
  2803. });
  2804. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  2805. /**
  2806. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  2807. * Bubbles: yes
  2808. */
  2809. get: function () {
  2810. return PrimitivePointerInfo._pointerOut;
  2811. },
  2812. enumerable: true,
  2813. configurable: true
  2814. });
  2815. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  2816. /**
  2817. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  2818. * Bubbles: no
  2819. */
  2820. get: function () {
  2821. return PrimitivePointerInfo._pointerLeave;
  2822. },
  2823. enumerable: true,
  2824. configurable: true
  2825. });
  2826. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  2827. /**
  2828. * 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.
  2829. * Bubbles: yes
  2830. */
  2831. get: function () {
  2832. return PrimitivePointerInfo._pointerGotCapture;
  2833. },
  2834. enumerable: true,
  2835. configurable: true
  2836. });
  2837. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  2838. /**
  2839. * This event type is raised after pointer capture is released for a pointer.
  2840. * Bubbles: yes
  2841. */
  2842. get: function () {
  2843. return PrimitivePointerInfo._pointerLostCapture;
  2844. },
  2845. enumerable: true,
  2846. configurable: true
  2847. });
  2848. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  2849. get: function () {
  2850. return PrimitivePointerInfo._mouseWheelPrecision;
  2851. },
  2852. enumerable: true,
  2853. configurable: true
  2854. });
  2855. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  2856. this.relatedTarget = prim;
  2857. this.relatedTargetPointerPos = primPointerPos;
  2858. };
  2859. PrimitivePointerInfo.getEventTypeName = function (mask) {
  2860. switch (mask) {
  2861. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  2862. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  2863. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  2864. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  2865. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  2866. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  2867. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  2868. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  2869. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  2870. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  2871. }
  2872. };
  2873. PrimitivePointerInfo._pointerOver = 0x0001;
  2874. PrimitivePointerInfo._pointerEnter = 0x0002;
  2875. PrimitivePointerInfo._pointerDown = 0x0004;
  2876. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  2877. PrimitivePointerInfo._pointerMove = 0x0010;
  2878. PrimitivePointerInfo._pointerUp = 0x0020;
  2879. PrimitivePointerInfo._pointerOut = 0x0040;
  2880. PrimitivePointerInfo._pointerLeave = 0x0080;
  2881. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  2882. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  2883. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  2884. return PrimitivePointerInfo;
  2885. }());
  2886. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  2887. /**
  2888. * Defines the horizontal and vertical alignment information for a Primitive.
  2889. */
  2890. var PrimitiveAlignment = (function () {
  2891. function PrimitiveAlignment(changeCallback) {
  2892. this._changedCallback = changeCallback;
  2893. this._horizontal = PrimitiveAlignment.AlignLeft;
  2894. this._vertical = PrimitiveAlignment.AlignBottom;
  2895. }
  2896. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  2897. /**
  2898. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  2899. */
  2900. get: function () { return PrimitiveAlignment._AlignLeft; },
  2901. enumerable: true,
  2902. configurable: true
  2903. });
  2904. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  2905. /**
  2906. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  2907. */
  2908. get: function () { return PrimitiveAlignment._AlignTop; },
  2909. enumerable: true,
  2910. configurable: true
  2911. });
  2912. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  2913. /**
  2914. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  2915. */
  2916. get: function () { return PrimitiveAlignment._AlignRight; },
  2917. enumerable: true,
  2918. configurable: true
  2919. });
  2920. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  2921. /**
  2922. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  2923. */
  2924. get: function () { return PrimitiveAlignment._AlignBottom; },
  2925. enumerable: true,
  2926. configurable: true
  2927. });
  2928. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  2929. /**
  2930. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  2931. */
  2932. get: function () { return PrimitiveAlignment._AlignCenter; },
  2933. enumerable: true,
  2934. configurable: true
  2935. });
  2936. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  2937. /**
  2938. * The content is stretched toward the opposite edges of the Primitive
  2939. */
  2940. get: function () { return PrimitiveAlignment._AlignStretch; },
  2941. enumerable: true,
  2942. configurable: true
  2943. });
  2944. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  2945. /**
  2946. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  2947. */
  2948. get: function () {
  2949. return this._horizontal;
  2950. },
  2951. set: function (value) {
  2952. if (this._horizontal === value) {
  2953. return;
  2954. }
  2955. this._horizontal = value;
  2956. this.onChangeCallback();
  2957. },
  2958. enumerable: true,
  2959. configurable: true
  2960. });
  2961. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  2962. /**
  2963. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  2964. */
  2965. get: function () {
  2966. return this._vertical;
  2967. },
  2968. set: function (value) {
  2969. if (this._vertical === value) {
  2970. return;
  2971. }
  2972. this._vertical = value;
  2973. this.onChangeCallback();
  2974. },
  2975. enumerable: true,
  2976. configurable: true
  2977. });
  2978. PrimitiveAlignment.prototype.onChangeCallback = function () {
  2979. if (this._changedCallback) {
  2980. this._changedCallback();
  2981. }
  2982. };
  2983. /**
  2984. * Set the horizontal alignment from a string value.
  2985. * @param text can be either: 'left','right','center','stretch'
  2986. */
  2987. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  2988. var v = text.trim().toLocaleLowerCase();
  2989. switch (v) {
  2990. case "left":
  2991. this.horizontal = PrimitiveAlignment.AlignLeft;
  2992. return;
  2993. case "right":
  2994. this.horizontal = PrimitiveAlignment.AlignRight;
  2995. return;
  2996. case "center":
  2997. this.horizontal = PrimitiveAlignment.AlignCenter;
  2998. return;
  2999. case "stretch":
  3000. this.horizontal = PrimitiveAlignment.AlignStretch;
  3001. return;
  3002. }
  3003. };
  3004. /**
  3005. * Set the vertical alignment from a string value.
  3006. * @param text can be either: 'top','bottom','center','stretch'
  3007. */
  3008. PrimitiveAlignment.prototype.setVertical = function (text) {
  3009. var v = text.trim().toLocaleLowerCase();
  3010. switch (v) {
  3011. case "top":
  3012. this.vertical = PrimitiveAlignment.AlignTop;
  3013. return;
  3014. case "bottom":
  3015. this.vertical = PrimitiveAlignment.AlignBottom;
  3016. return;
  3017. case "center":
  3018. this.vertical = PrimitiveAlignment.AlignCenter;
  3019. return;
  3020. case "stretch":
  3021. this.vertical = PrimitiveAlignment.AlignStretch;
  3022. return;
  3023. }
  3024. };
  3025. /**
  3026. * Set the horizontal and or vertical alignments from a string value.
  3027. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  3028. */
  3029. PrimitiveAlignment.prototype.fromString = function (value) {
  3030. var m = value.trim().split(",");
  3031. if (m.length === 1) {
  3032. this.setHorizontal(m[0]);
  3033. this.setVertical(m[0]);
  3034. }
  3035. else {
  3036. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  3037. var v = m_1[_i];
  3038. v = v.toLocaleLowerCase().trim();
  3039. // Horizontal
  3040. var i = v.indexOf("h:");
  3041. if (i === -1) {
  3042. i = v.indexOf("horizontal:");
  3043. }
  3044. if (i !== -1) {
  3045. v = v.substr(v.indexOf(":") + 1);
  3046. this.setHorizontal(v);
  3047. continue;
  3048. }
  3049. // Vertical
  3050. i = v.indexOf("v:");
  3051. if (i === -1) {
  3052. i = v.indexOf("vertical:");
  3053. }
  3054. if (i !== -1) {
  3055. v = v.substr(v.indexOf(":") + 1);
  3056. this.setVertical(v);
  3057. continue;
  3058. }
  3059. }
  3060. }
  3061. };
  3062. PrimitiveAlignment.prototype.copyFrom = function (pa) {
  3063. this._horizontal = pa._horizontal;
  3064. this._vertical = pa._vertical;
  3065. this.onChangeCallback();
  3066. };
  3067. Object.defineProperty(PrimitiveAlignment.prototype, "isDefault", {
  3068. get: function () {
  3069. return this.horizontal === PrimitiveAlignment.AlignLeft && this.vertical === PrimitiveAlignment.AlignBottom;
  3070. },
  3071. enumerable: true,
  3072. configurable: true
  3073. });
  3074. PrimitiveAlignment._AlignLeft = 1;
  3075. PrimitiveAlignment._AlignTop = 1; // Same as left
  3076. PrimitiveAlignment._AlignRight = 2;
  3077. PrimitiveAlignment._AlignBottom = 2; // Same as right
  3078. PrimitiveAlignment._AlignCenter = 3;
  3079. PrimitiveAlignment._AlignStretch = 4;
  3080. PrimitiveAlignment = __decorate([
  3081. BABYLON.className("PrimitiveAlignment", "BABYLON")
  3082. ], PrimitiveAlignment);
  3083. return PrimitiveAlignment;
  3084. }());
  3085. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  3086. /**
  3087. * Stores information about a Primitive that was intersected
  3088. */
  3089. var PrimitiveIntersectedInfo = (function () {
  3090. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  3091. this.prim = prim;
  3092. this.intersectionLocation = intersectionLocation;
  3093. }
  3094. return PrimitiveIntersectedInfo;
  3095. }());
  3096. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  3097. /**
  3098. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  3099. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  3100. */
  3101. var PrimitiveThickness = (function () {
  3102. function PrimitiveThickness(parentAccess, changedCallback) {
  3103. this._parentAccess = parentAccess;
  3104. this._changedCallback = changedCallback;
  3105. this._pixels = new Array(4);
  3106. this._percentages = new Array(4);
  3107. this._setType(0, PrimitiveThickness.Auto);
  3108. this._setType(1, PrimitiveThickness.Auto);
  3109. this._setType(2, PrimitiveThickness.Auto);
  3110. this._setType(3, PrimitiveThickness.Auto);
  3111. this._pixels[0] = 0;
  3112. this._pixels[1] = 0;
  3113. this._pixels[2] = 0;
  3114. this._pixels[3] = 0;
  3115. }
  3116. /**
  3117. * Set the thickness from a string value
  3118. * @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.
  3119. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  3120. */
  3121. PrimitiveThickness.prototype.fromString = function (thickness) {
  3122. this._clear();
  3123. var m = thickness.trim().split(",");
  3124. // Special case, one value to apply to all edges
  3125. if (m.length === 1 && thickness.indexOf(":") === -1) {
  3126. this._setStringValue(m[0], 0, false);
  3127. this._setStringValue(m[0], 1, false);
  3128. this._setStringValue(m[0], 2, false);
  3129. this._setStringValue(m[0], 3, false);
  3130. this.onChangeCallback();
  3131. return;
  3132. }
  3133. var res = false;
  3134. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  3135. var cm = m_2[_i];
  3136. res = this._extractString(cm, false) || res;
  3137. }
  3138. if (!res) {
  3139. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  3140. }
  3141. // Check the margin that weren't set and set them in auto
  3142. if ((this._flags & 0x000F) === 0)
  3143. this._flags |= PrimitiveThickness.Pixel << 0;
  3144. if ((this._flags & 0x00F0) === 0)
  3145. this._flags |= PrimitiveThickness.Pixel << 4;
  3146. if ((this._flags & 0x0F00) === 0)
  3147. this._flags |= PrimitiveThickness.Pixel << 8;
  3148. if ((this._flags & 0xF000) === 0)
  3149. this._flags |= PrimitiveThickness.Pixel << 12;
  3150. this.onChangeCallback();
  3151. };
  3152. /**
  3153. * Set the thickness from multiple string
  3154. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  3155. * @param top the top thickness to set
  3156. * @param left the left thickness to set
  3157. * @param right the right thickness to set
  3158. * @param bottom the bottom thickness to set
  3159. */
  3160. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  3161. this._clear();
  3162. this._setStringValue(top, 0, false);
  3163. this._setStringValue(left, 1, false);
  3164. this._setStringValue(right, 2, false);
  3165. this._setStringValue(bottom, 3, false);
  3166. this.onChangeCallback();
  3167. return this;
  3168. };
  3169. /**
  3170. * Set the thickness from pixel values
  3171. * @param top the top thickness in pixels to set
  3172. * @param left the left thickness in pixels to set
  3173. * @param right the right thickness in pixels to set
  3174. * @param bottom the bottom thickness in pixels to set
  3175. */
  3176. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  3177. this._clear();
  3178. this._pixels[0] = top;
  3179. this._pixels[1] = left;
  3180. this._pixels[2] = right;
  3181. this._pixels[3] = bottom;
  3182. this.onChangeCallback();
  3183. return this;
  3184. };
  3185. /**
  3186. * Apply the same pixel value to all edges
  3187. * @param margin the value to set, in pixels.
  3188. */
  3189. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  3190. this._clear();
  3191. this._pixels[0] = margin;
  3192. this._pixels[1] = margin;
  3193. this._pixels[2] = margin;
  3194. this._pixels[3] = margin;
  3195. this.onChangeCallback();
  3196. return this;
  3197. };
  3198. PrimitiveThickness.prototype.copyFrom = function (pt) {
  3199. this._clear();
  3200. for (var i = 0; i < 4; i++) {
  3201. this._pixels[i] = pt._pixels[i];
  3202. this._percentages[i] = pt._percentages[i];
  3203. }
  3204. this._flags = pt._flags;
  3205. this.onChangeCallback();
  3206. };
  3207. /**
  3208. * Set all edges in auto
  3209. */
  3210. PrimitiveThickness.prototype.auto = function () {
  3211. this._clear();
  3212. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  3213. this._pixels[0] = 0;
  3214. this._pixels[1] = 0;
  3215. this._pixels[2] = 0;
  3216. this._pixels[3] = 0;
  3217. this.onChangeCallback();
  3218. return this;
  3219. };
  3220. PrimitiveThickness.prototype._clear = function () {
  3221. this._flags = 0;
  3222. this._pixels[0] = 0;
  3223. this._pixels[1] = 0;
  3224. this._pixels[2] = 0;
  3225. this._pixels[3] = 0;
  3226. this._percentages[0] = null;
  3227. this._percentages[1] = null;
  3228. this._percentages[2] = null;
  3229. this._percentages[3] = null;
  3230. };
  3231. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  3232. var v = value.trim().toLocaleLowerCase();
  3233. if (v.indexOf("top:") === 0) {
  3234. v = v.substr(4).trim();
  3235. return this._setStringValue(v, 0, emitChanged);
  3236. }
  3237. if (v.indexOf("left:") === 0) {
  3238. v = v.substr(5).trim();
  3239. return this._setStringValue(v, 1, emitChanged);
  3240. }
  3241. if (v.indexOf("right:") === 0) {
  3242. v = v.substr(6).trim();
  3243. return this._setStringValue(v, 2, emitChanged);
  3244. }
  3245. if (v.indexOf("bottom:") === 0) {
  3246. v = v.substr(7).trim();
  3247. return this._setStringValue(v, 3, emitChanged);
  3248. }
  3249. return false;
  3250. };
  3251. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  3252. // Check for auto
  3253. var v = value.trim().toLocaleLowerCase();
  3254. if (v === "auto") {
  3255. if (this._isType(index, PrimitiveThickness.Auto)) {
  3256. return true;
  3257. }
  3258. this._setType(index, PrimitiveThickness.Auto);
  3259. this._pixels[index] = 0;
  3260. if (emitChanged) {
  3261. this.onChangeCallback();
  3262. }
  3263. }
  3264. else if (v === "inherit") {
  3265. if (this._isType(index, PrimitiveThickness.Inherit)) {
  3266. return true;
  3267. }
  3268. this._setType(index, PrimitiveThickness.Inherit);
  3269. this._pixels[index] = null;
  3270. if (emitChanged) {
  3271. this.onChangeCallback();
  3272. }
  3273. }
  3274. else {
  3275. var pI = v.indexOf("%");
  3276. // Check for percentage
  3277. if (pI !== -1) {
  3278. var n_1 = v.substr(0, pI);
  3279. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  3280. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  3281. return true;
  3282. }
  3283. this._setType(index, PrimitiveThickness.Percentage);
  3284. if (isNaN(number_1)) {
  3285. return false;
  3286. }
  3287. this._percentages[index] = number_1;
  3288. if (emitChanged) {
  3289. this.onChangeCallback();
  3290. }
  3291. return true;
  3292. }
  3293. // Check for pixel
  3294. var n = void 0;
  3295. pI = v.indexOf("px");
  3296. if (pI !== -1) {
  3297. n = v.substr(0, pI).trim();
  3298. }
  3299. else {
  3300. n = v;
  3301. }
  3302. var number = Number(n);
  3303. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  3304. return true;
  3305. }
  3306. if (isNaN(number)) {
  3307. return false;
  3308. }
  3309. this._pixels[index] = number;
  3310. this._setType(index, PrimitiveThickness.Pixel);
  3311. if (emitChanged) {
  3312. this.onChangeCallback();
  3313. }
  3314. return true;
  3315. }
  3316. };
  3317. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  3318. // 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
  3319. value = Math.round(value);
  3320. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  3321. return;
  3322. }
  3323. this._setType(index, PrimitiveThickness.Pixel);
  3324. this._pixels[index] = value;
  3325. if (emitChanged) {
  3326. this.onChangeCallback();
  3327. }
  3328. };
  3329. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  3330. // Clip Value to bounds
  3331. value = Math.min(1, value);
  3332. value = Math.max(0, value);
  3333. value = Math.round(value * 100) / 100; // 0.01 precision
  3334. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  3335. return;
  3336. }
  3337. this._setType(index, PrimitiveThickness.Percentage);
  3338. this._percentages[index] = value;
  3339. if (emitChanged) {
  3340. this.onChangeCallback();
  3341. }
  3342. };
  3343. PrimitiveThickness.prototype._getStringValue = function (index) {
  3344. var f = (this._flags >> (index * 4)) & 0xF;
  3345. switch (f) {
  3346. case PrimitiveThickness.Auto:
  3347. return "auto";
  3348. case PrimitiveThickness.Pixel:
  3349. return this._pixels[index] + "px";
  3350. case PrimitiveThickness.Percentage:
  3351. return this._percentages[index] * 100 + "%";
  3352. case PrimitiveThickness.Inherit:
  3353. return "inherit";
  3354. }
  3355. return "";
  3356. };
  3357. PrimitiveThickness.prototype._isType = function (index, type) {
  3358. var f = (this._flags >> (index * 4)) & 0xF;
  3359. return f === type;
  3360. };
  3361. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  3362. var t = (this._flags >> (index * 4)) & 0xF;
  3363. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  3364. var p = this._parentAccess();
  3365. if (p) {
  3366. return p._getType(index, true);
  3367. }
  3368. return PrimitiveThickness.Auto;
  3369. }
  3370. return t;
  3371. };
  3372. PrimitiveThickness.prototype._setType = function (index, type) {
  3373. this._flags &= ~(0xF << (index * 4));
  3374. this._flags |= type << (index * 4);
  3375. };
  3376. PrimitiveThickness.prototype.setTop = function (value) {
  3377. if (typeof value === "string") {
  3378. this._setStringValue(value, 0, true);
  3379. }
  3380. else {
  3381. this.topPixels = value;
  3382. }
  3383. };
  3384. PrimitiveThickness.prototype.setLeft = function (value) {
  3385. if (typeof value === "string") {
  3386. this._setStringValue(value, 1, true);
  3387. }
  3388. else {
  3389. this.leftPixels = value;
  3390. }
  3391. };
  3392. PrimitiveThickness.prototype.setRight = function (value) {
  3393. if (typeof value === "string") {
  3394. this._setStringValue(value, 2, true);
  3395. }
  3396. else {
  3397. this.rightPixels = value;
  3398. }
  3399. };
  3400. PrimitiveThickness.prototype.setBottom = function (value) {
  3401. if (typeof value === "string") {
  3402. this._setStringValue(value, 3, true);
  3403. }
  3404. else {
  3405. this.bottomPixels = value;
  3406. }
  3407. };
  3408. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  3409. /**
  3410. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  3411. */
  3412. get: function () {
  3413. return this._getStringValue(0);
  3414. },
  3415. set: function (value) {
  3416. this._setStringValue(value, 0, true);
  3417. },
  3418. enumerable: true,
  3419. configurable: true
  3420. });
  3421. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  3422. /**
  3423. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  3424. */
  3425. get: function () {
  3426. return this._getStringValue(1);
  3427. },
  3428. set: function (value) {
  3429. this._setStringValue(value, 1, true);
  3430. },
  3431. enumerable: true,
  3432. configurable: true
  3433. });
  3434. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  3435. /**
  3436. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  3437. */
  3438. get: function () {
  3439. return this._getStringValue(2);
  3440. },
  3441. set: function (value) {
  3442. this._setStringValue(value, 2, true);
  3443. },
  3444. enumerable: true,
  3445. configurable: true
  3446. });
  3447. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  3448. /**
  3449. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  3450. */
  3451. get: function () {
  3452. return this._getStringValue(3);
  3453. },
  3454. set: function (value) {
  3455. this._setStringValue(value, 3, true);
  3456. },
  3457. enumerable: true,
  3458. configurable: true
  3459. });
  3460. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  3461. /**
  3462. * Get/set the top thickness in pixel.
  3463. */
  3464. get: function () {
  3465. return this._pixels[0];
  3466. },
  3467. set: function (value) {
  3468. this._setPixels(value, 0, true);
  3469. },
  3470. enumerable: true,
  3471. configurable: true
  3472. });
  3473. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  3474. /**
  3475. * Get/set the left thickness in pixel.
  3476. */
  3477. get: function () {
  3478. return this._pixels[1];
  3479. },
  3480. set: function (value) {
  3481. this._setPixels(value, 1, true);
  3482. },
  3483. enumerable: true,
  3484. configurable: true
  3485. });
  3486. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  3487. /**
  3488. * Get/set the right thickness in pixel.
  3489. */
  3490. get: function () {
  3491. return this._pixels[2];
  3492. },
  3493. set: function (value) {
  3494. this._setPixels(value, 2, true);
  3495. },
  3496. enumerable: true,
  3497. configurable: true
  3498. });
  3499. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  3500. /**
  3501. * Get/set the bottom thickness in pixel.
  3502. */
  3503. get: function () {
  3504. return this._pixels[3];
  3505. },
  3506. set: function (value) {
  3507. this._setPixels(value, 3, true);
  3508. },
  3509. enumerable: true,
  3510. configurable: true
  3511. });
  3512. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  3513. /**
  3514. * Get/set the top thickness in percentage.
  3515. * The get will return a valid value only if the edge type is percentage.
  3516. * The Set will change the edge mode if needed
  3517. */
  3518. get: function () {
  3519. return this._percentages[0];
  3520. },
  3521. set: function (value) {
  3522. this._setPercentage(value, 0, true);
  3523. },
  3524. enumerable: true,
  3525. configurable: true
  3526. });
  3527. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  3528. /**
  3529. * Get/set the left thickness in percentage.
  3530. * The get will return a valid value only if the edge mode is percentage.
  3531. * The Set will change the edge mode if needed
  3532. */
  3533. get: function () {
  3534. return this._percentages[1];
  3535. },
  3536. set: function (value) {
  3537. this._setPercentage(value, 1, true);
  3538. },
  3539. enumerable: true,
  3540. configurable: true
  3541. });
  3542. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  3543. /**
  3544. * Get/set the right thickness in percentage.
  3545. * The get will return a valid value only if the edge mode is percentage.
  3546. * The Set will change the edge mode if needed
  3547. */
  3548. get: function () {
  3549. return this._percentages[2];
  3550. },
  3551. set: function (value) {
  3552. this._setPercentage(value, 2, true);
  3553. },
  3554. enumerable: true,
  3555. configurable: true
  3556. });
  3557. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  3558. /**
  3559. * Get/set the bottom thickness in percentage.
  3560. * The get will return a valid value only if the edge mode is percentage.
  3561. * The Set will change the edge mode if needed
  3562. */
  3563. get: function () {
  3564. return this._percentages[3];
  3565. },
  3566. set: function (value) {
  3567. this._setPercentage(value, 3, true);
  3568. },
  3569. enumerable: true,
  3570. configurable: true
  3571. });
  3572. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  3573. /**
  3574. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  3575. */
  3576. get: function () {
  3577. return this._getType(0, false);
  3578. },
  3579. set: function (mode) {
  3580. this._setType(0, mode);
  3581. },
  3582. enumerable: true,
  3583. configurable: true
  3584. });
  3585. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  3586. /**
  3587. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  3588. */
  3589. get: function () {
  3590. return this._getType(1, false);
  3591. },
  3592. set: function (mode) {
  3593. this._setType(1, mode);
  3594. },
  3595. enumerable: true,
  3596. configurable: true
  3597. });
  3598. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  3599. /**
  3600. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  3601. */
  3602. get: function () {
  3603. return this._getType(2, false);
  3604. },
  3605. set: function (mode) {
  3606. this._setType(2, mode);
  3607. },
  3608. enumerable: true,
  3609. configurable: true
  3610. });
  3611. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  3612. /**
  3613. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  3614. */
  3615. get: function () {
  3616. return this._getType(3, false);
  3617. },
  3618. set: function (mode) {
  3619. this._setType(3, mode);
  3620. },
  3621. enumerable: true,
  3622. configurable: true
  3623. });
  3624. Object.defineProperty(PrimitiveThickness.prototype, "isDefault", {
  3625. get: function () {
  3626. return this._flags === 0x1111;
  3627. },
  3628. enumerable: true,
  3629. configurable: true
  3630. });
  3631. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  3632. var type = this._getType(index, false);
  3633. if (type === PrimitiveThickness.Inherit) {
  3634. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  3635. return;
  3636. }
  3637. if (type !== PrimitiveThickness.Percentage) {
  3638. return;
  3639. }
  3640. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  3641. this._pixels[index] = pixels;
  3642. if (emitChanged) {
  3643. this.onChangeCallback();
  3644. }
  3645. };
  3646. PrimitiveThickness.prototype.onChangeCallback = function () {
  3647. if (this._changedCallback) {
  3648. this._changedCallback();
  3649. }
  3650. };
  3651. /**
  3652. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  3653. * @param sourceArea the source area where the content must be sized/positioned
  3654. * @param contentSize the content size to position/resize
  3655. * @param alignment the alignment setting
  3656. * @param dstOffset the position of the content, x, y, z, w are left, bottom, right, top
  3657. * @param dstArea the new size of the content
  3658. */
  3659. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea, computeLayoutArea) {
  3660. if (computeLayoutArea === void 0) { computeLayoutArea = false; }
  3661. // Fetch some data
  3662. var topType = this._getType(0, true);
  3663. var leftType = this._getType(1, true);
  3664. var rightType = this._getType(2, true);
  3665. var bottomType = this._getType(3, true);
  3666. var hasWidth = contentSize && (contentSize.width != null);
  3667. var hasHeight = contentSize && (contentSize.height != null);
  3668. var width = hasWidth ? contentSize.width : 0;
  3669. var height = hasHeight ? contentSize.height : 0;
  3670. var isTopAuto = topType === PrimitiveThickness.Auto;
  3671. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  3672. var isRightAuto = rightType === PrimitiveThickness.Auto;
  3673. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  3674. switch (alignment.horizontal) {
  3675. case PrimitiveAlignment.AlignLeft:
  3676. {
  3677. if (isLeftAuto) {
  3678. dstOffset.x = 0;
  3679. }
  3680. else {
  3681. this._computePixels(1, sourceArea, true);
  3682. dstOffset.x = this.leftPixels;
  3683. }
  3684. dstArea.width = width;
  3685. if (computeLayoutArea) {
  3686. dstArea.width += this.leftPixels;
  3687. }
  3688. dstOffset.z = sourceArea.width - (dstOffset.x + width);
  3689. break;
  3690. }
  3691. case PrimitiveAlignment.AlignRight:
  3692. {
  3693. if (isRightAuto) {
  3694. dstOffset.x = Math.round(sourceArea.width - width);
  3695. }
  3696. else {
  3697. this._computePixels(2, sourceArea, true);
  3698. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  3699. }
  3700. dstArea.width = width;
  3701. if (computeLayoutArea) {
  3702. dstArea.width += this.rightPixels;
  3703. }
  3704. dstOffset.z = this.rightPixels;
  3705. break;
  3706. }
  3707. case PrimitiveAlignment.AlignStretch:
  3708. {
  3709. if (isLeftAuto) {
  3710. dstOffset.x = 0;
  3711. }
  3712. else {
  3713. this._computePixels(1, sourceArea, true);
  3714. dstOffset.x = this.leftPixels;
  3715. }
  3716. var right = 0;
  3717. if (!isRightAuto) {
  3718. this._computePixels(2, sourceArea, true);
  3719. right = this.rightPixels;
  3720. }
  3721. dstArea.width = sourceArea.width - (dstOffset.x + right);
  3722. dstOffset.z = this.rightPixels;
  3723. break;
  3724. }
  3725. case PrimitiveAlignment.AlignCenter:
  3726. {
  3727. if (!isLeftAuto) {
  3728. this._computePixels(1, sourceArea, true);
  3729. }
  3730. if (!isRightAuto) {
  3731. this._computePixels(2, sourceArea, true);
  3732. }
  3733. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  3734. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  3735. dstArea.width = width;
  3736. dstOffset.z = sourceArea.width - (dstOffset.x + width);
  3737. break;
  3738. }
  3739. }
  3740. switch (alignment.vertical) {
  3741. case PrimitiveAlignment.AlignTop:
  3742. {
  3743. if (isTopAuto) {
  3744. dstOffset.y = sourceArea.height - height;
  3745. }
  3746. else {
  3747. this._computePixels(0, sourceArea, true);
  3748. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  3749. }
  3750. dstArea.height = height;
  3751. if (computeLayoutArea) {
  3752. dstArea.height += this.topPixels;
  3753. }
  3754. dstOffset.w = this.topPixels;
  3755. break;
  3756. }
  3757. case PrimitiveAlignment.AlignBottom:
  3758. {
  3759. if (isBottomAuto) {
  3760. dstOffset.y = 0;
  3761. }
  3762. else {
  3763. this._computePixels(3, sourceArea, true);
  3764. dstOffset.y = this.bottomPixels;
  3765. }
  3766. dstArea.height = height;
  3767. if (computeLayoutArea) {
  3768. dstArea.height += this.bottomPixels;
  3769. }
  3770. dstOffset.w = sourceArea.height - (dstOffset.y + height);
  3771. break;
  3772. }
  3773. case PrimitiveAlignment.AlignStretch:
  3774. {
  3775. if (isBottomAuto) {
  3776. dstOffset.y = 0;
  3777. }
  3778. else {
  3779. this._computePixels(3, sourceArea, true);
  3780. dstOffset.y = this.bottomPixels;
  3781. }
  3782. var top_1 = 0;
  3783. if (!isTopAuto) {
  3784. this._computePixels(0, sourceArea, true);
  3785. top_1 = this.topPixels;
  3786. }
  3787. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  3788. dstOffset.w = this.topPixels;
  3789. break;
  3790. }
  3791. case PrimitiveAlignment.AlignCenter:
  3792. {
  3793. if (!isTopAuto) {
  3794. this._computePixels(0, sourceArea, true);
  3795. }
  3796. if (!isBottomAuto) {
  3797. this._computePixels(3, sourceArea, true);
  3798. }
  3799. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  3800. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  3801. dstArea.height = height;
  3802. dstOffset.w = sourceArea.height - (dstOffset.y + height);
  3803. break;
  3804. }
  3805. }
  3806. };
  3807. /**
  3808. * Compute an area and its position considering this thickness properties based on a given source area
  3809. * @param sourceArea the source area
  3810. * @param dstOffset the position of the resulting area
  3811. * @param dstArea the size of the resulting area
  3812. */
  3813. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  3814. this._computePixels(0, sourceArea, true);
  3815. this._computePixels(1, sourceArea, true);
  3816. this._computePixels(2, sourceArea, true);
  3817. this._computePixels(3, sourceArea, true);
  3818. dstOffset.x = this.leftPixels;
  3819. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  3820. dstOffset.y = this.bottomPixels;
  3821. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  3822. };
  3823. /**
  3824. * Compute an area considering this thickness properties based on a given source area
  3825. * @param sourceArea the source area
  3826. * @param result the resulting area
  3827. */
  3828. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  3829. this._computePixels(0, sourceArea, true);
  3830. this._computePixels(1, sourceArea, true);
  3831. this._computePixels(2, sourceArea, true);
  3832. this._computePixels(3, sourceArea, true);
  3833. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  3834. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  3835. };
  3836. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  3837. this._computePixels(0, sourceArea, true);
  3838. this._computePixels(1, sourceArea, true);
  3839. this._computePixels(2, sourceArea, true);
  3840. this._computePixels(3, sourceArea, true);
  3841. dstOffset.x = this.leftPixels;
  3842. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  3843. dstOffset.y = this.bottomPixels;
  3844. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  3845. };
  3846. PrimitiveThickness.Auto = 0x1;
  3847. PrimitiveThickness.Inherit = 0x2;
  3848. PrimitiveThickness.Percentage = 0x4;
  3849. PrimitiveThickness.Pixel = 0x8;
  3850. PrimitiveThickness = __decorate([
  3851. BABYLON.className("PrimitiveThickness", "BABYLON")
  3852. ], PrimitiveThickness);
  3853. return PrimitiveThickness;
  3854. }());
  3855. BABYLON.PrimitiveThickness = PrimitiveThickness;
  3856. /**
  3857. * Main class used for the Primitive Intersection API
  3858. */
  3859. var IntersectInfo2D = (function () {
  3860. function IntersectInfo2D() {
  3861. this.findFirstOnly = false;
  3862. this.intersectHidden = false;
  3863. this.pickPosition = BABYLON.Vector2.Zero();
  3864. }
  3865. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  3866. /**
  3867. * true if at least one primitive intersected during the test
  3868. */
  3869. get: function () {
  3870. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  3871. },
  3872. enumerable: true,
  3873. configurable: true
  3874. });
  3875. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  3876. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  3877. var cur = _a[_i];
  3878. if (cur.prim === prim) {
  3879. return cur.intersectionLocation;
  3880. }
  3881. }
  3882. return null;
  3883. };
  3884. // Internals, don't use
  3885. IntersectInfo2D.prototype._exit = function (firstLevel) {
  3886. if (firstLevel) {
  3887. this._globalPickPosition = null;
  3888. }
  3889. };
  3890. return IntersectInfo2D;
  3891. }());
  3892. BABYLON.IntersectInfo2D = IntersectInfo2D;
  3893. var Prim2DBase = (function (_super) {
  3894. __extends(Prim2DBase, _super);
  3895. function Prim2DBase(settings) {
  3896. // Avoid checking every time if the object exists
  3897. if (settings == null) {
  3898. settings = {};
  3899. }
  3900. // BASE CLASS CALL
  3901. _super.call(this);
  3902. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  3903. var owner;
  3904. var parent;
  3905. if (Prim2DBase._isCanvasInit) {
  3906. owner = this;
  3907. parent = null;
  3908. this._canvasPreInit(settings);
  3909. }
  3910. else {
  3911. if (settings.parent != null) {
  3912. parent = settings.parent;
  3913. owner = settings.parent.owner;
  3914. if (!owner) {
  3915. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  3916. }
  3917. 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)) {
  3918. 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");
  3919. }
  3920. }
  3921. }
  3922. // Fields initialization
  3923. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  3924. this._size = null; //Size.Zero();
  3925. this._scale = new BABYLON.Vector2(1, 1);
  3926. this._actualSize = null;
  3927. this._boundingSize = BABYLON.Size.Zero();
  3928. this._layoutArea = BABYLON.Size.Zero();
  3929. this._layoutAreaPos = null;
  3930. this._layoutBoundingInfo = null;
  3931. this._marginOffset = BABYLON.Vector4.Zero();
  3932. this._paddingOffset = BABYLON.Vector4.Zero();
  3933. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  3934. this._parentContentArea = BABYLON.Size.Zero();
  3935. this._lastAutoSizeArea = BABYLON.Size.Zero();
  3936. this._contentArea = new BABYLON.Size(null, null);
  3937. this._pointerEventObservable = new BABYLON.Observable();
  3938. this._boundingInfo = new BABYLON.BoundingInfo2D();
  3939. this._owner = owner;
  3940. this._parent = null;
  3941. this._margin = null;
  3942. this._padding = null;
  3943. this._marginAlignment = null;
  3944. this._id = settings.id;
  3945. this._children = new Array();
  3946. this._localTransform = new BABYLON.Matrix();
  3947. this._globalTransform = null;
  3948. this._invGlobalTransform = null;
  3949. this._globalTransformProcessStep = 0;
  3950. this._globalTransformStep = 0;
  3951. this._renderGroup = null;
  3952. this._primLinearPosition = 0;
  3953. this._manualZOrder = null;
  3954. this._zOrder = 0;
  3955. this._zMax = 0;
  3956. this._firstZDirtyIndex = Prim2DBase._bigInt;
  3957. this._actualOpacity = 0;
  3958. this._actualScale = BABYLON.Vector2.Zero();
  3959. this._displayDebugAreas = false;
  3960. this._debugAreaGroup = null;
  3961. var isPickable = true;
  3962. var isContainer = true;
  3963. if (settings.isPickable !== undefined) {
  3964. isPickable = settings.isPickable;
  3965. }
  3966. if (settings.isContainer !== undefined) {
  3967. isContainer = settings.isContainer;
  3968. }
  3969. if (settings.dontInheritParentScale) {
  3970. this._setFlags(BABYLON.SmartPropertyPrim.flagDontInheritParentScale);
  3971. }
  3972. this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0) | BABYLON.SmartPropertyPrim.flagActualScaleDirty | BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  3973. if (settings.opacity != null) {
  3974. this._opacity = settings.opacity;
  3975. }
  3976. else {
  3977. this._opacity = 1;
  3978. }
  3979. this._updateRenderMode();
  3980. if (settings.childrenFlatZOrder) {
  3981. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  3982. }
  3983. // If the parent is given, initialize the hierarchy/owner related data
  3984. if (parent != null) {
  3985. parent.addChild(this);
  3986. this._hierarchyDepth = parent._hierarchyDepth + 1;
  3987. this._patchHierarchy(parent.owner);
  3988. }
  3989. // If it's a group, detect its own states
  3990. if (this.owner && this instanceof BABYLON.Group2D) {
  3991. var group = this;
  3992. group.detectGroupStates();
  3993. }
  3994. // Time to insert children if some are specified
  3995. if (settings.children != null) {
  3996. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  3997. var child = _a[_i];
  3998. this.addChild(child);
  3999. // Good time to patch the hierarchy, it won't go very far if there's no need to
  4000. if (this.owner != null) {
  4001. child._patchHierarchy(this.owner);
  4002. }
  4003. }
  4004. }
  4005. if (settings.zOrder != null) {
  4006. this.zOrder = settings.zOrder;
  4007. }
  4008. // Set the model related properties
  4009. if (settings.position != null) {
  4010. this.position = settings.position;
  4011. }
  4012. else if (settings.x != null || settings.y != null) {
  4013. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  4014. }
  4015. else {
  4016. this._position = null;
  4017. }
  4018. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  4019. if (settings.scale != null) {
  4020. this.scale = settings.scale;
  4021. }
  4022. else {
  4023. if (settings.scaleX != null) {
  4024. this.scaleX = settings.scaleX;
  4025. }
  4026. if (settings.scaleY != null) {
  4027. this.scaleY = settings.scaleY;
  4028. }
  4029. }
  4030. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  4031. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  4032. // Layout Engine
  4033. if (settings.layoutEngine != null) {
  4034. if (typeof settings.layoutEngine === "string") {
  4035. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  4036. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  4037. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  4038. }
  4039. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  4040. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  4041. }
  4042. else if (name_1.indexOf("verticalstackpanel") === 0) {
  4043. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  4044. }
  4045. }
  4046. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  4047. this.layoutEngine = settings.layoutEngine;
  4048. }
  4049. }
  4050. // Set the layout/margin stuffs
  4051. if (settings.marginTop) {
  4052. this.margin.setTop(settings.marginTop);
  4053. }
  4054. if (settings.marginLeft) {
  4055. this.margin.setLeft(settings.marginLeft);
  4056. }
  4057. if (settings.marginRight) {
  4058. this.margin.setRight(settings.marginRight);
  4059. }
  4060. if (settings.marginBottom) {
  4061. this.margin.setBottom(settings.marginBottom);
  4062. }
  4063. if (settings.margin) {
  4064. if (typeof settings.margin === "string") {
  4065. this.margin.fromString(settings.margin);
  4066. }
  4067. else {
  4068. this.margin.fromUniformPixels(settings.margin);
  4069. }
  4070. }
  4071. if (settings.marginHAlignment) {
  4072. this.marginAlignment.horizontal = settings.marginHAlignment;
  4073. }
  4074. if (settings.marginVAlignment) {
  4075. this.marginAlignment.vertical = settings.marginVAlignment;
  4076. }
  4077. if (settings.marginAlignment) {
  4078. this.marginAlignment.fromString(settings.marginAlignment);
  4079. }
  4080. if (settings.paddingTop) {
  4081. this.padding.setTop(settings.paddingTop);
  4082. }
  4083. if (settings.paddingLeft) {
  4084. this.padding.setLeft(settings.paddingLeft);
  4085. }
  4086. if (settings.paddingRight) {
  4087. this.padding.setRight(settings.paddingRight);
  4088. }
  4089. if (settings.paddingBottom) {
  4090. this.padding.setBottom(settings.paddingBottom);
  4091. }
  4092. if (settings.padding) {
  4093. this.padding.fromString(settings.padding);
  4094. }
  4095. // Dirty layout and positioning
  4096. this._parentLayoutDirty();
  4097. this._positioningDirty();
  4098. }
  4099. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  4100. get: function () {
  4101. if (!this._actionManager) {
  4102. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  4103. }
  4104. return this._actionManager;
  4105. },
  4106. enumerable: true,
  4107. configurable: true
  4108. });
  4109. /**
  4110. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  4111. * @param predicate the predicate to test on each parent
  4112. * @return the first primitive where the predicate was successful
  4113. */
  4114. Prim2DBase.prototype.traverseUp = function (predicate) {
  4115. var p = this;
  4116. while (p != null) {
  4117. if (predicate(p)) {
  4118. return p;
  4119. }
  4120. p = p._parent;
  4121. }
  4122. return null;
  4123. };
  4124. Object.defineProperty(Prim2DBase.prototype, "owner", {
  4125. /**
  4126. * Retrieve the owner Canvas2D
  4127. */
  4128. get: function () {
  4129. return this._owner;
  4130. },
  4131. enumerable: true,
  4132. configurable: true
  4133. });
  4134. Object.defineProperty(Prim2DBase.prototype, "parent", {
  4135. /**
  4136. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  4137. */
  4138. get: function () {
  4139. return this._parent;
  4140. },
  4141. enumerable: true,
  4142. configurable: true
  4143. });
  4144. Object.defineProperty(Prim2DBase.prototype, "children", {
  4145. /**
  4146. * The array of direct children primitives
  4147. */
  4148. get: function () {
  4149. return this._children;
  4150. },
  4151. enumerable: true,
  4152. configurable: true
  4153. });
  4154. Object.defineProperty(Prim2DBase.prototype, "id", {
  4155. /**
  4156. * The identifier of this primitive, may not be unique, it's for information purpose only
  4157. */
  4158. get: function () {
  4159. return this._id;
  4160. },
  4161. set: function (value) {
  4162. if (this._id === value) {
  4163. return;
  4164. }
  4165. var oldValue = this._id;
  4166. this.onPropertyChanged("id", oldValue, this._id);
  4167. },
  4168. enumerable: true,
  4169. configurable: true
  4170. });
  4171. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  4172. get: function () {
  4173. if (this._actualPosition != null) {
  4174. return this._actualPosition;
  4175. }
  4176. if (this._position != null) {
  4177. return this._position;
  4178. }
  4179. // At least return 0,0, we can't return null on actualPosition
  4180. return Prim2DBase._nullPosition;
  4181. },
  4182. /**
  4183. * DO NOT INVOKE for internal purpose only
  4184. */
  4185. set: function (val) {
  4186. this._actualPosition = val;
  4187. },
  4188. enumerable: true,
  4189. configurable: true
  4190. });
  4191. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  4192. /**
  4193. * Shortcut to actualPosition.x
  4194. */
  4195. get: function () {
  4196. return this.actualPosition.x;
  4197. },
  4198. set: function (val) {
  4199. this._actualPosition.x = val;
  4200. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, this._actualPosition);
  4201. },
  4202. enumerable: true,
  4203. configurable: true
  4204. });
  4205. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  4206. /**
  4207. * Shortcut to actualPosition.y
  4208. */
  4209. get: function () {
  4210. return this.actualPosition.y;
  4211. },
  4212. set: function (val) {
  4213. this._actualPosition.y = val;
  4214. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, this._actualPosition);
  4215. },
  4216. enumerable: true,
  4217. configurable: true
  4218. });
  4219. Object.defineProperty(Prim2DBase.prototype, "position", {
  4220. /**
  4221. * Position of the primitive, relative to its parent.
  4222. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  4223. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  4224. * Setting this property may have no effect is specific alignment are in effect.
  4225. */
  4226. get: function () {
  4227. if (!this._position) {
  4228. this._position = BABYLON.Vector2.Zero();
  4229. }
  4230. return this._position;
  4231. },
  4232. set: function (value) {
  4233. if (!this._checkPositionChange()) {
  4234. return;
  4235. }
  4236. this._position = value;
  4237. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  4238. },
  4239. enumerable: true,
  4240. configurable: true
  4241. });
  4242. Object.defineProperty(Prim2DBase.prototype, "x", {
  4243. /**
  4244. * Direct access to the position.x value of the primitive
  4245. * Use this property when you only want to change one component of the position property
  4246. */
  4247. get: function () {
  4248. if (!this._position) {
  4249. return null;
  4250. }
  4251. return this._position.x;
  4252. },
  4253. set: function (value) {
  4254. if (!this._checkPositionChange()) {
  4255. return;
  4256. }
  4257. if (!this._position) {
  4258. this._position = BABYLON.Vector2.Zero();
  4259. }
  4260. if (this._position.x === value) {
  4261. return;
  4262. }
  4263. this._position.x = value;
  4264. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  4265. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  4266. },
  4267. enumerable: true,
  4268. configurable: true
  4269. });
  4270. Object.defineProperty(Prim2DBase.prototype, "y", {
  4271. /**
  4272. * Direct access to the position.y value of the primitive
  4273. * Use this property when you only want to change one component of the position property
  4274. */
  4275. get: function () {
  4276. if (!this._position) {
  4277. return null;
  4278. }
  4279. return this._position.y;
  4280. },
  4281. set: function (value) {
  4282. if (!this._checkPositionChange()) {
  4283. return;
  4284. }
  4285. if (!this._position) {
  4286. this._position = BABYLON.Vector2.Zero();
  4287. }
  4288. if (this._position.y === value) {
  4289. return;
  4290. }
  4291. this._position.y = value;
  4292. this._triggerPropertyChanged(Prim2DBase.positionProperty, value);
  4293. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, value);
  4294. },
  4295. enumerable: true,
  4296. configurable: true
  4297. });
  4298. Object.defineProperty(Prim2DBase.prototype, "size", {
  4299. /**
  4300. * Size of the primitive or its bounding area
  4301. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  4302. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  4303. */
  4304. get: function () {
  4305. if (!this._size || this._size.width == null || this._size.height == null) {
  4306. if (Prim2DBase.boundinbBoxReentrency) {
  4307. return Prim2DBase.nullSize;
  4308. }
  4309. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  4310. return this._boundingSize;
  4311. }
  4312. Prim2DBase.boundinbBoxReentrency = true;
  4313. var b = this.boundingInfo;
  4314. Prim2DBase.boundinbBoxReentrency = false;
  4315. return this._boundingSize;
  4316. }
  4317. return this._size;
  4318. },
  4319. set: function (value) {
  4320. this._size = value;
  4321. },
  4322. enumerable: true,
  4323. configurable: true
  4324. });
  4325. Object.defineProperty(Prim2DBase.prototype, "width", {
  4326. /**
  4327. * Direct access to the size.width value of the primitive
  4328. * Use this property when you only want to change one component of the size property
  4329. */
  4330. get: function () {
  4331. if (!this.size) {
  4332. return null;
  4333. }
  4334. return this.size.width;
  4335. },
  4336. set: function (value) {
  4337. if (this.size && this.size.width === value) {
  4338. return;
  4339. }
  4340. if (!this.size) {
  4341. this.size = new BABYLON.Size(value, 0);
  4342. }
  4343. else {
  4344. this.size.width = value;
  4345. }
  4346. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  4347. this._positioningDirty();
  4348. },
  4349. enumerable: true,
  4350. configurable: true
  4351. });
  4352. Object.defineProperty(Prim2DBase.prototype, "height", {
  4353. /**
  4354. * Direct access to the size.height value of the primitive
  4355. * Use this property when you only want to change one component of the size property
  4356. */
  4357. get: function () {
  4358. if (!this.size) {
  4359. return null;
  4360. }
  4361. return this.size.height;
  4362. },
  4363. set: function (value) {
  4364. if (this.size && this.size.height === value) {
  4365. return;
  4366. }
  4367. if (!this.size) {
  4368. this.size = new BABYLON.Size(0, value);
  4369. }
  4370. else {
  4371. this.size.height = value;
  4372. }
  4373. this._triggerPropertyChanged(Prim2DBase.sizeProperty, value);
  4374. this._positioningDirty();
  4375. },
  4376. enumerable: true,
  4377. configurable: true
  4378. });
  4379. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  4380. get: function () {
  4381. return this._rotation;
  4382. },
  4383. set: function (value) {
  4384. this._rotation = value;
  4385. },
  4386. enumerable: true,
  4387. configurable: true
  4388. });
  4389. Object.defineProperty(Prim2DBase.prototype, "scale", {
  4390. get: function () {
  4391. return this._scale.x;
  4392. },
  4393. set: function (value) {
  4394. this._scale.x = this._scale.y = value;
  4395. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  4396. this._spreadActualScaleDirty();
  4397. },
  4398. enumerable: true,
  4399. configurable: true
  4400. });
  4401. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  4402. /**
  4403. * Return the size of the primitive as it's being rendered into the target.
  4404. * 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.
  4405. * BEWARE: don't use the setter, it's for internal purpose only
  4406. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  4407. */
  4408. get: function () {
  4409. if (this._actualSize) {
  4410. return this._actualSize;
  4411. }
  4412. return this._size;
  4413. },
  4414. set: function (value) {
  4415. if (this._actualSize.equals(value)) {
  4416. return;
  4417. }
  4418. this._actualSize = value;
  4419. },
  4420. enumerable: true,
  4421. configurable: true
  4422. });
  4423. Object.defineProperty(Prim2DBase.prototype, "actualWidth", {
  4424. /**
  4425. * Shortcut to actualSize.width
  4426. */
  4427. get: function () {
  4428. return this.actualSize.width;
  4429. },
  4430. set: function (val) {
  4431. this._actualSize.width = val;
  4432. this._triggerPropertyChanged(Prim2DBase.actualSizeProperty, this._actualSize);
  4433. },
  4434. enumerable: true,
  4435. configurable: true
  4436. });
  4437. Object.defineProperty(Prim2DBase.prototype, "actualHeight", {
  4438. /**
  4439. * Shortcut to actualPosition.height
  4440. */
  4441. get: function () {
  4442. return this.actualSize.height;
  4443. },
  4444. set: function (val) {
  4445. this._actualSize.height = val;
  4446. this._triggerPropertyChanged(Prim2DBase.actualPositionProperty, this._actualSize);
  4447. },
  4448. enumerable: true,
  4449. configurable: true
  4450. });
  4451. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  4452. get: function () {
  4453. if (this._manualZOrder != null) {
  4454. return this._manualZOrder;
  4455. }
  4456. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  4457. this._updateZOrder();
  4458. }
  4459. return (1 - this._zOrder);
  4460. },
  4461. enumerable: true,
  4462. configurable: true
  4463. });
  4464. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  4465. /**
  4466. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  4467. * The Primitive's size won't be less than specified.
  4468. * The default value depends of the Primitive type
  4469. */
  4470. get: function () {
  4471. return this._minSize;
  4472. },
  4473. set: function (value) {
  4474. if (this._minSize && value && this._minSize.equals(value)) {
  4475. return;
  4476. }
  4477. this._minSize = value;
  4478. this._parentLayoutDirty();
  4479. },
  4480. enumerable: true,
  4481. configurable: true
  4482. });
  4483. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  4484. /**
  4485. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  4486. * The Primitive's size won't be more than specified.
  4487. * The default value depends of the Primitive type
  4488. */
  4489. get: function () {
  4490. return this._maxSize;
  4491. },
  4492. set: function (value) {
  4493. if (this._maxSize && value && this._maxSize.equals(value)) {
  4494. return;
  4495. }
  4496. this._maxSize = value;
  4497. this._parentLayoutDirty();
  4498. },
  4499. enumerable: true,
  4500. configurable: true
  4501. });
  4502. Object.defineProperty(Prim2DBase.prototype, "origin", {
  4503. /**
  4504. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  4505. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  4506. * For instance:
  4507. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  4508. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  4509. * 0,1 means the center is top/left
  4510. * @returns The normalized center.
  4511. */
  4512. get: function () {
  4513. return this._origin;
  4514. },
  4515. set: function (value) {
  4516. this._origin = value;
  4517. },
  4518. enumerable: true,
  4519. configurable: true
  4520. });
  4521. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  4522. get: function () {
  4523. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  4524. },
  4525. set: function (value) {
  4526. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  4527. },
  4528. enumerable: true,
  4529. configurable: true
  4530. });
  4531. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  4532. get: function () {
  4533. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  4534. },
  4535. set: function (value) {
  4536. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  4537. },
  4538. enumerable: true,
  4539. configurable: true
  4540. });
  4541. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  4542. get: function () {
  4543. return this._manualZOrder;
  4544. },
  4545. set: function (value) {
  4546. if (this._manualZOrder === value) {
  4547. return;
  4548. }
  4549. this._manualZOrder = value;
  4550. this.onZOrderChanged();
  4551. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  4552. this._actualZOrderChangedObservable.notifyObservers(value);
  4553. }
  4554. },
  4555. enumerable: true,
  4556. configurable: true
  4557. });
  4558. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  4559. get: function () {
  4560. return this._manualZOrder != null;
  4561. },
  4562. enumerable: true,
  4563. configurable: true
  4564. });
  4565. Object.defineProperty(Prim2DBase.prototype, "margin", {
  4566. get: function () {
  4567. var _this = this;
  4568. if (!this._margin) {
  4569. this._margin = new PrimitiveThickness(function () {
  4570. if (!_this.parent) {
  4571. return null;
  4572. }
  4573. return _this.parent.margin;
  4574. }, function () { return _this._positioningDirty(); });
  4575. }
  4576. return this._margin;
  4577. },
  4578. set: function (value) {
  4579. this.margin.copyFrom(value);
  4580. },
  4581. enumerable: true,
  4582. configurable: true
  4583. });
  4584. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  4585. /**
  4586. * Check for both margin and marginAlignment, return true if at least one of them is specified with a non default value
  4587. */
  4588. get: function () {
  4589. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  4590. },
  4591. enumerable: true,
  4592. configurable: true
  4593. });
  4594. Object.defineProperty(Prim2DBase.prototype, "padding", {
  4595. get: function () {
  4596. var _this = this;
  4597. if (!this._padding) {
  4598. this._padding = new PrimitiveThickness(function () {
  4599. if (!_this.parent) {
  4600. return null;
  4601. }
  4602. return _this.parent.padding;
  4603. }, function () { return _this._positioningDirty(); });
  4604. }
  4605. return this._padding;
  4606. },
  4607. set: function (value) {
  4608. this.padding.copyFrom(value);
  4609. },
  4610. enumerable: true,
  4611. configurable: true
  4612. });
  4613. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  4614. get: function () {
  4615. return this._padding !== null && !this._padding.isDefault;
  4616. },
  4617. enumerable: true,
  4618. configurable: true
  4619. });
  4620. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  4621. get: function () {
  4622. var _this = this;
  4623. if (!this._marginAlignment) {
  4624. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  4625. }
  4626. return this._marginAlignment;
  4627. },
  4628. set: function (value) {
  4629. this.marginAlignment.copyFrom(value);
  4630. },
  4631. enumerable: true,
  4632. configurable: true
  4633. });
  4634. Object.defineProperty(Prim2DBase.prototype, "_hasMarginAlignment", {
  4635. /**
  4636. * Check if there a marginAlignment specified (non null and not default)
  4637. */
  4638. get: function () {
  4639. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  4640. },
  4641. enumerable: true,
  4642. configurable: true
  4643. });
  4644. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  4645. get: function () {
  4646. return this._opacity;
  4647. },
  4648. set: function (value) {
  4649. if (value < 0) {
  4650. value = 0;
  4651. }
  4652. else if (value > 1) {
  4653. value = 1;
  4654. }
  4655. if (this._opacity === value) {
  4656. return;
  4657. }
  4658. this._opacity = value;
  4659. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  4660. this._spreadActualOpacityChanged();
  4661. this._updateRenderMode();
  4662. },
  4663. enumerable: true,
  4664. configurable: true
  4665. });
  4666. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  4667. get: function () {
  4668. return this._scale.x;
  4669. },
  4670. set: function (value) {
  4671. this._scale.x = value;
  4672. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  4673. this._spreadActualScaleDirty();
  4674. },
  4675. enumerable: true,
  4676. configurable: true
  4677. });
  4678. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  4679. get: function () {
  4680. return this._scale.y;
  4681. },
  4682. set: function (value) {
  4683. this._scale.y = value;
  4684. this._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  4685. this._spreadActualScaleDirty();
  4686. },
  4687. enumerable: true,
  4688. configurable: true
  4689. });
  4690. Prim2DBase.prototype._spreadActualScaleDirty = function () {
  4691. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  4692. var child = _a[_i];
  4693. child._setFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  4694. child._spreadActualScaleDirty();
  4695. }
  4696. };
  4697. Object.defineProperty(Prim2DBase.prototype, "actualScale", {
  4698. /**
  4699. * 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
  4700. */
  4701. get: function () {
  4702. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualScaleDirty)) {
  4703. var cur = this._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : this.parent;
  4704. var sx = this.scaleX;
  4705. var sy = this.scaleY;
  4706. while (cur) {
  4707. sx *= cur.scaleX;
  4708. sy *= cur.scaleY;
  4709. cur = cur._isFlagSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? null : cur.parent;
  4710. }
  4711. this._actualScale.copyFromFloats(sx, sy);
  4712. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualScaleDirty);
  4713. }
  4714. return this._actualScale;
  4715. },
  4716. enumerable: true,
  4717. configurable: true
  4718. });
  4719. Object.defineProperty(Prim2DBase.prototype, "actualScaleX", {
  4720. /**
  4721. * Get the actual Scale of the X axis, shortcut for this.actualScale.x
  4722. */
  4723. get: function () {
  4724. return this.actualScale.x;
  4725. },
  4726. enumerable: true,
  4727. configurable: true
  4728. });
  4729. Object.defineProperty(Prim2DBase.prototype, "actualScaleY", {
  4730. /**
  4731. * Get the actual Scale of the Y axis, shortcut for this.actualScale.y
  4732. */
  4733. get: function () {
  4734. return this.actualScale.y;
  4735. },
  4736. enumerable: true,
  4737. configurable: true
  4738. });
  4739. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  4740. /**
  4741. * Get the actual opacity level, this property is computed from the opacity property, multiplied by the actualOpacity of its parent (if any)
  4742. */
  4743. get: function () {
  4744. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  4745. var cur = this.parent;
  4746. var op = this.opacity;
  4747. while (cur) {
  4748. op *= cur.opacity;
  4749. cur = cur.parent;
  4750. }
  4751. this._actualOpacity = op;
  4752. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  4753. }
  4754. return this._actualOpacity;
  4755. },
  4756. enumerable: true,
  4757. configurable: true
  4758. });
  4759. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  4760. /**
  4761. * Get/set the layout engine to use for this primitive.
  4762. * The default layout engine is the CanvasLayoutEngine.
  4763. */
  4764. get: function () {
  4765. if (!this._layoutEngine) {
  4766. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  4767. }
  4768. return this._layoutEngine;
  4769. },
  4770. set: function (value) {
  4771. if (this._layoutEngine === value) {
  4772. return;
  4773. }
  4774. this._changeLayoutEngine(value);
  4775. },
  4776. enumerable: true,
  4777. configurable: true
  4778. });
  4779. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  4780. /**
  4781. * Get/set the layout are of this primitive.
  4782. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  4783. * The setter should only be called by a Layout Engine class.
  4784. */
  4785. get: function () {
  4786. return this._layoutArea;
  4787. },
  4788. set: function (val) {
  4789. if (this._layoutArea.equals(val)) {
  4790. return;
  4791. }
  4792. this._positioningDirty();
  4793. if (this.parent) {
  4794. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  4795. }
  4796. this._layoutArea = val;
  4797. },
  4798. enumerable: true,
  4799. configurable: true
  4800. });
  4801. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  4802. /**
  4803. * Get/set the layout area position (relative to the parent primitive).
  4804. * The setter should only be called by a Layout Engine class.
  4805. */
  4806. get: function () {
  4807. if (!this._layoutAreaPos) {
  4808. this._layoutAreaPos = BABYLON.Vector2.Zero();
  4809. }
  4810. return this._layoutAreaPos;
  4811. },
  4812. set: function (val) {
  4813. if (this._layoutAreaPos && this._layoutAreaPos.equals(val)) {
  4814. return;
  4815. }
  4816. if (this.parent) {
  4817. this.parent._setFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  4818. }
  4819. this._positioningDirty();
  4820. this._layoutAreaPos = val;
  4821. },
  4822. enumerable: true,
  4823. configurable: true
  4824. });
  4825. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  4826. /**
  4827. * Define if the Primitive can be subject to intersection test or not (default is true)
  4828. */
  4829. get: function () {
  4830. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  4831. },
  4832. set: function (value) {
  4833. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  4834. },
  4835. enumerable: true,
  4836. configurable: true
  4837. });
  4838. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  4839. /**
  4840. * Define if the Primitive acts as a container or not
  4841. * A container will encapsulate its children for interaction event.
  4842. * If it's not a container events will be process down to children if the primitive is not pickable.
  4843. * Default value is true
  4844. */
  4845. get: function () {
  4846. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  4847. },
  4848. set: function (value) {
  4849. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  4850. },
  4851. enumerable: true,
  4852. configurable: true
  4853. });
  4854. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  4855. /**
  4856. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  4857. */
  4858. get: function () {
  4859. return this._hierarchyDepth;
  4860. },
  4861. enumerable: true,
  4862. configurable: true
  4863. });
  4864. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  4865. /**
  4866. * Retrieve the Group that is responsible to render this primitive
  4867. */
  4868. get: function () {
  4869. return this._renderGroup;
  4870. },
  4871. enumerable: true,
  4872. configurable: true
  4873. });
  4874. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  4875. /**
  4876. * Get the global transformation matrix of the primitive
  4877. */
  4878. get: function () {
  4879. this._updateLocalTransform();
  4880. return this._globalTransform;
  4881. },
  4882. enumerable: true,
  4883. configurable: true
  4884. });
  4885. /**
  4886. * return the global position of the primitive, relative to its canvas
  4887. */
  4888. Prim2DBase.prototype.getGlobalPosition = function () {
  4889. var v = new BABYLON.Vector2(0, 0);
  4890. this.getGlobalPositionByRef(v);
  4891. return v;
  4892. };
  4893. /**
  4894. * return the global position of the primitive, relative to its canvas
  4895. * @param v the valid Vector2 object where the global position will be stored
  4896. */
  4897. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  4898. v.x = this.globalTransform.m[12];
  4899. v.y = this.globalTransform.m[13];
  4900. };
  4901. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  4902. /**
  4903. * Get invert of the global transformation matrix of the primitive
  4904. */
  4905. get: function () {
  4906. this._updateLocalTransform();
  4907. return this._invGlobalTransform;
  4908. },
  4909. enumerable: true,
  4910. configurable: true
  4911. });
  4912. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  4913. /**
  4914. * Get the local transformation of the primitive
  4915. */
  4916. get: function () {
  4917. this._updateLocalTransform();
  4918. return this._localTransform;
  4919. },
  4920. enumerable: true,
  4921. configurable: true
  4922. });
  4923. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  4924. /**
  4925. * Get the boundingInfo associated to the primitive and its children.
  4926. * The value is supposed to be always up to date
  4927. */
  4928. get: function () {
  4929. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  4930. if (this.owner) {
  4931. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  4932. }
  4933. if (this.isSizedByContent) {
  4934. this._boundingInfo.clear();
  4935. }
  4936. else {
  4937. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  4938. }
  4939. var bi = this._boundingInfo;
  4940. var tps = new BABYLON.BoundingInfo2D();
  4941. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  4942. var curChild = _a[_i];
  4943. var bb = curChild.boundingInfo;
  4944. bb.transformToRef(curChild.localTransform, tps);
  4945. bi.unionToRef(tps, bi);
  4946. }
  4947. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  4948. this._boundingSize.copyFromFloats((!this._size || this._size.width == null) ? Math.ceil(Prim2DBase._bMax.x) : this._size.width, (!this._size || this._size.height == null) ? Math.ceil(Prim2DBase._bMax.y) : this._size.height);
  4949. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  4950. }
  4951. return this._boundingInfo;
  4952. },
  4953. enumerable: true,
  4954. configurable: true
  4955. });
  4956. Object.defineProperty(Prim2DBase.prototype, "layoutBoundingInfo", {
  4957. /**
  4958. * Get the boundingInfo of the primitive's content arranged by a layout Engine
  4959. * If a particular child is not arranged by layout, it's boundingInfo is used instead to produce something as accurate as possible
  4960. */
  4961. get: function () {
  4962. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty)) {
  4963. if (!this._layoutBoundingInfo) {
  4964. this._layoutBoundingInfo = new BABYLON.BoundingInfo2D();
  4965. }
  4966. if (this.isSizedByContent) {
  4967. this._layoutBoundingInfo.clear();
  4968. }
  4969. else {
  4970. this._layoutBoundingInfo.copyFrom(this.levelBoundingInfo);
  4971. }
  4972. var bi = this._layoutBoundingInfo;
  4973. var tps = new BABYLON.BoundingInfo2D();
  4974. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  4975. var curChild = _a[_i];
  4976. var bb = void 0;
  4977. if (curChild._layoutAreaPos) {
  4978. var s = curChild._layoutArea;
  4979. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(0, s.width, 0, s.height, Prim2DBase._tpsBB);
  4980. bb = Prim2DBase._tpsBB;
  4981. }
  4982. else {
  4983. bb = curChild.boundingInfo;
  4984. }
  4985. bb.transformToRef(curChild.localTransform, tps);
  4986. bi.unionToRef(tps, bi);
  4987. }
  4988. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutBoundingInfoDirty);
  4989. }
  4990. return this._layoutBoundingInfo;
  4991. },
  4992. enumerable: true,
  4993. configurable: true
  4994. });
  4995. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  4996. /**
  4997. * Determine if the size is automatically computed or fixed because manually specified.
  4998. * Use the actualSize property to get the final/real size of the primitive
  4999. * @returns true if the size is automatically computed, false if it were manually specified.
  5000. */
  5001. get: function () {
  5002. return this._size == null;
  5003. },
  5004. enumerable: true,
  5005. configurable: true
  5006. });
  5007. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  5008. /**
  5009. * Return true if this prim has an auto size which is set by the children's global bounding box
  5010. */
  5011. get: function () {
  5012. return (this._size == null) && (this._children.length > 0);
  5013. },
  5014. enumerable: true,
  5015. configurable: true
  5016. });
  5017. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  5018. /**
  5019. * Determine if the position is automatically computed or fixed because manually specified.
  5020. * Use the actualPosition property to get the final/real position of the primitive
  5021. * @returns true if the position is automatically computed, false if it were manually specified.
  5022. */
  5023. get: function () {
  5024. return this._position == null;
  5025. },
  5026. enumerable: true,
  5027. configurable: true
  5028. });
  5029. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  5030. /**
  5031. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  5032. */
  5033. get: function () {
  5034. return this._pointerEventObservable;
  5035. },
  5036. enumerable: true,
  5037. configurable: true
  5038. });
  5039. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  5040. get: function () {
  5041. if (!this._actualZOrderChangedObservable) {
  5042. this._actualZOrderChangedObservable = new BABYLON.Observable();
  5043. }
  5044. return this._actualZOrderChangedObservable;
  5045. },
  5046. enumerable: true,
  5047. configurable: true
  5048. });
  5049. Object.defineProperty(Prim2DBase.prototype, "displayDebugAreas", {
  5050. get: function () {
  5051. return this._displayDebugAreas;
  5052. },
  5053. set: function (value) {
  5054. if (this._displayDebugAreas === value) {
  5055. return;
  5056. }
  5057. if (value === false) {
  5058. this._debugAreaGroup.dispose();
  5059. this._debugAreaGroup = null;
  5060. }
  5061. else {
  5062. var layoutFill = "#F0808040"; // Red - Layout area
  5063. var layoutBorder = "#F08080FF";
  5064. var marginFill = "#F0F04040"; // Yellow - Margin area
  5065. var marginBorder = "#F0F040FF";
  5066. var paddingFill = "#F040F040"; // Magenta - Padding Area
  5067. var paddingBorder = "#F040F0FF";
  5068. var contentFill = "#40F0F040"; // Cyan - Content area
  5069. var contentBorder = "#40F0F0FF";
  5070. var s = new BABYLON.Size(10, 10);
  5071. var p = BABYLON.Vector2.Zero();
  5072. this._debugAreaGroup = new BABYLON.Group2D({ dontInheritParentScale: true,
  5073. parent: (this.parent != null) ? this.parent : this, id: "###DEBUG AREA GROUP###", children: [
  5074. new BABYLON.Group2D({
  5075. id: "###Layout Area###", position: p, size: s, children: [
  5076. new BABYLON.Rectangle2D({ id: "###Layout Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: layoutBorder }),
  5077. new BABYLON.Rectangle2D({ id: "###Layout Top###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  5078. new BABYLON.Rectangle2D({ id: "###Layout Left###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  5079. new BABYLON.Rectangle2D({ id: "###Layout Right###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill }),
  5080. new BABYLON.Rectangle2D({ id: "###Layout Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: layoutFill })
  5081. ]
  5082. }),
  5083. new BABYLON.Group2D({
  5084. id: "###Margin Area###", position: p, size: s, children: [
  5085. new BABYLON.Rectangle2D({ id: "###Margin Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: marginBorder }),
  5086. new BABYLON.Rectangle2D({ id: "###Margin Top###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  5087. new BABYLON.Rectangle2D({ id: "###Margin Left###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  5088. new BABYLON.Rectangle2D({ id: "###Margin Right###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill }),
  5089. new BABYLON.Rectangle2D({ id: "###Margin Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: marginFill })
  5090. ]
  5091. }),
  5092. new BABYLON.Group2D({
  5093. id: "###Padding Area###", position: p, size: s, children: [
  5094. new BABYLON.Rectangle2D({ id: "###Padding Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: paddingBorder }),
  5095. new BABYLON.Rectangle2D({ id: "###Padding Top###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  5096. new BABYLON.Rectangle2D({ id: "###Padding Left###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  5097. new BABYLON.Rectangle2D({ id: "###Padding Right###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill }),
  5098. new BABYLON.Rectangle2D({ id: "###Padding Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: paddingFill })
  5099. ]
  5100. }),
  5101. new BABYLON.Group2D({
  5102. id: "###Content Area###", position: p, size: s, children: [
  5103. new BABYLON.Rectangle2D({ id: "###Content Frame###", position: BABYLON.Vector2.Zero(), size: s, fill: null, border: contentBorder }),
  5104. new BABYLON.Rectangle2D({ id: "###Content Top###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  5105. new BABYLON.Rectangle2D({ id: "###Content Left###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  5106. new BABYLON.Rectangle2D({ id: "###Content Right###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill }),
  5107. new BABYLON.Rectangle2D({ id: "###Content Bottom###", position: BABYLON.Vector2.Zero(), size: s, fill: contentFill })
  5108. ]
  5109. })
  5110. ]
  5111. });
  5112. this._debugAreaGroup._setFlags(BABYLON.SmartPropertyPrim.flagNoPartOfLayout);
  5113. this._updateDebugArea();
  5114. }
  5115. this._displayDebugAreas = value;
  5116. },
  5117. enumerable: true,
  5118. configurable: true
  5119. });
  5120. Prim2DBase.prototype._updateDebugArea = function () {
  5121. var areaNames = ["Layout", "Margin", "Padding", "Content"];
  5122. var areaZones = ["Area", "Frame", "Top", "Left", "Right", "Bottom"];
  5123. var prims = new Array(4);
  5124. // Get all the primitives used to display the areas
  5125. for (var i = 0; i < 4; i++) {
  5126. prims[i] = new Array(6);
  5127. for (var j = 0; j < 6; j++) {
  5128. prims[i][j] = this._debugAreaGroup.findById("###" + areaNames[i] + " " + areaZones[j] + "###");
  5129. if (j > 1) {
  5130. prims[i][j].levelVisible = false;
  5131. }
  5132. }
  5133. }
  5134. // Update the visibility status of layout/margin/padding
  5135. var hasLayout = this._layoutAreaPos != null;
  5136. var hasPos = (this.actualPosition.x !== 0) || (this.actualPosition.y !== 0);
  5137. var hasMargin = this._hasMargin;
  5138. var hasPadding = this._hasPadding;
  5139. prims[0][0].levelVisible = hasLayout;
  5140. prims[1][0].levelVisible = hasMargin;
  5141. prims[2][0].levelVisible = hasPadding;
  5142. prims[3][0].levelVisible = true;
  5143. // Current offset
  5144. var curOffset = BABYLON.Vector2.Zero();
  5145. // Store the area info of the layout area
  5146. var curAreaIndex = 0;
  5147. // Store data about each area
  5148. var areaInfo = new Array(4);
  5149. var storeAreaInfo = function (pos, size) {
  5150. var min = pos.clone();
  5151. var max = pos.clone();
  5152. if (size.width > 0) {
  5153. max.x += size.width;
  5154. }
  5155. if (size.height > 0) {
  5156. max.y += size.height;
  5157. }
  5158. areaInfo[curAreaIndex++] = { off: pos, size: size, min: min, max: max };
  5159. };
  5160. var isCanvas = this instanceof BABYLON.Canvas2D;
  5161. var marginH = this._marginOffset.x + this._marginOffset.z;
  5162. var marginV = this._marginOffset.y + this._marginOffset.w;
  5163. var actualSize = this.actualSize.multiplyByFloats(isCanvas ? 1 : this.scaleX, isCanvas ? 1 : this.scaleY);
  5164. var w = hasLayout ? (this.layoutAreaPos.x + this.layoutArea.width) : (marginH + actualSize.width);
  5165. var h = hasLayout ? (this.layoutAreaPos.y + this.layoutArea.height) : (marginV + actualSize.height);
  5166. var pos = (!hasLayout && !hasMargin && !hasPadding && hasPos) ? this.actualPosition : BABYLON.Vector2.Zero();
  5167. storeAreaInfo(pos, new BABYLON.Size(w, h));
  5168. // Compute the layout related data
  5169. if (hasLayout) {
  5170. var layoutOffset = this.layoutAreaPos.clone();
  5171. storeAreaInfo(layoutOffset, (hasMargin || hasPadding) ? this.layoutArea.clone() : actualSize.clone());
  5172. curOffset = layoutOffset.clone();
  5173. }
  5174. // Compute margin data
  5175. if (hasMargin) {
  5176. var marginOffset = curOffset.clone();
  5177. marginOffset.x += this._marginOffset.x;
  5178. marginOffset.y += this._marginOffset.y;
  5179. var marginArea = actualSize;
  5180. storeAreaInfo(marginOffset, marginArea);
  5181. curOffset = marginOffset.clone();
  5182. }
  5183. if (hasPadding) {
  5184. var contentOffset = curOffset.clone();
  5185. contentOffset.x += this._paddingOffset.x;
  5186. contentOffset.y += this._paddingOffset.y;
  5187. var contentArea = this.contentArea;
  5188. storeAreaInfo(contentOffset, contentArea);
  5189. curOffset = curOffset.add(contentOffset);
  5190. }
  5191. // Helper function that set the pos and size of a given prim
  5192. var setArea = function (i, j, pos, size) {
  5193. prims[i][j].position = pos;
  5194. prims[i][j].size = size;
  5195. };
  5196. var setFullRect = function (i, pos, size) {
  5197. var plist = prims[i];
  5198. plist[2].levelVisible = true;
  5199. plist[3].levelVisible = false;
  5200. plist[4].levelVisible = false;
  5201. plist[5].levelVisible = false;
  5202. setArea(i, 1, pos, size);
  5203. setArea(i, 2, pos, size);
  5204. };
  5205. var setQuadRect = function (i, areaIndex) {
  5206. var plist = prims[i];
  5207. plist[2].levelVisible = true;
  5208. plist[3].levelVisible = true;
  5209. plist[4].levelVisible = true;
  5210. plist[5].levelVisible = true;
  5211. var ca = areaInfo[areaIndex];
  5212. var na = areaInfo[areaIndex + 1];
  5213. var tp = new BABYLON.Vector2(ca.min.x, na.max.y);
  5214. var ts = new BABYLON.Size(ca.size.width, ca.max.y - tp.y);
  5215. var lp = new BABYLON.Vector2(ca.min.x, na.min.y);
  5216. var ls = new BABYLON.Size(na.min.x - ca.min.x, na.max.y - na.min.y);
  5217. var rp = new BABYLON.Vector2(na.max.x, na.min.y);
  5218. var rs = new BABYLON.Size(ca.max.x - na.max.x, na.max.y - na.min.y);
  5219. var bp = new BABYLON.Vector2(ca.min.x, ca.min.y);
  5220. var bs = new BABYLON.Size(ca.size.width, na.min.y - ca.min.y);
  5221. // Frame
  5222. plist[1].position = ca.off;
  5223. plist[1].size = ca.size;
  5224. // Top rect
  5225. plist[2].position = tp;
  5226. plist[2].size = ts;
  5227. // Left rect
  5228. plist[3].position = lp;
  5229. plist[3].size = ls;
  5230. // Right rect
  5231. plist[4].position = rp;
  5232. plist[4].size = rs;
  5233. // Bottom rect
  5234. plist[5].position = bp;
  5235. plist[5].size = bs;
  5236. };
  5237. var areaCount = curAreaIndex;
  5238. curAreaIndex = 0;
  5239. // Available zones
  5240. var availableZones = [false, hasLayout, hasMargin, hasPadding, true];
  5241. for (var k = 1; k < 5; k++) {
  5242. if (availableZones[k]) {
  5243. var ai = areaInfo[curAreaIndex];
  5244. setArea(k - 1, 0, BABYLON.Vector2.Zero(), ai.size);
  5245. // setArea(k-1, 1, Vector2.Zero(), ai.size);
  5246. if (k === 4) {
  5247. setFullRect(k - 1, ai.off, ai.size);
  5248. }
  5249. else {
  5250. setQuadRect(k - 1, curAreaIndex);
  5251. }
  5252. ++curAreaIndex;
  5253. }
  5254. }
  5255. };
  5256. Prim2DBase.prototype.findById = function (id) {
  5257. if (this._id === id) {
  5258. return this;
  5259. }
  5260. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  5261. var child = _a[_i];
  5262. var r = child.findById(id);
  5263. if (r != null) {
  5264. return r;
  5265. }
  5266. }
  5267. };
  5268. Prim2DBase.prototype.onZOrderChanged = function () {
  5269. };
  5270. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  5271. return false;
  5272. };
  5273. /**
  5274. * Capture all the Events of the given PointerId for this primitive.
  5275. * Don't forget to call releasePointerEventsCapture when done.
  5276. * @param pointerId the Id of the pointer to capture the events from.
  5277. */
  5278. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  5279. return this.owner._setPointerCapture(pointerId, this);
  5280. };
  5281. /**
  5282. * Release a captured pointer made with setPointerEventCapture.
  5283. * @param pointerId the Id of the pointer to release the capture from.
  5284. */
  5285. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  5286. return this.owner._releasePointerCapture(pointerId, this);
  5287. };
  5288. Prim2DBase.prototype.intersect = function (intersectInfo) {
  5289. if (!intersectInfo) {
  5290. return false;
  5291. }
  5292. // If this is null it means this method is call for the first level, initialize stuffs
  5293. var firstLevel = !intersectInfo._globalPickPosition;
  5294. if (firstLevel) {
  5295. // 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).
  5296. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  5297. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  5298. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  5299. intersectInfo.intersectedPrimitives = new Array();
  5300. intersectInfo.topMostIntersectedPrimitive = null;
  5301. }
  5302. if (!Prim2DBase._bypassGroup2DExclusion && this instanceof BABYLON.Group2D && this.isCachedGroup && !this.isRenderableGroup) {
  5303. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  5304. intersectInfo._exit(firstLevel);
  5305. return false;
  5306. }
  5307. if (!intersectInfo.intersectHidden && !this.isVisible) {
  5308. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  5309. intersectInfo._exit(firstLevel);
  5310. return false;
  5311. }
  5312. var id = this.id;
  5313. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  5314. try {
  5315. Prim2DBase._bypassGroup2DExclusion = true;
  5316. var ownerGroup = this.getExternalData("__cachedGroup__");
  5317. return ownerGroup.intersect(intersectInfo);
  5318. }
  5319. finally {
  5320. Prim2DBase._bypassGroup2DExclusion = false;
  5321. }
  5322. }
  5323. // 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).
  5324. var isIntersectionTest = false;
  5325. if (this instanceof BABYLON.Group2D) {
  5326. var g = this;
  5327. isIntersectionTest = g.isCachedGroup;
  5328. }
  5329. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  5330. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  5331. intersectInfo._exit(firstLevel);
  5332. return false;
  5333. }
  5334. // Fast rejection test with boundingInfo
  5335. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  5336. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  5337. intersectInfo._exit(firstLevel);
  5338. return false;
  5339. }
  5340. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  5341. var levelIntersectRes = false;
  5342. if (this.isPickable) {
  5343. levelIntersectRes = this.levelIntersect(intersectInfo);
  5344. if (levelIntersectRes) {
  5345. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  5346. intersectInfo.intersectedPrimitives.push(pii);
  5347. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  5348. intersectInfo.topMostIntersectedPrimitive = pii;
  5349. }
  5350. // If we must stop at the first intersection, we're done, quit!
  5351. if (intersectInfo.findFirstOnly) {
  5352. intersectInfo._exit(firstLevel);
  5353. return true;
  5354. }
  5355. }
  5356. }
  5357. // Recurse to children if needed
  5358. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  5359. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  5360. var curChild = _a[_i];
  5361. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  5362. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  5363. continue;
  5364. }
  5365. // Must compute the localPickLocation for the children level
  5366. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  5367. // If we got an intersection with the child and we only need to find the first one, quit!
  5368. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  5369. intersectInfo._exit(firstLevel);
  5370. return true;
  5371. }
  5372. }
  5373. }
  5374. intersectInfo._exit(firstLevel);
  5375. return intersectInfo.isIntersected;
  5376. };
  5377. /**
  5378. * Move a child object into a new position regarding its siblings to change its rendering order.
  5379. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  5380. * @param child the object to move
  5381. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  5382. */
  5383. Prim2DBase.prototype.moveChild = function (child, previous) {
  5384. if (child.parent !== this) {
  5385. return false;
  5386. }
  5387. var childIndex = this._children.indexOf(child);
  5388. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  5389. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  5390. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  5391. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  5392. }
  5393. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  5394. return true;
  5395. };
  5396. /**
  5397. * Move the given child so it's displayed on the top of all its siblings
  5398. * @param child the primitive to move to the top
  5399. */
  5400. Prim2DBase.prototype.moveChildToTop = function (child) {
  5401. return this.moveChild(child, this._children[this._children.length - 1]);
  5402. };
  5403. /**
  5404. * Move the given child so it's displayed on the bottom of all its siblings
  5405. * @param child the primitive to move to the top
  5406. */
  5407. Prim2DBase.prototype.moveChildToBottom = function (child) {
  5408. return this.moveChild(child, null);
  5409. };
  5410. /**
  5411. * Move this primitive to be at the top among all its sibling
  5412. */
  5413. Prim2DBase.prototype.moveToTop = function () {
  5414. if (this.parent == null) {
  5415. return false;
  5416. }
  5417. return this.parent.moveChildToTop(this);
  5418. };
  5419. /**
  5420. * Move this primitive to be at the bottom among all its sibling
  5421. */
  5422. Prim2DBase.prototype.moveToBottom = function () {
  5423. if (this.parent == null) {
  5424. return false;
  5425. }
  5426. return this.parent.moveChildToBottom(this);
  5427. };
  5428. Prim2DBase.prototype.addChild = function (child) {
  5429. child._parent = this;
  5430. this._boundingBoxDirty();
  5431. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  5432. if (flat) {
  5433. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  5434. child._setZOrder(this._zOrder, true);
  5435. child._zMax = this._zOrder;
  5436. }
  5437. else {
  5438. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  5439. }
  5440. var length = this._children.push(child);
  5441. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  5442. };
  5443. /**
  5444. * Dispose the primitive, remove it from its parent.
  5445. */
  5446. Prim2DBase.prototype.dispose = function () {
  5447. if (!_super.prototype.dispose.call(this)) {
  5448. return false;
  5449. }
  5450. if (this._pointerEventObservable) {
  5451. this._pointerEventObservable.clear();
  5452. this._pointerEventObservable = null;
  5453. }
  5454. if (this._actionManager) {
  5455. this._actionManager.dispose();
  5456. this._actionManager = null;
  5457. }
  5458. // If there's a parent, remove this object from its parent list
  5459. if (this._parent) {
  5460. if (this instanceof BABYLON.Group2D) {
  5461. var g = this;
  5462. if (g.isRenderableGroup) {
  5463. var parentRenderable = this.parent.traverseUp(function (p) { return (p instanceof BABYLON.Group2D && p.isRenderableGroup); });
  5464. if (parentRenderable != null) {
  5465. var l = parentRenderable._renderableData._childrenRenderableGroups;
  5466. var i_1 = l.indexOf(g);
  5467. if (i_1 !== -1) {
  5468. l.splice(i_1, 1);
  5469. }
  5470. }
  5471. }
  5472. }
  5473. var i = this._parent._children.indexOf(this);
  5474. if (i !== undefined) {
  5475. this._parent._children.splice(i, 1);
  5476. }
  5477. this._parent = null;
  5478. }
  5479. // Recurse dispose to children
  5480. if (this._children) {
  5481. while (this._children.length > 0) {
  5482. this._children[this._children.length - 1].dispose();
  5483. }
  5484. }
  5485. return true;
  5486. };
  5487. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  5488. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  5489. this._renderGroup._addPrimToDirtyList(this);
  5490. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  5491. }
  5492. };
  5493. Prim2DBase.prototype._needPrepare = function () {
  5494. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty | BABYLON.SmartPropertyPrim.flagNeedRefresh) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  5495. };
  5496. Prim2DBase.prototype._prepareRender = function (context) {
  5497. this._prepareRenderPre(context);
  5498. this._prepareRenderPost(context);
  5499. };
  5500. Prim2DBase.prototype._prepareRenderPre = function (context) {
  5501. };
  5502. Prim2DBase.prototype._prepareRenderPost = function (context) {
  5503. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  5504. if (this instanceof BABYLON.Group2D) {
  5505. var self = this;
  5506. if (self.isRenderableGroup) {
  5507. return;
  5508. }
  5509. }
  5510. // Check if we need to recurse the prepare to children primitives
  5511. // - must have children
  5512. // - the global transform of this level have changed, or
  5513. // - the visible state of primitive has changed
  5514. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  5515. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  5516. this._children.forEach(function (c) {
  5517. // As usual stop the recursion if we meet a renderable group
  5518. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  5519. c._prepareRender(context);
  5520. }
  5521. });
  5522. }
  5523. // Finally reset the dirty flags as we've processed everything
  5524. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  5525. this._instanceDirtyFlags = 0;
  5526. };
  5527. Prim2DBase.prototype._canvasPreInit = function (settings) {
  5528. };
  5529. Prim2DBase.CheckParent = function (parent) {
  5530. //if (!Prim2DBase._isCanvasInit && !parent) {
  5531. // 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)");
  5532. //}
  5533. };
  5534. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  5535. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  5536. var cur = list_1[_i];
  5537. cur.updateCachedStates(recurse);
  5538. }
  5539. };
  5540. Prim2DBase.prototype._parentLayoutDirty = function () {
  5541. if (!this._parent || this._parent.isDisposed) {
  5542. return;
  5543. }
  5544. this._parent._setLayoutDirty();
  5545. };
  5546. Prim2DBase.prototype._setLayoutDirty = function () {
  5547. this.onPrimBecomesDirty();
  5548. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  5549. };
  5550. Prim2DBase.prototype._checkPositionChange = function () {
  5551. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  5552. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  5553. return false;
  5554. }
  5555. return true;
  5556. };
  5557. Prim2DBase.prototype._positioningDirty = function () {
  5558. this.onPrimBecomesDirty();
  5559. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  5560. };
  5561. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  5562. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  5563. var child = _a[_i];
  5564. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  5565. child._updateRenderMode();
  5566. child.onPrimBecomesDirty();
  5567. child._spreadActualOpacityChanged();
  5568. }
  5569. };
  5570. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  5571. this._layoutEngine = engine;
  5572. };
  5573. Prim2DBase.prototype._updateLocalTransform = function () {
  5574. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  5575. if (this.checkPropertiesDirty(tflags)) {
  5576. if (this.owner) {
  5577. this.owner.addupdateLocalTransformCounter(1);
  5578. }
  5579. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  5580. var local;
  5581. var pos = this._position ? this.position : this.layoutAreaPos;
  5582. if (this._origin.x === 0 && this._origin.y === 0) {
  5583. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x + this._marginOffset.x, pos.y + this._marginOffset.y, 0));
  5584. this._localTransform = local;
  5585. }
  5586. else {
  5587. // -Origin offset
  5588. var as = this.actualSize;
  5589. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  5590. // -Origin * rotation
  5591. rot.toRotationMatrix(Prim2DBase._t1);
  5592. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  5593. // -Origin * rotation * scale
  5594. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  5595. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  5596. // -Origin * rotation * scale * (Origin + Position)
  5597. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x + this._marginOffset.x, (as.height * this._origin.y) + pos.y + this._marginOffset.y, 0, Prim2DBase._t2);
  5598. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  5599. }
  5600. this.clearPropertiesDirty(tflags);
  5601. this._setFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  5602. return true;
  5603. }
  5604. return false;
  5605. };
  5606. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  5607. if (this.isDisposed) {
  5608. return;
  5609. }
  5610. this.owner.addCachedGroupRenderCounter(1);
  5611. // Check if the parent is synced
  5612. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  5613. this._parent.updateCachedStates(false);
  5614. }
  5615. // Update Z-Order if needed
  5616. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  5617. this._updateZOrder();
  5618. }
  5619. // Update actualSize only if there' not positioning to recompute and the size changed
  5620. // Otherwise positioning will take care of it.
  5621. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  5622. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  5623. var size = this.size;
  5624. if (size) {
  5625. if (this.size.width != null) {
  5626. this.actualSize.width = this.size.width;
  5627. }
  5628. if (this.size.height != null) {
  5629. this.actualSize.height = this.size.height;
  5630. }
  5631. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  5632. }
  5633. }
  5634. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  5635. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  5636. // Check for layout update
  5637. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  5638. this.owner.addUpdateLayoutCounter(1);
  5639. this._layoutEngine.updateLayout(this);
  5640. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  5641. }
  5642. var autoContentChanged = false;
  5643. if (this.isSizeAuto) {
  5644. if (!this._lastAutoSizeArea) {
  5645. autoContentChanged = this.actualSize !== null;
  5646. }
  5647. else {
  5648. autoContentChanged = (!this._lastAutoSizeArea.equals(this.actualSize));
  5649. }
  5650. }
  5651. // Check for positioning update
  5652. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  5653. this._updatePositioning();
  5654. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  5655. if (sizeDirty) {
  5656. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  5657. }
  5658. positioningComputed = true;
  5659. }
  5660. if (positioningComputed && this._parent) {
  5661. this._parentContentArea.copyFrom(this._parent.contentArea);
  5662. }
  5663. // Check if we must update this prim
  5664. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  5665. this.owner.addUpdateGlobalTransformCounter(1);
  5666. var curVisibleState = this.isVisible;
  5667. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  5668. // Detect a change of visibility
  5669. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  5670. // Get/compute the localTransform
  5671. var localDirty = this._updateLocalTransform();
  5672. var parentPaddingChanged = false;
  5673. var parentPaddingOffset = Prim2DBase._v0;
  5674. if (this._parent) {
  5675. parentPaddingOffset = new BABYLON.Vector2(this._parent._paddingOffset.x, this._parent._paddingOffset.y);
  5676. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  5677. }
  5678. // Check if there are changes in the parent that will force us to update the global matrix
  5679. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  5680. // Check if we have to update the globalTransform
  5681. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged || this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty)) {
  5682. var globalTransform = this._parent ? this._parent._globalTransform : null;
  5683. var localTransform = void 0;
  5684. Prim2DBase._transMtx.copyFrom(this._localTransform);
  5685. Prim2DBase._transMtx.m[12] += parentPaddingOffset.x;
  5686. Prim2DBase._transMtx.m[13] += parentPaddingOffset.y;
  5687. localTransform = Prim2DBase._transMtx;
  5688. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  5689. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  5690. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  5691. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  5692. this._clearFlags(BABYLON.SmartPropertyPrim.flagGlobalTransformDirty);
  5693. }
  5694. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  5695. }
  5696. if (recurse) {
  5697. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  5698. var child = _a[_i];
  5699. // Stop the recursion if we meet a renderable group
  5700. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  5701. }
  5702. }
  5703. };
  5704. Prim2DBase.prototype._updatePositioning = function () {
  5705. if (this.owner) {
  5706. this.owner.addUpdatePositioningCounter(1);
  5707. }
  5708. // From this point we assume that the primitive layoutArea is computed and up to date.
  5709. // We know have to :
  5710. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  5711. // 2. Determine the contentArea based on the padding property.
  5712. var isSizeAuto = this.isSizeAuto;
  5713. // 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
  5714. if (!this._hasMarginAlignment && (isSizeAuto || (this.actualSize.width == null || this.actualSize.height == null))) {
  5715. if (isSizeAuto || this.actualSize.width == null) {
  5716. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  5717. }
  5718. if (isSizeAuto || this.actualSize.height == null) {
  5719. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  5720. }
  5721. }
  5722. // Apply margin
  5723. if (this._hasMargin) {
  5724. this.margin.computeWithAlignment(this.layoutArea, this.size || this.actualSize, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  5725. this.actualSize = Prim2DBase._size.clone();
  5726. }
  5727. var po = new BABYLON.Vector2(this._paddingOffset.x, this._paddingOffset.y);
  5728. if (this._hasPadding) {
  5729. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  5730. if (isSizeAuto) {
  5731. var content = this.size.clone();
  5732. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  5733. this.padding.enlarge(Prim2DBase._icArea, po, Prim2DBase._size);
  5734. this._contentArea.copyFrom(content);
  5735. this.actualSize = Prim2DBase._size.clone();
  5736. // Changing the padding has resize the prim, which forces us to recompute margin again
  5737. if (this._hasMargin) {
  5738. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  5739. }
  5740. }
  5741. else {
  5742. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icZone, Prim2DBase._icArea);
  5743. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  5744. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  5745. this.padding.compute(Prim2DBase._icArea, po, Prim2DBase._size);
  5746. this._paddingOffset.x = po.x;
  5747. this._paddingOffset.y = po.y;
  5748. this._paddingOffset.x += Prim2DBase._icZone.x;
  5749. this._paddingOffset.y += Prim2DBase._icZone.y;
  5750. this._paddingOffset.z -= Prim2DBase._icZone.z;
  5751. this._paddingOffset.w -= Prim2DBase._icZone.w;
  5752. this._contentArea.copyFrom(Prim2DBase._size);
  5753. }
  5754. }
  5755. else {
  5756. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icZone, Prim2DBase._icArea);
  5757. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  5758. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  5759. this._paddingOffset.x = Prim2DBase._icZone.x;
  5760. this._paddingOffset.y = Prim2DBase._icZone.y;
  5761. this._paddingOffset.z = Prim2DBase._icZone.z;
  5762. this._paddingOffset.w = Prim2DBase._icZone.z;
  5763. this._contentArea.copyFrom(Prim2DBase._icArea);
  5764. }
  5765. if (!this._position) {
  5766. var aPos = new BABYLON.Vector2(this.layoutAreaPos.x + this._marginOffset.x, this.layoutAreaPos.y + this._marginOffset.y);
  5767. this.actualPosition = aPos;
  5768. }
  5769. if (isSizeAuto) {
  5770. this._lastAutoSizeArea = this.actualSize;
  5771. }
  5772. if (this.displayDebugAreas) {
  5773. this._updateDebugArea();
  5774. }
  5775. };
  5776. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  5777. /**
  5778. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  5779. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  5780. */
  5781. get: function () {
  5782. // Check for positioning update
  5783. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  5784. this._updatePositioning();
  5785. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  5786. }
  5787. return this._contentArea;
  5788. },
  5789. enumerable: true,
  5790. configurable: true
  5791. });
  5792. Prim2DBase.prototype._patchHierarchy = function (owner) {
  5793. this._owner = owner;
  5794. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  5795. if (this._renderGroup != null) {
  5796. return;
  5797. }
  5798. if (this instanceof BABYLON.Group2D) {
  5799. var group = this;
  5800. group.detectGroupStates();
  5801. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  5802. group.owner._registerTrackedNode(this);
  5803. }
  5804. }
  5805. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  5806. if (this._parent) {
  5807. this._parentLayoutDirty();
  5808. }
  5809. // Make sure the prim is in the dirtyList if it should be
  5810. if (this._renderGroup && this.isDirty) {
  5811. var list = this._renderGroup._renderableData._primDirtyList;
  5812. var i = list.indexOf(this);
  5813. if (i === -1) {
  5814. list.push(this);
  5815. }
  5816. }
  5817. // Recurse
  5818. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  5819. var child = _a[_i];
  5820. child._hierarchyDepth = this._hierarchyDepth + 1;
  5821. child._patchHierarchy(owner);
  5822. }
  5823. };
  5824. Prim2DBase.prototype._updateZOrder = function () {
  5825. var prevLinPos = this._primLinearPosition;
  5826. var startI = 0;
  5827. var startZ = this._zOrder;
  5828. // 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
  5829. var childrenCount = this._children.length;
  5830. if (this._firstZDirtyIndex > 0) {
  5831. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  5832. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  5833. prevLinPos = prevPrim._primLinearPosition;
  5834. startI = this._firstZDirtyIndex - 1;
  5835. startZ = prevPrim._zOrder;
  5836. }
  5837. }
  5838. var startPos = prevLinPos;
  5839. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  5840. Prim2DBase._totalCount = 0;
  5841. for (var i = startI; i < childrenCount; i++) {
  5842. var child = this._children[i];
  5843. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  5844. }
  5845. // Compute the new Z-Order for all the primitives
  5846. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  5847. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  5848. // 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.
  5849. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  5850. // 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...
  5851. if (Prim2DBase._zRebuildReentrency) {
  5852. var p = this._parent;
  5853. if (p == null) {
  5854. // 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...)
  5855. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  5856. Prim2DBase._zRebuildReentrency = false;
  5857. return;
  5858. }
  5859. p._firstZDirtyIndex = 0;
  5860. return p._updateZOrder();
  5861. }
  5862. Prim2DBase._zRebuildReentrency = true;
  5863. this._firstZDirtyIndex = 0;
  5864. this._updateZOrder();
  5865. Prim2DBase._zRebuildReentrency = false;
  5866. }
  5867. for (var i = startI; i < childrenCount; i++) {
  5868. var child = this._children[i];
  5869. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  5870. }
  5871. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  5872. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  5873. var p = _a[_i];
  5874. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  5875. }
  5876. Prim2DBase._zOrderChangedNotifList.splice(0);
  5877. this._firstZDirtyIndex = Prim2DBase._bigInt;
  5878. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  5879. };
  5880. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  5881. if (this.isManualZOrder) {
  5882. return prevLinPos;
  5883. }
  5884. this._primLinearPosition = ++prevLinPos;
  5885. Prim2DBase._totalCount++;
  5886. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  5887. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  5888. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  5889. var child = _a[_i];
  5890. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  5891. }
  5892. }
  5893. return prevLinPos;
  5894. };
  5895. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  5896. if (this.isManualZOrder) {
  5897. return null;
  5898. }
  5899. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  5900. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  5901. this._setZOrder(newZ, false);
  5902. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  5903. this._firstZDirtyIndex = Prim2DBase._bigInt;
  5904. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  5905. }
  5906. var curZ = newZ;
  5907. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  5908. if (isFlat) {
  5909. if (this._children.length > 0) {
  5910. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  5911. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  5912. var child = _a[_i];
  5913. child._updatePrimitiveFlatZOrder(this._zOrder);
  5914. }
  5915. }
  5916. }
  5917. else {
  5918. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  5919. var child = _c[_b];
  5920. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  5921. if (r != null) {
  5922. curZ = r;
  5923. }
  5924. }
  5925. }
  5926. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  5927. return curZ;
  5928. };
  5929. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  5930. if (this.isManualZOrder) {
  5931. return;
  5932. }
  5933. this._setZOrder(newZ, false);
  5934. this._zMax = newZ;
  5935. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  5936. this._firstZDirtyIndex = Prim2DBase._bigInt;
  5937. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  5938. }
  5939. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  5940. var child = _a[_i];
  5941. child._updatePrimitiveFlatZOrder(newZ);
  5942. }
  5943. };
  5944. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  5945. if (newZ !== this._zOrder) {
  5946. this._zOrder = newZ;
  5947. this.onPrimBecomesDirty();
  5948. this.onZOrderChanged();
  5949. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  5950. if (directEmit) {
  5951. this._actualZOrderChangedObservable.notifyObservers(newZ);
  5952. }
  5953. else {
  5954. Prim2DBase._zOrderChangedNotifList.push(this);
  5955. }
  5956. }
  5957. }
  5958. };
  5959. Prim2DBase.prototype._updateRenderMode = function () {
  5960. };
  5961. /**
  5962. * This method is used to alter the contentArea of the Primitive before margin is applied.
  5963. * 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.
  5964. * @param primSize the current size of the primitive
  5965. * @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
  5966. * @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!
  5967. */
  5968. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  5969. initialContentArea.copyFrom(primSize);
  5970. initialContentPosition.x = initialContentPosition.y = initialContentPosition.z = initialContentPosition.w = 0;
  5971. };
  5972. /**
  5973. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  5974. * Check the Rectangle2D implementation for a concrete application.
  5975. * @param primSize the current size of the primitive
  5976. * @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!
  5977. */
  5978. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  5979. newPrimSize.copyFrom(primSize);
  5980. };
  5981. Prim2DBase.PRIM2DBASE_PROPCOUNT = 25;
  5982. Prim2DBase._bigInt = Math.pow(2, 30);
  5983. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  5984. Prim2DBase.boundinbBoxReentrency = false;
  5985. Prim2DBase.nullSize = BABYLON.Size.Zero();
  5986. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  5987. Prim2DBase._tpsBB = new BABYLON.BoundingInfo2D();
  5988. /**
  5989. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  5990. * @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.
  5991. */
  5992. Prim2DBase._bypassGroup2DExclusion = false;
  5993. Prim2DBase._isCanvasInit = false;
  5994. Prim2DBase._t0 = new BABYLON.Matrix();
  5995. Prim2DBase._t1 = new BABYLON.Matrix();
  5996. Prim2DBase._t2 = new BABYLON.Matrix();
  5997. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  5998. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  5999. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  6000. Prim2DBase._icZone = BABYLON.Vector4.Zero();
  6001. Prim2DBase._icArea = BABYLON.Size.Zero();
  6002. Prim2DBase._size = BABYLON.Size.Zero();
  6003. Prim2DBase._zOrderChangedNotifList = new Array();
  6004. Prim2DBase._zRebuildReentrency = false;
  6005. Prim2DBase._totalCount = 0;
  6006. __decorate([
  6007. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  6008. ], Prim2DBase.prototype, "actualPosition", null);
  6009. __decorate([
  6010. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 1, function (pi) { return Prim2DBase.actualXProperty = pi; }, false, false, true)
  6011. ], Prim2DBase.prototype, "actualX", null);
  6012. __decorate([
  6013. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 2, function (pi) { return Prim2DBase.actualYProperty = pi; }, false, false, true)
  6014. ], Prim2DBase.prototype, "actualY", null);
  6015. __decorate([
  6016. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 3, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  6017. ], Prim2DBase.prototype, "position", null);
  6018. __decorate([
  6019. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 4, function (pi) { return Prim2DBase.xProperty = pi; }, false, false, true)
  6020. ], Prim2DBase.prototype, "x", null);
  6021. __decorate([
  6022. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 5, function (pi) { return Prim2DBase.yProperty = pi; }, false, false, true)
  6023. ], Prim2DBase.prototype, "y", null);
  6024. __decorate([
  6025. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 6, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  6026. ], Prim2DBase.prototype, "size", null);
  6027. __decorate([
  6028. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 7, function (pi) { return Prim2DBase.widthProperty = pi; }, false, true)
  6029. ], Prim2DBase.prototype, "width", null);
  6030. __decorate([
  6031. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 8, function (pi) { return Prim2DBase.heightProperty = pi; }, false, true)
  6032. ], Prim2DBase.prototype, "height", null);
  6033. __decorate([
  6034. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 9, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  6035. ], Prim2DBase.prototype, "rotation", null);
  6036. __decorate([
  6037. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 10, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  6038. ], Prim2DBase.prototype, "scale", null);
  6039. __decorate([
  6040. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 11, function (pi) { return Prim2DBase.actualSizeProperty = pi; }, false, true)
  6041. ], Prim2DBase.prototype, "actualSize", null);
  6042. __decorate([
  6043. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 12, function (pi) { return Prim2DBase.actualWidthProperty = pi; }, false, true)
  6044. ], Prim2DBase.prototype, "actualWidth", null);
  6045. __decorate([
  6046. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 13, function (pi) { return Prim2DBase.actualHeightProperty = pi; }, false, true)
  6047. ], Prim2DBase.prototype, "actualHeight", null);
  6048. __decorate([
  6049. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 14, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  6050. ], Prim2DBase.prototype, "origin", null);
  6051. __decorate([
  6052. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 15, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  6053. ], Prim2DBase.prototype, "levelVisible", null);
  6054. __decorate([
  6055. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 16, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  6056. ], Prim2DBase.prototype, "isVisible", null);
  6057. __decorate([
  6058. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 17, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  6059. ], Prim2DBase.prototype, "zOrder", null);
  6060. __decorate([
  6061. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 18, function (pi) { return Prim2DBase.marginProperty = pi; })
  6062. ], Prim2DBase.prototype, "margin", null);
  6063. __decorate([
  6064. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 19, function (pi) { return Prim2DBase.paddingProperty = pi; })
  6065. ], Prim2DBase.prototype, "padding", null);
  6066. __decorate([
  6067. BABYLON.dynamicLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 20, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  6068. ], Prim2DBase.prototype, "marginAlignment", null);
  6069. __decorate([
  6070. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 21, function (pi) { return Prim2DBase.opacityProperty = pi; })
  6071. ], Prim2DBase.prototype, "opacity", null);
  6072. __decorate([
  6073. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 22, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  6074. ], Prim2DBase.prototype, "scaleX", null);
  6075. __decorate([
  6076. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 23, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  6077. ], Prim2DBase.prototype, "scaleY", null);
  6078. __decorate([
  6079. BABYLON.instanceLevelProperty(BABYLON.SmartPropertyPrim.SMARTPROPERTYPRIM_PROPCOUNT + 24, function (pi) { return Prim2DBase.actualScaleProperty = pi; }, false, true)
  6080. ], Prim2DBase.prototype, "actualScale", null);
  6081. Prim2DBase = __decorate([
  6082. BABYLON.className("Prim2DBase", "BABYLON")
  6083. ], Prim2DBase);
  6084. return Prim2DBase;
  6085. }(BABYLON.SmartPropertyPrim));
  6086. BABYLON.Prim2DBase = Prim2DBase;
  6087. })(BABYLON || (BABYLON = {}));
  6088. var BABYLON;
  6089. (function (BABYLON) {
  6090. var GroupInstanceInfo = (function () {
  6091. function GroupInstanceInfo(owner, mrc, partCount) {
  6092. this._partCount = partCount;
  6093. this.owner = owner;
  6094. this.modelRenderCache = mrc;
  6095. this.modelRenderCache.addRef();
  6096. this.partIndexFromId = new BABYLON.StringDictionary();
  6097. this._usedShaderCategories = new Array(partCount);
  6098. this._strides = new Array(partCount);
  6099. this._opaqueData = null;
  6100. this._alphaTestData = null;
  6101. this._transparentData = null;
  6102. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  6103. }
  6104. GroupInstanceInfo.prototype.dispose = function () {
  6105. if (this._isDisposed) {
  6106. return false;
  6107. }
  6108. if (this.modelRenderCache) {
  6109. this.modelRenderCache.dispose();
  6110. this.modelRenderCache = null;
  6111. }
  6112. var engine = this.owner.owner.engine;
  6113. if (this._opaqueData) {
  6114. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  6115. this._opaqueData = null;
  6116. }
  6117. if (this._alphaTestData) {
  6118. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  6119. this._alphaTestData = null;
  6120. }
  6121. if (this._transparentData) {
  6122. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  6123. this._transparentData = null;
  6124. }
  6125. this.partIndexFromId = null;
  6126. this._isDisposed = true;
  6127. return true;
  6128. };
  6129. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  6130. get: function () {
  6131. return this._opaqueData != null;
  6132. },
  6133. enumerable: true,
  6134. configurable: true
  6135. });
  6136. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  6137. get: function () {
  6138. return this._alphaTestData != null;
  6139. },
  6140. enumerable: true,
  6141. configurable: true
  6142. });
  6143. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  6144. get: function () {
  6145. return this._transparentData != null;
  6146. },
  6147. enumerable: true,
  6148. configurable: true
  6149. });
  6150. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  6151. get: function () {
  6152. if (!this._opaqueData) {
  6153. this._opaqueData = new Array(this._partCount);
  6154. for (var i = 0; i < this._partCount; i++) {
  6155. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  6156. }
  6157. }
  6158. return this._opaqueData;
  6159. },
  6160. enumerable: true,
  6161. configurable: true
  6162. });
  6163. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  6164. get: function () {
  6165. if (!this._alphaTestData) {
  6166. this._alphaTestData = new Array(this._partCount);
  6167. for (var i = 0; i < this._partCount; i++) {
  6168. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  6169. }
  6170. }
  6171. return this._alphaTestData;
  6172. },
  6173. enumerable: true,
  6174. configurable: true
  6175. });
  6176. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  6177. get: function () {
  6178. if (!this._transparentData) {
  6179. this._transparentData = new Array(this._partCount);
  6180. for (var i = 0; i < this._partCount; i++) {
  6181. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  6182. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  6183. }
  6184. }
  6185. return this._transparentData;
  6186. },
  6187. enumerable: true,
  6188. configurable: true
  6189. });
  6190. GroupInstanceInfo.prototype.sortTransparentData = function () {
  6191. if (!this.transparentOrderDirty) {
  6192. return;
  6193. }
  6194. for (var i = 0; i < this._transparentData.length; i++) {
  6195. var td = this._transparentData[i];
  6196. td._partData.sort();
  6197. }
  6198. this.transparentOrderDirty = false;
  6199. };
  6200. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  6201. get: function () {
  6202. return this._usedShaderCategories;
  6203. },
  6204. enumerable: true,
  6205. configurable: true
  6206. });
  6207. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  6208. get: function () {
  6209. return this._strides;
  6210. },
  6211. enumerable: true,
  6212. configurable: true
  6213. });
  6214. return GroupInstanceInfo;
  6215. }());
  6216. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  6217. var TransparentSegment = (function () {
  6218. function TransparentSegment() {
  6219. this.groupInsanceInfo = null;
  6220. this.startZ = 0;
  6221. this.endZ = 0;
  6222. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  6223. this.endDataIndex = 0;
  6224. this.partBuffers = null;
  6225. }
  6226. TransparentSegment.prototype.dispose = function (engine) {
  6227. if (this.partBuffers) {
  6228. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  6229. this.partBuffers.splice(0);
  6230. this.partBuffers = null;
  6231. }
  6232. };
  6233. return TransparentSegment;
  6234. }());
  6235. BABYLON.TransparentSegment = TransparentSegment;
  6236. var GroupInfoPartData = (function () {
  6237. function GroupInfoPartData(stride) {
  6238. this._partData = null;
  6239. this._partBuffer = null;
  6240. this._partBufferSize = 0;
  6241. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  6242. this._isDisposed = false;
  6243. }
  6244. GroupInfoPartData.prototype.dispose = function (engine) {
  6245. if (this._isDisposed) {
  6246. return false;
  6247. }
  6248. if (this._partBuffer) {
  6249. engine._releaseBuffer(this._partBuffer);
  6250. this._partBuffer = null;
  6251. }
  6252. this._partData = null;
  6253. this._isDisposed = true;
  6254. };
  6255. return GroupInfoPartData;
  6256. }());
  6257. BABYLON.GroupInfoPartData = GroupInfoPartData;
  6258. var TransparentGroupInfoPartData = (function (_super) {
  6259. __extends(TransparentGroupInfoPartData, _super);
  6260. function TransparentGroupInfoPartData(stride, zoff) {
  6261. _super.call(this, stride);
  6262. this._partData.compareValueOffset = zoff;
  6263. this._partData.sortingAscending = false;
  6264. }
  6265. return TransparentGroupInfoPartData;
  6266. }(GroupInfoPartData));
  6267. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  6268. var ModelRenderCache = (function () {
  6269. function ModelRenderCache(engine, modelKey) {
  6270. this._engine = engine;
  6271. this._modelKey = modelKey;
  6272. this._nextKey = 1;
  6273. this._refCounter = 1;
  6274. this._partData = null;
  6275. }
  6276. ModelRenderCache.prototype.dispose = function () {
  6277. if (--this._refCounter !== 0) {
  6278. return false;
  6279. }
  6280. // Remove the Model Render Cache from the global dictionary
  6281. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  6282. if (edata) {
  6283. edata.DisposeModelRenderCache(this);
  6284. }
  6285. return true;
  6286. };
  6287. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  6288. get: function () {
  6289. return this._refCounter <= 0;
  6290. },
  6291. enumerable: true,
  6292. configurable: true
  6293. });
  6294. ModelRenderCache.prototype.addRef = function () {
  6295. return ++this._refCounter;
  6296. };
  6297. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  6298. get: function () {
  6299. return this._modelKey;
  6300. },
  6301. enumerable: true,
  6302. configurable: true
  6303. });
  6304. /**
  6305. * Render the model instances
  6306. * @param instanceInfo
  6307. * @param context
  6308. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  6309. */
  6310. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  6311. return true;
  6312. };
  6313. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  6314. for (var i = 0; i < this._partData.length; i++) {
  6315. if (this._partData[i]._partId === partId) {
  6316. return i;
  6317. }
  6318. }
  6319. return null;
  6320. };
  6321. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  6322. var i = this.getPartIndexFromId(partId);
  6323. if (i === null) {
  6324. return null;
  6325. }
  6326. var ci = this._partsClassInfo[i];
  6327. var categories = this._partData[i]._partUsedCategories;
  6328. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  6329. return res;
  6330. };
  6331. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  6332. var pd = this._partData[partIndex];
  6333. var offset = (pd._partDataStride / 4) * elementCount;
  6334. var pci = this._partsClassInfo[partIndex];
  6335. var self = this;
  6336. pci.fullContent.forEach(function (k, v) {
  6337. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  6338. switch (v.dataType) {
  6339. case 4 /* float */:
  6340. {
  6341. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  6342. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  6343. break;
  6344. }
  6345. case 0 /* Vector2 */:
  6346. {
  6347. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  6348. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  6349. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  6350. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  6351. break;
  6352. }
  6353. case 5 /* Color3 */:
  6354. case 1 /* Vector3 */:
  6355. {
  6356. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  6357. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  6358. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  6359. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  6360. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  6361. break;
  6362. }
  6363. case 6 /* Color4 */:
  6364. case 2 /* Vector4 */:
  6365. {
  6366. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  6367. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  6368. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  6369. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  6370. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  6371. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  6372. break;
  6373. }
  6374. default:
  6375. }
  6376. }
  6377. });
  6378. };
  6379. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  6380. // let i = this.getPartIndexFromId(partId);
  6381. // if (i === null) {
  6382. // return null;
  6383. // }
  6384. // let pci = this._partsClassInfo[i];
  6385. // pci.fullContent.forEach((k, v) => {
  6386. // if (uniforms.indexOf(v.attributeName) !== -1) {
  6387. // v.uniformLocation = effect.getUniform(v.attributeName);
  6388. // }
  6389. // });
  6390. //}
  6391. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  6392. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  6393. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  6394. return ModelRenderCache;
  6395. }());
  6396. BABYLON.ModelRenderCache = ModelRenderCache;
  6397. var ModelRenderCachePartData = (function () {
  6398. function ModelRenderCachePartData() {
  6399. }
  6400. return ModelRenderCachePartData;
  6401. }());
  6402. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  6403. })(BABYLON || (BABYLON = {}));
  6404. var BABYLON;
  6405. (function (BABYLON) {
  6406. var InstanceClassInfo = (function () {
  6407. function InstanceClassInfo(base) {
  6408. this._baseInfo = base;
  6409. this._nextOffset = new BABYLON.StringDictionary();
  6410. this._attributes = new Array();
  6411. }
  6412. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  6413. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  6414. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  6415. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  6416. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  6417. if (push) {
  6418. this._attributes.push(propInfo);
  6419. }
  6420. };
  6421. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  6422. var catInline = ";" + categories.join(";") + ";";
  6423. var res = new Array();
  6424. var curInfo = this;
  6425. while (curInfo) {
  6426. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  6427. var attrib = _a[_i];
  6428. // 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
  6429. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  6430. var index = effect.getAttributeLocationByName(attrib.attributeName);
  6431. var iai = new BABYLON.InstancingAttributeInfo();
  6432. iai.index = index;
  6433. 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)
  6434. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  6435. iai.attributeName = attrib.attributeName;
  6436. res.push(iai);
  6437. }
  6438. }
  6439. curInfo = curInfo._baseInfo;
  6440. }
  6441. return res;
  6442. };
  6443. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  6444. var res = new Array();
  6445. var curInfo = this;
  6446. while (curInfo) {
  6447. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  6448. var attrib = _a[_i];
  6449. // 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
  6450. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  6451. res.push(attrib.attributeName);
  6452. }
  6453. }
  6454. curInfo = curInfo._baseInfo;
  6455. }
  6456. return res;
  6457. };
  6458. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  6459. var curOffset = 0;
  6460. var curBase = this._baseInfo;
  6461. while (curBase) {
  6462. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  6463. curBase = curBase._baseInfo;
  6464. }
  6465. return curOffset;
  6466. };
  6467. return InstanceClassInfo;
  6468. }());
  6469. BABYLON.InstanceClassInfo = InstanceClassInfo;
  6470. var InstancePropInfo = (function () {
  6471. function InstancePropInfo() {
  6472. this.instanceOffset = new BABYLON.StringDictionary();
  6473. }
  6474. InstancePropInfo.prototype.setSize = function (val) {
  6475. if (val instanceof BABYLON.Vector2) {
  6476. this.size = 8;
  6477. this.dataType = 0 /* Vector2 */;
  6478. return;
  6479. }
  6480. if (val instanceof BABYLON.Vector3) {
  6481. this.size = 12;
  6482. this.dataType = 1 /* Vector3 */;
  6483. return;
  6484. }
  6485. if (val instanceof BABYLON.Vector4) {
  6486. this.size = 16;
  6487. this.dataType = 2 /* Vector4 */;
  6488. return;
  6489. }
  6490. if (val instanceof BABYLON.Matrix) {
  6491. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  6492. }
  6493. if (typeof (val) === "number") {
  6494. this.size = 4;
  6495. this.dataType = 4 /* float */;
  6496. return;
  6497. }
  6498. if (val instanceof BABYLON.Color3) {
  6499. this.size = 12;
  6500. this.dataType = 5 /* Color3 */;
  6501. return;
  6502. }
  6503. if (val instanceof BABYLON.Color4) {
  6504. this.size = 16;
  6505. this.dataType = 6 /* Color4 */;
  6506. return;
  6507. }
  6508. if (val instanceof BABYLON.Size) {
  6509. this.size = 8;
  6510. this.dataType = 7 /* Size */;
  6511. return;
  6512. }
  6513. return;
  6514. };
  6515. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  6516. switch (this.dataType) {
  6517. case 0 /* Vector2 */:
  6518. {
  6519. var v = val;
  6520. array[offset + 0] = v.x;
  6521. array[offset + 1] = v.y;
  6522. break;
  6523. }
  6524. case 1 /* Vector3 */:
  6525. {
  6526. var v = val;
  6527. array[offset + 0] = v.x;
  6528. array[offset + 1] = v.y;
  6529. array[offset + 2] = v.z;
  6530. break;
  6531. }
  6532. case 2 /* Vector4 */:
  6533. {
  6534. var v = val;
  6535. array[offset + 0] = v.x;
  6536. array[offset + 1] = v.y;
  6537. array[offset + 2] = v.z;
  6538. array[offset + 3] = v.w;
  6539. break;
  6540. }
  6541. case 5 /* Color3 */:
  6542. {
  6543. var v = val;
  6544. array[offset + 0] = v.r;
  6545. array[offset + 1] = v.g;
  6546. array[offset + 2] = v.b;
  6547. break;
  6548. }
  6549. case 6 /* Color4 */:
  6550. {
  6551. var v = val;
  6552. array[offset + 0] = v.r;
  6553. array[offset + 1] = v.g;
  6554. array[offset + 2] = v.b;
  6555. array[offset + 3] = v.a;
  6556. break;
  6557. }
  6558. case 4 /* float */:
  6559. {
  6560. var v = val;
  6561. array[offset] = v;
  6562. break;
  6563. }
  6564. case 3 /* Matrix */:
  6565. {
  6566. var v = val;
  6567. for (var i = 0; i < 16; i++) {
  6568. array[offset + i] = v.m[i];
  6569. }
  6570. break;
  6571. }
  6572. case 7 /* Size */:
  6573. {
  6574. var s = val;
  6575. array[offset + 0] = s.width;
  6576. array[offset + 1] = s.height;
  6577. break;
  6578. }
  6579. }
  6580. };
  6581. return InstancePropInfo;
  6582. }());
  6583. BABYLON.InstancePropInfo = InstancePropInfo;
  6584. function instanceData(category, shaderAttributeName) {
  6585. return function (target, propName, descriptor) {
  6586. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  6587. var node = dic.getLevelOf(target);
  6588. var instanceDataName = propName;
  6589. shaderAttributeName = shaderAttributeName || instanceDataName;
  6590. var info = node.levelContent.get(instanceDataName);
  6591. if (info) {
  6592. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  6593. }
  6594. info = new InstancePropInfo();
  6595. info.attributeName = shaderAttributeName;
  6596. info.category = category || null;
  6597. if (info.category) {
  6598. info.delimitedCategory = ";" + info.category + ";";
  6599. }
  6600. node.levelContent.add(instanceDataName, info);
  6601. descriptor.get = function () {
  6602. return null;
  6603. };
  6604. descriptor.set = function (val) {
  6605. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  6606. // Quit if it's the case, otherwise we could overwrite data somewhere...
  6607. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  6608. return;
  6609. }
  6610. if (!info.size) {
  6611. info.setSize(val);
  6612. node.classContent.mapProperty(info, true);
  6613. }
  6614. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  6615. node.classContent.mapProperty(info, false);
  6616. }
  6617. var obj = this;
  6618. if (obj.dataBuffer && obj.dataElements) {
  6619. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  6620. info.writeData(obj.dataBuffer.buffer, offset, val);
  6621. }
  6622. };
  6623. };
  6624. }
  6625. BABYLON.instanceData = instanceData;
  6626. var InstanceDataBase = (function () {
  6627. function InstanceDataBase(partId, dataElementCount) {
  6628. this.id = partId;
  6629. this.curElement = 0;
  6630. this._dataElementCount = dataElementCount;
  6631. this.renderMode = 0;
  6632. this.arrayLengthChanged = false;
  6633. }
  6634. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  6635. get: function () {
  6636. return null;
  6637. },
  6638. set: function (value) {
  6639. },
  6640. enumerable: true,
  6641. configurable: true
  6642. });
  6643. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  6644. get: function () {
  6645. return null;
  6646. },
  6647. set: function (value) {
  6648. },
  6649. enumerable: true,
  6650. configurable: true
  6651. });
  6652. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  6653. get: function () {
  6654. return null;
  6655. },
  6656. set: function (value) {
  6657. },
  6658. enumerable: true,
  6659. configurable: true
  6660. });
  6661. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  6662. get: function () {
  6663. return null;
  6664. },
  6665. set: function (value) {
  6666. },
  6667. enumerable: true,
  6668. configurable: true
  6669. });
  6670. InstanceDataBase.prototype.getClassTreeInfo = function () {
  6671. if (!this.typeInfo) {
  6672. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  6673. }
  6674. return this.typeInfo;
  6675. };
  6676. InstanceDataBase.prototype.allocElements = function () {
  6677. if (!this.dataBuffer || this.dataElements) {
  6678. return;
  6679. }
  6680. var res = new Array(this.dataElementCount);
  6681. for (var i = 0; i < this.dataElementCount; i++) {
  6682. res[i] = this.dataBuffer.allocElement();
  6683. }
  6684. this.dataElements = res;
  6685. };
  6686. InstanceDataBase.prototype.freeElements = function () {
  6687. if (!this.dataElements) {
  6688. return;
  6689. }
  6690. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  6691. var ei = _a[_i];
  6692. this.dataBuffer.freeElement(ei);
  6693. }
  6694. this.dataElements = null;
  6695. };
  6696. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  6697. get: function () {
  6698. return this._dataElementCount;
  6699. },
  6700. set: function (value) {
  6701. if (value === this._dataElementCount) {
  6702. return;
  6703. }
  6704. this.arrayLengthChanged = true;
  6705. this.freeElements();
  6706. this._dataElementCount = value;
  6707. this.allocElements();
  6708. },
  6709. enumerable: true,
  6710. configurable: true
  6711. });
  6712. __decorate([
  6713. instanceData()
  6714. ], InstanceDataBase.prototype, "zBias", null);
  6715. __decorate([
  6716. instanceData()
  6717. ], InstanceDataBase.prototype, "transformX", null);
  6718. __decorate([
  6719. instanceData()
  6720. ], InstanceDataBase.prototype, "transformY", null);
  6721. __decorate([
  6722. instanceData()
  6723. ], InstanceDataBase.prototype, "opacity", null);
  6724. return InstanceDataBase;
  6725. }());
  6726. BABYLON.InstanceDataBase = InstanceDataBase;
  6727. var RenderablePrim2D = (function (_super) {
  6728. __extends(RenderablePrim2D, _super);
  6729. function RenderablePrim2D(settings) {
  6730. _super.call(this, settings);
  6731. this._transparentPrimitiveInfo = null;
  6732. }
  6733. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  6734. get: function () {
  6735. return this._useTextureAlpha() || this._isPrimAlphaTest();
  6736. },
  6737. enumerable: true,
  6738. configurable: true
  6739. });
  6740. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  6741. get: function () {
  6742. return (this.actualOpacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  6743. },
  6744. enumerable: true,
  6745. configurable: true
  6746. });
  6747. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  6748. get: function () {
  6749. return this._renderMode;
  6750. },
  6751. enumerable: true,
  6752. configurable: true
  6753. });
  6754. /**
  6755. * Dispose the primitive and its resources, remove it from its parent
  6756. */
  6757. RenderablePrim2D.prototype.dispose = function () {
  6758. if (!_super.prototype.dispose.call(this)) {
  6759. return false;
  6760. }
  6761. if (this.renderGroup) {
  6762. this.renderGroup._setCacheGroupDirty();
  6763. }
  6764. if (this._transparentPrimitiveInfo) {
  6765. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  6766. this._transparentPrimitiveInfo = null;
  6767. }
  6768. if (this._instanceDataParts) {
  6769. this._cleanupInstanceDataParts();
  6770. }
  6771. if (this._modelRenderCache) {
  6772. this._modelRenderCache.dispose();
  6773. this._modelRenderCache = null;
  6774. }
  6775. if (this._instanceDataParts) {
  6776. this._instanceDataParts.forEach(function (p) {
  6777. p.freeElements();
  6778. });
  6779. this._instanceDataParts = null;
  6780. }
  6781. return true;
  6782. };
  6783. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  6784. var gii = null;
  6785. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  6786. var part = _a[_i];
  6787. part.freeElements();
  6788. gii = part.groupInstanceInfo;
  6789. }
  6790. if (gii) {
  6791. var usedCount = 0;
  6792. if (gii.hasOpaqueData) {
  6793. var od = gii.opaqueData[0];
  6794. usedCount += od._partData.usedElementCount;
  6795. gii.opaqueDirty = true;
  6796. }
  6797. if (gii.hasAlphaTestData) {
  6798. var atd = gii.alphaTestData[0];
  6799. usedCount += atd._partData.usedElementCount;
  6800. gii.alphaTestDirty = true;
  6801. }
  6802. if (gii.hasTransparentData) {
  6803. var td = gii.transparentData[0];
  6804. usedCount += td._partData.usedElementCount;
  6805. gii.transparentDirty = true;
  6806. }
  6807. if (usedCount === 0 && gii.modelRenderCache != null) {
  6808. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  6809. gii.dispose();
  6810. }
  6811. if (this._modelRenderCache) {
  6812. this._modelRenderCache.dispose();
  6813. this._modelRenderCache = null;
  6814. }
  6815. }
  6816. this._instanceDataParts = null;
  6817. };
  6818. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  6819. _super.prototype._prepareRenderPre.call(this, context);
  6820. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  6821. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  6822. this._cleanupInstanceDataParts();
  6823. }
  6824. // Need to create the model?
  6825. var setupModelRenderCache = false;
  6826. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  6827. setupModelRenderCache = this._createModelRenderCache();
  6828. }
  6829. var gii = null;
  6830. var newInstance = false;
  6831. // Need to create the instance data parts?
  6832. if (!this._instanceDataParts) {
  6833. // Yes, flag it for later, more processing will have to be done
  6834. newInstance = true;
  6835. gii = this._createModelDataParts();
  6836. }
  6837. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  6838. if (setupModelRenderCache) {
  6839. this.setupModelRenderCache(this._modelRenderCache);
  6840. }
  6841. // 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.
  6842. // 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.
  6843. if (this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagNeedRefresh) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  6844. this._updateInstanceDataParts(gii);
  6845. }
  6846. };
  6847. RenderablePrim2D.prototype._createModelRenderCache = function () {
  6848. var _this = this;
  6849. var setupModelRenderCache = false;
  6850. if (this._modelRenderCache) {
  6851. this._modelRenderCache.dispose();
  6852. }
  6853. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  6854. var mrc = _this.createModelRenderCache(key);
  6855. setupModelRenderCache = true;
  6856. return mrc;
  6857. });
  6858. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  6859. // if this is still false it means the MRC already exists, so we add a reference to it
  6860. if (!setupModelRenderCache) {
  6861. this._modelRenderCache.addRef();
  6862. }
  6863. return setupModelRenderCache;
  6864. };
  6865. RenderablePrim2D.prototype._createModelDataParts = function () {
  6866. var _this = this;
  6867. // Create the instance data parts of the primitive and store them
  6868. var parts = this.createInstanceDataParts();
  6869. this._instanceDataParts = parts;
  6870. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  6871. if (!this._modelRenderCache._partData) {
  6872. this._setupModelRenderCache(parts);
  6873. }
  6874. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  6875. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  6876. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  6877. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  6878. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  6879. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  6880. var part = _this._instanceDataParts[j];
  6881. res.partIndexFromId.add(part.id.toString(), j);
  6882. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  6883. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  6884. }
  6885. return res;
  6886. });
  6887. // Get the GroupInfoDataPart corresponding to the render category of the part
  6888. var rm = 0;
  6889. var gipd = null;
  6890. if (this.isTransparent) {
  6891. gipd = gii.transparentData;
  6892. rm = BABYLON.Render2DContext.RenderModeTransparent;
  6893. }
  6894. else if (this.isAlphaTest) {
  6895. gipd = gii.alphaTestData;
  6896. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  6897. }
  6898. else {
  6899. gipd = gii.opaqueData;
  6900. rm = BABYLON.Render2DContext.RenderModeOpaque;
  6901. }
  6902. // For each instance data part of the primitive, allocate the instanced element it needs for render
  6903. for (var i = 0; i < parts.length; i++) {
  6904. var part = parts[i];
  6905. part.dataBuffer = gipd[i]._partData;
  6906. part.allocElements();
  6907. part.renderMode = rm;
  6908. part.groupInstanceInfo = gii;
  6909. }
  6910. return gii;
  6911. };
  6912. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  6913. var ctiArray = new Array();
  6914. this._modelRenderCache._partData = new Array();
  6915. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  6916. var dataPart = parts_1[_i];
  6917. var pd = new BABYLON.ModelRenderCachePartData();
  6918. this._modelRenderCache._partData.push(pd);
  6919. var cat = this.getUsedShaderCategories(dataPart);
  6920. var cti = dataPart.getClassTreeInfo();
  6921. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  6922. var curVisible = this.isVisible;
  6923. this.isVisible = true;
  6924. // 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.
  6925. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  6926. var joinCat = ";" + cat.join(";") + ";";
  6927. pd._partJoinedUsedCategories = joinCat;
  6928. InstanceClassInfo._CurCategories = joinCat;
  6929. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  6930. if (!this.refreshInstanceDataPart(dataPart)) {
  6931. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  6932. }
  6933. this.afterRefreshForLayoutConstruction(dataPart, obj);
  6934. this.isVisible = curVisible;
  6935. var size = 0;
  6936. cti.fullContent.forEach(function (k, v) {
  6937. if (!v.category || cat.indexOf(v.category) !== -1) {
  6938. if (v.attributeName === "zBias") {
  6939. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  6940. }
  6941. if (!v.size) {
  6942. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  6943. }
  6944. else {
  6945. size += v.size;
  6946. }
  6947. }
  6948. });
  6949. pd._partDataStride = size;
  6950. pd._partUsedCategories = cat;
  6951. pd._partId = dataPart.id;
  6952. ctiArray.push(cti);
  6953. }
  6954. this._modelRenderCache._partsClassInfo = ctiArray;
  6955. };
  6956. RenderablePrim2D.prototype.onZOrderChanged = function () {
  6957. if (this.isTransparent && this._transparentPrimitiveInfo) {
  6958. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  6959. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  6960. // Flag the transparentData dirty has will have to sort it again
  6961. gii.transparentOrderDirty = true;
  6962. }
  6963. };
  6964. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  6965. return false;
  6966. };
  6967. RenderablePrim2D.prototype._useTextureAlpha = function () {
  6968. return false;
  6969. };
  6970. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  6971. return false;
  6972. };
  6973. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  6974. return false;
  6975. };
  6976. RenderablePrim2D.prototype._isPrimTransparent = function () {
  6977. return false;
  6978. };
  6979. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  6980. // Fetch the GroupInstanceInfo if we don't already have it
  6981. var rd = this.renderGroup._renderableData;
  6982. if (!gii) {
  6983. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  6984. }
  6985. var isTransparent = this.isTransparent;
  6986. var isAlphaTest = this.isAlphaTest;
  6987. var wereTransparent = false;
  6988. // Check a render mode change
  6989. var rmChanged = false;
  6990. if (this._instanceDataParts.length > 0) {
  6991. var firstPart = this._instanceDataParts[0];
  6992. var partRM = firstPart.renderMode;
  6993. var curRM = this.renderMode;
  6994. if (partRM !== curRM) {
  6995. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  6996. rmChanged = true;
  6997. var gipd = void 0;
  6998. switch (curRM) {
  6999. case BABYLON.Render2DContext.RenderModeTransparent:
  7000. gipd = gii.transparentData;
  7001. break;
  7002. case BABYLON.Render2DContext.RenderModeAlphaTest:
  7003. gipd = gii.alphaTestData;
  7004. break;
  7005. default:
  7006. gipd = gii.opaqueData;
  7007. }
  7008. for (var i = 0; i < this._instanceDataParts.length; i++) {
  7009. var part = this._instanceDataParts[i];
  7010. part.freeElements();
  7011. part.dataBuffer = gipd[i]._partData;
  7012. part.renderMode = curRM;
  7013. }
  7014. }
  7015. }
  7016. // Handle changes related to ZOffset
  7017. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  7018. if (isTransparent || wereTransparent) {
  7019. // Handle visibility change, which is also triggered when the primitive just got created
  7020. if (visChanged || rmChanged) {
  7021. if (this.isVisible && !wereTransparent) {
  7022. if (!this._transparentPrimitiveInfo) {
  7023. // Add the primitive to the list of transparent ones in the group that render is
  7024. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  7025. }
  7026. }
  7027. else {
  7028. if (this._transparentPrimitiveInfo) {
  7029. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  7030. this._transparentPrimitiveInfo = null;
  7031. }
  7032. }
  7033. gii.transparentOrderDirty = true;
  7034. }
  7035. }
  7036. var rebuildTrans = false;
  7037. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  7038. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  7039. var part = _a[_i];
  7040. var justAllocated = false;
  7041. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  7042. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  7043. part.allocElements();
  7044. justAllocated = true;
  7045. }
  7046. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  7047. // Will return false if the instance should not be rendered (not visible or other any reasons)
  7048. part.arrayLengthChanged = false;
  7049. if (!this.refreshInstanceDataPart(part)) {
  7050. // Free the data element
  7051. if (part.dataElements) {
  7052. part.freeElements();
  7053. }
  7054. // The refresh couldn't succeed, push the primitive to be dirty again for the next render
  7055. if (this.isVisible) {
  7056. rd._primNewDirtyList.push(this);
  7057. }
  7058. }
  7059. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  7060. }
  7061. this._instanceDirtyFlags = 0;
  7062. // Make the appropriate data dirty
  7063. if (isTransparent) {
  7064. gii.transparentDirty = true;
  7065. if (rebuildTrans) {
  7066. rd._transparentListChanged = true;
  7067. }
  7068. }
  7069. else if (isAlphaTest) {
  7070. gii.alphaTestDirty = true;
  7071. }
  7072. else {
  7073. gii.opaqueDirty = true;
  7074. }
  7075. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  7076. };
  7077. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  7078. var minOff = BABYLON.Prim2DBase._bigInt;
  7079. var maxOff = 0;
  7080. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  7081. var part = _a[_i];
  7082. if (part && part.dataElements) {
  7083. part.dataBuffer.pack();
  7084. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  7085. var el = _c[_b];
  7086. minOff = Math.min(minOff, el.offset);
  7087. maxOff = Math.max(maxOff, el.offset);
  7088. }
  7089. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  7090. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  7091. }
  7092. }
  7093. };
  7094. // This internal method is mainly used for transparency processing
  7095. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  7096. var length = this._instanceDataParts.length;
  7097. for (var i = 0; i < length; i++) {
  7098. var part = this._instanceDataParts[i];
  7099. if (part) {
  7100. var stride = part.dataBuffer.stride;
  7101. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  7102. // check if it's the last in the DFA
  7103. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  7104. return null;
  7105. }
  7106. // Return the Z of the next primitive that lies in the DFA
  7107. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  7108. }
  7109. }
  7110. return null;
  7111. };
  7112. // This internal method is mainly used for transparency processing
  7113. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  7114. var length = this._instanceDataParts.length;
  7115. for (var i = 0; i < length; i++) {
  7116. var part = this._instanceDataParts[i];
  7117. if (part) {
  7118. var stride = part.dataBuffer.stride;
  7119. var firstElementOffset = part.dataElements[0].offset;
  7120. // check if it's the first in the DFA
  7121. if (firstElementOffset === 0) {
  7122. return null;
  7123. }
  7124. // Return the Z of the previous primitive that lies in the DFA
  7125. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  7126. }
  7127. }
  7128. return null;
  7129. };
  7130. /**
  7131. * Transform a given point using the Primitive's origin setting.
  7132. * This method requires the Primitive's actualSize to be accurate
  7133. * @param p the point to transform
  7134. * @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.
  7135. * @param res an allocated Vector2 that will receive the transformed content
  7136. */
  7137. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  7138. var actualSize = this.actualSize;
  7139. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  7140. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  7141. };
  7142. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  7143. this.transformPointWithOriginByRef(p, originOffset, res);
  7144. return res;
  7145. };
  7146. /**
  7147. * Get the info for a given effect based on the dataPart metadata
  7148. * @param dataPartId partId in part list to get the info
  7149. * @param vertexBufferAttributes vertex buffer attributes to manually add
  7150. * @param uniforms uniforms to manually add
  7151. * @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
  7152. */
  7153. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  7154. if (uniforms === void 0) { uniforms = null; }
  7155. if (useInstanced === void 0) { useInstanced = null; }
  7156. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  7157. if (!dataPart) {
  7158. return null;
  7159. }
  7160. var instancedArray = this.owner.supportInstancedArray;
  7161. if (useInstanced != null) {
  7162. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  7163. if (useInstanced && instancedArray === false) {
  7164. return null;
  7165. }
  7166. // Use the caller's setting
  7167. instancedArray = useInstanced;
  7168. }
  7169. var cti = dataPart.getClassTreeInfo();
  7170. var categories = this.getUsedShaderCategories(dataPart);
  7171. var att = cti.classContent.getShaderAttributes(categories);
  7172. var defines = "";
  7173. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  7174. if (instancedArray) {
  7175. defines += "#define Instanced\n";
  7176. }
  7177. return {
  7178. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  7179. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  7180. defines: defines
  7181. };
  7182. };
  7183. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  7184. get: function () {
  7185. return this._modelRenderCache;
  7186. },
  7187. enumerable: true,
  7188. configurable: true
  7189. });
  7190. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  7191. return null;
  7192. };
  7193. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  7194. };
  7195. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  7196. return null;
  7197. };
  7198. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  7199. return [];
  7200. };
  7201. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  7202. };
  7203. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  7204. };
  7205. RenderablePrim2D.prototype.applyActualScaleOnTransform = function () {
  7206. return true;
  7207. };
  7208. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  7209. if (!this.isVisible) {
  7210. return false;
  7211. }
  7212. part.isVisible = this.isVisible;
  7213. // 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)
  7214. if (part.dataElementCount === 1) {
  7215. part.curElement = 0;
  7216. this.updateInstanceDataPart(part);
  7217. }
  7218. return true;
  7219. };
  7220. /**
  7221. * Update the instanceDataBase level properties of a part
  7222. * @param part the part to update
  7223. * @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).
  7224. */
  7225. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  7226. if (positionOffset === void 0) { positionOffset = null; }
  7227. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform); // Compute the transformation into the renderGroup's space
  7228. var rgScale = this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagDontInheritParentScale) ? RenderablePrim2D._uV : this.renderGroup.actualScale; // We still need to apply the scale of the renderGroup to our rendering, so get it.
  7229. var size = this.renderGroup.viewportSize;
  7230. var zBias = this.actualZOffset;
  7231. var offX = 0;
  7232. var offY = 0;
  7233. // If there's an offset, apply the global transformation matrix on it to get a global offset
  7234. if (positionOffset) {
  7235. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  7236. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  7237. }
  7238. // 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
  7239. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  7240. // So for X:
  7241. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  7242. // - 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].
  7243. // At last we don't forget to apply the actualScale of the Render Group to tx[0] and ty[1] to propagate scaling correctly
  7244. var w = size.width;
  7245. var h = size.height;
  7246. var invZBias = 1 / zBias;
  7247. var tx = new BABYLON.Vector4(t.m[0] * rgScale.x * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * rgScale.x * 2 / w) - 1);
  7248. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * rgScale.y * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * rgScale.y * 2 / h) - 1);
  7249. if (!this.applyActualScaleOnTransform()) {
  7250. var las = this.actualScale;
  7251. tx.x /= las.x;
  7252. ty.y /= las.y;
  7253. }
  7254. part.transformX = tx;
  7255. part.transformY = ty;
  7256. part.opacity = this.actualOpacity;
  7257. // 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)
  7258. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  7259. };
  7260. RenderablePrim2D.prototype._updateRenderMode = function () {
  7261. if (this.isTransparent) {
  7262. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  7263. }
  7264. else if (this.isAlphaTest) {
  7265. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  7266. }
  7267. else {
  7268. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  7269. }
  7270. };
  7271. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  7272. RenderablePrim2D._uV = new BABYLON.Vector2(1, 1);
  7273. __decorate([
  7274. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  7275. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  7276. __decorate([
  7277. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  7278. ], RenderablePrim2D.prototype, "isTransparent", null);
  7279. RenderablePrim2D = __decorate([
  7280. BABYLON.className("RenderablePrim2D", "BABYLON")
  7281. ], RenderablePrim2D);
  7282. return RenderablePrim2D;
  7283. }(BABYLON.Prim2DBase));
  7284. BABYLON.RenderablePrim2D = RenderablePrim2D;
  7285. })(BABYLON || (BABYLON = {}));
  7286. var BABYLON;
  7287. (function (BABYLON) {
  7288. var Shape2D = (function (_super) {
  7289. __extends(Shape2D, _super);
  7290. function Shape2D(settings) {
  7291. _super.call(this, settings);
  7292. if (!settings) {
  7293. settings = {};
  7294. }
  7295. var borderBrush = null;
  7296. if (settings.border) {
  7297. if (typeof (settings.border) === "string") {
  7298. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  7299. }
  7300. else {
  7301. borderBrush = settings.border;
  7302. }
  7303. }
  7304. var fillBrush = null;
  7305. if (settings.fill) {
  7306. if (typeof (settings.fill) === "string") {
  7307. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  7308. }
  7309. else {
  7310. fillBrush = settings.fill;
  7311. }
  7312. }
  7313. this._isTransparent = false;
  7314. this._oldTransparent = false;
  7315. this.border = borderBrush;
  7316. this.fill = fillBrush;
  7317. this._updateTransparencyStatus();
  7318. this.borderThickness = settings.borderThickness;
  7319. }
  7320. Object.defineProperty(Shape2D.prototype, "border", {
  7321. get: function () {
  7322. return this._border;
  7323. },
  7324. set: function (value) {
  7325. this._border = value;
  7326. this._updateTransparencyStatus();
  7327. },
  7328. enumerable: true,
  7329. configurable: true
  7330. });
  7331. Object.defineProperty(Shape2D.prototype, "fill", {
  7332. /**
  7333. * Get/set the brush to render the Fill part of the Primitive
  7334. */
  7335. get: function () {
  7336. return this._fill;
  7337. },
  7338. set: function (value) {
  7339. this._fill = value;
  7340. this._updateTransparencyStatus();
  7341. },
  7342. enumerable: true,
  7343. configurable: true
  7344. });
  7345. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  7346. get: function () {
  7347. return this._borderThickness;
  7348. },
  7349. set: function (value) {
  7350. this._borderThickness = value;
  7351. },
  7352. enumerable: true,
  7353. configurable: true
  7354. });
  7355. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  7356. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  7357. // Fill Part
  7358. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  7359. var fill = this.fill;
  7360. if (fill instanceof BABYLON.SolidColorBrush2D) {
  7361. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  7362. }
  7363. if (fill instanceof BABYLON.GradientColorBrush2D) {
  7364. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  7365. }
  7366. }
  7367. // Border Part
  7368. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  7369. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  7370. var border = this.border;
  7371. if (border instanceof BABYLON.SolidColorBrush2D) {
  7372. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  7373. }
  7374. if (border instanceof BABYLON.GradientColorBrush2D) {
  7375. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  7376. }
  7377. }
  7378. return cat;
  7379. };
  7380. Shape2D.prototype.applyActualScaleOnTransform = function () {
  7381. return false;
  7382. };
  7383. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  7384. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  7385. return false;
  7386. }
  7387. // Fill Part
  7388. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  7389. var d = part;
  7390. if (this.fill) {
  7391. var fill = this.fill;
  7392. if (fill instanceof BABYLON.SolidColorBrush2D) {
  7393. d.fillSolidColor = fill.color;
  7394. }
  7395. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  7396. d.fillGradientColor1 = fill.color1;
  7397. d.fillGradientColor2 = fill.color2;
  7398. 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));
  7399. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  7400. d.fillGradientTY = ty;
  7401. }
  7402. }
  7403. }
  7404. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  7405. var d = part;
  7406. if (this.border) {
  7407. d.borderThickness = this.borderThickness;
  7408. var border = this.border;
  7409. if (border instanceof BABYLON.SolidColorBrush2D) {
  7410. d.borderSolidColor = border.color;
  7411. }
  7412. else if (border instanceof BABYLON.GradientColorBrush2D) {
  7413. d.borderGradientColor1 = border.color1;
  7414. d.borderGradientColor2 = border.color2;
  7415. 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));
  7416. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  7417. d.borderGradientTY = ty;
  7418. }
  7419. }
  7420. }
  7421. return true;
  7422. };
  7423. Shape2D.prototype._updateTransparencyStatus = function () {
  7424. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  7425. if (this._isTransparent !== this._oldTransparent) {
  7426. this._oldTransparent = this._isTransparent;
  7427. this._updateRenderMode();
  7428. }
  7429. };
  7430. Shape2D.prototype._mustUpdateInstance = function () {
  7431. var res = this._oldTransparent !== this._isTransparent;
  7432. if (res) {
  7433. this._updateRenderMode();
  7434. this._oldTransparent = this._isTransparent;
  7435. }
  7436. return res;
  7437. };
  7438. Shape2D.prototype._isPrimTransparent = function () {
  7439. return this._isTransparent;
  7440. };
  7441. Shape2D.SHAPE2D_BORDERPARTID = 1;
  7442. Shape2D.SHAPE2D_FILLPARTID = 2;
  7443. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  7444. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  7445. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  7446. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  7447. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  7448. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  7449. __decorate([
  7450. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  7451. ], Shape2D.prototype, "border", null);
  7452. __decorate([
  7453. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  7454. ], Shape2D.prototype, "fill", null);
  7455. __decorate([
  7456. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  7457. ], Shape2D.prototype, "borderThickness", null);
  7458. Shape2D = __decorate([
  7459. BABYLON.className("Shape2D", "BABYLON")
  7460. ], Shape2D);
  7461. return Shape2D;
  7462. }(BABYLON.RenderablePrim2D));
  7463. BABYLON.Shape2D = Shape2D;
  7464. var Shape2DInstanceData = (function (_super) {
  7465. __extends(Shape2DInstanceData, _super);
  7466. function Shape2DInstanceData() {
  7467. _super.apply(this, arguments);
  7468. }
  7469. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  7470. // FILL ATTRIBUTES
  7471. get: function () {
  7472. return null;
  7473. },
  7474. set: function (value) {
  7475. },
  7476. enumerable: true,
  7477. configurable: true
  7478. });
  7479. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  7480. get: function () {
  7481. return null;
  7482. },
  7483. set: function (value) {
  7484. },
  7485. enumerable: true,
  7486. configurable: true
  7487. });
  7488. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  7489. get: function () {
  7490. return null;
  7491. },
  7492. set: function (value) {
  7493. },
  7494. enumerable: true,
  7495. configurable: true
  7496. });
  7497. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  7498. get: function () {
  7499. return null;
  7500. },
  7501. set: function (value) {
  7502. },
  7503. enumerable: true,
  7504. configurable: true
  7505. });
  7506. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  7507. // BORDER ATTRIBUTES
  7508. get: function () {
  7509. return null;
  7510. },
  7511. set: function (value) {
  7512. },
  7513. enumerable: true,
  7514. configurable: true
  7515. });
  7516. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  7517. get: function () {
  7518. return null;
  7519. },
  7520. set: function (value) {
  7521. },
  7522. enumerable: true,
  7523. configurable: true
  7524. });
  7525. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  7526. get: function () {
  7527. return null;
  7528. },
  7529. set: function (value) {
  7530. },
  7531. enumerable: true,
  7532. configurable: true
  7533. });
  7534. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  7535. get: function () {
  7536. return null;
  7537. },
  7538. set: function (value) {
  7539. },
  7540. enumerable: true,
  7541. configurable: true
  7542. });
  7543. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  7544. get: function () {
  7545. return null;
  7546. },
  7547. set: function (value) {
  7548. },
  7549. enumerable: true,
  7550. configurable: true
  7551. });
  7552. __decorate([
  7553. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  7554. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  7555. __decorate([
  7556. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  7557. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  7558. __decorate([
  7559. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  7560. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  7561. __decorate([
  7562. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  7563. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  7564. __decorate([
  7565. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  7566. ], Shape2DInstanceData.prototype, "borderThickness", null);
  7567. __decorate([
  7568. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  7569. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  7570. __decorate([
  7571. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  7572. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  7573. __decorate([
  7574. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  7575. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  7576. __decorate([
  7577. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  7578. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  7579. return Shape2DInstanceData;
  7580. }(BABYLON.InstanceDataBase));
  7581. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  7582. })(BABYLON || (BABYLON = {}));
  7583. var BABYLON;
  7584. (function (BABYLON) {
  7585. var Group2D = (function (_super) {
  7586. __extends(Group2D, _super);
  7587. /**
  7588. * Create an Logical or Renderable Group.
  7589. * @param settings a combination of settings, possible ones are
  7590. * - 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)
  7591. * - children: an array of direct children
  7592. * - id a text identifier, for information purpose
  7593. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  7594. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  7595. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  7596. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  7597. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  7598. * - zOrder: override the zOrder with the specified value
  7599. * - origin: define the normalized origin point location, default [0.5;0.5]
  7600. * - 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.
  7601. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  7602. * - 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).
  7603. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  7604. * - 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.
  7605. * - 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.
  7606. * - 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!
  7607. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  7608. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  7609. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  7610. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  7611. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  7612. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  7613. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  7614. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  7615. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  7616. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  7617. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  7618. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  7619. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  7620. */
  7621. function Group2D(settings) {
  7622. if (settings == null) {
  7623. settings = {};
  7624. }
  7625. if (settings.origin == null) {
  7626. settings.origin = new BABYLON.Vector2(0, 0);
  7627. }
  7628. _super.call(this, settings);
  7629. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  7630. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  7631. if (this._trackedNode && this.owner) {
  7632. this.owner._registerTrackedNode(this);
  7633. }
  7634. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  7635. var rd = this._renderableData;
  7636. if (rd) {
  7637. rd._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  7638. }
  7639. this.size = size;
  7640. this._viewportPosition = BABYLON.Vector2.Zero();
  7641. this._viewportSize = BABYLON.Size.Zero();
  7642. }
  7643. Group2D._createCachedCanvasGroup = function (owner) {
  7644. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true, isPickable: false, dontInheritParentScale: true });
  7645. return g;
  7646. };
  7647. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  7648. this._bindCacheTarget();
  7649. if (vertexData) {
  7650. var uv = vertexData.uvs;
  7651. var nodeuv = this._renderableData._cacheNodeUVs;
  7652. for (var i = 0; i < 4; i++) {
  7653. uv[i * 2 + 0] = nodeuv[i].x;
  7654. uv[i * 2 + 1] = nodeuv[i].y;
  7655. }
  7656. }
  7657. if (material) {
  7658. material.diffuseTexture = this._renderableData._cacheTexture;
  7659. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  7660. }
  7661. this._renderableData._cacheTexture.hasAlpha = true;
  7662. this._unbindCacheTarget();
  7663. };
  7664. Object.defineProperty(Group2D.prototype, "cachedRect", {
  7665. /**
  7666. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  7667. * 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.
  7668. */
  7669. get: function () {
  7670. if (!this._renderableData) {
  7671. return null;
  7672. }
  7673. return this._renderableData._cacheNode;
  7674. },
  7675. enumerable: true,
  7676. configurable: true
  7677. });
  7678. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  7679. /**
  7680. * The UVs into the MapTexture that map the cached group
  7681. */
  7682. get: function () {
  7683. if (!this._renderableData) {
  7684. return null;
  7685. }
  7686. return this._renderableData._cacheNodeUVs;
  7687. },
  7688. enumerable: true,
  7689. configurable: true
  7690. });
  7691. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  7692. get: function () {
  7693. if (!this._renderableData) {
  7694. return null;
  7695. }
  7696. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  7697. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  7698. }
  7699. return this._renderableData._cacheNodeUVsChangedObservable;
  7700. },
  7701. enumerable: true,
  7702. configurable: true
  7703. });
  7704. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  7705. /**
  7706. * Access the texture that maintains a cached version of the Group2D.
  7707. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  7708. */
  7709. get: function () {
  7710. if (!this._renderableData) {
  7711. return null;
  7712. }
  7713. return this._renderableData._cacheTexture;
  7714. },
  7715. enumerable: true,
  7716. configurable: true
  7717. });
  7718. /**
  7719. * Call this method to remove this Group and its children from the Canvas
  7720. */
  7721. Group2D.prototype.dispose = function () {
  7722. if (!_super.prototype.dispose.call(this)) {
  7723. return false;
  7724. }
  7725. if (this._trackedNode != null) {
  7726. this.owner._unregisterTrackedNode(this);
  7727. this._trackedNode = null;
  7728. }
  7729. if (this._renderableData) {
  7730. this._renderableData.dispose(this.owner);
  7731. this._renderableData = null;
  7732. }
  7733. return true;
  7734. };
  7735. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  7736. /**
  7737. * @returns Returns true if the Group render content, false if it's a logical group only
  7738. */
  7739. get: function () {
  7740. return this._isRenderableGroup;
  7741. },
  7742. enumerable: true,
  7743. configurable: true
  7744. });
  7745. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  7746. /**
  7747. * @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
  7748. */
  7749. get: function () {
  7750. return this._isCachedGroup;
  7751. },
  7752. enumerable: true,
  7753. configurable: true
  7754. });
  7755. Object.defineProperty(Group2D.prototype, "size", {
  7756. get: function () {
  7757. return this._size;
  7758. },
  7759. /**
  7760. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  7761. * 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.
  7762. */
  7763. set: function (val) {
  7764. this._size = val;
  7765. },
  7766. enumerable: true,
  7767. configurable: true
  7768. });
  7769. Object.defineProperty(Group2D.prototype, "viewportSize", {
  7770. get: function () {
  7771. return this._viewportSize;
  7772. },
  7773. enumerable: true,
  7774. configurable: true
  7775. });
  7776. Object.defineProperty(Group2D.prototype, "actualSize", {
  7777. get: function () {
  7778. // The computed size will be floor on both width and height
  7779. var actualSize;
  7780. // Return the actualSize if set
  7781. if (this._actualSize) {
  7782. return this._actualSize;
  7783. }
  7784. // Return the size if set by the user
  7785. if (this._size) {
  7786. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  7787. }
  7788. else {
  7789. var m = this.layoutBoundingInfo.max();
  7790. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  7791. }
  7792. // Compare the size with the one we previously had, if it differs we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  7793. if (!actualSize.equals(this._actualSize)) {
  7794. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  7795. this._actualSize = actualSize;
  7796. this.handleGroupChanged(Group2D.actualSizeProperty);
  7797. }
  7798. return actualSize;
  7799. },
  7800. set: function (value) {
  7801. this._actualSize = value;
  7802. },
  7803. enumerable: true,
  7804. configurable: true
  7805. });
  7806. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  7807. /**
  7808. * 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.
  7809. * GROUPCACHEBEHAVIOR_NORESIZEONSCALE can also be set if you set it at creation time.
  7810. * 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.
  7811. */
  7812. get: function () {
  7813. return this._cacheBehavior;
  7814. },
  7815. enumerable: true,
  7816. configurable: true
  7817. });
  7818. Group2D.prototype._addPrimToDirtyList = function (prim) {
  7819. this._renderableData._primDirtyList.push(prim);
  7820. };
  7821. Group2D.prototype._renderCachedCanvas = function () {
  7822. this.owner._addGroupRenderCount(1);
  7823. this.updateCachedStates(true);
  7824. var context = new BABYLON.PrepareRender2DContext();
  7825. this._prepareGroupRender(context);
  7826. this._groupRender();
  7827. };
  7828. Object.defineProperty(Group2D.prototype, "trackedNode", {
  7829. /**
  7830. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  7831. */
  7832. get: function () {
  7833. return this._trackedNode;
  7834. },
  7835. set: function (val) {
  7836. if (val != null) {
  7837. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  7838. this.owner._registerTrackedNode(this);
  7839. }
  7840. this._trackedNode = val;
  7841. }
  7842. else {
  7843. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  7844. this.owner._unregisterTrackedNode(this);
  7845. }
  7846. this._trackedNode = null;
  7847. }
  7848. },
  7849. enumerable: true,
  7850. configurable: true
  7851. });
  7852. Group2D.prototype.levelIntersect = function (intersectInfo) {
  7853. // 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
  7854. return true;
  7855. };
  7856. Group2D.prototype.updateLevelBoundingInfo = function () {
  7857. var size;
  7858. // If the size is set by the user, the boundingInfo is computed from this value
  7859. if (this.size) {
  7860. size = this.size;
  7861. }
  7862. else {
  7863. size = new BABYLON.Size(0, 0);
  7864. }
  7865. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  7866. };
  7867. // Method called only on renderable groups to prepare the rendering
  7868. Group2D.prototype._prepareGroupRender = function (context) {
  7869. var sortedDirtyList = null;
  7870. // Update the Global Transformation and visibility status of the changed primitives
  7871. var rd = this._renderableData;
  7872. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  7873. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  7874. this.updateCachedStatesOf(sortedDirtyList, true);
  7875. }
  7876. var s = this.actualSize;
  7877. var a = this.actualScale;
  7878. var sw = Math.ceil(s.width * a.x);
  7879. var sh = Math.ceil(s.height * a.y);
  7880. // 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.
  7881. // So we set the width/height to the rendering's one because that's what we want for the viewport!
  7882. if (this instanceof BABYLON.Canvas2D) {
  7883. var c = this;
  7884. if (c.designSize != null) {
  7885. sw = this.owner.engine.getRenderWidth();
  7886. sh = this.owner.engine.getRenderHeight();
  7887. }
  7888. }
  7889. // Setup the size of the rendering viewport
  7890. // 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
  7891. if (!this._isCachedGroup) {
  7892. // Compute the WebGL viewport's location/size
  7893. var t = this._globalTransform.getTranslation();
  7894. var rs = this.owner._renderingSize;
  7895. sh = Math.min(sh, rs.height - t.y);
  7896. sw = Math.min(sw, rs.width - t.x);
  7897. var x = t.x;
  7898. var y = t.y;
  7899. // 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
  7900. this._viewportPosition.x = x;
  7901. this._viewportPosition.y = y;
  7902. }
  7903. // 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.
  7904. if (this._viewportSize.width !== sw || this._viewportSize.height !== sh) {
  7905. context.forceRefreshPrimitive = true;
  7906. this._viewportSize.width = sw;
  7907. this._viewportSize.height = sh;
  7908. }
  7909. if ((rd._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  7910. // If the group is cached, set the dirty flag to true because of the incoming changes
  7911. this._cacheGroupDirty = this._isCachedGroup;
  7912. rd._primNewDirtyList.splice(0);
  7913. // If it's a force refresh, prepare all the children
  7914. if (context.forceRefreshPrimitive) {
  7915. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  7916. var p = _a[_i];
  7917. p._prepareRender(context);
  7918. }
  7919. }
  7920. else {
  7921. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  7922. // the hierarchyDepth in order to prepare primitives from top to bottom
  7923. if (!sortedDirtyList) {
  7924. sortedDirtyList = rd._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  7925. }
  7926. sortedDirtyList.forEach(function (p) {
  7927. // 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.
  7928. // 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.
  7929. if (!p.isDisposed && p._needPrepare()) {
  7930. p._prepareRender(context);
  7931. }
  7932. });
  7933. }
  7934. // Everything is updated, clear the dirty list
  7935. rd._primDirtyList.forEach(function (p) {
  7936. if (rd._primNewDirtyList.indexOf(p) === -1) {
  7937. p._resetPropertiesDirty();
  7938. }
  7939. else {
  7940. p._setFlags(BABYLON.SmartPropertyPrim.flagNeedRefresh);
  7941. }
  7942. });
  7943. rd._primDirtyList.splice(0);
  7944. rd._primDirtyList = rd._primDirtyList.concat(rd._primNewDirtyList);
  7945. }
  7946. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  7947. rd._childrenRenderableGroups.forEach(function (g) {
  7948. g._prepareGroupRender(context);
  7949. });
  7950. };
  7951. Group2D.prototype._groupRender = function () {
  7952. var _this = this;
  7953. var engine = this.owner.engine;
  7954. var failedCount = 0;
  7955. // First recurse to children render group to render them (in their cache or on screen)
  7956. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  7957. var childGroup = _a[_i];
  7958. childGroup._groupRender();
  7959. }
  7960. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  7961. if (!this.isCachedGroup || this._cacheGroupDirty) {
  7962. this.owner._addGroupRenderCount(1);
  7963. if (this.isCachedGroup) {
  7964. this._bindCacheTarget();
  7965. }
  7966. else {
  7967. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  7968. }
  7969. var curAlphaTest = engine.getAlphaTesting() === true;
  7970. var curDepthWrite = engine.getDepthWrite() === true;
  7971. // ===================================================================
  7972. // First pass, update the InstancedArray and render Opaque primitives
  7973. // Disable Alpha Testing, Enable Depth Write
  7974. engine.setAlphaTesting(false);
  7975. engine.setDepthWrite(true);
  7976. // For each different model of primitive to render
  7977. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  7978. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  7979. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  7980. var renderCount = _this._prepareContext(engine, context_1, v);
  7981. // If null is returned, there's no opaque data to render
  7982. if (renderCount === null) {
  7983. return;
  7984. }
  7985. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  7986. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  7987. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  7988. var renderFailed = !v.modelRenderCache.render(v, context_1);
  7989. // Update dirty flag/related
  7990. v.opaqueDirty = renderFailed;
  7991. failedCount += renderFailed ? 1 : 0;
  7992. }
  7993. });
  7994. // =======================================================================
  7995. // Second pass, update the InstancedArray and render AlphaTest primitives
  7996. // Enable Alpha Testing, Enable Depth Write
  7997. engine.setAlphaTesting(true);
  7998. engine.setDepthWrite(true);
  7999. // For each different model of primitive to render
  8000. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  8001. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  8002. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  8003. var renderCount = _this._prepareContext(engine, context_1, v);
  8004. // If null is returned, there's no opaque data to render
  8005. if (renderCount === null) {
  8006. return;
  8007. }
  8008. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  8009. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  8010. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  8011. var renderFailed = !v.modelRenderCache.render(v, context_1);
  8012. // Update dirty flag/related
  8013. v.opaqueDirty = renderFailed;
  8014. failedCount += renderFailed ? 1 : 0;
  8015. }
  8016. });
  8017. // =======================================================================
  8018. // Third pass, transparent primitive rendering
  8019. // Enable Alpha Testing, Disable Depth Write
  8020. engine.setAlphaTesting(true);
  8021. engine.setDepthWrite(false);
  8022. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  8023. if (this._renderableData._transparentListChanged) {
  8024. this._updateTransparentData();
  8025. }
  8026. // From this point on we have up to date data to render, so let's go
  8027. failedCount += this._renderTransparentData();
  8028. // =======================================================================
  8029. // Unbind target/restore viewport setting, clear dirty flag, and quit
  8030. // The group's content is no longer dirty
  8031. this._cacheGroupDirty = failedCount !== 0;
  8032. if (this.isCachedGroup) {
  8033. this._unbindCacheTarget();
  8034. }
  8035. else {
  8036. if (curVP) {
  8037. engine.setViewport(curVP);
  8038. }
  8039. }
  8040. // Restore saved states
  8041. engine.setAlphaTesting(curAlphaTest);
  8042. engine.setDepthWrite(curDepthWrite);
  8043. }
  8044. };
  8045. Group2D.prototype._setCacheGroupDirty = function () {
  8046. this._cacheGroupDirty = true;
  8047. };
  8048. Group2D.prototype._updateTransparentData = function () {
  8049. this.owner._addUpdateTransparentDataCount(1);
  8050. var rd = this._renderableData;
  8051. // Sort all the primitive from their depth, max (bottom) to min (top)
  8052. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  8053. var checkAndAddPrimInSegment = function (seg, tpiI) {
  8054. var tpi = rd._transparentPrimitives[tpiI];
  8055. // Fast rejection: if gii are different
  8056. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  8057. return false;
  8058. }
  8059. //let tpiZ = tpi._primitive.actualZOffset;
  8060. // We've made it so far, the tpi can be part of the segment, add it
  8061. tpi._transparentSegment = seg;
  8062. tpi._primitive._updateTransparentSegmentIndices(seg);
  8063. return true;
  8064. };
  8065. // Free the existing TransparentSegments
  8066. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  8067. var ts = _a[_i];
  8068. ts.dispose(this.owner.engine);
  8069. }
  8070. rd._transparentSegments.splice(0);
  8071. var prevSeg = null;
  8072. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  8073. var tpi = rd._transparentPrimitives[tpiI];
  8074. // Check if the Data in which the primitive is stored is not sorted properly
  8075. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  8076. tpi._groupInstanceInfo.sortTransparentData();
  8077. }
  8078. // Reset the segment, we have to create/rebuild it
  8079. tpi._transparentSegment = null;
  8080. // If there's a previous valid segment, check if this prim can be part of it
  8081. if (prevSeg) {
  8082. checkAndAddPrimInSegment(prevSeg, tpiI);
  8083. }
  8084. // If we couldn't insert in the adjacent segments, he have to create one
  8085. if (!tpi._transparentSegment) {
  8086. var ts = new BABYLON.TransparentSegment();
  8087. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  8088. var prim = tpi._primitive;
  8089. ts.startZ = prim.actualZOffset;
  8090. prim._updateTransparentSegmentIndices(ts);
  8091. ts.endZ = ts.startZ;
  8092. tpi._transparentSegment = ts;
  8093. rd._transparentSegments.push(ts);
  8094. }
  8095. // Update prevSeg
  8096. prevSeg = tpi._transparentSegment;
  8097. }
  8098. //rd._firstChangedPrim = null;
  8099. rd._transparentListChanged = false;
  8100. };
  8101. Group2D.prototype._renderTransparentData = function () {
  8102. var failedCount = 0;
  8103. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  8104. var rd = this._renderableData;
  8105. var useInstanced = this.owner.supportInstancedArray;
  8106. var length = rd._transparentSegments.length;
  8107. for (var i = 0; i < length; i++) {
  8108. context.instancedBuffers = null;
  8109. var ts = rd._transparentSegments[i];
  8110. var gii = ts.groupInsanceInfo;
  8111. var mrc = gii.modelRenderCache;
  8112. var engine = this.owner.engine;
  8113. var count = ts.endDataIndex - ts.startDataIndex;
  8114. // Use Instanced Array if it's supported and if there's at least minPartCountToUseInstancedArray prims to draw.
  8115. // We don't want to create an Instanced Buffer for less that minPartCountToUseInstancedArray prims
  8116. if (useInstanced && count >= this.owner.minPartCountToUseInstancedArray) {
  8117. if (!ts.partBuffers) {
  8118. var buffers = new Array();
  8119. for (var j = 0; j < gii.transparentData.length; j++) {
  8120. var gitd = gii.transparentData[j];
  8121. var dfa = gitd._partData;
  8122. var data = dfa.pack();
  8123. var stride = dfa.stride;
  8124. var neededSize = count * stride * 4;
  8125. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  8126. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  8127. engine.updateArrayBuffer(segData);
  8128. buffers.push(buffer);
  8129. }
  8130. ts.partBuffers = buffers;
  8131. }
  8132. else if (gii.transparentDirty) {
  8133. for (var j = 0; j < gii.transparentData.length; j++) {
  8134. var gitd = gii.transparentData[j];
  8135. var dfa = gitd._partData;
  8136. var data = dfa.pack();
  8137. var stride = dfa.stride;
  8138. var buffer = ts.partBuffers[j];
  8139. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  8140. engine.bindArrayBuffer(buffer);
  8141. engine.updateArrayBuffer(segData);
  8142. }
  8143. }
  8144. context.useInstancing = true;
  8145. context.instancesCount = count;
  8146. context.instancedBuffers = ts.partBuffers;
  8147. context.groupInfoPartData = gii.transparentData;
  8148. var renderFailed = !mrc.render(gii, context);
  8149. failedCount += renderFailed ? 1 : 0;
  8150. }
  8151. else {
  8152. context.useInstancing = false;
  8153. context.partDataStartIndex = ts.startDataIndex;
  8154. context.partDataEndIndex = ts.endDataIndex;
  8155. context.groupInfoPartData = gii.transparentData;
  8156. var renderFailed = !mrc.render(gii, context);
  8157. failedCount += renderFailed ? 1 : 0;
  8158. }
  8159. }
  8160. return failedCount;
  8161. };
  8162. Group2D.prototype._prepareContext = function (engine, context, gii) {
  8163. var gipd = null;
  8164. var setDirty;
  8165. var getDirty;
  8166. // Render Mode specifics
  8167. switch (context.renderMode) {
  8168. case BABYLON.Render2DContext.RenderModeOpaque:
  8169. {
  8170. if (!gii.hasOpaqueData) {
  8171. return null;
  8172. }
  8173. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  8174. getDirty = function () { return gii.opaqueDirty; };
  8175. context.groupInfoPartData = gii.opaqueData;
  8176. gipd = gii.opaqueData;
  8177. break;
  8178. }
  8179. case BABYLON.Render2DContext.RenderModeAlphaTest:
  8180. {
  8181. if (!gii.hasAlphaTestData) {
  8182. return null;
  8183. }
  8184. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  8185. getDirty = function () { return gii.alphaTestDirty; };
  8186. context.groupInfoPartData = gii.alphaTestData;
  8187. gipd = gii.alphaTestData;
  8188. break;
  8189. }
  8190. default:
  8191. throw new Error("_prepareContext is only for opaque or alphaTest");
  8192. }
  8193. var renderCount = 0;
  8194. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  8195. // Skip it if instanced arrays are not supported
  8196. if (this.owner.supportInstancedArray) {
  8197. // Flag for instancing
  8198. context.useInstancing = true;
  8199. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  8200. for (var i = 0; i < gipd.length; i++) {
  8201. var pid = gipd[i];
  8202. // If the instances of the model was changed, pack the data
  8203. var array = pid._partData;
  8204. var instanceData_1 = array.pack();
  8205. renderCount += array.usedElementCount;
  8206. // Compute the size the instance buffer should have
  8207. var neededSize = array.usedElementCount * array.stride * 4;
  8208. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  8209. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  8210. if (pid._partBuffer) {
  8211. engine.deleteInstancesBuffer(pid._partBuffer);
  8212. }
  8213. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  8214. pid._partBufferSize = neededSize;
  8215. setDirty(false);
  8216. // Update the WebGL buffer to match the new content of the instances data
  8217. engine.updateArrayBuffer(instanceData_1);
  8218. }
  8219. else if (getDirty()) {
  8220. // Update the WebGL buffer to match the new content of the instances data
  8221. engine.bindArrayBuffer(pid._partBuffer);
  8222. engine.updateArrayBuffer(instanceData_1);
  8223. }
  8224. }
  8225. setDirty(false);
  8226. }
  8227. else {
  8228. context.partDataStartIndex = 0;
  8229. // Find the first valid object to get the count
  8230. if (context.groupInfoPartData.length > 0) {
  8231. var i = 0;
  8232. while (!context.groupInfoPartData[i]) {
  8233. i++;
  8234. }
  8235. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  8236. }
  8237. }
  8238. return renderCount;
  8239. };
  8240. Group2D.prototype._setRenderingScale = function (scale) {
  8241. if (this._renderableData._renderingScale === scale) {
  8242. return;
  8243. }
  8244. this._renderableData._renderingScale = scale;
  8245. };
  8246. Group2D.prototype._bindCacheTarget = function () {
  8247. var curWidth;
  8248. var curHeight;
  8249. var rd = this._renderableData;
  8250. var rs = rd._renderingScale;
  8251. var noResizeScale = rd._noResizeOnScale;
  8252. var isCanvas = this.parent == null;
  8253. var scale;
  8254. if (noResizeScale) {
  8255. scale = isCanvas ? Group2D._uV : this.parent.actualScale;
  8256. }
  8257. else {
  8258. scale = this.actualScale;
  8259. }
  8260. if (isCanvas && this.owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS && this.owner.isScreenSpace) {
  8261. Group2D._s.width = this.owner.engine.getRenderWidth();
  8262. Group2D._s.height = this.owner.engine.getRenderHeight();
  8263. }
  8264. else {
  8265. Group2D._s.width = Math.ceil(this.actualSize.width * scale.x * rs);
  8266. Group2D._s.height = Math.ceil(this.actualSize.height * scale.y * rs);
  8267. }
  8268. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  8269. if (rd._cacheNode) {
  8270. var size = rd._cacheNode.contentSize;
  8271. // Check if we have to deallocate because the size is too small
  8272. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  8273. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  8274. // For World space: no over-provisioning
  8275. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  8276. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  8277. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  8278. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  8279. rd._cacheTexture.freeRect(rd._cacheNode);
  8280. rd._cacheNode = null;
  8281. }
  8282. }
  8283. if (!rd._cacheNode) {
  8284. // Check if we have to allocate a rendering zone in the global cache texture
  8285. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  8286. rd._cacheNode = res.node;
  8287. rd._cacheTexture = res.texture;
  8288. if (rd._cacheRenderSprite) {
  8289. rd._cacheRenderSprite.dispose();
  8290. }
  8291. rd._cacheRenderSprite = res.sprite;
  8292. sizeChanged = true;
  8293. }
  8294. if (sizeChanged) {
  8295. rd._cacheSize.copyFrom(Group2D._s);
  8296. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  8297. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  8298. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  8299. }
  8300. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  8301. }
  8302. var n = rd._cacheNode;
  8303. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  8304. };
  8305. Group2D.prototype._unbindCacheTarget = function () {
  8306. if (this._renderableData._cacheTexture) {
  8307. this._renderableData._cacheTexture.unbindTexture();
  8308. }
  8309. };
  8310. Group2D.prototype._spreadActualScaleDirty = function () {
  8311. if (this._renderableData && this._renderableData._cacheRenderSprite) {
  8312. this.handleGroupChanged(BABYLON.Prim2DBase.actualScaleProperty);
  8313. }
  8314. _super.prototype._spreadActualScaleDirty.call(this);
  8315. };
  8316. Group2D.prototype.handleGroupChanged = function (prop) {
  8317. // This method is only for cachedGroup
  8318. var rd = this._renderableData;
  8319. if (!rd) {
  8320. return;
  8321. }
  8322. var cachedSprite = rd._cacheRenderSprite;
  8323. if (!this.isCachedGroup || !cachedSprite) {
  8324. return;
  8325. }
  8326. // For now we only support these property changes
  8327. // TODO: add more! :)
  8328. switch (prop.id) {
  8329. case BABYLON.Prim2DBase.actualScaleProperty.id:
  8330. case BABYLON.Prim2DBase.actualPositionProperty.id:
  8331. var noResizeScale = rd._noResizeOnScale;
  8332. var isCanvas = parent == null;
  8333. var scale = void 0;
  8334. if (noResizeScale) {
  8335. scale = isCanvas ? Group2D._unS : this.parent.actualScale;
  8336. }
  8337. else {
  8338. scale = this.actualScale;
  8339. }
  8340. cachedSprite.actualPosition = this.actualPosition.multiply(scale);
  8341. if (cachedSprite.position != null) {
  8342. cachedSprite.position = cachedSprite.actualPosition.clone();
  8343. }
  8344. break;
  8345. case BABYLON.Prim2DBase.rotationProperty.id:
  8346. cachedSprite.rotation = this.rotation;
  8347. break;
  8348. case BABYLON.Prim2DBase.scaleProperty.id:
  8349. cachedSprite.scale = this.scale;
  8350. break;
  8351. case BABYLON.Prim2DBase.originProperty.id:
  8352. cachedSprite.origin = this.origin.clone();
  8353. break;
  8354. case Group2D.actualSizeProperty.id:
  8355. cachedSprite.size = this.actualSize.clone();
  8356. break;
  8357. }
  8358. };
  8359. Group2D.prototype.detectGroupStates = function () {
  8360. var isCanvas = this instanceof BABYLON.Canvas2D;
  8361. var canvasStrat = this.owner.cachingStrategy;
  8362. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  8363. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  8364. this._isRenderableGroup = isCanvas;
  8365. this._isCachedGroup = false;
  8366. }
  8367. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  8368. if (isCanvas) {
  8369. this._isRenderableGroup = true;
  8370. this._isCachedGroup = true;
  8371. }
  8372. else {
  8373. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  8374. this._isCachedGroup = false;
  8375. }
  8376. }
  8377. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  8378. if (isCanvas) {
  8379. this._isRenderableGroup = true;
  8380. this._isCachedGroup = false;
  8381. }
  8382. else {
  8383. if (this.hierarchyDepth === 1) {
  8384. this._isRenderableGroup = true;
  8385. this._isCachedGroup = true;
  8386. }
  8387. else {
  8388. this._isRenderableGroup = false;
  8389. this._isCachedGroup = false;
  8390. }
  8391. }
  8392. }
  8393. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  8394. if (isCanvas) {
  8395. this._isRenderableGroup = true;
  8396. this._isCachedGroup = false;
  8397. }
  8398. else {
  8399. var gcb = this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK;
  8400. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  8401. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  8402. this._isCachedGroup = false;
  8403. }
  8404. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  8405. this._isRenderableGroup = true;
  8406. this._isCachedGroup = true;
  8407. }
  8408. }
  8409. }
  8410. if (this._isRenderableGroup) {
  8411. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  8412. if (!this._renderableData) {
  8413. this._renderableData = new RenderableGroupData();
  8414. }
  8415. }
  8416. // If the group is tagged as renderable we add it to the renderable tree
  8417. if (this._isCachedGroup) {
  8418. this._renderableData._noResizeOnScale = (this.cacheBehavior & Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE) !== 0;
  8419. var cur = this.parent;
  8420. while (cur) {
  8421. if (cur instanceof Group2D && cur._isRenderableGroup) {
  8422. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  8423. cur._renderableData._childrenRenderableGroups.push(this);
  8424. }
  8425. break;
  8426. }
  8427. cur = cur.parent;
  8428. }
  8429. }
  8430. };
  8431. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  8432. /**
  8433. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  8434. */
  8435. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  8436. /**
  8437. * When used, this group's content won't be cached, no matter which strategy used.
  8438. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  8439. */
  8440. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  8441. /**
  8442. * When used, the group's content will be cached in the nearest cached parent group/canvas
  8443. */
  8444. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  8445. /**
  8446. * 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
  8447. */
  8448. Group2D.GROUPCACHEBEHAVIOR_NORESIZEONSCALE = 0x100;
  8449. Group2D.GROUPCACHEBEHAVIOR_OPTIONMASK = 0xFF;
  8450. Group2D._uV = new BABYLON.Vector2(1, 1);
  8451. Group2D._s = BABYLON.Size.Zero();
  8452. Group2D._unS = new BABYLON.Vector2(1, 1);
  8453. __decorate([
  8454. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  8455. ], Group2D.prototype, "size", null);
  8456. __decorate([
  8457. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  8458. ], Group2D.prototype, "actualSize", null);
  8459. Group2D = __decorate([
  8460. BABYLON.className("Group2D", "BABYLON")
  8461. ], Group2D);
  8462. return Group2D;
  8463. }(BABYLON.Prim2DBase));
  8464. BABYLON.Group2D = Group2D;
  8465. var RenderableGroupData = (function () {
  8466. function RenderableGroupData() {
  8467. this._primDirtyList = new Array();
  8468. this._primNewDirtyList = new Array();
  8469. this._childrenRenderableGroups = new Array();
  8470. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  8471. this._transparentPrimitives = new Array();
  8472. this._transparentSegments = new Array();
  8473. this._transparentListChanged = false;
  8474. this._cacheNode = null;
  8475. this._cacheTexture = null;
  8476. this._cacheRenderSprite = null;
  8477. this._renderingScale = 1;
  8478. this._cacheNodeUVs = null;
  8479. this._cacheNodeUVsChangedObservable = null;
  8480. this._cacheSize = BABYLON.Size.Zero();
  8481. this._useMipMap = false;
  8482. this._anisotropicLevel = 1;
  8483. this._noResizeOnScale = false;
  8484. }
  8485. RenderableGroupData.prototype.dispose = function (owner) {
  8486. var engine = owner.engine;
  8487. if (this._cacheRenderSprite) {
  8488. this._cacheRenderSprite.dispose();
  8489. this._cacheRenderSprite = null;
  8490. }
  8491. if (this._cacheTexture && this._cacheNode) {
  8492. this._cacheTexture.freeRect(this._cacheNode);
  8493. this._cacheTexture = null;
  8494. this._cacheNode = null;
  8495. }
  8496. if (this._primDirtyList) {
  8497. this._primDirtyList.splice(0);
  8498. this._primDirtyList = null;
  8499. }
  8500. if (this._renderGroupInstancesInfo) {
  8501. this._renderGroupInstancesInfo.forEach(function (k, v) {
  8502. v.dispose();
  8503. });
  8504. this._renderGroupInstancesInfo = null;
  8505. }
  8506. if (this._cacheNodeUVsChangedObservable) {
  8507. this._cacheNodeUVsChangedObservable.clear();
  8508. this._cacheNodeUVsChangedObservable = null;
  8509. }
  8510. if (this._transparentSegments) {
  8511. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  8512. var ts = _a[_i];
  8513. ts.dispose(engine);
  8514. }
  8515. this._transparentSegments.splice(0);
  8516. this._transparentSegments = null;
  8517. }
  8518. };
  8519. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  8520. var tpi = new TransparentPrimitiveInfo();
  8521. tpi._primitive = prim;
  8522. tpi._groupInstanceInfo = gii;
  8523. tpi._transparentSegment = null;
  8524. this._transparentPrimitives.push(tpi);
  8525. this._transparentListChanged = true;
  8526. return tpi;
  8527. };
  8528. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  8529. var index = this._transparentPrimitives.indexOf(tpi);
  8530. if (index !== -1) {
  8531. this._transparentPrimitives.splice(index, 1);
  8532. this._transparentListChanged = true;
  8533. }
  8534. };
  8535. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  8536. this._transparentListChanged = true;
  8537. //this.updateSmallestZChangedPrim(tpi);
  8538. };
  8539. return RenderableGroupData;
  8540. }());
  8541. BABYLON.RenderableGroupData = RenderableGroupData;
  8542. var TransparentPrimitiveInfo = (function () {
  8543. function TransparentPrimitiveInfo() {
  8544. }
  8545. return TransparentPrimitiveInfo;
  8546. }());
  8547. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  8548. })(BABYLON || (BABYLON = {}));
  8549. var BABYLON;
  8550. (function (BABYLON) {
  8551. var Rectangle2DRenderCache = (function (_super) {
  8552. __extends(Rectangle2DRenderCache, _super);
  8553. function Rectangle2DRenderCache(engine, modelKey) {
  8554. _super.call(this, engine, modelKey);
  8555. this.effectsReady = false;
  8556. this.fillVB = null;
  8557. this.fillIB = null;
  8558. this.fillIndicesCount = 0;
  8559. this.instancingFillAttributes = null;
  8560. this.effectFill = null;
  8561. this.effectFillInstanced = null;
  8562. this.borderVB = null;
  8563. this.borderIB = null;
  8564. this.borderIndicesCount = 0;
  8565. this.instancingBorderAttributes = null;
  8566. this.effectBorder = null;
  8567. this.effectBorderInstanced = null;
  8568. }
  8569. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  8570. // Do nothing if the shader is still loading/preparing
  8571. if (!this.effectsReady) {
  8572. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  8573. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  8574. return false;
  8575. }
  8576. this.effectsReady = true;
  8577. }
  8578. var canvas = instanceInfo.owner.owner;
  8579. var engine = canvas.engine;
  8580. var depthFunction = 0;
  8581. if (this.effectFill && this.effectBorder) {
  8582. depthFunction = engine.getDepthFunction();
  8583. engine.setDepthFunctionToLessOrEqual();
  8584. }
  8585. var curAlphaMode = engine.getAlphaMode();
  8586. if (this.effectFill) {
  8587. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  8588. var pid = context.groupInfoPartData[partIndex];
  8589. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  8590. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  8591. }
  8592. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  8593. engine.enableEffect(effect);
  8594. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  8595. if (context.useInstancing) {
  8596. if (!this.instancingFillAttributes) {
  8597. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  8598. }
  8599. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  8600. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  8601. canvas._addDrawCallCount(1, context.renderMode);
  8602. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  8603. engine.draw(true, 0, this.fillIndicesCount, count);
  8604. engine.unbindInstanceAttributes();
  8605. }
  8606. else {
  8607. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  8608. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  8609. this.setupUniforms(effect, partIndex, pid._partData, i);
  8610. engine.draw(true, 0, this.fillIndicesCount);
  8611. }
  8612. }
  8613. }
  8614. if (this.effectBorder) {
  8615. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  8616. var pid = context.groupInfoPartData[partIndex];
  8617. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  8618. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  8619. }
  8620. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  8621. engine.enableEffect(effect);
  8622. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  8623. if (context.useInstancing) {
  8624. if (!this.instancingBorderAttributes) {
  8625. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  8626. }
  8627. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  8628. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  8629. canvas._addDrawCallCount(1, context.renderMode);
  8630. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  8631. engine.draw(true, 0, this.borderIndicesCount, count);
  8632. engine.unbindInstanceAttributes();
  8633. }
  8634. else {
  8635. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  8636. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  8637. this.setupUniforms(effect, partIndex, pid._partData, i);
  8638. engine.draw(true, 0, this.borderIndicesCount);
  8639. }
  8640. }
  8641. }
  8642. engine.setAlphaMode(curAlphaMode, true);
  8643. if (this.effectFill && this.effectBorder) {
  8644. engine.setDepthFunction(depthFunction);
  8645. }
  8646. return true;
  8647. };
  8648. Rectangle2DRenderCache.prototype.dispose = function () {
  8649. if (!_super.prototype.dispose.call(this)) {
  8650. return false;
  8651. }
  8652. if (this.fillVB) {
  8653. this._engine._releaseBuffer(this.fillVB);
  8654. this.fillVB = null;
  8655. }
  8656. if (this.fillIB) {
  8657. this._engine._releaseBuffer(this.fillIB);
  8658. this.fillIB = null;
  8659. }
  8660. this.effectFill = null;
  8661. this.effectFillInstanced = null;
  8662. this.effectBorder = null;
  8663. this.effectBorderInstanced = null;
  8664. if (this.borderVB) {
  8665. this._engine._releaseBuffer(this.borderVB);
  8666. this.borderVB = null;
  8667. }
  8668. if (this.borderIB) {
  8669. this._engine._releaseBuffer(this.borderIB);
  8670. this.borderIB = null;
  8671. }
  8672. return true;
  8673. };
  8674. return Rectangle2DRenderCache;
  8675. }(BABYLON.ModelRenderCache));
  8676. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  8677. var Rectangle2DInstanceData = (function (_super) {
  8678. __extends(Rectangle2DInstanceData, _super);
  8679. function Rectangle2DInstanceData(partId) {
  8680. _super.call(this, partId, 1);
  8681. }
  8682. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  8683. get: function () {
  8684. return null;
  8685. },
  8686. set: function (value) {
  8687. },
  8688. enumerable: true,
  8689. configurable: true
  8690. });
  8691. __decorate([
  8692. BABYLON.instanceData()
  8693. ], Rectangle2DInstanceData.prototype, "properties", null);
  8694. return Rectangle2DInstanceData;
  8695. }(BABYLON.Shape2DInstanceData));
  8696. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  8697. var Rectangle2D = (function (_super) {
  8698. __extends(Rectangle2D, _super);
  8699. /**
  8700. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  8701. * @param settings a combination of settings, possible ones are
  8702. * - 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)
  8703. * - children: an array of direct children
  8704. * - id a text identifier, for information purpose
  8705. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  8706. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  8707. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  8708. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  8709. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  8710. * - zOrder: override the zOrder with the specified value
  8711. * - origin: define the normalized origin point location, default [0.5;0.5]
  8712. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  8713. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  8714. * - 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)
  8715. * - 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)
  8716. * - borderThickness: the thickness of the drawn border, default is 1.
  8717. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  8718. * - 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.
  8719. * - 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.
  8720. * - 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!
  8721. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  8722. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  8723. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  8724. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  8725. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  8726. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  8727. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  8728. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  8729. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  8730. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  8731. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  8732. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  8733. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  8734. */
  8735. function Rectangle2D(settings) {
  8736. // Avoid checking every time if the object exists
  8737. if (settings == null) {
  8738. settings = {};
  8739. }
  8740. _super.call(this, settings);
  8741. if (settings.size != null) {
  8742. this.size = settings.size;
  8743. }
  8744. else if (settings.width || settings.height) {
  8745. var size = new BABYLON.Size(settings.width, settings.height);
  8746. this.size = size;
  8747. }
  8748. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  8749. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  8750. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  8751. //this.size = size;
  8752. this.roundRadius = roundRadius;
  8753. this.borderThickness = borderThickness;
  8754. }
  8755. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  8756. get: function () {
  8757. if (this._actualSize) {
  8758. return this._actualSize;
  8759. }
  8760. return this.size;
  8761. },
  8762. set: function (value) {
  8763. this._actualSize = value;
  8764. },
  8765. enumerable: true,
  8766. configurable: true
  8767. });
  8768. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  8769. get: function () {
  8770. return this._notRounded;
  8771. },
  8772. set: function (value) {
  8773. this._notRounded = value;
  8774. },
  8775. enumerable: true,
  8776. configurable: true
  8777. });
  8778. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  8779. get: function () {
  8780. return this._roundRadius;
  8781. },
  8782. set: function (value) {
  8783. this._roundRadius = value;
  8784. this.notRounded = value === 0;
  8785. this._positioningDirty();
  8786. },
  8787. enumerable: true,
  8788. configurable: true
  8789. });
  8790. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  8791. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  8792. if (this.notRounded) {
  8793. return true;
  8794. }
  8795. // 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.
  8796. // 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)
  8797. // 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.
  8798. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  8799. var size = this.size;
  8800. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  8801. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  8802. var rr = this.roundRadius;
  8803. var rrs = rr * rr;
  8804. // Check if the point is in the bottom/left quarter area
  8805. Rectangle2D._i1.x = rr;
  8806. Rectangle2D._i1.y = rr;
  8807. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  8808. // Compute the intersection point in the quarter local space
  8809. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  8810. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  8811. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  8812. return Rectangle2D._i2.lengthSquared() <= rrs;
  8813. }
  8814. // Check if the point is in the top/left quarter area
  8815. Rectangle2D._i1.x = rr;
  8816. Rectangle2D._i1.y = size.height - rr;
  8817. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  8818. // Compute the intersection point in the quarter local space
  8819. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  8820. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  8821. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  8822. return Rectangle2D._i2.lengthSquared() <= rrs;
  8823. }
  8824. // Check if the point is in the top/right quarter area
  8825. Rectangle2D._i1.x = size.width - rr;
  8826. Rectangle2D._i1.y = size.height - rr;
  8827. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  8828. // Compute the intersection point in the quarter local space
  8829. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  8830. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  8831. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  8832. return Rectangle2D._i2.lengthSquared() <= rrs;
  8833. }
  8834. // Check if the point is in the bottom/right quarter area
  8835. Rectangle2D._i1.x = size.width - rr;
  8836. Rectangle2D._i1.y = rr;
  8837. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  8838. // Compute the intersection point in the quarter local space
  8839. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  8840. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  8841. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  8842. return Rectangle2D._i2.lengthSquared() <= rrs;
  8843. }
  8844. // At any other locations the point is guarantied to be inside
  8845. return true;
  8846. };
  8847. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  8848. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  8849. };
  8850. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  8851. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  8852. return renderCache;
  8853. };
  8854. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  8855. var renderCache = modelRenderCache;
  8856. var engine = this.owner.engine;
  8857. // Need to create WebGL resources for fill part?
  8858. if (this.fill) {
  8859. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  8860. var vb = new Float32Array(vbSize);
  8861. for (var i = 0; i < vbSize; i++) {
  8862. vb[i] = i;
  8863. }
  8864. renderCache.fillVB = engine.createVertexBuffer(vb);
  8865. var triCount = vbSize - 1;
  8866. var ib = new Float32Array(triCount * 3);
  8867. for (var i = 0; i < triCount; i++) {
  8868. ib[i * 3 + 0] = 0;
  8869. ib[i * 3 + 2] = i + 1;
  8870. ib[i * 3 + 1] = i + 2;
  8871. }
  8872. ib[triCount * 3 - 2] = 1;
  8873. renderCache.fillIB = engine.createIndexBuffer(ib);
  8874. renderCache.fillIndicesCount = triCount * 3;
  8875. // 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
  8876. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  8877. if (ei) {
  8878. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  8879. }
  8880. // Get the non instanced version
  8881. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  8882. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  8883. }
  8884. // Need to create WebGL resource for border part?
  8885. if (this.border) {
  8886. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  8887. var vb = new Float32Array(vbSize);
  8888. for (var i = 0; i < vbSize; i++) {
  8889. vb[i] = i;
  8890. }
  8891. renderCache.borderVB = engine.createVertexBuffer(vb);
  8892. var triCount = vbSize;
  8893. var rs = triCount / 2;
  8894. var ib = new Float32Array(triCount * 3);
  8895. for (var i = 0; i < rs; i++) {
  8896. var r0 = i;
  8897. var r1 = (i + 1) % rs;
  8898. ib[i * 6 + 0] = rs + r1;
  8899. ib[i * 6 + 1] = rs + r0;
  8900. ib[i * 6 + 2] = r0;
  8901. ib[i * 6 + 3] = r1;
  8902. ib[i * 6 + 4] = rs + r1;
  8903. ib[i * 6 + 5] = r0;
  8904. }
  8905. renderCache.borderIB = engine.createIndexBuffer(ib);
  8906. renderCache.borderIndicesCount = triCount * 3;
  8907. // 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
  8908. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  8909. if (ei) {
  8910. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  8911. }
  8912. // Get the non instanced version
  8913. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  8914. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  8915. }
  8916. return renderCache;
  8917. };
  8918. // 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
  8919. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  8920. // Fall back to default implementation if there's no round Radius
  8921. if (this._notRounded) {
  8922. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  8923. }
  8924. else {
  8925. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  8926. initialContentPosition.x = initialContentPosition.y = rr;
  8927. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  8928. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  8929. initialContentPosition.z = primSize.width - (initialContentPosition.x + initialContentArea.width);
  8930. initialContentPosition.w = primSize.height - (initialContentPosition.y + initialContentArea.height);
  8931. }
  8932. };
  8933. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  8934. // Fall back to default implementation if there's no round Radius
  8935. if (this._notRounded) {
  8936. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  8937. }
  8938. else {
  8939. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  8940. newPrimSize.copyFrom(primSize);
  8941. newPrimSize.width += rr * 2;
  8942. newPrimSize.height += rr * 2;
  8943. }
  8944. };
  8945. Rectangle2D.prototype.createInstanceDataParts = function () {
  8946. var res = new Array();
  8947. if (this.border) {
  8948. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  8949. }
  8950. if (this.fill) {
  8951. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  8952. }
  8953. return res;
  8954. };
  8955. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  8956. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  8957. return false;
  8958. }
  8959. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  8960. var d = part;
  8961. var size = this.actualSize;
  8962. var s = this.actualScale;
  8963. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  8964. }
  8965. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  8966. var d = part;
  8967. var size = this.actualSize;
  8968. var s = this.actualScale;
  8969. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.roundRadius || 0);
  8970. }
  8971. return true;
  8972. };
  8973. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  8974. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  8975. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  8976. Rectangle2D.roundSubdivisions = 16;
  8977. __decorate([
  8978. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  8979. ], Rectangle2D.prototype, "actualSize", null);
  8980. __decorate([
  8981. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  8982. ], Rectangle2D.prototype, "notRounded", null);
  8983. __decorate([
  8984. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  8985. ], Rectangle2D.prototype, "roundRadius", null);
  8986. Rectangle2D = __decorate([
  8987. BABYLON.className("Rectangle2D", "BABYLON")
  8988. ], Rectangle2D);
  8989. return Rectangle2D;
  8990. }(BABYLON.Shape2D));
  8991. BABYLON.Rectangle2D = Rectangle2D;
  8992. })(BABYLON || (BABYLON = {}));
  8993. var BABYLON;
  8994. (function (BABYLON) {
  8995. var Ellipse2DRenderCache = (function (_super) {
  8996. __extends(Ellipse2DRenderCache, _super);
  8997. function Ellipse2DRenderCache(engine, modelKey) {
  8998. _super.call(this, engine, modelKey);
  8999. this.effectsReady = false;
  9000. this.fillVB = null;
  9001. this.fillIB = null;
  9002. this.fillIndicesCount = 0;
  9003. this.instancingFillAttributes = null;
  9004. this.effectFillInstanced = null;
  9005. this.effectFill = null;
  9006. this.borderVB = null;
  9007. this.borderIB = null;
  9008. this.borderIndicesCount = 0;
  9009. this.instancingBorderAttributes = null;
  9010. this.effectBorderInstanced = null;
  9011. this.effectBorder = null;
  9012. }
  9013. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  9014. // Do nothing if the shader is still loading/preparing
  9015. if (!this.effectsReady) {
  9016. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  9017. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  9018. return false;
  9019. }
  9020. this.effectsReady = true;
  9021. }
  9022. var canvas = instanceInfo.owner.owner;
  9023. var engine = canvas.engine;
  9024. var depthFunction = 0;
  9025. if (this.effectFill && this.effectBorder) {
  9026. depthFunction = engine.getDepthFunction();
  9027. engine.setDepthFunctionToLessOrEqual();
  9028. }
  9029. var curAlphaMode = engine.getAlphaMode();
  9030. if (this.effectFill) {
  9031. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  9032. var pid = context.groupInfoPartData[partIndex];
  9033. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  9034. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  9035. }
  9036. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  9037. engine.enableEffect(effect);
  9038. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  9039. if (context.useInstancing) {
  9040. if (!this.instancingFillAttributes) {
  9041. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  9042. }
  9043. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  9044. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  9045. canvas._addDrawCallCount(1, context.renderMode);
  9046. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  9047. engine.draw(true, 0, this.fillIndicesCount, count);
  9048. engine.unbindInstanceAttributes();
  9049. }
  9050. else {
  9051. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  9052. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  9053. this.setupUniforms(effect, partIndex, pid._partData, i);
  9054. engine.draw(true, 0, this.fillIndicesCount);
  9055. }
  9056. }
  9057. }
  9058. if (this.effectBorder) {
  9059. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  9060. var pid = context.groupInfoPartData[partIndex];
  9061. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  9062. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  9063. }
  9064. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  9065. engine.enableEffect(effect);
  9066. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  9067. if (context.useInstancing) {
  9068. if (!this.instancingBorderAttributes) {
  9069. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  9070. }
  9071. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  9072. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  9073. canvas._addDrawCallCount(1, context.renderMode);
  9074. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  9075. engine.draw(true, 0, this.borderIndicesCount, count);
  9076. engine.unbindInstanceAttributes();
  9077. }
  9078. else {
  9079. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  9080. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  9081. this.setupUniforms(effect, partIndex, pid._partData, i);
  9082. engine.draw(true, 0, this.borderIndicesCount);
  9083. }
  9084. }
  9085. }
  9086. engine.setAlphaMode(curAlphaMode, true);
  9087. if (this.effectFill && this.effectBorder) {
  9088. engine.setDepthFunction(depthFunction);
  9089. }
  9090. return true;
  9091. };
  9092. Ellipse2DRenderCache.prototype.dispose = function () {
  9093. if (!_super.prototype.dispose.call(this)) {
  9094. return false;
  9095. }
  9096. if (this.fillVB) {
  9097. this._engine._releaseBuffer(this.fillVB);
  9098. this.fillVB = null;
  9099. }
  9100. if (this.fillIB) {
  9101. this._engine._releaseBuffer(this.fillIB);
  9102. this.fillIB = null;
  9103. }
  9104. this.effectFill = null;
  9105. this.effectFillInstanced = null;
  9106. this.effectBorder = null;
  9107. this.effectBorderInstanced = null;
  9108. if (this.borderVB) {
  9109. this._engine._releaseBuffer(this.borderVB);
  9110. this.borderVB = null;
  9111. }
  9112. if (this.borderIB) {
  9113. this._engine._releaseBuffer(this.borderIB);
  9114. this.borderIB = null;
  9115. }
  9116. return true;
  9117. };
  9118. return Ellipse2DRenderCache;
  9119. }(BABYLON.ModelRenderCache));
  9120. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  9121. var Ellipse2DInstanceData = (function (_super) {
  9122. __extends(Ellipse2DInstanceData, _super);
  9123. function Ellipse2DInstanceData(partId) {
  9124. _super.call(this, partId, 1);
  9125. }
  9126. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  9127. get: function () {
  9128. return null;
  9129. },
  9130. set: function (value) {
  9131. },
  9132. enumerable: true,
  9133. configurable: true
  9134. });
  9135. __decorate([
  9136. BABYLON.instanceData()
  9137. ], Ellipse2DInstanceData.prototype, "properties", null);
  9138. return Ellipse2DInstanceData;
  9139. }(BABYLON.Shape2DInstanceData));
  9140. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  9141. var Ellipse2D = (function (_super) {
  9142. __extends(Ellipse2D, _super);
  9143. /**
  9144. * Create an Ellipse 2D Shape primitive
  9145. * @param settings a combination of settings, possible ones are
  9146. * - 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)
  9147. * - children: an array of direct children
  9148. * - id: a text identifier, for information purpose
  9149. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  9150. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  9151. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  9152. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  9153. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  9154. * - zOrder: override the zOrder with the specified value
  9155. * - origin: define the normalized origin point location, default [0.5;0.5]
  9156. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  9157. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  9158. * - 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)
  9159. * - 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)
  9160. * - borderThickness: the thickness of the drawn border, default is 1.
  9161. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  9162. * - 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.
  9163. * - 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.
  9164. * - 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!
  9165. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9166. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9167. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9168. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9169. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  9170. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  9171. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  9172. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  9173. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9174. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9175. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9176. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9177. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  9178. */
  9179. function Ellipse2D(settings) {
  9180. // Avoid checking every time if the object exists
  9181. if (settings == null) {
  9182. settings = {};
  9183. }
  9184. _super.call(this, settings);
  9185. if (settings.size != null) {
  9186. this.size = settings.size;
  9187. }
  9188. else if (settings.width || settings.height) {
  9189. var size = new BABYLON.Size(settings.width, settings.height);
  9190. this.size = size;
  9191. }
  9192. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  9193. this.subdivisions = sub;
  9194. }
  9195. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  9196. get: function () {
  9197. if (this._actualSize) {
  9198. return this._actualSize;
  9199. }
  9200. return this.size;
  9201. },
  9202. set: function (value) {
  9203. this._actualSize = value;
  9204. },
  9205. enumerable: true,
  9206. configurable: true
  9207. });
  9208. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  9209. get: function () {
  9210. return this._subdivisions;
  9211. },
  9212. set: function (value) {
  9213. this._subdivisions = value;
  9214. },
  9215. enumerable: true,
  9216. configurable: true
  9217. });
  9218. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  9219. var w = this.size.width / 2;
  9220. var h = this.size.height / 2;
  9221. var x = intersectInfo._localPickPosition.x - w;
  9222. var y = intersectInfo._localPickPosition.y - h;
  9223. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  9224. };
  9225. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  9226. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  9227. };
  9228. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  9229. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  9230. return renderCache;
  9231. };
  9232. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  9233. var renderCache = modelRenderCache;
  9234. var engine = this.owner.engine;
  9235. // Need to create WebGL resources for fill part?
  9236. if (this.fill) {
  9237. var vbSize = this.subdivisions + 1;
  9238. var vb = new Float32Array(vbSize);
  9239. for (var i = 0; i < vbSize; i++) {
  9240. vb[i] = i;
  9241. }
  9242. renderCache.fillVB = engine.createVertexBuffer(vb);
  9243. var triCount = vbSize - 1;
  9244. var ib = new Float32Array(triCount * 3);
  9245. for (var i = 0; i < triCount; i++) {
  9246. ib[i * 3 + 0] = 0;
  9247. ib[i * 3 + 2] = i + 1;
  9248. ib[i * 3 + 1] = i + 2;
  9249. }
  9250. ib[triCount * 3 - 2] = 1;
  9251. renderCache.fillIB = engine.createIndexBuffer(ib);
  9252. renderCache.fillIndicesCount = triCount * 3;
  9253. // 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
  9254. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  9255. if (ei) {
  9256. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  9257. }
  9258. // Get the non instanced version
  9259. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  9260. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  9261. }
  9262. // Need to create WebGL resource for border part?
  9263. if (this.border) {
  9264. var vbSize = this.subdivisions * 2;
  9265. var vb = new Float32Array(vbSize);
  9266. for (var i = 0; i < vbSize; i++) {
  9267. vb[i] = i;
  9268. }
  9269. renderCache.borderVB = engine.createVertexBuffer(vb);
  9270. var triCount = vbSize;
  9271. var rs = triCount / 2;
  9272. var ib = new Float32Array(triCount * 3);
  9273. for (var i = 0; i < rs; i++) {
  9274. var r0 = i;
  9275. var r1 = (i + 1) % rs;
  9276. ib[i * 6 + 0] = rs + r1;
  9277. ib[i * 6 + 1] = rs + r0;
  9278. ib[i * 6 + 2] = r0;
  9279. ib[i * 6 + 3] = r1;
  9280. ib[i * 6 + 4] = rs + r1;
  9281. ib[i * 6 + 5] = r0;
  9282. }
  9283. renderCache.borderIB = engine.createIndexBuffer(ib);
  9284. renderCache.borderIndicesCount = (triCount * 3);
  9285. // 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
  9286. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  9287. if (ei) {
  9288. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  9289. }
  9290. // Get the non instanced version
  9291. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  9292. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  9293. }
  9294. return renderCache;
  9295. };
  9296. Ellipse2D.prototype.createInstanceDataParts = function () {
  9297. var res = new Array();
  9298. if (this.border) {
  9299. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  9300. }
  9301. if (this.fill) {
  9302. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  9303. }
  9304. return res;
  9305. };
  9306. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  9307. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  9308. return false;
  9309. }
  9310. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  9311. var d = part;
  9312. var size = this.actualSize;
  9313. var s = this.actualScale;
  9314. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  9315. }
  9316. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  9317. var d = part;
  9318. var size = this.actualSize;
  9319. var s = this.actualScale;
  9320. d.properties = new BABYLON.Vector3(size.width * s.x, size.height * s.y, this.subdivisions);
  9321. }
  9322. return true;
  9323. };
  9324. __decorate([
  9325. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  9326. ], Ellipse2D.prototype, "actualSize", null);
  9327. __decorate([
  9328. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  9329. ], Ellipse2D.prototype, "subdivisions", null);
  9330. Ellipse2D = __decorate([
  9331. BABYLON.className("Ellipse2D", "BABYLON")
  9332. ], Ellipse2D);
  9333. return Ellipse2D;
  9334. }(BABYLON.Shape2D));
  9335. BABYLON.Ellipse2D = Ellipse2D;
  9336. })(BABYLON || (BABYLON = {}));
  9337. var BABYLON;
  9338. (function (BABYLON) {
  9339. var Sprite2DRenderCache = (function (_super) {
  9340. __extends(Sprite2DRenderCache, _super);
  9341. function Sprite2DRenderCache() {
  9342. _super.apply(this, arguments);
  9343. this.effectsReady = false;
  9344. this.vb = null;
  9345. this.ib = null;
  9346. this.instancingAttributes = null;
  9347. this.texture = null;
  9348. this.effect = null;
  9349. this.effectInstanced = null;
  9350. }
  9351. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  9352. // Do nothing if the shader is still loading/preparing
  9353. if (!this.effectsReady) {
  9354. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  9355. return false;
  9356. }
  9357. this.effectsReady = true;
  9358. }
  9359. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  9360. var canvas = instanceInfo.owner.owner;
  9361. var engine = canvas.engine;
  9362. var cur = engine.getAlphaMode();
  9363. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  9364. engine.enableEffect(effect);
  9365. effect.setTexture("diffuseSampler", this.texture);
  9366. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  9367. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  9368. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  9369. }
  9370. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  9371. var pid = context.groupInfoPartData[0];
  9372. if (context.useInstancing) {
  9373. if (!this.instancingAttributes) {
  9374. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  9375. }
  9376. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  9377. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  9378. canvas._addDrawCallCount(1, context.renderMode);
  9379. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  9380. engine.draw(true, 0, 6, count);
  9381. engine.unbindInstanceAttributes();
  9382. }
  9383. else {
  9384. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  9385. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  9386. this.setupUniforms(effect, 0, pid._partData, i);
  9387. engine.draw(true, 0, 6);
  9388. }
  9389. }
  9390. engine.setAlphaMode(cur, true);
  9391. return true;
  9392. };
  9393. Sprite2DRenderCache.prototype.dispose = function () {
  9394. if (!_super.prototype.dispose.call(this)) {
  9395. return false;
  9396. }
  9397. if (this.vb) {
  9398. this._engine._releaseBuffer(this.vb);
  9399. this.vb = null;
  9400. }
  9401. if (this.ib) {
  9402. this._engine._releaseBuffer(this.ib);
  9403. this.ib = null;
  9404. }
  9405. //if (this.texture) {
  9406. // this.texture.dispose();
  9407. // this.texture = null;
  9408. //}
  9409. this.effect = null;
  9410. this.effectInstanced = null;
  9411. return true;
  9412. };
  9413. return Sprite2DRenderCache;
  9414. }(BABYLON.ModelRenderCache));
  9415. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  9416. var Sprite2DInstanceData = (function (_super) {
  9417. __extends(Sprite2DInstanceData, _super);
  9418. function Sprite2DInstanceData(partId) {
  9419. _super.call(this, partId, 1);
  9420. }
  9421. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  9422. get: function () {
  9423. return null;
  9424. },
  9425. set: function (value) {
  9426. },
  9427. enumerable: true,
  9428. configurable: true
  9429. });
  9430. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  9431. get: function () {
  9432. return null;
  9433. },
  9434. set: function (value) {
  9435. },
  9436. enumerable: true,
  9437. configurable: true
  9438. });
  9439. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  9440. get: function () {
  9441. return null;
  9442. },
  9443. set: function (value) {
  9444. },
  9445. enumerable: true,
  9446. configurable: true
  9447. });
  9448. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  9449. get: function () {
  9450. return null;
  9451. },
  9452. set: function (value) {
  9453. },
  9454. enumerable: true,
  9455. configurable: true
  9456. });
  9457. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  9458. // 3 floats being:
  9459. // - x: frame number to display
  9460. // - y: invertY setting
  9461. // - z: alignToPixel setting
  9462. get: function () {
  9463. return null;
  9464. },
  9465. set: function (value) {
  9466. },
  9467. enumerable: true,
  9468. configurable: true
  9469. });
  9470. __decorate([
  9471. BABYLON.instanceData()
  9472. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  9473. __decorate([
  9474. BABYLON.instanceData()
  9475. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  9476. __decorate([
  9477. BABYLON.instanceData()
  9478. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  9479. __decorate([
  9480. BABYLON.instanceData()
  9481. ], Sprite2DInstanceData.prototype, "textureSize", null);
  9482. __decorate([
  9483. BABYLON.instanceData()
  9484. ], Sprite2DInstanceData.prototype, "properties", null);
  9485. return Sprite2DInstanceData;
  9486. }(BABYLON.InstanceDataBase));
  9487. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  9488. var Sprite2D = (function (_super) {
  9489. __extends(Sprite2D, _super);
  9490. /**
  9491. * Create an 2D Sprite primitive
  9492. * @param texture the texture that stores the sprite to render
  9493. * @param settings a combination of settings, possible ones are
  9494. * - 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)
  9495. * - children: an array of direct children
  9496. * - id a text identifier, for information purpose
  9497. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  9498. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  9499. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  9500. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  9501. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  9502. * - zOrder: override the zOrder with the specified value
  9503. * - origin: define the normalized origin point location, default [0.5;0.5]
  9504. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  9505. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  9506. * - spriteScaleFactor: 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.
  9507. * - invertY: if true the texture Y will be inverted, default is false.
  9508. * - 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.
  9509. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  9510. * - 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.
  9511. * - 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.
  9512. * - 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!
  9513. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9514. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9515. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9516. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9517. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  9518. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  9519. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  9520. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  9521. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9522. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9523. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9524. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9525. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  9526. */
  9527. function Sprite2D(texture, settings) {
  9528. var _this = this;
  9529. if (!settings) {
  9530. settings = {};
  9531. }
  9532. _super.call(this, settings);
  9533. this.texture = texture;
  9534. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9535. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  9536. this.size = (settings.spriteSize != null) ? settings.spriteSize.clone() : null;
  9537. this.spriteLocation = (settings.spriteLocation != null) ? settings.spriteLocation.clone() : new BABYLON.Vector2(0, 0);
  9538. this.spriteScaleFactor = (settings.spriteScaleFactor != null) ? settings.spriteScaleFactor : new BABYLON.Vector2(1, 1);
  9539. this.spriteFrame = 0;
  9540. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  9541. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  9542. this.useAlphaFromTexture = true;
  9543. // 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.
  9544. // The fucking delayed texture sprite bug is fixed!
  9545. if (settings.spriteSize == null) {
  9546. this.size = new BABYLON.Size(10, 10);
  9547. }
  9548. if (settings.spriteSize == null || !texture.isReady()) {
  9549. if (texture.isReady()) {
  9550. var s = texture.getBaseSize();
  9551. this.size = new BABYLON.Size(s.width, s.height);
  9552. }
  9553. else {
  9554. texture.onLoadObservable.add(function () {
  9555. if (settings.spriteSize == null) {
  9556. var s = texture.getBaseSize();
  9557. _this.size = new BABYLON.Size(s.width, s.height);
  9558. }
  9559. _this._positioningDirty();
  9560. _this._setLayoutDirty();
  9561. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  9562. });
  9563. }
  9564. }
  9565. }
  9566. Object.defineProperty(Sprite2D.prototype, "texture", {
  9567. get: function () {
  9568. return this._texture;
  9569. },
  9570. set: function (value) {
  9571. this._texture = value;
  9572. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  9573. },
  9574. enumerable: true,
  9575. configurable: true
  9576. });
  9577. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  9578. get: function () {
  9579. return this._useAlphaFromTexture;
  9580. },
  9581. set: function (value) {
  9582. if (this._useAlphaFromTexture === value) {
  9583. return;
  9584. }
  9585. this._useAlphaFromTexture = value;
  9586. this._updateRenderMode();
  9587. },
  9588. enumerable: true,
  9589. configurable: true
  9590. });
  9591. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  9592. get: function () {
  9593. if (this._actualSize) {
  9594. return this._actualSize;
  9595. }
  9596. return this.size;
  9597. },
  9598. set: function (value) {
  9599. this._actualSize = value;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  9605. get: function () {
  9606. return this._location;
  9607. },
  9608. set: function (value) {
  9609. this._location = value;
  9610. },
  9611. enumerable: true,
  9612. configurable: true
  9613. });
  9614. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  9615. get: function () {
  9616. return this._spriteFrame;
  9617. },
  9618. set: function (value) {
  9619. this._spriteFrame = value;
  9620. },
  9621. enumerable: true,
  9622. configurable: true
  9623. });
  9624. Object.defineProperty(Sprite2D.prototype, "invertY", {
  9625. get: function () {
  9626. return this._invertY;
  9627. },
  9628. set: function (value) {
  9629. this._invertY = value;
  9630. },
  9631. enumerable: true,
  9632. configurable: true
  9633. });
  9634. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  9635. get: function () {
  9636. return this._spriteScaleFactor;
  9637. },
  9638. set: function (value) {
  9639. this._spriteScaleFactor = value;
  9640. },
  9641. enumerable: true,
  9642. configurable: true
  9643. });
  9644. /**
  9645. * Sets the scale of the sprite using a BABYLON.Size(w,h).
  9646. * Keeps proportion by taking the maximum of the two scale for x and y.
  9647. * @param {Size} size Size(width,height)
  9648. */
  9649. Sprite2D.prototype.scaleToSize = function (size) {
  9650. var baseSize = this.size;
  9651. if (baseSize == null || !this.texture.isReady()) {
  9652. // we're probably at initiation of the scene, size is not set
  9653. if (this.texture.isReady()) {
  9654. baseSize = this.texture.getBaseSize();
  9655. }
  9656. else {
  9657. // the texture is not ready, wait for it to load before calling scaleToSize again
  9658. var thisObject = this;
  9659. this.texture.onLoadObservable.add(function () {
  9660. thisObject.scaleToSize(size);
  9661. });
  9662. return;
  9663. }
  9664. }
  9665. this.scale = Math.max(size.height / baseSize.height, size.width / baseSize.width);
  9666. };
  9667. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  9668. /**
  9669. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  9670. */
  9671. get: function () {
  9672. return this._alignToPixel;
  9673. },
  9674. set: function (value) {
  9675. this._alignToPixel = value;
  9676. },
  9677. enumerable: true,
  9678. configurable: true
  9679. });
  9680. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  9681. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  9682. };
  9683. /**
  9684. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  9685. */
  9686. Sprite2D.prototype.getAnimatables = function () {
  9687. var res = new Array();
  9688. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  9689. res.push(this.texture);
  9690. }
  9691. return res;
  9692. };
  9693. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  9694. // 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
  9695. return true;
  9696. };
  9697. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  9698. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  9699. return renderCache;
  9700. };
  9701. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  9702. var renderCache = modelRenderCache;
  9703. var engine = this.owner.engine;
  9704. var vb = new Float32Array(4);
  9705. for (var i = 0; i < 4; i++) {
  9706. vb[i] = i;
  9707. }
  9708. renderCache.vb = engine.createVertexBuffer(vb);
  9709. var ib = new Float32Array(6);
  9710. ib[0] = 0;
  9711. ib[1] = 2;
  9712. ib[2] = 1;
  9713. ib[3] = 0;
  9714. ib[4] = 3;
  9715. ib[5] = 2;
  9716. renderCache.ib = engine.createIndexBuffer(ib);
  9717. renderCache.texture = this.texture;
  9718. // 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
  9719. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  9720. if (ei) {
  9721. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  9722. }
  9723. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  9724. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  9725. return renderCache;
  9726. };
  9727. Sprite2D.prototype.createInstanceDataParts = function () {
  9728. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  9729. };
  9730. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  9731. Sprite2D.layoutConstructMode = true;
  9732. };
  9733. // if obj contains something, we restore the _text property
  9734. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  9735. Sprite2D.layoutConstructMode = false;
  9736. };
  9737. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  9738. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  9739. return false;
  9740. }
  9741. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  9742. return false;
  9743. }
  9744. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  9745. var d = this._instanceDataParts[0];
  9746. if (Sprite2D.layoutConstructMode) {
  9747. d.topLeftUV = BABYLON.Vector2.Zero();
  9748. d.sizeUV = BABYLON.Vector2.Zero();
  9749. d.properties = BABYLON.Vector3.Zero();
  9750. d.textureSize = BABYLON.Vector2.Zero();
  9751. d.scaleFactor = BABYLON.Vector2.Zero();
  9752. }
  9753. else {
  9754. var ts = this.texture.getBaseSize();
  9755. var sl = this.spriteLocation;
  9756. var ss = this.actualSize;
  9757. var ssf = this.spriteScaleFactor;
  9758. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  9759. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  9760. d.sizeUV = suv;
  9761. d.scaleFactor = ssf;
  9762. Sprite2D._prop.x = this.spriteFrame;
  9763. Sprite2D._prop.y = this.invertY ? 1 : 0;
  9764. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  9765. d.properties = Sprite2D._prop;
  9766. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  9767. }
  9768. }
  9769. return true;
  9770. };
  9771. Sprite2D.prototype._mustUpdateInstance = function () {
  9772. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  9773. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  9774. if (res) {
  9775. this._updateRenderMode();
  9776. }
  9777. return res;
  9778. };
  9779. Sprite2D.prototype._useTextureAlpha = function () {
  9780. return this.texture != null && this.texture.hasAlpha;
  9781. };
  9782. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  9783. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  9784. };
  9785. Sprite2D.SPRITE2D_MAINPARTID = 1;
  9786. Sprite2D._prop = BABYLON.Vector3.Zero();
  9787. Sprite2D.layoutConstructMode = false;
  9788. __decorate([
  9789. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  9790. ], Sprite2D.prototype, "texture", null);
  9791. __decorate([
  9792. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
  9793. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  9794. __decorate([
  9795. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  9796. ], Sprite2D.prototype, "actualSize", null);
  9797. __decorate([
  9798. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  9799. ], Sprite2D.prototype, "spriteLocation", null);
  9800. __decorate([
  9801. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  9802. ], Sprite2D.prototype, "spriteFrame", null);
  9803. __decorate([
  9804. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
  9805. ], Sprite2D.prototype, "invertY", null);
  9806. __decorate([
  9807. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  9808. ], Sprite2D.prototype, "spriteScaleFactor", null);
  9809. Sprite2D = __decorate([
  9810. BABYLON.className("Sprite2D", "BABYLON")
  9811. ], Sprite2D);
  9812. return Sprite2D;
  9813. }(BABYLON.RenderablePrim2D));
  9814. BABYLON.Sprite2D = Sprite2D;
  9815. })(BABYLON || (BABYLON = {}));
  9816. var BABYLON;
  9817. (function (BABYLON) {
  9818. var Text2DRenderCache = (function (_super) {
  9819. __extends(Text2DRenderCache, _super);
  9820. function Text2DRenderCache() {
  9821. _super.apply(this, arguments);
  9822. this.effectsReady = false;
  9823. this.vb = null;
  9824. this.ib = null;
  9825. this.instancingAttributes = null;
  9826. this.fontTexture = null;
  9827. this.effect = null;
  9828. this.effectInstanced = null;
  9829. }
  9830. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  9831. // Do nothing if the shader is still loading/preparing
  9832. if (!this.effectsReady) {
  9833. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  9834. return false;
  9835. }
  9836. this.effectsReady = true;
  9837. }
  9838. var canvas = instanceInfo.owner.owner;
  9839. var engine = canvas.engine;
  9840. this.fontTexture.update();
  9841. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  9842. engine.enableEffect(effect);
  9843. effect.setTexture("diffuseSampler", this.fontTexture);
  9844. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  9845. var curAlphaMode = engine.getAlphaMode();
  9846. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  9847. var pid = context.groupInfoPartData[0];
  9848. if (context.useInstancing) {
  9849. if (!this.instancingAttributes) {
  9850. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  9851. }
  9852. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  9853. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  9854. canvas._addDrawCallCount(1, context.renderMode);
  9855. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  9856. engine.draw(true, 0, 6, count);
  9857. engine.unbindInstanceAttributes();
  9858. }
  9859. else {
  9860. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  9861. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  9862. this.setupUniforms(effect, 0, pid._partData, i);
  9863. engine.draw(true, 0, 6);
  9864. }
  9865. }
  9866. engine.setAlphaMode(curAlphaMode, true);
  9867. return true;
  9868. };
  9869. Text2DRenderCache.prototype.dispose = function () {
  9870. if (!_super.prototype.dispose.call(this)) {
  9871. return false;
  9872. }
  9873. if (this.vb) {
  9874. this._engine._releaseBuffer(this.vb);
  9875. this.vb = null;
  9876. }
  9877. if (this.ib) {
  9878. this._engine._releaseBuffer(this.ib);
  9879. this.ib = null;
  9880. }
  9881. if (this.fontTexture) {
  9882. this.fontTexture.decCachedFontTextureCounter();
  9883. this.fontTexture = null;
  9884. }
  9885. this.effect = null;
  9886. this.effectInstanced = null;
  9887. return true;
  9888. };
  9889. return Text2DRenderCache;
  9890. }(BABYLON.ModelRenderCache));
  9891. BABYLON.Text2DRenderCache = Text2DRenderCache;
  9892. var Text2DInstanceData = (function (_super) {
  9893. __extends(Text2DInstanceData, _super);
  9894. function Text2DInstanceData(partId, dataElementCount) {
  9895. _super.call(this, partId, dataElementCount);
  9896. }
  9897. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  9898. get: function () {
  9899. return null;
  9900. },
  9901. set: function (value) {
  9902. },
  9903. enumerable: true,
  9904. configurable: true
  9905. });
  9906. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  9907. get: function () {
  9908. return null;
  9909. },
  9910. set: function (value) {
  9911. },
  9912. enumerable: true,
  9913. configurable: true
  9914. });
  9915. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  9916. get: function () {
  9917. return null;
  9918. },
  9919. set: function (value) {
  9920. },
  9921. enumerable: true,
  9922. configurable: true
  9923. });
  9924. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  9925. get: function () {
  9926. return null;
  9927. },
  9928. set: function (value) {
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  9934. get: function () {
  9935. return null;
  9936. },
  9937. set: function (value) {
  9938. },
  9939. enumerable: true,
  9940. configurable: true
  9941. });
  9942. __decorate([
  9943. BABYLON.instanceData()
  9944. ], Text2DInstanceData.prototype, "topLeftUV", null);
  9945. __decorate([
  9946. BABYLON.instanceData()
  9947. ], Text2DInstanceData.prototype, "sizeUV", null);
  9948. __decorate([
  9949. BABYLON.instanceData()
  9950. ], Text2DInstanceData.prototype, "textureSize", null);
  9951. __decorate([
  9952. BABYLON.instanceData()
  9953. ], Text2DInstanceData.prototype, "color", null);
  9954. __decorate([
  9955. BABYLON.instanceData()
  9956. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  9957. return Text2DInstanceData;
  9958. }(BABYLON.InstanceDataBase));
  9959. BABYLON.Text2DInstanceData = Text2DInstanceData;
  9960. var Text2D = (function (_super) {
  9961. __extends(Text2D, _super);
  9962. /**
  9963. * Create a Text primitive
  9964. * @param text the text to display
  9965. * @param settings a combination of settings, possible ones are
  9966. * - 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)
  9967. * - children: an array of direct children
  9968. * - id a text identifier, for information purpose
  9969. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  9970. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  9971. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  9972. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  9973. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  9974. * - zOrder: override the zOrder with the specified value
  9975. * - origin: define the normalized origin point location, default [0.5;0.5]
  9976. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  9977. * - 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.
  9978. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  9979. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  9980. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  9981. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  9982. * - 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.
  9983. * - 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.
  9984. * - 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!
  9985. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9986. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9987. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9988. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9989. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  9990. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  9991. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  9992. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  9993. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9994. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9995. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9996. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  9997. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  9998. */
  9999. function Text2D(text, settings) {
  10000. if (!settings) {
  10001. settings = {};
  10002. }
  10003. _super.call(this, settings);
  10004. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  10005. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  10006. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  10007. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  10008. this._textSize = null;
  10009. this.text = text;
  10010. this.size = (settings.size == null) ? null : settings.size;
  10011. this._updateRenderMode();
  10012. }
  10013. Object.defineProperty(Text2D.prototype, "fontName", {
  10014. get: function () {
  10015. return this._fontName;
  10016. },
  10017. set: function (value) {
  10018. if (this._fontName) {
  10019. throw new Error("Font Name change is not supported right now.");
  10020. }
  10021. this._fontName = value;
  10022. },
  10023. enumerable: true,
  10024. configurable: true
  10025. });
  10026. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  10027. get: function () {
  10028. return this._defaultFontColor;
  10029. },
  10030. set: function (value) {
  10031. this._defaultFontColor = value;
  10032. },
  10033. enumerable: true,
  10034. configurable: true
  10035. });
  10036. Object.defineProperty(Text2D.prototype, "text", {
  10037. get: function () {
  10038. return this._text;
  10039. },
  10040. set: function (value) {
  10041. if (!value) {
  10042. value = "";
  10043. }
  10044. this._text = value;
  10045. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  10046. this._size = null;
  10047. this._updateCharCount();
  10048. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  10049. var s = this.textSize;
  10050. },
  10051. enumerable: true,
  10052. configurable: true
  10053. });
  10054. Object.defineProperty(Text2D.prototype, "size", {
  10055. get: function () {
  10056. if (this._size != null) {
  10057. return this._size;
  10058. }
  10059. return this.textSize;
  10060. },
  10061. set: function (value) {
  10062. this._size = value;
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. Object.defineProperty(Text2D.prototype, "isSizeAuto", {
  10068. get: function () {
  10069. return false;
  10070. },
  10071. enumerable: true,
  10072. configurable: true
  10073. });
  10074. Object.defineProperty(Text2D.prototype, "actualSize", {
  10075. /**
  10076. * Get the actual size of the Text2D primitive
  10077. */
  10078. get: function () {
  10079. if (this._actualSize) {
  10080. return this._actualSize;
  10081. }
  10082. return this.size;
  10083. },
  10084. enumerable: true,
  10085. configurable: true
  10086. });
  10087. Object.defineProperty(Text2D.prototype, "textSize", {
  10088. /**
  10089. * Get the area that bounds the text associated to the primitive
  10090. */
  10091. get: function () {
  10092. if (!this._textSize) {
  10093. if (this.owner && this._text) {
  10094. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  10095. if (!newSize.equals(this._textSize)) {
  10096. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  10097. this._positioningDirty();
  10098. }
  10099. this._textSize = newSize;
  10100. }
  10101. else {
  10102. return Text2D.nullSize;
  10103. }
  10104. }
  10105. return this._textSize;
  10106. },
  10107. enumerable: true,
  10108. configurable: true
  10109. });
  10110. Object.defineProperty(Text2D.prototype, "fontTexture", {
  10111. get: function () {
  10112. if (this._fontTexture) {
  10113. return this._fontTexture;
  10114. }
  10115. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  10116. return null;
  10117. }
  10118. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  10119. return this._fontTexture;
  10120. },
  10121. enumerable: true,
  10122. configurable: true
  10123. });
  10124. /**
  10125. * Dispose the primitive, remove it from its parent
  10126. */
  10127. Text2D.prototype.dispose = function () {
  10128. if (!_super.prototype.dispose.call(this)) {
  10129. return false;
  10130. }
  10131. if (this._fontTexture) {
  10132. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  10133. this._fontTexture = null;
  10134. }
  10135. return true;
  10136. };
  10137. Text2D.prototype.updateLevelBoundingInfo = function () {
  10138. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  10139. };
  10140. Text2D.prototype.levelIntersect = function (intersectInfo) {
  10141. // 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...
  10142. return true;
  10143. };
  10144. Text2D.prototype.createModelRenderCache = function (modelKey) {
  10145. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  10146. return renderCache;
  10147. };
  10148. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  10149. var renderCache = modelRenderCache;
  10150. var engine = this.owner.engine;
  10151. renderCache.fontTexture = this.fontTexture;
  10152. renderCache.fontTexture.incCachedFontTextureCounter();
  10153. var vb = new Float32Array(4);
  10154. for (var i = 0; i < 4; i++) {
  10155. vb[i] = i;
  10156. }
  10157. renderCache.vb = engine.createVertexBuffer(vb);
  10158. var ib = new Float32Array(6);
  10159. ib[0] = 0;
  10160. ib[1] = 2;
  10161. ib[2] = 1;
  10162. ib[3] = 0;
  10163. ib[4] = 3;
  10164. ib[5] = 2;
  10165. renderCache.ib = engine.createIndexBuffer(ib);
  10166. // 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
  10167. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
  10168. if (ei) {
  10169. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  10170. }
  10171. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
  10172. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  10173. return renderCache;
  10174. };
  10175. Text2D.prototype.createInstanceDataParts = function () {
  10176. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  10177. };
  10178. // Looks like a hack!? Yes! Because that's what it is!
  10179. // 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
  10180. // 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)
  10181. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  10182. if (!this._charCount) {
  10183. var curText = this._text;
  10184. this.text = "A";
  10185. return curText;
  10186. }
  10187. };
  10188. // if obj contains something, we restore the _text property
  10189. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  10190. if (obj !== undefined) {
  10191. this.text = obj;
  10192. }
  10193. };
  10194. Text2D.prototype.refreshInstanceDataPart = function (part) {
  10195. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  10196. return false;
  10197. }
  10198. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  10199. var d = part;
  10200. var texture = this.fontTexture;
  10201. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  10202. var ts = texture.getSize();
  10203. var offset = BABYLON.Vector2.Zero();
  10204. var lh = this.fontTexture.lineHeight;
  10205. offset.y = ((this.textSize.height / lh) - 1) * lh; // Origin is bottom, not top, so the offset is starting with a y that is the top location of the text
  10206. var charxpos = 0;
  10207. d.dataElementCount = this._charCount;
  10208. d.curElement = 0;
  10209. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  10210. var char = _a[_i];
  10211. // Line feed
  10212. if (char === "\n") {
  10213. offset.x = 0;
  10214. offset.y -= texture.lineHeight;
  10215. }
  10216. // Tabulation ?
  10217. if (char === "\t") {
  10218. var nextPos = charxpos + this._tabulationSize;
  10219. nextPos = nextPos - (nextPos % this._tabulationSize);
  10220. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  10221. charxpos = nextPos;
  10222. continue;
  10223. }
  10224. if (char < " ") {
  10225. continue;
  10226. }
  10227. this.updateInstanceDataPart(d, offset);
  10228. var ci = texture.getChar(char);
  10229. offset.x += ci.charWidth;
  10230. d.topLeftUV = ci.topLeftUV;
  10231. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  10232. d.sizeUV = suv;
  10233. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  10234. d.color = this.defaultFontColor;
  10235. d.superSampleFactor = superSampleFactor;
  10236. ++d.curElement;
  10237. }
  10238. }
  10239. return true;
  10240. };
  10241. Text2D.prototype._updateCharCount = function () {
  10242. var count = 0;
  10243. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  10244. var char = _a[_i];
  10245. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  10246. continue;
  10247. }
  10248. ++count;
  10249. }
  10250. this._charCount = count;
  10251. };
  10252. Text2D.prototype._useTextureAlpha = function () {
  10253. return this.fontTexture != null && this.fontTexture.hasAlpha;
  10254. };
  10255. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  10256. return true;
  10257. };
  10258. Text2D.TEXT2D_MAINPARTID = 1;
  10259. __decorate([
  10260. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  10261. ], Text2D.prototype, "fontName", null);
  10262. __decorate([
  10263. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  10264. ], Text2D.prototype, "defaultFontColor", null);
  10265. __decorate([
  10266. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  10267. ], Text2D.prototype, "text", null);
  10268. __decorate([
  10269. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  10270. ], Text2D.prototype, "size", null);
  10271. Text2D = __decorate([
  10272. BABYLON.className("Text2D", "BABYLON")
  10273. ], Text2D);
  10274. return Text2D;
  10275. }(BABYLON.RenderablePrim2D));
  10276. BABYLON.Text2D = Text2D;
  10277. })(BABYLON || (BABYLON = {}));
  10278. var BABYLON;
  10279. (function (BABYLON) {
  10280. var Lines2DRenderCache = (function (_super) {
  10281. __extends(Lines2DRenderCache, _super);
  10282. function Lines2DRenderCache(engine, modelKey) {
  10283. _super.call(this, engine, modelKey);
  10284. this.effectsReady = false;
  10285. this.fillVB = null;
  10286. this.fillIB = null;
  10287. this.fillIndicesCount = 0;
  10288. this.instancingFillAttributes = null;
  10289. this.effectFill = null;
  10290. this.effectFillInstanced = null;
  10291. this.borderVB = null;
  10292. this.borderIB = null;
  10293. this.borderIndicesCount = 0;
  10294. this.instancingBorderAttributes = null;
  10295. this.effectBorder = null;
  10296. this.effectBorderInstanced = null;
  10297. }
  10298. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  10299. // Do nothing if the shader is still loading/preparing
  10300. if (!this.effectsReady) {
  10301. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  10302. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  10303. return false;
  10304. }
  10305. this.effectsReady = true;
  10306. }
  10307. var canvas = instanceInfo.owner.owner;
  10308. var engine = canvas.engine;
  10309. var depthFunction = 0;
  10310. if (this.effectFill && this.effectBorder) {
  10311. depthFunction = engine.getDepthFunction();
  10312. engine.setDepthFunctionToLessOrEqual();
  10313. }
  10314. var curAlphaMode = engine.getAlphaMode();
  10315. if (this.effectFill) {
  10316. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  10317. var pid = context.groupInfoPartData[partIndex];
  10318. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  10319. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  10320. }
  10321. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  10322. engine.enableEffect(effect);
  10323. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  10324. if (context.useInstancing) {
  10325. if (!this.instancingFillAttributes) {
  10326. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  10327. }
  10328. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  10329. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  10330. canvas._addDrawCallCount(1, context.renderMode);
  10331. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  10332. engine.draw(true, 0, this.fillIndicesCount, count);
  10333. engine.unbindInstanceAttributes();
  10334. }
  10335. else {
  10336. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  10337. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  10338. this.setupUniforms(effect, partIndex, pid._partData, i);
  10339. engine.draw(true, 0, this.fillIndicesCount);
  10340. }
  10341. }
  10342. }
  10343. if (this.effectBorder) {
  10344. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  10345. var pid = context.groupInfoPartData[partIndex];
  10346. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  10347. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  10348. }
  10349. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  10350. engine.enableEffect(effect);
  10351. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  10352. if (context.useInstancing) {
  10353. if (!this.instancingBorderAttributes) {
  10354. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  10355. }
  10356. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  10357. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  10358. canvas._addDrawCallCount(1, context.renderMode);
  10359. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  10360. engine.draw(true, 0, this.borderIndicesCount, count);
  10361. engine.unbindInstanceAttributes();
  10362. }
  10363. else {
  10364. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  10365. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  10366. this.setupUniforms(effect, partIndex, pid._partData, i);
  10367. engine.draw(true, 0, this.borderIndicesCount);
  10368. }
  10369. }
  10370. }
  10371. engine.setAlphaMode(curAlphaMode, true);
  10372. if (this.effectFill && this.effectBorder) {
  10373. engine.setDepthFunction(depthFunction);
  10374. }
  10375. return true;
  10376. };
  10377. Lines2DRenderCache.prototype.dispose = function () {
  10378. if (!_super.prototype.dispose.call(this)) {
  10379. return false;
  10380. }
  10381. if (this.fillVB) {
  10382. this._engine._releaseBuffer(this.fillVB);
  10383. this.fillVB = null;
  10384. }
  10385. if (this.fillIB) {
  10386. this._engine._releaseBuffer(this.fillIB);
  10387. this.fillIB = null;
  10388. }
  10389. this.effectFill = null;
  10390. this.effectFillInstanced = null;
  10391. this.effectBorder = null;
  10392. this.effectBorderInstanced = null;
  10393. if (this.borderVB) {
  10394. this._engine._releaseBuffer(this.borderVB);
  10395. this.borderVB = null;
  10396. }
  10397. if (this.borderIB) {
  10398. this._engine._releaseBuffer(this.borderIB);
  10399. this.borderIB = null;
  10400. }
  10401. return true;
  10402. };
  10403. return Lines2DRenderCache;
  10404. }(BABYLON.ModelRenderCache));
  10405. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  10406. var Lines2DInstanceData = (function (_super) {
  10407. __extends(Lines2DInstanceData, _super);
  10408. function Lines2DInstanceData(partId) {
  10409. _super.call(this, partId, 1);
  10410. }
  10411. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  10412. get: function () {
  10413. return null;
  10414. },
  10415. set: function (value) {
  10416. },
  10417. enumerable: true,
  10418. configurable: true
  10419. });
  10420. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  10421. get: function () {
  10422. return null;
  10423. },
  10424. set: function (value) {
  10425. },
  10426. enumerable: true,
  10427. configurable: true
  10428. });
  10429. __decorate([
  10430. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  10431. ], Lines2DInstanceData.prototype, "boundingMin", null);
  10432. __decorate([
  10433. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  10434. ], Lines2DInstanceData.prototype, "boundingMax", null);
  10435. return Lines2DInstanceData;
  10436. }(BABYLON.Shape2DInstanceData));
  10437. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  10438. var Lines2D = (function (_super) {
  10439. __extends(Lines2D, _super);
  10440. /**
  10441. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  10442. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  10443. * @param settings a combination of settings, possible ones are
  10444. * - 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)
  10445. * - children: an array of direct children
  10446. * - id a text identifier, for information purpose
  10447. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  10448. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  10449. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  10450. * - dontInheritParentScale: if set the parent's scale won't be taken into consideration to compute the actualScale property
  10451. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  10452. * - zOrder: override the zOrder with the specified value
  10453. * - origin: define the normalized origin point location, default [0.5;0.5]
  10454. * - 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.
  10455. * - 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.
  10456. * - 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.
  10457. * - 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.
  10458. * - 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)
  10459. * - 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)
  10460. * - borderThickness: the thickness of the drawn border, default is 1.
  10461. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  10462. * - 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.
  10463. * - 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.
  10464. * - 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!
  10465. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10466. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10467. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10468. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10469. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  10470. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  10471. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  10472. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  10473. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10474. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10475. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10476. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  10477. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  10478. */
  10479. function Lines2D(points, settings) {
  10480. if (!settings) {
  10481. settings = {};
  10482. }
  10483. _super.call(this, settings);
  10484. this._fillVB = null;
  10485. this._fillIB = null;
  10486. this._borderVB = null;
  10487. this._borderIB = null;
  10488. this._size = BABYLON.Size.Zero();
  10489. this._boundingMin = null;
  10490. this._boundingMax = null;
  10491. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  10492. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  10493. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  10494. var closed = (settings.closed == null) ? false : settings.closed;
  10495. this.points = points;
  10496. this.fillThickness = fillThickness;
  10497. this.startCap = startCap;
  10498. this.endCap = endCap;
  10499. this.closed = closed;
  10500. }
  10501. Object.defineProperty(Lines2D, "NoCap", {
  10502. /**
  10503. * No Cap to apply on the extremity
  10504. */
  10505. get: function () { return Lines2D._noCap; },
  10506. enumerable: true,
  10507. configurable: true
  10508. });
  10509. Object.defineProperty(Lines2D, "RoundCap", {
  10510. /**
  10511. * A round cap, will use the line thickness as diameter
  10512. */
  10513. get: function () { return Lines2D._roundCap; },
  10514. enumerable: true,
  10515. configurable: true
  10516. });
  10517. Object.defineProperty(Lines2D, "TriangleCap", {
  10518. /**
  10519. * Creates a triangle at the extremity.
  10520. */
  10521. get: function () { return Lines2D._triangleCap; },
  10522. enumerable: true,
  10523. configurable: true
  10524. });
  10525. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  10526. /**
  10527. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  10528. */
  10529. get: function () { return Lines2D._squareAnchorCap; },
  10530. enumerable: true,
  10531. configurable: true
  10532. });
  10533. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  10534. /**
  10535. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  10536. */
  10537. get: function () { return Lines2D._roundAnchorCap; },
  10538. enumerable: true,
  10539. configurable: true
  10540. });
  10541. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  10542. /**
  10543. * Creates a diamond anchor at the extremity.
  10544. */
  10545. get: function () { return Lines2D._diamondAnchorCap; },
  10546. enumerable: true,
  10547. configurable: true
  10548. });
  10549. Object.defineProperty(Lines2D, "ArrowCap", {
  10550. /**
  10551. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  10552. */
  10553. get: function () { return Lines2D._arrowCap; },
  10554. enumerable: true,
  10555. configurable: true
  10556. });
  10557. Object.defineProperty(Lines2D.prototype, "points", {
  10558. get: function () {
  10559. return this._points;
  10560. },
  10561. set: function (value) {
  10562. this._points = value;
  10563. this._contour = null;
  10564. this._boundingBoxDirty();
  10565. },
  10566. enumerable: true,
  10567. configurable: true
  10568. });
  10569. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  10570. get: function () {
  10571. return this._fillThickness;
  10572. },
  10573. set: function (value) {
  10574. this._fillThickness = value;
  10575. },
  10576. enumerable: true,
  10577. configurable: true
  10578. });
  10579. Object.defineProperty(Lines2D.prototype, "closed", {
  10580. get: function () {
  10581. return this._closed;
  10582. },
  10583. set: function (value) {
  10584. this._closed = value;
  10585. },
  10586. enumerable: true,
  10587. configurable: true
  10588. });
  10589. Object.defineProperty(Lines2D.prototype, "startCap", {
  10590. get: function () {
  10591. return this._startCap;
  10592. },
  10593. set: function (value) {
  10594. this._startCap = value;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. Object.defineProperty(Lines2D.prototype, "endCap", {
  10600. get: function () {
  10601. return this._endCap;
  10602. },
  10603. set: function (value) {
  10604. this._endCap = value;
  10605. },
  10606. enumerable: true,
  10607. configurable: true
  10608. });
  10609. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  10610. var _this = this;
  10611. if (this._contour == null) {
  10612. this._computeLines2D();
  10613. }
  10614. var pl = this.points.length;
  10615. var l = this.closed ? pl + 1 : pl;
  10616. var p = intersectInfo._localPickPosition;
  10617. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  10618. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  10619. for (var i = 1; i < l; i++) {
  10620. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  10621. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  10622. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  10623. return true;
  10624. }
  10625. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  10626. return true;
  10627. }
  10628. Lines2D._prevA.x = Lines2D._curA.x;
  10629. Lines2D._prevA.y = Lines2D._curA.y;
  10630. Lines2D._prevB.x = Lines2D._curB.x;
  10631. Lines2D._prevB.y = Lines2D._curB.y;
  10632. }
  10633. var capIntersect = function (tri, points) {
  10634. var l = tri.length;
  10635. for (var i = 0; i < l; i += 3) {
  10636. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  10637. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  10638. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  10639. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  10640. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  10641. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  10642. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  10643. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  10644. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  10645. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  10646. return true;
  10647. }
  10648. }
  10649. return false;
  10650. };
  10651. if (this._startCapTriIndices) {
  10652. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  10653. return true;
  10654. }
  10655. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  10656. return true;
  10657. }
  10658. }
  10659. return false;
  10660. };
  10661. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  10662. get: function () {
  10663. if (!this._boundingMin) {
  10664. this._computeLines2D();
  10665. }
  10666. return this._boundingMin;
  10667. },
  10668. enumerable: true,
  10669. configurable: true
  10670. });
  10671. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  10672. get: function () {
  10673. if (!this._boundingMax) {
  10674. this._computeLines2D();
  10675. }
  10676. return this._boundingMax;
  10677. },
  10678. enumerable: true,
  10679. configurable: true
  10680. });
  10681. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  10682. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  10683. // Remove the BORDER category, we don't use it in the VertexShader
  10684. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  10685. if (i !== -1) {
  10686. res.splice(i, 1);
  10687. }
  10688. return res;
  10689. };
  10690. Lines2D.prototype.updateLevelBoundingInfo = function () {
  10691. if (!this._boundingMin) {
  10692. this._computeLines2D();
  10693. }
  10694. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  10695. };
  10696. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  10697. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  10698. return renderCache;
  10699. };
  10700. ///////////////////////////////////////////////////////////////////////////////////
  10701. // Methods for Lines building
  10702. Lines2D.prototype._perp = function (v, res) {
  10703. res.x = v.y;
  10704. res.y = -v.x;
  10705. };
  10706. ;
  10707. Lines2D.prototype._direction = function (a, b, res) {
  10708. a.subtractToRef(b, res);
  10709. res.normalize();
  10710. };
  10711. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  10712. a.addToRef(b, tangent);
  10713. tangent.normalize();
  10714. miter.x = -tangent.y;
  10715. miter.y = tangent.x;
  10716. Lines2D._miterTps.x = -a.y;
  10717. Lines2D._miterTps.y = a.x;
  10718. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  10719. };
  10720. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  10721. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  10722. if (d === 0)
  10723. return false;
  10724. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  10725. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  10726. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  10727. return false;
  10728. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  10729. return false;
  10730. return true;
  10731. };
  10732. Lines2D.prototype._updateMinMax = function (array, offset) {
  10733. if (offset >= array.length) {
  10734. return;
  10735. }
  10736. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  10737. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  10738. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  10739. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  10740. };
  10741. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  10742. var borderMode = borderThickness != null && !isNaN(borderThickness);
  10743. var off = index * (borderMode ? 8 : 4);
  10744. // 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)
  10745. if (off >= array.length) {
  10746. return;
  10747. }
  10748. // Store start/end normal, we need it for the cap construction
  10749. if (index === 0) {
  10750. this._perp(n, Lines2D._startDir);
  10751. }
  10752. else if (index === max - 1) {
  10753. this._perp(n, Lines2D._endDir);
  10754. Lines2D._endDir.x *= -1;
  10755. Lines2D._endDir.y *= -1;
  10756. }
  10757. var swap = false;
  10758. array[off + 0] = p.x + n.x * halfThickness;
  10759. array[off + 1] = p.y + n.y * halfThickness;
  10760. array[off + 2] = p.x + n.x * -halfThickness;
  10761. array[off + 3] = p.y + n.y * -halfThickness;
  10762. this._updateMinMax(array, off);
  10763. this._updateMinMax(array, off + 2);
  10764. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  10765. // 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
  10766. if (detectFlip !== undefined) {
  10767. // Flip if intersect
  10768. var flipOff = detectFlip * (borderMode ? 8 : 4);
  10769. 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])) {
  10770. swap = true;
  10771. var tps = array[off + 0];
  10772. array[off + 0] = array[off + 2];
  10773. array[off + 2] = tps;
  10774. tps = array[off + 1];
  10775. array[off + 1] = array[off + 3];
  10776. array[off + 3] = tps;
  10777. }
  10778. }
  10779. if (borderMode) {
  10780. var t = halfThickness + borderThickness;
  10781. array[off + 4] = p.x + n.x * (swap ? -t : t);
  10782. array[off + 5] = p.y + n.y * (swap ? -t : t);
  10783. array[off + 6] = p.x + n.x * (swap ? t : -t);
  10784. array[off + 7] = p.y + n.y * (swap ? t : -t);
  10785. this._updateMinMax(array, off + 4);
  10786. this._updateMinMax(array, off + 6);
  10787. }
  10788. if (contour) {
  10789. off += borderMode ? 4 : 0;
  10790. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  10791. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  10792. }
  10793. };
  10794. Lines2D.prototype._getCapSize = function (type, border) {
  10795. if (border === void 0) { border = false; }
  10796. var sd = Lines2D._roundCapSubDiv;
  10797. // If no array given, we call this to get the size
  10798. var vbsize = 0, ibsize = 0;
  10799. switch (type) {
  10800. case Lines2D.NoCap:
  10801. {
  10802. // If the line is not close and we're computing border, we add the size to generate the edge border
  10803. if (!this.closed && border) {
  10804. vbsize = 4;
  10805. ibsize = 6;
  10806. }
  10807. else {
  10808. vbsize = ibsize = 0;
  10809. }
  10810. break;
  10811. }
  10812. case Lines2D.RoundCap:
  10813. {
  10814. if (border) {
  10815. vbsize = sd;
  10816. ibsize = (sd - 2) * 3;
  10817. }
  10818. else {
  10819. vbsize = (sd / 2) + 1;
  10820. ibsize = (sd / 2) * 3;
  10821. }
  10822. break;
  10823. }
  10824. case Lines2D.ArrowCap:
  10825. {
  10826. if (border) {
  10827. vbsize = 12;
  10828. ibsize = 24;
  10829. }
  10830. else {
  10831. vbsize = 3;
  10832. ibsize = 3;
  10833. }
  10834. break;
  10835. }
  10836. case Lines2D.TriangleCap:
  10837. {
  10838. if (border) {
  10839. vbsize = 6;
  10840. ibsize = 12;
  10841. }
  10842. else {
  10843. vbsize = 3;
  10844. ibsize = 3;
  10845. }
  10846. break;
  10847. }
  10848. case Lines2D.DiamondAnchorCap:
  10849. {
  10850. if (border) {
  10851. vbsize = 10;
  10852. ibsize = 24;
  10853. }
  10854. else {
  10855. vbsize = 5;
  10856. ibsize = 9;
  10857. }
  10858. break;
  10859. }
  10860. case Lines2D.SquareAnchorCap:
  10861. {
  10862. if (border) {
  10863. vbsize = 12;
  10864. ibsize = 30;
  10865. }
  10866. else {
  10867. vbsize = 4;
  10868. ibsize = 6;
  10869. }
  10870. break;
  10871. }
  10872. case Lines2D.RoundAnchorCap:
  10873. {
  10874. if (border) {
  10875. vbsize = sd * 2;
  10876. ibsize = (sd - 1) * 6;
  10877. }
  10878. else {
  10879. vbsize = sd + 1;
  10880. ibsize = (sd + 1) * 3;
  10881. }
  10882. break;
  10883. }
  10884. }
  10885. return { vbsize: vbsize * 2, ibsize: ibsize };
  10886. };
  10887. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  10888. var c = Math.cos(rotation);
  10889. var s = Math.sin(rotation);
  10890. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  10891. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  10892. var offset = baseOffset + (index * 2);
  10893. vb[offset + 0] = Lines2D._tpsV.x;
  10894. vb[offset + 1] = Lines2D._tpsV.y;
  10895. if (contour) {
  10896. contour.push(Lines2D._tpsV.x);
  10897. contour.push(Lines2D._tpsV.y);
  10898. }
  10899. this._updateMinMax(vb, offset);
  10900. return (baseOffset + index * 2) / 2;
  10901. };
  10902. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  10903. ib[baseOffset + index] = vertexIndex;
  10904. };
  10905. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  10906. // 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
  10907. var sd = Lines2D._roundCapSubDiv;
  10908. var dir = new BABYLON.Vector2(1, 0);
  10909. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  10910. var ht = thickness / 2;
  10911. var t = thickness;
  10912. var borderMode = borderThickness != null;
  10913. var bt = borderThickness;
  10914. switch (type) {
  10915. case Lines2D.NoCap:
  10916. if (borderMode && !this.closed) {
  10917. var vi = 0;
  10918. var ii = 0;
  10919. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  10920. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  10921. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  10922. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  10923. this._storeIndex(ib, ibi, ii++, v1);
  10924. this._storeIndex(ib, ibi, ii++, v2);
  10925. this._storeIndex(ib, ibi, ii++, v3);
  10926. this._storeIndex(ib, ibi, ii++, v1);
  10927. this._storeIndex(ib, ibi, ii++, v3);
  10928. this._storeIndex(ib, ibi, ii++, v4);
  10929. }
  10930. break;
  10931. case Lines2D.ArrowCap:
  10932. ht *= 2;
  10933. case Lines2D.TriangleCap:
  10934. {
  10935. if (borderMode) {
  10936. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  10937. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  10938. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  10939. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  10940. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  10941. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  10942. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  10943. var ii = 0;
  10944. this._storeIndex(ib, ibi, ii++, v1);
  10945. this._storeIndex(ib, ibi, ii++, v4);
  10946. this._storeIndex(ib, ibi, ii++, v5);
  10947. this._storeIndex(ib, ibi, ii++, v1);
  10948. this._storeIndex(ib, ibi, ii++, v5);
  10949. this._storeIndex(ib, ibi, ii++, v2);
  10950. this._storeIndex(ib, ibi, ii++, v6);
  10951. this._storeIndex(ib, ibi, ii++, v3);
  10952. this._storeIndex(ib, ibi, ii++, v2);
  10953. this._storeIndex(ib, ibi, ii++, v6);
  10954. this._storeIndex(ib, ibi, ii++, v2);
  10955. this._storeIndex(ib, ibi, ii++, v5);
  10956. if (type === Lines2D.ArrowCap) {
  10957. var rht = thickness / 2;
  10958. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  10959. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  10960. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  10961. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  10962. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  10963. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  10964. this._storeIndex(ib, ibi, ii++, v7);
  10965. this._storeIndex(ib, ibi, ii++, v8);
  10966. this._storeIndex(ib, ibi, ii++, v9);
  10967. this._storeIndex(ib, ibi, ii++, v7);
  10968. this._storeIndex(ib, ibi, ii++, v9);
  10969. this._storeIndex(ib, ibi, ii++, v4);
  10970. this._storeIndex(ib, ibi, ii++, v10);
  10971. this._storeIndex(ib, ibi, ii++, v12);
  10972. this._storeIndex(ib, ibi, ii++, v11);
  10973. this._storeIndex(ib, ibi, ii++, v10);
  10974. this._storeIndex(ib, ibi, ii++, v6);
  10975. this._storeIndex(ib, ibi, ii++, v12);
  10976. }
  10977. }
  10978. else {
  10979. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  10980. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  10981. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  10982. this._storeIndex(ib, ibi, 0, v1);
  10983. this._storeIndex(ib, ibi, 1, v2);
  10984. this._storeIndex(ib, ibi, 2, v3);
  10985. }
  10986. break;
  10987. }
  10988. case Lines2D.RoundCap:
  10989. {
  10990. if (borderMode) {
  10991. var curA = -Math.PI / 2;
  10992. var incA = Math.PI / (sd / 2 - 1);
  10993. var ii = 0;
  10994. for (var i = 0; i < (sd / 2); i++) {
  10995. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  10996. 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);
  10997. if (i > 0) {
  10998. this._storeIndex(ib, ibi, ii++, v1 - 2);
  10999. this._storeIndex(ib, ibi, ii++, v2 - 2);
  11000. this._storeIndex(ib, ibi, ii++, v2);
  11001. this._storeIndex(ib, ibi, ii++, v1 - 2);
  11002. this._storeIndex(ib, ibi, ii++, v2);
  11003. this._storeIndex(ib, ibi, ii++, v1);
  11004. }
  11005. curA += incA;
  11006. }
  11007. }
  11008. else {
  11009. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  11010. var curA = -Math.PI / 2;
  11011. var incA = Math.PI / (sd / 2 - 1);
  11012. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  11013. curA += incA;
  11014. for (var i = 1; i < (sd / 2); i++) {
  11015. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  11016. this._storeIndex(ib, ibi, i * 3 + 0, c);
  11017. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  11018. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  11019. curA += incA;
  11020. }
  11021. }
  11022. break;
  11023. }
  11024. case Lines2D.SquareAnchorCap:
  11025. {
  11026. var vi = 0;
  11027. var c = borderMode ? null : contour;
  11028. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  11029. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  11030. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  11031. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  11032. if (borderMode) {
  11033. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  11034. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  11035. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  11036. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  11037. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  11038. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  11039. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  11040. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  11041. var ii = 0;
  11042. this._storeIndex(ib, ibi, ii++, v6);
  11043. this._storeIndex(ib, ibi, ii++, v1);
  11044. this._storeIndex(ib, ibi, ii++, v5);
  11045. this._storeIndex(ib, ibi, ii++, v6);
  11046. this._storeIndex(ib, ibi, ii++, v7);
  11047. this._storeIndex(ib, ibi, ii++, v1);
  11048. this._storeIndex(ib, ibi, ii++, v1);
  11049. this._storeIndex(ib, ibi, ii++, v7);
  11050. this._storeIndex(ib, ibi, ii++, v8);
  11051. this._storeIndex(ib, ibi, ii++, v1);
  11052. this._storeIndex(ib, ibi, ii++, v8);
  11053. this._storeIndex(ib, ibi, ii++, v2);
  11054. this._storeIndex(ib, ibi, ii++, v2);
  11055. this._storeIndex(ib, ibi, ii++, v8);
  11056. this._storeIndex(ib, ibi, ii++, v9);
  11057. this._storeIndex(ib, ibi, ii++, v2);
  11058. this._storeIndex(ib, ibi, ii++, v9);
  11059. this._storeIndex(ib, ibi, ii++, v3);
  11060. this._storeIndex(ib, ibi, ii++, v3);
  11061. this._storeIndex(ib, ibi, ii++, v9);
  11062. this._storeIndex(ib, ibi, ii++, v10);
  11063. this._storeIndex(ib, ibi, ii++, v3);
  11064. this._storeIndex(ib, ibi, ii++, v10);
  11065. this._storeIndex(ib, ibi, ii++, v4);
  11066. this._storeIndex(ib, ibi, ii++, v10);
  11067. this._storeIndex(ib, ibi, ii++, v11);
  11068. this._storeIndex(ib, ibi, ii++, v4);
  11069. this._storeIndex(ib, ibi, ii++, v11);
  11070. this._storeIndex(ib, ibi, ii++, v12);
  11071. this._storeIndex(ib, ibi, ii++, v4);
  11072. }
  11073. else {
  11074. this._storeIndex(ib, ibi, 0, v1);
  11075. this._storeIndex(ib, ibi, 1, v2);
  11076. this._storeIndex(ib, ibi, 2, v3);
  11077. this._storeIndex(ib, ibi, 3, v1);
  11078. this._storeIndex(ib, ibi, 4, v3);
  11079. this._storeIndex(ib, ibi, 5, v4);
  11080. }
  11081. break;
  11082. }
  11083. case Lines2D.RoundAnchorCap:
  11084. {
  11085. var cpos = Math.sqrt(t * t - ht * ht);
  11086. var center = new BABYLON.Vector2(cpos, 0);
  11087. var curA = BABYLON.Tools.ToRadians(-150);
  11088. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  11089. if (borderMode) {
  11090. var ii = 0;
  11091. for (var i = 0; i < sd; i++) {
  11092. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  11093. 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);
  11094. if (i > 0) {
  11095. this._storeIndex(ib, ibi, ii++, v1 - 2);
  11096. this._storeIndex(ib, ibi, ii++, v2 - 2);
  11097. this._storeIndex(ib, ibi, ii++, v2);
  11098. this._storeIndex(ib, ibi, ii++, v1 - 2);
  11099. this._storeIndex(ib, ibi, ii++, v2);
  11100. this._storeIndex(ib, ibi, ii++, v1);
  11101. }
  11102. curA += incA;
  11103. }
  11104. }
  11105. else {
  11106. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  11107. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  11108. curA += incA;
  11109. for (var i = 1; i < sd; i++) {
  11110. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  11111. this._storeIndex(ib, ibi, i * 3 + 0, c);
  11112. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  11113. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  11114. curA += incA;
  11115. }
  11116. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  11117. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  11118. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  11119. }
  11120. break;
  11121. }
  11122. case Lines2D.DiamondAnchorCap:
  11123. {
  11124. var vi = 0;
  11125. var c = borderMode ? null : contour;
  11126. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  11127. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  11128. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  11129. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  11130. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  11131. if (borderMode) {
  11132. var f = Math.sqrt(bt * bt * 2);
  11133. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  11134. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  11135. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  11136. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  11137. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  11138. var ii = 0;
  11139. this._storeIndex(ib, ibi, ii++, v6);
  11140. this._storeIndex(ib, ibi, ii++, v7);
  11141. this._storeIndex(ib, ibi, ii++, v1);
  11142. this._storeIndex(ib, ibi, ii++, v1);
  11143. this._storeIndex(ib, ibi, ii++, v7);
  11144. this._storeIndex(ib, ibi, ii++, v2);
  11145. this._storeIndex(ib, ibi, ii++, v2);
  11146. this._storeIndex(ib, ibi, ii++, v7);
  11147. this._storeIndex(ib, ibi, ii++, v8);
  11148. this._storeIndex(ib, ibi, ii++, v2);
  11149. this._storeIndex(ib, ibi, ii++, v8);
  11150. this._storeIndex(ib, ibi, ii++, v3);
  11151. this._storeIndex(ib, ibi, ii++, v3);
  11152. this._storeIndex(ib, ibi, ii++, v8);
  11153. this._storeIndex(ib, ibi, ii++, v9);
  11154. this._storeIndex(ib, ibi, ii++, v3);
  11155. this._storeIndex(ib, ibi, ii++, v9);
  11156. this._storeIndex(ib, ibi, ii++, v4);
  11157. this._storeIndex(ib, ibi, ii++, v4);
  11158. this._storeIndex(ib, ibi, ii++, v9);
  11159. this._storeIndex(ib, ibi, ii++, v10);
  11160. this._storeIndex(ib, ibi, ii++, v4);
  11161. this._storeIndex(ib, ibi, ii++, v10);
  11162. this._storeIndex(ib, ibi, ii++, v5);
  11163. }
  11164. else {
  11165. this._storeIndex(ib, ibi, 0, v1);
  11166. this._storeIndex(ib, ibi, 1, v2);
  11167. this._storeIndex(ib, ibi, 2, v3);
  11168. this._storeIndex(ib, ibi, 3, v1);
  11169. this._storeIndex(ib, ibi, 4, v3);
  11170. this._storeIndex(ib, ibi, 5, v5);
  11171. this._storeIndex(ib, ibi, 6, v5);
  11172. this._storeIndex(ib, ibi, 7, v3);
  11173. this._storeIndex(ib, ibi, 8, v4);
  11174. }
  11175. break;
  11176. }
  11177. }
  11178. return null;
  11179. };
  11180. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  11181. var lineA = BABYLON.Vector2.Zero();
  11182. var lineB = BABYLON.Vector2.Zero();
  11183. var tangent = BABYLON.Vector2.Zero();
  11184. var miter = BABYLON.Vector2.Zero();
  11185. var curNormal = null;
  11186. if (this.closed) {
  11187. this.points.push(this.points[0]);
  11188. }
  11189. var total = this.points.length;
  11190. for (var i = 1; i < total; i++) {
  11191. var last = this.points[i - 1];
  11192. var cur = this.points[i];
  11193. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  11194. this._direction(cur, last, lineA);
  11195. if (!curNormal) {
  11196. curNormal = BABYLON.Vector2.Zero();
  11197. this._perp(lineA, curNormal);
  11198. }
  11199. if (i === 1) {
  11200. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  11201. }
  11202. if (!next) {
  11203. this._perp(lineA, curNormal);
  11204. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  11205. }
  11206. else {
  11207. this._direction(next, cur, lineB);
  11208. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  11209. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  11210. }
  11211. }
  11212. if (this.points.length > 2 && this.closed) {
  11213. var last2 = this.points[total - 2];
  11214. var cur2 = this.points[0];
  11215. var next2 = this.points[1];
  11216. this._direction(cur2, last2, lineA);
  11217. this._direction(next2, cur2, lineB);
  11218. this._perp(lineA, curNormal);
  11219. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  11220. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  11221. // Patch contour
  11222. if (contour) {
  11223. var off = (bt == null) ? 0 : 4;
  11224. contour[0].x = vb[off + 0];
  11225. contour[0].y = vb[off + 1];
  11226. contour[1].x = vb[off + 2];
  11227. contour[1].y = vb[off + 3];
  11228. }
  11229. }
  11230. // Remove the point we added at the beginning
  11231. if (this.closed) {
  11232. this.points.splice(total - 1);
  11233. }
  11234. };
  11235. // Methods for Lines building
  11236. ///////////////////////////////////////////////////////////////////////////////////
  11237. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  11238. var renderCache = modelRenderCache;
  11239. var engine = this.owner.engine;
  11240. if (this._fillVB === null) {
  11241. this._computeLines2D();
  11242. }
  11243. // Need to create WebGL resources for fill part?
  11244. if (this.fill) {
  11245. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  11246. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  11247. renderCache.fillIndicesCount = this._fillIB.length;
  11248. // 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
  11249. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  11250. if (ei) {
  11251. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11252. }
  11253. // Get the non instanced version
  11254. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  11255. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  11256. }
  11257. // Need to create WebGL resources for border part?
  11258. if (this.border) {
  11259. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  11260. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  11261. renderCache.borderIndicesCount = this._borderIB.length;
  11262. // 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
  11263. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  11264. if (ei) {
  11265. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  11266. }
  11267. // Get the non instanced version
  11268. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  11269. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  11270. }
  11271. this._fillVB = null;
  11272. this._fillIB = null;
  11273. this._borderVB = null;
  11274. this._borderIB = null;
  11275. return renderCache;
  11276. };
  11277. Lines2D.prototype._computeLines2D = function () {
  11278. // Init min/max because their being computed here
  11279. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  11280. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  11281. var contour = new Array();
  11282. var startCapContour = new Array();
  11283. var endCapContour = new Array();
  11284. // Need to create WebGL resources for fill part?
  11285. if (this.fill) {
  11286. var startCapInfo = this._getCapSize(this.startCap);
  11287. var endCapInfo = this._getCapSize(this.endCap);
  11288. var count = this.points.length;
  11289. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  11290. this._fillVB = new Float32Array(vbSize);
  11291. var vb = this._fillVB;
  11292. var ht = this.fillThickness / 2;
  11293. var total = this.points.length;
  11294. this._buildLine(vb, this.border ? null : contour, ht);
  11295. var max = total * 2;
  11296. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  11297. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  11298. var ib = this._fillIB;
  11299. for (var i = 0; i < triCount; i += 2) {
  11300. ib[i * 3 + 0] = i + 0;
  11301. ib[i * 3 + 1] = i + 1;
  11302. ib[i * 3 + 2] = (i + 2) % max;
  11303. ib[i * 3 + 3] = i + 1;
  11304. ib[i * 3 + 4] = (i + 3) % max;
  11305. ib[i * 3 + 5] = (i + 2) % max;
  11306. }
  11307. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  11308. this._buildCap(vb, (count * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, null, this.endCap, Lines2D._endDir, this.border ? null : startCapContour);
  11309. }
  11310. // Need to create WebGL resources for border part?
  11311. if (this.border) {
  11312. var startCapInfo = this._getCapSize(this.startCap, true);
  11313. var endCapInfo = this._getCapSize(this.endCap, true);
  11314. var count = this.points.length;
  11315. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  11316. this._borderVB = new Float32Array(vbSize);
  11317. var vb = this._borderVB;
  11318. var ht = this.fillThickness / 2;
  11319. var bt = this.borderThickness;
  11320. var total = this.points.length;
  11321. this._buildLine(vb, contour, ht, bt);
  11322. var max = total * 2 * 2;
  11323. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  11324. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  11325. var ib = this._borderIB;
  11326. for (var i = 0; i < triCount; i += 4) {
  11327. ib[i * 3 + 0] = i + 0;
  11328. ib[i * 3 + 1] = i + 2;
  11329. ib[i * 3 + 2] = (i + 6) % max;
  11330. ib[i * 3 + 3] = i + 0;
  11331. ib[i * 3 + 4] = (i + 6) % max;
  11332. ib[i * 3 + 5] = (i + 4) % max;
  11333. ib[i * 3 + 6] = i + 3;
  11334. ib[i * 3 + 7] = i + 1;
  11335. ib[i * 3 + 8] = (i + 5) % max;
  11336. ib[i * 3 + 9] = i + 3;
  11337. ib[i * 3 + 10] = (i + 5) % max;
  11338. ib[i * 3 + 11] = (i + 7) % max;
  11339. }
  11340. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  11341. 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._endDir, endCapContour);
  11342. }
  11343. this._contour = contour;
  11344. if (startCapContour.length > 0) {
  11345. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  11346. this._startCapTriIndices = startCapTri;
  11347. this._startCapContour = startCapContour;
  11348. }
  11349. else {
  11350. this._startCapTriIndices = null;
  11351. this._startCapContour = null;
  11352. }
  11353. if (endCapContour.length > 0) {
  11354. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  11355. this._endCapContour = endCapContour;
  11356. this._endCapTriIndices = endCapTri;
  11357. }
  11358. else {
  11359. this._endCapContour = null;
  11360. this._endCapTriIndices = null;
  11361. }
  11362. var bs = this._boundingMax.subtract(this._boundingMin);
  11363. this._size.width = bs.x;
  11364. this._size.height = bs.y;
  11365. };
  11366. Object.defineProperty(Lines2D.prototype, "size", {
  11367. get: function () {
  11368. if (this._size == null) {
  11369. this._computeLines2D();
  11370. }
  11371. return this._size;
  11372. },
  11373. enumerable: true,
  11374. configurable: true
  11375. });
  11376. Lines2D.prototype.createInstanceDataParts = function () {
  11377. var res = new Array();
  11378. if (this.border) {
  11379. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  11380. }
  11381. if (this.fill) {
  11382. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  11383. }
  11384. return res;
  11385. };
  11386. Lines2D.prototype.applyActualScaleOnTransform = function () {
  11387. return true;
  11388. };
  11389. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  11390. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  11391. return false;
  11392. }
  11393. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  11394. var d = part;
  11395. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  11396. d.boundingMin = this.boundingMin;
  11397. d.boundingMax = this.boundingMax;
  11398. }
  11399. }
  11400. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  11401. var d = part;
  11402. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  11403. d.boundingMin = this.boundingMin;
  11404. d.boundingMax = this.boundingMax;
  11405. }
  11406. }
  11407. return true;
  11408. };
  11409. Lines2D._prevA = BABYLON.Vector2.Zero();
  11410. Lines2D._prevB = BABYLON.Vector2.Zero();
  11411. Lines2D._curA = BABYLON.Vector2.Zero();
  11412. Lines2D._curB = BABYLON.Vector2.Zero();
  11413. Lines2D._miterTps = BABYLON.Vector2.Zero();
  11414. Lines2D._startDir = BABYLON.Vector2.Zero();
  11415. Lines2D._endDir = BABYLON.Vector2.Zero();
  11416. Lines2D._tpsV = BABYLON.Vector2.Zero();
  11417. Lines2D._noCap = 0;
  11418. Lines2D._roundCap = 1;
  11419. Lines2D._triangleCap = 2;
  11420. Lines2D._squareAnchorCap = 3;
  11421. Lines2D._roundAnchorCap = 4;
  11422. Lines2D._diamondAnchorCap = 5;
  11423. Lines2D._arrowCap = 6;
  11424. Lines2D._roundCapSubDiv = 36;
  11425. __decorate([
  11426. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  11427. ], Lines2D.prototype, "points", null);
  11428. __decorate([
  11429. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  11430. ], Lines2D.prototype, "fillThickness", null);
  11431. __decorate([
  11432. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  11433. ], Lines2D.prototype, "closed", null);
  11434. __decorate([
  11435. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  11436. ], Lines2D.prototype, "startCap", null);
  11437. __decorate([
  11438. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  11439. ], Lines2D.prototype, "endCap", null);
  11440. Lines2D = __decorate([
  11441. BABYLON.className("Lines2D", "BABYLON")
  11442. ], Lines2D);
  11443. return Lines2D;
  11444. }(BABYLON.Shape2D));
  11445. BABYLON.Lines2D = Lines2D;
  11446. })(BABYLON || (BABYLON = {}));
  11447. var BABYLON;
  11448. (function (BABYLON) {
  11449. // This class contains data that lifetime is bounding to the Babylon Engine object
  11450. var Canvas2DEngineBoundData = (function () {
  11451. function Canvas2DEngineBoundData() {
  11452. this._modelCache = new BABYLON.StringDictionary();
  11453. }
  11454. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  11455. return this._modelCache.getOrAddWithFactory(key, factory);
  11456. };
  11457. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  11458. if (!modelRenderCache.isDisposed) {
  11459. return false;
  11460. }
  11461. this._modelCache.remove(modelRenderCache.modelKey);
  11462. return true;
  11463. };
  11464. return Canvas2DEngineBoundData;
  11465. }());
  11466. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  11467. var Canvas2D = (function (_super) {
  11468. __extends(Canvas2D, _super);
  11469. function Canvas2D(scene, settings) {
  11470. var _this = this;
  11471. _super.call(this, settings);
  11472. /**
  11473. * 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.
  11474. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  11475. */
  11476. this.worldSpaceToNodeLocal = function (worldPos) {
  11477. var node = _this._worldSpaceNode;
  11478. if (!node) {
  11479. return;
  11480. }
  11481. var mtx = node.getWorldMatrix().clone();
  11482. mtx.invert();
  11483. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  11484. var res = new BABYLON.Vector2(v.x, v.y);
  11485. var size = _this.actualSize;
  11486. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  11487. res.y += size.height * 0.5;
  11488. return res;
  11489. };
  11490. /**
  11491. * 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
  11492. */
  11493. this.worldSpaceCacheChanged = function () {
  11494. var plane = _this.worldSpaceCanvasNode;
  11495. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  11496. vd.uvs = new Float32Array(8);
  11497. var material = plane.material;
  11498. var tex = _this._renderableData._cacheTexture;
  11499. if (material.diffuseTexture !== tex) {
  11500. material.diffuseTexture = tex;
  11501. tex.hasAlpha = true;
  11502. }
  11503. var nodeuv = _this._renderableData._cacheNodeUVs;
  11504. for (var i = 0; i < 4; i++) {
  11505. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  11506. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  11507. }
  11508. vd.applyToMesh(plane);
  11509. };
  11510. this._notifDebugMode = false;
  11511. /**
  11512. * Instanced Array will be create if there's at least this number of parts/prim that can fit into it
  11513. */
  11514. this.minPartCountToUseInstancedArray = 5;
  11515. this._mapCounter = 0;
  11516. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  11517. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  11518. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  11519. this._groupRenderCounter = new BABYLON.PerfCounter();
  11520. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  11521. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  11522. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  11523. this._updateLayoutCounter = new BABYLON.PerfCounter();
  11524. this._updatePositioningCounter = new BABYLON.PerfCounter();
  11525. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  11526. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  11527. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  11528. this._uid = null;
  11529. this._cachedCanvasGroup = null;
  11530. this._renderingGroupObserver = null;
  11531. this._beforeRenderObserver = null;
  11532. this._afterRenderObserver = null;
  11533. this._profileInfoText = null;
  11534. BABYLON.Prim2DBase._isCanvasInit = false;
  11535. if (!settings) {
  11536. settings = {};
  11537. }
  11538. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  11539. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  11540. this._background.zOrder = 1.0;
  11541. this._background.isPickable = false;
  11542. this._background.origin = BABYLON.Vector2.Zero();
  11543. this._background.levelVisible = false;
  11544. if (settings.backgroundRoundRadius != null) {
  11545. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  11546. }
  11547. if (settings.backgroundBorder != null) {
  11548. if (typeof (settings.backgroundBorder) === "string") {
  11549. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  11550. }
  11551. else {
  11552. this.backgroundBorder = settings.backgroundBorder;
  11553. }
  11554. }
  11555. if (settings.backgroundBorderThickNess != null) {
  11556. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  11557. }
  11558. if (settings.backgroundFill != null) {
  11559. if (typeof (settings.backgroundFill) === "string") {
  11560. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  11561. }
  11562. else {
  11563. this.backgroundFill = settings.backgroundFill;
  11564. }
  11565. }
  11566. // Put a handler to resize the background whenever the canvas is resizing
  11567. this.propertyChanged.add(function (e, s) {
  11568. if (e.propertyName === "size") {
  11569. _this._background.size = _this.size;
  11570. }
  11571. }, BABYLON.Group2D.sizeProperty.flagId);
  11572. this._background._patchHierarchy(this);
  11573. }
  11574. var engine = scene.getEngine();
  11575. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  11576. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  11577. this._capturedPointers = new BABYLON.StringDictionary();
  11578. this._pickStartingPosition = BABYLON.Vector2.Zero();
  11579. this._hierarchyLevelMaxSiblingCount = 50;
  11580. this._hierarchyDepth = 0;
  11581. this._zOrder = 0;
  11582. this._zMax = 1;
  11583. this._scene = scene;
  11584. this._engine = engine;
  11585. this._renderingSize = new BABYLON.Size(0, 0);
  11586. this._designSize = settings.designSize || null;
  11587. this._designUseHorizAxis = settings.designUseHorizAxis === true;
  11588. this._trackedGroups = new Array();
  11589. this._maxAdaptiveWorldSpaceCanvasSize = null;
  11590. this._groupCacheMaps = new BABYLON.StringDictionary();
  11591. this._patchHierarchy(this);
  11592. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  11593. this._fitRenderingDevice = !settings.size;
  11594. if (!settings.size) {
  11595. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  11596. }
  11597. // Register scene dispose to also dispose the canvas when it'll happens
  11598. scene.onDisposeObservable.add(function (d, s) {
  11599. _this.dispose();
  11600. });
  11601. if (this._isScreenSpace) {
  11602. if (settings.renderingPhase) {
  11603. if (!settings.renderingPhase.camera || settings.renderingPhase.renderingGroupID == null) {
  11604. throw Error("You have to specify a valid camera and renderingGroup");
  11605. }
  11606. this._renderingGroupObserver = this._scene.onRenderingGroupObservable.add(function (e, s) {
  11607. if ((_this._scene.activeCamera === settings.renderingPhase.camera) && (e.renderStage === BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT)) {
  11608. _this._engine.clear(null, false, true, true);
  11609. _this._render();
  11610. }
  11611. }, Math.pow(2, settings.renderingPhase.renderingGroupID));
  11612. }
  11613. else {
  11614. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  11615. _this._engine.clear(null, false, true, true);
  11616. _this._render();
  11617. });
  11618. }
  11619. }
  11620. else {
  11621. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  11622. _this._render();
  11623. });
  11624. }
  11625. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  11626. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  11627. this._setupInteraction(enableInteraction);
  11628. // Register this instance
  11629. Canvas2D._INSTANCES.push(this);
  11630. }
  11631. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  11632. get: function () {
  11633. return this._drawCallsOpaqueCounter;
  11634. },
  11635. enumerable: true,
  11636. configurable: true
  11637. });
  11638. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  11639. get: function () {
  11640. return this._drawCallsAlphaTestCounter;
  11641. },
  11642. enumerable: true,
  11643. configurable: true
  11644. });
  11645. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  11646. get: function () {
  11647. return this._drawCallsTransparentCounter;
  11648. },
  11649. enumerable: true,
  11650. configurable: true
  11651. });
  11652. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  11653. get: function () {
  11654. return this._groupRenderCounter;
  11655. },
  11656. enumerable: true,
  11657. configurable: true
  11658. });
  11659. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  11660. get: function () {
  11661. return this._updateTransparentDataCounter;
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  11667. get: function () {
  11668. return this._cachedGroupRenderCounter;
  11669. },
  11670. enumerable: true,
  11671. configurable: true
  11672. });
  11673. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  11674. get: function () {
  11675. return this._updateCachedStateCounter;
  11676. },
  11677. enumerable: true,
  11678. configurable: true
  11679. });
  11680. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  11681. get: function () {
  11682. return this._updateLayoutCounter;
  11683. },
  11684. enumerable: true,
  11685. configurable: true
  11686. });
  11687. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  11688. get: function () {
  11689. return this._updatePositioningCounter;
  11690. },
  11691. enumerable: true,
  11692. configurable: true
  11693. });
  11694. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  11695. get: function () {
  11696. return this._updateLocalTransformCounter;
  11697. },
  11698. enumerable: true,
  11699. configurable: true
  11700. });
  11701. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  11702. get: function () {
  11703. return this._updateGlobalTransformCounter;
  11704. },
  11705. enumerable: true,
  11706. configurable: true
  11707. });
  11708. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  11709. get: function () {
  11710. return this._boundingInfoRecomputeCounter;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Canvas2D, "instances", {
  11716. get: function () {
  11717. return Canvas2D._INSTANCES;
  11718. },
  11719. enumerable: true,
  11720. configurable: true
  11721. });
  11722. Canvas2D.prototype._canvasPreInit = function (settings) {
  11723. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  11724. this._cachingStrategy = cachingStrategy;
  11725. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  11726. };
  11727. Canvas2D.prototype._setupInteraction = function (enable) {
  11728. var _this = this;
  11729. // No change detection
  11730. if (enable === this._interactionEnabled) {
  11731. return;
  11732. }
  11733. // Set the new state
  11734. this._interactionEnabled = enable;
  11735. // ScreenSpace mode
  11736. if (this._isScreenSpace) {
  11737. // Disable interaction
  11738. if (!enable) {
  11739. if (this._scenePrePointerObserver) {
  11740. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  11741. this._scenePrePointerObserver = null;
  11742. }
  11743. return;
  11744. }
  11745. // Enable Interaction
  11746. // Register the observable
  11747. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  11748. if (_this.isVisible === false) {
  11749. return;
  11750. }
  11751. var hs = 1 / _this.engine.getHardwareScalingLevel();
  11752. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  11753. _this._handlePointerEventForInteraction(e, localPos, s);
  11754. });
  11755. }
  11756. else {
  11757. var scene = this.scene;
  11758. if (enable) {
  11759. scene.constantlyUpdateMeshUnderPointer = true;
  11760. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  11761. if (_this.isVisible === false) {
  11762. return;
  11763. }
  11764. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  11765. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  11766. _this._handlePointerEventForInteraction(e, localPos, s);
  11767. }
  11768. });
  11769. }
  11770. else {
  11771. if (this._scenePointerObserver) {
  11772. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  11773. this._scenePointerObserver = null;
  11774. }
  11775. }
  11776. }
  11777. };
  11778. /**
  11779. * Internal method, you should use the Prim2DBase version instead
  11780. */
  11781. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  11782. if (this.isPointerCaptured(pointerId)) {
  11783. return false;
  11784. }
  11785. // Try to capture the pointer on the HTML side
  11786. try {
  11787. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  11788. }
  11789. catch (e) {
  11790. }
  11791. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  11792. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  11793. this._capturedPointers.add(pointerId.toString(), primitive);
  11794. return true;
  11795. };
  11796. /**
  11797. * Internal method, you should use the Prim2DBase version instead
  11798. */
  11799. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  11800. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  11801. return false;
  11802. }
  11803. // Try to release the pointer on the HTML side
  11804. try {
  11805. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  11806. }
  11807. catch (e) {
  11808. }
  11809. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  11810. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  11811. this._capturedPointers.remove(pointerId.toString());
  11812. return true;
  11813. };
  11814. /**
  11815. * Determine if the given pointer is captured or not
  11816. * @param pointerId the Id of the pointer
  11817. * @return true if it's captured, false otherwise
  11818. */
  11819. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  11820. return this._capturedPointers.contains(pointerId.toString());
  11821. };
  11822. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  11823. // Avoid unnecessary lookup
  11824. if (this._capturedPointers.count === 0) {
  11825. return null;
  11826. }
  11827. return this._capturedPointers.get(pointerId.toString());
  11828. };
  11829. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  11830. // Dispose check
  11831. if (this.isDisposed) {
  11832. return;
  11833. }
  11834. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  11835. if (!this._updatePointerInfo(eventData, localPosition)) {
  11836. return;
  11837. }
  11838. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  11839. // 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.
  11840. // 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.
  11841. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null, true);
  11842. // 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
  11843. this._updateOverStatus(true);
  11844. // Check if we have nothing to raise
  11845. if (!this._actualOverPrimitive && !capturedPrim) {
  11846. return;
  11847. }
  11848. // Update the relatedTarget info with the over primitive or the captured one (if any)
  11849. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  11850. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  11851. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  11852. // Analyze the pointer event type and fire proper events on the primitive
  11853. var skip = false;
  11854. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  11855. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData);
  11856. }
  11857. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  11858. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData);
  11859. }
  11860. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  11861. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData);
  11862. }
  11863. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  11864. skip = !this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData);
  11865. }
  11866. eventState.skipNextObservers = skip;
  11867. };
  11868. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  11869. var s = this.scale;
  11870. var pii = this._primPointerInfo;
  11871. if (!pii.canvasPointerPos) {
  11872. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  11873. }
  11874. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  11875. if (!camera || !camera.viewport) {
  11876. return false;
  11877. }
  11878. var engine = this._scene.getEngine();
  11879. if (this._isScreenSpace) {
  11880. var cameraViewport = camera.viewport;
  11881. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  11882. // Moving coordinates to local viewport world
  11883. var x = localPosition.x - viewport.x;
  11884. var y = localPosition.y - viewport.y;
  11885. pii.canvasPointerPos.x = (x - this.actualPosition.x) / s;
  11886. pii.canvasPointerPos.y = (engine.getRenderHeight() - y - this.actualPosition.y) / s;
  11887. }
  11888. else {
  11889. pii.canvasPointerPos.x = localPosition.x / s;
  11890. pii.canvasPointerPos.y = localPosition.y / s;
  11891. }
  11892. //console.log(`UpdatePointerInfo for ${this.id}, X:${pii.canvasPointerPos.x}, Y:${pii.canvasPointerPos.y}`);
  11893. pii.mouseWheelDelta = 0;
  11894. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  11895. var event = eventData.event;
  11896. if (event.wheelDelta) {
  11897. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  11898. }
  11899. else if (event.detail) {
  11900. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  11901. }
  11902. }
  11903. else {
  11904. var pe = eventData.event;
  11905. pii.ctrlKey = pe.ctrlKey;
  11906. pii.altKey = pe.altKey;
  11907. pii.shiftKey = pe.shiftKey;
  11908. pii.metaKey = pe.metaKey;
  11909. pii.button = pe.button;
  11910. pii.buttons = pe.buttons;
  11911. pii.pointerId = pe.pointerId;
  11912. pii.width = pe.width;
  11913. pii.height = pe.height;
  11914. pii.presssure = pe.pressure;
  11915. pii.tilt.x = pe.tiltX;
  11916. pii.tilt.y = pe.tiltY;
  11917. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  11918. }
  11919. return true;
  11920. };
  11921. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture, force) {
  11922. if (!force && (this.scene.getRenderId() === this._intersectionRenderId)) {
  11923. return;
  11924. }
  11925. // 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
  11926. if (!this._globalTransform) {
  11927. this.updateCachedStates(true);
  11928. }
  11929. var ii = Canvas2D._interInfo;
  11930. ii.pickPosition.x = mouseLocalPos.x;
  11931. ii.pickPosition.y = mouseLocalPos.y;
  11932. ii.findFirstOnly = false;
  11933. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  11934. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  11935. // Reset intersection info as we don't hit anything
  11936. ii.intersectedPrimitives = new Array();
  11937. ii.topMostIntersectedPrimitive = null;
  11938. }
  11939. else {
  11940. // The pointer is inside the Canvas, do an intersection test
  11941. this.intersect(ii);
  11942. }
  11943. {
  11944. // Update prev/actual intersection info, fire "overPrim" property change if needed
  11945. this._previousIntersectionList = this._actualIntersectionList;
  11946. this._actualIntersectionList = ii.intersectedPrimitives;
  11947. this._previousOverPrimitive = this._actualOverPrimitive;
  11948. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  11949. var prev = (this._previousOverPrimitive != null) ? this._previousOverPrimitive.prim : null;
  11950. var actual = (this._actualOverPrimitive != null) ? this._actualOverPrimitive.prim : null;
  11951. if (prev !== actual) {
  11952. this.onPropertyChanged("overPrim", this._previousOverPrimitive ? this._previousOverPrimitive.prim : null, this._actualOverPrimitive ? this._actualOverPrimitive.prim : null);
  11953. }
  11954. }
  11955. this._intersectionRenderId = this.scene.getRenderId();
  11956. };
  11957. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  11958. Canvas2D.prototype._updateOverStatus = function (force) {
  11959. if ((!force && (this.scene.getRenderId() === this._hoverStatusRenderId)) || !this._previousIntersectionList || !this._actualIntersectionList) {
  11960. return;
  11961. }
  11962. // Detect a change of over
  11963. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  11964. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  11965. if (prevPrim !== actualPrim) {
  11966. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  11967. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  11968. // Notify the previous "over" prim that the pointer is no longer over it
  11969. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  11970. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  11971. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  11972. }
  11973. // Notify the new "over" prim that the pointer is over it
  11974. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  11975. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  11976. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  11977. }
  11978. }
  11979. this._hoverStatusRenderId = this.scene.getRenderId();
  11980. };
  11981. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  11982. if (this._primPointerInfo.isCaptured) {
  11983. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  11984. }
  11985. else {
  11986. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  11987. var pii = _a[_i];
  11988. if (pii.prim === prim) {
  11989. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  11990. return;
  11991. }
  11992. }
  11993. }
  11994. };
  11995. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  11996. if (!this._notifDebugMode) {
  11997. return;
  11998. }
  11999. var debug = "";
  12000. for (var i = 0; i < prim.hierarchyDepth; i++) {
  12001. debug += " ";
  12002. }
  12003. var pii = this._primPointerInfo;
  12004. 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();
  12005. console.log(debug);
  12006. };
  12007. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  12008. var ppi = this._primPointerInfo;
  12009. var event = eventData ? eventData.event : null;
  12010. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  12011. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  12012. this._notifParents(prim, mask);
  12013. }
  12014. var bubbleCancelled = false;
  12015. var cur = prim;
  12016. while (cur) {
  12017. // Only trigger the observers if the primitive is intersected (except for out)
  12018. if (!bubbleCancelled) {
  12019. this._updatePrimPointerPos(cur);
  12020. // Exec the observers
  12021. this._debugExecObserver(cur, mask);
  12022. if (!cur._pointerEventObservable.notifyObservers(ppi, mask) && eventData instanceof BABYLON.PointerInfoPre) {
  12023. eventData.skipOnPointerObservable = true;
  12024. return false;
  12025. }
  12026. this._triggerActionManager(cur, ppi, mask, event);
  12027. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  12028. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  12029. if (ppi.cancelBubble) {
  12030. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  12031. return false;
  12032. }
  12033. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  12034. bubbleCancelled = true;
  12035. }
  12036. }
  12037. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  12038. if (bubbleCancelled) {
  12039. this._updatePrimPointerPos(cur);
  12040. }
  12041. // NOTE TO MYSELF, this is commented right now because it doesn't seemed needed but I can't figure out why I put this code in the first place
  12042. //// Trigger a PointerEnter corresponding to the PointerOver
  12043. //if (mask === PrimitivePointerInfo.PointerOver) {
  12044. // this._debugExecObserver(cur, PrimitivePointerInfo.PointerEnter);
  12045. // cur._pointerEventObservable.notifyObservers(ppi, PrimitivePointerInfo.PointerEnter);
  12046. //}
  12047. //// Trigger a PointerLeave corresponding to the PointerOut
  12048. //else if (mask === PrimitivePointerInfo.PointerOut) {
  12049. // this._debugExecObserver(cur, PrimitivePointerInfo.PointerLeave);
  12050. // cur._pointerEventObservable.notifyObservers(ppi, PrimitivePointerInfo.PointerLeave);
  12051. //}
  12052. // Loop to the parent
  12053. cur = cur.parent;
  12054. }
  12055. return true;
  12056. };
  12057. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  12058. var _this = this;
  12059. // 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
  12060. if (!this._globalTransform) {
  12061. this.updateCachedStates(true);
  12062. }
  12063. // Process Trigger related to PointerDown
  12064. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  12065. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  12066. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  12067. this._pickStartingTime = new Date().getTime();
  12068. this._pickedDownPrim = null;
  12069. if (prim.actionManager) {
  12070. this._pickedDownPrim = prim;
  12071. if (prim.actionManager.hasPickTriggers) {
  12072. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  12073. switch (eventData.button) {
  12074. case 0:
  12075. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  12076. break;
  12077. case 1:
  12078. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  12079. break;
  12080. case 2:
  12081. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  12082. break;
  12083. }
  12084. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  12085. }
  12086. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  12087. window.setTimeout(function () {
  12088. var ppi = _this._primPointerInfo;
  12089. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  12090. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null, true);
  12091. _this._updateOverStatus(false);
  12092. var ii = new BABYLON.IntersectInfo2D();
  12093. ii.pickPosition = ppi.canvasPointerPos.clone();
  12094. ii.findFirstOnly = false;
  12095. _this.intersect(ii);
  12096. if (ii.isPrimIntersected(prim) !== null) {
  12097. if (prim.actionManager) {
  12098. 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)) {
  12099. _this._pickStartingTime = 0;
  12100. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  12101. }
  12102. }
  12103. }
  12104. }, BABYLON.ActionManager.LongPressDelay);
  12105. }
  12106. }
  12107. }
  12108. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  12109. this._pickStartingTime = 0;
  12110. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  12111. if (prim.actionManager) {
  12112. // OnPickUpTrigger
  12113. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  12114. // OnPickTrigger
  12115. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  12116. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  12117. }
  12118. }
  12119. // OnPickOutTrigger
  12120. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  12121. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  12122. }
  12123. }
  12124. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  12125. if (prim.actionManager) {
  12126. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  12127. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  12128. }
  12129. }
  12130. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  12131. if (prim.actionManager) {
  12132. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  12133. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  12134. }
  12135. }
  12136. };
  12137. Canvas2D.prototype._notifParents = function (prim, mask) {
  12138. var pii = this._primPointerInfo;
  12139. var curPrim = this;
  12140. while (curPrim) {
  12141. this._updatePrimPointerPos(curPrim);
  12142. // Fire the proper notification
  12143. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  12144. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  12145. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  12146. }
  12147. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  12148. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  12149. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  12150. }
  12151. curPrim = curPrim.parent;
  12152. }
  12153. };
  12154. /**
  12155. * Don't forget to call the dispose method when you're done with the Canvas instance.
  12156. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  12157. */
  12158. Canvas2D.prototype.dispose = function () {
  12159. if (!_super.prototype.dispose.call(this)) {
  12160. return false;
  12161. }
  12162. if (this._profilingCanvas) {
  12163. this._profilingCanvas.dispose();
  12164. this._profilingCanvas = null;
  12165. }
  12166. if (this.interactionEnabled) {
  12167. this._setupInteraction(false);
  12168. }
  12169. if (this._renderingGroupObserver) {
  12170. this._scene.onRenderingGroupObservable.remove(this._renderingGroupObserver);
  12171. this._renderingGroupObserver = null;
  12172. }
  12173. if (this._beforeRenderObserver) {
  12174. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  12175. this._beforeRenderObserver = null;
  12176. }
  12177. if (this._afterRenderObserver) {
  12178. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  12179. this._afterRenderObserver = null;
  12180. }
  12181. if (this._groupCacheMaps) {
  12182. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  12183. this._groupCacheMaps = null;
  12184. }
  12185. // Unregister this instance
  12186. var index = Canvas2D._INSTANCES.indexOf(this);
  12187. if (index > -1) {
  12188. Canvas2D._INSTANCES.splice(index, 1);
  12189. }
  12190. };
  12191. Object.defineProperty(Canvas2D.prototype, "scene", {
  12192. /**
  12193. * Accessor to the Scene that owns the Canvas
  12194. * @returns The instance of the Scene object
  12195. */
  12196. get: function () {
  12197. return this._scene;
  12198. },
  12199. enumerable: true,
  12200. configurable: true
  12201. });
  12202. Object.defineProperty(Canvas2D.prototype, "engine", {
  12203. /**
  12204. * Accessor to the Engine that drives the Scene used by this Canvas
  12205. * @returns The instance of the Engine object
  12206. */
  12207. get: function () {
  12208. return this._engine;
  12209. },
  12210. enumerable: true,
  12211. configurable: true
  12212. });
  12213. Object.defineProperty(Canvas2D.prototype, "uid", {
  12214. /**
  12215. * return a unique identifier for the Canvas2D
  12216. */
  12217. get: function () {
  12218. if (!this._uid) {
  12219. this._uid = BABYLON.Tools.RandomId();
  12220. }
  12221. return this._uid;
  12222. },
  12223. enumerable: true,
  12224. configurable: true
  12225. });
  12226. Object.defineProperty(Canvas2D.prototype, "renderObservable", {
  12227. /**
  12228. * And observable called during the Canvas rendering process.
  12229. * This observable is called twice per render, each time with a different mask:
  12230. * - 1: before render is executed
  12231. * - 2: after render is executed
  12232. */
  12233. get: function () {
  12234. if (!this._renderObservable) {
  12235. this._renderObservable = new BABYLON.Observable();
  12236. }
  12237. return this._renderObservable;
  12238. },
  12239. enumerable: true,
  12240. configurable: true
  12241. });
  12242. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  12243. /**
  12244. * Accessor of the Caching Strategy used by this Canvas.
  12245. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  12246. * @returns the value corresponding to the used strategy.
  12247. */
  12248. get: function () {
  12249. return this._cachingStrategy;
  12250. },
  12251. enumerable: true,
  12252. configurable: true
  12253. });
  12254. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  12255. /**
  12256. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  12257. * @returns {}
  12258. */
  12259. get: function () {
  12260. return this._isScreenSpace;
  12261. },
  12262. enumerable: true,
  12263. configurable: true
  12264. });
  12265. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  12266. /**
  12267. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  12268. */
  12269. get: function () {
  12270. return this._worldSpaceNode;
  12271. },
  12272. set: function (val) {
  12273. this._worldSpaceNode = val;
  12274. },
  12275. enumerable: true,
  12276. configurable: true
  12277. });
  12278. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  12279. /**
  12280. * Check if the WebGL Instanced Array extension is supported or not
  12281. */
  12282. get: function () {
  12283. return this._supprtInstancedArray;
  12284. },
  12285. enumerable: true,
  12286. configurable: true
  12287. });
  12288. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  12289. /**
  12290. * Property that defines the fill object used to draw the background of the Canvas.
  12291. * Note that Canvas with a Caching Strategy of
  12292. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  12293. */
  12294. get: function () {
  12295. if (!this._background || !this._background.isVisible) {
  12296. return null;
  12297. }
  12298. return this._background.fill;
  12299. },
  12300. set: function (value) {
  12301. this.checkBackgroundAvailability();
  12302. if (value === this._background.fill) {
  12303. return;
  12304. }
  12305. this._background.fill = value;
  12306. this._background.levelVisible = true;
  12307. },
  12308. enumerable: true,
  12309. configurable: true
  12310. });
  12311. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  12312. /**
  12313. * Property that defines the border object used to draw the background of the Canvas.
  12314. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  12315. */
  12316. get: function () {
  12317. if (!this._background || !this._background.isVisible) {
  12318. return null;
  12319. }
  12320. return this._background.border;
  12321. },
  12322. set: function (value) {
  12323. this.checkBackgroundAvailability();
  12324. if (value === this._background.border) {
  12325. return;
  12326. }
  12327. this._background.border = value;
  12328. this._background.levelVisible = true;
  12329. },
  12330. enumerable: true,
  12331. configurable: true
  12332. });
  12333. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  12334. /**
  12335. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  12336. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  12337. */
  12338. get: function () {
  12339. if (!this._background || !this._background.isVisible) {
  12340. return null;
  12341. }
  12342. return this._background.borderThickness;
  12343. },
  12344. set: function (value) {
  12345. this.checkBackgroundAvailability();
  12346. if (value === this._background.borderThickness) {
  12347. return;
  12348. }
  12349. this._background.borderThickness = value;
  12350. },
  12351. enumerable: true,
  12352. configurable: true
  12353. });
  12354. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  12355. /**
  12356. * You can set the roundRadius of the background
  12357. * @returns The current roundRadius
  12358. */
  12359. get: function () {
  12360. if (!this._background || !this._background.isVisible) {
  12361. return null;
  12362. }
  12363. return this._background.roundRadius;
  12364. },
  12365. set: function (value) {
  12366. this.checkBackgroundAvailability();
  12367. if (value === this._background.roundRadius) {
  12368. return;
  12369. }
  12370. this._background.roundRadius = value;
  12371. this._background.levelVisible = true;
  12372. },
  12373. enumerable: true,
  12374. configurable: true
  12375. });
  12376. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  12377. /**
  12378. * Enable/Disable interaction for this Canvas
  12379. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  12380. */
  12381. get: function () {
  12382. return this._interactionEnabled;
  12383. },
  12384. set: function (enable) {
  12385. this._setupInteraction(enable);
  12386. },
  12387. enumerable: true,
  12388. configurable: true
  12389. });
  12390. Object.defineProperty(Canvas2D.prototype, "designSize", {
  12391. get: function () {
  12392. return this._designSize;
  12393. },
  12394. enumerable: true,
  12395. configurable: true
  12396. });
  12397. Object.defineProperty(Canvas2D.prototype, "designSizeUseHorizAxis", {
  12398. get: function () {
  12399. return this._designUseHorizAxis;
  12400. },
  12401. enumerable: true,
  12402. configurable: true
  12403. });
  12404. Object.defineProperty(Canvas2D.prototype, "overPrim", {
  12405. /**
  12406. * Return
  12407. */
  12408. get: function () {
  12409. return this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  12410. },
  12411. enumerable: true,
  12412. configurable: true
  12413. });
  12414. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  12415. /**
  12416. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  12417. * @returns {}
  12418. */
  12419. get: function () {
  12420. return this.__engineData;
  12421. },
  12422. enumerable: true,
  12423. configurable: true
  12424. });
  12425. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  12426. if (this._profilingCanvas) {
  12427. return this._profilingCanvas;
  12428. }
  12429. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  12430. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  12431. new BABYLON.Rectangle2D({
  12432. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  12433. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  12434. ]
  12435. })
  12436. ]
  12437. });
  12438. this._profileInfoText = canvas.findById("ProfileInfoText");
  12439. this._profilingCanvas = canvas;
  12440. return canvas;
  12441. };
  12442. Canvas2D.prototype.checkBackgroundAvailability = function () {
  12443. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  12444. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  12445. }
  12446. };
  12447. Canvas2D.prototype._initPerfMetrics = function () {
  12448. this._drawCallsOpaqueCounter.fetchNewFrame();
  12449. this._drawCallsAlphaTestCounter.fetchNewFrame();
  12450. this._drawCallsTransparentCounter.fetchNewFrame();
  12451. this._groupRenderCounter.fetchNewFrame();
  12452. this._updateTransparentDataCounter.fetchNewFrame();
  12453. this._cachedGroupRenderCounter.fetchNewFrame();
  12454. this._updateCachedStateCounter.fetchNewFrame();
  12455. this._updateLayoutCounter.fetchNewFrame();
  12456. this._updatePositioningCounter.fetchNewFrame();
  12457. this._updateLocalTransformCounter.fetchNewFrame();
  12458. this._updateGlobalTransformCounter.fetchNewFrame();
  12459. this._boundingInfoRecomputeCounter.fetchNewFrame();
  12460. };
  12461. Canvas2D.prototype._fetchPerfMetrics = function () {
  12462. this._drawCallsOpaqueCounter.addCount(0, true);
  12463. this._drawCallsAlphaTestCounter.addCount(0, true);
  12464. this._drawCallsTransparentCounter.addCount(0, true);
  12465. this._groupRenderCounter.addCount(0, true);
  12466. this._updateTransparentDataCounter.addCount(0, true);
  12467. this._cachedGroupRenderCounter.addCount(0, true);
  12468. this._updateCachedStateCounter.addCount(0, true);
  12469. this._updateLayoutCounter.addCount(0, true);
  12470. this._updatePositioningCounter.addCount(0, true);
  12471. this._updateLocalTransformCounter.addCount(0, true);
  12472. this._updateGlobalTransformCounter.addCount(0, true);
  12473. this._boundingInfoRecomputeCounter.addCount(0, true);
  12474. };
  12475. Canvas2D.prototype._updateProfileCanvas = function () {
  12476. if (this._profileInfoText == null) {
  12477. return;
  12478. }
  12479. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  12480. var p = "Draw Calls:\n" +
  12481. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  12482. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  12483. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  12484. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  12485. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  12486. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  12487. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  12488. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  12489. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  12490. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  12491. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  12492. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  12493. this._profileInfoText.text = p;
  12494. };
  12495. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  12496. switch (renderMode) {
  12497. case BABYLON.Render2DContext.RenderModeOpaque:
  12498. this._drawCallsOpaqueCounter.addCount(count, false);
  12499. return;
  12500. case BABYLON.Render2DContext.RenderModeAlphaTest:
  12501. this._drawCallsAlphaTestCounter.addCount(count, false);
  12502. return;
  12503. case BABYLON.Render2DContext.RenderModeTransparent:
  12504. this._drawCallsTransparentCounter.addCount(count, false);
  12505. return;
  12506. }
  12507. };
  12508. Canvas2D.prototype._addGroupRenderCount = function (count) {
  12509. this._groupRenderCounter.addCount(count, false);
  12510. };
  12511. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  12512. this._updateTransparentDataCounter.addCount(count, false);
  12513. };
  12514. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  12515. this._cachedGroupRenderCounter.addCount(count, false);
  12516. };
  12517. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  12518. this._updateCachedStateCounter.addCount(count, false);
  12519. };
  12520. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  12521. this._updateLayoutCounter.addCount(count, false);
  12522. };
  12523. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  12524. this._updatePositioningCounter.addCount(count, false);
  12525. };
  12526. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  12527. this._updateLocalTransformCounter.addCount(count, false);
  12528. };
  12529. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  12530. this._updateGlobalTransformCounter.addCount(count, false);
  12531. };
  12532. Canvas2D.prototype._updateTrackedNodes = function () {
  12533. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  12534. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  12535. var rh = this.engine.getRenderHeight();
  12536. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  12537. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  12538. var group = _a[_i];
  12539. if (group.isDisposed || !group.isVisible) {
  12540. continue;
  12541. }
  12542. var node = group.trackedNode;
  12543. var worldMtx = node.getWorldMatrix();
  12544. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  12545. var s = this.scale;
  12546. group.x = Math.round(proj.x / s);
  12547. group.y = Math.round((rh - proj.y) / s);
  12548. }
  12549. };
  12550. /**
  12551. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  12552. */
  12553. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  12554. this._updateCanvasState(forceRecompute);
  12555. };
  12556. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  12557. if (this._globalTransformStep < 2) {
  12558. return;
  12559. }
  12560. var n = this.worldSpaceCanvasNode;
  12561. var bi = n.getBoundingInfo().boundingBox;
  12562. var v = bi.vectorsWorld;
  12563. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  12564. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  12565. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  12566. var projPoints = new Array(4);
  12567. for (var i = 0; i < 4; i++) {
  12568. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  12569. }
  12570. var left = projPoints[3].subtract(projPoints[0]).length();
  12571. var top = projPoints[3].subtract(projPoints[1]).length();
  12572. var right = projPoints[1].subtract(projPoints[2]).length();
  12573. var bottom = projPoints[2].subtract(projPoints[0]).length();
  12574. var w = Math.round(Math.max(top, bottom));
  12575. var h = Math.round(Math.max(right, left));
  12576. var isW = w > h;
  12577. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  12578. var edge = Math.max(w, h);
  12579. if (edge < 256) {
  12580. edge = 256;
  12581. }
  12582. else {
  12583. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  12584. }
  12585. // Clip values if needed
  12586. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  12587. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  12588. if (newScale !== this.scale) {
  12589. var scale = newScale;
  12590. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  12591. this._setRenderingScale(scale);
  12592. }
  12593. };
  12594. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  12595. // Check if the update has already been made for this render Frame
  12596. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  12597. return;
  12598. }
  12599. // Detect a change of rendering size
  12600. var renderingSizeChanged = false;
  12601. var newWidth = this.engine.getRenderWidth();
  12602. if (newWidth !== this._renderingSize.width) {
  12603. renderingSizeChanged = true;
  12604. }
  12605. this._renderingSize.width = newWidth;
  12606. var newHeight = this.engine.getRenderHeight();
  12607. if (newHeight !== this._renderingSize.height) {
  12608. renderingSizeChanged = true;
  12609. }
  12610. this._renderingSize.height = newHeight;
  12611. // If the canvas fit the rendering size and it changed, update
  12612. if (renderingSizeChanged && this._fitRenderingDevice) {
  12613. this._actualSize = this._renderingSize.clone();
  12614. this._size = this._renderingSize.clone();
  12615. if (this._background) {
  12616. this._background.size = this.size;
  12617. }
  12618. // Dirty the Layout at the Canvas level to recompute as the size changed
  12619. this._setLayoutDirty();
  12620. }
  12621. // If there's a design size, update the scale according to the renderingSize
  12622. if (this._designSize) {
  12623. var scale = void 0;
  12624. if (this._designUseHorizAxis) {
  12625. scale = this._renderingSize.width / this._designSize.width;
  12626. }
  12627. else {
  12628. scale = this._renderingSize.height / this._designSize.height;
  12629. }
  12630. this.size = this._designSize.clone();
  12631. this.actualSize = this._designSize.clone();
  12632. this.scale = scale;
  12633. }
  12634. var context = new BABYLON.PrepareRender2DContext();
  12635. ++this._globalTransformProcessStep;
  12636. this.updateCachedStates(false);
  12637. this._prepareGroupRender(context);
  12638. this._updateRenderId = this.scene.getRenderId();
  12639. };
  12640. /**
  12641. * Method that renders the Canvas, you should not invoke
  12642. */
  12643. Canvas2D.prototype._render = function () {
  12644. this._initPerfMetrics();
  12645. if (this._renderObservable && this._renderObservable.hasObservers()) {
  12646. this._renderObservable.notifyObservers(this, Canvas2D.RENDEROBSERVABLE_PRE);
  12647. }
  12648. this._updateCanvasState(false);
  12649. this._updateTrackedNodes();
  12650. // Nothing to do is the Canvas is not visible
  12651. if (this.isVisible === false) {
  12652. return;
  12653. }
  12654. if (!this._isScreenSpace) {
  12655. this._updateAdaptiveSizeWorldCanvas();
  12656. }
  12657. this._updateCanvasState(false);
  12658. if (this._primPointerInfo.canvasPointerPos) {
  12659. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false, false);
  12660. this._updateOverStatus(false);
  12661. }
  12662. this.engine.setState(false);
  12663. this._groupRender();
  12664. if (!this._isScreenSpace) {
  12665. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  12666. this.worldSpaceCacheChanged();
  12667. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  12668. }
  12669. }
  12670. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  12671. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  12672. this._cachedCanvasGroup._renderCachedCanvas();
  12673. }
  12674. this._fetchPerfMetrics();
  12675. this._updateProfileCanvas();
  12676. if (this._renderObservable && this._renderObservable.hasObservers()) {
  12677. this._renderObservable.notifyObservers(this, Canvas2D.RENDEROBSERVABLE_POST);
  12678. }
  12679. };
  12680. /**
  12681. * Internal method that allocate a cache for the given group.
  12682. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  12683. * @param group The group to allocate the cache of.
  12684. * @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.
  12685. */
  12686. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  12687. if (useMipMap === void 0) { useMipMap = false; }
  12688. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  12689. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  12690. var rd = group._renderableData;
  12691. var noResizeScale = rd._noResizeOnScale;
  12692. var isCanvas = parent == null;
  12693. var scale;
  12694. if (noResizeScale) {
  12695. scale = isCanvas ? Canvas2D._unS : group.parent.actualScale;
  12696. }
  12697. else {
  12698. scale = group.actualScale;
  12699. }
  12700. // Determine size
  12701. var size = group.actualSize;
  12702. size = new BABYLON.Size(Math.ceil(size.width * scale.x), Math.ceil(size.height * scale.y));
  12703. var originalSize = size.clone();
  12704. if (minSize) {
  12705. size.width = Math.max(minSize.width, size.width);
  12706. size.height = Math.max(minSize.height, size.height);
  12707. }
  12708. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  12709. // Try to find a spot in one of the cached texture
  12710. var res = null;
  12711. var map;
  12712. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  12713. var _map = mapArray_1[_i];
  12714. map = _map;
  12715. var node = map.allocateRect(size);
  12716. if (node) {
  12717. res = { node: node, texture: map };
  12718. break;
  12719. }
  12720. }
  12721. // Couldn't find a map that could fit the rect, create a new map for it
  12722. if (!res) {
  12723. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  12724. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  12725. if (size.width > mapSize.width || size.height > mapSize.height) {
  12726. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  12727. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  12728. }
  12729. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  12730. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  12731. map.hasAlpha = true;
  12732. map.anisotropicFilteringLevel = 4;
  12733. mapArray.splice(0, 0, map);
  12734. var node = map.allocateRect(size);
  12735. res = { node: node, texture: map };
  12736. }
  12737. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  12738. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  12739. if (group !== this || this._isScreenSpace) {
  12740. var node = res.node;
  12741. // 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
  12742. var sprite = void 0;
  12743. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  12744. if (this._cachedCanvasGroup) {
  12745. this._cachedCanvasGroup.dispose();
  12746. }
  12747. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  12748. sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: originalSize, spriteLocation: node.pos });
  12749. sprite.zOrder = 1;
  12750. sprite.origin = BABYLON.Vector2.Zero();
  12751. }
  12752. else {
  12753. sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x * scale.x, y: group.actualPosition.y * scale.y, spriteSize: originalSize, spriteLocation: node.pos, dontInheritParentScale: true });
  12754. sprite.origin = group.origin.clone();
  12755. sprite.addExternalData("__cachedGroup__", group);
  12756. sprite.pointerEventObservable.add(function (e, s) {
  12757. if (group.pointerEventObservable !== null) {
  12758. group.pointerEventObservable.notifyObservers(e, s.mask);
  12759. }
  12760. });
  12761. res.sprite = sprite;
  12762. }
  12763. if (sprite && noResizeScale) {
  12764. var relScale = isCanvas ? group.actualScale : group.actualScale.divide(group.parent.actualScale);
  12765. sprite.scaleX = relScale.x;
  12766. sprite.scaleY = relScale.y;
  12767. }
  12768. }
  12769. return res;
  12770. };
  12771. /**
  12772. * Internal method used to register a Scene Node to track position for the given group
  12773. * Do not invoke this method, for internal purpose only.
  12774. * @param group the group to track its associated Scene Node
  12775. */
  12776. Canvas2D.prototype._registerTrackedNode = function (group) {
  12777. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  12778. return;
  12779. }
  12780. this._trackedGroups.push(group);
  12781. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  12782. };
  12783. /**
  12784. * Internal method used to unregister a tracked Scene Node
  12785. * Do not invoke this method, it's for internal purpose only.
  12786. * @param group the group to unregister its tracked Scene Node from.
  12787. */
  12788. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  12789. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  12790. return;
  12791. }
  12792. var i = this._trackedGroups.indexOf(group);
  12793. if (i !== -1) {
  12794. this._trackedGroups.splice(i, 1);
  12795. }
  12796. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  12797. };
  12798. /**
  12799. * Get a Solid Color Brush instance matching the given color.
  12800. * @param color The color to retrieve
  12801. * @return A shared instance of the SolidColorBrush2D class that use the given color
  12802. */
  12803. Canvas2D.GetSolidColorBrush = function (color) {
  12804. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  12805. };
  12806. /**
  12807. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  12808. * @param color The color to retrieve
  12809. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  12810. */
  12811. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  12812. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  12813. };
  12814. /**
  12815. * Get a Gradient Color Brush
  12816. * @param color1 starting color
  12817. * @param color2 engine color
  12818. * @param translation translation vector to apply. default is [0;0]
  12819. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  12820. * @param scale scaling factor to apply. default is 1.
  12821. */
  12822. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  12823. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  12824. if (rotation === void 0) { rotation = 0; }
  12825. if (scale === void 0) { scale = 1; }
  12826. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  12827. };
  12828. /**
  12829. * Create a solid or gradient brush from a string value.
  12830. * @param brushString should be either
  12831. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  12832. * - "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.
  12833. */
  12834. Canvas2D.GetBrushFromString = function (brushString) {
  12835. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  12836. brushString = brushString.trim();
  12837. var split = brushString.split(",");
  12838. // Solid, formatted as: "[solid:]#FF808080"
  12839. if (split.length === 1) {
  12840. var value = null;
  12841. if (brushString.indexOf("solid:") === 0) {
  12842. value = brushString.substr(6).trim();
  12843. }
  12844. else if (brushString.indexOf("#") === 0) {
  12845. value = brushString;
  12846. }
  12847. else {
  12848. return null;
  12849. }
  12850. return Canvas2D.GetSolidColorBrushFromHex(value);
  12851. }
  12852. else {
  12853. if (split[0].indexOf("gradient:") === 0) {
  12854. split[0] = split[0].substr(9).trim();
  12855. }
  12856. try {
  12857. var start = BABYLON.Color4.FromHexString(split[0].trim());
  12858. var end = BABYLON.Color4.FromHexString(split[1].trim());
  12859. var t = BABYLON.Vector2.Zero();
  12860. if (split.length > 2) {
  12861. var v = split[2].trim();
  12862. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  12863. return null;
  12864. }
  12865. var sep = v.indexOf(":");
  12866. var x = parseFloat(v.substr(1, sep));
  12867. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  12868. t = new BABYLON.Vector2(x, y);
  12869. }
  12870. var r = 0;
  12871. if (split.length > 3) {
  12872. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  12873. }
  12874. var s = 1;
  12875. if (split.length > 4) {
  12876. s = parseFloat(split[4].trim());
  12877. }
  12878. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  12879. }
  12880. catch (e) {
  12881. return null;
  12882. }
  12883. }
  12884. };
  12885. /**
  12886. * 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.
  12887. * This strategy doesn't allow primitives added directly as children of the Canvas.
  12888. * 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.
  12889. */
  12890. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  12891. /**
  12892. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  12893. * 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.
  12894. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  12895. * 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.
  12896. */
  12897. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  12898. /**
  12899. * 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).
  12900. */
  12901. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  12902. /**
  12903. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  12904. * 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).
  12905. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  12906. */
  12907. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  12908. /**
  12909. * Observable Mask to be notified before rendering is made
  12910. */
  12911. Canvas2D.RENDEROBSERVABLE_PRE = 1;
  12912. /**
  12913. * Observable Mask to be notified after rendering is made
  12914. */
  12915. Canvas2D.RENDEROBSERVABLE_POST = 2;
  12916. Canvas2D._INSTANCES = [];
  12917. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  12918. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  12919. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  12920. Canvas2D._m = BABYLON.Matrix.Identity();
  12921. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  12922. /**
  12923. * Define the default size used for both the width and height of a MapTexture to allocate.
  12924. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  12925. */
  12926. Canvas2D._groupTextureCacheSize = 1024;
  12927. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  12928. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  12929. Canvas2D = __decorate([
  12930. BABYLON.className("Canvas2D", "BABYLON")
  12931. ], Canvas2D);
  12932. return Canvas2D;
  12933. }(BABYLON.Group2D));
  12934. BABYLON.Canvas2D = Canvas2D;
  12935. var WorldSpaceCanvas2D = (function (_super) {
  12936. __extends(WorldSpaceCanvas2D, _super);
  12937. /**
  12938. * 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.
  12939. * 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.
  12940. * @param scene the Scene that owns the Canvas
  12941. * @param size the dimension of the Canvas in World Space
  12942. * @param settings a combination of settings, possible ones are
  12943. * - children: an array of direct children primitives
  12944. * - id: a text identifier, for information purpose only, default is null.
  12945. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  12946. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  12947. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  12948. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  12949. * - 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).
  12950. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  12951. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  12952. * - 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.
  12953. * - 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.
  12954. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  12955. * - 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.
  12956. * - 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.
  12957. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12958. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12959. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12960. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  12961. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  12962. */
  12963. function WorldSpaceCanvas2D(scene, size, settings) {
  12964. var _this = this;
  12965. BABYLON.Prim2DBase._isCanvasInit = true;
  12966. var s = settings;
  12967. s.isScreenSpace = false;
  12968. s.size = size.clone();
  12969. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  12970. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  12971. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  12972. }
  12973. _super.call(this, scene, settings);
  12974. BABYLON.Prim2DBase._isCanvasInit = false;
  12975. this._renderableData._useMipMap = true;
  12976. this._renderableData._anisotropicLevel = 8;
  12977. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  12978. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  12979. //}
  12980. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  12981. var id = settings ? settings.id || null : null;
  12982. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  12983. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  12984. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  12985. if (settings.maxAdaptiveCanvasSize == null) {
  12986. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  12987. }
  12988. else {
  12989. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  12990. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  12991. }
  12992. if (createWorldSpaceNode) {
  12993. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  12994. var vertexData = BABYLON.VertexData.CreatePlane({
  12995. width: size.width,
  12996. height: size.height,
  12997. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  12998. });
  12999. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  13000. this.applyCachedTexture(vertexData, mtl);
  13001. vertexData.applyToMesh(plane, true);
  13002. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  13003. mtl.disableLighting = true;
  13004. mtl.useAlphaFromDiffuseTexture = true;
  13005. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  13006. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  13007. plane.material = mtl;
  13008. this._worldSpaceNode = plane;
  13009. }
  13010. else {
  13011. this._worldSpaceNode = settings.customWorldSpaceNode;
  13012. this.applyCachedTexture(null, null);
  13013. }
  13014. this.propertyChanged.add(function (e, st) {
  13015. var mesh = _this._worldSpaceNode;
  13016. if (mesh) {
  13017. mesh.isVisible = e.newValue;
  13018. }
  13019. }, BABYLON.Prim2DBase.isVisibleProperty.flagId);
  13020. }
  13021. WorldSpaceCanvas2D = __decorate([
  13022. BABYLON.className("WorldSpaceCanvas2D", "BABYLON")
  13023. ], WorldSpaceCanvas2D);
  13024. return WorldSpaceCanvas2D;
  13025. }(Canvas2D));
  13026. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  13027. var ScreenSpaceCanvas2D = (function (_super) {
  13028. __extends(ScreenSpaceCanvas2D, _super);
  13029. /**
  13030. * 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.
  13031. * 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.
  13032. * All caching strategies will be available.
  13033. * 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]
  13034. * @param scene the Scene that owns the Canvas
  13035. * @param settings a combination of settings, possible ones are
  13036. * - children: an array of direct children primitives
  13037. * - id: a text identifier, for information purpose only
  13038. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  13039. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  13040. * - 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]
  13041. * - width: the width of the Canvas. you can alternatively use the size setting.
  13042. * - height: the height of the Canvas. you can alternatively use the size setting.
  13043. * - 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
  13044. * - 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.
  13045. * - 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.
  13046. * - 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.
  13047. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  13048. * - 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.
  13049. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  13050. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  13051. * - 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.
  13052. * - 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.
  13053. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  13054. * - 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.
  13055. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  13056. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  13057. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  13058. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  13059. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  13060. */
  13061. function ScreenSpaceCanvas2D(scene, settings) {
  13062. BABYLON.Prim2DBase._isCanvasInit = true;
  13063. _super.call(this, scene, settings);
  13064. }
  13065. ScreenSpaceCanvas2D = __decorate([
  13066. BABYLON.className("ScreenSpaceCanvas2D", "BABYLON")
  13067. ], ScreenSpaceCanvas2D);
  13068. return ScreenSpaceCanvas2D;
  13069. }(Canvas2D));
  13070. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  13071. })(BABYLON || (BABYLON = {}));
  13072. var BABYLON;
  13073. (function (BABYLON) {
  13074. /**
  13075. * This is the class that is used to display a World Space Canvas into a 3D scene
  13076. */
  13077. var WorldSpaceCanvas2DNode = (function (_super) {
  13078. __extends(WorldSpaceCanvas2DNode, _super);
  13079. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  13080. _super.call(this, name, scene);
  13081. this._canvas = canvas;
  13082. }
  13083. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  13084. _super.prototype.dispose.call(this);
  13085. if (this._canvas) {
  13086. this._canvas.dispose();
  13087. this._canvas = null;
  13088. }
  13089. };
  13090. return WorldSpaceCanvas2DNode;
  13091. }(BABYLON.Mesh));
  13092. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  13093. })(BABYLON || (BABYLON = {}));
  13094. var BABYLON;
  13095. (function (BABYLON) {
  13096. var Command = (function () {
  13097. function Command(execute, canExecute) {
  13098. if (!execute) {
  13099. throw Error("At least an execute lambda must be given at Command creation time");
  13100. }
  13101. this._canExecuteChanged = null;
  13102. this._lastCanExecuteResult = null;
  13103. this.execute = execute;
  13104. this.canExecute = canExecute;
  13105. }
  13106. Command.prototype.canExecute = function (parameter) {
  13107. var res = true;
  13108. if (this._canExecute) {
  13109. res = this._canExecute(parameter);
  13110. }
  13111. if (res !== this._lastCanExecuteResult) {
  13112. if (this._canExecuteChanged && this._canExecuteChanged.hasObservers()) {
  13113. this._canExecuteChanged.notifyObservers(null);
  13114. }
  13115. this._lastCanExecuteResult = res;
  13116. }
  13117. return res;
  13118. };
  13119. Command.prototype.execute = function (parameter) {
  13120. this._execute(parameter);
  13121. };
  13122. Object.defineProperty(Command.prototype, "canExecuteChanged", {
  13123. get: function () {
  13124. if (!this._canExecuteChanged) {
  13125. this._canExecuteChanged = new BABYLON.Observable();
  13126. }
  13127. return this._canExecuteChanged;
  13128. },
  13129. enumerable: true,
  13130. configurable: true
  13131. });
  13132. return Command;
  13133. }());
  13134. BABYLON.Command = Command;
  13135. var UIElement = (function (_super) {
  13136. __extends(UIElement, _super);
  13137. function UIElement(settings) {
  13138. _super.call(this);
  13139. if (!settings) {
  13140. throw Error("A settings object must be passed with at least either a parent or owner parameter");
  13141. }
  13142. var type = BABYLON.Tools.getFullClassName(this);
  13143. this._ownerWindow = null;
  13144. this._parent = null;
  13145. this._visualPlaceholder = null;
  13146. this._visualTemplateRoot = null;
  13147. this._visualChildrenPlaceholder = null;
  13148. this._hierarchyDepth = 0;
  13149. this._renderingTemplateName = (settings.templateName != null) ? settings.templateName : GUIManager.DefaultTemplateName;
  13150. this._style = (settings.styleName != null) ? GUIManager.getStyle(type, settings.styleName) : null;
  13151. this._flags = 0;
  13152. this._id = (settings.id != null) ? settings.id : null;
  13153. this._uid = null;
  13154. this._width = (settings.width != null) ? settings.width : null;
  13155. this._height = (settings.height != null) ? settings.height : null;
  13156. this._minWidth = (settings.minWidth != null) ? settings.minWidth : 0;
  13157. this._minHeight = (settings.minHeight != null) ? settings.minHeight : 0;
  13158. this._maxWidth = (settings.maxWidth != null) ? settings.maxWidth : Number.MAX_VALUE;
  13159. this._maxHeight = (settings.maxHeight != null) ? settings.maxHeight : Number.MAX_VALUE;
  13160. this._margin = null;
  13161. this._padding = null;
  13162. this._marginAlignment = null;
  13163. this._setFlags(UIElement.flagIsVisible | UIElement.flagIsEnabled);
  13164. // Default Margin Alignment for UIElement is stretch for horizontal/vertical and not left/bottom (which is the default for Canvas2D Primitives)
  13165. //this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  13166. //this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  13167. // Set the layout/margin stuffs
  13168. if (settings.marginTop) {
  13169. this.margin.setTop(settings.marginTop);
  13170. }
  13171. if (settings.marginLeft) {
  13172. this.margin.setLeft(settings.marginLeft);
  13173. }
  13174. if (settings.marginRight) {
  13175. this.margin.setRight(settings.marginRight);
  13176. }
  13177. if (settings.marginBottom) {
  13178. this.margin.setBottom(settings.marginBottom);
  13179. }
  13180. if (settings.margin) {
  13181. if (typeof settings.margin === "string") {
  13182. this.margin.fromString(settings.margin);
  13183. }
  13184. else {
  13185. this.margin.fromUniformPixels(settings.margin);
  13186. }
  13187. }
  13188. if (settings.marginHAlignment) {
  13189. this.marginAlignment.horizontal = settings.marginHAlignment;
  13190. }
  13191. if (settings.marginVAlignment) {
  13192. this.marginAlignment.vertical = settings.marginVAlignment;
  13193. }
  13194. if (settings.marginAlignment) {
  13195. this.marginAlignment.fromString(settings.marginAlignment);
  13196. }
  13197. if (settings.paddingTop) {
  13198. this.padding.setTop(settings.paddingTop);
  13199. }
  13200. if (settings.paddingLeft) {
  13201. this.padding.setLeft(settings.paddingLeft);
  13202. }
  13203. if (settings.paddingRight) {
  13204. this.padding.setRight(settings.paddingRight);
  13205. }
  13206. if (settings.paddingBottom) {
  13207. this.padding.setBottom(settings.paddingBottom);
  13208. }
  13209. if (settings.padding) {
  13210. this.padding.fromString(settings.padding);
  13211. }
  13212. if (settings.paddingHAlignment) {
  13213. this.paddingAlignment.horizontal = settings.paddingHAlignment;
  13214. }
  13215. if (settings.paddingVAlignment) {
  13216. this.paddingAlignment.vertical = settings.paddingVAlignment;
  13217. }
  13218. if (settings.paddingAlignment) {
  13219. this.paddingAlignment.fromString(settings.paddingAlignment);
  13220. }
  13221. if (settings.parent != null) {
  13222. this._parent = settings.parent;
  13223. this._hierarchyDepth = this._parent._hierarchyDepth + 1;
  13224. }
  13225. }
  13226. Object.defineProperty(UIElement, "enabledState", {
  13227. get: function () {
  13228. return UIElement._enableState;
  13229. },
  13230. enumerable: true,
  13231. configurable: true
  13232. });
  13233. Object.defineProperty(UIElement, "disabledState", {
  13234. get: function () {
  13235. return UIElement._disabledState;
  13236. },
  13237. enumerable: true,
  13238. configurable: true
  13239. });
  13240. Object.defineProperty(UIElement, "mouseOverState", {
  13241. get: function () {
  13242. return UIElement._mouseOverState;
  13243. },
  13244. enumerable: true,
  13245. configurable: true
  13246. });
  13247. UIElement.prototype.dispose = function () {
  13248. if (this.isDisposed) {
  13249. return false;
  13250. }
  13251. if (this._renderingTemplate) {
  13252. this._renderingTemplate.detach();
  13253. this._renderingTemplate = null;
  13254. }
  13255. _super.prototype.dispose.call(this);
  13256. // Don't set to null, it may upset somebody...
  13257. this.animations.splice(0);
  13258. return true;
  13259. };
  13260. /**
  13261. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  13262. * Look at Sprite2D for more information
  13263. */
  13264. UIElement.prototype.getAnimatables = function () {
  13265. return new Array();
  13266. };
  13267. // TODO
  13268. // PROPERTIES
  13269. // Style
  13270. // Id
  13271. // Parent/Children
  13272. // ActualWidth/Height, MinWidth/Height, MaxWidth/Height,
  13273. // Alignment/Margin
  13274. // Visibility, IsVisible
  13275. // IsEnabled (is false, control is disabled, no interaction and a specific render state)
  13276. // CacheMode of Visual Elements
  13277. // Focusable/IsFocused
  13278. // IsPointerCaptured, CapturePointer, IsPointerDirectlyOver, IsPointerOver. De-correlate mouse, stylus, touch?
  13279. // ContextMenu
  13280. // Cursor
  13281. // DesiredSize
  13282. // IsInputEnable ?
  13283. // Opacity, OpacityMask ?
  13284. // SnapToDevicePixels
  13285. // Tag
  13286. // ToolTip
  13287. // METHODS
  13288. // BringIntoView (for scrollable content, to move the scroll to bring the given element visible in the parent's area)
  13289. // Capture/ReleaseCapture (mouse, touch, stylus)
  13290. // Focus
  13291. // PointFrom/ToScreen to translate coordinates
  13292. // EVENTS
  13293. // ContextMenuOpening/Closing/Changed
  13294. // DragEnter/LeaveOver, Drop
  13295. // Got/LostFocus
  13296. // IsEnabledChanged
  13297. // IsPointerOver/DirectlyOverChanged
  13298. // IsVisibleChanged
  13299. // KeyDown/Up
  13300. // LayoutUpdated ?
  13301. // Pointer related events
  13302. // SizeChanged
  13303. // ToolTipOpening/Closing
  13304. UIElement.prototype.findById = function (id) {
  13305. if (this._id === id) {
  13306. return this;
  13307. }
  13308. var children = this._getChildren();
  13309. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  13310. var child = children_1[_i];
  13311. var r = child.findById(id);
  13312. if (r != null) {
  13313. return r;
  13314. }
  13315. }
  13316. };
  13317. Object.defineProperty(UIElement.prototype, "ownerWindow", {
  13318. get: function () {
  13319. return this._ownerWindow;
  13320. },
  13321. enumerable: true,
  13322. configurable: true
  13323. });
  13324. Object.defineProperty(UIElement.prototype, "style", {
  13325. get: function () {
  13326. if (!this.style) {
  13327. return GUIManager.DefaultStyleName;
  13328. }
  13329. return this._style.name;
  13330. },
  13331. set: function (value) {
  13332. if (this._style && (this._style.name === value)) {
  13333. return;
  13334. }
  13335. var newStyle = null;
  13336. if (value) {
  13337. newStyle = GUIManager.getStyle(BABYLON.Tools.getFullClassName(this), value);
  13338. if (!newStyle) {
  13339. throw Error("Couldn't find Style " + value + " for UIElement " + BABYLON.Tools.getFullClassName(this));
  13340. }
  13341. }
  13342. if (this._style) {
  13343. this._style.removeStyle(this);
  13344. }
  13345. if (newStyle) {
  13346. newStyle.applyStyle(this);
  13347. }
  13348. this._style = newStyle;
  13349. },
  13350. enumerable: true,
  13351. configurable: true
  13352. });
  13353. Object.defineProperty(UIElement.prototype, "id", {
  13354. /**
  13355. * A string that identifies the UIElement.
  13356. * The id is optional and there's possible collision with other UIElement's id as the uniqueness is not supported.
  13357. */
  13358. get: function () {
  13359. return this._id;
  13360. },
  13361. set: function (value) {
  13362. if (this._id === value) {
  13363. return;
  13364. }
  13365. this._id = value;
  13366. },
  13367. enumerable: true,
  13368. configurable: true
  13369. });
  13370. Object.defineProperty(UIElement.prototype, "uid", {
  13371. /**
  13372. * Return a unique id automatically generated.
  13373. * This property is mainly used for serialization to ensure a perfect way of identifying a UIElement
  13374. */
  13375. get: function () {
  13376. if (!this._uid) {
  13377. this._uid = BABYLON.Tools.RandomId();
  13378. }
  13379. return this._uid;
  13380. },
  13381. enumerable: true,
  13382. configurable: true
  13383. });
  13384. Object.defineProperty(UIElement.prototype, "hierarchyDepth", {
  13385. get: function () {
  13386. return this._hierarchyDepth;
  13387. },
  13388. enumerable: true,
  13389. configurable: true
  13390. });
  13391. Object.defineProperty(UIElement.prototype, "parent", {
  13392. get: function () {
  13393. return this._parent;
  13394. },
  13395. set: function (value) {
  13396. this._parent = value;
  13397. },
  13398. enumerable: true,
  13399. configurable: true
  13400. });
  13401. Object.defineProperty(UIElement.prototype, "width", {
  13402. get: function () {
  13403. return this._width;
  13404. },
  13405. set: function (value) {
  13406. this._width = value;
  13407. },
  13408. enumerable: true,
  13409. configurable: true
  13410. });
  13411. Object.defineProperty(UIElement.prototype, "height", {
  13412. get: function () {
  13413. return this._height;
  13414. },
  13415. set: function (value) {
  13416. this._height = value;
  13417. },
  13418. enumerable: true,
  13419. configurable: true
  13420. });
  13421. Object.defineProperty(UIElement.prototype, "minWidth", {
  13422. get: function () {
  13423. return this._minWidth;
  13424. },
  13425. set: function (value) {
  13426. this._minWidth = value;
  13427. },
  13428. enumerable: true,
  13429. configurable: true
  13430. });
  13431. Object.defineProperty(UIElement.prototype, "minHheight", {
  13432. get: function () {
  13433. return this._minHeight;
  13434. },
  13435. enumerable: true,
  13436. configurable: true
  13437. });
  13438. Object.defineProperty(UIElement.prototype, "minHeight", {
  13439. set: function (value) {
  13440. this._minHeight = value;
  13441. },
  13442. enumerable: true,
  13443. configurable: true
  13444. });
  13445. Object.defineProperty(UIElement.prototype, "maxWidth", {
  13446. get: function () {
  13447. return this._maxWidth;
  13448. },
  13449. set: function (value) {
  13450. this._maxWidth = value;
  13451. },
  13452. enumerable: true,
  13453. configurable: true
  13454. });
  13455. Object.defineProperty(UIElement.prototype, "maxHeight", {
  13456. get: function () {
  13457. return this._maxHeight;
  13458. },
  13459. set: function (value) {
  13460. this._maxHeight = value;
  13461. },
  13462. enumerable: true,
  13463. configurable: true
  13464. });
  13465. Object.defineProperty(UIElement.prototype, "actualWidth", {
  13466. get: function () {
  13467. return this._actualWidth;
  13468. },
  13469. set: function (value) {
  13470. this._actualWidth = value;
  13471. },
  13472. enumerable: true,
  13473. configurable: true
  13474. });
  13475. Object.defineProperty(UIElement.prototype, "actualHeight", {
  13476. get: function () {
  13477. return this._actualHeight;
  13478. },
  13479. set: function (value) {
  13480. this._actualHeight = value;
  13481. },
  13482. enumerable: true,
  13483. configurable: true
  13484. });
  13485. Object.defineProperty(UIElement.prototype, "margin", {
  13486. get: function () {
  13487. var _this = this;
  13488. if (!this._margin) {
  13489. this._margin = new BABYLON.PrimitiveThickness(function () {
  13490. if (!_this.parent) {
  13491. return null;
  13492. }
  13493. return _this.parent.margin;
  13494. });
  13495. }
  13496. return this._margin;
  13497. },
  13498. set: function (value) {
  13499. this.margin.copyFrom(value);
  13500. },
  13501. enumerable: true,
  13502. configurable: true
  13503. });
  13504. Object.defineProperty(UIElement.prototype, "_hasMargin", {
  13505. get: function () {
  13506. return (this._margin !== null && !this._margin.isDefault) || (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  13507. },
  13508. enumerable: true,
  13509. configurable: true
  13510. });
  13511. Object.defineProperty(UIElement.prototype, "padding", {
  13512. get: function () {
  13513. var _this = this;
  13514. if (!this._padding) {
  13515. this._padding = new BABYLON.PrimitiveThickness(function () {
  13516. if (!_this.parent) {
  13517. return null;
  13518. }
  13519. return _this.parent.padding;
  13520. });
  13521. }
  13522. return this._padding;
  13523. },
  13524. set: function (value) {
  13525. this.padding.copyFrom(value);
  13526. },
  13527. enumerable: true,
  13528. configurable: true
  13529. });
  13530. Object.defineProperty(UIElement.prototype, "_hasPadding", {
  13531. get: function () {
  13532. return this._padding !== null && !this._padding.isDefault;
  13533. },
  13534. enumerable: true,
  13535. configurable: true
  13536. });
  13537. Object.defineProperty(UIElement.prototype, "marginAlignment", {
  13538. get: function () {
  13539. if (!this._marginAlignment) {
  13540. this._marginAlignment = new BABYLON.PrimitiveAlignment();
  13541. }
  13542. return this._marginAlignment;
  13543. },
  13544. set: function (value) {
  13545. this.marginAlignment.copyFrom(value);
  13546. },
  13547. enumerable: true,
  13548. configurable: true
  13549. });
  13550. Object.defineProperty(UIElement.prototype, "_hasMarginAlignment", {
  13551. /**
  13552. * Check if there a marginAlignment specified (non null and not default)
  13553. */
  13554. get: function () {
  13555. return (this._marginAlignment !== null && !this._marginAlignment.isDefault);
  13556. },
  13557. enumerable: true,
  13558. configurable: true
  13559. });
  13560. Object.defineProperty(UIElement.prototype, "paddingAlignment", {
  13561. get: function () {
  13562. if (!this._paddingAlignment) {
  13563. this._paddingAlignment = new BABYLON.PrimitiveAlignment();
  13564. }
  13565. return this._paddingAlignment;
  13566. },
  13567. set: function (value) {
  13568. this.paddingAlignment.copyFrom(value);
  13569. },
  13570. enumerable: true,
  13571. configurable: true
  13572. });
  13573. Object.defineProperty(UIElement.prototype, "_hasPaddingAlignment", {
  13574. /**
  13575. * Check if there a marginAlignment specified (non null and not default)
  13576. */
  13577. get: function () {
  13578. return (this._paddingAlignment !== null && !this._paddingAlignment.isDefault);
  13579. },
  13580. enumerable: true,
  13581. configurable: true
  13582. });
  13583. Object.defineProperty(UIElement.prototype, "isVisible", {
  13584. get: function () {
  13585. return this._isFlagSet(UIElement.flagIsVisible);
  13586. },
  13587. set: function (value) {
  13588. if (this.isVisible === value) {
  13589. return;
  13590. }
  13591. this._visualPlaceholder.levelVisible = value;
  13592. this._changeFlags(UIElement.flagIsVisible, value);
  13593. },
  13594. enumerable: true,
  13595. configurable: true
  13596. });
  13597. Object.defineProperty(UIElement.prototype, "isEnabled", {
  13598. get: function () {
  13599. return this._isFlagSet(UIElement.flagIsEnabled);
  13600. },
  13601. set: function (value) {
  13602. this._changeFlags(UIElement.flagIsEnabled, value);
  13603. },
  13604. enumerable: true,
  13605. configurable: true
  13606. });
  13607. Object.defineProperty(UIElement.prototype, "isFocused", {
  13608. get: function () {
  13609. return this._isFlagSet(UIElement.flagIsFocus);
  13610. },
  13611. set: function (value) {
  13612. // If the UIElement doesn't accept focus, set it on its parent
  13613. if (!this.isFocusable) {
  13614. var p = this.parent;
  13615. if (!p) {
  13616. return;
  13617. }
  13618. p.isFocused = value;
  13619. }
  13620. // If the focus is being set, notify the Focus Manager
  13621. if (value) {
  13622. this.ownerWindow.focusManager.setFocusOn(this, this.getFocusScope());
  13623. }
  13624. this._changeFlags(UIElement.flagIsFocus, value);
  13625. },
  13626. enumerable: true,
  13627. configurable: true
  13628. });
  13629. Object.defineProperty(UIElement.prototype, "isMouseOver", {
  13630. get: function () {
  13631. return this._isFlagSet(UIElement.flagIsMouseOver);
  13632. },
  13633. set: function (value) {
  13634. this._changeFlags(UIElement.flagIsMouseOver, value);
  13635. },
  13636. enumerable: true,
  13637. configurable: true
  13638. });
  13639. Object.defineProperty(UIElement.prototype, "isFocusScope", {
  13640. get: function () {
  13641. return this._isFlagSet(UIElement.flagIsFocusScope);
  13642. },
  13643. set: function (value) {
  13644. this._changeFlags(UIElement.flagIsFocusScope, value);
  13645. },
  13646. enumerable: true,
  13647. configurable: true
  13648. });
  13649. Object.defineProperty(UIElement.prototype, "isFocusable", {
  13650. get: function () {
  13651. return this._isFlagSet(UIElement.flagIsFocusable);
  13652. },
  13653. set: function (value) {
  13654. this._changeFlags(UIElement.flagIsFocusable, value);
  13655. },
  13656. enumerable: true,
  13657. configurable: true
  13658. });
  13659. // 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)
  13660. UIElement.prototype.getFocusScope = function () {
  13661. if (this.isFocusScope) {
  13662. return this;
  13663. }
  13664. var p = this.parent;
  13665. if (!p) {
  13666. return null;
  13667. }
  13668. return p.getFocusScope();
  13669. };
  13670. /**
  13671. * Check if a given flag is set
  13672. * @param flag the flag value
  13673. * @return true if set, false otherwise
  13674. */
  13675. UIElement.prototype._isFlagSet = function (flag) {
  13676. return (this._flags & flag) !== 0;
  13677. };
  13678. /**
  13679. * Check if all given flags are set
  13680. * @param flags the flags ORed
  13681. * @return true if all the flags are set, false otherwise
  13682. */
  13683. UIElement.prototype._areAllFlagsSet = function (flags) {
  13684. return (this._flags & flags) === flags;
  13685. };
  13686. /**
  13687. * Check if at least one flag of the given flags is set
  13688. * @param flags the flags ORed
  13689. * @return true if at least one flag is set, false otherwise
  13690. */
  13691. UIElement.prototype._areSomeFlagsSet = function (flags) {
  13692. return (this._flags & flags) !== 0;
  13693. };
  13694. /**
  13695. * Clear the given flags
  13696. * @param flags the flags to clear
  13697. */
  13698. UIElement.prototype._clearFlags = function (flags) {
  13699. this._flags &= ~flags;
  13700. };
  13701. /**
  13702. * Set the given flags to true state
  13703. * @param flags the flags ORed to set
  13704. * @return the flags state before this call
  13705. */
  13706. UIElement.prototype._setFlags = function (flags) {
  13707. var cur = this._flags;
  13708. this._flags |= flags;
  13709. return cur;
  13710. };
  13711. /**
  13712. * Change the state of the given flags
  13713. * @param flags the flags ORed to change
  13714. * @param state true to set them, false to clear them
  13715. */
  13716. UIElement.prototype._changeFlags = function (flags, state) {
  13717. if (state) {
  13718. this._flags |= flags;
  13719. }
  13720. else {
  13721. this._flags &= ~flags;
  13722. }
  13723. };
  13724. UIElement.prototype._assignTemplate = function (templateName) {
  13725. if (!templateName) {
  13726. templateName = GUIManager.DefaultTemplateName;
  13727. }
  13728. var className = BABYLON.Tools.getFullClassName(this);
  13729. if (!className) {
  13730. throw Error("Couldn't access class name of this UIElement, you have to decorate the type with the className decorator");
  13731. }
  13732. var factory = GUIManager.getRenderingTemplate(className, templateName);
  13733. if (!factory) {
  13734. throw Error("Couldn't get the renderingTemplate " + templateName + " of class " + className);
  13735. }
  13736. this._renderingTemplateName = templateName;
  13737. this._renderingTemplate = factory();
  13738. this._renderingTemplate.attach(this);
  13739. };
  13740. UIElement.prototype._createVisualTree = function () {
  13741. var parentPrim = this.ownerWindow.canvas;
  13742. if (this.parent) {
  13743. parentPrim = this.parent.visualChildrenPlaceholder;
  13744. }
  13745. if (!this._renderingTemplate) {
  13746. this._assignTemplate(this._renderingTemplateName);
  13747. }
  13748. this._visualPlaceholder = new BABYLON.Group2D({ parent: parentPrim, id: "GUI " + BABYLON.Tools.getClassName(this) + " RootGroup of " + this.id });
  13749. var p = this._visualPlaceholder;
  13750. p.addExternalData("_GUIOwnerElement_", this);
  13751. p.dataSource = this;
  13752. p.createSimpleDataBinding(BABYLON.Prim2DBase.widthProperty, "width", BABYLON.DataBinding.MODE_ONEWAY);
  13753. p.createSimpleDataBinding(BABYLON.Prim2DBase.heightProperty, "height", BABYLON.DataBinding.MODE_ONEWAY);
  13754. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualWidthProperty, "actualWidth", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  13755. p.createSimpleDataBinding(BABYLON.Prim2DBase.actualHeightProperty, "actualHeight", BABYLON.DataBinding.MODE_ONEWAYTOSOURCE);
  13756. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "margin", BABYLON.DataBinding.MODE_ONEWAY);
  13757. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "marginAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  13758. this.createVisualTree();
  13759. };
  13760. UIElement.prototype._patchUIElement = function (ownerWindow, parent) {
  13761. if (ownerWindow) {
  13762. if (!this._ownerWindow) {
  13763. ownerWindow._registerVisualToBuild(this);
  13764. }
  13765. this._ownerWindow = ownerWindow;
  13766. }
  13767. this._parent = parent;
  13768. if (parent) {
  13769. this._hierarchyDepth = parent.hierarchyDepth + 1;
  13770. }
  13771. var children = this._getChildren();
  13772. if (children) {
  13773. for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
  13774. var curChild = children_2[_i];
  13775. curChild._patchUIElement(ownerWindow, this);
  13776. }
  13777. }
  13778. };
  13779. // 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.
  13780. UIElement.prototype._getDataSource = function () {
  13781. var levelDS = _super.prototype._getDataSource.call(this);
  13782. if (levelDS != null) {
  13783. return levelDS;
  13784. }
  13785. var p = this.parent;
  13786. if (p != null) {
  13787. return p.dataSource;
  13788. }
  13789. return null;
  13790. };
  13791. UIElement.prototype.createVisualTree = function () {
  13792. var res = this._renderingTemplate.createVisualTree(this, this._visualPlaceholder);
  13793. this._visualTemplateRoot = res.root;
  13794. this._visualChildrenPlaceholder = res.contentPlaceholder;
  13795. };
  13796. Object.defineProperty(UIElement.prototype, "visualPlaceholder", {
  13797. get: function () {
  13798. return this._visualPlaceholder;
  13799. },
  13800. enumerable: true,
  13801. configurable: true
  13802. });
  13803. Object.defineProperty(UIElement.prototype, "visualTemplateRoot", {
  13804. get: function () {
  13805. return this._visualTemplateRoot;
  13806. },
  13807. enumerable: true,
  13808. configurable: true
  13809. });
  13810. Object.defineProperty(UIElement.prototype, "visualChildrenPlaceholder", {
  13811. get: function () {
  13812. return this._visualChildrenPlaceholder;
  13813. },
  13814. enumerable: true,
  13815. configurable: true
  13816. });
  13817. Object.defineProperty(UIElement.prototype, "_position", {
  13818. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  13819. ,
  13820. enumerable: true,
  13821. configurable: true
  13822. });
  13823. UIElement.UIELEMENT_PROPCOUNT = 16;
  13824. UIElement.flagVisualToBuild = 0x0000001;
  13825. UIElement.flagIsVisible = 0x0000002;
  13826. UIElement.flagIsFocus = 0x0000004;
  13827. UIElement.flagIsFocusScope = 0x0000008;
  13828. UIElement.flagIsFocusable = 0x0000010;
  13829. UIElement.flagIsEnabled = 0x0000020;
  13830. UIElement.flagIsMouseOver = 0x0000040;
  13831. UIElement._enableState = "Enabled";
  13832. UIElement._disabledState = "Disabled";
  13833. UIElement._mouseOverState = "MouseOver";
  13834. __decorate([
  13835. BABYLON.dependencyProperty(0, function (pi) { return UIElement.parentProperty = pi; })
  13836. ], UIElement.prototype, "parent", null);
  13837. __decorate([
  13838. BABYLON.dependencyProperty(1, function (pi) { return UIElement.widthProperty = pi; })
  13839. ], UIElement.prototype, "width", null);
  13840. __decorate([
  13841. BABYLON.dependencyProperty(2, function (pi) { return UIElement.heightProperty = pi; })
  13842. ], UIElement.prototype, "height", null);
  13843. __decorate([
  13844. BABYLON.dependencyProperty(3, function (pi) { return UIElement.minWidthProperty = pi; })
  13845. ], UIElement.prototype, "minWidth", null);
  13846. __decorate([
  13847. BABYLON.dependencyProperty(4, function (pi) { return UIElement.minHeightProperty = pi; })
  13848. ], UIElement.prototype, "minHheight", null);
  13849. __decorate([
  13850. BABYLON.dependencyProperty(5, function (pi) { return UIElement.maxWidthProperty = pi; })
  13851. ], UIElement.prototype, "maxWidth", null);
  13852. __decorate([
  13853. BABYLON.dependencyProperty(6, function (pi) { return UIElement.maxHeightProperty = pi; })
  13854. ], UIElement.prototype, "maxHeight", null);
  13855. __decorate([
  13856. BABYLON.dependencyProperty(7, function (pi) { return UIElement.actualWidthProperty = pi; })
  13857. ], UIElement.prototype, "actualWidth", null);
  13858. __decorate([
  13859. BABYLON.dependencyProperty(8, function (pi) { return UIElement.actualHeightProperty = pi; })
  13860. ], UIElement.prototype, "actualHeight", null);
  13861. __decorate([
  13862. BABYLON.dynamicLevelProperty(9, function (pi) { return UIElement.marginProperty = pi; })
  13863. ], UIElement.prototype, "margin", null);
  13864. __decorate([
  13865. BABYLON.dynamicLevelProperty(10, function (pi) { return UIElement.paddingProperty = pi; })
  13866. ], UIElement.prototype, "padding", null);
  13867. __decorate([
  13868. BABYLON.dynamicLevelProperty(11, function (pi) { return UIElement.marginAlignmentProperty = pi; })
  13869. ], UIElement.prototype, "marginAlignment", null);
  13870. __decorate([
  13871. BABYLON.dynamicLevelProperty(12, function (pi) { return UIElement.paddingAlignmentProperty = pi; })
  13872. ], UIElement.prototype, "paddingAlignment", null);
  13873. __decorate([
  13874. BABYLON.dynamicLevelProperty(13, function (pi) { return UIElement.isEnabledProperty = pi; })
  13875. ], UIElement.prototype, "isEnabled", null);
  13876. __decorate([
  13877. BABYLON.dynamicLevelProperty(14, function (pi) { return UIElement.isFocusedProperty = pi; })
  13878. ], UIElement.prototype, "isFocused", null);
  13879. __decorate([
  13880. BABYLON.dynamicLevelProperty(15, function (pi) { return UIElement.isMouseOverProperty = pi; })
  13881. ], UIElement.prototype, "isMouseOver", null);
  13882. return UIElement;
  13883. }(BABYLON.SmartPropertyBase));
  13884. BABYLON.UIElement = UIElement;
  13885. var UIElementStyle = (function () {
  13886. function UIElementStyle() {
  13887. }
  13888. Object.defineProperty(UIElementStyle.prototype, "name", {
  13889. get: function () { return null; } // TODO use abstract keyword when TS 2.0 will be approved
  13890. ,
  13891. enumerable: true,
  13892. configurable: true
  13893. });
  13894. return UIElementStyle;
  13895. }());
  13896. BABYLON.UIElementStyle = UIElementStyle;
  13897. var GUIManager = (function () {
  13898. function GUIManager() {
  13899. }
  13900. /////////////////////////////////////////////////////////////////////////////////////////////////////
  13901. // DATA TEMPLATE MANAGER
  13902. GUIManager.registerDataTemplate = function (className, factory) {
  13903. };
  13904. // DATA TEMPLATE MANAGER
  13905. /////////////////////////////////////////////////////////////////////////////////////////////////////
  13906. /////////////////////////////////////////////////////////////////////////////////////////////////////
  13907. // STYLE MANAGER
  13908. GUIManager.getStyle = function (uiElType, styleName) {
  13909. var styles = GUIManager.stylesByUIElement.get(uiElType);
  13910. if (!styles) {
  13911. throw Error("The type " + uiElType + " is unknown, no style were registered for it.");
  13912. }
  13913. var style = styles.get(styleName);
  13914. if (!style) {
  13915. throw Error("Couldn't find Template " + styleName + " of UIElement type " + uiElType);
  13916. }
  13917. return style;
  13918. };
  13919. GUIManager.registerStyle = function (uiElType, templateName, style) {
  13920. var templates = GUIManager.stylesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  13921. if (templates.contains(templateName)) {
  13922. templates[templateName] = style;
  13923. }
  13924. else {
  13925. templates.add(templateName, style);
  13926. }
  13927. };
  13928. Object.defineProperty(GUIManager, "DefaultStyleName", {
  13929. get: function () {
  13930. return GUIManager._defaultStyleName;
  13931. },
  13932. set: function (value) {
  13933. GUIManager._defaultStyleName = value;
  13934. },
  13935. enumerable: true,
  13936. configurable: true
  13937. });
  13938. // STYLE MANAGER
  13939. /////////////////////////////////////////////////////////////////////////////////////////////////////
  13940. /////////////////////////////////////////////////////////////////////////////////////////////////////
  13941. // RENDERING TEMPLATE MANAGER
  13942. GUIManager.getRenderingTemplate = function (uiElType, templateName) {
  13943. var templates = GUIManager.renderingTemplatesByUIElement.get(uiElType);
  13944. if (!templates) {
  13945. throw Error("The type " + uiElType + " is unknown, no Rendering Template were registered for it.");
  13946. }
  13947. var templateFactory = templates.get(templateName);
  13948. if (!templateFactory) {
  13949. throw Error("Couldn't find Template " + templateName + " of UI Element type " + uiElType);
  13950. }
  13951. return templateFactory;
  13952. };
  13953. GUIManager.registerRenderingTemplate = function (uiElType, templateName, factory) {
  13954. var templates = GUIManager.renderingTemplatesByUIElement.getOrAddWithFactory(uiElType, function () { return new BABYLON.StringDictionary(); });
  13955. if (templates.contains(templateName)) {
  13956. templates[templateName] = factory;
  13957. }
  13958. else {
  13959. templates.add(templateName, factory);
  13960. }
  13961. };
  13962. Object.defineProperty(GUIManager, "DefaultTemplateName", {
  13963. get: function () {
  13964. return GUIManager._defaultTemplateName;
  13965. },
  13966. set: function (value) {
  13967. GUIManager._defaultTemplateName = value;
  13968. },
  13969. enumerable: true,
  13970. configurable: true
  13971. });
  13972. GUIManager.stylesByUIElement = new BABYLON.StringDictionary();
  13973. GUIManager.renderingTemplatesByUIElement = new BABYLON.StringDictionary();
  13974. // RENDERING TEMPLATE MANAGER
  13975. /////////////////////////////////////////////////////////////////////////////////////////////////////
  13976. GUIManager._defaultTemplateName = "Default";
  13977. GUIManager._defaultStyleName = "Default";
  13978. return GUIManager;
  13979. }());
  13980. BABYLON.GUIManager = GUIManager;
  13981. var UIElementRenderingTemplateBase = (function () {
  13982. function UIElementRenderingTemplateBase() {
  13983. }
  13984. UIElementRenderingTemplateBase.prototype.attach = function (owner) {
  13985. this._owner = owner;
  13986. };
  13987. UIElementRenderingTemplateBase.prototype.detach = function () {
  13988. };
  13989. Object.defineProperty(UIElementRenderingTemplateBase.prototype, "owner", {
  13990. get: function () {
  13991. return this._owner;
  13992. },
  13993. enumerable: true,
  13994. configurable: true
  13995. });
  13996. return UIElementRenderingTemplateBase;
  13997. }());
  13998. BABYLON.UIElementRenderingTemplateBase = UIElementRenderingTemplateBase;
  13999. function registerWindowRenderingTemplate(uiElType, templateName, factory) {
  14000. return function () {
  14001. GUIManager.registerRenderingTemplate(uiElType, templateName, factory);
  14002. };
  14003. }
  14004. BABYLON.registerWindowRenderingTemplate = registerWindowRenderingTemplate;
  14005. })(BABYLON || (BABYLON = {}));
  14006. var BABYLON;
  14007. (function (BABYLON) {
  14008. var StackPanel = (function (_super) {
  14009. __extends(StackPanel, _super);
  14010. function StackPanel(settings) {
  14011. if (!settings) {
  14012. settings = {};
  14013. }
  14014. _super.call(this, settings);
  14015. this.isOrientationHorizontal = (settings.isOrientationHorizontal == null) ? true : settings.isOrientationHorizontal;
  14016. this._children = new Array();
  14017. if (settings.children != null) {
  14018. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  14019. var child = _a[_i];
  14020. this._children.push(child);
  14021. }
  14022. }
  14023. }
  14024. Object.defineProperty(StackPanel.prototype, "isOrientationHorizontal", {
  14025. get: function () {
  14026. return this._isOrientationHorizontal;
  14027. },
  14028. set: function (value) {
  14029. this._isOrientationHorizontal = value;
  14030. },
  14031. enumerable: true,
  14032. configurable: true
  14033. });
  14034. StackPanel.prototype.createVisualTree = function () {
  14035. _super.prototype.createVisualTree.call(this);
  14036. // A StackPanel Control has a Group2D, child of the visualPlaceHolder, which is the Children placeholder.
  14037. // The Children UIElement Tree will be create inside this placeholder.
  14038. this._childrenPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "StackPanel Children Placeholder of " + this.id });
  14039. var p = this._childrenPlaceholder;
  14040. p.layoutEngine = this.isOrientationHorizontal ? BABYLON.StackPanelLayoutEngine.Horizontal : BABYLON.StackPanelLayoutEngine.Vertical;
  14041. // 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.
  14042. p.dataSource = this;
  14043. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  14044. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  14045. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  14046. // But it's not the case for a StackPanel, the placeholder of UIElement Children (the content)
  14047. this._visualChildrenPlaceholder = this._childrenPlaceholder;
  14048. };
  14049. Object.defineProperty(StackPanel.prototype, "children", {
  14050. get: function () {
  14051. return this._children;
  14052. },
  14053. enumerable: true,
  14054. configurable: true
  14055. });
  14056. StackPanel.prototype._getChildren = function () {
  14057. return this.children;
  14058. };
  14059. StackPanel.STACKPANEL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3;
  14060. __decorate([
  14061. BABYLON.dependencyProperty(StackPanel.STACKPANEL_PROPCOUNT + 0, function (pi) { return StackPanel.orientationHorizontalProperty = pi; })
  14062. ], StackPanel.prototype, "isOrientationHorizontal", null);
  14063. StackPanel = __decorate([
  14064. BABYLON.className("StackPanel", "BABYLON")
  14065. ], StackPanel);
  14066. return StackPanel;
  14067. }(BABYLON.UIElement));
  14068. BABYLON.StackPanel = StackPanel;
  14069. var DefaultStackPanelRenderingTemplate = (function (_super) {
  14070. __extends(DefaultStackPanelRenderingTemplate, _super);
  14071. function DefaultStackPanelRenderingTemplate() {
  14072. _super.apply(this, arguments);
  14073. }
  14074. DefaultStackPanelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  14075. return { root: visualPlaceholder, contentPlaceholder: visualPlaceholder };
  14076. };
  14077. DefaultStackPanelRenderingTemplate.prototype.attach = function (owner) {
  14078. _super.prototype.attach.call(this, owner);
  14079. };
  14080. DefaultStackPanelRenderingTemplate = __decorate([
  14081. BABYLON.registerWindowRenderingTemplate("BABYLON.StackPanel", "Default", function () { return new DefaultStackPanelRenderingTemplate(); })
  14082. ], DefaultStackPanelRenderingTemplate);
  14083. return DefaultStackPanelRenderingTemplate;
  14084. }(BABYLON.UIElementRenderingTemplateBase));
  14085. BABYLON.DefaultStackPanelRenderingTemplate = DefaultStackPanelRenderingTemplate;
  14086. })(BABYLON || (BABYLON = {}));
  14087. var BABYLON;
  14088. (function (BABYLON) {
  14089. var Control = (function (_super) {
  14090. __extends(Control, _super);
  14091. function Control(settings) {
  14092. _super.call(this, settings);
  14093. }
  14094. Object.defineProperty(Control.prototype, "background", {
  14095. get: function () {
  14096. if (!this._background) {
  14097. this._background = new BABYLON.ObservableStringDictionary(false);
  14098. }
  14099. return this._background;
  14100. },
  14101. set: function (value) {
  14102. this.background.copyFrom(value);
  14103. },
  14104. enumerable: true,
  14105. configurable: true
  14106. });
  14107. Object.defineProperty(Control.prototype, "border", {
  14108. get: function () {
  14109. return this._border;
  14110. },
  14111. set: function (value) {
  14112. this._border = value;
  14113. },
  14114. enumerable: true,
  14115. configurable: true
  14116. });
  14117. Object.defineProperty(Control.prototype, "borderThickness", {
  14118. get: function () {
  14119. return this._borderThickness;
  14120. },
  14121. set: function (value) {
  14122. this._borderThickness = value;
  14123. },
  14124. enumerable: true,
  14125. configurable: true
  14126. });
  14127. Object.defineProperty(Control.prototype, "fontName", {
  14128. get: function () {
  14129. return this._fontName;
  14130. },
  14131. set: function (value) {
  14132. this._fontName = value;
  14133. },
  14134. enumerable: true,
  14135. configurable: true
  14136. });
  14137. Object.defineProperty(Control.prototype, "foreground", {
  14138. get: function () {
  14139. return this._foreground;
  14140. },
  14141. set: function (value) {
  14142. this._foreground = value;
  14143. },
  14144. enumerable: true,
  14145. configurable: true
  14146. });
  14147. Control.CONTROL_PROPCOUNT = BABYLON.UIElement.UIELEMENT_PROPCOUNT + 5;
  14148. __decorate([
  14149. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 0, function (pi) { return Control.backgroundProperty = pi; })
  14150. ], Control.prototype, "background", null);
  14151. __decorate([
  14152. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 1, function (pi) { return Control.borderProperty = pi; })
  14153. ], Control.prototype, "border", null);
  14154. __decorate([
  14155. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 2, function (pi) { return Control.borderThicknessProperty = pi; })
  14156. ], Control.prototype, "borderThickness", null);
  14157. __decorate([
  14158. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 3, function (pi) { return Control.fontNameProperty = pi; })
  14159. ], Control.prototype, "fontName", null);
  14160. __decorate([
  14161. BABYLON.dependencyProperty(BABYLON.UIElement.UIELEMENT_PROPCOUNT + 4, function (pi) { return Control.foregroundProperty = pi; })
  14162. ], Control.prototype, "foreground", null);
  14163. Control = __decorate([
  14164. BABYLON.className("Control", "BABYLON")
  14165. ], Control);
  14166. return Control;
  14167. }(BABYLON.UIElement));
  14168. BABYLON.Control = Control;
  14169. })(BABYLON || (BABYLON = {}));
  14170. var BABYLON;
  14171. (function (BABYLON) {
  14172. var ContentControl = (function (_super) {
  14173. __extends(ContentControl, _super);
  14174. function ContentControl(settings) {
  14175. if (!settings) {
  14176. settings = {};
  14177. }
  14178. _super.call(this, settings);
  14179. if (settings.content != null) {
  14180. this._content = settings.content;
  14181. }
  14182. }
  14183. ContentControl.prototype.dispose = function () {
  14184. if (this.isDisposed) {
  14185. return false;
  14186. }
  14187. if (this.content && this.content.dispose) {
  14188. this.content.dispose();
  14189. this.content = null;
  14190. }
  14191. if (this.__contentUIElement) {
  14192. this.__contentUIElement.dispose();
  14193. this.__contentUIElement = null;
  14194. }
  14195. _super.prototype.dispose.call(this);
  14196. return true;
  14197. };
  14198. Object.defineProperty(ContentControl.prototype, "content", {
  14199. get: function () {
  14200. return this._content;
  14201. },
  14202. set: function (value) {
  14203. this._content = value;
  14204. },
  14205. enumerable: true,
  14206. configurable: true
  14207. });
  14208. Object.defineProperty(ContentControl.prototype, "_contentUIElement", {
  14209. get: function () {
  14210. if (!this.__contentUIElement) {
  14211. this._buildContentUIElement();
  14212. }
  14213. return this.__contentUIElement;
  14214. },
  14215. enumerable: true,
  14216. configurable: true
  14217. });
  14218. ContentControl.prototype._createVisualTree = function () {
  14219. // Base implementation will create the Group2D for the Visual Placeholder and its Visual Tree
  14220. _super.prototype._createVisualTree.call(this);
  14221. // A Content Control has a Group2D, child of the visualPlaceHolder, which is the Content placeholder.
  14222. // The Content UIElement Tree will be create inside this placeholder.
  14223. this._contentPlaceholder = new BABYLON.Group2D({ parent: this._visualPlaceholder, id: "ContentControl Content Placeholder of " + this.id });
  14224. var p = this._contentPlaceholder;
  14225. // 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.
  14226. p.dataSource = this;
  14227. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginProperty, "padding", BABYLON.DataBinding.MODE_ONEWAY);
  14228. p.createSimpleDataBinding(BABYLON.Prim2DBase.marginAlignmentProperty, "paddingAlignment", BABYLON.DataBinding.MODE_ONEWAY);
  14229. // The UIElement set the childrenPlaceholder with the visual returned by the renderingTemplate.
  14230. // But it's not the case for a ContentControl, the placeholder of UIElement Children (the content)
  14231. this._visualChildrenPlaceholder = this._contentPlaceholder;
  14232. };
  14233. ContentControl.prototype._buildContentUIElement = function () {
  14234. var c = this._content;
  14235. this.__contentUIElement = null;
  14236. // Already a UIElement
  14237. if (c instanceof BABYLON.UIElement) {
  14238. this.__contentUIElement = c;
  14239. }
  14240. else if ((typeof c === "string") || (typeof c === "boolean") || (typeof c === "number")) {
  14241. var l = new BABYLON.Label({ parent: this, id: "Content of " + this.id });
  14242. var binding = new BABYLON.DataBinding();
  14243. binding.propertyPathName = "content";
  14244. binding.stringFormat = function (v) { return ("" + v); };
  14245. binding.dataSource = this;
  14246. l.createDataBinding(BABYLON.Label.textProperty, binding);
  14247. this.__contentUIElement = l;
  14248. }
  14249. else {
  14250. }
  14251. if (this.__contentUIElement) {
  14252. this.__contentUIElement._patchUIElement(this.ownerWindow, this);
  14253. }
  14254. };
  14255. ContentControl.prototype._getChildren = function () {
  14256. var children = new Array();
  14257. if (this.content) {
  14258. children.push(this._contentUIElement);
  14259. }
  14260. return children;
  14261. };
  14262. ContentControl.CONTENTCONTROL_PROPCOUNT = BABYLON.Control.CONTROL_PROPCOUNT + 2;
  14263. __decorate([
  14264. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return ContentControl.contentProperty = pi; })
  14265. ], ContentControl.prototype, "content", null);
  14266. ContentControl = __decorate([
  14267. BABYLON.className("ContentControl", "BABYLON")
  14268. ], ContentControl);
  14269. return ContentControl;
  14270. }(BABYLON.Control));
  14271. BABYLON.ContentControl = ContentControl;
  14272. })(BABYLON || (BABYLON = {}));
  14273. var BABYLON;
  14274. (function (BABYLON) {
  14275. var FocusScopeData = (function () {
  14276. function FocusScopeData(focusScope) {
  14277. this.focusScope = focusScope;
  14278. this.focusedElement = null;
  14279. }
  14280. return FocusScopeData;
  14281. }());
  14282. var FocusManager = (function () {
  14283. function FocusManager() {
  14284. this._focusScopes = new BABYLON.StringDictionary();
  14285. this._rootScope = new FocusScopeData(null);
  14286. this._activeScope = null;
  14287. }
  14288. FocusManager.prototype.setFocusOn = function (el, focusScope) {
  14289. var fsd = (focusScope != null) ? this._focusScopes.getOrAddWithFactory(focusScope.uid, function (k) { return new FocusScopeData(focusScope); }) : this._rootScope;
  14290. if (fsd.focusedElement !== el) {
  14291. // Remove focus from current
  14292. if (fsd.focusedElement) {
  14293. fsd.focusedElement.isFocused = false;
  14294. }
  14295. fsd.focusedElement = el;
  14296. }
  14297. if (this._activeScope !== fsd) {
  14298. this._activeScope = fsd;
  14299. }
  14300. };
  14301. return FocusManager;
  14302. }());
  14303. BABYLON.FocusManager = FocusManager;
  14304. var GUISceneData = (function () {
  14305. function GUISceneData(scene) {
  14306. this.scene = scene;
  14307. this.screenSpaceCanvas = new BABYLON.ScreenSpaceCanvas2D(scene, { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE });
  14308. this.focusManager = new FocusManager();
  14309. }
  14310. return GUISceneData;
  14311. }());
  14312. var Window = (function (_super) {
  14313. __extends(Window, _super);
  14314. function Window(scene, settings) {
  14315. var _this = this;
  14316. if (!settings) {
  14317. settings = {};
  14318. }
  14319. _super.call(this, settings);
  14320. // Per default a Window is focus scope
  14321. this.isFocusScope = true;
  14322. this.isActive = false;
  14323. if (!this._UIElementVisualToBuildList) {
  14324. this._UIElementVisualToBuildList = new Array();
  14325. }
  14326. // Patch the owner and also the parent property through the whole tree
  14327. this._patchUIElement(this, null);
  14328. // Screen Space UI
  14329. if (!settings.worldPosition && !settings.worldRotation) {
  14330. this._sceneData = Window.getSceneData(scene);
  14331. this._canvas = this._sceneData.screenSpaceCanvas;
  14332. this._isWorldSpaceCanvas = false;
  14333. this._left = (settings.left != null) ? settings.left : 0;
  14334. this._bottom = (settings.bottom != null) ? settings.bottom : 0;
  14335. }
  14336. else {
  14337. var w = (settings.width == null) ? 100 : settings.width;
  14338. var h = (settings.height == null) ? 100 : settings.height;
  14339. var wpos = (settings.worldPosition == null) ? BABYLON.Vector3.Zero() : settings.worldPosition;
  14340. var wrot = (settings.worldRotation == null) ? BABYLON.Quaternion.Identity() : settings.worldRotation;
  14341. this._canvas = new BABYLON.WorldSpaceCanvas2D(scene, new BABYLON.Size(w, h), { id: "GUI Canvas", cachingStrategy: BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE, worldPosition: wpos, worldRotation: wrot });
  14342. this._isWorldSpaceCanvas = true;
  14343. }
  14344. this._renderObserver = this._canvas.renderObservable.add(function (e, s) { return _this._canvasPreRender(); }, BABYLON.Canvas2D.RENDEROBSERVABLE_PRE);
  14345. this._disposeObserver = this._canvas.disposeObservable.add(function (e, s) { return _this._canvasDisposed(); });
  14346. this._canvas.propertyChanged.add(function (e, s) {
  14347. if (e.propertyName === "overPrim") {
  14348. _this._overPrimChanged(e.oldValue, e.newValue);
  14349. }
  14350. });
  14351. this._mouseOverUIElement = null;
  14352. }
  14353. Object.defineProperty(Window.prototype, "canvas", {
  14354. get: function () {
  14355. return this._canvas;
  14356. },
  14357. enumerable: true,
  14358. configurable: true
  14359. });
  14360. Object.defineProperty(Window.prototype, "left", {
  14361. get: function () {
  14362. return this._left;
  14363. },
  14364. set: function (value) {
  14365. var old = new BABYLON.Vector2(this._left, this._bottom);
  14366. this._left = value;
  14367. this.onPropertyChanged("_position", old, this._position);
  14368. },
  14369. enumerable: true,
  14370. configurable: true
  14371. });
  14372. Object.defineProperty(Window.prototype, "bottom", {
  14373. get: function () {
  14374. return this._bottom;
  14375. },
  14376. set: function (value) {
  14377. var old = new BABYLON.Vector2(this._left, this._bottom);
  14378. this._bottom = value;
  14379. this.onPropertyChanged("_position", old, this._position);
  14380. },
  14381. enumerable: true,
  14382. configurable: true
  14383. });
  14384. Object.defineProperty(Window.prototype, "position", {
  14385. get: function () {
  14386. return this._position;
  14387. },
  14388. set: function (value) {
  14389. this._left = value.x;
  14390. this._bottom = value.y;
  14391. },
  14392. enumerable: true,
  14393. configurable: true
  14394. });
  14395. Object.defineProperty(Window.prototype, "isActive", {
  14396. get: function () {
  14397. return this._isActive;
  14398. },
  14399. set: function (value) {
  14400. this._isActive = value;
  14401. },
  14402. enumerable: true,
  14403. configurable: true
  14404. });
  14405. Object.defineProperty(Window.prototype, "focusManager", {
  14406. get: function () {
  14407. return this._sceneData.focusManager;
  14408. },
  14409. enumerable: true,
  14410. configurable: true
  14411. });
  14412. Object.defineProperty(Window.prototype, "_position", {
  14413. get: function () {
  14414. return new BABYLON.Vector2(this.left, this.bottom);
  14415. },
  14416. enumerable: true,
  14417. configurable: true
  14418. });
  14419. Window.prototype.createVisualTree = function () {
  14420. _super.prototype.createVisualTree.call(this);
  14421. var p = this._visualPlaceholder;
  14422. p.createSimpleDataBinding(BABYLON.Group2D.positionProperty, "position");
  14423. };
  14424. Window.prototype._registerVisualToBuild = function (uiel) {
  14425. if (uiel._isFlagSet(BABYLON.UIElement.flagVisualToBuild)) {
  14426. return;
  14427. }
  14428. if (!this._UIElementVisualToBuildList) {
  14429. this._UIElementVisualToBuildList = new Array();
  14430. }
  14431. this._UIElementVisualToBuildList.push(uiel);
  14432. uiel._setFlags(BABYLON.UIElement.flagVisualToBuild);
  14433. };
  14434. Window.prototype._overPrimChanged = function (oldPrim, newPrim) {
  14435. var curOverEl = this._mouseOverUIElement;
  14436. var newOverEl = null;
  14437. var curGroup = newPrim ? newPrim.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  14438. while (curGroup) {
  14439. var uiel = curGroup.getExternalData("_GUIOwnerElement_");
  14440. if (uiel) {
  14441. newOverEl = uiel;
  14442. break;
  14443. }
  14444. curGroup = curGroup.parent ? curGroup.parent.traverseUp(function (p) { return p instanceof BABYLON.Group2D; }) : null;
  14445. }
  14446. if (curOverEl === newOverEl) {
  14447. return;
  14448. }
  14449. if (curOverEl) {
  14450. curOverEl.isMouseOver = false;
  14451. }
  14452. if (newOverEl) {
  14453. newOverEl.isMouseOver = true;
  14454. }
  14455. this._mouseOverUIElement = newOverEl;
  14456. };
  14457. Window.prototype._canvasPreRender = function () {
  14458. // Check if we have visual to create
  14459. if (this._UIElementVisualToBuildList.length > 0) {
  14460. // Sort the UI Element to get the highest (so lowest hierarchy depth) in the hierarchy tree first
  14461. var sortedElementList = this._UIElementVisualToBuildList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  14462. for (var _i = 0, sortedElementList_1 = sortedElementList; _i < sortedElementList_1.length; _i++) {
  14463. var el = sortedElementList_1[_i];
  14464. el._createVisualTree();
  14465. }
  14466. this._UIElementVisualToBuildList.splice(0);
  14467. }
  14468. };
  14469. Window.prototype._canvasDisposed = function () {
  14470. this._canvas.disposeObservable.remove(this._disposeObserver);
  14471. this._canvas.renderObservable.remove(this._renderObserver);
  14472. };
  14473. Window.getSceneData = function (scene) {
  14474. return Window._sceneData.getOrAddWithFactory(scene.uid, function (k) { return new GUISceneData(scene); });
  14475. };
  14476. Window.WINDOW_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 4;
  14477. Window._sceneData = new BABYLON.StringDictionary();
  14478. __decorate([
  14479. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 0, function (pi) { return Window.leftProperty = pi; })
  14480. ], Window.prototype, "left", null);
  14481. __decorate([
  14482. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 1, function (pi) { return Window.bottomProperty = pi; })
  14483. ], Window.prototype, "bottom", null);
  14484. __decorate([
  14485. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 2, function (pi) { return Window.positionProperty = pi; })
  14486. ], Window.prototype, "position", null);
  14487. __decorate([
  14488. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3, function (pi) { return Window.isActiveProperty = pi; })
  14489. ], Window.prototype, "isActive", null);
  14490. Window = __decorate([
  14491. BABYLON.className("Window", "BABYLON")
  14492. ], Window);
  14493. return Window;
  14494. }(BABYLON.ContentControl));
  14495. BABYLON.Window = Window;
  14496. var DefaultWindowRenderingTemplate = (function (_super) {
  14497. __extends(DefaultWindowRenderingTemplate, _super);
  14498. function DefaultWindowRenderingTemplate() {
  14499. _super.apply(this, arguments);
  14500. }
  14501. DefaultWindowRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  14502. var r = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#808080FF" });
  14503. return { root: r, contentPlaceholder: r };
  14504. };
  14505. DefaultWindowRenderingTemplate = __decorate([
  14506. BABYLON.registerWindowRenderingTemplate("BABYLON.Window", "Default", function () { return new DefaultWindowRenderingTemplate(); })
  14507. ], DefaultWindowRenderingTemplate);
  14508. return DefaultWindowRenderingTemplate;
  14509. }(BABYLON.UIElementRenderingTemplateBase));
  14510. BABYLON.DefaultWindowRenderingTemplate = DefaultWindowRenderingTemplate;
  14511. })(BABYLON || (BABYLON = {}));
  14512. var BABYLON;
  14513. (function (BABYLON) {
  14514. var Label = (function (_super) {
  14515. __extends(Label, _super);
  14516. function Label(settings) {
  14517. if (!settings) {
  14518. settings = {};
  14519. }
  14520. _super.call(this, settings);
  14521. if (settings.text != null) {
  14522. this.text = settings.text;
  14523. }
  14524. }
  14525. Object.defineProperty(Label.prototype, "_position", {
  14526. get: function () {
  14527. return BABYLON.Vector2.Zero();
  14528. },
  14529. enumerable: true,
  14530. configurable: true
  14531. });
  14532. Label.prototype._getChildren = function () {
  14533. return Label._emptyArray;
  14534. };
  14535. Label.prototype.createVisualTree = function () {
  14536. _super.prototype.createVisualTree.call(this);
  14537. var p = this._visualChildrenPlaceholder;
  14538. };
  14539. Object.defineProperty(Label.prototype, "text", {
  14540. get: function () {
  14541. return this._text;
  14542. },
  14543. set: function (value) {
  14544. this._text = value;
  14545. },
  14546. enumerable: true,
  14547. configurable: true
  14548. });
  14549. Label._emptyArray = new Array();
  14550. __decorate([
  14551. BABYLON.dependencyProperty(BABYLON.Control.CONTROL_PROPCOUNT + 0, function (pi) { return Label.textProperty = pi; })
  14552. ], Label.prototype, "text", null);
  14553. Label = __decorate([
  14554. BABYLON.className("Label", "BABYLON")
  14555. ], Label);
  14556. return Label;
  14557. }(BABYLON.Control));
  14558. BABYLON.Label = Label;
  14559. var DefaultLabelRenderingTemplate = (function (_super) {
  14560. __extends(DefaultLabelRenderingTemplate, _super);
  14561. function DefaultLabelRenderingTemplate() {
  14562. _super.apply(this, arguments);
  14563. }
  14564. DefaultLabelRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  14565. var r = new BABYLON.Text2D("", { parent: visualPlaceholder });
  14566. r.createSimpleDataBinding(BABYLON.Text2D.textProperty, "text");
  14567. r.dataSource = owner;
  14568. return { root: r, contentPlaceholder: r };
  14569. };
  14570. DefaultLabelRenderingTemplate = __decorate([
  14571. BABYLON.registerWindowRenderingTemplate("BABYLON.Label", "Default", function () { return new DefaultLabelRenderingTemplate(); })
  14572. ], DefaultLabelRenderingTemplate);
  14573. return DefaultLabelRenderingTemplate;
  14574. }(BABYLON.UIElementRenderingTemplateBase));
  14575. BABYLON.DefaultLabelRenderingTemplate = DefaultLabelRenderingTemplate;
  14576. })(BABYLON || (BABYLON = {}));
  14577. var BABYLON;
  14578. (function (BABYLON) {
  14579. var Button = (function (_super) {
  14580. __extends(Button, _super);
  14581. function Button(settings) {
  14582. if (!settings) {
  14583. settings = {};
  14584. }
  14585. _super.call(this, settings);
  14586. if (settings.paddingAlignment == null) {
  14587. this.paddingAlignment.horizontal = BABYLON.PrimitiveAlignment.AlignCenter;
  14588. this.paddingAlignment.vertical = BABYLON.PrimitiveAlignment.AlignCenter;
  14589. }
  14590. this._normalStateBackground = new BABYLON.ObservableStringDictionary(false);
  14591. this._normalStateBorder = new BABYLON.ObservableStringDictionary(false);
  14592. this._defaultStateBackground = new BABYLON.ObservableStringDictionary(false);
  14593. this._defaultStateBorder = new BABYLON.ObservableStringDictionary(false);
  14594. this._normalStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#337AB7FF"));
  14595. this._normalStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#7BA9D0FF"));
  14596. this._normalStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#286090FF"));
  14597. this._normalStateBackground.add(Button.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#1E496EFF"));
  14598. this._normalStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E6DA4FF"));
  14599. this._normalStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#77A0C4FF"));
  14600. this._normalStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#204D74FF"));
  14601. this._normalStateBorder.add(Button.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#2E5D9EFF"));
  14602. this._defaultStateBackground.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  14603. this._defaultStateBackground.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#FFFFFFFF"));
  14604. this._defaultStateBackground.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#E6E6E6FF"));
  14605. this._defaultStateBackground.add(Button.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#D4D4D4FF"));
  14606. this._defaultStateBorder.add(BABYLON.UIElement.enabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#CCCCCCFF"));
  14607. this._defaultStateBorder.add(BABYLON.UIElement.disabledState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#DEDEDEFF"));
  14608. this._defaultStateBorder.add(BABYLON.UIElement.mouseOverState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#ADADADFF"));
  14609. this._defaultStateBorder.add(Button.pushedState, BABYLON.Canvas2D.GetSolidColorBrushFromHex("#6C8EC5FF"));
  14610. }
  14611. Object.defineProperty(Button, "pushedState", {
  14612. get: function () {
  14613. return Button._pushedState;
  14614. },
  14615. enumerable: true,
  14616. configurable: true
  14617. });
  14618. Object.defineProperty(Button.prototype, "isPushed", {
  14619. get: function () {
  14620. return this._isPushed;
  14621. },
  14622. set: function (value) {
  14623. this._isPushed = value;
  14624. },
  14625. enumerable: true,
  14626. configurable: true
  14627. });
  14628. Object.defineProperty(Button.prototype, "isDefault", {
  14629. get: function () {
  14630. return this._isDefault;
  14631. },
  14632. set: function (value) {
  14633. this._isDefault = value;
  14634. },
  14635. enumerable: true,
  14636. configurable: true
  14637. });
  14638. Object.defineProperty(Button.prototype, "isOutline", {
  14639. get: function () {
  14640. return this._isOutline;
  14641. },
  14642. set: function (value) {
  14643. this._isOutline = value;
  14644. },
  14645. enumerable: true,
  14646. configurable: true
  14647. });
  14648. Object.defineProperty(Button.prototype, "clickObservable", {
  14649. get: function () {
  14650. if (!this._clickObservable) {
  14651. this._clickObservable = new BABYLON.Observable();
  14652. }
  14653. return this._clickObservable;
  14654. },
  14655. enumerable: true,
  14656. configurable: true
  14657. });
  14658. Button.prototype._raiseClick = function () {
  14659. if (this._clickObservable && this._clickObservable.hasObservers()) {
  14660. this._clickObservable.notifyObservers(this);
  14661. }
  14662. };
  14663. Button.prototype.createVisualTree = function () {
  14664. var _this = this;
  14665. _super.prototype.createVisualTree.call(this);
  14666. var p = this._visualPlaceholder;
  14667. p.pointerEventObservable.add(function (e, s) {
  14668. // check if input must be discarded
  14669. if (!_this.isVisible || !_this.isEnabled) {
  14670. return;
  14671. }
  14672. // We reject an event coming from the placeholder because it means it's on an empty spot, so it's not valid.
  14673. if (e.relatedTarget === _this._visualPlaceholder) {
  14674. return;
  14675. }
  14676. if (s.mask === BABYLON.PrimitivePointerInfo.PointerUp) {
  14677. _this._raiseClick();
  14678. _this.isPushed = false;
  14679. }
  14680. else if (s.mask === BABYLON.PrimitivePointerInfo.PointerDown) {
  14681. _this.isPushed = true;
  14682. _this.isFocused = true;
  14683. }
  14684. }, BABYLON.PrimitivePointerInfo.PointerUp | BABYLON.PrimitivePointerInfo.PointerDown);
  14685. };
  14686. Object.defineProperty(Button.prototype, "normalStateBackground", {
  14687. get: function () {
  14688. return this._normalStateBackground;
  14689. },
  14690. enumerable: true,
  14691. configurable: true
  14692. });
  14693. Object.defineProperty(Button.prototype, "defaultStateBackground", {
  14694. get: function () {
  14695. return this._defaultStateBackground;
  14696. },
  14697. enumerable: true,
  14698. configurable: true
  14699. });
  14700. Object.defineProperty(Button.prototype, "normalStateBorder", {
  14701. get: function () {
  14702. return this._normalStateBorder;
  14703. },
  14704. enumerable: true,
  14705. configurable: true
  14706. });
  14707. Object.defineProperty(Button.prototype, "defaultStateBorder", {
  14708. get: function () {
  14709. return this._defaultStateBorder;
  14710. },
  14711. enumerable: true,
  14712. configurable: true
  14713. });
  14714. Button.BUTTON_PROPCOUNT = BABYLON.ContentControl.CONTENTCONTROL_PROPCOUNT + 3;
  14715. Button._pushedState = "Pushed";
  14716. __decorate([
  14717. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 0, function (pi) { return Button.isPushedProperty = pi; })
  14718. ], Button.prototype, "isPushed", null);
  14719. __decorate([
  14720. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 1, function (pi) { return Button.isDefaultProperty = pi; })
  14721. ], Button.prototype, "isDefault", null);
  14722. __decorate([
  14723. BABYLON.dependencyProperty(BABYLON.ContentControl.CONTROL_PROPCOUNT + 2, function (pi) { return Button.isOutlineProperty = pi; })
  14724. ], Button.prototype, "isOutline", null);
  14725. Button = __decorate([
  14726. BABYLON.className("Button", "BABYLON")
  14727. ], Button);
  14728. return Button;
  14729. }(BABYLON.ContentControl));
  14730. BABYLON.Button = Button;
  14731. var DefaultButtonRenderingTemplate = (function (_super) {
  14732. __extends(DefaultButtonRenderingTemplate, _super);
  14733. function DefaultButtonRenderingTemplate() {
  14734. _super.apply(this, arguments);
  14735. }
  14736. DefaultButtonRenderingTemplate.prototype.createVisualTree = function (owner, visualPlaceholder) {
  14737. this._rect = new BABYLON.Rectangle2D({ parent: visualPlaceholder, fill: "#FF8080FF", border: "#FF8080FF", roundRadius: 10, borderThickness: 2 });
  14738. this.stateChange();
  14739. return { root: this._rect, contentPlaceholder: this._rect };
  14740. };
  14741. DefaultButtonRenderingTemplate.prototype.attach = function (owner) {
  14742. var _this = this;
  14743. _super.prototype.attach.call(this, owner);
  14744. this.owner.propertyChanged.add(function (e, s) { return _this.stateChange(); }, BABYLON.UIElement.isEnabledProperty.flagId |
  14745. BABYLON.UIElement.isFocusedProperty.flagId |
  14746. BABYLON.UIElement.isMouseOverProperty.flagId |
  14747. Button.isDefaultProperty.flagId |
  14748. Button.isOutlineProperty.flagId |
  14749. Button.isPushedProperty.flagId);
  14750. // Register for brush change and update the Visual
  14751. var button = owner;
  14752. button.normalStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  14753. button.normalStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  14754. button.defaultStateBackground.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  14755. button.defaultStateBorder.dictionaryChanged.add(function (e, c) { return _this.stateChange(); });
  14756. };
  14757. DefaultButtonRenderingTemplate.prototype.stateChange = function () {
  14758. //console.log("state changed");
  14759. var b = this.owner;
  14760. var state = BABYLON.UIElement.enabledState;
  14761. var bg = b.isDefault ? b.defaultStateBackground.get(state) : b.normalStateBackground.get(state);
  14762. var bd = b.isDefault ? b.defaultStateBorder.get(state) : b.normalStateBorder.get(state);
  14763. if (b.isPushed) {
  14764. state = Button.pushedState;
  14765. if (b.isDefault) {
  14766. bg = b.defaultStateBackground.get(state);
  14767. bd = b.defaultStateBorder.get(state);
  14768. }
  14769. else {
  14770. bg = b.normalStateBackground.get(state);
  14771. bd = b.normalStateBorder.get(state);
  14772. }
  14773. }
  14774. else if (b.isMouseOver) {
  14775. state = BABYLON.UIElement.mouseOverState;
  14776. if (b.isDefault) {
  14777. bg = b.defaultStateBackground.get(state);
  14778. bd = b.defaultStateBorder.get(state);
  14779. }
  14780. else {
  14781. bg = b.normalStateBackground.get(state);
  14782. bd = b.normalStateBorder.get(state);
  14783. }
  14784. }
  14785. else if (!b.isEnabled) {
  14786. state = BABYLON.UIElement.disabledState;
  14787. if (b.isDefault) {
  14788. bg = b.defaultStateBackground.get(state);
  14789. bd = b.defaultStateBorder.get(state);
  14790. }
  14791. else {
  14792. bg = b.normalStateBackground.get(state);
  14793. bd = b.normalStateBorder.get(state);
  14794. }
  14795. }
  14796. this._rect.fill = bg;
  14797. this._rect.border = bd;
  14798. };
  14799. DefaultButtonRenderingTemplate = __decorate([
  14800. BABYLON.registerWindowRenderingTemplate("BABYLON.Button", "Default", function () { return new DefaultButtonRenderingTemplate(); })
  14801. ], DefaultButtonRenderingTemplate);
  14802. return DefaultButtonRenderingTemplate;
  14803. }(BABYLON.UIElementRenderingTemplateBase));
  14804. BABYLON.DefaultButtonRenderingTemplate = DefaultButtonRenderingTemplate;
  14805. })(BABYLON || (BABYLON = {}));
  14806. BABYLON.Effect.ShadersStore['ellipse2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  14807. 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}";
  14808. BABYLON.Effect.ShadersStore['lines2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  14809. 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}";
  14810. BABYLON.Effect.ShadersStore['rect2dPixelShader'] = "varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}";
  14811. 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}";
  14812. BABYLON.Effect.ShadersStore['sprite2dPixelShader'] = "varying vec2 vUV;\nvarying float vOpacity;\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}";
  14813. 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;\natt vec2 scaleFactor;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\nvec2 sfSizeUV=sizeUV*scaleFactor;\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*sfSizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),topLeftUV.y-off.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}\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ";
  14814. BABYLON.Effect.ShadersStore['text2dPixelShader'] = "varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n}";
  14815. 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}";
  14816. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  14817. module.exports = BABYLON;
  14818. };