1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112 |
- (function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.G = {}));
- }(this, (function (exports) { 'use strict';
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
- function createCommonjsModule(fn, basedir, module) {
- return module = {
- path: basedir,
- exports: {},
- require: function (path, base) {
- return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
- }
- }, fn(module, module.exports), module.exports;
- }
- function commonjsRequire () {
- throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
- }
- var rbush = createCommonjsModule(function (module, exports) {
- (function (global, factory) {
- module.exports = factory() ;
- }(commonjsGlobal, function () {
- function quickselect(arr, k, left, right, compare) {
- quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
- }
- function quickselectStep(arr, k, left, right, compare) {
- while (right > left) {
- if (right - left > 600) {
- var n = right - left + 1;
- var m = k - left + 1;
- var z = Math.log(n);
- var s = 0.5 * Math.exp(2 * z / 3);
- var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
- var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
- var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
- quickselectStep(arr, k, newLeft, newRight, compare);
- }
- var t = arr[k];
- var i = left;
- var j = right;
- swap(arr, left, k);
- if (compare(arr[right], t) > 0) { swap(arr, left, right); }
- while (i < j) {
- swap(arr, i, j);
- i++;
- j--;
- while (compare(arr[i], t) < 0) { i++; }
- while (compare(arr[j], t) > 0) { j--; }
- }
- if (compare(arr[left], t) === 0) { swap(arr, left, j); }
- else {
- j++;
- swap(arr, j, right);
- }
- if (j <= k) { left = j + 1; }
- if (k <= j) { right = j - 1; }
- }
- }
- function swap(arr, i, j) {
- var tmp = arr[i];
- arr[i] = arr[j];
- arr[j] = tmp;
- }
- function defaultCompare(a, b) {
- return a < b ? -1 : a > b ? 1 : 0;
- }
- var RBush = function RBush(maxEntries) {
- if ( maxEntries === void 0 ) maxEntries = 9;
- // max entries in a node is 9 by default; min node fill is 40% for best performance
- this._maxEntries = Math.max(4, maxEntries);
- this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
- this.clear();
- };
- RBush.prototype.all = function all () {
- return this._all(this.data, []);
- };
- RBush.prototype.search = function search (bbox) {
- var node = this.data;
- var result = [];
- if (!intersects(bbox, node)) { return result; }
- var toBBox = this.toBBox;
- var nodesToSearch = [];
- while (node) {
- for (var i = 0; i < node.children.length; i++) {
- var child = node.children[i];
- var childBBox = node.leaf ? toBBox(child) : child;
- if (intersects(bbox, childBBox)) {
- if (node.leaf) { result.push(child); }
- else if (contains(bbox, childBBox)) { this._all(child, result); }
- else { nodesToSearch.push(child); }
- }
- }
- node = nodesToSearch.pop();
- }
- return result;
- };
- RBush.prototype.collides = function collides (bbox) {
- var node = this.data;
- if (!intersects(bbox, node)) { return false; }
- var nodesToSearch = [];
- while (node) {
- for (var i = 0; i < node.children.length; i++) {
- var child = node.children[i];
- var childBBox = node.leaf ? this.toBBox(child) : child;
- if (intersects(bbox, childBBox)) {
- if (node.leaf || contains(bbox, childBBox)) { return true; }
- nodesToSearch.push(child);
- }
- }
- node = nodesToSearch.pop();
- }
- return false;
- };
- RBush.prototype.load = function load (data) {
- if (!(data && data.length)) { return this; }
- if (data.length < this._minEntries) {
- for (var i = 0; i < data.length; i++) {
- this.insert(data[i]);
- }
- return this;
- }
- // recursively build the tree with the given data from scratch using OMT algorithm
- var node = this._build(data.slice(), 0, data.length - 1, 0);
- if (!this.data.children.length) {
- // save as is if tree is empty
- this.data = node;
- } else if (this.data.height === node.height) {
- // split root if trees have the same height
- this._splitRoot(this.data, node);
- } else {
- if (this.data.height < node.height) {
- // swap trees if inserted one is bigger
- var tmpNode = this.data;
- this.data = node;
- node = tmpNode;
- }
- // insert the small tree into the large tree at appropriate level
- this._insert(node, this.data.height - node.height - 1, true);
- }
- return this;
- };
- RBush.prototype.insert = function insert (item) {
- if (item) { this._insert(item, this.data.height - 1); }
- return this;
- };
- RBush.prototype.clear = function clear () {
- this.data = createNode([]);
- return this;
- };
- RBush.prototype.remove = function remove (item, equalsFn) {
- if (!item) { return this; }
- var node = this.data;
- var bbox = this.toBBox(item);
- var path = [];
- var indexes = [];
- var i, parent, goingUp;
- // depth-first iterative tree traversal
- while (node || path.length) {
- if (!node) { // go up
- node = path.pop();
- parent = path[path.length - 1];
- i = indexes.pop();
- goingUp = true;
- }
- if (node.leaf) { // check current node
- var index = findItem(item, node.children, equalsFn);
- if (index !== -1) {
- // item found, remove the item and condense tree upwards
- node.children.splice(index, 1);
- path.push(node);
- this._condense(path);
- return this;
- }
- }
- if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
- path.push(node);
- indexes.push(i);
- i = 0;
- parent = node;
- node = node.children[0];
- } else if (parent) { // go right
- i++;
- node = parent.children[i];
- goingUp = false;
- } else { node = null; } // nothing found
- }
- return this;
- };
- RBush.prototype.toBBox = function toBBox (item) { return item; };
- RBush.prototype.compareMinX = function compareMinX (a, b) { return a.minX - b.minX; };
- RBush.prototype.compareMinY = function compareMinY (a, b) { return a.minY - b.minY; };
- RBush.prototype.toJSON = function toJSON () { return this.data; };
- RBush.prototype.fromJSON = function fromJSON (data) {
- this.data = data;
- return this;
- };
- RBush.prototype._all = function _all (node, result) {
- var nodesToSearch = [];
- while (node) {
- if (node.leaf) { result.push.apply(result, node.children); }
- else { nodesToSearch.push.apply(nodesToSearch, node.children); }
- node = nodesToSearch.pop();
- }
- return result;
- };
- RBush.prototype._build = function _build (items, left, right, height) {
- var N = right - left + 1;
- var M = this._maxEntries;
- var node;
- if (N <= M) {
- // reached leaf level; return leaf
- node = createNode(items.slice(left, right + 1));
- calcBBox(node, this.toBBox);
- return node;
- }
- if (!height) {
- // target height of the bulk-loaded tree
- height = Math.ceil(Math.log(N) / Math.log(M));
- // target number of root entries to maximize storage utilization
- M = Math.ceil(N / Math.pow(M, height - 1));
- }
- node = createNode([]);
- node.leaf = false;
- node.height = height;
- // split the items into M mostly square tiles
- var N2 = Math.ceil(N / M);
- var N1 = N2 * Math.ceil(Math.sqrt(M));
- multiSelect(items, left, right, N1, this.compareMinX);
- for (var i = left; i <= right; i += N1) {
- var right2 = Math.min(i + N1 - 1, right);
- multiSelect(items, i, right2, N2, this.compareMinY);
- for (var j = i; j <= right2; j += N2) {
- var right3 = Math.min(j + N2 - 1, right2);
- // pack each entry recursively
- node.children.push(this._build(items, j, right3, height - 1));
- }
- }
- calcBBox(node, this.toBBox);
- return node;
- };
- RBush.prototype._chooseSubtree = function _chooseSubtree (bbox, node, level, path) {
- while (true) {
- path.push(node);
- if (node.leaf || path.length - 1 === level) { break; }
- var minArea = Infinity;
- var minEnlargement = Infinity;
- var targetNode = (void 0);
- for (var i = 0; i < node.children.length; i++) {
- var child = node.children[i];
- var area = bboxArea(child);
- var enlargement = enlargedArea(bbox, child) - area;
- // choose entry with the least area enlargement
- if (enlargement < minEnlargement) {
- minEnlargement = enlargement;
- minArea = area < minArea ? area : minArea;
- targetNode = child;
- } else if (enlargement === minEnlargement) {
- // otherwise choose one with the smallest area
- if (area < minArea) {
- minArea = area;
- targetNode = child;
- }
- }
- }
- node = targetNode || node.children[0];
- }
- return node;
- };
- RBush.prototype._insert = function _insert (item, level, isNode) {
- var bbox = isNode ? item : this.toBBox(item);
- var insertPath = [];
- // find the best node for accommodating the item, saving all nodes along the path too
- var node = this._chooseSubtree(bbox, this.data, level, insertPath);
- // put the item into the node
- node.children.push(item);
- extend(node, bbox);
- // split on node overflow; propagate upwards if necessary
- while (level >= 0) {
- if (insertPath[level].children.length > this._maxEntries) {
- this._split(insertPath, level);
- level--;
- } else { break; }
- }
- // adjust bboxes along the insertion path
- this._adjustParentBBoxes(bbox, insertPath, level);
- };
- // split overflowed node into two
- RBush.prototype._split = function _split (insertPath, level) {
- var node = insertPath[level];
- var M = node.children.length;
- var m = this._minEntries;
- this._chooseSplitAxis(node, m, M);
- var splitIndex = this._chooseSplitIndex(node, m, M);
- var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
- newNode.height = node.height;
- newNode.leaf = node.leaf;
- calcBBox(node, this.toBBox);
- calcBBox(newNode, this.toBBox);
- if (level) { insertPath[level - 1].children.push(newNode); }
- else { this._splitRoot(node, newNode); }
- };
- RBush.prototype._splitRoot = function _splitRoot (node, newNode) {
- // split root node
- this.data = createNode([node, newNode]);
- this.data.height = node.height + 1;
- this.data.leaf = false;
- calcBBox(this.data, this.toBBox);
- };
- RBush.prototype._chooseSplitIndex = function _chooseSplitIndex (node, m, M) {
- var index;
- var minOverlap = Infinity;
- var minArea = Infinity;
- for (var i = m; i <= M - m; i++) {
- var bbox1 = distBBox(node, 0, i, this.toBBox);
- var bbox2 = distBBox(node, i, M, this.toBBox);
- var overlap = intersectionArea(bbox1, bbox2);
- var area = bboxArea(bbox1) + bboxArea(bbox2);
- // choose distribution with minimum overlap
- if (overlap < minOverlap) {
- minOverlap = overlap;
- index = i;
- minArea = area < minArea ? area : minArea;
- } else if (overlap === minOverlap) {
- // otherwise choose distribution with minimum area
- if (area < minArea) {
- minArea = area;
- index = i;
- }
- }
- }
- return index || M - m;
- };
- // sorts node children by the best axis for split
- RBush.prototype._chooseSplitAxis = function _chooseSplitAxis (node, m, M) {
- var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;
- var compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;
- var xMargin = this._allDistMargin(node, m, M, compareMinX);
- var yMargin = this._allDistMargin(node, m, M, compareMinY);
- // if total distributions margin value is minimal for x, sort by minX,
- // otherwise it's already sorted by minY
- if (xMargin < yMargin) { node.children.sort(compareMinX); }
- };
- // total margin of all possible split distributions where each node is at least m full
- RBush.prototype._allDistMargin = function _allDistMargin (node, m, M, compare) {
- node.children.sort(compare);
- var toBBox = this.toBBox;
- var leftBBox = distBBox(node, 0, m, toBBox);
- var rightBBox = distBBox(node, M - m, M, toBBox);
- var margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);
- for (var i = m; i < M - m; i++) {
- var child = node.children[i];
- extend(leftBBox, node.leaf ? toBBox(child) : child);
- margin += bboxMargin(leftBBox);
- }
- for (var i$1 = M - m - 1; i$1 >= m; i$1--) {
- var child$1 = node.children[i$1];
- extend(rightBBox, node.leaf ? toBBox(child$1) : child$1);
- margin += bboxMargin(rightBBox);
- }
- return margin;
- };
- RBush.prototype._adjustParentBBoxes = function _adjustParentBBoxes (bbox, path, level) {
- // adjust bboxes along the given tree path
- for (var i = level; i >= 0; i--) {
- extend(path[i], bbox);
- }
- };
- RBush.prototype._condense = function _condense (path) {
- // go through the path, removing empty nodes and updating bboxes
- for (var i = path.length - 1, siblings = (void 0); i >= 0; i--) {
- if (path[i].children.length === 0) {
- if (i > 0) {
- siblings = path[i - 1].children;
- siblings.splice(siblings.indexOf(path[i]), 1);
- } else { this.clear(); }
- } else { calcBBox(path[i], this.toBBox); }
- }
- };
- function findItem(item, items, equalsFn) {
- if (!equalsFn) { return items.indexOf(item); }
- for (var i = 0; i < items.length; i++) {
- if (equalsFn(item, items[i])) { return i; }
- }
- return -1;
- }
- // calculate node's bbox from bboxes of its children
- function calcBBox(node, toBBox) {
- distBBox(node, 0, node.children.length, toBBox, node);
- }
- // min bounding rectangle of node children from k to p-1
- function distBBox(node, k, p, toBBox, destNode) {
- if (!destNode) { destNode = createNode(null); }
- destNode.minX = Infinity;
- destNode.minY = Infinity;
- destNode.maxX = -Infinity;
- destNode.maxY = -Infinity;
- for (var i = k; i < p; i++) {
- var child = node.children[i];
- extend(destNode, node.leaf ? toBBox(child) : child);
- }
- return destNode;
- }
- function extend(a, b) {
- a.minX = Math.min(a.minX, b.minX);
- a.minY = Math.min(a.minY, b.minY);
- a.maxX = Math.max(a.maxX, b.maxX);
- a.maxY = Math.max(a.maxY, b.maxY);
- return a;
- }
- function compareNodeMinX(a, b) { return a.minX - b.minX; }
- function compareNodeMinY(a, b) { return a.minY - b.minY; }
- function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
- function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
- function enlargedArea(a, b) {
- return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
- (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
- }
- function intersectionArea(a, b) {
- var minX = Math.max(a.minX, b.minX);
- var minY = Math.max(a.minY, b.minY);
- var maxX = Math.min(a.maxX, b.maxX);
- var maxY = Math.min(a.maxY, b.maxY);
- return Math.max(0, maxX - minX) *
- Math.max(0, maxY - minY);
- }
- function contains(a, b) {
- return a.minX <= b.minX &&
- a.minY <= b.minY &&
- b.maxX <= a.maxX &&
- b.maxY <= a.maxY;
- }
- function intersects(a, b) {
- return b.minX <= a.maxX &&
- b.minY <= a.maxY &&
- b.maxX >= a.minX &&
- b.maxY >= a.minY;
- }
- function createNode(children) {
- return {
- children: children,
- height: 1,
- leaf: true,
- minX: Infinity,
- minY: Infinity,
- maxX: -Infinity,
- maxY: -Infinity
- };
- }
- // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
- // combines selection algorithm with binary divide & conquer approach
- function multiSelect(arr, left, right, n, compare) {
- var stack = [left, right];
- while (stack.length) {
- right = stack.pop();
- left = stack.pop();
- if (right - left <= n) { continue; }
- var mid = left + Math.ceil((right - left) / n / 2) * n;
- quickselect(arr, mid, left, right, compare);
- stack.push(left, mid, mid, right);
- }
- }
- return RBush;
- }));
- });
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type
- */
- (function (PropertySyntax) {
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#coordinate
- */
- PropertySyntax["COORDINATE"] = "<coordinate>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#color
- */
- PropertySyntax["COLOR"] = "<color>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#paint
- */
- PropertySyntax["PAINT"] = "<paint>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#number
- */
- PropertySyntax["NUMBER"] = "<number>";
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/angle
- */
- PropertySyntax["ANGLE"] = "<angle>";
- /**
- * <number> with range 0..1
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#opacity_value
- */
- PropertySyntax["OPACITY_VALUE"] = "<opacity-value>";
- /**
- * <number> with range 0..Infinity
- */
- PropertySyntax["SHADOW_BLUR"] = "<shadow-blur>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#length
- */
- PropertySyntax["LENGTH"] = "<length>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#percentage
- */
- PropertySyntax["PERCENTAGE"] = "<percentage>";
- PropertySyntax["LENGTH_PERCENTAGE"] = "<length> | <percentage>";
- PropertySyntax["LENGTH_PERCENTAGE_12"] = "[<length> | <percentage>]{1,2}";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin#formal_syntax
- */
- PropertySyntax["LENGTH_PERCENTAGE_14"] = "[<length> | <percentage>]{1,4}";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#list-of-ts
- */
- PropertySyntax["LIST_OF_POINTS"] = "<list-of-points>";
- PropertySyntax["PATH"] = "<path>";
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/filter#formal_syntax
- */
- PropertySyntax["FILTER"] = "<filter>";
- PropertySyntax["Z_INDEX"] = "<z-index>";
- PropertySyntax["OFFSET_DISTANCE"] = "<offset-distance>";
- PropertySyntax["DEFINED_PATH"] = "<defined-path>";
- PropertySyntax["MARKER"] = "<marker>";
- PropertySyntax["TRANSFORM"] = "<transform>";
- PropertySyntax["TRANSFORM_ORIGIN"] = "<transform-origin>";
- PropertySyntax["TEXT"] = "<text>";
- PropertySyntax["TEXT_TRANSFORM"] = "<text-transform>";
- })(exports.PropertySyntax || (exports.PropertySyntax = {}));
- function _regeneratorRuntime() {
- _regeneratorRuntime = function () {
- return exports;
- };
- var exports = {},
- Op = Object.prototype,
- hasOwn = Op.hasOwnProperty,
- defineProperty = Object.defineProperty || function (obj, key, desc) {
- obj[key] = desc.value;
- },
- $Symbol = "function" == typeof Symbol ? Symbol : {},
- iteratorSymbol = $Symbol.iterator || "@@iterator",
- asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
- toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
- function define(obj, key, value) {
- return Object.defineProperty(obj, key, {
- value: value,
- enumerable: !0,
- configurable: !0,
- writable: !0
- }), obj[key];
- }
- try {
- define({}, "");
- } catch (err) {
- define = function (obj, key, value) {
- return obj[key] = value;
- };
- }
- function wrap(innerFn, outerFn, self, tryLocsList) {
- var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
- generator = Object.create(protoGenerator.prototype),
- context = new Context(tryLocsList || []);
- return defineProperty(generator, "_invoke", {
- value: makeInvokeMethod(innerFn, self, context)
- }), generator;
- }
- function tryCatch(fn, obj, arg) {
- try {
- return {
- type: "normal",
- arg: fn.call(obj, arg)
- };
- } catch (err) {
- return {
- type: "throw",
- arg: err
- };
- }
- }
- exports.wrap = wrap;
- var ContinueSentinel = {};
- function Generator() {}
- function GeneratorFunction() {}
- function GeneratorFunctionPrototype() {}
- var IteratorPrototype = {};
- define(IteratorPrototype, iteratorSymbol, function () {
- return this;
- });
- var getProto = Object.getPrototypeOf,
- NativeIteratorPrototype = getProto && getProto(getProto(values([])));
- NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
- var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
- function defineIteratorMethods(prototype) {
- ["next", "throw", "return"].forEach(function (method) {
- define(prototype, method, function (arg) {
- return this._invoke(method, arg);
- });
- });
- }
- function AsyncIterator(generator, PromiseImpl) {
- function invoke(method, arg, resolve, reject) {
- var record = tryCatch(generator[method], generator, arg);
- if ("throw" !== record.type) {
- var result = record.arg,
- value = result.value;
- return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
- invoke("next", value, resolve, reject);
- }, function (err) {
- invoke("throw", err, resolve, reject);
- }) : PromiseImpl.resolve(value).then(function (unwrapped) {
- result.value = unwrapped, resolve(result);
- }, function (error) {
- return invoke("throw", error, resolve, reject);
- });
- }
- reject(record.arg);
- }
- var previousPromise;
- defineProperty(this, "_invoke", {
- value: function (method, arg) {
- function callInvokeWithMethodAndArg() {
- return new PromiseImpl(function (resolve, reject) {
- invoke(method, arg, resolve, reject);
- });
- }
- return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
- }
- });
- }
- function makeInvokeMethod(innerFn, self, context) {
- var state = "suspendedStart";
- return function (method, arg) {
- if ("executing" === state) throw new Error("Generator is already running");
- if ("completed" === state) {
- if ("throw" === method) throw arg;
- return doneResult();
- }
- for (context.method = method, context.arg = arg;;) {
- var delegate = context.delegate;
- if (delegate) {
- var delegateResult = maybeInvokeDelegate(delegate, context);
- if (delegateResult) {
- if (delegateResult === ContinueSentinel) continue;
- return delegateResult;
- }
- }
- if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
- if ("suspendedStart" === state) throw state = "completed", context.arg;
- context.dispatchException(context.arg);
- } else "return" === context.method && context.abrupt("return", context.arg);
- state = "executing";
- var record = tryCatch(innerFn, self, context);
- if ("normal" === record.type) {
- if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
- return {
- value: record.arg,
- done: context.done
- };
- }
- "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
- }
- };
- }
- function maybeInvokeDelegate(delegate, context) {
- var methodName = context.method,
- method = delegate.iterator[methodName];
- if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel;
- var record = tryCatch(method, delegate.iterator, context.arg);
- if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
- var info = record.arg;
- return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
- }
- function pushTryEntry(locs) {
- var entry = {
- tryLoc: locs[0]
- };
- 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
- }
- function resetTryEntry(entry) {
- var record = entry.completion || {};
- record.type = "normal", delete record.arg, entry.completion = record;
- }
- function Context(tryLocsList) {
- this.tryEntries = [{
- tryLoc: "root"
- }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
- }
- function values(iterable) {
- if (iterable) {
- var iteratorMethod = iterable[iteratorSymbol];
- if (iteratorMethod) return iteratorMethod.call(iterable);
- if ("function" == typeof iterable.next) return iterable;
- if (!isNaN(iterable.length)) {
- var i = -1,
- next = function next() {
- for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
- return next.value = undefined, next.done = !0, next;
- };
- return next.next = next;
- }
- }
- return {
- next: doneResult
- };
- }
- function doneResult() {
- return {
- value: undefined,
- done: !0
- };
- }
- return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", {
- value: GeneratorFunctionPrototype,
- configurable: !0
- }), defineProperty(GeneratorFunctionPrototype, "constructor", {
- value: GeneratorFunction,
- configurable: !0
- }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
- var ctor = "function" == typeof genFun && genFun.constructor;
- return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
- }, exports.mark = function (genFun) {
- return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
- }, exports.awrap = function (arg) {
- return {
- __await: arg
- };
- }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
- return this;
- }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
- void 0 === PromiseImpl && (PromiseImpl = Promise);
- var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
- return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
- return result.done ? result.value : iter.next();
- });
- }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
- return this;
- }), define(Gp, "toString", function () {
- return "[object Generator]";
- }), exports.keys = function (val) {
- var object = Object(val),
- keys = [];
- for (var key in object) keys.push(key);
- return keys.reverse(), function next() {
- for (; keys.length;) {
- var key = keys.pop();
- if (key in object) return next.value = key, next.done = !1, next;
- }
- return next.done = !0, next;
- };
- }, exports.values = values, Context.prototype = {
- constructor: Context,
- reset: function (skipTempReset) {
- if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
- },
- stop: function () {
- this.done = !0;
- var rootRecord = this.tryEntries[0].completion;
- if ("throw" === rootRecord.type) throw rootRecord.arg;
- return this.rval;
- },
- dispatchException: function (exception) {
- if (this.done) throw exception;
- var context = this;
- function handle(loc, caught) {
- return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
- }
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i],
- record = entry.completion;
- if ("root" === entry.tryLoc) return handle("end");
- if (entry.tryLoc <= this.prev) {
- var hasCatch = hasOwn.call(entry, "catchLoc"),
- hasFinally = hasOwn.call(entry, "finallyLoc");
- if (hasCatch && hasFinally) {
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
- } else if (hasCatch) {
- if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
- } else {
- if (!hasFinally) throw new Error("try statement without catch or finally");
- if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
- }
- }
- }
- },
- abrupt: function (type, arg) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
- var finallyEntry = entry;
- break;
- }
- }
- finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
- var record = finallyEntry ? finallyEntry.completion : {};
- return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
- },
- complete: function (record, afterLoc) {
- if ("throw" === record.type) throw record.arg;
- return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
- },
- finish: function (finallyLoc) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
- }
- },
- catch: function (tryLoc) {
- for (var i = this.tryEntries.length - 1; i >= 0; --i) {
- var entry = this.tryEntries[i];
- if (entry.tryLoc === tryLoc) {
- var record = entry.completion;
- if ("throw" === record.type) {
- var thrown = record.arg;
- resetTryEntry(entry);
- }
- return thrown;
- }
- }
- throw new Error("illegal catch attempt");
- },
- delegateYield: function (iterable, resultName, nextLoc) {
- return this.delegate = {
- iterator: values(iterable),
- resultName: resultName,
- nextLoc: nextLoc
- }, "next" === this.method && (this.arg = undefined), ContinueSentinel;
- }
- }, exports;
- }
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
- try {
- var info = gen[key](arg);
- var value = info.value;
- } catch (error) {
- reject(error);
- return;
- }
- if (info.done) {
- resolve(value);
- } else {
- Promise.resolve(value).then(_next, _throw);
- }
- }
- function _asyncToGenerator(fn) {
- return function () {
- var self = this,
- args = arguments;
- return new Promise(function (resolve, reject) {
- var gen = fn.apply(self, args);
- function _next(value) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
- }
- function _throw(err) {
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
- }
- _next(undefined);
- });
- };
- }
- function _defineProperties(target, props) {
- for (var i = 0; i < props.length; i++) {
- var descriptor = props[i];
- descriptor.enumerable = descriptor.enumerable || false;
- descriptor.configurable = true;
- if ("value" in descriptor) descriptor.writable = true;
- Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
- }
- }
- function _createClass(Constructor, protoProps, staticProps) {
- if (protoProps) _defineProperties(Constructor.prototype, protoProps);
- if (staticProps) _defineProperties(Constructor, staticProps);
- Object.defineProperty(Constructor, "prototype", {
- writable: false
- });
- return Constructor;
- }
- function _extends() {
- _extends = Object.assign ? Object.assign.bind() : function (target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i];
- for (var key in source) {
- if (Object.prototype.hasOwnProperty.call(source, key)) {
- target[key] = source[key];
- }
- }
- }
- return target;
- };
- return _extends.apply(this, arguments);
- }
- function _inheritsLoose(subClass, superClass) {
- subClass.prototype = Object.create(superClass.prototype);
- subClass.prototype.constructor = subClass;
- _setPrototypeOf(subClass, superClass);
- }
- function _setPrototypeOf(o, p) {
- _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
- o.__proto__ = p;
- return o;
- };
- return _setPrototypeOf(o, p);
- }
- function _objectWithoutPropertiesLoose(source, excluded) {
- if (source == null) return {};
- var target = {};
- var sourceKeys = Object.keys(source);
- var key, i;
- for (i = 0; i < sourceKeys.length; i++) {
- key = sourceKeys[i];
- if (excluded.indexOf(key) >= 0) continue;
- target[key] = source[key];
- }
- return target;
- }
- function _assertThisInitialized(self) {
- if (self === void 0) {
- throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
- }
- return self;
- }
- function _unsupportedIterableToArray(o, minLen) {
- if (!o) return;
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
- var n = Object.prototype.toString.call(o).slice(8, -1);
- if (n === "Object" && o.constructor) n = o.constructor.name;
- if (n === "Map" || n === "Set") return Array.from(o);
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
- }
- function _arrayLikeToArray(arr, len) {
- if (len == null || len > arr.length) len = arr.length;
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
- return arr2;
- }
- function _createForOfIteratorHelperLoose(o, allowArrayLike) {
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
- if (it) return (it = it.call(o)).next.bind(it);
- if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
- if (it) o = it;
- var i = 0;
- return function () {
- if (i >= o.length) return {
- done: true
- };
- return {
- done: false,
- value: o[i++]
- };
- };
- }
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
- }
- function _toPrimitive(input, hint) {
- if (typeof input !== "object" || input === null) return input;
- var prim = input[Symbol.toPrimitive];
- if (prim !== undefined) {
- var res = prim.call(input, hint || "default");
- if (typeof res !== "object") return res;
- throw new TypeError("@@toPrimitive must return a primitive value.");
- }
- return (hint === "string" ? String : Number)(input);
- }
- function _toPropertyKey(arg) {
- var key = _toPrimitive(arg, "string");
- return typeof key === "symbol" ? key : String(key);
- }
- /**
- * Common utilities
- * @module glMatrix
- */
- // Configuration Constants
- var EPSILON = 0.000001;
- var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
- if (!Math.hypot) Math.hypot = function () {
- var y = 0,
- i = arguments.length;
- while (i--) {
- y += arguments[i] * arguments[i];
- }
- return Math.sqrt(y);
- };
- /**
- * 3x3 Matrix
- * @module mat3
- */
- /**
- * Creates a new identity mat3
- *
- * @returns {mat3} a new 3x3 matrix
- */
- function create() {
- var out = new ARRAY_TYPE(9);
- if (ARRAY_TYPE != Float32Array) {
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[5] = 0;
- out[6] = 0;
- out[7] = 0;
- }
- out[0] = 1;
- out[4] = 1;
- out[8] = 1;
- return out;
- }
- /**
- * Copies the upper-left 3x3 values into the given mat3.
- *
- * @param {mat3} out the receiving 3x3 matrix
- * @param {ReadonlyMat4} a the source 4x4 matrix
- * @returns {mat3} out
- */
- function fromMat4(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[4];
- out[4] = a[5];
- out[5] = a[6];
- out[6] = a[8];
- out[7] = a[9];
- out[8] = a[10];
- return out;
- }
- /**
- * Create a new mat3 with the given values
- *
- * @param {Number} m00 Component in column 0, row 0 position (index 0)
- * @param {Number} m01 Component in column 0, row 1 position (index 1)
- * @param {Number} m02 Component in column 0, row 2 position (index 2)
- * @param {Number} m10 Component in column 1, row 0 position (index 3)
- * @param {Number} m11 Component in column 1, row 1 position (index 4)
- * @param {Number} m12 Component in column 1, row 2 position (index 5)
- * @param {Number} m20 Component in column 2, row 0 position (index 6)
- * @param {Number} m21 Component in column 2, row 1 position (index 7)
- * @param {Number} m22 Component in column 2, row 2 position (index 8)
- * @returns {mat3} A new mat3
- */
- function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
- var out = new ARRAY_TYPE(9);
- out[0] = m00;
- out[1] = m01;
- out[2] = m02;
- out[3] = m10;
- out[4] = m11;
- out[5] = m12;
- out[6] = m20;
- out[7] = m21;
- out[8] = m22;
- return out;
- }
- /**
- * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied.
- * @module mat4
- */
- /**
- * Creates a new identity mat4
- *
- * @returns {mat4} a new 4x4 matrix
- */
- function create$1() {
- var out = new ARRAY_TYPE(16);
- if (ARRAY_TYPE != Float32Array) {
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- }
- out[0] = 1;
- out[5] = 1;
- out[10] = 1;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a new mat4 initialized with values from an existing matrix
- *
- * @param {ReadonlyMat4} a matrix to clone
- * @returns {mat4} a new 4x4 matrix
- */
- function clone(a) {
- var out = new ARRAY_TYPE(16);
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[3];
- out[4] = a[4];
- out[5] = a[5];
- out[6] = a[6];
- out[7] = a[7];
- out[8] = a[8];
- out[9] = a[9];
- out[10] = a[10];
- out[11] = a[11];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- return out;
- }
- /**
- * Copy the values from one mat4 to another
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the source matrix
- * @returns {mat4} out
- */
- function copy(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[3];
- out[4] = a[4];
- out[5] = a[5];
- out[6] = a[6];
- out[7] = a[7];
- out[8] = a[8];
- out[9] = a[9];
- out[10] = a[10];
- out[11] = a[11];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- return out;
- }
- /**
- * Create a new mat4 with the given values
- *
- * @param {Number} m00 Component in column 0, row 0 position (index 0)
- * @param {Number} m01 Component in column 0, row 1 position (index 1)
- * @param {Number} m02 Component in column 0, row 2 position (index 2)
- * @param {Number} m03 Component in column 0, row 3 position (index 3)
- * @param {Number} m10 Component in column 1, row 0 position (index 4)
- * @param {Number} m11 Component in column 1, row 1 position (index 5)
- * @param {Number} m12 Component in column 1, row 2 position (index 6)
- * @param {Number} m13 Component in column 1, row 3 position (index 7)
- * @param {Number} m20 Component in column 2, row 0 position (index 8)
- * @param {Number} m21 Component in column 2, row 1 position (index 9)
- * @param {Number} m22 Component in column 2, row 2 position (index 10)
- * @param {Number} m23 Component in column 2, row 3 position (index 11)
- * @param {Number} m30 Component in column 3, row 0 position (index 12)
- * @param {Number} m31 Component in column 3, row 1 position (index 13)
- * @param {Number} m32 Component in column 3, row 2 position (index 14)
- * @param {Number} m33 Component in column 3, row 3 position (index 15)
- * @returns {mat4} A new mat4
- */
- function fromValues$1(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
- var out = new ARRAY_TYPE(16);
- out[0] = m00;
- out[1] = m01;
- out[2] = m02;
- out[3] = m03;
- out[4] = m10;
- out[5] = m11;
- out[6] = m12;
- out[7] = m13;
- out[8] = m20;
- out[9] = m21;
- out[10] = m22;
- out[11] = m23;
- out[12] = m30;
- out[13] = m31;
- out[14] = m32;
- out[15] = m33;
- return out;
- }
- /**
- * Set the components of a mat4 to the given values
- *
- * @param {mat4} out the receiving matrix
- * @param {Number} m00 Component in column 0, row 0 position (index 0)
- * @param {Number} m01 Component in column 0, row 1 position (index 1)
- * @param {Number} m02 Component in column 0, row 2 position (index 2)
- * @param {Number} m03 Component in column 0, row 3 position (index 3)
- * @param {Number} m10 Component in column 1, row 0 position (index 4)
- * @param {Number} m11 Component in column 1, row 1 position (index 5)
- * @param {Number} m12 Component in column 1, row 2 position (index 6)
- * @param {Number} m13 Component in column 1, row 3 position (index 7)
- * @param {Number} m20 Component in column 2, row 0 position (index 8)
- * @param {Number} m21 Component in column 2, row 1 position (index 9)
- * @param {Number} m22 Component in column 2, row 2 position (index 10)
- * @param {Number} m23 Component in column 2, row 3 position (index 11)
- * @param {Number} m30 Component in column 3, row 0 position (index 12)
- * @param {Number} m31 Component in column 3, row 1 position (index 13)
- * @param {Number} m32 Component in column 3, row 2 position (index 14)
- * @param {Number} m33 Component in column 3, row 3 position (index 15)
- * @returns {mat4} out
- */
- function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
- out[0] = m00;
- out[1] = m01;
- out[2] = m02;
- out[3] = m03;
- out[4] = m10;
- out[5] = m11;
- out[6] = m12;
- out[7] = m13;
- out[8] = m20;
- out[9] = m21;
- out[10] = m22;
- out[11] = m23;
- out[12] = m30;
- out[13] = m31;
- out[14] = m32;
- out[15] = m33;
- return out;
- }
- /**
- * Set a mat4 to the identity matrix
- *
- * @param {mat4} out the receiving matrix
- * @returns {mat4} out
- */
- function identity(out) {
- out[0] = 1;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = 1;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = 1;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Transpose the values of a mat4
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the source matrix
- * @returns {mat4} out
- */
- function transpose(out, a) {
- // If we are transposing ourselves we can skip a few steps but have to cache some values
- if (out === a) {
- var a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a12 = a[6],
- a13 = a[7];
- var a23 = a[11];
- out[1] = a[4];
- out[2] = a[8];
- out[3] = a[12];
- out[4] = a01;
- out[6] = a[9];
- out[7] = a[13];
- out[8] = a02;
- out[9] = a12;
- out[11] = a[14];
- out[12] = a03;
- out[13] = a13;
- out[14] = a23;
- } else {
- out[0] = a[0];
- out[1] = a[4];
- out[2] = a[8];
- out[3] = a[12];
- out[4] = a[1];
- out[5] = a[5];
- out[6] = a[9];
- out[7] = a[13];
- out[8] = a[2];
- out[9] = a[6];
- out[10] = a[10];
- out[11] = a[14];
- out[12] = a[3];
- out[13] = a[7];
- out[14] = a[11];
- out[15] = a[15];
- }
- return out;
- }
- /**
- * Inverts a mat4
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the source matrix
- * @returns {mat4} out
- */
- function invert(out, a) {
- var a00 = a[0],
- a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a10 = a[4],
- a11 = a[5],
- a12 = a[6],
- a13 = a[7];
- var a20 = a[8],
- a21 = a[9],
- a22 = a[10],
- a23 = a[11];
- var a30 = a[12],
- a31 = a[13],
- a32 = a[14],
- a33 = a[15];
- var b00 = a00 * a11 - a01 * a10;
- var b01 = a00 * a12 - a02 * a10;
- var b02 = a00 * a13 - a03 * a10;
- var b03 = a01 * a12 - a02 * a11;
- var b04 = a01 * a13 - a03 * a11;
- var b05 = a02 * a13 - a03 * a12;
- var b06 = a20 * a31 - a21 * a30;
- var b07 = a20 * a32 - a22 * a30;
- var b08 = a20 * a33 - a23 * a30;
- var b09 = a21 * a32 - a22 * a31;
- var b10 = a21 * a33 - a23 * a31;
- var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
- var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
- if (!det) {
- return null;
- }
- det = 1.0 / det;
- out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
- out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
- out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
- out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
- out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
- out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
- out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
- out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
- out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
- out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
- out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
- out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
- out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
- out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
- out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
- out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
- return out;
- }
- /**
- * Calculates the adjugate of a mat4
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the source matrix
- * @returns {mat4} out
- */
- function adjoint(out, a) {
- var a00 = a[0],
- a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a10 = a[4],
- a11 = a[5],
- a12 = a[6],
- a13 = a[7];
- var a20 = a[8],
- a21 = a[9],
- a22 = a[10],
- a23 = a[11];
- var a30 = a[12],
- a31 = a[13],
- a32 = a[14],
- a33 = a[15];
- out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);
- out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
- out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);
- out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
- out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
- out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);
- out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
- out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);
- out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);
- out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
- out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);
- out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
- out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
- out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);
- out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
- out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);
- return out;
- }
- /**
- * Calculates the determinant of a mat4
- *
- * @param {ReadonlyMat4} a the source matrix
- * @returns {Number} determinant of a
- */
- function determinant(a) {
- var a00 = a[0],
- a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a10 = a[4],
- a11 = a[5],
- a12 = a[6],
- a13 = a[7];
- var a20 = a[8],
- a21 = a[9],
- a22 = a[10],
- a23 = a[11];
- var a30 = a[12],
- a31 = a[13],
- a32 = a[14],
- a33 = a[15];
- var b00 = a00 * a11 - a01 * a10;
- var b01 = a00 * a12 - a02 * a10;
- var b02 = a00 * a13 - a03 * a10;
- var b03 = a01 * a12 - a02 * a11;
- var b04 = a01 * a13 - a03 * a11;
- var b05 = a02 * a13 - a03 * a12;
- var b06 = a20 * a31 - a21 * a30;
- var b07 = a20 * a32 - a22 * a30;
- var b08 = a20 * a33 - a23 * a30;
- var b09 = a21 * a32 - a22 * a31;
- var b10 = a21 * a33 - a23 * a31;
- var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
- return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
- }
- /**
- * Multiplies two mat4s
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the first operand
- * @param {ReadonlyMat4} b the second operand
- * @returns {mat4} out
- */
- function multiply(out, a, b) {
- var a00 = a[0],
- a01 = a[1],
- a02 = a[2],
- a03 = a[3];
- var a10 = a[4],
- a11 = a[5],
- a12 = a[6],
- a13 = a[7];
- var a20 = a[8],
- a21 = a[9],
- a22 = a[10],
- a23 = a[11];
- var a30 = a[12],
- a31 = a[13],
- a32 = a[14],
- a33 = a[15]; // Cache only the current line of the second matrix
- var b0 = b[0],
- b1 = b[1],
- b2 = b[2],
- b3 = b[3];
- out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
- out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
- out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
- out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
- b0 = b[4];
- b1 = b[5];
- b2 = b[6];
- b3 = b[7];
- out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
- out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
- out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
- out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
- b0 = b[8];
- b1 = b[9];
- b2 = b[10];
- b3 = b[11];
- out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
- out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
- out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
- out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
- b0 = b[12];
- b1 = b[13];
- b2 = b[14];
- b3 = b[15];
- out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
- out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
- out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
- out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
- return out;
- }
- /**
- * Translate a mat4 by the given vector
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to translate
- * @param {ReadonlyVec3} v vector to translate by
- * @returns {mat4} out
- */
- function translate(out, a, v) {
- var x = v[0],
- y = v[1],
- z = v[2];
- var a00, a01, a02, a03;
- var a10, a11, a12, a13;
- var a20, a21, a22, a23;
- if (a === out) {
- out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
- out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
- out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
- out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
- } else {
- a00 = a[0];
- a01 = a[1];
- a02 = a[2];
- a03 = a[3];
- a10 = a[4];
- a11 = a[5];
- a12 = a[6];
- a13 = a[7];
- a20 = a[8];
- a21 = a[9];
- a22 = a[10];
- a23 = a[11];
- out[0] = a00;
- out[1] = a01;
- out[2] = a02;
- out[3] = a03;
- out[4] = a10;
- out[5] = a11;
- out[6] = a12;
- out[7] = a13;
- out[8] = a20;
- out[9] = a21;
- out[10] = a22;
- out[11] = a23;
- out[12] = a00 * x + a10 * y + a20 * z + a[12];
- out[13] = a01 * x + a11 * y + a21 * z + a[13];
- out[14] = a02 * x + a12 * y + a22 * z + a[14];
- out[15] = a03 * x + a13 * y + a23 * z + a[15];
- }
- return out;
- }
- /**
- * Scales the mat4 by the dimensions in the given vec3 not using vectorization
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to scale
- * @param {ReadonlyVec3} v the vec3 to scale the matrix by
- * @returns {mat4} out
- **/
- function scale(out, a, v) {
- var x = v[0],
- y = v[1],
- z = v[2];
- out[0] = a[0] * x;
- out[1] = a[1] * x;
- out[2] = a[2] * x;
- out[3] = a[3] * x;
- out[4] = a[4] * y;
- out[5] = a[5] * y;
- out[6] = a[6] * y;
- out[7] = a[7] * y;
- out[8] = a[8] * z;
- out[9] = a[9] * z;
- out[10] = a[10] * z;
- out[11] = a[11] * z;
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- return out;
- }
- /**
- * Rotates a mat4 by the given angle around the given axis
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to rotate
- * @param {Number} rad the angle to rotate the matrix by
- * @param {ReadonlyVec3} axis the axis to rotate around
- * @returns {mat4} out
- */
- function rotate(out, a, rad, axis) {
- var x = axis[0],
- y = axis[1],
- z = axis[2];
- var len = Math.hypot(x, y, z);
- var s, c, t;
- var a00, a01, a02, a03;
- var a10, a11, a12, a13;
- var a20, a21, a22, a23;
- var b00, b01, b02;
- var b10, b11, b12;
- var b20, b21, b22;
- if (len < EPSILON) {
- return null;
- }
- len = 1 / len;
- x *= len;
- y *= len;
- z *= len;
- s = Math.sin(rad);
- c = Math.cos(rad);
- t = 1 - c;
- a00 = a[0];
- a01 = a[1];
- a02 = a[2];
- a03 = a[3];
- a10 = a[4];
- a11 = a[5];
- a12 = a[6];
- a13 = a[7];
- a20 = a[8];
- a21 = a[9];
- a22 = a[10];
- a23 = a[11]; // Construct the elements of the rotation matrix
- b00 = x * x * t + c;
- b01 = y * x * t + z * s;
- b02 = z * x * t - y * s;
- b10 = x * y * t - z * s;
- b11 = y * y * t + c;
- b12 = z * y * t + x * s;
- b20 = x * z * t + y * s;
- b21 = y * z * t - x * s;
- b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
- out[0] = a00 * b00 + a10 * b01 + a20 * b02;
- out[1] = a01 * b00 + a11 * b01 + a21 * b02;
- out[2] = a02 * b00 + a12 * b01 + a22 * b02;
- out[3] = a03 * b00 + a13 * b01 + a23 * b02;
- out[4] = a00 * b10 + a10 * b11 + a20 * b12;
- out[5] = a01 * b10 + a11 * b11 + a21 * b12;
- out[6] = a02 * b10 + a12 * b11 + a22 * b12;
- out[7] = a03 * b10 + a13 * b11 + a23 * b12;
- out[8] = a00 * b20 + a10 * b21 + a20 * b22;
- out[9] = a01 * b20 + a11 * b21 + a21 * b22;
- out[10] = a02 * b20 + a12 * b21 + a22 * b22;
- out[11] = a03 * b20 + a13 * b21 + a23 * b22;
- if (a !== out) {
- // If the source and destination differ, copy the unchanged last row
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- }
- return out;
- }
- /**
- * Rotates a matrix by the given angle around the X axis
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to rotate
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function rotateX(out, a, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad);
- var a10 = a[4];
- var a11 = a[5];
- var a12 = a[6];
- var a13 = a[7];
- var a20 = a[8];
- var a21 = a[9];
- var a22 = a[10];
- var a23 = a[11];
- if (a !== out) {
- // If the source and destination differ, copy the unchanged rows
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[3];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- } // Perform axis-specific matrix multiplication
- out[4] = a10 * c + a20 * s;
- out[5] = a11 * c + a21 * s;
- out[6] = a12 * c + a22 * s;
- out[7] = a13 * c + a23 * s;
- out[8] = a20 * c - a10 * s;
- out[9] = a21 * c - a11 * s;
- out[10] = a22 * c - a12 * s;
- out[11] = a23 * c - a13 * s;
- return out;
- }
- /**
- * Rotates a matrix by the given angle around the Y axis
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to rotate
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function rotateY(out, a, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad);
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a03 = a[3];
- var a20 = a[8];
- var a21 = a[9];
- var a22 = a[10];
- var a23 = a[11];
- if (a !== out) {
- // If the source and destination differ, copy the unchanged rows
- out[4] = a[4];
- out[5] = a[5];
- out[6] = a[6];
- out[7] = a[7];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- } // Perform axis-specific matrix multiplication
- out[0] = a00 * c - a20 * s;
- out[1] = a01 * c - a21 * s;
- out[2] = a02 * c - a22 * s;
- out[3] = a03 * c - a23 * s;
- out[8] = a00 * s + a20 * c;
- out[9] = a01 * s + a21 * c;
- out[10] = a02 * s + a22 * c;
- out[11] = a03 * s + a23 * c;
- return out;
- }
- /**
- * Rotates a matrix by the given angle around the Z axis
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to rotate
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function rotateZ(out, a, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad);
- var a00 = a[0];
- var a01 = a[1];
- var a02 = a[2];
- var a03 = a[3];
- var a10 = a[4];
- var a11 = a[5];
- var a12 = a[6];
- var a13 = a[7];
- if (a !== out) {
- // If the source and destination differ, copy the unchanged last row
- out[8] = a[8];
- out[9] = a[9];
- out[10] = a[10];
- out[11] = a[11];
- out[12] = a[12];
- out[13] = a[13];
- out[14] = a[14];
- out[15] = a[15];
- } // Perform axis-specific matrix multiplication
- out[0] = a00 * c + a10 * s;
- out[1] = a01 * c + a11 * s;
- out[2] = a02 * c + a12 * s;
- out[3] = a03 * c + a13 * s;
- out[4] = a10 * c - a00 * s;
- out[5] = a11 * c - a01 * s;
- out[6] = a12 * c - a02 * s;
- out[7] = a13 * c - a03 * s;
- return out;
- }
- /**
- * Creates a matrix from a vector translation
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.translate(dest, dest, vec);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {ReadonlyVec3} v Translation vector
- * @returns {mat4} out
- */
- function fromTranslation(out, v) {
- out[0] = 1;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = 1;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = 1;
- out[11] = 0;
- out[12] = v[0];
- out[13] = v[1];
- out[14] = v[2];
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from a vector scaling
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.scale(dest, dest, vec);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {ReadonlyVec3} v Scaling vector
- * @returns {mat4} out
- */
- function fromScaling(out, v) {
- out[0] = v[0];
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = v[1];
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = v[2];
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from a given angle around a given axis
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.rotate(dest, dest, rad, axis);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {Number} rad the angle to rotate the matrix by
- * @param {ReadonlyVec3} axis the axis to rotate around
- * @returns {mat4} out
- */
- function fromRotation(out, rad, axis) {
- var x = axis[0],
- y = axis[1],
- z = axis[2];
- var len = Math.hypot(x, y, z);
- var s, c, t;
- if (len < EPSILON) {
- return null;
- }
- len = 1 / len;
- x *= len;
- y *= len;
- z *= len;
- s = Math.sin(rad);
- c = Math.cos(rad);
- t = 1 - c; // Perform rotation-specific matrix multiplication
- out[0] = x * x * t + c;
- out[1] = y * x * t + z * s;
- out[2] = z * x * t - y * s;
- out[3] = 0;
- out[4] = x * y * t - z * s;
- out[5] = y * y * t + c;
- out[6] = z * y * t + x * s;
- out[7] = 0;
- out[8] = x * z * t + y * s;
- out[9] = y * z * t - x * s;
- out[10] = z * z * t + c;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from the given angle around the X axis
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.rotateX(dest, dest, rad);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function fromXRotation(out, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad); // Perform axis-specific matrix multiplication
- out[0] = 1;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = c;
- out[6] = s;
- out[7] = 0;
- out[8] = 0;
- out[9] = -s;
- out[10] = c;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from the given angle around the Y axis
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.rotateY(dest, dest, rad);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function fromYRotation(out, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad); // Perform axis-specific matrix multiplication
- out[0] = c;
- out[1] = 0;
- out[2] = -s;
- out[3] = 0;
- out[4] = 0;
- out[5] = 1;
- out[6] = 0;
- out[7] = 0;
- out[8] = s;
- out[9] = 0;
- out[10] = c;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from the given angle around the Z axis
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.rotateZ(dest, dest, rad);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {Number} rad the angle to rotate the matrix by
- * @returns {mat4} out
- */
- function fromZRotation(out, rad) {
- var s = Math.sin(rad);
- var c = Math.cos(rad); // Perform axis-specific matrix multiplication
- out[0] = c;
- out[1] = s;
- out[2] = 0;
- out[3] = 0;
- out[4] = -s;
- out[5] = c;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = 1;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from a quaternion rotation and vector translation
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.translate(dest, vec);
- * let quatMat = mat4.create();
- * quat4.toMat4(quat, quatMat);
- * mat4.multiply(dest, quatMat);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {quat4} q Rotation quaternion
- * @param {ReadonlyVec3} v Translation vector
- * @returns {mat4} out
- */
- function fromRotationTranslation(out, q, v) {
- // Quaternion math
- var x = q[0],
- y = q[1],
- z = q[2],
- w = q[3];
- var x2 = x + x;
- var y2 = y + y;
- var z2 = z + z;
- var xx = x * x2;
- var xy = x * y2;
- var xz = x * z2;
- var yy = y * y2;
- var yz = y * z2;
- var zz = z * z2;
- var wx = w * x2;
- var wy = w * y2;
- var wz = w * z2;
- out[0] = 1 - (yy + zz);
- out[1] = xy + wz;
- out[2] = xz - wy;
- out[3] = 0;
- out[4] = xy - wz;
- out[5] = 1 - (xx + zz);
- out[6] = yz + wx;
- out[7] = 0;
- out[8] = xz + wy;
- out[9] = yz - wx;
- out[10] = 1 - (xx + yy);
- out[11] = 0;
- out[12] = v[0];
- out[13] = v[1];
- out[14] = v[2];
- out[15] = 1;
- return out;
- }
- /**
- * Creates a new mat4 from a dual quat.
- *
- * @param {mat4} out Matrix
- * @param {ReadonlyQuat2} a Dual Quaternion
- * @returns {mat4} mat4 receiving operation result
- */
- function fromQuat2(out, a) {
- var translation = new ARRAY_TYPE(3);
- var bx = -a[0],
- by = -a[1],
- bz = -a[2],
- bw = a[3],
- ax = a[4],
- ay = a[5],
- az = a[6],
- aw = a[7];
- var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense
- if (magnitude > 0) {
- translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;
- translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;
- translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;
- } else {
- translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;
- translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;
- translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;
- }
- fromRotationTranslation(out, a, translation);
- return out;
- }
- /**
- * Returns the translation vector component of a transformation
- * matrix. If a matrix is built with fromRotationTranslation,
- * the returned vector will be the same as the translation vector
- * originally supplied.
- * @param {vec3} out Vector to receive translation component
- * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
- * @return {vec3} out
- */
- function getTranslation(out, mat) {
- out[0] = mat[12];
- out[1] = mat[13];
- out[2] = mat[14];
- return out;
- }
- /**
- * Returns the scaling factor component of a transformation
- * matrix. If a matrix is built with fromRotationTranslationScale
- * with a normalized Quaternion paramter, the returned vector will be
- * the same as the scaling vector
- * originally supplied.
- * @param {vec3} out Vector to receive scaling factor component
- * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
- * @return {vec3} out
- */
- function getScaling(out, mat) {
- var m11 = mat[0];
- var m12 = mat[1];
- var m13 = mat[2];
- var m21 = mat[4];
- var m22 = mat[5];
- var m23 = mat[6];
- var m31 = mat[8];
- var m32 = mat[9];
- var m33 = mat[10];
- out[0] = Math.hypot(m11, m12, m13);
- out[1] = Math.hypot(m21, m22, m23);
- out[2] = Math.hypot(m31, m32, m33);
- return out;
- }
- /**
- * Returns a quaternion representing the rotational component
- * of a transformation matrix. If a matrix is built with
- * fromRotationTranslation, the returned quaternion will be the
- * same as the quaternion originally supplied.
- * @param {quat} out Quaternion to receive the rotation component
- * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
- * @return {quat} out
- */
- function getRotation(out, mat) {
- var scaling = new ARRAY_TYPE(3);
- getScaling(scaling, mat);
- var is1 = 1 / scaling[0];
- var is2 = 1 / scaling[1];
- var is3 = 1 / scaling[2];
- var sm11 = mat[0] * is1;
- var sm12 = mat[1] * is2;
- var sm13 = mat[2] * is3;
- var sm21 = mat[4] * is1;
- var sm22 = mat[5] * is2;
- var sm23 = mat[6] * is3;
- var sm31 = mat[8] * is1;
- var sm32 = mat[9] * is2;
- var sm33 = mat[10] * is3;
- var trace = sm11 + sm22 + sm33;
- var S = 0;
- if (trace > 0) {
- S = Math.sqrt(trace + 1.0) * 2;
- out[3] = 0.25 * S;
- out[0] = (sm23 - sm32) / S;
- out[1] = (sm31 - sm13) / S;
- out[2] = (sm12 - sm21) / S;
- } else if (sm11 > sm22 && sm11 > sm33) {
- S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;
- out[3] = (sm23 - sm32) / S;
- out[0] = 0.25 * S;
- out[1] = (sm12 + sm21) / S;
- out[2] = (sm31 + sm13) / S;
- } else if (sm22 > sm33) {
- S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;
- out[3] = (sm31 - sm13) / S;
- out[0] = (sm12 + sm21) / S;
- out[1] = 0.25 * S;
- out[2] = (sm23 + sm32) / S;
- } else {
- S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;
- out[3] = (sm12 - sm21) / S;
- out[0] = (sm31 + sm13) / S;
- out[1] = (sm23 + sm32) / S;
- out[2] = 0.25 * S;
- }
- return out;
- }
- /**
- * Creates a matrix from a quaternion rotation, vector translation and vector scale
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.translate(dest, vec);
- * let quatMat = mat4.create();
- * quat4.toMat4(quat, quatMat);
- * mat4.multiply(dest, quatMat);
- * mat4.scale(dest, scale)
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {quat4} q Rotation quaternion
- * @param {ReadonlyVec3} v Translation vector
- * @param {ReadonlyVec3} s Scaling vector
- * @returns {mat4} out
- */
- function fromRotationTranslationScale(out, q, v, s) {
- // Quaternion math
- var x = q[0],
- y = q[1],
- z = q[2],
- w = q[3];
- var x2 = x + x;
- var y2 = y + y;
- var z2 = z + z;
- var xx = x * x2;
- var xy = x * y2;
- var xz = x * z2;
- var yy = y * y2;
- var yz = y * z2;
- var zz = z * z2;
- var wx = w * x2;
- var wy = w * y2;
- var wz = w * z2;
- var sx = s[0];
- var sy = s[1];
- var sz = s[2];
- out[0] = (1 - (yy + zz)) * sx;
- out[1] = (xy + wz) * sx;
- out[2] = (xz - wy) * sx;
- out[3] = 0;
- out[4] = (xy - wz) * sy;
- out[5] = (1 - (xx + zz)) * sy;
- out[6] = (yz + wx) * sy;
- out[7] = 0;
- out[8] = (xz + wy) * sz;
- out[9] = (yz - wx) * sz;
- out[10] = (1 - (xx + yy)) * sz;
- out[11] = 0;
- out[12] = v[0];
- out[13] = v[1];
- out[14] = v[2];
- out[15] = 1;
- return out;
- }
- /**
- * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin
- * This is equivalent to (but much faster than):
- *
- * mat4.identity(dest);
- * mat4.translate(dest, vec);
- * mat4.translate(dest, origin);
- * let quatMat = mat4.create();
- * quat4.toMat4(quat, quatMat);
- * mat4.multiply(dest, quatMat);
- * mat4.scale(dest, scale)
- * mat4.translate(dest, negativeOrigin);
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {quat4} q Rotation quaternion
- * @param {ReadonlyVec3} v Translation vector
- * @param {ReadonlyVec3} s Scaling vector
- * @param {ReadonlyVec3} o The origin vector around which to scale and rotate
- * @returns {mat4} out
- */
- function fromRotationTranslationScaleOrigin(out, q, v, s, o) {
- // Quaternion math
- var x = q[0],
- y = q[1],
- z = q[2],
- w = q[3];
- var x2 = x + x;
- var y2 = y + y;
- var z2 = z + z;
- var xx = x * x2;
- var xy = x * y2;
- var xz = x * z2;
- var yy = y * y2;
- var yz = y * z2;
- var zz = z * z2;
- var wx = w * x2;
- var wy = w * y2;
- var wz = w * z2;
- var sx = s[0];
- var sy = s[1];
- var sz = s[2];
- var ox = o[0];
- var oy = o[1];
- var oz = o[2];
- var out0 = (1 - (yy + zz)) * sx;
- var out1 = (xy + wz) * sx;
- var out2 = (xz - wy) * sx;
- var out4 = (xy - wz) * sy;
- var out5 = (1 - (xx + zz)) * sy;
- var out6 = (yz + wx) * sy;
- var out8 = (xz + wy) * sz;
- var out9 = (yz - wx) * sz;
- var out10 = (1 - (xx + yy)) * sz;
- out[0] = out0;
- out[1] = out1;
- out[2] = out2;
- out[3] = 0;
- out[4] = out4;
- out[5] = out5;
- out[6] = out6;
- out[7] = 0;
- out[8] = out8;
- out[9] = out9;
- out[10] = out10;
- out[11] = 0;
- out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);
- out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);
- out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);
- out[15] = 1;
- return out;
- }
- /**
- * Calculates a 4x4 matrix from the given quaternion
- *
- * @param {mat4} out mat4 receiving operation result
- * @param {ReadonlyQuat} q Quaternion to create matrix from
- *
- * @returns {mat4} out
- */
- function fromQuat(out, q) {
- var x = q[0],
- y = q[1],
- z = q[2],
- w = q[3];
- var x2 = x + x;
- var y2 = y + y;
- var z2 = z + z;
- var xx = x * x2;
- var yx = y * x2;
- var yy = y * y2;
- var zx = z * x2;
- var zy = z * y2;
- var zz = z * z2;
- var wx = w * x2;
- var wy = w * y2;
- var wz = w * z2;
- out[0] = 1 - yy - zz;
- out[1] = yx + wz;
- out[2] = zx - wy;
- out[3] = 0;
- out[4] = yx - wz;
- out[5] = 1 - xx - zz;
- out[6] = zy + wx;
- out[7] = 0;
- out[8] = zx + wy;
- out[9] = zy - wx;
- out[10] = 1 - xx - yy;
- out[11] = 0;
- out[12] = 0;
- out[13] = 0;
- out[14] = 0;
- out[15] = 1;
- return out;
- }
- /**
- * Generates a frustum matrix with the given bounds
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {Number} left Left bound of the frustum
- * @param {Number} right Right bound of the frustum
- * @param {Number} bottom Bottom bound of the frustum
- * @param {Number} top Top bound of the frustum
- * @param {Number} near Near bound of the frustum
- * @param {Number} far Far bound of the frustum
- * @returns {mat4} out
- */
- function frustum(out, left, right, bottom, top, near, far) {
- var rl = 1 / (right - left);
- var tb = 1 / (top - bottom);
- var nf = 1 / (near - far);
- out[0] = near * 2 * rl;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = near * 2 * tb;
- out[6] = 0;
- out[7] = 0;
- out[8] = (right + left) * rl;
- out[9] = (top + bottom) * tb;
- out[10] = (far + near) * nf;
- out[11] = -1;
- out[12] = 0;
- out[13] = 0;
- out[14] = far * near * 2 * nf;
- out[15] = 0;
- return out;
- }
- /**
- * Generates a perspective projection matrix with the given bounds.
- * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
- * which matches WebGL/OpenGL's clip volume.
- * Passing null/undefined/no value for far will generate infinite projection matrix.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {number} fovy Vertical field of view in radians
- * @param {number} aspect Aspect ratio. typically viewport width/height
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum, can be null or Infinity
- * @returns {mat4} out
- */
- function perspectiveNO(out, fovy, aspect, near, far) {
- var f = 1.0 / Math.tan(fovy / 2),
- nf;
- out[0] = f / aspect;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = f;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[11] = -1;
- out[12] = 0;
- out[13] = 0;
- out[15] = 0;
- if (far != null && far !== Infinity) {
- nf = 1 / (near - far);
- out[10] = (far + near) * nf;
- out[14] = 2 * far * near * nf;
- } else {
- out[10] = -1;
- out[14] = -2 * near;
- }
- return out;
- }
- /**
- * Alias for {@link mat4.perspectiveNO}
- * @function
- */
- var perspective = perspectiveNO;
- /**
- * Generates a perspective projection matrix suitable for WebGPU with the given bounds.
- * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],
- * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.
- * Passing null/undefined/no value for far will generate infinite projection matrix.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {number} fovy Vertical field of view in radians
- * @param {number} aspect Aspect ratio. typically viewport width/height
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum, can be null or Infinity
- * @returns {mat4} out
- */
- function perspectiveZO(out, fovy, aspect, near, far) {
- var f = 1.0 / Math.tan(fovy / 2),
- nf;
- out[0] = f / aspect;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = f;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[11] = -1;
- out[12] = 0;
- out[13] = 0;
- out[15] = 0;
- if (far != null && far !== Infinity) {
- nf = 1 / (near - far);
- out[10] = far * nf;
- out[14] = far * near * nf;
- } else {
- out[10] = -1;
- out[14] = -near;
- }
- return out;
- }
- /**
- * Generates a perspective projection matrix with the given field of view.
- * This is primarily useful for generating projection matrices to be used
- * with the still experiemental WebVR API.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum
- * @returns {mat4} out
- */
- function perspectiveFromFieldOfView(out, fov, near, far) {
- var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
- var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
- var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
- var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
- var xScale = 2.0 / (leftTan + rightTan);
- var yScale = 2.0 / (upTan + downTan);
- out[0] = xScale;
- out[1] = 0.0;
- out[2] = 0.0;
- out[3] = 0.0;
- out[4] = 0.0;
- out[5] = yScale;
- out[6] = 0.0;
- out[7] = 0.0;
- out[8] = -((leftTan - rightTan) * xScale * 0.5);
- out[9] = (upTan - downTan) * yScale * 0.5;
- out[10] = far / (near - far);
- out[11] = -1.0;
- out[12] = 0.0;
- out[13] = 0.0;
- out[14] = far * near / (near - far);
- out[15] = 0.0;
- return out;
- }
- /**
- * Generates a orthogonal projection matrix with the given bounds.
- * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
- * which matches WebGL/OpenGL's clip volume.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {number} left Left bound of the frustum
- * @param {number} right Right bound of the frustum
- * @param {number} bottom Bottom bound of the frustum
- * @param {number} top Top bound of the frustum
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum
- * @returns {mat4} out
- */
- function orthoNO(out, left, right, bottom, top, near, far) {
- var lr = 1 / (left - right);
- var bt = 1 / (bottom - top);
- var nf = 1 / (near - far);
- out[0] = -2 * lr;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = -2 * bt;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = 2 * nf;
- out[11] = 0;
- out[12] = (left + right) * lr;
- out[13] = (top + bottom) * bt;
- out[14] = (far + near) * nf;
- out[15] = 1;
- return out;
- }
- /**
- * Alias for {@link mat4.orthoNO}
- * @function
- */
- var ortho = orthoNO;
- /**
- * Generates a orthogonal projection matrix with the given bounds.
- * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],
- * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {number} left Left bound of the frustum
- * @param {number} right Right bound of the frustum
- * @param {number} bottom Bottom bound of the frustum
- * @param {number} top Top bound of the frustum
- * @param {number} near Near bound of the frustum
- * @param {number} far Far bound of the frustum
- * @returns {mat4} out
- */
- function orthoZO(out, left, right, bottom, top, near, far) {
- var lr = 1 / (left - right);
- var bt = 1 / (bottom - top);
- var nf = 1 / (near - far);
- out[0] = -2 * lr;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = -2 * bt;
- out[6] = 0;
- out[7] = 0;
- out[8] = 0;
- out[9] = 0;
- out[10] = nf;
- out[11] = 0;
- out[12] = (left + right) * lr;
- out[13] = (top + bottom) * bt;
- out[14] = near * nf;
- out[15] = 1;
- return out;
- }
- /**
- * Generates a look-at matrix with the given eye position, focal point, and up axis.
- * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {ReadonlyVec3} eye Position of the viewer
- * @param {ReadonlyVec3} center Point the viewer is looking at
- * @param {ReadonlyVec3} up vec3 pointing up
- * @returns {mat4} out
- */
- function lookAt(out, eye, center, up) {
- var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
- var eyex = eye[0];
- var eyey = eye[1];
- var eyez = eye[2];
- var upx = up[0];
- var upy = up[1];
- var upz = up[2];
- var centerx = center[0];
- var centery = center[1];
- var centerz = center[2];
- if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
- return identity(out);
- }
- z0 = eyex - centerx;
- z1 = eyey - centery;
- z2 = eyez - centerz;
- len = 1 / Math.hypot(z0, z1, z2);
- z0 *= len;
- z1 *= len;
- z2 *= len;
- x0 = upy * z2 - upz * z1;
- x1 = upz * z0 - upx * z2;
- x2 = upx * z1 - upy * z0;
- len = Math.hypot(x0, x1, x2);
- if (!len) {
- x0 = 0;
- x1 = 0;
- x2 = 0;
- } else {
- len = 1 / len;
- x0 *= len;
- x1 *= len;
- x2 *= len;
- }
- y0 = z1 * x2 - z2 * x1;
- y1 = z2 * x0 - z0 * x2;
- y2 = z0 * x1 - z1 * x0;
- len = Math.hypot(y0, y1, y2);
- if (!len) {
- y0 = 0;
- y1 = 0;
- y2 = 0;
- } else {
- len = 1 / len;
- y0 *= len;
- y1 *= len;
- y2 *= len;
- }
- out[0] = x0;
- out[1] = y0;
- out[2] = z0;
- out[3] = 0;
- out[4] = x1;
- out[5] = y1;
- out[6] = z1;
- out[7] = 0;
- out[8] = x2;
- out[9] = y2;
- out[10] = z2;
- out[11] = 0;
- out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
- out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
- out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
- out[15] = 1;
- return out;
- }
- /**
- * Generates a matrix that makes something look at something else.
- *
- * @param {mat4} out mat4 frustum matrix will be written into
- * @param {ReadonlyVec3} eye Position of the viewer
- * @param {ReadonlyVec3} center Point the viewer is looking at
- * @param {ReadonlyVec3} up vec3 pointing up
- * @returns {mat4} out
- */
- function targetTo(out, eye, target, up) {
- var eyex = eye[0],
- eyey = eye[1],
- eyez = eye[2],
- upx = up[0],
- upy = up[1],
- upz = up[2];
- var z0 = eyex - target[0],
- z1 = eyey - target[1],
- z2 = eyez - target[2];
- var len = z0 * z0 + z1 * z1 + z2 * z2;
- if (len > 0) {
- len = 1 / Math.sqrt(len);
- z0 *= len;
- z1 *= len;
- z2 *= len;
- }
- var x0 = upy * z2 - upz * z1,
- x1 = upz * z0 - upx * z2,
- x2 = upx * z1 - upy * z0;
- len = x0 * x0 + x1 * x1 + x2 * x2;
- if (len > 0) {
- len = 1 / Math.sqrt(len);
- x0 *= len;
- x1 *= len;
- x2 *= len;
- }
- out[0] = x0;
- out[1] = x1;
- out[2] = x2;
- out[3] = 0;
- out[4] = z1 * x2 - z2 * x1;
- out[5] = z2 * x0 - z0 * x2;
- out[6] = z0 * x1 - z1 * x0;
- out[7] = 0;
- out[8] = z0;
- out[9] = z1;
- out[10] = z2;
- out[11] = 0;
- out[12] = eyex;
- out[13] = eyey;
- out[14] = eyez;
- out[15] = 1;
- return out;
- }
- /**
- * Returns a string representation of a mat4
- *
- * @param {ReadonlyMat4} a matrix to represent as a string
- * @returns {String} string representation of the matrix
- */
- function str(a) {
- return "mat4(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ", " + a[8] + ", " + a[9] + ", " + a[10] + ", " + a[11] + ", " + a[12] + ", " + a[13] + ", " + a[14] + ", " + a[15] + ")";
- }
- /**
- * Returns Frobenius norm of a mat4
- *
- * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of
- * @returns {Number} Frobenius norm
- */
- function frob(a) {
- return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);
- }
- /**
- * Adds two mat4's
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the first operand
- * @param {ReadonlyMat4} b the second operand
- * @returns {mat4} out
- */
- function add(out, a, b) {
- out[0] = a[0] + b[0];
- out[1] = a[1] + b[1];
- out[2] = a[2] + b[2];
- out[3] = a[3] + b[3];
- out[4] = a[4] + b[4];
- out[5] = a[5] + b[5];
- out[6] = a[6] + b[6];
- out[7] = a[7] + b[7];
- out[8] = a[8] + b[8];
- out[9] = a[9] + b[9];
- out[10] = a[10] + b[10];
- out[11] = a[11] + b[11];
- out[12] = a[12] + b[12];
- out[13] = a[13] + b[13];
- out[14] = a[14] + b[14];
- out[15] = a[15] + b[15];
- return out;
- }
- /**
- * Subtracts matrix b from matrix a
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the first operand
- * @param {ReadonlyMat4} b the second operand
- * @returns {mat4} out
- */
- function subtract(out, a, b) {
- out[0] = a[0] - b[0];
- out[1] = a[1] - b[1];
- out[2] = a[2] - b[2];
- out[3] = a[3] - b[3];
- out[4] = a[4] - b[4];
- out[5] = a[5] - b[5];
- out[6] = a[6] - b[6];
- out[7] = a[7] - b[7];
- out[8] = a[8] - b[8];
- out[9] = a[9] - b[9];
- out[10] = a[10] - b[10];
- out[11] = a[11] - b[11];
- out[12] = a[12] - b[12];
- out[13] = a[13] - b[13];
- out[14] = a[14] - b[14];
- out[15] = a[15] - b[15];
- return out;
- }
- /**
- * Multiply each element of the matrix by a scalar.
- *
- * @param {mat4} out the receiving matrix
- * @param {ReadonlyMat4} a the matrix to scale
- * @param {Number} b amount to scale the matrix's elements by
- * @returns {mat4} out
- */
- function multiplyScalar(out, a, b) {
- out[0] = a[0] * b;
- out[1] = a[1] * b;
- out[2] = a[2] * b;
- out[3] = a[3] * b;
- out[4] = a[4] * b;
- out[5] = a[5] * b;
- out[6] = a[6] * b;
- out[7] = a[7] * b;
- out[8] = a[8] * b;
- out[9] = a[9] * b;
- out[10] = a[10] * b;
- out[11] = a[11] * b;
- out[12] = a[12] * b;
- out[13] = a[13] * b;
- out[14] = a[14] * b;
- out[15] = a[15] * b;
- return out;
- }
- /**
- * Adds two mat4's after multiplying each element of the second operand by a scalar value.
- *
- * @param {mat4} out the receiving vector
- * @param {ReadonlyMat4} a the first operand
- * @param {ReadonlyMat4} b the second operand
- * @param {Number} scale the amount to scale b's elements by before adding
- * @returns {mat4} out
- */
- function multiplyScalarAndAdd(out, a, b, scale) {
- out[0] = a[0] + b[0] * scale;
- out[1] = a[1] + b[1] * scale;
- out[2] = a[2] + b[2] * scale;
- out[3] = a[3] + b[3] * scale;
- out[4] = a[4] + b[4] * scale;
- out[5] = a[5] + b[5] * scale;
- out[6] = a[6] + b[6] * scale;
- out[7] = a[7] + b[7] * scale;
- out[8] = a[8] + b[8] * scale;
- out[9] = a[9] + b[9] * scale;
- out[10] = a[10] + b[10] * scale;
- out[11] = a[11] + b[11] * scale;
- out[12] = a[12] + b[12] * scale;
- out[13] = a[13] + b[13] * scale;
- out[14] = a[14] + b[14] * scale;
- out[15] = a[15] + b[15] * scale;
- return out;
- }
- /**
- * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
- *
- * @param {ReadonlyMat4} a The first matrix.
- * @param {ReadonlyMat4} b The second matrix.
- * @returns {Boolean} True if the matrices are equal, false otherwise.
- */
- function exactEquals(a, b) {
- return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];
- }
- /**
- * Returns whether or not the matrices have approximately the same elements in the same position.
- *
- * @param {ReadonlyMat4} a The first matrix.
- * @param {ReadonlyMat4} b The second matrix.
- * @returns {Boolean} True if the matrices are equal, false otherwise.
- */
- function equals(a, b) {
- var a0 = a[0],
- a1 = a[1],
- a2 = a[2],
- a3 = a[3];
- var a4 = a[4],
- a5 = a[5],
- a6 = a[6],
- a7 = a[7];
- var a8 = a[8],
- a9 = a[9],
- a10 = a[10],
- a11 = a[11];
- var a12 = a[12],
- a13 = a[13],
- a14 = a[14],
- a15 = a[15];
- var b0 = b[0],
- b1 = b[1],
- b2 = b[2],
- b3 = b[3];
- var b4 = b[4],
- b5 = b[5],
- b6 = b[6],
- b7 = b[7];
- var b8 = b[8],
- b9 = b[9],
- b10 = b[10],
- b11 = b[11];
- var b12 = b[12],
- b13 = b[13],
- b14 = b[14],
- b15 = b[15];
- return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));
- }
- /**
- * Alias for {@link mat4.multiply}
- * @function
- */
- var mul = multiply;
- /**
- * Alias for {@link mat4.subtract}
- * @function
- */
- var sub = subtract;
- var mat4 = /*#__PURE__*/Object.freeze({
- __proto__: null,
- create: create$1,
- clone: clone,
- copy: copy,
- fromValues: fromValues$1,
- set: set,
- identity: identity,
- transpose: transpose,
- invert: invert,
- adjoint: adjoint,
- determinant: determinant,
- multiply: multiply,
- translate: translate,
- scale: scale,
- rotate: rotate,
- rotateX: rotateX,
- rotateY: rotateY,
- rotateZ: rotateZ,
- fromTranslation: fromTranslation,
- fromScaling: fromScaling,
- fromRotation: fromRotation,
- fromXRotation: fromXRotation,
- fromYRotation: fromYRotation,
- fromZRotation: fromZRotation,
- fromRotationTranslation: fromRotationTranslation,
- fromQuat2: fromQuat2,
- getTranslation: getTranslation,
- getScaling: getScaling,
- getRotation: getRotation,
- fromRotationTranslationScale: fromRotationTranslationScale,
- fromRotationTranslationScaleOrigin: fromRotationTranslationScaleOrigin,
- fromQuat: fromQuat,
- frustum: frustum,
- perspectiveNO: perspectiveNO,
- perspective: perspective,
- perspectiveZO: perspectiveZO,
- perspectiveFromFieldOfView: perspectiveFromFieldOfView,
- orthoNO: orthoNO,
- ortho: ortho,
- orthoZO: orthoZO,
- lookAt: lookAt,
- targetTo: targetTo,
- str: str,
- frob: frob,
- add: add,
- subtract: subtract,
- multiplyScalar: multiplyScalar,
- multiplyScalarAndAdd: multiplyScalarAndAdd,
- exactEquals: exactEquals,
- equals: equals,
- mul: mul,
- sub: sub
- });
- /**
- * 3 Dimensional Vector
- * @module vec3
- */
- /**
- * Creates a new, empty vec3
- *
- * @returns {vec3} a new 3D vector
- */
- function create$2() {
- var out = new ARRAY_TYPE(3);
- if (ARRAY_TYPE != Float32Array) {
- out[0] = 0;
- out[1] = 0;
- out[2] = 0;
- }
- return out;
- }
- /**
- * Creates a new vec3 initialized with values from an existing vector
- *
- * @param {ReadonlyVec3} a vector to clone
- * @returns {vec3} a new 3D vector
- */
- function clone$1(a) {
- var out = new ARRAY_TYPE(3);
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- return out;
- }
- /**
- * Calculates the length of a vec3
- *
- * @param {ReadonlyVec3} a vector to calculate length of
- * @returns {Number} length of a
- */
- function length(a) {
- var x = a[0];
- var y = a[1];
- var z = a[2];
- return Math.hypot(x, y, z);
- }
- /**
- * Creates a new vec3 initialized with the given values
- *
- * @param {Number} x X component
- * @param {Number} y Y component
- * @param {Number} z Z component
- * @returns {vec3} a new 3D vector
- */
- function fromValues$2(x, y, z) {
- var out = new ARRAY_TYPE(3);
- out[0] = x;
- out[1] = y;
- out[2] = z;
- return out;
- }
- /**
- * Copy the values from one vec3 to another
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the source vector
- * @returns {vec3} out
- */
- function copy$1(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- return out;
- }
- /**
- * Set the components of a vec3 to the given values
- *
- * @param {vec3} out the receiving vector
- * @param {Number} x X component
- * @param {Number} y Y component
- * @param {Number} z Z component
- * @returns {vec3} out
- */
- function set$1(out, x, y, z) {
- out[0] = x;
- out[1] = y;
- out[2] = z;
- return out;
- }
- /**
- * Adds two vec3's
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {vec3} out
- */
- function add$1(out, a, b) {
- out[0] = a[0] + b[0];
- out[1] = a[1] + b[1];
- out[2] = a[2] + b[2];
- return out;
- }
- /**
- * Subtracts vector b from vector a
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {vec3} out
- */
- function subtract$1(out, a, b) {
- out[0] = a[0] - b[0];
- out[1] = a[1] - b[1];
- out[2] = a[2] - b[2];
- return out;
- }
- /**
- * Multiplies two vec3's
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {vec3} out
- */
- function multiply$1(out, a, b) {
- out[0] = a[0] * b[0];
- out[1] = a[1] * b[1];
- out[2] = a[2] * b[2];
- return out;
- }
- /**
- * Scales a vec3 by a scalar number
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the vector to scale
- * @param {Number} b amount to scale the vector by
- * @returns {vec3} out
- */
- function scale$1(out, a, b) {
- out[0] = a[0] * b;
- out[1] = a[1] * b;
- out[2] = a[2] * b;
- return out;
- }
- /**
- * Normalize a vec3
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a vector to normalize
- * @returns {vec3} out
- */
- function normalize(out, a) {
- var x = a[0];
- var y = a[1];
- var z = a[2];
- var len = x * x + y * y + z * z;
- if (len > 0) {
- //TODO: evaluate use of glm_invsqrt here?
- len = 1 / Math.sqrt(len);
- }
- out[0] = a[0] * len;
- out[1] = a[1] * len;
- out[2] = a[2] * len;
- return out;
- }
- /**
- * Calculates the dot product of two vec3's
- *
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {Number} dot product of a and b
- */
- function dot(a, b) {
- return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
- }
- /**
- * Computes the cross product of two vec3's
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @returns {vec3} out
- */
- function cross(out, a, b) {
- var ax = a[0],
- ay = a[1],
- az = a[2];
- var bx = b[0],
- by = b[1],
- bz = b[2];
- out[0] = ay * bz - az * by;
- out[1] = az * bx - ax * bz;
- out[2] = ax * by - ay * bx;
- return out;
- }
- /**
- * Performs a linear interpolation between two vec3's
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the first operand
- * @param {ReadonlyVec3} b the second operand
- * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
- * @returns {vec3} out
- */
- function lerp(out, a, b, t) {
- var ax = a[0];
- var ay = a[1];
- var az = a[2];
- out[0] = ax + t * (b[0] - ax);
- out[1] = ay + t * (b[1] - ay);
- out[2] = az + t * (b[2] - az);
- return out;
- }
- /**
- * Transforms the vec3 with a mat4.
- * 4th vector component is implicitly '1'
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the vector to transform
- * @param {ReadonlyMat4} m matrix to transform with
- * @returns {vec3} out
- */
- function transformMat4(out, a, m) {
- var x = a[0],
- y = a[1],
- z = a[2];
- var w = m[3] * x + m[7] * y + m[11] * z + m[15];
- w = w || 1.0;
- out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
- out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
- out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
- return out;
- }
- /**
- * Transforms the vec3 with a mat3.
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the vector to transform
- * @param {ReadonlyMat3} m the 3x3 matrix to transform with
- * @returns {vec3} out
- */
- function transformMat3(out, a, m) {
- var x = a[0],
- y = a[1],
- z = a[2];
- out[0] = x * m[0] + y * m[3] + z * m[6];
- out[1] = x * m[1] + y * m[4] + z * m[7];
- out[2] = x * m[2] + y * m[5] + z * m[8];
- return out;
- }
- /**
- * Transforms the vec3 with a quat
- * Can also be used for dual quaternions. (Multiply it with the real part)
- *
- * @param {vec3} out the receiving vector
- * @param {ReadonlyVec3} a the vector to transform
- * @param {ReadonlyQuat} q quaternion to transform with
- * @returns {vec3} out
- */
- function transformQuat(out, a, q) {
- // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
- var qx = q[0],
- qy = q[1],
- qz = q[2],
- qw = q[3];
- var x = a[0],
- y = a[1],
- z = a[2]; // var qvec = [qx, qy, qz];
- // var uv = vec3.cross([], qvec, a);
- var uvx = qy * z - qz * y,
- uvy = qz * x - qx * z,
- uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
- var uuvx = qy * uvz - qz * uvy,
- uuvy = qz * uvx - qx * uvz,
- uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
- var w2 = qw * 2;
- uvx *= w2;
- uvy *= w2;
- uvz *= w2; // vec3.scale(uuv, uuv, 2);
- uuvx *= 2;
- uuvy *= 2;
- uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
- out[0] = x + uvx + uuvx;
- out[1] = y + uvy + uuvy;
- out[2] = z + uvz + uuvz;
- return out;
- }
- /**
- * Returns whether or not the vectors have approximately the same elements in the same position.
- *
- * @param {ReadonlyVec3} a The first vector.
- * @param {ReadonlyVec3} b The second vector.
- * @returns {Boolean} True if the vectors are equal, false otherwise.
- */
- function equals$1(a, b) {
- var a0 = a[0],
- a1 = a[1],
- a2 = a[2];
- var b0 = b[0],
- b1 = b[1],
- b2 = b[2];
- return Math.abs(a0 - b0) <= EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));
- }
- /**
- * Alias for {@link vec3.length}
- * @function
- */
- var len = length;
- /**
- * Perform some operation over an array of vec3s.
- *
- * @param {Array} a the array of vectors to iterate over
- * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
- * @param {Number} offset Number of elements to skip at the beginning of the array
- * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
- * @param {Function} fn Function to call for each vector in the array
- * @param {Object} [arg] additional argument to pass to fn
- * @returns {Array} a
- * @function
- */
- var forEach = function () {
- var vec = create$2();
- return function (a, stride, offset, count, fn, arg) {
- var i, l;
- if (!stride) {
- stride = 3;
- }
- if (!offset) {
- offset = 0;
- }
- if (count) {
- l = Math.min(count * stride + offset, a.length);
- } else {
- l = a.length;
- }
- for (i = offset; i < l; i += stride) {
- vec[0] = a[i];
- vec[1] = a[i + 1];
- vec[2] = a[i + 2];
- fn(vec, vec, arg);
- a[i] = vec[0];
- a[i + 1] = vec[1];
- a[i + 2] = vec[2];
- }
- return a;
- };
- }();
- /**
- * 4 Dimensional Vector
- * @module vec4
- */
- /**
- * Creates a new, empty vec4
- *
- * @returns {vec4} a new 4D vector
- */
- function create$3() {
- var out = new ARRAY_TYPE(4);
- if (ARRAY_TYPE != Float32Array) {
- out[0] = 0;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- }
- return out;
- }
- /**
- * Creates a new vec4 initialized with the given values
- *
- * @param {Number} x X component
- * @param {Number} y Y component
- * @param {Number} z Z component
- * @param {Number} w W component
- * @returns {vec4} a new 4D vector
- */
- function fromValues$3(x, y, z, w) {
- var out = new ARRAY_TYPE(4);
- out[0] = x;
- out[1] = y;
- out[2] = z;
- out[3] = w;
- return out;
- }
- /**
- * Copy the values from one vec4 to another
- *
- * @param {vec4} out the receiving vector
- * @param {ReadonlyVec4} a the source vector
- * @returns {vec4} out
- */
- function copy$2(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- out[2] = a[2];
- out[3] = a[3];
- return out;
- }
- /**
- * Normalize a vec4
- *
- * @param {vec4} out the receiving vector
- * @param {ReadonlyVec4} a vector to normalize
- * @returns {vec4} out
- */
- function normalize$1(out, a) {
- var x = a[0];
- var y = a[1];
- var z = a[2];
- var w = a[3];
- var len = x * x + y * y + z * z + w * w;
- if (len > 0) {
- len = 1 / Math.sqrt(len);
- }
- out[0] = x * len;
- out[1] = y * len;
- out[2] = z * len;
- out[3] = w * len;
- return out;
- }
- /**
- * Transforms the vec4 with a mat4.
- *
- * @param {vec4} out the receiving vector
- * @param {ReadonlyVec4} a the vector to transform
- * @param {ReadonlyMat4} m matrix to transform with
- * @returns {vec4} out
- */
- function transformMat4$1(out, a, m) {
- var x = a[0],
- y = a[1],
- z = a[2],
- w = a[3];
- out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
- out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
- out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
- out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
- return out;
- }
- /**
- * Perform some operation over an array of vec4s.
- *
- * @param {Array} a the array of vectors to iterate over
- * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
- * @param {Number} offset Number of elements to skip at the beginning of the array
- * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
- * @param {Function} fn Function to call for each vector in the array
- * @param {Object} [arg] additional argument to pass to fn
- * @returns {Array} a
- * @function
- */
- var forEach$1 = function () {
- var vec = create$3();
- return function (a, stride, offset, count, fn, arg) {
- var i, l;
- if (!stride) {
- stride = 4;
- }
- if (!offset) {
- offset = 0;
- }
- if (count) {
- l = Math.min(count * stride + offset, a.length);
- } else {
- l = a.length;
- }
- for (i = offset; i < l; i += stride) {
- vec[0] = a[i];
- vec[1] = a[i + 1];
- vec[2] = a[i + 2];
- vec[3] = a[i + 3];
- fn(vec, vec, arg);
- a[i] = vec[0];
- a[i + 1] = vec[1];
- a[i + 2] = vec[2];
- a[i + 3] = vec[3];
- }
- return a;
- };
- }();
- /**
- * Quaternion
- * @module quat
- */
- /**
- * Creates a new identity quat
- *
- * @returns {quat} a new quaternion
- */
- function create$4() {
- var out = new ARRAY_TYPE(4);
- if (ARRAY_TYPE != Float32Array) {
- out[0] = 0;
- out[1] = 0;
- out[2] = 0;
- }
- out[3] = 1;
- return out;
- }
- /**
- * Sets a quat from the given angle and rotation axis,
- * then returns it.
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyVec3} axis the axis around which to rotate
- * @param {Number} rad the angle in radians
- * @returns {quat} out
- **/
- function setAxisAngle(out, axis, rad) {
- rad = rad * 0.5;
- var s = Math.sin(rad);
- out[0] = s * axis[0];
- out[1] = s * axis[1];
- out[2] = s * axis[2];
- out[3] = Math.cos(rad);
- return out;
- }
- /**
- * Multiplies two quat's
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a the first operand
- * @param {ReadonlyQuat} b the second operand
- * @returns {quat} out
- */
- function multiply$2(out, a, b) {
- var ax = a[0],
- ay = a[1],
- az = a[2],
- aw = a[3];
- var bx = b[0],
- by = b[1],
- bz = b[2],
- bw = b[3];
- out[0] = ax * bw + aw * bx + ay * bz - az * by;
- out[1] = ay * bw + aw * by + az * bx - ax * bz;
- out[2] = az * bw + aw * bz + ax * by - ay * bx;
- out[3] = aw * bw - ax * bx - ay * by - az * bz;
- return out;
- }
- /**
- * Performs a spherical linear interpolation between two quat
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a the first operand
- * @param {ReadonlyQuat} b the second operand
- * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
- * @returns {quat} out
- */
- function slerp(out, a, b, t) {
- // benchmarks:
- // http://jsperf.com/quaternion-slerp-implementations
- var ax = a[0],
- ay = a[1],
- az = a[2],
- aw = a[3];
- var bx = b[0],
- by = b[1],
- bz = b[2],
- bw = b[3];
- var omega, cosom, sinom, scale0, scale1; // calc cosine
- cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
- if (cosom < 0.0) {
- cosom = -cosom;
- bx = -bx;
- by = -by;
- bz = -bz;
- bw = -bw;
- } // calculate coefficients
- if (1.0 - cosom > EPSILON) {
- // standard case (slerp)
- omega = Math.acos(cosom);
- sinom = Math.sin(omega);
- scale0 = Math.sin((1.0 - t) * omega) / sinom;
- scale1 = Math.sin(t * omega) / sinom;
- } else {
- // "from" and "to" quaternions are very close
- // ... so we can do a linear interpolation
- scale0 = 1.0 - t;
- scale1 = t;
- } // calculate final values
- out[0] = scale0 * ax + scale1 * bx;
- out[1] = scale0 * ay + scale1 * by;
- out[2] = scale0 * az + scale1 * bz;
- out[3] = scale0 * aw + scale1 * bw;
- return out;
- }
- /**
- * Calculates the inverse of a quat
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a quat to calculate inverse of
- * @returns {quat} out
- */
- function invert$1(out, a) {
- var a0 = a[0],
- a1 = a[1],
- a2 = a[2],
- a3 = a[3];
- var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
- var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
- out[0] = -a0 * invDot;
- out[1] = -a1 * invDot;
- out[2] = -a2 * invDot;
- out[3] = a3 * invDot;
- return out;
- }
- /**
- * Creates a quaternion from the given 3x3 rotation matrix.
- *
- * NOTE: The resultant quaternion is not normalized, so you should be sure
- * to renormalize the quaternion yourself where necessary.
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyMat3} m rotation matrix
- * @returns {quat} out
- * @function
- */
- function fromMat3(out, m) {
- // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
- // article "Quaternion Calculus and Fast Animation".
- var fTrace = m[0] + m[4] + m[8];
- var fRoot;
- if (fTrace > 0.0) {
- // |w| > 1/2, may as well choose w > 1/2
- fRoot = Math.sqrt(fTrace + 1.0); // 2w
- out[3] = 0.5 * fRoot;
- fRoot = 0.5 / fRoot; // 1/(4w)
- out[0] = (m[5] - m[7]) * fRoot;
- out[1] = (m[6] - m[2]) * fRoot;
- out[2] = (m[1] - m[3]) * fRoot;
- } else {
- // |w| <= 1/2
- var i = 0;
- if (m[4] > m[0]) i = 1;
- if (m[8] > m[i * 3 + i]) i = 2;
- var j = (i + 1) % 3;
- var k = (i + 2) % 3;
- fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
- out[i] = 0.5 * fRoot;
- fRoot = 0.5 / fRoot;
- out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
- out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
- out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
- }
- return out;
- }
- /**
- * Creates a quaternion from the given euler angle x, y, z.
- *
- * @param {quat} out the receiving quaternion
- * @param {x} Angle to rotate around X axis in degrees.
- * @param {y} Angle to rotate around Y axis in degrees.
- * @param {z} Angle to rotate around Z axis in degrees.
- * @returns {quat} out
- * @function
- */
- function fromEuler(out, x, y, z) {
- var halfToRad = 0.5 * Math.PI / 180.0;
- x *= halfToRad;
- y *= halfToRad;
- z *= halfToRad;
- var sx = Math.sin(x);
- var cx = Math.cos(x);
- var sy = Math.sin(y);
- var cy = Math.cos(y);
- var sz = Math.sin(z);
- var cz = Math.cos(z);
- out[0] = sx * cy * cz - cx * sy * sz;
- out[1] = cx * sy * cz + sx * cy * sz;
- out[2] = cx * cy * sz - sx * sy * cz;
- out[3] = cx * cy * cz + sx * sy * sz;
- return out;
- }
- /**
- * Creates a new quat initialized with the given values
- *
- * @param {Number} x X component
- * @param {Number} y Y component
- * @param {Number} z Z component
- * @param {Number} w W component
- * @returns {quat} a new quaternion
- * @function
- */
- var fromValues$4 = fromValues$3;
- /**
- * Copy the values from one quat to another
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a the source quaternion
- * @returns {quat} out
- * @function
- */
- var copy$3 = copy$2;
- /**
- * Alias for {@link quat.multiply}
- * @function
- */
- var mul$1 = multiply$2;
- /**
- * Normalize a quat
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a quaternion to normalize
- * @returns {quat} out
- * @function
- */
- var normalize$2 = normalize$1;
- /**
- * Sets a quaternion to represent the shortest rotation from one
- * vector to another.
- *
- * Both vectors are assumed to be unit length.
- *
- * @param {quat} out the receiving quaternion.
- * @param {ReadonlyVec3} a the initial vector
- * @param {ReadonlyVec3} b the destination vector
- * @returns {quat} out
- */
- var rotationTo = function () {
- var tmpvec3 = create$2();
- var xUnitVec3 = fromValues$2(1, 0, 0);
- var yUnitVec3 = fromValues$2(0, 1, 0);
- return function (out, a, b) {
- var dot$1 = dot(a, b);
- if (dot$1 < -0.999999) {
- cross(tmpvec3, xUnitVec3, a);
- if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
- normalize(tmpvec3, tmpvec3);
- setAxisAngle(out, tmpvec3, Math.PI);
- return out;
- } else if (dot$1 > 0.999999) {
- out[0] = 0;
- out[1] = 0;
- out[2] = 0;
- out[3] = 1;
- return out;
- } else {
- cross(tmpvec3, a, b);
- out[0] = tmpvec3[0];
- out[1] = tmpvec3[1];
- out[2] = tmpvec3[2];
- out[3] = 1 + dot$1;
- return normalize$2(out, out);
- }
- };
- }();
- /**
- * Performs a spherical linear interpolation with two control points
- *
- * @param {quat} out the receiving quaternion
- * @param {ReadonlyQuat} a the first operand
- * @param {ReadonlyQuat} b the second operand
- * @param {ReadonlyQuat} c the third operand
- * @param {ReadonlyQuat} d the fourth operand
- * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
- * @returns {quat} out
- */
- var sqlerp = function () {
- var temp1 = create$4();
- var temp2 = create$4();
- return function (out, a, b, c, d, t) {
- slerp(temp1, a, d, t);
- slerp(temp2, b, c, t);
- slerp(out, temp1, temp2, 2 * t * (1 - t));
- return out;
- };
- }();
- /**
- * Sets the specified quaternion with values corresponding to the given
- * axes. Each axis is a vec3 and is expected to be unit length and
- * perpendicular to all other specified axes.
- *
- * @param {ReadonlyVec3} view the vector representing the viewing direction
- * @param {ReadonlyVec3} right the vector representing the local "right" direction
- * @param {ReadonlyVec3} up the vector representing the local "up" direction
- * @returns {quat} out
- */
- var setAxes = function () {
- var matr = create();
- return function (out, view, right, up) {
- matr[0] = right[0];
- matr[3] = right[1];
- matr[6] = right[2];
- matr[1] = up[0];
- matr[4] = up[1];
- matr[7] = up[2];
- matr[2] = -view[0];
- matr[5] = -view[1];
- matr[8] = -view[2];
- return normalize$2(out, fromMat3(out, matr));
- };
- }();
- /**
- * 2 Dimensional Vector
- * @module vec2
- */
- /**
- * Creates a new, empty vec2
- *
- * @returns {vec2} a new 2D vector
- */
- function create$5() {
- var out = new ARRAY_TYPE(2);
- if (ARRAY_TYPE != Float32Array) {
- out[0] = 0;
- out[1] = 0;
- }
- return out;
- }
- /**
- * Creates a new vec2 initialized with the given values
- *
- * @param {Number} x X component
- * @param {Number} y Y component
- * @returns {vec2} a new 2D vector
- */
- function fromValues$5(x, y) {
- var out = new ARRAY_TYPE(2);
- out[0] = x;
- out[1] = y;
- return out;
- }
- /**
- * Copy the values from one vec2 to another
- *
- * @param {vec2} out the receiving vector
- * @param {ReadonlyVec2} a the source vector
- * @returns {vec2} out
- */
- function copy$4(out, a) {
- out[0] = a[0];
- out[1] = a[1];
- return out;
- }
- /**
- * Normalize a vec2
- *
- * @param {vec2} out the receiving vector
- * @param {ReadonlyVec2} a vector to normalize
- * @returns {vec2} out
- */
- function normalize$3(out, a) {
- var x = a[0],
- y = a[1];
- var len = x * x + y * y;
- if (len > 0) {
- //TODO: evaluate use of glm_invsqrt here?
- len = 1 / Math.sqrt(len);
- }
- out[0] = a[0] * len;
- out[1] = a[1] * len;
- return out;
- }
- /**
- * Calculates the dot product of two vec2's
- *
- * @param {ReadonlyVec2} a the first operand
- * @param {ReadonlyVec2} b the second operand
- * @returns {Number} dot product of a and b
- */
- function dot$1(a, b) {
- return a[0] * b[0] + a[1] * b[1];
- }
- /**
- * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
- *
- * @param {ReadonlyVec2} a The first vector.
- * @param {ReadonlyVec2} b The second vector.
- * @returns {Boolean} True if the vectors are equal, false otherwise.
- */
- function exactEquals$1(a, b) {
- return a[0] === b[0] && a[1] === b[1];
- }
- /**
- * Perform some operation over an array of vec2s.
- *
- * @param {Array} a the array of vectors to iterate over
- * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
- * @param {Number} offset Number of elements to skip at the beginning of the array
- * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
- * @param {Function} fn Function to call for each vector in the array
- * @param {Object} [arg] additional argument to pass to fn
- * @returns {Array} a
- * @function
- */
- var forEach$2 = function () {
- var vec = create$5();
- return function (a, stride, offset, count, fn, arg) {
- var i, l;
- if (!stride) {
- stride = 2;
- }
- if (!offset) {
- offset = 0;
- }
- if (count) {
- l = Math.min(count * stride + offset, a.length);
- } else {
- l = a.length;
- }
- for (i = offset; i < l; i += stride) {
- vec[0] = a[i];
- vec[1] = a[i + 1];
- fn(vec, vec, arg);
- a[i] = vec[0];
- a[i + 1] = vec[1];
- }
- return a;
- };
- }();
- function clonePath(path) {
- return path.map(function (x) { return (Array.isArray(x) ? [].concat(x) : x); });
- }
- /******************************************************************************
- Copyright (c) Microsoft Corporation.
- Permission to use, copy, modify, and/or distribute this software for any
- purpose with or without fee is hereby granted.
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
- ***************************************************************************** */
- var __assign = function() {
- __assign = Object.assign || function __assign(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
- };
- var paramsParser = {
- x1: 0,
- y1: 0,
- x2: 0,
- y2: 0,
- x: 0,
- y: 0,
- qx: null,
- qy: null,
- };
- function fixArc(pathArray, allPathCommands, i) {
- if (pathArray[i].length > 7) {
- pathArray[i].shift();
- var pi = pathArray[i];
- // const ni = i + 1;
- var ni = i;
- while (pi.length) {
- // if created multiple C:s, their original seg is saved
- allPathCommands[i] = 'A';
- // @ts-ignore
- pathArray.splice((ni += 1), 0, ['C'].concat(pi.splice(0, 6)));
- }
- pathArray.splice(i, 1);
- }
- }
- var paramsCount = {
- a: 7,
- c: 6,
- h: 1,
- l: 2,
- m: 2,
- r: 4,
- q: 4,
- s: 4,
- t: 2,
- v: 1,
- z: 0,
- };
- /**
- * Iterates an array to check if it's an actual `PathArray`.
- */
- function isPathArray(path) {
- return (Array.isArray(path) &&
- path.every(function (seg) {
- var lk = seg[0].toLowerCase();
- return paramsCount[lk] === seg.length - 1 && 'achlmqstvz'.includes(lk);
- }));
- }
- /**
- * Iterates an array to check if it's a `PathArray`
- * with all absolute values.
- */
- function isAbsoluteArray(path) {
- return (isPathArray(path) &&
- // @ts-ignore -- `isPathArray` also checks if it's `Array`
- path.every(function (_a) {
- var x = _a[0];
- return x === x.toUpperCase();
- }));
- }
- /**
- * Iterates an array to check if it's a `PathArray`
- * with all segments are in non-shorthand notation
- * with absolute values.
- */
- function isNormalizedArray(path) {
- return isAbsoluteArray(path) && path.every(function (_a) {
- var pc = _a[0];
- return 'ACLMQZ'.includes(pc);
- });
- }
- /**
- * Breaks the parsing of a pathString once a segment is finalized.
- */
- function finalizeSegment(path) {
- var pathCommand = path.pathValue[path.segmentStart];
- var LK = pathCommand.toLowerCase();
- var data = path.data;
- while (data.length >= paramsCount[LK]) {
- // overloaded `moveTo`
- // https://github.com/rveciana/svg-path-properties/blob/master/src/parse.ts
- if (LK === 'm' && data.length > 2) {
- // @ts-ignore
- path.segments.push([pathCommand].concat(data.splice(0, 2)));
- LK = 'l';
- pathCommand = pathCommand === 'm' ? 'l' : 'L';
- }
- else {
- // @ts-ignore
- path.segments.push([pathCommand].concat(data.splice(0, paramsCount[LK])));
- }
- if (!paramsCount[LK]) {
- break;
- }
- }
- }
- /**
- * Validates an A (arc-to) specific path command value.
- * Usually a `large-arc-flag` or `sweep-flag`.
- */
- function scanFlag(path) {
- var index = path.index, pathValue = path.pathValue;
- var code = pathValue.charCodeAt(index);
- if (code === 0x30 /* 0 */) {
- path.param = 0;
- path.index += 1;
- return;
- }
- if (code === 0x31 /* 1 */) {
- path.param = 1;
- path.index += 1;
- return;
- }
- path.err = "[path-util]: invalid Arc flag \"" + pathValue[index] + "\", expecting 0 or 1 at index " + index;
- }
- /**
- * Checks if the character is or belongs to a number.
- * [0-9]|+|-|.
- */
- function isDigitStart(code) {
- return ((code >= 48 && code <= 57) /* 0..9 */ || code === 0x2b /* + */ || code === 0x2d /* - */ || code === 0x2e); /* . */
- }
- function isDigit(code) {
- return code >= 48 && code <= 57; // 0..9
- }
- /**
- * Validates every character of the path string,
- * every path command, negative numbers or floating point numbers.
- */
- function scanParam(path) {
- var max = path.max, pathValue = path.pathValue, start = path.index;
- var index = start;
- var zeroFirst = false;
- var hasCeiling = false;
- var hasDecimal = false;
- var hasDot = false;
- var ch;
- if (index >= max) {
- // path.err = 'SvgPath: missed param (at pos ' + index + ')';
- path.err = "[path-util]: Invalid path value at index " + index + ", \"pathValue\" is missing param";
- return;
- }
- ch = pathValue.charCodeAt(index);
- if (ch === 0x2b /* + */ || ch === 0x2d /* - */) {
- index += 1;
- // ch = (index < max) ? pathValue.charCodeAt(index) : 0;
- ch = pathValue.charCodeAt(index);
- }
- // This logic is shamelessly borrowed from Esprima
- // https://github.com/ariya/esprimas
- if (!isDigit(ch) && ch !== 0x2e /* . */) {
- // path.err = 'SvgPath: param should start with 0..9 or `.` (at pos ' + index + ')';
- path.err = "[path-util]: Invalid path value at index " + index + ", \"" + pathValue[index] + "\" is not a number";
- return;
- }
- if (ch !== 0x2e /* . */) {
- zeroFirst = ch === 0x30 /* 0 */;
- index += 1;
- ch = pathValue.charCodeAt(index);
- if (zeroFirst && index < max) {
- // decimal number starts with '0' such as '09' is illegal.
- if (ch && isDigit(ch)) {
- // path.err = 'SvgPath: numbers started with `0` such as `09`
- // are illegal (at pos ' + start + ')';
- path.err = "[path-util]: Invalid path value at index " + start + ", \"" + pathValue[start] + "\" illegal number";
- return;
- }
- }
- while (index < max && isDigit(pathValue.charCodeAt(index))) {
- index += 1;
- hasCeiling = true;
- }
- ch = pathValue.charCodeAt(index);
- }
- if (ch === 0x2e /* . */) {
- hasDot = true;
- index += 1;
- while (isDigit(pathValue.charCodeAt(index))) {
- index += 1;
- hasDecimal = true;
- }
- ch = pathValue.charCodeAt(index);
- }
- if (ch === 0x65 /* e */ || ch === 0x45 /* E */) {
- if (hasDot && !hasCeiling && !hasDecimal) {
- path.err = "[path-util]: Invalid path value at index " + index + ", \"" + pathValue[index] + "\" invalid float exponent";
- return;
- }
- index += 1;
- ch = pathValue.charCodeAt(index);
- if (ch === 0x2b /* + */ || ch === 0x2d /* - */) {
- index += 1;
- }
- if (index < max && isDigit(pathValue.charCodeAt(index))) {
- while (index < max && isDigit(pathValue.charCodeAt(index))) {
- index += 1;
- }
- }
- else {
- path.err = "[path-util]: Invalid path value at index " + index + ", \"" + pathValue[index] + "\" invalid integer exponent";
- return;
- }
- }
- path.index = index;
- path.param = +path.pathValue.slice(start, index);
- }
- /**
- * Checks if the character is a space.
- */
- function isSpace(ch) {
- var specialSpaces = [
- 0x1680, 0x180e, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x202f,
- 0x205f, 0x3000, 0xfeff,
- ];
- /* istanbul ignore next */
- return (ch === 0x0a ||
- ch === 0x0d ||
- ch === 0x2028 ||
- ch === 0x2029 || // Line terminators
- // White spaces
- ch === 0x20 ||
- ch === 0x09 ||
- ch === 0x0b ||
- ch === 0x0c ||
- ch === 0xa0 ||
- (ch >= 0x1680 && specialSpaces.includes(ch)));
- }
- /**
- * Points the parser to the next character in the
- * path string every time it encounters any kind of
- * space character.
- */
- function skipSpaces(path) {
- var pathValue = path.pathValue, max = path.max;
- while (path.index < max && isSpace(pathValue.charCodeAt(path.index))) {
- path.index += 1;
- }
- }
- /**
- * Checks if the character is a path command.
- */
- function isPathCommand(code) {
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy
- switch (code | 0x20) {
- case 0x6d /* m */:
- case 0x7a /* z */:
- case 0x6c /* l */:
- case 0x68 /* h */:
- case 0x76 /* v */:
- case 0x63 /* c */:
- case 0x73 /* s */:
- case 0x71 /* q */:
- case 0x74 /* t */:
- case 0x61 /* a */:
- // case 0x72/* r */:
- return true;
- default:
- return false;
- }
- }
- /**
- * Checks if the character is an A (arc-to) path command.
- */
- function isArcCommand(code) {
- return (code | 0x20) === 0x61;
- }
- /**
- * Scans every character in the path string to determine
- * where a segment starts and where it ends.
- */
- function scanSegment(path) {
- var max = path.max, pathValue = path.pathValue, index = path.index;
- var cmdCode = pathValue.charCodeAt(index);
- var reqParams = paramsCount[pathValue[index].toLowerCase()];
- path.segmentStart = index;
- if (!isPathCommand(cmdCode)) {
- path.err = "[path-util]: Invalid path value \"" + pathValue[index] + "\" is not a path command";
- return;
- }
- path.index += 1;
- skipSpaces(path);
- path.data = [];
- if (!reqParams) {
- // Z
- finalizeSegment(path);
- return;
- }
- for (;;) {
- for (var i = reqParams; i > 0; i -= 1) {
- if (isArcCommand(cmdCode) && (i === 3 || i === 4))
- scanFlag(path);
- else
- scanParam(path);
- if (path.err.length) {
- return;
- }
- path.data.push(path.param);
- skipSpaces(path);
- // after ',' param is mandatory
- if (path.index < max && pathValue.charCodeAt(path.index) === 0x2c /* , */) {
- path.index += 1;
- skipSpaces(path);
- }
- }
- if (path.index >= path.max) {
- break;
- }
- // Stop on next segment
- if (!isDigitStart(pathValue.charCodeAt(path.index))) {
- break;
- }
- }
- finalizeSegment(path);
- }
- /**
- * The `PathParser` is used by the `parsePathString` static method
- * to generate a `pathArray`.
- */
- var PathParser = /** @class */ (function () {
- function PathParser(pathString) {
- this.pathValue = pathString;
- // @ts-ignore
- this.segments = [];
- this.max = pathString.length;
- this.index = 0;
- this.param = 0.0;
- this.segmentStart = 0;
- this.data = [];
- this.err = '';
- }
- return PathParser;
- }());
- /**
- * Parses a path string value and returns an array
- * of segments we like to call `pathArray`.
- */
- function parsePathString(pathInput) {
- if (isPathArray(pathInput)) {
- return clonePath(pathInput);
- }
- var path = new PathParser(pathInput);
- skipSpaces(path);
- while (path.index < path.max && !path.err.length) {
- scanSegment(path);
- }
- return path.err ? path.err : path.segments;
- }
- function path2Absolute(pathInput) {
- if (isAbsoluteArray(pathInput)) {
- return clonePath(pathInput);
- }
- var path = parsePathString(pathInput);
- // if (!path || !path.length) {
- // return [['M', 0, 0]];
- // }
- var x = 0;
- var y = 0;
- var mx = 0;
- var my = 0;
- // @ts-ignore
- return path.map(function (segment) {
- var values = segment.slice(1).map(Number);
- var pathCommand = segment[0];
- var absCommand = pathCommand.toUpperCase();
- if (pathCommand === 'M') {
- x = values[0], y = values[1];
- mx = x;
- my = y;
- return ['M', x, y];
- }
- var absoluteSegment;
- if (pathCommand !== absCommand) {
- switch (absCommand) {
- case 'A':
- absoluteSegment = [
- absCommand,
- values[0],
- values[1],
- values[2],
- values[3],
- values[4],
- values[5] + x,
- values[6] + y,
- ];
- break;
- case 'V':
- absoluteSegment = [absCommand, values[0] + y];
- break;
- case 'H':
- absoluteSegment = [absCommand, values[0] + x];
- break;
- default: {
- // use brakets for `eslint: no-case-declaration`
- // https://stackoverflow.com/a/50753272/803358
- var absValues = values.map(function (n, j) { return n + (j % 2 ? y : x); });
- // for n, l, c, s, q, t
- // @ts-ignore
- absoluteSegment = [absCommand].concat(absValues);
- }
- }
- }
- else {
- // @ts-ignore
- absoluteSegment = [absCommand].concat(values);
- }
- var segLength = absoluteSegment.length;
- switch (absCommand) {
- case 'Z':
- x = mx;
- y = my;
- break;
- case 'H':
- x = absoluteSegment[1];
- break;
- case 'V':
- y = absoluteSegment[1];
- break;
- default:
- x = absoluteSegment[segLength - 2];
- y = absoluteSegment[segLength - 1];
- if (absCommand === 'M') {
- mx = x;
- my = y;
- }
- }
- return absoluteSegment;
- });
- }
- /**
- * Normalizes a single segment of a `PathArray` object.
- * eg. H/V -> L, T -> Q
- */
- function normalizeSegment(segment, params) {
- var pathCommand = segment[0];
- var px1 = params.x1, py1 = params.y1, px2 = params.x2, py2 = params.y2;
- var values = segment.slice(1).map(Number);
- var result = segment;
- if (!'TQ'.includes(pathCommand)) {
- // optional but good to be cautious
- params.qx = null;
- params.qy = null;
- }
- if (pathCommand === 'H') {
- result = ['L', segment[1], py1];
- }
- else if (pathCommand === 'V') {
- result = ['L', px1, segment[1]];
- }
- else if (pathCommand === 'S') {
- var x1 = px1 * 2 - px2;
- var y1 = py1 * 2 - py2;
- params.x1 = x1;
- params.y1 = y1;
- result = ['C', x1, y1].concat(values);
- }
- else if (pathCommand === 'T') {
- var qx = px1 * 2 - params.qx;
- var qy = py1 * 2 - params.qy;
- params.qx = qx;
- params.qy = qy;
- result = ['Q', qx, qy].concat(values);
- }
- else if (pathCommand === 'Q') {
- var nqx = values[0], nqy = values[1];
- params.qx = nqx;
- params.qy = nqy;
- }
- return result;
- }
- /**
- * @example
- * const path = 'M0 0 H50';
- * const normalizedPath = SVGPathCommander.normalizePath(path);
- * // result => [['M', 0, 0], ['L', 50, 0]]
- */
- function normalizePath(pathInput) {
- if (isNormalizedArray(pathInput)) {
- return clonePath(pathInput);
- }
- var path = path2Absolute(pathInput);
- var params = __assign({}, paramsParser);
- for (var i = 0; i < path.length; i += 1) {
- // Save current path command
- path[i] = normalizeSegment(path[i], params);
- var segment = path[i];
- var seglen = segment.length;
- params.x1 = +segment[seglen - 2];
- params.y1 = +segment[seglen - 1];
- params.x2 = +segment[seglen - 4] || params.x1;
- params.y2 = +segment[seglen - 3] || params.y1;
- }
- return path;
- }
- /**
- * Iterates an array to check if it's a `PathArray`
- * with all C (cubic bezier) segments.
- *
- * @param {string | PathArray} path the `Array` to be checked
- * @returns {boolean} iteration result
- */
- function isCurveArray(path) {
- return isNormalizedArray(path) && path.every(function (_a) {
- var pc = _a[0];
- return 'MC'.includes(pc);
- });
- }
- function rotateVector(x, y, rad) {
- var X = x * Math.cos(rad) - y * Math.sin(rad);
- var Y = x * Math.sin(rad) + y * Math.cos(rad);
- return { x: X, y: Y };
- }
- /**
- * Converts A (arc-to) segments to C (cubic-bezier-to).
- *
- * For more information of where this math came from visit:
- * http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
- */
- function arcToCubic(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, recursive) {
- var x1 = X1;
- var y1 = Y1;
- var rx = RX;
- var ry = RY;
- var x2 = X2;
- var y2 = Y2;
- // for more information of where this Math came from visit:
- // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
- var d120 = (Math.PI * 120) / 180;
- var rad = (Math.PI / 180) * (+angle || 0);
- /** @type {number[]} */
- var res = [];
- var xy;
- var f1;
- var f2;
- var cx;
- var cy;
- if (!recursive) {
- xy = rotateVector(x1, y1, -rad);
- x1 = xy.x;
- y1 = xy.y;
- xy = rotateVector(x2, y2, -rad);
- x2 = xy.x;
- y2 = xy.y;
- var x = (x1 - x2) / 2;
- var y = (y1 - y2) / 2;
- var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
- if (h > 1) {
- h = Math.sqrt(h);
- rx *= h;
- ry *= h;
- }
- var rx2 = rx * rx;
- var ry2 = ry * ry;
- var k = (LAF === SF ? -1 : 1) *
- Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)));
- cx = (k * rx * y) / ry + (x1 + x2) / 2;
- cy = (k * -ry * x) / rx + (y1 + y2) / 2;
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy no-bitwise
- f1 = Math.asin(((((y1 - cy) / ry) * Math.pow(10, 9)) >> 0) / Math.pow(10, 9));
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy no-bitwise
- f2 = Math.asin(((((y2 - cy) / ry) * Math.pow(10, 9)) >> 0) / Math.pow(10, 9));
- f1 = x1 < cx ? Math.PI - f1 : f1;
- f2 = x2 < cx ? Math.PI - f2 : f2;
- if (f1 < 0)
- f1 = Math.PI * 2 + f1;
- if (f2 < 0)
- f2 = Math.PI * 2 + f2;
- if (SF && f1 > f2) {
- f1 -= Math.PI * 2;
- }
- if (!SF && f2 > f1) {
- f2 -= Math.PI * 2;
- }
- }
- else {
- f1 = recursive[0], f2 = recursive[1], cx = recursive[2], cy = recursive[3];
- }
- var df = f2 - f1;
- if (Math.abs(df) > d120) {
- var f2old = f2;
- var x2old = x2;
- var y2old = y2;
- f2 = f1 + d120 * (SF && f2 > f1 ? 1 : -1);
- x2 = cx + rx * Math.cos(f2);
- y2 = cy + ry * Math.sin(f2);
- res = arcToCubic(x2, y2, rx, ry, angle, 0, SF, x2old, y2old, [f2, f2old, cx, cy]);
- }
- df = f2 - f1;
- var c1 = Math.cos(f1);
- var s1 = Math.sin(f1);
- var c2 = Math.cos(f2);
- var s2 = Math.sin(f2);
- var t = Math.tan(df / 4);
- var hx = (4 / 3) * rx * t;
- var hy = (4 / 3) * ry * t;
- var m1 = [x1, y1];
- var m2 = [x1 + hx * s1, y1 - hy * c1];
- var m3 = [x2 + hx * s2, y2 - hy * c2];
- var m4 = [x2, y2];
- m2[0] = 2 * m1[0] - m2[0];
- m2[1] = 2 * m1[1] - m2[1];
- if (recursive) {
- return m2.concat(m3, m4, res);
- // return [...m2, ...m3, ...m4, ...res];
- }
- res = m2.concat(m3, m4, res);
- // res = [...m2, ...m3, ...m4, ...res];
- var newres = [];
- for (var i = 0, ii = res.length; i < ii; i += 1) {
- newres[i] = i % 2 ? rotateVector(res[i - 1], res[i], rad).y : rotateVector(res[i], res[i + 1], rad).x;
- }
- return newres;
- }
- // const TAU = Math.PI * 2;
- // const mapToEllipse = (
- // { x, y }: { x: number; y: number },
- // rx: number,
- // ry: number,
- // cosphi: number,
- // sinphi: number,
- // centerx: number,
- // centery: number,
- // ) => {
- // x *= rx;
- // y *= ry;
- // const xp = cosphi * x - sinphi * y;
- // const yp = sinphi * x + cosphi * y;
- // return {
- // x: xp + centerx,
- // y: yp + centery,
- // };
- // };
- // const approxUnitArc = (ang1: number, ang2: number) => {
- // // If 90 degree circular arc, use a constant
- // // as derived from http://spencermortensen.com/articles/bezier-circle
- // const a =
- // ang2 === 1.5707963267948966
- // ? 0.551915024494
- // : ang2 === -1.5707963267948966
- // ? -0.551915024494
- // : (4 / 3) * Math.tan(ang2 / 4);
- // const x1 = Math.cos(ang1);
- // const y1 = Math.sin(ang1);
- // const x2 = Math.cos(ang1 + ang2);
- // const y2 = Math.sin(ang1 + ang2);
- // return [
- // {
- // x: x1 - y1 * a,
- // y: y1 + x1 * a,
- // },
- // {
- // x: x2 + y2 * a,
- // y: y2 - x2 * a,
- // },
- // {
- // x: x2,
- // y: y2,
- // },
- // ];
- // };
- // const vectorAngle = (ux: number, uy: number, vx: number, vy: number) => {
- // const sign = ux * vy - uy * vx < 0 ? -1 : 1;
- // let dot = ux * vx + uy * vy;
- // if (dot > 1) {
- // dot = 1;
- // }
- // if (dot < -1) {
- // dot = -1;
- // }
- // return sign * Math.acos(dot);
- // };
- // const getArcCenter = (
- // px: any,
- // py: any,
- // cx: any,
- // cy: any,
- // rx: number,
- // ry: number,
- // largeArcFlag: number,
- // sweepFlag: number,
- // sinphi: number,
- // cosphi: number,
- // pxp: number,
- // pyp: number,
- // ) => {
- // const rxsq = Math.pow(rx, 2);
- // const rysq = Math.pow(ry, 2);
- // const pxpsq = Math.pow(pxp, 2);
- // const pypsq = Math.pow(pyp, 2);
- // let radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq;
- // if (radicant < 0) {
- // radicant = 0;
- // }
- // radicant /= rxsq * pypsq + rysq * pxpsq;
- // radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);
- // const centerxp = ((radicant * rx) / ry) * pyp;
- // const centeryp = ((radicant * -ry) / rx) * pxp;
- // const centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2;
- // const centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2;
- // const vx1 = (pxp - centerxp) / rx;
- // const vy1 = (pyp - centeryp) / ry;
- // const vx2 = (-pxp - centerxp) / rx;
- // const vy2 = (-pyp - centeryp) / ry;
- // const ang1 = vectorAngle(1, 0, vx1, vy1);
- // let ang2 = vectorAngle(vx1, vy1, vx2, vy2);
- // if (sweepFlag === 0 && ang2 > 0) {
- // ang2 -= TAU;
- // }
- // if (sweepFlag === 1 && ang2 < 0) {
- // ang2 += TAU;
- // }
- // return [centerx, centery, ang1, ang2];
- // };
- // const arcToBezier = ({ px, py, cx, cy, rx, ry, xAxisRotation = 0, largeArcFlag = 0, sweepFlag = 0 }) => {
- // const curves = [];
- // if (rx === 0 || ry === 0) {
- // return [{ x1: 0, y1: 0, x2: 0, y2: 0, x: cx, y: cy }];
- // }
- // const sinphi = Math.sin((xAxisRotation * TAU) / 360);
- // const cosphi = Math.cos((xAxisRotation * TAU) / 360);
- // const pxp = (cosphi * (px - cx)) / 2 + (sinphi * (py - cy)) / 2;
- // const pyp = (-sinphi * (px - cx)) / 2 + (cosphi * (py - cy)) / 2;
- // if (pxp === 0 && pyp === 0) {
- // return [{ x1: 0, y1: 0, x2: 0, y2: 0, x: cx, y: cy }];
- // }
- // rx = Math.abs(rx);
- // ry = Math.abs(ry);
- // const lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2);
- // if (lambda > 1) {
- // rx *= Math.sqrt(lambda);
- // ry *= Math.sqrt(lambda);
- // }
- // let [centerx, centery, ang1, ang2] = getArcCenter(
- // px,
- // py,
- // cx,
- // cy,
- // rx,
- // ry,
- // largeArcFlag,
- // sweepFlag,
- // sinphi,
- // cosphi,
- // pxp,
- // pyp,
- // );
- // // If 'ang2' == 90.0000000001, then `ratio` will evaluate to
- // // 1.0000000001. This causes `segments` to be greater than one, which is an
- // // unecessary split, and adds extra points to the bezier curve. To alleviate
- // // this issue, we round to 1.0 when the ratio is close to 1.0.
- // let ratio = Math.abs(ang2) / (TAU / 4);
- // if (Math.abs(1.0 - ratio) < 0.0000001) {
- // ratio = 1.0;
- // }
- // const segments = Math.max(Math.ceil(ratio), 1);
- // ang2 /= segments;
- // for (let i = 0; i < segments; i++) {
- // curves.push(approxUnitArc(ang1, ang2));
- // ang1 += ang2;
- // }
- // return curves.map((curve) => {
- // const { x: x1, y: y1 } = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery);
- // const { x: x2, y: y2 } = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery);
- // const { x, y } = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery);
- // return { x1, y1, x2, y2, x, y };
- // });
- // };
- // export function arcToCubic(
- // x1: number,
- // y1: number,
- // rx: number,
- // ry: number,
- // angle: number,
- // LAF: number,
- // SF: number,
- // x2: number,
- // y2: number,
- // ) {
- // const curves = arcToBezier({
- // px: x1,
- // py: y1,
- // cx: x2,
- // cy: y2,
- // rx,
- // ry,
- // xAxisRotation: angle,
- // largeArcFlag: LAF,
- // sweepFlag: SF,
- // });
- // return curves.reduce((prev, cur) => {
- // const { x1, y1, x2, y2, x, y } = cur;
- // prev.push(x1, y1, x2, y2, x, y);
- // return prev;
- // }, [] as number[]);
- // }
- function quadToCubic(x1, y1, qx, qy, x2, y2) {
- var r13 = 1 / 3;
- var r23 = 2 / 3;
- return [
- r13 * x1 + r23 * qx,
- r13 * y1 + r23 * qy,
- r13 * x2 + r23 * qx,
- r13 * y2 + r23 * qy,
- x2,
- y2, // x,y
- ];
- }
- function midPoint(a, b, t) {
- var ax = a[0];
- var ay = a[1];
- var bx = b[0];
- var by = b[1];
- return [ax + (bx - ax) * t, ay + (by - ay) * t];
- }
- function distanceSquareRoot(a, b) {
- return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]));
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the minimum and maximum {x,y} coordinates of a line (L,V,H,Z) segment.
- */
- function segmentLineFactory(x1, y1, x2, y2, distance) {
- var length = distanceSquareRoot([x1, y1], [x2, y2]);
- var point = { x: 0, y: 0 };
- if (typeof distance === 'number') {
- if (distance <= 0) {
- point = { x: x1, y: y1 };
- }
- else if (distance >= length) {
- point = { x: x2, y: y2 };
- }
- else {
- var _a = midPoint([x1, y1], [x2, y2], distance / length), x = _a[0], y = _a[1];
- point = { x: x, y: y };
- }
- }
- return {
- length: length,
- point: point,
- min: {
- x: Math.min(x1, x2),
- y: Math.min(y1, y2),
- },
- max: {
- x: Math.max(x1, x2),
- y: Math.max(y1, y2),
- },
- };
- }
- function lineToCubic(x1, y1, x2, y2) {
- var t = 0.5;
- var p0 = [x1, y1];
- var p1 = [x2, y2];
- var p2 = midPoint(p0, p1, t);
- var p3 = midPoint(p1, p2, t);
- var p4 = midPoint(p2, p3, t);
- var p5 = midPoint(p3, p4, t);
- var p6 = midPoint(p4, p5, t);
- // const seg1 = [...p0, ...p2, ...p4, ...p6, t];
- // @ts-ignore
- var cp1 = segmentLineFactory(p0[0], p0[1], p2[0], p2[1], p4[0]).point;
- // const seg2 = [...p6, ...p5, ...p3, ...p1, 0];
- // @ts-ignore
- var cp2 = segmentLineFactory(p6[0], p6[1], p5[0], p5[1], p3[0]).point;
- return [cp1.x, cp1.y, cp2.x, cp2.y, x2, y2];
- }
- function segmentToCubic(segment, params) {
- var pathCommand = segment[0];
- var values = segment.slice(1).map(Number);
- var x = values[0], y = values[1];
- var args;
- var px1 = params.x1, py1 = params.y1, px = params.x, py = params.y;
- if (!'TQ'.includes(pathCommand)) {
- params.qx = null;
- params.qy = null;
- }
- switch (pathCommand) {
- case 'M':
- params.x = x;
- params.y = y;
- return segment;
- case 'A':
- args = [px1, py1].concat(values);
- // @ts-ignore
- return ['C'].concat(arcToCubic(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]));
- case 'Q':
- params.qx = x;
- params.qy = y;
- args = [px1, py1].concat(values);
- // @ts-ignore
- return ['C'].concat(quadToCubic(args[0], args[1], args[2], args[3], args[4], args[5]));
- case 'L':
- // @ts-ignore
- return ['C'].concat(lineToCubic(px1, py1, x, y));
- case 'Z':
- // prevent NaN from divide 0
- if (px1 === px && py1 === py) {
- return ['C', px1, py1, px, py, px, py];
- }
- // @ts-ignore
- return ['C'].concat(lineToCubic(px1, py1, px, py));
- }
- return segment;
- }
- // import { fixPath } from '../process/fix-path';
- function path2Curve(pathInput, needZCommandIndexes) {
- if (needZCommandIndexes === void 0) { needZCommandIndexes = false; }
- if (isCurveArray(pathInput)) {
- var cloned = clonePath(pathInput);
- if (needZCommandIndexes) {
- return [cloned, []];
- }
- else {
- return cloned;
- }
- }
- // fixPath will remove 'Z' command
- // const path = fixPath(normalizePath(pathInput));
- var path = normalizePath(pathInput);
- var params = __assign({}, paramsParser);
- var allPathCommands = [];
- var pathCommand = '';
- var ii = path.length;
- var segment;
- var seglen;
- var zCommandIndexes = [];
- for (var i = 0; i < ii; i += 1) {
- if (path[i])
- pathCommand = path[i][0];
- allPathCommands[i] = pathCommand;
- var curveSegment = segmentToCubic(path[i], params);
- path[i] = curveSegment;
- fixArc(path, allPathCommands, i);
- ii = path.length; // solves curveArrays ending in Z
- // keep Z command account for lineJoin
- // @see https://github.com/antvis/util/issues/68
- if (pathCommand === 'Z') {
- zCommandIndexes.push(i);
- }
- segment = path[i];
- seglen = segment.length;
- params.x1 = +segment[seglen - 2];
- params.y1 = +segment[seglen - 1];
- params.x2 = +segment[seglen - 4] || params.x1;
- params.y2 = +segment[seglen - 3] || params.y1;
- }
- // validate
- if (needZCommandIndexes) {
- return [path, zCommandIndexes];
- }
- else {
- return path;
- }
- }
- // reverse CURVE based pathArray segments only
- function reverseCurve(pathArray) {
- var rotatedCurve = pathArray
- .slice(1)
- .map(function (x, i, curveOnly) {
- // @ts-ignore
- return !i ? pathArray[0].slice(1).concat(x.slice(1)) : curveOnly[i - 1].slice(-2).concat(x.slice(1));
- })
- // @ts-ignore
- .map(function (x) { return x.map(function (y, i) { return x[x.length - i - 2 * (1 - (i % 2))]; }); })
- .reverse();
- return [['M'].concat(rotatedCurve[0].slice(0, 2))].concat(rotatedCurve.map(function (x) { return ['C'].concat(x.slice(2)); }));
- }
- function angleBetween(v0, v1) {
- var v0x = v0.x, v0y = v0.y;
- var v1x = v1.x, v1y = v1.y;
- var p = v0x * v1x + v0y * v1y;
- var n = Math.sqrt((Math.pow(v0x, 2) + Math.pow(v0y, 2)) * (Math.pow(v1x, 2) + Math.pow(v1y, 2)));
- var sign = v0x * v1y - v0y * v1x < 0 ? -1 : 1;
- var angle = sign * Math.acos(p / n);
- return angle;
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the minimum and maximum {x,y} coordinates of a C (cubic-bezier) segment.
- * @see https://github.com/MadLittleMods/svg-curve-lib/blob/master/src/js/svg-curve-lib.js
- */
- function getPointAtArcSegmentLength(x1, y1, RX, RY, angle, LAF, SF, x, y, t) {
- var abs = Math.abs, sin = Math.sin, cos = Math.cos, sqrt = Math.sqrt, PI = Math.PI;
- var rx = abs(RX);
- var ry = abs(RY);
- var xRot = ((angle % 360) + 360) % 360;
- var xRotRad = xRot * (PI / 180);
- if (x1 === x && y1 === y) {
- return { x: x1, y: y1 };
- }
- if (rx === 0 || ry === 0) {
- return segmentLineFactory(x1, y1, x, y, t).point;
- }
- var dx = (x1 - x) / 2;
- var dy = (y1 - y) / 2;
- var transformedPoint = {
- x: cos(xRotRad) * dx + sin(xRotRad) * dy,
- y: -sin(xRotRad) * dx + cos(xRotRad) * dy,
- };
- var radiiCheck = Math.pow(transformedPoint.x, 2) / Math.pow(rx, 2) + Math.pow(transformedPoint.y, 2) / Math.pow(ry, 2);
- if (radiiCheck > 1) {
- rx *= sqrt(radiiCheck);
- ry *= sqrt(radiiCheck);
- }
- var cSquareNumerator = Math.pow(rx, 2) * Math.pow(ry, 2) - Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) - Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
- var cSquareRootDenom = Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) + Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
- var cRadicand = cSquareNumerator / cSquareRootDenom;
- cRadicand = cRadicand < 0 ? 0 : cRadicand;
- var cCoef = (LAF !== SF ? 1 : -1) * sqrt(cRadicand);
- var transformedCenter = {
- x: cCoef * ((rx * transformedPoint.y) / ry),
- y: cCoef * (-(ry * transformedPoint.x) / rx),
- };
- var center = {
- x: cos(xRotRad) * transformedCenter.x - sin(xRotRad) * transformedCenter.y + (x1 + x) / 2,
- y: sin(xRotRad) * transformedCenter.x + cos(xRotRad) * transformedCenter.y + (y1 + y) / 2,
- };
- var startVector = {
- x: (transformedPoint.x - transformedCenter.x) / rx,
- y: (transformedPoint.y - transformedCenter.y) / ry,
- };
- var startAngle = angleBetween({ x: 1, y: 0 }, startVector);
- var endVector = {
- x: (-transformedPoint.x - transformedCenter.x) / rx,
- y: (-transformedPoint.y - transformedCenter.y) / ry,
- };
- var sweepAngle = angleBetween(startVector, endVector);
- if (!SF && sweepAngle > 0) {
- sweepAngle -= 2 * PI;
- }
- else if (SF && sweepAngle < 0) {
- sweepAngle += 2 * PI;
- }
- sweepAngle %= 2 * PI;
- var alpha = startAngle + sweepAngle * t;
- var ellipseComponentX = rx * cos(alpha);
- var ellipseComponentY = ry * sin(alpha);
- var point = {
- x: cos(xRotRad) * ellipseComponentX - sin(xRotRad) * ellipseComponentY + center.x,
- y: sin(xRotRad) * ellipseComponentX + cos(xRotRad) * ellipseComponentY + center.y,
- };
- // to be used later
- // point.ellipticalArcStartAngle = startAngle;
- // point.ellipticalArcEndAngle = startAngle + sweepAngle;
- // point.ellipticalArcAngle = alpha;
- // point.ellipticalArcCenter = center;
- // point.resultantRx = rx;
- // point.resultantRy = ry;
- return point;
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the shape minimum and maximum {x,y} coordinates of an A (arc-to) segment.
- *
- * For better performance, it can skip calculate bbox or length in some scenario.
- */
- function segmentArcFactory(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, distance, options) {
- var _a;
- var _b = options.bbox, bbox = _b === void 0 ? true : _b, _c = options.length, length = _c === void 0 ? true : _c, _d = options.sampleSize, sampleSize = _d === void 0 ? 30 : _d;
- var distanceIsNumber = typeof distance === 'number';
- var x = X1;
- var y = Y1;
- var LENGTH = 0;
- var prev = [x, y, LENGTH];
- var cur = [x, y];
- var t = 0;
- var POINT = { x: 0, y: 0 };
- var POINTS = [{ x: x, y: y }];
- if (distanceIsNumber && distance <= 0) {
- POINT = { x: x, y: y };
- }
- // bad perf when size > 100
- for (var j = 0; j <= sampleSize; j += 1) {
- t = j / sampleSize;
- (_a = getPointAtArcSegmentLength(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, t), x = _a.x, y = _a.y);
- if (bbox) {
- POINTS.push({ x: x, y: y });
- }
- if (length) {
- LENGTH += distanceSquareRoot(cur, [x, y]);
- }
- cur = [x, y];
- if (distanceIsNumber && LENGTH >= distance && distance > prev[2]) {
- var dv = (LENGTH - distance) / (LENGTH - prev[2]);
- POINT = {
- x: cur[0] * (1 - dv) + prev[0] * dv,
- y: cur[1] * (1 - dv) + prev[1] * dv,
- };
- }
- prev = [x, y, LENGTH];
- }
- if (distanceIsNumber && distance >= LENGTH) {
- POINT = { x: X2, y: Y2 };
- }
- return {
- length: LENGTH,
- point: POINT,
- min: {
- x: Math.min.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.min.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- max: {
- x: Math.max.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.max.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- };
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the minimum and maximum {x,y} coordinates of a C (cubic-bezier) segment.
- */
- function getPointAtCubicSegmentLength(x1, y1, c1x, c1y, c2x, c2y, x2, y2, t) {
- var t1 = 1 - t;
- return {
- x: Math.pow(t1, 3) * x1 + 3 * Math.pow(t1, 2) * t * c1x + 3 * t1 * Math.pow(t, 2) * c2x + Math.pow(t, 3) * x2,
- y: Math.pow(t1, 3) * y1 + 3 * Math.pow(t1, 2) * t * c1y + 3 * t1 * Math.pow(t, 2) * c2y + Math.pow(t, 3) * y2,
- };
- }
- /**
- * Returns the length of a C (cubic-bezier) segment
- * or an {x,y} point at a given length.
- */
- function segmentCubicFactory(x1, y1, c1x, c1y, c2x, c2y, x2, y2, distance, options) {
- var _a;
- var _b = options.bbox, bbox = _b === void 0 ? true : _b, _c = options.length, length = _c === void 0 ? true : _c, _d = options.sampleSize, sampleSize = _d === void 0 ? 10 : _d;
- var distanceIsNumber = typeof distance === 'number';
- var x = x1;
- var y = y1;
- var LENGTH = 0;
- var prev = [x, y, LENGTH];
- var cur = [x, y];
- var t = 0;
- var POINT = { x: 0, y: 0 };
- var POINTS = [{ x: x, y: y }];
- if (distanceIsNumber && distance <= 0) {
- POINT = { x: x, y: y };
- }
- // bad perf when size = 300
- for (var j = 0; j <= sampleSize; j += 1) {
- t = j / sampleSize;
- (_a = getPointAtCubicSegmentLength(x1, y1, c1x, c1y, c2x, c2y, x2, y2, t), x = _a.x, y = _a.y);
- if (bbox) {
- POINTS.push({ x: x, y: y });
- }
- if (length) {
- LENGTH += distanceSquareRoot(cur, [x, y]);
- }
- cur = [x, y];
- if (distanceIsNumber && LENGTH >= distance && distance > prev[2]) {
- var dv = (LENGTH - distance) / (LENGTH - prev[2]);
- POINT = {
- x: cur[0] * (1 - dv) + prev[0] * dv,
- y: cur[1] * (1 - dv) + prev[1] * dv,
- };
- }
- prev = [x, y, LENGTH];
- }
- if (distanceIsNumber && distance >= LENGTH) {
- POINT = { x: x2, y: y2 };
- }
- return {
- length: LENGTH,
- point: POINT,
- min: {
- x: Math.min.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.min.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- max: {
- x: Math.max.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.max.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- };
- }
- /**
- * Returns the {x,y} coordinates of a point at a
- * given length of a quadratic-bezier segment.
- *
- * @see https://github.com/substack/point-at-length
- */
- function getPointAtQuadSegmentLength(x1, y1, cx, cy, x2, y2, t) {
- var t1 = 1 - t;
- return {
- x: Math.pow(t1, 2) * x1 + 2 * t1 * t * cx + Math.pow(t, 2) * x2,
- y: Math.pow(t1, 2) * y1 + 2 * t1 * t * cy + Math.pow(t, 2) * y2,
- };
- }
- /**
- * Returns a {x,y} point at a given length, the total length and
- * the minimum and maximum {x,y} coordinates of a Q (quadratic-bezier) segment.
- */
- function segmentQuadFactory(x1, y1, qx, qy, x2, y2, distance, options) {
- var _a;
- var _b = options.bbox, bbox = _b === void 0 ? true : _b, _c = options.length, length = _c === void 0 ? true : _c, _d = options.sampleSize, sampleSize = _d === void 0 ? 10 : _d;
- var distanceIsNumber = typeof distance === 'number';
- var x = x1;
- var y = y1;
- var LENGTH = 0;
- var prev = [x, y, LENGTH];
- var cur = [x, y];
- var t = 0;
- var POINT = { x: 0, y: 0 };
- var POINTS = [{ x: x, y: y }];
- if (distanceIsNumber && distance <= 0) {
- POINT = { x: x, y: y };
- }
- for (var j = 0; j <= sampleSize; j += 1) {
- t = j / sampleSize;
- (_a = getPointAtQuadSegmentLength(x1, y1, qx, qy, x2, y2, t), x = _a.x, y = _a.y);
- if (bbox) {
- POINTS.push({ x: x, y: y });
- }
- if (length) {
- LENGTH += distanceSquareRoot(cur, [x, y]);
- }
- cur = [x, y];
- if (distanceIsNumber && LENGTH >= distance && distance > prev[2]) {
- var dv = (LENGTH - distance) / (LENGTH - prev[2]);
- POINT = {
- x: cur[0] * (1 - dv) + prev[0] * dv,
- y: cur[1] * (1 - dv) + prev[1] * dv,
- };
- }
- prev = [x, y, LENGTH];
- }
- /* istanbul ignore else */
- if (distanceIsNumber && distance >= LENGTH) {
- POINT = { x: x2, y: y2 };
- }
- return {
- length: LENGTH,
- point: POINT,
- min: {
- x: Math.min.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.min.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- max: {
- x: Math.max.apply(null, POINTS.map(function (n) { return n.x; })),
- y: Math.max.apply(null, POINTS.map(function (n) { return n.y; })),
- },
- };
- }
- /**
- * Returns a {x,y} point at a given length
- * of a shape, the shape total length and
- * the shape minimum and maximum {x,y} coordinates.
- */
- function pathLengthFactory(pathInput, distance, options) {
- var _a, _b, _c, _d, _e, _f;
- var path = normalizePath(pathInput);
- var distanceIsNumber = typeof distance === 'number';
- var isM;
- var data = [];
- var pathCommand;
- var x = 0;
- var y = 0;
- var mx = 0;
- var my = 0;
- var seg;
- var MIN = [];
- var MAX = [];
- var length = 0;
- var min = { x: 0, y: 0 };
- var max = min;
- var point = min;
- var POINT = min;
- var LENGTH = 0;
- for (var i = 0, ll = path.length; i < ll; i += 1) {
- seg = path[i];
- pathCommand = seg[0];
- isM = pathCommand === 'M';
- data = !isM ? [x, y].concat(seg.slice(1)) : data;
- // this segment is always ZERO
- /* istanbul ignore else */
- if (isM) {
- // remember mx, my for Z
- mx = seg[1], my = seg[2];
- min = { x: mx, y: my };
- max = min;
- length = 0;
- if (distanceIsNumber && distance < 0.001) {
- POINT = min;
- }
- }
- else if (pathCommand === 'L') {
- (_a = segmentLineFactory(data[0], data[1], data[2], data[3], (distance || 0) - LENGTH), length = _a.length, min = _a.min, max = _a.max, point = _a.point);
- }
- else if (pathCommand === 'A') {
- (_b = segmentArcFactory(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], (distance || 0) - LENGTH, options || {}), length = _b.length, min = _b.min, max = _b.max, point = _b.point);
- }
- else if (pathCommand === 'C') {
- (_c = segmentCubicFactory(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], (distance || 0) - LENGTH, options || {}), length = _c.length, min = _c.min, max = _c.max, point = _c.point);
- }
- else if (pathCommand === 'Q') {
- (_d = segmentQuadFactory(data[0], data[1], data[2], data[3], data[4], data[5], (distance || 0) - LENGTH, options || {}), length = _d.length, min = _d.min, max = _d.max, point = _d.point);
- }
- else if (pathCommand === 'Z') {
- data = [x, y, mx, my];
- (_e = segmentLineFactory(data[0], data[1], data[2], data[3], (distance || 0) - LENGTH), length = _e.length, min = _e.min, max = _e.max, point = _e.point);
- }
- if (distanceIsNumber && LENGTH < distance && LENGTH + length >= distance) {
- POINT = point;
- }
- MAX.push(max);
- MIN.push(min);
- LENGTH += length;
- _f = pathCommand !== 'Z' ? seg.slice(-2) : [mx, my], x = _f[0], y = _f[1];
- }
- // native `getPointAtLength` behavior when the given distance
- // is higher than total length
- if (distanceIsNumber && distance >= LENGTH) {
- POINT = { x: x, y: y };
- }
- return {
- length: LENGTH,
- point: POINT,
- min: {
- x: Math.min.apply(null, MIN.map(function (n) { return n.x; })),
- y: Math.min.apply(null, MIN.map(function (n) { return n.y; })),
- },
- max: {
- x: Math.max.apply(null, MAX.map(function (n) { return n.x; })),
- y: Math.max.apply(null, MAX.map(function (n) { return n.y; })),
- },
- };
- }
- /**
- * Returns the shape total length, or the equivalent to `shape.getTotalLength()`.
- *
- * The `normalizePath` version is lighter, faster, more efficient and more accurate
- * with paths that are not `curveArray`.
- */
- function getTotalLength(pathInput, options) {
- return pathLengthFactory(pathInput, undefined, __assign(__assign({}, options), { bbox: false, length: true })).length;
- }
- function getRotations(a) {
- var segCount = a.length;
- var pointCount = segCount - 1;
- return a.map(function (f, idx) {
- return a.map(function (p, i) {
- var oldSegIdx = idx + i;
- var seg;
- if (i === 0 || (a[oldSegIdx] && a[oldSegIdx][0] === 'M')) {
- seg = a[oldSegIdx];
- return ['M'].concat(seg.slice(-2));
- }
- if (oldSegIdx >= segCount)
- oldSegIdx -= pointCount;
- return a[oldSegIdx];
- });
- });
- }
- function getRotatedCurve(a, b) {
- var segCount = a.length - 1;
- var lineLengths = [];
- var computedIndex = 0;
- var sumLensSqrd = 0;
- var rotations = getRotations(a);
- rotations.forEach(function (r, i) {
- a.slice(1).forEach(function (s, j) {
- // @ts-ignore
- sumLensSqrd += distanceSquareRoot(a[(i + j) % segCount].slice(-2), b[j % segCount].slice(-2));
- });
- lineLengths[i] = sumLensSqrd;
- sumLensSqrd = 0;
- });
- computedIndex = lineLengths.indexOf(Math.min.apply(null, lineLengths));
- return rotations[computedIndex];
- }
- /**
- * Returns the area of a single cubic-bezier segment.
- *
- * http://objectmix.com/graphics/133553-area-closed-bezier-curve.html
- */
- function getCubicSegArea(x1, y1, c1x, c1y, c2x, c2y, x2, y2) {
- // https://stackoverflow.com/a/15845996
- return ((3 *
- ((y2 - y1) * (c1x + c2x) -
- (x2 - x1) * (c1y + c2y) +
- c1y * (x1 - c2x) -
- c1x * (y1 - c2y) +
- y2 * (c2x + x1 / 3) -
- x2 * (c2y + y1 / 3))) /
- 20);
- }
- /**
- * Returns the area of a shape.
- * @author Jürg Lehni & Jonathan Puckey
- *
- * @see https://github.com/paperjs/paper.js/blob/develop/src/path/Path.js
- */
- function getPathArea(path) {
- var x = 0;
- var y = 0;
- var len = 0;
- return path2Curve(path)
- .map(function (seg) {
- var _a;
- switch (seg[0]) {
- case 'M':
- x = seg[1], y = seg[2];
- return 0;
- default:
- // @ts-ignore
- var _b = seg.slice(1), c1x = _b[0], c1y = _b[1], c2x = _b[2], c2y = _b[3], x2 = _b[4], y2 = _b[5];
- len = getCubicSegArea(x, y, c1x, c1y, c2x, c2y, x2, y2);
- _a = seg.slice(-2), x = _a[0], y = _a[1];
- return len;
- }
- })
- .reduce(function (a, b) { return a + b; }, 0);
- }
- // export function getPathArea(pathArray: AbsoluteArray) {
- // let x = 0;
- // let y = 0;
- // let mx = 0;
- // let my = 0;
- // let len = 0;
- // return pathArray
- // .map((seg) => {
- // switch (seg[0]) {
- // case 'M':
- // case 'Z':
- // mx = seg[0] === 'M' ? seg[1] : mx;
- // my = seg[0] === 'M' ? seg[2] : my;
- // x = mx;
- // y = my;
- // return 0;
- // default:
- // // @ts-ignore
- // len = getCubicSegArea.apply(0, [x, y].concat(seg.slice(1)));
- // [x, y] = seg.slice(-2) as [number, number];
- // return len;
- // }
- // })
- // .reduce((a, b) => a + b, 0);
- // }
- function getDrawDirection(pathArray) {
- return getPathArea(pathArray) >= 0;
- }
- /**
- * Returns [x,y] coordinates of a point at a given length of a shape.
- */
- function getPointAtLength(pathInput, distance, options) {
- return pathLengthFactory(pathInput, distance, __assign(__assign({}, options), { bbox: false, length: true })).point;
- }
- function splitCubic(pts, t) {
- if (t === void 0) { t = 0.5; }
- var p0 = pts.slice(0, 2);
- var p1 = pts.slice(2, 4);
- var p2 = pts.slice(4, 6);
- var p3 = pts.slice(6, 8);
- var p4 = midPoint(p0, p1, t);
- var p5 = midPoint(p1, p2, t);
- var p6 = midPoint(p2, p3, t);
- var p7 = midPoint(p4, p5, t);
- var p8 = midPoint(p5, p6, t);
- var p9 = midPoint(p7, p8, t);
- return [
- // @ts-ignore
- ['C'].concat(p4, p7, p9),
- // @ts-ignore
- ['C'].concat(p8, p6, p3),
- ];
- }
- function getCurveArray(segments) {
- return segments.map(function (segment, i, pathArray) {
- // @ts-ignore
- var segmentData = i && pathArray[i - 1].slice(-2).concat(segment.slice(1));
- // @ts-ignore
- var curveLength = i
- ? segmentCubicFactory(segmentData[0], segmentData[1], segmentData[2], segmentData[3], segmentData[4], segmentData[5], segmentData[6], segmentData[7], segmentData[8], { bbox: false }).length
- : 0;
- var subsegs;
- if (i) {
- // must be [segment,segment]
- subsegs = curveLength ? splitCubic(segmentData) : [segment, segment];
- }
- else {
- subsegs = [segment];
- }
- return {
- s: segment,
- ss: subsegs,
- l: curveLength,
- };
- });
- }
- function equalizeSegments(path1, path2, TL) {
- var c1 = getCurveArray(path1);
- var c2 = getCurveArray(path2);
- var L1 = c1.length;
- var L2 = c2.length;
- var l1 = c1.filter(function (x) { return x.l; }).length;
- var l2 = c2.filter(function (x) { return x.l; }).length;
- var m1 = c1.filter(function (x) { return x.l; }).reduce(function (a, _a) {
- var l = _a.l;
- return a + l;
- }, 0) / l1 || 0;
- var m2 = c2.filter(function (x) { return x.l; }).reduce(function (a, _a) {
- var l = _a.l;
- return a + l;
- }, 0) / l2 || 0;
- var tl = TL || Math.max(L1, L2);
- var mm = [m1, m2];
- var dif = [tl - L1, tl - L2];
- var canSplit = 0;
- var result = [c1, c2].map(function (x, i) {
- // @ts-ignore
- return x.l === tl
- ? x.map(function (y) { return y.s; })
- : x
- .map(function (y, j) {
- canSplit = j && dif[i] && y.l >= mm[i];
- dif[i] -= canSplit ? 1 : 0;
- return canSplit ? y.ss : [y.s];
- })
- .flat();
- });
- return result[0].length === result[1].length ? result : equalizeSegments(result[0], result[1], tl);
- }
- // isFinite,
- var isNil = function (value) {
- /**
- * isNil(null) => true
- * isNil() => true
- */
- return value === null || value === undefined;
- };
- var toString = {}.toString;
- var isType = function (value, type) { return toString.call(value) === '[object ' + type + ']'; };
- var isArray = (function (value) {
- return Array.isArray ? Array.isArray(value) : isType(value, 'Array');
- });
- var isObject = (function (value) {
- /**
- * isObject({}) => true
- * isObject([1, 2, 3]) => true
- * isObject(Function) => true
- * isObject(null) => false
- */
- var type = typeof value;
- return (value !== null && type === 'object') || type === 'function';
- });
- /**
- * @param {Array} arr The array to iterate over.
- * @return {*} Returns the maximum value.
- * @example
- *
- * max([1, 2]);
- * // => 2
- *
- * max([]);
- * // => undefined
- *
- * const data = new Array(1250010).fill(1).map((d,idx) => idx);
- *
- * max(data);
- * // => 1250010
- * // Math.max(...data) will encounter "Maximum call stack size exceeded" error
- */
- var max = (function (arr) {
- if (!isArray(arr)) {
- return undefined;
- }
- return arr.reduce(function (prev, curr) {
- return Math.max(prev, curr);
- }, arr[0]);
- });
- /**
- * @param {Array} arr The array to iterate over.
- * @return {*} Returns the minimum value.
- * @example
- *
- * min([1, 2]);
- * // => 1
- *
- * min([]);
- * // => undefined
- *
- * const data = new Array(1250010).fill(1).map((d,idx) => idx);
- *
- * min(data);
- * // => 1250010
- * // Math.min(...data) will encounter "Maximum call stack size exceeded" error
- */
- var min = (function (arr) {
- if (!isArray(arr)) {
- return undefined;
- }
- return arr.reduce(function (prev, curr) {
- return Math.min(prev, curr);
- }, arr[0]);
- });
- var isString = (function (str) {
- return isType(str, 'String');
- });
- var clamp = function (a, min, max) {
- if (a < min) {
- return min;
- }
- else if (a > max) {
- return max;
- }
- return a;
- };
- /**
- * 判断是否数字
- * @return {Boolean} 是否数字
- */
- var isNumber = function (value) {
- return isType(value, 'Number');
- };
- var PRECISION = 0.00001; // numbers less than this is considered as 0
- function isNumberEqual(a, b, precision) {
- if (precision === void 0) { precision = PRECISION; }
- return Math.abs(a - b) < precision;
- }
- var mod = function (n, m) {
- return ((n % m) + m) % m;
- };
- /**
- * 是否是布尔类型
- *
- * @param {Object} value 测试的值
- * @return {Boolean}
- */
- var isBoolean = function (value) {
- return isType(value, 'Boolean');
- };
- var isUndefined = function (value) {
- return value === undefined;
- };
- // These units are iterated through, so be careful when adding or changing the
- (function (UnitType) {
- UnitType[UnitType["kUnknown"] = 0] = "kUnknown";
- UnitType[UnitType["kNumber"] = 1] = "kNumber";
- UnitType[UnitType["kPercentage"] = 2] = "kPercentage";
- // Length units
- UnitType[UnitType["kEms"] = 3] = "kEms";
- // kExs,
- UnitType[UnitType["kPixels"] = 4] = "kPixels";
- // kCentimeters,
- // kMillimeters,
- // kInches,
- // kPoints,
- // kPicas,
- // kQuarterMillimeters,
- // https://drafts.csswg.org/css-values-4/#viewport-relative-lengths
- //
- // See also IsViewportPercentageLength.
- // kViewportWidth,
- // kViewportHeight,
- // kViewportInlineSize,
- // kViewportBlockSize,
- // kViewportMin,
- // kViewportMax,
- // kSmallViewportWidth,
- // kSmallViewportHeight,
- // kSmallViewportInlineSize,
- // kSmallViewportBlockSize,
- // kSmallViewportMin,
- // kSmallViewportMax,
- // kLargeViewportWidth,
- // kLargeViewportHeight,
- // kLargeViewportInlineSize,
- // kLargeViewportBlockSize,
- // kLargeViewportMin,
- // kLargeViewportMax,
- // kDynamicViewportWidth,
- // kDynamicViewportHeight,
- // kDynamicViewportInlineSize,
- // kDynamicViewportBlockSize,
- // kDynamicViewportMin,
- // kDynamicViewportMax,
- // https://drafts.csswg.org/css-contain-3/#container-lengths
- //
- // See also IsContainerPercentageLength.
- // kContainerWidth,
- // kContainerHeight,
- // kContainerInlineSize,
- // kContainerBlockSize,
- // kContainerMin,
- // kContainerMax,
- UnitType[UnitType["kRems"] = 5] = "kRems";
- // kChs,
- // kUserUnits, // The SVG term for unitless lengths
- // Angle units
- UnitType[UnitType["kDegrees"] = 6] = "kDegrees";
- UnitType[UnitType["kRadians"] = 7] = "kRadians";
- UnitType[UnitType["kGradians"] = 8] = "kGradians";
- UnitType[UnitType["kTurns"] = 9] = "kTurns";
- // Time units
- UnitType[UnitType["kMilliseconds"] = 10] = "kMilliseconds";
- UnitType[UnitType["kSeconds"] = 11] = "kSeconds";
- // kHertz,
- // kKilohertz,
- // Resolution
- // kDotsPerPixel,
- // kDotsPerInch,
- // kDotsPerCentimeter,
- // Other units
- // kFraction,
- UnitType[UnitType["kInteger"] = 12] = "kInteger";
- // This value is used to handle quirky margins in reflow roots (body, td,
- // and th) like WinIE. The basic idea is that a stylesheet can use the value
- // __qem (for quirky em) instead of em. When the quirky value is used, if
- // you're in quirks mode, the margin will collapse away inside a table cell.
- // This quirk is specified in the HTML spec but our impl is different.
- // TODO: Remove this. crbug.com/443952
- // kQuirkyEms,
- })(exports.UnitType || (exports.UnitType = {}));
- var UnitCategory;
- (function (UnitCategory) {
- UnitCategory[UnitCategory["kUNumber"] = 0] = "kUNumber";
- UnitCategory[UnitCategory["kUPercent"] = 1] = "kUPercent";
- UnitCategory[UnitCategory["kULength"] = 2] = "kULength";
- UnitCategory[UnitCategory["kUAngle"] = 3] = "kUAngle";
- UnitCategory[UnitCategory["kUTime"] = 4] = "kUTime";
- // kUFrequency,
- // kUResolution,
- UnitCategory[UnitCategory["kUOther"] = 5] = "kUOther";
- })(UnitCategory || (UnitCategory = {}));
- var ValueRange;
- (function (ValueRange) {
- ValueRange[ValueRange["kAll"] = 0] = "kAll";
- ValueRange[ValueRange["kNonNegative"] = 1] = "kNonNegative";
- ValueRange[ValueRange["kInteger"] = 2] = "kInteger";
- ValueRange[ValueRange["kNonNegativeInteger"] = 3] = "kNonNegativeInteger";
- ValueRange[ValueRange["kPositiveInteger"] = 4] = "kPositiveInteger";
- })(ValueRange || (ValueRange = {}));
- var Nested;
- (function (Nested) {
- Nested[Nested["kYes"] = 0] = "kYes";
- Nested[Nested["kNo"] = 1] = "kNo";
- })(Nested || (Nested = {}));
- var ParenLess;
- (function (ParenLess) {
- ParenLess[ParenLess["kYes"] = 0] = "kYes";
- ParenLess[ParenLess["kNo"] = 1] = "kNo";
- })(ParenLess || (ParenLess = {}));
- // This file specifies the unit strings used in CSSPrimitiveValues.
- var data = [{
- name: 'em',
- unit_type: exports.UnitType.kEms
- },
- // {
- // name: 'ex',
- // unit_type: UnitType.kExs,
- // },
- {
- name: 'px',
- unit_type: exports.UnitType.kPixels
- },
- // {
- // name: "cm",
- // unit_type: UnitType.kCentimeters,
- // },
- // {
- // name: "mm",
- // unit_type: UnitType.kMillimeters,
- // },
- // {
- // name: "q",
- // unit_type: UnitType.kQuarterMillimeters,
- // },
- // {
- // name: "in",
- // unit_type: UnitType.kInches,
- // },
- // {
- // name: "pt",
- // unit_type: UnitType.kPoints,
- // },
- // {
- // name: "pc",
- // unit_type: UnitType.kPicas,
- // },
- {
- name: 'deg',
- unit_type: exports.UnitType.kDegrees
- }, {
- name: 'rad',
- unit_type: exports.UnitType.kRadians
- }, {
- name: 'grad',
- unit_type: exports.UnitType.kGradians
- }, {
- name: 'ms',
- unit_type: exports.UnitType.kMilliseconds
- }, {
- name: 's',
- unit_type: exports.UnitType.kSeconds
- },
- // {
- // name: "hz",
- // unit_type: UnitType.kHertz,
- // },
- // {
- // name: "khz",
- // unit_type: UnitType.kKilohertz,
- // },
- // {
- // name: "dpi",
- // unit_type: "kDotsPerInch",
- // },
- // {
- // name: "dpcm",
- // unit_type: "kDotsPerCentimeter",
- // },
- // {
- // name: "dppx",
- // unit_type: "kDotsPerPixel",
- // },
- // {
- // name: "x",
- // unit_type: "kDotsPerPixel",
- // },
- // {
- // name: "vw",
- // unit_type: "kViewportWidth",
- // },
- // {
- // name: "vh",
- // unit_type: "kViewportHeight",
- // },
- // {
- // name: "vi",
- // unit_type: "kViewportInlineSize",
- // },
- // {
- // name: "vb",
- // unit_type: "kViewportBlockSize",
- // },
- // {
- // name: "vmin",
- // unit_type: UnitType.kViewportMin,
- // },
- // {
- // name: "vmax",
- // unit_type: UnitType.kViewportMax,
- // },
- // {
- // name: "svw",
- // unit_type: "kSmallViewportWidth",
- // },
- // {
- // name: "svh",
- // unit_type: "kSmallViewportHeight",
- // },
- // {
- // name: "svi",
- // unit_type: "kSmallViewportInlineSize",
- // },
- // {
- // name: "svb",
- // unit_type: "kSmallViewportBlockSize",
- // },
- // {
- // name: "svmin",
- // unit_type: "kSmallViewportMin",
- // },
- // {
- // name: "svmax",
- // unit_type: "kSmallViewportMax",
- // },
- // {
- // name: "lvw",
- // unit_type: "kLargeViewportWidth",
- // },
- // {
- // name: "lvh",
- // unit_type: "kLargeViewportHeight",
- // },
- // {
- // name: "lvi",
- // unit_type: "kLargeViewportInlineSize",
- // },
- // {
- // name: "lvb",
- // unit_type: "kLargeViewportBlockSize",
- // },
- // {
- // name: "lvmin",
- // unit_type: UnitType.kLargeViewportMin,
- // },
- // {
- // name: "lvmax",
- // unit_type: UnitType.kLargeViewportMax,
- // },
- // {
- // name: "dvw",
- // unit_type: UnitType.kDynamicViewportWidth,
- // },
- // {
- // name: "dvh",
- // unit_type: UnitType.kDynamicViewportHeight,
- // },
- // {
- // name: "dvi",
- // unit_type: UnitType.kDynamicViewportInlineSize,
- // },
- // {
- // name: "dvb",
- // unit_type: UnitType.kDynamicViewportBlockSize,
- // },
- // {
- // name: "dvmin",
- // unit_type: UnitType.kDynamicViewportMin,
- // },
- // {
- // name: "dvmax",
- // unit_type: UnitType.kDynamicViewportMax,
- // },
- // {
- // name: "cqw",
- // unit_type: UnitType.kContainerWidth,
- // },
- // {
- // name: "cqh",
- // unit_type: UnitType.kContainerHeight,
- // },
- // {
- // name: "cqi",
- // unit_type: UnitType.kContainerInlineSize,
- // },
- // {
- // name: "cqb",
- // unit_type: UnitType.kContainerBlockSize,
- // },
- // {
- // name: "cqmin",
- // unit_type: UnitType.kContainerMin,
- // },
- // {
- // name: "cqmax",
- // unit_type: UnitType.kContainerMax,
- // },
- {
- name: 'rem',
- unit_type: exports.UnitType.kRems
- },
- // {
- // name: 'fr',
- // unit_type: UnitType.kFraction,
- // },
- {
- name: 'turn',
- unit_type: exports.UnitType.kTurns
- }
- // {
- // name: 'ch',
- // unit_type: UnitType.kChs,
- // },
- // {
- // name: '__qem',
- // unit_type: UnitType.kQuirkyEms,
- // },
- ];
- var CSSStyleValueType;
- (function (CSSStyleValueType) {
- CSSStyleValueType[CSSStyleValueType["kUnknownType"] = 0] = "kUnknownType";
- CSSStyleValueType[CSSStyleValueType["kUnparsedType"] = 1] = "kUnparsedType";
- CSSStyleValueType[CSSStyleValueType["kKeywordType"] = 2] = "kKeywordType";
- // Start of CSSNumericValue subclasses
- CSSStyleValueType[CSSStyleValueType["kUnitType"] = 3] = "kUnitType";
- CSSStyleValueType[CSSStyleValueType["kSumType"] = 4] = "kSumType";
- CSSStyleValueType[CSSStyleValueType["kProductType"] = 5] = "kProductType";
- CSSStyleValueType[CSSStyleValueType["kNegateType"] = 6] = "kNegateType";
- CSSStyleValueType[CSSStyleValueType["kInvertType"] = 7] = "kInvertType";
- CSSStyleValueType[CSSStyleValueType["kMinType"] = 8] = "kMinType";
- CSSStyleValueType[CSSStyleValueType["kMaxType"] = 9] = "kMaxType";
- CSSStyleValueType[CSSStyleValueType["kClampType"] = 10] = "kClampType";
- // End of CSSNumericValue subclasses
- CSSStyleValueType[CSSStyleValueType["kTransformType"] = 11] = "kTransformType";
- CSSStyleValueType[CSSStyleValueType["kPositionType"] = 12] = "kPositionType";
- CSSStyleValueType[CSSStyleValueType["kURLImageType"] = 13] = "kURLImageType";
- CSSStyleValueType[CSSStyleValueType["kColorType"] = 14] = "kColorType";
- CSSStyleValueType[CSSStyleValueType["kUnsupportedColorType"] = 15] = "kUnsupportedColorType";
- })(CSSStyleValueType || (CSSStyleValueType = {}));
- // function parseCSSStyleValue(propertyName: string, value: string): CSSStyleValue[] {
- // // const propertyId = cssPropertyID(propertyName);
- // // if (propertyId === CSSPropertyID.kInvalid) {
- // // return [];
- // // }
- // // const customPropertyName = propertyId === CSSPropertyID.kVariable ? propertyName : null;
- // // return fromString(propertyId, customPropertyName, value);
- // return [];
- // }
- var stringToUnitType = function stringToUnitType(name) {
- return data.find(function (item) {
- return item.name === name;
- }).unit_type;
- };
- var unitFromName = function unitFromName(name) {
- if (!name) {
- return exports.UnitType.kUnknown;
- }
- if (name === 'number') {
- return exports.UnitType.kNumber;
- }
- if (name === 'percent' || name === '%') {
- return exports.UnitType.kPercentage;
- }
- return stringToUnitType(name);
- };
- var unitTypeToUnitCategory = function unitTypeToUnitCategory(type) {
- switch (type) {
- case exports.UnitType.kNumber:
- case exports.UnitType.kInteger:
- return UnitCategory.kUNumber;
- case exports.UnitType.kPercentage:
- return UnitCategory.kUPercent;
- case exports.UnitType.kPixels:
- // case UnitType.kCentimeters:
- // case UnitType.kMillimeters:
- // case UnitType.kQuarterMillimeters:
- // case UnitType.kInches:
- // case UnitType.kPoints:
- // case UnitType.kPicas:
- // case UnitType.kUserUnits:
- return UnitCategory.kULength;
- case exports.UnitType.kMilliseconds:
- case exports.UnitType.kSeconds:
- return UnitCategory.kUTime;
- case exports.UnitType.kDegrees:
- case exports.UnitType.kRadians:
- case exports.UnitType.kGradians:
- case exports.UnitType.kTurns:
- return UnitCategory.kUAngle;
- // case UnitType.kHertz:
- // case UnitType.kKilohertz:
- // return UnitCategory.kUFrequency;
- // case UnitType.kDotsPerPixel:
- // case UnitType.kDotsPerInch:
- // case UnitType.kDotsPerCentimeter:
- // return UnitCategory.kUResolution;
- default:
- return UnitCategory.kUOther;
- }
- };
- var canonicalUnitTypeForCategory = function canonicalUnitTypeForCategory(category) {
- // The canonical unit type is chosen according to the way
- // CSSPropertyParser.ValidUnit() chooses the default unit in each category
- // (based on unitflags).
- switch (category) {
- case UnitCategory.kUNumber:
- return exports.UnitType.kNumber;
- case UnitCategory.kULength:
- return exports.UnitType.kPixels;
- case UnitCategory.kUPercent:
- return exports.UnitType.kPercentage;
- // return UnitType.kUnknown; // Cannot convert between numbers and percent.
- case UnitCategory.kUTime:
- return exports.UnitType.kSeconds;
- case UnitCategory.kUAngle:
- return exports.UnitType.kDegrees;
- // case UnitCategory.kUFrequency:
- // return UnitType.kHertz;
- // case UnitCategory.kUResolution:
- // return UnitType.kDotsPerPixel;
- default:
- return exports.UnitType.kUnknown;
- }
- };
- /**
- * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/css_primitive_value.cc#353
- */
- var conversionToCanonicalUnitsScaleFactor = function conversionToCanonicalUnitsScaleFactor(unit_type) {
- var factor = 1.0;
- // FIXME: the switch can be replaced by an array of scale factors.
- switch (unit_type) {
- // These are "canonical" units in their respective categories.
- case exports.UnitType.kPixels:
- // case UnitType.kUserUnits:
- case exports.UnitType.kDegrees:
- case exports.UnitType.kSeconds:
- // case UnitType.kHertz:
- break;
- case exports.UnitType.kMilliseconds:
- factor = 0.001;
- break;
- // case UnitType.kCentimeters:
- // // factor = kCssPixelsPerCentimeter;
- // break;
- // case UnitType.kDotsPerCentimeter:
- // // factor = 1 / kCssPixelsPerCentimeter;
- // break;
- // case UnitType.kMillimeters:
- // // factor = kCssPixelsPerMillimeter;
- // break;
- // case UnitType.kQuarterMillimeters:
- // // factor = kCssPixelsPerQuarterMillimeter;
- // break;
- // case UnitType.kInches:
- // // factor = kCssPixelsPerInch;
- // break;
- // case UnitType.kDotsPerInch:
- // // factor = 1 / kCssPixelsPerInch;
- // break;
- // case UnitType.kPoints:
- // // factor = kCssPixelsPerPoint;
- // break;
- // case UnitType.kPicas:
- // // factor = kCssPixelsPerPica;
- // break;
- case exports.UnitType.kRadians:
- factor = 180 / Math.PI;
- break;
- case exports.UnitType.kGradians:
- factor = 0.9;
- break;
- case exports.UnitType.kTurns:
- factor = 360;
- break;
- }
- return factor;
- };
- var unitTypeToString = function unitTypeToString(type) {
- switch (type) {
- case exports.UnitType.kNumber:
- case exports.UnitType.kInteger:
- // case UnitType.kUserUnits:
- return '';
- case exports.UnitType.kPercentage:
- return '%';
- case exports.UnitType.kEms:
- // case UnitType.kQuirkyEms:
- return 'em';
- // case UnitType.kExs:
- // return 'ex';
- case exports.UnitType.kRems:
- return 'rem';
- // case UnitType.kChs:
- // return 'ch';
- case exports.UnitType.kPixels:
- return 'px';
- // case UnitType.kCentimeters:
- // return 'cm';
- // case UnitType.kDotsPerPixel:
- // return 'dppx';
- // case UnitType.kDotsPerInch:
- // return 'dpi';
- // case UnitType.kDotsPerCentimeter:
- // return 'dpcm';
- // case UnitType.kMillimeters:
- // return 'mm';
- // case UnitType.kQuarterMillimeters:
- // return 'q';
- // case UnitType.kInches:
- // return 'in';
- // case UnitType.kPoints:
- // return 'pt';
- // case UnitType.kPicas:
- // return 'pc';
- case exports.UnitType.kDegrees:
- return 'deg';
- case exports.UnitType.kRadians:
- return 'rad';
- case exports.UnitType.kGradians:
- return 'grad';
- case exports.UnitType.kMilliseconds:
- return 'ms';
- case exports.UnitType.kSeconds:
- return 's';
- // case UnitType.kHertz:
- // return 'hz';
- // case UnitType.kKilohertz:
- // return 'khz';
- case exports.UnitType.kTurns:
- return 'turn';
- }
- return '';
- };
- /**
- * CSSStyleValue is the base class for all CSS values accessible from Typed OM.
- * Values that are not yet supported as specific types are also returned as base CSSStyleValues.
- *
- * Spec @see https://drafts.css-houdini.org/css-typed-om/#stylevalue-objects
- * Docs @see https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleValue
- */
- var CSSStyleValue = /*#__PURE__*/function () {
- function CSSStyleValue() {}
- // static parse(propertyName: string, value: string): CSSStyleValue {
- // return parseCSSStyleValue(propertyName, value)[0];
- // }
- // static parseAll(propertyName: string, value: string): CSSStyleValue[] {
- // return parseCSSStyleValue(propertyName, value);
- // }
- CSSStyleValue.isAngle = function isAngle(unit) {
- return unit === exports.UnitType.kDegrees || unit === exports.UnitType.kRadians || unit === exports.UnitType.kGradians || unit === exports.UnitType.kTurns;
- }
- // static isViewportPercentageLength(type: UnitType) {
- // return type >= UnitType.kViewportWidth && type <= UnitType.kDynamicViewportMax;
- // }
- // static isContainerPercentageLength(type: UnitType) {
- // return type >= UnitType.kContainerWidth && type <= UnitType.kContainerMax;
- // }
- ;
- CSSStyleValue.isLength = function isLength(type) {
- // return (type >= UnitType.kEms && type <= UnitType.kUserUnits) || type == UnitType.kQuirkyEms;
- return type >= exports.UnitType.kEms && type < exports.UnitType.kDegrees;
- };
- CSSStyleValue.isRelativeUnit = function isRelativeUnit(type) {
- return type === exports.UnitType.kPercentage || type === exports.UnitType.kEms ||
- // type === UnitType.kExs ||
- type === exports.UnitType.kRems
- // type === UnitType.kChs ||
- // this.isViewportPercentageLength(type) ||
- // this.isContainerPercentageLength(type)
- ;
- };
- CSSStyleValue.isTime = function isTime(unit) {
- return unit === exports.UnitType.kSeconds || unit === exports.UnitType.kMilliseconds;
- }
- // protected abstract toCSSValue(): CSSValue;
- ;
- var _proto = CSSStyleValue.prototype;
- _proto.toString = function toString() {
- return this.buildCSSText(Nested.kNo, ParenLess.kNo, '');
- };
- _proto.isNumericValue = function isNumericValue() {
- return this.getType() >= CSSStyleValueType.kUnitType && this.getType() <= CSSStyleValueType.kClampType;
- };
- return CSSStyleValue;
- }();
- /**
- * CSSColorValue is the base class used for the various CSS color interfaces.
- *
- * @see https://drafts.css-houdini.org/css-typed-om-1/#colorvalue-objects
- */
- var CSSColorValue = /*#__PURE__*/function (_CSSStyleValue) {
- _inheritsLoose(CSSColorValue, _CSSStyleValue);
- function CSSColorValue(colorSpace) {
- var _this;
- _this = _CSSStyleValue.call(this) || this;
- _this.colorSpace = void 0;
- _this.colorSpace = colorSpace;
- return _this;
- }
- var _proto = CSSColorValue.prototype;
- _proto.getType = function getType() {
- return CSSStyleValueType.kColorType;
- }
- // buildCSSText(n: Nested, p: ParenLess, result: string): string {
- // let text = '';
- // if (this.colorSpace === 'rgb') {
- // text = `rgba(${this.channels.join(',')},${this.alpha})`;
- // }
- // return (result += text);
- // }
- /**
- * @see https://drafts.css-houdini.org/css-typed-om-1/#dom-csscolorvalue-to
- */;
- _proto.to = function to(colorSpace) {
- return this;
- };
- return CSSColorValue;
- }(CSSStyleValue);
- (function (GradientType) {
- GradientType[GradientType["Constant"] = 0] = "Constant";
- GradientType[GradientType["LinearGradient"] = 1] = "LinearGradient";
- GradientType[GradientType["RadialGradient"] = 2] = "RadialGradient";
- })(exports.GradientType || (exports.GradientType = {}));
- var CSSGradientValue = /*#__PURE__*/function (_CSSStyleValue) {
- _inheritsLoose(CSSGradientValue, _CSSStyleValue);
- function CSSGradientValue(type, value) {
- var _this;
- _this = _CSSStyleValue.call(this) || this;
- _this.type = void 0;
- _this.value = void 0;
- _this.type = type;
- _this.value = value;
- return _this;
- }
- var _proto = CSSGradientValue.prototype;
- _proto.clone = function clone() {
- return new CSSGradientValue(this.type, this.value);
- };
- _proto.buildCSSText = function buildCSSText(n, p, result) {
- return result;
- };
- _proto.getType = function getType() {
- return CSSStyleValueType.kColorType;
- };
- return CSSGradientValue;
- }(CSSStyleValue);
- /**
- * CSSKeywordValue represents CSS Values that are specified as keywords
- * eg. 'initial'
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSKeywordValue
- * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_keyword_value.idl
- */
- var CSSKeywordValue = /*#__PURE__*/function (_CSSStyleValue) {
- _inheritsLoose(CSSKeywordValue, _CSSStyleValue);
- function CSSKeywordValue(value) {
- var _this;
- _this = _CSSStyleValue.call(this) || this;
- _this.value = void 0;
- _this.value = value;
- return _this;
- }
- var _proto = CSSKeywordValue.prototype;
- _proto.clone = function clone() {
- return new CSSKeywordValue(this.value);
- };
- _proto.getType = function getType() {
- return CSSStyleValueType.kKeywordType;
- };
- _proto.buildCSSText = function buildCSSText(n, p, result) {
- return result + this.value;
- };
- return CSSKeywordValue;
- }(CSSStyleValue);
- function memoize(func, resolver) {
- if (typeof func !== 'function' || resolver != null && typeof resolver !== 'function') {
- throw new TypeError('Expected a function');
- }
- var memoized = function memoized() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- var key = resolver ? resolver.apply(this, args) : args[0];
- var cache = memoized.cache;
- if (cache.has(key)) {
- return cache.get(key);
- }
- var result = func.apply(this, args);
- memoized.cache = cache.set(key, result) || cache;
- return result;
- };
- memoized.cache = new (memoize.Cache || Map)();
- return memoized;
- }
- memoize.Cache = Map;
- var camelCase = memoize(function (str) {
- if (str === void 0) {
- str = '';
- }
- return str.replace(/-([a-z])/g, function (g) {
- return g[1].toUpperCase();
- });
- });
- var kebabize = function kebabize(str) {
- return str.split('').map(function (letter, idx) {
- return letter.toUpperCase() === letter ? "" + (idx !== 0 ? '-' : '') + letter.toLowerCase() : letter;
- }).join('');
- };
- function DCHECK(bool) {
- if (!bool) {
- throw new Error();
- }
- }
- function isFunction(func) {
- return typeof func === 'function';
- }
- function isSymbol(value) {
- // @see https://github.com/lodash/lodash/blob/master/isSymbol.js
- return typeof value === 'symbol';
- }
- var definedProps = function definedProps(obj) {
- return Object.fromEntries(Object.entries(obj).filter(function (_ref) {
- var v = _ref[1];
- return v !== undefined;
- }));
- };
- var FORMAT_ATTR_MAP = {
- d: {
- alias: 'path'
- },
- strokeDasharray: {
- alias: 'lineDash'
- },
- strokeWidth: {
- alias: 'lineWidth'
- },
- textAnchor: {
- alias: 'textAlign'
- },
- src: {
- alias: 'img'
- }
- };
- var formatAttributeName = memoize(function (name) {
- var attributeName = camelCase(name);
- var map = FORMAT_ATTR_MAP[attributeName];
- attributeName = (map === null || map === void 0 ? void 0 : map.alias) || attributeName;
- return attributeName;
- });
- // type CSSNumericBaseType =
- // | 'length'
- // | 'angle'
- // | 'time'
- // | 'frequency'
- // | 'resolution'
- // | 'flex'
- // | 'percent';
- // https://drafts.css-houdini.org/css-typed-om/#dictdef-cssnumerictype
- // interface CSSNumericType {
- // length: number;
- // angle: number;
- // time: number;
- // frequency: number;
- // resolution: number;
- // flex: number;
- // percent: number;
- // percentHint: CSSNumericBaseType;
- // }
- var formatInfinityOrNaN = function formatInfinityOrNaN(number, suffix) {
- if (suffix === void 0) {
- suffix = '';
- }
- var result = '';
- if (!Number.isFinite(number)) {
- if (number > 0) result = 'infinity';else result = '-infinity';
- } else {
- DCHECK(Number.isNaN(number));
- result = 'NaN';
- }
- return result += suffix;
- };
- var toCanonicalUnit = function toCanonicalUnit(unit) {
- return canonicalUnitTypeForCategory(unitTypeToUnitCategory(unit));
- };
- /**
- * CSSNumericValue is the base class for numeric and length typed CSS Values.
- * @see https://drafts.css-houdini.org/css-typed-om/#numeric-objects
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSNumericValue
- * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_numeric_value.idl
- */
- /**
- * Represents numeric values that can be expressed as a single number plus a
- * unit (or a naked number or percentage).
- * @see https://drafts.css-houdini.org/css-typed-om/#cssunitvalue
- */
- var CSSUnitValue = /*#__PURE__*/function (_CSSStyleValue) {
- _inheritsLoose(CSSUnitValue, _CSSStyleValue);
- function CSSUnitValue(value, unitOrName) {
- var _this;
- if (unitOrName === void 0) {
- unitOrName = exports.UnitType.kNumber;
- }
- _this = _CSSStyleValue.call(this) || this;
- _this.unit = void 0;
- _this.value = void 0;
- var unit;
- if (typeof unitOrName === 'string') {
- unit = unitFromName(unitOrName);
- } else {
- unit = unitOrName;
- }
- _this.unit = unit;
- _this.value = value;
- return _this;
- }
- var _proto = CSSUnitValue.prototype;
- _proto.clone = function clone() {
- return new CSSUnitValue(this.value, this.unit);
- };
- _proto.equals = function equals(other) {
- var other_unit_value = other;
- return this.value === other_unit_value.value && this.unit === other_unit_value.unit;
- };
- _proto.getType = function getType() {
- return CSSStyleValueType.kUnitType;
- };
- _proto.convertTo = function convertTo(target_unit) {
- if (this.unit === target_unit) {
- return new CSSUnitValue(this.value, this.unit);
- }
- // Instead of defining the scale factors for every unit to every other unit,
- // we simply convert to the canonical unit and back since we already have
- // the scale factors for canonical units.
- var canonical_unit = toCanonicalUnit(this.unit);
- if (canonical_unit !== toCanonicalUnit(target_unit) || canonical_unit === exports.UnitType.kUnknown) {
- return null;
- }
- var scale_factor = conversionToCanonicalUnitsScaleFactor(this.unit) / conversionToCanonicalUnitsScaleFactor(target_unit);
- return new CSSUnitValue(this.value * scale_factor, target_unit);
- };
- _proto.buildCSSText = function buildCSSText(n, p, result) {
- var text;
- switch (this.unit) {
- case exports.UnitType.kUnknown:
- // FIXME
- break;
- case exports.UnitType.kInteger:
- text = Number(this.value).toFixed(0);
- break;
- case exports.UnitType.kNumber:
- case exports.UnitType.kPercentage:
- case exports.UnitType.kEms:
- // case UnitType.kQuirkyEms:
- // case UnitType.kExs:
- case exports.UnitType.kRems:
- // case UnitType.kChs:
- case exports.UnitType.kPixels:
- // case UnitType.kCentimeters:
- // case UnitType.kDotsPerPixel:
- // case UnitType.kDotsPerInch:
- // case UnitType.kDotsPerCentimeter:
- // case UnitType.kMillimeters:
- // case UnitType.kQuarterMillimeters:
- // case UnitType.kInches:
- // case UnitType.kPoints:
- // case UnitType.kPicas:
- // case UnitType.kUserUnits:
- case exports.UnitType.kDegrees:
- case exports.UnitType.kRadians:
- case exports.UnitType.kGradians:
- case exports.UnitType.kMilliseconds:
- case exports.UnitType.kSeconds:
- // case UnitType.kHertz:
- // case UnitType.kKilohertz:
- case exports.UnitType.kTurns:
- // case UnitType.kContainerMax: { // case UnitType.kContainerMin: // case UnitType.kContainerBlockSize: // case UnitType.kContainerInlineSize: // case UnitType.kContainerHeight: // case UnitType.kContainerWidth: // case UnitType.kDynamicViewportMax: // case UnitType.kDynamicViewportMin: // case UnitType.kDynamicViewportBlockSize: // case UnitType.kDynamicViewportInlineSize: // case UnitType.kDynamicViewportHeight: // case UnitType.kDynamicViewportWidth: // case UnitType.kLargeViewportMax: // case UnitType.kLargeViewportMin: // case UnitType.kLargeViewportBlockSize: // case UnitType.kLargeViewportInlineSize: // case UnitType.kLargeViewportHeight: // case UnitType.kLargeViewportWidth: // case UnitType.kSmallViewportMax: // case UnitType.kSmallViewportMin: // case UnitType.kSmallViewportBlockSize: // case UnitType.kSmallViewportInlineSize: // case UnitType.kSmallViewportHeight: // case UnitType.kSmallViewportWidth: // case UnitType.kViewportMax: // case UnitType.kViewportMin: // case UnitType.kViewportBlockSize: // case UnitType.kViewportInlineSize: // case UnitType.kViewportHeight: // case UnitType.kViewportWidth: // case UnitType.kFraction:
- {
- var kMinInteger = -999999;
- var kMaxInteger = 999999;
- var value = this.value;
- var unit = unitTypeToString(this.unit);
- if (value < kMinInteger || value > kMaxInteger) {
- var _unit = unitTypeToString(this.unit);
- if (!Number.isFinite(value) || Number.isNaN(value)) {
- text = formatInfinityOrNaN(value, _unit);
- } else {
- text = value + (_unit || '');
- }
- } else {
- text = "" + value + unit;
- }
- }
- }
- result += text;
- return result;
- };
- return CSSUnitValue;
- }(CSSStyleValue);
- var Opx = new CSSUnitValue(0, 'px');
- var Lpx = new CSSUnitValue(1, 'px');
- var Odeg = new CSSUnitValue(0, 'deg');
- /**
- * The CSSRGB class represents the CSS rgb()/rgba() functions.
- *
- * @see https://drafts.css-houdini.org/css-typed-om-1/#cssrgb
- */
- var CSSRGB = /*#__PURE__*/function (_CSSColorValue) {
- _inheritsLoose(CSSRGB, _CSSColorValue);
- function CSSRGB(r, g, b, alpha,
- /**
- * 'transparent' & 'none' has the same rgba data
- */
- isNone) {
- var _this;
- if (alpha === void 0) {
- alpha = 1;
- }
- if (isNone === void 0) {
- isNone = false;
- }
- _this = _CSSColorValue.call(this, 'rgb') || this;
- _this.r = void 0;
- _this.g = void 0;
- _this.b = void 0;
- _this.alpha = void 0;
- _this.isNone = void 0;
- _this.r = r;
- _this.g = g;
- _this.b = b;
- _this.alpha = alpha;
- _this.isNone = isNone;
- return _this;
- }
- var _proto = CSSRGB.prototype;
- _proto.clone = function clone() {
- return new CSSRGB(this.r, this.g, this.b, this.alpha);
- };
- _proto.buildCSSText = function buildCSSText(n, p, result) {
- return result + ("rgba(" + this.r + "," + this.g + "," + this.b + "," + this.alpha + ")");
- };
- return CSSRGB;
- }(CSSColorValue);
- /**
- * holds useful CSS-related methods.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS
- *
- * * CSS Typed OM @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/factory_functions
- * * register property @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
- * * CSS Layout API
- */
- var CSS = {
- /**
- * <number>
- * @see https://drafts.csswg.org/css-values-4/#number-value
- */
- number: function number(n) {
- return new CSSUnitValue(n);
- },
- /**
- * <percentage>
- * @see https://drafts.csswg.org/css-values-4/#percentage-value
- */
- percent: function percent(n) {
- return new CSSUnitValue(n, '%');
- },
- /**
- * <length>
- */
- px: function px(n) {
- return new CSSUnitValue(n, 'px');
- },
- /**
- * <length>
- */
- em: function em(n) {
- return new CSSUnitValue(n, 'em');
- },
- rem: function rem(n) {
- return new CSSUnitValue(n, 'rem');
- },
- /**
- * <angle>
- */
- deg: function deg(n) {
- return new CSSUnitValue(n, 'deg');
- },
- /**
- * <angle>
- */
- grad: function grad(n) {
- return new CSSUnitValue(n, 'grad');
- },
- /**
- * <angle>
- */
- rad: function rad(n) {
- return new CSSUnitValue(n, 'rad');
- },
- /**
- * <angle>
- */
- turn: function turn(n) {
- return new CSSUnitValue(n, 'turn');
- },
- /**
- * <time>
- */
- s: function s(n) {
- return new CSSUnitValue(n, 's');
- },
- /**
- * <time>
- */
- ms: function ms(n) {
- return new CSSUnitValue(n, 'ms');
- },
- /**
- * CSS Properties & Values API
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS_Properties_and_Values_API
- * @see https://drafts.css-houdini.org/css-properties-values-api/#registering-custom-properties
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
- */
- registerProperty: function registerProperty(definition) {
- var name = definition.name,
- inherits = definition.inherits,
- interpolable = definition.interpolable,
- initialValue = definition.initialValue,
- syntax = definition.syntax;
- runtime.styleValueRegistry.registerMetadata({
- n: name,
- inh: inherits,
- int: interpolable,
- d: initialValue,
- syntax: syntax
- });
- },
- /**
- * CSS Layout API
- * register layout
- *
- * @see https://github.com/w3c/css-houdini-drafts/blob/main/css-layout-api/EXPLAINER.md
- * @see https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini#css_layout_api
- */
- registerLayout: function registerLayout(name, clazz) {
- runtime.layoutRegistry.registerLayout(name, clazz);
- }
- };
- /**
- * CSSKeywordValue
- */
- var unsetKeywordValue = new CSSKeywordValue('unset');
- var initialKeywordValue = new CSSKeywordValue('initial');
- var inheritKeywordValue = new CSSKeywordValue('inherit');
- var keywordCache = {
- '': unsetKeywordValue,
- unset: unsetKeywordValue,
- initial: initialKeywordValue,
- inherit: inheritKeywordValue
- };
- var getOrCreateKeyword = function getOrCreateKeyword(name) {
- if (!keywordCache[name]) {
- keywordCache[name] = new CSSKeywordValue(name);
- }
- return keywordCache[name];
- };
- /**
- * CSSColor
- */
- var noneColor = new CSSRGB(0, 0, 0, 0, true);
- var transparentColor = new CSSRGB(0, 0, 0, 0);
- var getOrCreateRGBA = memoize(function (r, g, b, a) {
- return new CSSRGB(r, g, b, a);
- }, function (r, g, b, a) {
- return "rgba(" + r + "," + g + "," + b + "," + a + ")";
- });
- // export const getOrCreateUnitValue = memoize(
- // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
- // return new CSSUnitValue(value, unitOrName);
- // },
- // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
- // return `${value}${unitOrName}`;
- // },
- // );
- var getOrCreateUnitValue = function getOrCreateUnitValue(value, unitOrName) {
- if (unitOrName === void 0) {
- unitOrName = exports.UnitType.kNumber;
- }
- return new CSSUnitValue(value, unitOrName);
- };
- var PECENTAGE_50 = new CSSUnitValue(50, '%');
- function define(constructor, factory, prototype) {
- constructor.prototype = factory.prototype = prototype;
- prototype.constructor = constructor;
- }
- function extend(parent, definition) {
- var prototype = Object.create(parent.prototype);
- for (var key in definition) prototype[key] = definition[key];
- return prototype;
- }
- function Color() {}
- var darker = 0.7;
- var brighter = 1 / darker;
- var reI = "\\s*([+-]?\\d+)\\s*",
- reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
- reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
- reHex = /^#([0-9a-f]{3,8})$/,
- reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
- reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
- reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
- reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
- reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
- reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");
- var named = {
- aliceblue: 0xf0f8ff,
- antiquewhite: 0xfaebd7,
- aqua: 0x00ffff,
- aquamarine: 0x7fffd4,
- azure: 0xf0ffff,
- beige: 0xf5f5dc,
- bisque: 0xffe4c4,
- black: 0x000000,
- blanchedalmond: 0xffebcd,
- blue: 0x0000ff,
- blueviolet: 0x8a2be2,
- brown: 0xa52a2a,
- burlywood: 0xdeb887,
- cadetblue: 0x5f9ea0,
- chartreuse: 0x7fff00,
- chocolate: 0xd2691e,
- coral: 0xff7f50,
- cornflowerblue: 0x6495ed,
- cornsilk: 0xfff8dc,
- crimson: 0xdc143c,
- cyan: 0x00ffff,
- darkblue: 0x00008b,
- darkcyan: 0x008b8b,
- darkgoldenrod: 0xb8860b,
- darkgray: 0xa9a9a9,
- darkgreen: 0x006400,
- darkgrey: 0xa9a9a9,
- darkkhaki: 0xbdb76b,
- darkmagenta: 0x8b008b,
- darkolivegreen: 0x556b2f,
- darkorange: 0xff8c00,
- darkorchid: 0x9932cc,
- darkred: 0x8b0000,
- darksalmon: 0xe9967a,
- darkseagreen: 0x8fbc8f,
- darkslateblue: 0x483d8b,
- darkslategray: 0x2f4f4f,
- darkslategrey: 0x2f4f4f,
- darkturquoise: 0x00ced1,
- darkviolet: 0x9400d3,
- deeppink: 0xff1493,
- deepskyblue: 0x00bfff,
- dimgray: 0x696969,
- dimgrey: 0x696969,
- dodgerblue: 0x1e90ff,
- firebrick: 0xb22222,
- floralwhite: 0xfffaf0,
- forestgreen: 0x228b22,
- fuchsia: 0xff00ff,
- gainsboro: 0xdcdcdc,
- ghostwhite: 0xf8f8ff,
- gold: 0xffd700,
- goldenrod: 0xdaa520,
- gray: 0x808080,
- green: 0x008000,
- greenyellow: 0xadff2f,
- grey: 0x808080,
- honeydew: 0xf0fff0,
- hotpink: 0xff69b4,
- indianred: 0xcd5c5c,
- indigo: 0x4b0082,
- ivory: 0xfffff0,
- khaki: 0xf0e68c,
- lavender: 0xe6e6fa,
- lavenderblush: 0xfff0f5,
- lawngreen: 0x7cfc00,
- lemonchiffon: 0xfffacd,
- lightblue: 0xadd8e6,
- lightcoral: 0xf08080,
- lightcyan: 0xe0ffff,
- lightgoldenrodyellow: 0xfafad2,
- lightgray: 0xd3d3d3,
- lightgreen: 0x90ee90,
- lightgrey: 0xd3d3d3,
- lightpink: 0xffb6c1,
- lightsalmon: 0xffa07a,
- lightseagreen: 0x20b2aa,
- lightskyblue: 0x87cefa,
- lightslategray: 0x778899,
- lightslategrey: 0x778899,
- lightsteelblue: 0xb0c4de,
- lightyellow: 0xffffe0,
- lime: 0x00ff00,
- limegreen: 0x32cd32,
- linen: 0xfaf0e6,
- magenta: 0xff00ff,
- maroon: 0x800000,
- mediumaquamarine: 0x66cdaa,
- mediumblue: 0x0000cd,
- mediumorchid: 0xba55d3,
- mediumpurple: 0x9370db,
- mediumseagreen: 0x3cb371,
- mediumslateblue: 0x7b68ee,
- mediumspringgreen: 0x00fa9a,
- mediumturquoise: 0x48d1cc,
- mediumvioletred: 0xc71585,
- midnightblue: 0x191970,
- mintcream: 0xf5fffa,
- mistyrose: 0xffe4e1,
- moccasin: 0xffe4b5,
- navajowhite: 0xffdead,
- navy: 0x000080,
- oldlace: 0xfdf5e6,
- olive: 0x808000,
- olivedrab: 0x6b8e23,
- orange: 0xffa500,
- orangered: 0xff4500,
- orchid: 0xda70d6,
- palegoldenrod: 0xeee8aa,
- palegreen: 0x98fb98,
- paleturquoise: 0xafeeee,
- palevioletred: 0xdb7093,
- papayawhip: 0xffefd5,
- peachpuff: 0xffdab9,
- peru: 0xcd853f,
- pink: 0xffc0cb,
- plum: 0xdda0dd,
- powderblue: 0xb0e0e6,
- purple: 0x800080,
- rebeccapurple: 0x663399,
- red: 0xff0000,
- rosybrown: 0xbc8f8f,
- royalblue: 0x4169e1,
- saddlebrown: 0x8b4513,
- salmon: 0xfa8072,
- sandybrown: 0xf4a460,
- seagreen: 0x2e8b57,
- seashell: 0xfff5ee,
- sienna: 0xa0522d,
- silver: 0xc0c0c0,
- skyblue: 0x87ceeb,
- slateblue: 0x6a5acd,
- slategray: 0x708090,
- slategrey: 0x708090,
- snow: 0xfffafa,
- springgreen: 0x00ff7f,
- steelblue: 0x4682b4,
- tan: 0xd2b48c,
- teal: 0x008080,
- thistle: 0xd8bfd8,
- tomato: 0xff6347,
- turquoise: 0x40e0d0,
- violet: 0xee82ee,
- wheat: 0xf5deb3,
- white: 0xffffff,
- whitesmoke: 0xf5f5f5,
- yellow: 0xffff00,
- yellowgreen: 0x9acd32
- };
- define(Color, color, {
- copy: function(channels) {
- return Object.assign(new this.constructor, this, channels);
- },
- displayable: function() {
- return this.rgb().displayable();
- },
- hex: color_formatHex, // Deprecated! Use color.formatHex.
- formatHex: color_formatHex,
- formatHsl: color_formatHsl,
- formatRgb: color_formatRgb,
- toString: color_formatRgb
- });
- function color_formatHex() {
- return this.rgb().formatHex();
- }
- function color_formatHsl() {
- return hslConvert(this).formatHsl();
- }
- function color_formatRgb() {
- return this.rgb().formatRgb();
- }
- function color(format) {
- var m, l;
- format = (format + "").trim().toLowerCase();
- return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000
- : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
- : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
- : l === 4 ? rgba((m >> 12 & 0xf) | (m >> 8 & 0xf0), (m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), (((m & 0xf) << 4) | (m & 0xf)) / 0xff) // #f000
- : null) // invalid hex
- : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
- : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
- : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
- : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
- : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
- : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
- : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins
- : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
- : null;
- }
- function rgbn(n) {
- return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
- }
- function rgba(r, g, b, a) {
- if (a <= 0) r = g = b = NaN;
- return new Rgb(r, g, b, a);
- }
- function rgbConvert(o) {
- if (!(o instanceof Color)) o = color(o);
- if (!o) return new Rgb;
- o = o.rgb();
- return new Rgb(o.r, o.g, o.b, o.opacity);
- }
- function rgb(r, g, b, opacity) {
- return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
- }
- function Rgb(r, g, b, opacity) {
- this.r = +r;
- this.g = +g;
- this.b = +b;
- this.opacity = +opacity;
- }
- define(Rgb, rgb, extend(Color, {
- brighter: function(k) {
- k = k == null ? brighter : Math.pow(brighter, k);
- return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
- },
- darker: function(k) {
- k = k == null ? darker : Math.pow(darker, k);
- return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
- },
- rgb: function() {
- return this;
- },
- displayable: function() {
- return (-0.5 <= this.r && this.r < 255.5)
- && (-0.5 <= this.g && this.g < 255.5)
- && (-0.5 <= this.b && this.b < 255.5)
- && (0 <= this.opacity && this.opacity <= 1);
- },
- hex: rgb_formatHex, // Deprecated! Use color.formatHex.
- formatHex: rgb_formatHex,
- formatRgb: rgb_formatRgb,
- toString: rgb_formatRgb
- }));
- function rgb_formatHex() {
- return "#" + hex(this.r) + hex(this.g) + hex(this.b);
- }
- function rgb_formatRgb() {
- var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
- return (a === 1 ? "rgb(" : "rgba(")
- + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
- + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
- + Math.max(0, Math.min(255, Math.round(this.b) || 0))
- + (a === 1 ? ")" : ", " + a + ")");
- }
- function hex(value) {
- value = Math.max(0, Math.min(255, Math.round(value) || 0));
- return (value < 16 ? "0" : "") + value.toString(16);
- }
- function hsla(h, s, l, a) {
- if (a <= 0) h = s = l = NaN;
- else if (l <= 0 || l >= 1) h = s = NaN;
- else if (s <= 0) h = NaN;
- return new Hsl(h, s, l, a);
- }
- function hslConvert(o) {
- if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
- if (!(o instanceof Color)) o = color(o);
- if (!o) return new Hsl;
- if (o instanceof Hsl) return o;
- o = o.rgb();
- var r = o.r / 255,
- g = o.g / 255,
- b = o.b / 255,
- min = Math.min(r, g, b),
- max = Math.max(r, g, b),
- h = NaN,
- s = max - min,
- l = (max + min) / 2;
- if (s) {
- if (r === max) h = (g - b) / s + (g < b) * 6;
- else if (g === max) h = (b - r) / s + 2;
- else h = (r - g) / s + 4;
- s /= l < 0.5 ? max + min : 2 - max - min;
- h *= 60;
- } else {
- s = l > 0 && l < 1 ? 0 : h;
- }
- return new Hsl(h, s, l, o.opacity);
- }
- function hsl(h, s, l, opacity) {
- return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
- }
- function Hsl(h, s, l, opacity) {
- this.h = +h;
- this.s = +s;
- this.l = +l;
- this.opacity = +opacity;
- }
- define(Hsl, hsl, extend(Color, {
- brighter: function(k) {
- k = k == null ? brighter : Math.pow(brighter, k);
- return new Hsl(this.h, this.s, this.l * k, this.opacity);
- },
- darker: function(k) {
- k = k == null ? darker : Math.pow(darker, k);
- return new Hsl(this.h, this.s, this.l * k, this.opacity);
- },
- rgb: function() {
- var h = this.h % 360 + (this.h < 0) * 360,
- s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
- l = this.l,
- m2 = l + (l < 0.5 ? l : 1 - l) * s,
- m1 = 2 * l - m2;
- return new Rgb(
- hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
- hsl2rgb(h, m1, m2),
- hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
- this.opacity
- );
- },
- displayable: function() {
- return (0 <= this.s && this.s <= 1 || isNaN(this.s))
- && (0 <= this.l && this.l <= 1)
- && (0 <= this.opacity && this.opacity <= 1);
- },
- formatHsl: function() {
- var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
- return (a === 1 ? "hsl(" : "hsla(")
- + (this.h || 0) + ", "
- + (this.s || 0) * 100 + "%, "
- + (this.l || 0) * 100 + "%"
- + (a === 1 ? ")" : ", " + a + ")");
- }
- }));
- /* From FvD 13.37, CSS Color Module Level 3 */
- function hsl2rgb(h, m1, m2) {
- return (h < 60 ? m1 + (m2 - m1) * h / 60
- : h < 180 ? m2
- : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
- : m1) * 255;
- }
- var canvasMap = {};
- var defaultCanvasIdCounter = 0;
- /**
- * destroy existed canvas with the same id
- */
- function cleanExistedCanvas(container, canvas) {
- if (container) {
- var id = typeof container === 'string' ? container : container.id || defaultCanvasIdCounter++;
- if (canvasMap[id]) {
- canvasMap[id].destroy();
- }
- canvasMap[id] = canvas;
- }
- }
- var isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
- function sortedIndex(array, value) {
- var low = 0;
- var high = array.length;
- while (low < high) {
- var mid = low + high >>> 1;
- if (sortByZIndex(array[mid], value) < 0) {
- low = mid + 1;
- } else {
- high = mid;
- }
- }
- return low;
- }
- function sortByZIndex(o1, o2) {
- var zIndex1 = Number(o1.parsedStyle.zIndex);
- var zIndex2 = Number(o2.parsedStyle.zIndex);
- if (zIndex1 === zIndex2) {
- var parent = o1.parentNode;
- if (parent) {
- var children = parent.childNodes || [];
- return children.indexOf(o1) - children.indexOf(o2);
- }
- }
- return zIndex1 - zIndex2;
- }
- function findClosestClipPathTarget(object) {
- var el = object;
- do {
- var _el$parsedStyle;
- var clipPath = (_el$parsedStyle = el.parsedStyle) === null || _el$parsedStyle === void 0 ? void 0 : _el$parsedStyle.clipPath;
- if (clipPath) return el;
- el = el.parentElement;
- } while (el !== null);
- return null;
- }
- var PX_SUFFIX = 'px';
- function setDOMSize($el, width, height) {
- if (isBrowser && $el.style) {
- $el.style.width = width + PX_SUFFIX;
- $el.style.height = height + PX_SUFFIX;
- }
- }
- function getStyle($el, property) {
- if (isBrowser) {
- return document.defaultView.getComputedStyle($el, null).getPropertyValue(property);
- }
- }
- function getWidth($el) {
- var width = getStyle($el, 'width');
- if (width === 'auto') {
- return $el.offsetWidth;
- }
- return parseFloat(width);
- }
- function getHeight($el) {
- var height = getStyle($el, 'height');
- if (height === 'auto') {
- return $el.offsetHeight;
- }
- return parseFloat(height);
- }
- var ERROR_MSG_METHOD_NOT_IMPLEMENTED = 'Method not implemented.';
- var ERROR_MSG_USE_DOCUMENT_ELEMENT = 'Use document.documentElement instead.';
- var ERROR_MSG_APPEND_DESTROYED_ELEMENT = 'Cannot append a destroyed element.';
- // borrow from hammer.js
- var MOUSE_POINTER_ID = 1;
- var TOUCH_TO_POINTER = {
- touchstart: 'pointerdown',
- touchend: 'pointerup',
- touchendoutside: 'pointerupoutside',
- touchmove: 'pointermove',
- touchcancel: 'pointercancel'
- };
- function copyVec3(a, b) {
- a[0] = b[0];
- a[1] = b[1];
- a[2] = b[2];
- return a;
- }
- function subVec3(o, a, b) {
- o[0] = a[0] - b[0];
- o[1] = a[1] - b[1];
- o[2] = a[2] - b[2];
- return o;
- }
- function addVec3(o, a, b) {
- o[0] = a[0] + b[0];
- o[1] = a[1] + b[1];
- o[2] = a[2] + b[2];
- return o;
- }
- function scaleVec3(o, a, b) {
- o[0] = a[0] * b;
- o[1] = a[1] * b;
- o[2] = a[2] * b;
- return o;
- }
- function maxVec3(o, a, b) {
- o[0] = Math.max(a[0], b[0]);
- o[1] = Math.max(a[1], b[1]);
- o[2] = Math.max(a[2], b[2]);
- return o;
- }
- function minVec3(o, a, b) {
- o[0] = Math.min(a[0], b[0]);
- o[1] = Math.min(a[1], b[1]);
- o[2] = Math.min(a[2], b[2]);
- return o;
- }
- function getAngle(angle) {
- if (angle === undefined) {
- return 0;
- } else if (angle > 360 || angle < -360) {
- return angle % 360;
- }
- return angle;
- }
- function createVec3(x, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (Array.isArray(x) && x.length === 3) {
- return clone$1(x);
- }
- if (isNumber(x)) {
- return fromValues$2(x, y, z);
- }
- return fromValues$2(x[0], x[1] || y, x[2] || z);
- }
- function deg2rad(deg) {
- return deg * (Math.PI / 180);
- }
- function rad2deg(rad) {
- return rad * (180 / Math.PI);
- }
- function grad2deg(grads) {
- grads = grads % 400;
- if (grads < 0) {
- grads += 400;
- }
- return grads / 400 * 360;
- }
- function deg2turn(deg) {
- return deg / 360;
- }
- function turn2deg(turn) {
- return 360 * turn;
- }
- function getEulerFromQuat(out, quat) {
- var x = quat[0];
- var y = quat[1];
- var z = quat[2];
- var w = quat[3];
- var x2 = x * x;
- var y2 = y * y;
- var z2 = z * z;
- var w2 = w * w;
- var unit = x2 + y2 + z2 + w2;
- var test = x * w - y * z;
- if (test > 0.499995 * unit) {
- // TODO: Use glmatrix.EPSILON
- // singularity at the north pole
- out[0] = Math.PI / 2;
- out[1] = 2 * Math.atan2(y, x);
- out[2] = 0;
- } else if (test < -0.499995 * unit) {
- //TODO: Use glmatrix.EPSILON
- // singularity at the south pole
- out[0] = -Math.PI / 2;
- out[1] = 2 * Math.atan2(y, x);
- out[2] = 0;
- } else {
- out[0] = Math.asin(2 * (x * z - w * y));
- out[1] = Math.atan2(2 * (x * w + y * z), 1 - 2 * (z2 + w2));
- out[2] = Math.atan2(2 * (x * y + z * w), 1 - 2 * (y2 + z2));
- }
- // TODO: Return them as degrees and not as radians
- return out;
- }
- function getEulerFromMat4(out, m) {
- var x;
- var z;
- var halfPi = Math.PI * 0.5;
- var _mat4$getScaling = getScaling(create$2(), m),
- sx = _mat4$getScaling[0],
- sy = _mat4$getScaling[1],
- sz = _mat4$getScaling[2];
- var y = Math.asin(-m[2] / sx);
- if (y < halfPi) {
- if (y > -halfPi) {
- x = Math.atan2(m[6] / sy, m[10] / sz);
- z = Math.atan2(m[1] / sx, m[0] / sx);
- } else {
- // Not a unique solution
- z = 0;
- x = -Math.atan2(m[4] / sy, m[5] / sy);
- }
- } else {
- // Not a unique solution
- z = 0;
- x = Math.atan2(m[4] / sy, m[5] / sy);
- }
- out[0] = x;
- out[1] = y;
- out[2] = z;
- return out;
- }
- /**
- * @see https://github.com/toji/gl-matrix/issues/329
- * @see https://doc.babylonjs.com/divingDeeper/mesh/transforms/center_origin/rotation_conventions
- */
- function getEuler(out, quat) {
- if (quat.length === 16) {
- return getEulerFromMat4(out, quat);
- } else {
- return getEulerFromQuat(out, quat);
- }
- }
- function fromRotationTranslationScale$1(rotation, x, y, scaleX, scaleY) {
- var cos = Math.cos(rotation);
- var sin = Math.sin(rotation);
- return fromValues(scaleX * cos, scaleY * sin, 0, -scaleX * sin, scaleY * cos, 0, x, y, 1);
- }
- function makePerspective(out, left, right, top, bottom, near, far) {
- var x = 2 * near / (right - left);
- var y = 2 * near / (top - bottom);
- var a = (right + left) / (right - left);
- var b = (top + bottom) / (top - bottom);
- var c = -(far + near) / (far - near);
- var d = -2 * far * near / (far - near);
- out[0] = x;
- out[1] = 0;
- out[2] = 0;
- out[3] = 0;
- out[4] = 0;
- out[5] = y;
- out[6] = 0;
- out[7] = 0;
- out[8] = a;
- out[9] = b;
- out[10] = c;
- out[11] = -1;
- out[12] = 0;
- out[13] = 0;
- out[14] = d;
- out[15] = 0;
- return out;
- }
- function decompose(mat) {
- var row0x = mat[0];
- var row0y = mat[1];
- var row1x = mat[3];
- var row1y = mat[4];
- // decompose 3x3 matrix
- // @see https://www.w3.org/TR/css-transforms-1/#decomposing-a-2d-matrix
- var scalingX = Math.sqrt(row0x * row0x + row0y * row0y);
- var scalingY = Math.sqrt(row1x * row1x + row1y * row1y);
- // If determinant is negative, one axis was flipped.
- var determinant = row0x * row1y - row0y * row1x;
- if (determinant < 0) {
- // Flip axis with minimum unit vector dot product.
- if (row0x < row1y) {
- scalingX = -scalingX;
- } else {
- scalingY = -scalingY;
- }
- }
- // Renormalize matrix to remove scale.
- if (scalingX) {
- row0x *= 1 / scalingX;
- row0y *= 1 / scalingX;
- }
- if (scalingY) {
- row1x *= 1 / scalingY;
- row1y *= 1 / scalingY;
- }
- // Compute rotation and renormalize matrix.
- var rotation = Math.atan2(row0y, row0x);
- var angle = rad2deg(rotation);
- return [mat[6], mat[7], scalingX, scalingY, angle];
- }
- var tmp = create$1();
- var perspectiveMatrix = create$1();
- var tmpVec4 = create$3();
- var row = [create$2(), create$2(), create$2()];
- var pdum3 = create$2();
- /*
- Input: matrix ; a 4x4 matrix
- Output: translation ; a 3 component vector
- scale ; a 3 component vector
- skew ; skew factors XY,XZ,YZ represented as a 3 component vector
- perspective ; a 4 component vector
- quaternion ; a 4 component vector
- Returns false if the matrix cannot be decomposed, true if it can
- References:
- https://github.com/kamicane/matrix3d/blob/master/lib/Matrix3d.js
- https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc
- http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix
- */
- function decomposeMat4(matrix, translation, scale, skew, perspective, quaternion) {
- //normalize, if not possible then bail out early
- if (!normalize$4(tmp, matrix)) return false;
- // perspectiveMatrix is used to solve for perspective, but it also provides
- // an easy way to test for singularity of the upper 3x3 component.
- copy(perspectiveMatrix, tmp);
- perspectiveMatrix[3] = 0;
- perspectiveMatrix[7] = 0;
- perspectiveMatrix[11] = 0;
- perspectiveMatrix[15] = 1;
- // If the perspectiveMatrix is not invertible, we are also unable to
- // decompose, so we'll bail early. Constant taken from SkMatrix44::invert.
- if (Math.abs(determinant(perspectiveMatrix)) < 1e-8) return false;
- var a03 = tmp[3],
- a13 = tmp[7],
- a23 = tmp[11],
- a30 = tmp[12],
- a31 = tmp[13],
- a32 = tmp[14],
- a33 = tmp[15];
- // First, isolate perspective.
- if (a03 !== 0 || a13 !== 0 || a23 !== 0) {
- tmpVec4[0] = a03;
- tmpVec4[1] = a13;
- tmpVec4[2] = a23;
- tmpVec4[3] = a33;
- // Solve the equation by inverting perspectiveMatrix and multiplying
- // rightHandSide by the inverse.
- // resuing the perspectiveMatrix here since it's no longer needed
- var ret = invert(perspectiveMatrix, perspectiveMatrix);
- if (!ret) return false;
- transpose(perspectiveMatrix, perspectiveMatrix);
- //multiply by transposed inverse perspective matrix, into perspective vec4
- transformMat4$1(perspective, tmpVec4, perspectiveMatrix);
- } else {
- //no perspective
- perspective[0] = perspective[1] = perspective[2] = 0;
- perspective[3] = 1;
- }
- // Next take care of translation
- translation[0] = a30;
- translation[1] = a31;
- translation[2] = a32;
- // Now get scale and shear. 'row' is a 3 element array of 3 component vectors
- mat3from4(row, tmp);
- // Compute X scale factor and normalize first row.
- scale[0] = length(row[0]);
- normalize(row[0], row[0]);
- // Compute XY shear factor and make 2nd row orthogonal to 1st.
- skew[0] = dot(row[0], row[1]);
- combine(row[1], row[1], row[0], 1.0, -skew[0]);
- // Now, compute Y scale and normalize 2nd row.
- scale[1] = length(row[1]);
- normalize(row[1], row[1]);
- skew[0] /= scale[1];
- // Compute XZ and YZ shears, orthogonalize 3rd row
- skew[1] = dot(row[0], row[2]);
- combine(row[2], row[2], row[0], 1.0, -skew[1]);
- skew[2] = dot(row[1], row[2]);
- combine(row[2], row[2], row[1], 1.0, -skew[2]);
- // Next, get Z scale and normalize 3rd row.
- scale[2] = length(row[2]);
- normalize(row[2], row[2]);
- skew[1] /= scale[2];
- skew[2] /= scale[2];
- // At this point, the matrix (in rows) is orthonormal.
- // Check for a coordinate system flip. If the determinant
- // is -1, then negate the matrix and the scaling factors.
- cross(pdum3, row[1], row[2]);
- if (dot(row[0], pdum3) < 0) {
- for (var i = 0; i < 3; i++) {
- scale[i] *= -1;
- row[i][0] *= -1;
- row[i][1] *= -1;
- row[i][2] *= -1;
- }
- }
- // Now, get the rotations out
- quaternion[0] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] - row[1][1] - row[2][2], 0));
- quaternion[1] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] + row[1][1] - row[2][2], 0));
- quaternion[2] = 0.5 * Math.sqrt(Math.max(1 - row[0][0] - row[1][1] + row[2][2], 0));
- quaternion[3] = 0.5 * Math.sqrt(Math.max(1 + row[0][0] + row[1][1] + row[2][2], 0));
- if (row[2][1] > row[1][2]) quaternion[0] = -quaternion[0];
- if (row[0][2] > row[2][0]) quaternion[1] = -quaternion[1];
- if (row[1][0] > row[0][1]) quaternion[2] = -quaternion[2];
- return true;
- }
- function normalize$4(out, mat) {
- var m44 = mat[15];
- // Cannot normalize.
- if (m44 === 0) return false;
- var scale = 1 / m44;
- for (var i = 0; i < 16; i++) out[i] = mat[i] * scale;
- return true;
- }
- //gets upper-left of a 4x4 matrix into a 3x3 of vectors
- function mat3from4(out, mat4x4) {
- out[0][0] = mat4x4[0];
- out[0][1] = mat4x4[1];
- out[0][2] = mat4x4[2];
- out[1][0] = mat4x4[4];
- out[1][1] = mat4x4[5];
- out[1][2] = mat4x4[6];
- out[2][0] = mat4x4[8];
- out[2][1] = mat4x4[9];
- out[2][2] = mat4x4[10];
- }
- function combine(out, a, b, scale1, scale2) {
- out[0] = a[0] * scale1 + b[0] * scale2;
- out[1] = a[1] * scale1 + b[1] * scale2;
- out[2] = a[2] * scale1 + b[2] * scale2;
- }
- var tmpMat4 = create$1();
- function parsedTransformToMat4(transform, object) {
- if (transform && transform.length) {
- var defX = 0;
- var defY = 0;
- if (object) {
- defX = object.parsedStyle.defX || 0;
- defY = object.parsedStyle.defY || 0;
- // reset transform
- object.resetLocalTransform();
- object.setLocalPosition(defX, defY);
- } else {
- object = new DisplayObject({});
- }
- transform.forEach(function (parsed) {
- var t = parsed.t,
- d = parsed.d;
- if (t === 'scale') {
- // scale(1) scale(1, 1)
- var newScale = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1, 1];
- object.scaleLocal(newScale[0], newScale[1], 1);
- } else if (t === 'scalex') {
- var _newScale = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1];
- object.scaleLocal(_newScale[0], 1, 1);
- } else if (t === 'scaley') {
- var _newScale2 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1];
- object.scaleLocal(1, _newScale2[0], 1);
- } else if (t === 'scalez') {
- var _newScale3 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1];
- object.scaleLocal(1, 1, _newScale3[0]);
- } else if (t === 'scale3d') {
- var _newScale4 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [1, 1, 1];
- object.scaleLocal(_newScale4[0], _newScale4[1], _newScale4[2]);
- } else if (t === 'translate') {
- var newTranslation = d || [Opx, Opx];
- object.translateLocal(newTranslation[0].value, newTranslation[1].value, 0);
- } else if (t === 'translatex') {
- var _newTranslation = d || [Opx];
- object.translateLocal(_newTranslation[0].value, 0, 0);
- } else if (t === 'translatey') {
- var _newTranslation2 = d || [Opx];
- object.translateLocal(0, _newTranslation2[0].value, 0);
- } else if (t === 'translatez') {
- var _newTranslation3 = d || [Opx];
- object.translateLocal(0, 0, _newTranslation3[0].value);
- } else if (t === 'translate3d') {
- var _newTranslation4 = d || [Opx, Opx, Opx];
- object.translateLocal(_newTranslation4[0].value, _newTranslation4[1].value, _newTranslation4[2].value);
- } else if (t === 'rotate') {
- var newAngles = d || [Odeg];
- object.rotateLocal(0, 0, convertAngleUnit(newAngles[0]));
- } else if (t === 'rotatex') {
- var _newAngles = d || [Odeg];
- object.rotateLocal(convertAngleUnit(_newAngles[0]), 0, 0);
- } else if (t === 'rotatey') {
- var _newAngles2 = d || [Odeg];
- object.rotateLocal(0, convertAngleUnit(_newAngles2[0]), 0);
- } else if (t === 'rotatez') {
- var _newAngles3 = d || [Odeg];
- object.rotateLocal(0, 0, convertAngleUnit(_newAngles3[0]));
- } else if (t === 'rotate3d') ; else if (t === 'skew') {
- var newSkew = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [0, 0];
- object.setLocalSkew(deg2rad(newSkew[0]), deg2rad(newSkew[1]));
- } else if (t === 'skewx') {
- var _newSkew = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [0];
- object.setLocalSkew(deg2rad(_newSkew[0]), object.getLocalSkew()[1]);
- } else if (t === 'skewy') {
- var _newSkew2 = (d === null || d === void 0 ? void 0 : d.map(function (s) {
- return s.value;
- })) || [0];
- object.setLocalSkew(object.getLocalSkew()[0], deg2rad(_newSkew2[0]));
- } else if (t === 'matrix') {
- var _d$map = d.map(function (s) {
- return s.value;
- }),
- a = _d$map[0],
- b = _d$map[1],
- c = _d$map[2],
- dd = _d$map[3],
- tx = _d$map[4],
- ty = _d$map[5];
- object.setLocalTransform(set(tmpMat4, a, b, 0, 0, c, dd, 0, 0, 0, 0, 1, 0, tx + defX, ty + defY, 0, 1));
- } else if (t === 'matrix3d') {
- // @ts-ignore
- set.apply(mat4, [tmpMat4].concat(d.map(function (s) {
- return s.value;
- })));
- tmpMat4[12] += defX;
- tmpMat4[13] += defY;
- object.setLocalTransform(tmpMat4);
- }
- });
- }
- return object.getLocalTransform();
- }
- /**
- * borrow from gradient-parser, but we delete some browser compatible prefix such as `-webkit-`
- * @see https://github.com/rafaelcaricio/gradient-parser
- */
- function colorStopToString(colorStop) {
- var type = colorStop.type,
- value = colorStop.value;
- if (type === 'hex') {
- return "#" + value;
- } else if (type === 'literal') {
- return value;
- } else if (type === 'rgb') {
- return "rgb(" + value.join(',') + ")";
- } else {
- return "rgba(" + value.join(',') + ")";
- }
- }
- var parseGradient = function () {
- var tokens = {
- linearGradient: /^(linear\-gradient)/i,
- repeatingLinearGradient: /^(repeating\-linear\-gradient)/i,
- radialGradient: /^(radial\-gradient)/i,
- repeatingRadialGradient: /^(repeating\-radial\-gradient)/i,
- /**
- * @see https://projects.verou.me/conic-gradient/
- */
- conicGradient: /^(conic\-gradient)/i,
- sideOrCorner: /^to (left (top|bottom)|right (top|bottom)|top (left|right)|bottom (left|right)|left|right|top|bottom)/i,
- extentKeywords: /^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,
- positionKeywords: /^(left|center|right|top|bottom)/i,
- pixelValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,
- percentageValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,
- emValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,
- angleValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,
- startCall: /^\(/,
- endCall: /^\)/,
- comma: /^,/,
- hexColor: /^\#([0-9a-fA-F]+)/,
- literalColor: /^([a-zA-Z]+)/,
- rgbColor: /^rgb/i,
- rgbaColor: /^rgba/i,
- number: /^(([0-9]*\.[0-9]+)|([0-9]+\.?))/
- };
- var input = '';
- function error(msg) {
- throw new Error(input + ': ' + msg);
- }
- function getAST() {
- var ast = matchListDefinitions();
- if (input.length > 0) {
- error('Invalid input not EOF');
- }
- return ast;
- }
- function matchListDefinitions() {
- return matchListing(matchDefinition);
- }
- function matchDefinition() {
- return matchGradient('linear-gradient', tokens.linearGradient, matchLinearOrientation) || matchGradient('repeating-linear-gradient', tokens.repeatingLinearGradient, matchLinearOrientation) || matchGradient('radial-gradient', tokens.radialGradient, matchListRadialOrientations) || matchGradient('repeating-radial-gradient', tokens.repeatingRadialGradient, matchListRadialOrientations) || matchGradient('conic-gradient', tokens.conicGradient, matchListRadialOrientations);
- }
- function matchGradient(gradientType, pattern, orientationMatcher) {
- return matchCall(pattern, function (captures) {
- var orientation = orientationMatcher();
- if (orientation) {
- if (!scan(tokens.comma)) {
- error('Missing comma before color stops');
- }
- }
- return {
- type: gradientType,
- orientation: orientation,
- colorStops: matchListing(matchColorStop)
- };
- });
- }
- function matchCall(pattern, callback) {
- var captures = scan(pattern);
- if (captures) {
- if (!scan(tokens.startCall)) {
- error('Missing (');
- }
- var result = callback(captures);
- if (!scan(tokens.endCall)) {
- error('Missing )');
- }
- return result;
- }
- }
- function matchLinearOrientation() {
- return matchSideOrCorner() || matchAngle();
- }
- function matchSideOrCorner() {
- return match('directional', tokens.sideOrCorner, 1);
- }
- function matchAngle() {
- return match('angular', tokens.angleValue, 1);
- }
- function matchListRadialOrientations() {
- var radialOrientations,
- radialOrientation = matchRadialOrientation(),
- lookaheadCache;
- if (radialOrientation) {
- radialOrientations = [];
- radialOrientations.push(radialOrientation);
- lookaheadCache = input;
- if (scan(tokens.comma)) {
- radialOrientation = matchRadialOrientation();
- if (radialOrientation) {
- radialOrientations.push(radialOrientation);
- } else {
- input = lookaheadCache;
- }
- }
- }
- return radialOrientations;
- }
- function matchRadialOrientation() {
- var radialType = matchCircle() || matchEllipse();
- if (radialType) {
- // @ts-ignore
- radialType.at = matchAtPosition();
- } else {
- var extent = matchExtentKeyword();
- if (extent) {
- radialType = extent;
- var positionAt = matchAtPosition();
- if (positionAt) {
- // @ts-ignore
- radialType.at = positionAt;
- }
- } else {
- var defaultPosition = matchPositioning();
- if (defaultPosition) {
- radialType = {
- type: 'default-radial',
- // @ts-ignore
- at: defaultPosition
- };
- }
- }
- }
- return radialType;
- }
- function matchCircle() {
- var circle = match('shape', /^(circle)/i, 0);
- if (circle) {
- // @ts-ignore
- circle.style = matchLength() || matchExtentKeyword();
- }
- return circle;
- }
- function matchEllipse() {
- var ellipse = match('shape', /^(ellipse)/i, 0);
- if (ellipse) {
- // @ts-ignore
- ellipse.style = matchDistance() || matchExtentKeyword();
- }
- return ellipse;
- }
- function matchExtentKeyword() {
- return match('extent-keyword', tokens.extentKeywords, 1);
- }
- function matchAtPosition() {
- if (match('position', /^at/, 0)) {
- var positioning = matchPositioning();
- if (!positioning) {
- error('Missing positioning value');
- }
- return positioning;
- }
- }
- function matchPositioning() {
- var location = matchCoordinates();
- if (location.x || location.y) {
- return {
- type: 'position',
- value: location
- };
- }
- }
- function matchCoordinates() {
- return {
- x: matchDistance(),
- y: matchDistance()
- };
- }
- function matchListing(matcher) {
- var captures = matcher();
- var result = [];
- if (captures) {
- result.push(captures);
- while (scan(tokens.comma)) {
- captures = matcher();
- if (captures) {
- result.push(captures);
- } else {
- error('One extra comma');
- }
- }
- }
- return result;
- }
- function matchColorStop() {
- var color = matchColor();
- if (!color) {
- error('Expected color definition');
- }
- color.length = matchDistance();
- return color;
- }
- function matchColor() {
- return matchHexColor() || matchRGBAColor() || matchRGBColor() || matchLiteralColor();
- }
- function matchLiteralColor() {
- return match('literal', tokens.literalColor, 0);
- }
- function matchHexColor() {
- return match('hex', tokens.hexColor, 1);
- }
- function matchRGBColor() {
- return matchCall(tokens.rgbColor, function () {
- return {
- type: 'rgb',
- value: matchListing(matchNumber)
- };
- });
- }
- function matchRGBAColor() {
- return matchCall(tokens.rgbaColor, function () {
- return {
- type: 'rgba',
- value: matchListing(matchNumber)
- };
- });
- }
- function matchNumber() {
- return scan(tokens.number)[1];
- }
- function matchDistance() {
- return match('%', tokens.percentageValue, 1) || matchPositionKeyword() || matchLength();
- }
- function matchPositionKeyword() {
- return match('position-keyword', tokens.positionKeywords, 1);
- }
- function matchLength() {
- return match('px', tokens.pixelValue, 1) || match('em', tokens.emValue, 1);
- }
- function match(type, pattern, captureIndex) {
- var captures = scan(pattern);
- if (captures) {
- return {
- type: type,
- value: captures[captureIndex]
- };
- }
- }
- function scan(regexp) {
- var blankCaptures = /^[\n\r\t\s]+/.exec(input);
- if (blankCaptures) {
- consume(blankCaptures[0].length);
- }
- var captures = regexp.exec(input);
- if (captures) {
- consume(captures[0].length);
- }
- return captures;
- }
- function consume(size) {
- input = input.substring(size);
- }
- return function (code) {
- input = code;
- return getAST();
- };
- }();
- function computeLinearGradient(width, height, angle) {
- var rad = deg2rad(angle.value);
- var rx = 0;
- var ry = 0;
- var rcx = rx + width / 2;
- var rcy = ry + height / 2;
- // get the length of gradient line
- // @see https://observablehq.com/@danburzo/css-gradient-line
- var length = Math.abs(width * Math.cos(rad)) + Math.abs(height * Math.sin(rad));
- var x1 = rcx - Math.cos(rad) * length / 2;
- var y1 = rcy - Math.sin(rad) * length / 2;
- var x2 = rcx + Math.cos(rad) * length / 2;
- var y2 = rcy + Math.sin(rad) * length / 2;
- return {
- x1: x1,
- y1: y1,
- x2: x2,
- y2: y2
- };
- }
- function computeRadialGradient(width, height, cx, cy, size) {
- // 'px'
- var x = cx.value;
- var y = cy.value;
- // TODO: 'em'
- // '%'
- if (cx.unit === exports.UnitType.kPercentage) {
- x = cx.value / 100 * width;
- }
- if (cy.unit === exports.UnitType.kPercentage) {
- y = cy.value / 100 * height;
- }
- // default to farthest-side
- var r = Math.max(distanceSquareRoot([0, 0], [x, y]), distanceSquareRoot([0, height], [x, y]), distanceSquareRoot([width, height], [x, y]), distanceSquareRoot([width, 0], [x, y]));
- if (size) {
- if (size instanceof CSSUnitValue) {
- r = size.value;
- } else if (size instanceof CSSKeywordValue) {
- // @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/CSS_Images/Using_CSS_gradients#example_closest-side_for_circles
- if (size.value === 'closest-side') {
- r = Math.min(x, width - x, y, height - y);
- } else if (size.value === 'farthest-side') {
- r = Math.max(x, width - x, y, height - y);
- } else if (size.value === 'closest-corner') {
- r = Math.min(distanceSquareRoot([0, 0], [x, y]), distanceSquareRoot([0, height], [x, y]), distanceSquareRoot([width, height], [x, y]), distanceSquareRoot([width, 0], [x, y]));
- }
- }
- }
- return {
- x: x,
- y: y,
- r: r
- };
- }
- /**
- * 两点之间的距离
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @return {number} 距离
- */
- function distance(x1, y1, x2, y2) {
- var dx = x1 - x2;
- var dy = y1 - y2;
- return Math.sqrt(dx * dx + dy * dy);
- }
- function isNumberEqual$1(v1, v2) {
- return Math.abs(v1 - v2) < 0.001;
- }
- function getBBoxByArray(xArr, yArr) {
- var minX = Math.min.apply(Math, xArr);
- var minY = Math.min.apply(Math, yArr);
- var maxX = Math.max.apply(Math, xArr);
- var maxY = Math.max.apply(Math, yArr);
- return {
- x: minX,
- y: minY,
- width: maxX - minX,
- height: maxY - minY
- };
- }
- function piMod(angle) {
- return (angle + Math.PI * 2) % (Math.PI * 2);
- }
- var line = {
- /**
- * 计算线段的包围盒
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @return {object} 包围盒对象
- */
- box: function box(x1, y1, x2, y2) {
- return getBBoxByArray([x1, x2], [y1, y2]);
- },
- /**
- * 线段的长度
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @return {number} 距离
- */
- length: function length(x1, y1, x2, y2) {
- return distance(x1, y1, x2, y2);
- },
- /**
- * 根据比例获取点
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @param {number} t 指定比例
- * @return {object} 包含 x, y 的点
- */
- pointAt: function pointAt(x1, y1, x2, y2, t) {
- return {
- x: (1 - t) * x1 + t * x2,
- y: (1 - t) * y1 + t * y2
- };
- },
- /**
- * 点到线段的距离
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @param {number} x 测试点 x
- * @param {number} y 测试点 y
- * @return {number} 距离
- */
- pointDistance: function pointDistance(x1, y1, x2, y2, x, y) {
- // 投影距离 x1, y1 的向量,假设 p, p1, p2 三个点,投影点为 a
- // p1a = p1p.p1p2/|p1p2| * (p1p 的单位向量)
- var cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);
- if (cross < 0) {
- return distance(x1, y1, x, y);
- }
- var lengthSquare = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
- if (cross > lengthSquare) {
- return distance(x2, y2, x, y);
- }
- return this.pointToLine(x1, y1, x2, y2, x, y);
- },
- /**
- * 点到直线的距离,而不是点到线段的距离
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @param {number} x 测试点 x
- * @param {number} y 测试点 y
- * @return {number} 距离
- */
- pointToLine: function pointToLine(x1, y1, x2, y2, x, y) {
- var d = [x2 - x1, y2 - y1];
- // 如果端点相等,则判定点到点的距离
- if (exactEquals$1(d, [0, 0])) {
- return Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
- }
- var u = [-d[1], d[0]];
- normalize$3(u, u);
- var a = [x - x1, y - y1];
- return Math.abs(dot$1(a, u));
- },
- /**
- * 线段的角度
- * @param {number} x1 起始点 x
- * @param {number} y1 起始点 y
- * @param {number} x2 结束点 x
- * @param {number} y2 结束点 y
- * @return {number} 导数
- */
- tangentAngle: function tangentAngle(x1, y1, x2, y2) {
- return Math.atan2(y2 - y1, x2 - x1);
- }
- };
- var EPSILON$1 = 0.0001;
- /**
- * 使用牛顿切割法求最近的点
- * @param {number[]} xArr 点的 x 数组
- * @param {number[]} yArr 点的 y 数组
- * @param {number} x 指定的点 x
- * @param {number} y 指定的点 y
- * @param {Function} tCallback 差值函数
- */
- function nearestPoint(xArr, yArr, x, y, tCallback, length) {
- var t = -1;
- var d = Infinity;
- var v0 = [x, y];
- var segNum = 20;
- if (length && length > 200) {
- segNum = length / 10;
- }
- var increaseRate = 1 / segNum;
- var interval = increaseRate / 10;
- for (var i = 0; i <= segNum; i++) {
- var _t = i * increaseRate;
- var v1 = [tCallback.apply(void 0, xArr.concat([_t])), tCallback.apply(void 0, yArr.concat([_t]))];
- var d1 = distance(v0[0], v0[1], v1[0], v1[1]);
- if (d1 < d) {
- t = _t;
- d = d1;
- }
- }
- // 提前终止
- if (t === 0) {
- return {
- x: xArr[0],
- y: yArr[0]
- };
- }
- if (t === 1) {
- var count = xArr.length;
- return {
- x: xArr[count - 1],
- y: yArr[count - 1]
- };
- }
- d = Infinity;
- for (var _i = 0; _i < 32; _i++) {
- if (interval < EPSILON$1) {
- break;
- }
- var prev = t - interval;
- var next = t + interval;
- var _v = [tCallback.apply(void 0, xArr.concat([prev])), tCallback.apply(void 0, yArr.concat([prev]))];
- var _d = distance(v0[0], v0[1], _v[0], _v[1]);
- if (prev >= 0 && _d < d) {
- t = prev;
- d = _d;
- } else {
- var v2 = [tCallback.apply(void 0, xArr.concat([next])), tCallback.apply(void 0, yArr.concat([next]))];
- var d2 = distance(v0[0], v0[1], v2[0], v2[1]);
- if (next <= 1 && d2 < d) {
- t = next;
- d = d2;
- } else {
- interval *= 0.5;
- }
- }
- }
- return {
- x: tCallback.apply(void 0, xArr.concat([t])),
- y: tCallback.apply(void 0, yArr.concat([t]))
- };
- }
- // 近似求解 https://community.khronos.org/t/3d-cubic-bezier-segment-length/62363/2
- function snapLength(xArr, yArr) {
- var totalLength = 0;
- var count = xArr.length;
- for (var i = 0; i < count; i++) {
- var x = xArr[i];
- var y = yArr[i];
- var nextX = xArr[(i + 1) % count];
- var nextY = yArr[(i + 1) % count];
- totalLength += distance(x, y, nextX, nextY);
- }
- return totalLength / 2;
- }
- // 差值公式
- function quadraticAt(p0, p1, p2, t) {
- var onet = 1 - t;
- return onet * onet * p0 + 2 * t * onet * p1 + t * t * p2;
- }
- // 求极值
- function extrema(p0, p1, p2) {
- var a = p0 + p2 - 2 * p1;
- if (isNumberEqual$1(a, 0)) {
- return [0.5];
- }
- var rst = (p0 - p1) / a;
- if (rst <= 1 && rst >= 0) {
- return [rst];
- }
- return [];
- }
- function derivativeAt(p0, p1, p2, t) {
- return 2 * (1 - t) * (p1 - p0) + 2 * t * (p2 - p1);
- }
- // 分割贝塞尔曲线
- function divideQuadratic(x1, y1, x2, y2, x3, y3, t) {
- // 划分点
- var xt = quadraticAt(x1, x2, x3, t);
- var yt = quadraticAt(y1, y2, y3, t);
- // 分割的第一条曲线的控制点
- var controlPoint1 = line.pointAt(x1, y1, x2, y2, t);
- // 分割的第二条曲线的控制点
- var controlPoint2 = line.pointAt(x2, y2, x3, y3, t);
- return [[x1, y1, controlPoint1.x, controlPoint1.y, xt, yt], [xt, yt, controlPoint2.x, controlPoint2.y, x3, y3]];
- }
- // 使用迭代法取贝塞尔曲线的长度
- function quadraticLength(x1, y1, x2, y2, x3, y3, iterationCount) {
- if (iterationCount === 0) {
- return (distance(x1, y1, x2, y2) + distance(x2, y2, x3, y3) + distance(x1, y1, x3, y3)) / 2;
- }
- var quadratics = divideQuadratic(x1, y1, x2, y2, x3, y3, 0.5);
- var left = quadratics[0];
- var right = quadratics[1];
- left.push(iterationCount - 1);
- right.push(iterationCount - 1);
- return quadraticLength.apply(void 0, left) + quadraticLength.apply(void 0, right);
- }
- var quadratic = {
- box: function box(x1, y1, x2, y2, x3, y3) {
- var xExtrema = extrema(x1, x2, x3)[0];
- var yExtrema = extrema(y1, y2, y3)[0];
- // 控制点不加入 box 的计算
- var xArr = [x1, x3];
- var yArr = [y1, y3];
- if (xExtrema !== undefined) {
- xArr.push(quadraticAt(x1, x2, x3, xExtrema));
- }
- if (yExtrema !== undefined) {
- yArr.push(quadraticAt(y1, y2, y3, yExtrema));
- }
- return getBBoxByArray(xArr, yArr);
- },
- length: function length(x1, y1, x2, y2, x3, y3) {
- return quadraticLength(x1, y1, x2, y2, x3, y3, 3);
- },
- nearestPoint: function nearestPoint$1(x1, y1, x2, y2, x3, y3, x0, y0) {
- return nearestPoint([x1, x2, x3], [y1, y2, y3], x0, y0, quadraticAt);
- },
- pointDistance: function pointDistance(x1, y1, x2, y2, x3, y3, x0, y0) {
- var point = this.nearestPoint(x1, y1, x2, y2, x3, y3, x0, y0);
- return distance(point.x, point.y, x0, y0);
- },
- interpolationAt: quadraticAt,
- pointAt: function pointAt(x1, y1, x2, y2, x3, y3, t) {
- return {
- x: quadraticAt(x1, x2, x3, t),
- y: quadraticAt(y1, y2, y3, t)
- };
- },
- divide: function divide(x1, y1, x2, y2, x3, y3, t) {
- return divideQuadratic(x1, y1, x2, y2, x3, y3, t);
- },
- tangentAngle: function tangentAngle(x1, y1, x2, y2, x3, y3, t) {
- var dx = derivativeAt(x1, x2, x3, t);
- var dy = derivativeAt(y1, y2, y3, t);
- var angle = Math.atan2(dy, dx);
- return piMod(angle);
- }
- };
- function cubicAt(p0, p1, p2, p3, t) {
- var onet = 1 - t; // t * t * t 的性能大概是 Math.pow(t, 3) 的三倍
- return onet * onet * onet * p0 + 3 * p1 * t * onet * onet + 3 * p2 * t * t * onet + p3 * t * t * t;
- }
- function derivativeAt$1(p0, p1, p2, p3, t) {
- var onet = 1 - t;
- return 3 * (onet * onet * (p1 - p0) + 2 * onet * t * (p2 - p1) + t * t * (p3 - p2));
- }
- function extrema$1(p0, p1, p2, p3) {
- var a = -3 * p0 + 9 * p1 - 9 * p2 + 3 * p3;
- var b = 6 * p0 - 12 * p1 + 6 * p2;
- var c = 3 * p1 - 3 * p0;
- var extremas = [];
- var t1;
- var t2;
- var discSqrt;
- if (isNumberEqual$1(a, 0)) {
- if (!isNumberEqual$1(b, 0)) {
- t1 = -c / b;
- if (t1 >= 0 && t1 <= 1) {
- extremas.push(t1);
- }
- }
- } else {
- var disc = b * b - 4 * a * c;
- if (isNumberEqual$1(disc, 0)) {
- extremas.push(-b / (2 * a));
- } else if (disc > 0) {
- discSqrt = Math.sqrt(disc);
- t1 = (-b + discSqrt) / (2 * a);
- t2 = (-b - discSqrt) / (2 * a);
- if (t1 >= 0 && t1 <= 1) {
- extremas.push(t1);
- }
- if (t2 >= 0 && t2 <= 1) {
- extremas.push(t2);
- }
- }
- }
- return extremas;
- }
- // 分割贝塞尔曲线
- function divideCubic(x1, y1, x2, y2, x3, y3, x4, y4, t) {
- // 划分点
- var xt = cubicAt(x1, x2, x3, x4, t);
- var yt = cubicAt(y1, y2, y3, y4, t);
- // 计算两点之间的差值点
- var c1 = line.pointAt(x1, y1, x2, y2, t);
- var c2 = line.pointAt(x2, y2, x3, y3, t);
- var c3 = line.pointAt(x3, y3, x4, y4, t);
- var c12 = line.pointAt(c1.x, c1.y, c2.x, c2.y, t);
- var c23 = line.pointAt(c2.x, c2.y, c3.x, c3.y, t);
- return [[x1, y1, c1.x, c1.y, c12.x, c12.y, xt, yt], [xt, yt, c23.x, c23.y, c3.x, c3.y, x4, y4]];
- }
- // 使用迭代法取贝塞尔曲线的长度,二阶和三阶分开写,更清晰和便于调试
- function cubicLength(x1, y1, x2, y2, x3, y3, x4, y4, iterationCount) {
- if (iterationCount === 0) {
- return snapLength([x1, x2, x3, x4], [y1, y2, y3, y4]);
- }
- var cubics = divideCubic(x1, y1, x2, y2, x3, y3, x4, y4, 0.5);
- var left = [].concat(cubics[0], [iterationCount - 1]);
- var right = [].concat(cubics[1], [iterationCount - 1]);
- return cubicLength.apply(void 0, left) + cubicLength.apply(void 0, right);
- }
- var cubic = {
- extrema: extrema$1,
- box: function box(x1, y1, x2, y2, x3, y3, x4, y4) {
- var xArr = [x1, x4];
- var yArr = [y1, y4];
- var xExtrema = extrema$1(x1, x2, x3, x4);
- var yExtrema = extrema$1(y1, y2, y3, y4);
- for (var i = 0; i < xExtrema.length; i++) {
- xArr.push(cubicAt(x1, x2, x3, x4, xExtrema[i]));
- }
- for (var _i = 0; _i < yExtrema.length; _i++) {
- yArr.push(cubicAt(y1, y2, y3, y4, yExtrema[_i]));
- }
- return getBBoxByArray(xArr, yArr);
- },
- length: function length(x1, y1, x2, y2, x3, y3, x4, y4) {
- // 迭代三次,划分成 8 段求长度
- return cubicLength(x1, y1, x2, y2, x3, y3, x4, y4, 3);
- },
- nearestPoint: function nearestPoint$1(x1, y1, x2, y2, x3, y3, x4, y4, x0, y0, length) {
- return nearestPoint([x1, x2, x3, x4], [y1, y2, y3, y4], x0, y0, cubicAt, length);
- },
- pointDistance: function pointDistance(x1, y1, x2, y2, x3, y3, x4, y4, x0, y0, length) {
- var point = this.nearestPoint(x1, y1, x2, y2, x3, y3, x4, y4, x0, y0, length);
- return distance(point.x, point.y, x0, y0);
- },
- interpolationAt: cubicAt,
- pointAt: function pointAt(x1, y1, x2, y2, x3, y3, x4, y4, t) {
- return {
- x: cubicAt(x1, x2, x3, x4, t),
- y: cubicAt(y1, y2, y3, y4, t)
- };
- },
- divide: function divide(x1, y1, x2, y2, x3, y3, x4, y4, t) {
- return divideCubic(x1, y1, x2, y2, x3, y3, x4, y4, t);
- },
- tangentAngle: function tangentAngle(x1, y1, x2, y2, x3, y3, x4, y4, t) {
- var dx = derivativeAt$1(x1, x2, x3, x4, t);
- var dy = derivativeAt$1(y1, y2, y3, y4, t);
- return piMod(Math.atan2(dy, dx));
- }
- };
- /**
- * @fileoverview 椭圆的一些计算,
- * - 周长计算参考:https://www.mathsisfun.com/geometry/ellipse-perimeter.html
- * - 距离计算参考:https://wet-robots.ghost.io/simple-method-for-distance-to-ellipse/
- * @author dxq613@gmail.com
- */
- function copysign(v1, v2) {
- var absv = Math.abs(v1);
- return v2 > 0 ? absv : absv * -1;
- }
- var ellipse = {
- /**
- * 包围盒计算
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @return {object} 包围盒
- */
- box: function box(x, y, rx, ry) {
- return {
- x: x - rx,
- y: y - ry,
- width: rx * 2,
- height: ry * 2
- };
- },
- /**
- * 计算周长,使用近似法
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @return {number} 椭圆周长
- */
- length: function length(x, y, rx, ry) {
- return Math.PI * (3 * (rx + ry) - Math.sqrt((3 * rx + ry) * (rx + 3 * ry)));
- },
- /**
- * 距离椭圆最近的点
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @param {number} x0 指定的点 x
- * @param {number} y0 指定的点 y
- * @return {object} 椭圆上距离指定点最近的点
- */
- nearestPoint: function nearestPoint(x, y, rx, ry, x0, y0) {
- var a = rx;
- var b = ry;
- // 假如椭圆半径为0则返回圆心
- if (a === 0 || b === 0) {
- return {
- x: x,
- y: y
- };
- }
- // 转换成 0, 0 为中心的椭圆计算
- var relativeX = x0 - x;
- var relativeY = y0 - y;
- var px = Math.abs(relativeX);
- var py = Math.abs(relativeY);
- var squareA = a * a;
- var squareB = b * b;
- // const angle0 = Math.atan2(relativeY, relativeX);
- var t = Math.PI / 4;
- var nearestX = 0; // 椭圆上的任一点
- var nearestY = 0;
- // 迭代 4 次
- for (var i = 0; i < 4; i++) {
- nearestX = a * Math.cos(t);
- nearestY = b * Math.sin(t);
- var ex = (squareA - squareB) * Math.pow(Math.cos(t), 3) / a;
- var ey = (squareB - squareA) * Math.pow(Math.sin(t), 3) / b;
- var rx1 = nearestX - ex;
- var ry1 = nearestY - ey;
- var qx = px - ex;
- var qy = py - ey;
- var r = Math.hypot(ry1, rx1);
- var q = Math.hypot(qy, qx);
- var delta_c = r * Math.asin((rx1 * qy - ry1 * qx) / (r * q));
- var delta_t = delta_c / Math.sqrt(squareA + squareB - nearestX * nearestX - nearestY * nearestY);
- t += delta_t;
- t = Math.min(Math.PI / 2, Math.max(0, t));
- }
- return {
- x: x + copysign(nearestX, relativeX),
- y: y + copysign(nearestY, relativeY)
- };
- },
- /**
- * 点到椭圆最近的距离
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @param {number} x0 指定的点 x
- * @param {number} y0 指定的点 y
- * @return {number} 点到椭圆的距离
- */
- pointDistance: function pointDistance(x, y, rx, ry, x0, y0) {
- var nearestPoint = this.nearestPoint(x, y, rx, ry, x0, y0);
- return distance(nearestPoint.x, nearestPoint.y, x0, y0);
- },
- /**
- * 根据比例获取点
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @param {number} t 指定比例,x轴方向为 0
- * @return {object} 点
- */
- pointAt: function pointAt(x, y, rx, ry, t) {
- var angle = 2 * Math.PI * t; // 按照角度进行计算,而不按照周长计算
- return {
- x: x + rx * Math.cos(angle),
- y: y + ry * Math.sin(angle)
- };
- },
- /**
- * 根据比例计算切线角度
- * @param {number} x 椭圆中心 x
- * @param {number} y 椭圆中心 y
- * @param {number} rx 椭圆 x 方向半径
- * @param {number} ry 椭圆 y 方向半径
- * @param {number} t 指定比例 0 - 1 之间,x轴方向为 0。在 0-1 范围之外是循环还是返回 null,还需要调整
- * @return {number} 角度,在 0 - 2PI 之间
- */
- tangentAngle: function tangentAngle(x, y, rx, ry, t) {
- var angle = 2 * Math.PI * t; // 按照角度进行计算,而不按照周长计算
- // 直接使用 x,y 的导数计算, x' = -rx * sin(t); y' = ry * cos(t);
- var tangentAngle = Math.atan2(ry * Math.cos(angle), -rx * Math.sin(angle));
- // 也可以使用指定点的切线方程计算,成本有些高
- // const point = this.pointAt(0, 0, rx, ry, t); // 椭圆的切线同椭圆的中心不相关
- // let tangentAngle = -1 * Math.atan((ry * ry * point.x) / (rx * rx * point.y));
- // if (angle >= 0 && angle <= Math.PI) {
- // tangentAngle += Math.PI;
- // }
- return piMod(tangentAngle);
- }
- };
- // 偏导数 x
- function derivativeXAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle) {
- return -1 * rx * Math.cos(xRotation) * Math.sin(angle) - ry * Math.sin(xRotation) * Math.cos(angle);
- }
- // 偏导数 y
- function derivativeYAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle) {
- return -1 * rx * Math.sin(xRotation) * Math.sin(angle) + ry * Math.cos(xRotation) * Math.cos(angle);
- }
- // x 的极值
- function xExtrema(rx, ry, xRotation) {
- return Math.atan(-ry / rx * Math.tan(xRotation));
- }
- // y 的极值
- function yExtrema(rx, ry, xRotation) {
- return Math.atan(ry / (rx * Math.tan(xRotation)));
- }
- // 根据角度求 x 坐标
- function xAt(cx, cy, rx, ry, xRotation, angle) {
- return rx * Math.cos(xRotation) * Math.cos(angle) - ry * Math.sin(xRotation) * Math.sin(angle) + cx;
- }
- // 根据角度求 y 坐标
- function yAt(cx, cy, rx, ry, xRotation, angle) {
- return rx * Math.sin(xRotation) * Math.cos(angle) + ry * Math.cos(xRotation) * Math.sin(angle) + cy;
- }
- // 获取点在椭圆上的角度
- function getAngle$1(rx, ry, x0, y0) {
- var angle = Math.atan2(y0 * rx, x0 * ry);
- // 转换到 0 - 2PI 内
- return (angle + Math.PI * 2) % (Math.PI * 2);
- }
- // 根据角度获取,x,y
- function getPoint(rx, ry, angle) {
- return {
- x: rx * Math.cos(angle),
- y: ry * Math.sin(angle)
- };
- }
- // 旋转
- function rotate$1(x, y, angle) {
- var cos = Math.cos(angle);
- var sin = Math.sin(angle);
- return [x * cos - y * sin, x * sin + y * cos];
- }
- var arc = {
- /**
- * 计算包围盒
- * @param {number} cx 圆心 x
- * @param {number} cy 圆心 y
- * @param {number} rx x 轴方向的半径
- * @param {number} ry y 轴方向的半径
- * @param {number} xRotation 旋转角度
- * @param {number} startAngle 起始角度
- * @param {number} endAngle 结束角度
- * @return {object} 包围盒对象
- */
- box: function box(cx, cy, rx, ry, xRotation, startAngle, endAngle) {
- var xDim = xExtrema(rx, ry, xRotation);
- var minX = Infinity;
- var maxX = -Infinity;
- var xs = [startAngle, endAngle];
- for (var i = -Math.PI * 2; i <= Math.PI * 2; i += Math.PI) {
- var xAngle = xDim + i;
- if (startAngle < endAngle) {
- if (startAngle < xAngle && xAngle < endAngle) {
- xs.push(xAngle);
- }
- } else {
- if (endAngle < xAngle && xAngle < startAngle) {
- xs.push(xAngle);
- }
- }
- }
- for (var _i = 0; _i < xs.length; _i++) {
- var x = xAt(cx, cy, rx, ry, xRotation, xs[_i]);
- if (x < minX) {
- minX = x;
- }
- if (x > maxX) {
- maxX = x;
- }
- }
- var yDim = yExtrema(rx, ry, xRotation);
- var minY = Infinity;
- var maxY = -Infinity;
- var ys = [startAngle, endAngle];
- for (var _i2 = -Math.PI * 2; _i2 <= Math.PI * 2; _i2 += Math.PI) {
- var yAngle = yDim + _i2;
- if (startAngle < endAngle) {
- if (startAngle < yAngle && yAngle < endAngle) {
- ys.push(yAngle);
- }
- } else {
- if (endAngle < yAngle && yAngle < startAngle) {
- ys.push(yAngle);
- }
- }
- }
- for (var _i3 = 0; _i3 < ys.length; _i3++) {
- var y = yAt(cx, cy, rx, ry, xRotation, ys[_i3]);
- if (y < minY) {
- minY = y;
- }
- if (y > maxY) {
- maxY = y;
- }
- }
- return {
- x: minX,
- y: minY,
- width: maxX - minX,
- height: maxY - minY
- };
- },
- /**
- * 获取圆弧的长度,计算圆弧长度时不考虑旋转角度,
- * 仅跟 rx, ry, startAngle, endAngle 相关
- * @param {number} cx 圆心 x
- * @param {number} cy 圆心 y
- * @param {number} rx x 轴方向的半径
- * @param {number} ry y 轴方向的半径
- * @param {number} xRotation 旋转角度
- * @param {number} startAngle 起始角度
- * @param {number} endAngle 结束角度
- */
- length: function length(cx, cy, rx, ry, xRotation, startAngle, endAngle) {},
- /**
- * 获取指定点到圆弧的最近距离的点
- * @param {number} cx 圆心 x
- * @param {number} cy 圆心 y
- * @param {number} rx x 轴方向的半径
- * @param {number} ry y 轴方向的半径
- * @param {number} xRotation 旋转角度
- * @param {number} startAngle 起始角度
- * @param {number} endAngle 结束角度
- * @param {number} x0 指定点的 x
- * @param {number} y0 指定点的 y
- * @return {object} 到指定点最近距离的点
- */
- nearestPoint: function nearestPoint(cx, cy, rx, ry, xRotation, startAngle, endAngle, x0, y0) {
- // 将最近距离问题转换成到椭圆中心 0,0 没有旋转的椭圆问题
- var relativeVector = rotate$1(x0 - cx, y0 - cy, -xRotation);
- var x1 = relativeVector[0],
- y1 = relativeVector[1];
- // 计算点到椭圆的最近的点
- var relativePoint = ellipse.nearestPoint(0, 0, rx, ry, x1, y1);
- // 获取点在椭圆上的角度
- var angle = getAngle$1(rx, ry, relativePoint.x, relativePoint.y);
- // 点没有在圆弧上
- if (angle < startAngle) {
- // 小于起始圆弧
- relativePoint = getPoint(rx, ry, startAngle);
- } else if (angle > endAngle) {
- // 大于结束圆弧
- relativePoint = getPoint(rx, ry, endAngle);
- }
- // 旋转到 xRotation 的角度
- var vector = rotate$1(relativePoint.x, relativePoint.y, xRotation);
- return {
- x: vector[0] + cx,
- y: vector[1] + cy
- };
- },
- pointDistance: function pointDistance(cx, cy, rx, ry, xRotation, startAngle, endAngle, x0, y0) {
- var nearestPoint = this.nearestPoint(cx, cy, rx, ry, xRotation, startAngle, endAngle, x0, y0);
- return distance(nearestPoint.x, nearestPoint.y, x0, y0);
- },
- pointAt: function pointAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, t) {
- var angle = (endAngle - startAngle) * t + startAngle;
- return {
- x: xAt(cx, cy, rx, ry, xRotation, angle),
- y: yAt(cx, cy, rx, ry, xRotation, angle)
- };
- },
- tangentAngle: function tangentAngle(cx, cy, rx, ry, xRotation, startAngle, endAngle, t) {
- var angle = (endAngle - startAngle) * t + startAngle;
- var dx = derivativeXAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle);
- var dy = derivativeYAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle);
- return piMod(Math.atan2(dy, dx));
- }
- };
- function analyzePoints(points) {
- // 计算每段的长度和总的长度
- var totalLength = 0;
- var segments = [];
- for (var i = 0; i < points.length - 1; i++) {
- var from = points[i];
- var to = points[i + 1];
- var length = distance(from[0], from[1], to[0], to[1]);
- var seg = {
- from: from,
- to: to,
- length: length
- };
- segments.push(seg);
- totalLength += length;
- }
- return {
- segments: segments,
- totalLength: totalLength
- };
- }
- function lengthOfSegment(points) {
- if (points.length < 2) {
- return 0;
- }
- var totalLength = 0;
- for (var i = 0; i < points.length - 1; i++) {
- var from = points[i];
- var to = points[i + 1];
- totalLength += distance(from[0], from[1], to[0], to[1]);
- }
- return totalLength;
- }
- /**
- * 按照比例在数据片段中获取点
- * @param {array} points 点的集合
- * @param {number} t 百分比 0-1
- * @return {object} 点的坐标
- */
- function pointAtSegments(points, t) {
- // 边界判断
- if (t > 1 || t < 0 || points.length < 2) {
- return null;
- }
- var _analyzePoints = analyzePoints(points),
- segments = _analyzePoints.segments,
- totalLength = _analyzePoints.totalLength;
- // 多个点有可能重合
- if (totalLength === 0) {
- return {
- x: points[0][0],
- y: points[0][1]
- };
- }
- // 计算比例
- var startRatio = 0;
- var point = null;
- for (var i = 0; i < segments.length; i++) {
- var seg = segments[i];
- var from = seg.from,
- to = seg.to;
- var currentRatio = seg.length / totalLength;
- if (t >= startRatio && t <= startRatio + currentRatio) {
- var localRatio = (t - startRatio) / currentRatio;
- point = line.pointAt(from[0], from[1], to[0], to[1], localRatio);
- break;
- }
- startRatio += currentRatio;
- }
- return point;
- }
- /**
- * 按照比例在数据片段中获取切线的角度
- * @param {array} points 点的集合
- * @param {number} t 百分比 0-1
- */
- function angleAtSegments(points, t) {
- // 边界判断
- if (t > 1 || t < 0 || points.length < 2) {
- return 0;
- }
- var _analyzePoints2 = analyzePoints(points),
- segments = _analyzePoints2.segments,
- totalLength = _analyzePoints2.totalLength;
- // 计算比例
- var startRatio = 0;
- var angle = 0;
- for (var i = 0; i < segments.length; i++) {
- var seg = segments[i];
- var from = seg.from,
- to = seg.to;
- var currentRatio = seg.length / totalLength;
- if (t >= startRatio && t <= startRatio + currentRatio) {
- angle = Math.atan2(to[1] - from[1], to[0] - from[0]);
- break;
- }
- startRatio += currentRatio;
- }
- return angle;
- }
- function distanceAtSegment(points, x, y) {
- var minDistance = Infinity;
- for (var i = 0; i < points.length - 1; i++) {
- var point = points[i];
- var nextPoint = points[i + 1];
- var _distance = line.pointDistance(point[0], point[1], nextPoint[0], nextPoint[1], x, y);
- if (_distance < minDistance) {
- minDistance = _distance;
- }
- }
- return minDistance;
- }
- var polyline = {
- /**
- * 计算多折线的包围盒
- * @param {array} points 点的集合 [x,y] 的形式
- * @return {object} 包围盒
- */
- box: function box(points) {
- var xArr = [];
- var yArr = [];
- for (var i = 0; i < points.length; i++) {
- var point = points[i];
- xArr.push(point[0]);
- yArr.push(point[1]);
- }
- return getBBoxByArray(xArr, yArr);
- },
- /**
- * 计算多折线的长度
- * @param {array} points 点的集合 [x,y] 的形式
- * @return {object} 多条边的长度
- */
- length: function length(points) {
- return lengthOfSegment(points);
- },
- /**
- * 根据比例获取多折线的点
- * @param {array} points 点的集合 [x,y] 的形式
- * @param {number} t 在多折线的长度上的比例
- * @return {object} 根据比例值计算出来的点
- */
- pointAt: function pointAt(points, t) {
- return pointAtSegments(points, t);
- },
- /**
- * 指定点到多折线的距离
- * @param {array} points 点的集合 [x,y] 的形式
- * @param {number} x 指定点的 x
- * @param {number} y 指定点的 y
- * @return {number} 点到多折线的距离
- */
- pointDistance: function pointDistance(points, x, y) {
- return distanceAtSegment(points, x, y);
- },
- /**
- * 根据比例获取多折线的切线角度
- * @param {array} points 点的集合 [x,y] 的形式
- * @param {number} t 在多折线的长度上的比例
- * @return {object} 根据比例值计算出来的角度
- */
- tangentAngle: function tangentAngle(points, t) {
- return angleAtSegments(points, t);
- }
- };
- (function (Shape) {
- Shape["GROUP"] = "g";
- Shape["CIRCLE"] = "circle";
- Shape["ELLIPSE"] = "ellipse";
- Shape["IMAGE"] = "image";
- Shape["RECT"] = "rect";
- Shape["LINE"] = "line";
- Shape["POLYLINE"] = "polyline";
- Shape["POLYGON"] = "polygon";
- Shape["TEXT"] = "text";
- Shape["PATH"] = "path";
- Shape["HTML"] = "html";
- Shape["MESH"] = "mesh";
- })(exports.Shape || (exports.Shape = {}));
- function getOrCalculatePathTotalLength(path) {
- if (path.parsedStyle.path.totalLength === 0) {
- path.parsedStyle.path.totalLength = getTotalLength(path.parsedStyle.path.absolutePath);
- }
- return path.parsedStyle.path.totalLength;
- }
- function hasArcOrBezier(path) {
- var hasArc = false;
- var count = path.length;
- for (var i = 0; i < count; i++) {
- var params = path[i];
- var cmd = params[0];
- if (cmd === 'C' || cmd === 'A' || cmd === 'Q') {
- hasArc = true;
- break;
- }
- }
- return hasArc;
- }
- function extractPolygons(pathArray) {
- var polygons = [];
- var polylines = [];
- var points = []; // 防止第一个命令不是 'M'
- for (var i = 0; i < pathArray.length; i++) {
- var params = pathArray[i];
- var cmd = params[0];
- if (cmd === 'M') {
- // 遇到 'M' 判定是否是新数组,新数组中没有点
- if (points.length) {
- // 如果存在点,则说明没有遇到 'Z',开始了一个新的多边形
- polylines.push(points);
- points = []; // 创建新的点
- }
- points.push([params[1], params[2]]);
- } else if (cmd === 'Z') {
- if (points.length) {
- // 存在点
- polygons.push(points);
- points = []; // 开始新的点集合
- }
- // 如果不存在点,同时 'Z',则说明是错误,不处理
- } else {
- points.push([params[1], params[2]]);
- }
- }
- // 说明 points 未放入 polygons 或者 polyline
- // 仅当只有一个 M,没有 Z 时会发生这种情况
- if (points.length > 0) {
- polylines.push(points);
- }
- return {
- polygons: polygons,
- polylines: polylines
- };
- }
- function isSamePoint(point1, point2) {
- return point1[0] === point2[0] && point1[1] === point2[1];
- }
- function getPathBBox(segments, lineWidth) {
- var xArr = [];
- var yArr = [];
- var segmentsWithAngle = [];
- for (var i = 0; i < segments.length; i++) {
- var segment = segments[i];
- var currentPoint = segment.currentPoint,
- params = segment.params,
- prePoint = segment.prePoint;
- var box = void 0;
- switch (segment.command) {
- case 'Q':
- box = quadratic.box(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4]);
- break;
- case 'C':
- box = cubic.box(prePoint[0], prePoint[1], params[1], params[2], params[3], params[4], params[5], params[6]);
- break;
- case 'A':
- var arcParams = segment.arcParams;
- box = arc.box(arcParams.cx, arcParams.cy, arcParams.rx, arcParams.ry, arcParams.xRotation, arcParams.startAngle, arcParams.endAngle);
- break;
- default:
- xArr.push(currentPoint[0]);
- yArr.push(currentPoint[1]);
- break;
- }
- if (box) {
- segment.box = box;
- xArr.push(box.x, box.x + box.width);
- yArr.push(box.y, box.y + box.height);
- }
- if (lineWidth && (segment.command === 'L' || segment.command === 'M') && segment.prePoint && segment.nextPoint) {
- segmentsWithAngle.push(segment);
- }
- }
- // bbox calculation should ignore NaN for path attribute
- // ref: https://github.com/antvis/g/issues/210
- // ref: https://github.com/antvis/G2/issues/3109
- xArr = xArr.filter(function (item) {
- return !Number.isNaN(item) && item !== Infinity && item !== -Infinity;
- });
- yArr = yArr.filter(function (item) {
- return !Number.isNaN(item) && item !== Infinity && item !== -Infinity;
- });
- var minX = min(xArr);
- var minY = min(yArr);
- var maxX = max(xArr);
- var maxY = max(yArr);
- if (segmentsWithAngle.length === 0) {
- return {
- x: minX,
- y: minY,
- width: maxX - minX,
- height: maxY - minY
- };
- }
- for (var _i = 0; _i < segmentsWithAngle.length; _i++) {
- var _segment = segmentsWithAngle[_i];
- var _currentPoint = _segment.currentPoint;
- var extra = void 0;
- if (_currentPoint[0] === minX) {
- extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
- minX = minX - extra.xExtra;
- } else if (_currentPoint[0] === maxX) {
- extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
- maxX = maxX + extra.xExtra;
- }
- if (_currentPoint[1] === minY) {
- extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
- minY = minY - extra.yExtra;
- } else if (_currentPoint[1] === maxY) {
- extra = getExtraFromSegmentWithAngle(_segment, lineWidth);
- maxY = maxY + extra.yExtra;
- }
- }
- return {
- x: minX,
- y: minY,
- width: maxX - minX,
- height: maxY - minY
- };
- }
- function getExtraFromSegmentWithAngle(segment, lineWidth) {
- var prePoint = segment.prePoint,
- currentPoint = segment.currentPoint,
- nextPoint = segment.nextPoint;
- var currentAndPre = Math.pow(currentPoint[0] - prePoint[0], 2) + Math.pow(currentPoint[1] - prePoint[1], 2);
- var currentAndNext = Math.pow(currentPoint[0] - nextPoint[0], 2) + Math.pow(currentPoint[1] - nextPoint[1], 2);
- var preAndNext = Math.pow(prePoint[0] - nextPoint[0], 2) + Math.pow(prePoint[1] - nextPoint[1], 2);
- // 以 currentPoint 为顶点的夹角
- var currentAngle = Math.acos((currentAndPre + currentAndNext - preAndNext) / (2 * Math.sqrt(currentAndPre) * Math.sqrt(currentAndNext)));
- // 夹角为空、 0 或 PI 时,不需要计算夹角处的额外宽度
- // 注意: 由于计算精度问题,夹角为 0 的情况计算出来的角度可能是一个很小的值,还需要判断其与 0 是否近似相等
- if (!currentAngle || Math.sin(currentAngle) === 0 || isNumberEqual(currentAngle, 0)) {
- return {
- xExtra: 0,
- yExtra: 0
- };
- }
- var xAngle = Math.abs(Math.atan2(nextPoint[1] - currentPoint[1], nextPoint[0] - currentPoint[0]));
- var yAngle = Math.abs(Math.atan2(nextPoint[0] - currentPoint[0], nextPoint[1] - currentPoint[1]));
- // 将夹角转为锐角
- xAngle = xAngle > Math.PI / 2 ? Math.PI - xAngle : xAngle;
- yAngle = yAngle > Math.PI / 2 ? Math.PI - yAngle : yAngle;
- // 这里不考虑在水平和垂直方向的投影,直接使用最大差值
- // 由于上层统一加减了二分之一线宽,这里需要进行弥补
- var extra = {
- // 水平方向投影
- xExtra: Math.cos(currentAngle / 2 - xAngle) * (lineWidth / 2 * (1 / Math.sin(currentAngle / 2))) - lineWidth / 2 || 0,
- // 垂直方向投影
- yExtra: Math.cos(yAngle - currentAngle / 2) * (lineWidth / 2 * (1 / Math.sin(currentAngle / 2))) - lineWidth / 2 || 0
- };
- return extra;
- }
- // 点对称
- function toSymmetry(point, center) {
- return [center[0] + (center[0] - point[0]), center[1] + (center[1] - point[1])];
- }
- var angleBetween$1 = function angleBetween(v0, v1) {
- var p = v0.x * v1.x + v0.y * v1.y;
- var n = Math.sqrt((Math.pow(v0.x, 2) + Math.pow(v0.y, 2)) * (Math.pow(v1.x, 2) + Math.pow(v1.y, 2)));
- var sign = v0.x * v1.y - v0.y * v1.x < 0 ? -1 : 1;
- var angle = sign * Math.acos(p / n);
- return angle;
- };
- /**
- * @see https://github.com/rveciana/svg-path-properties/blob/b6bd9a322966f6ef7a311872d80c56e3718de861/src/arc.ts#L121
- */
- var pointOnEllipticalArc = function pointOnEllipticalArc(p0, rx, ry, xAxisRotation, largeArcFlag, sweepFlag, p1, t) {
- // In accordance to: http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
- rx = Math.abs(rx);
- ry = Math.abs(ry);
- xAxisRotation = mod(xAxisRotation, 360);
- var xAxisRotationRadians = deg2rad(xAxisRotation);
- // If the endpoints are identical, then this is equivalent to omitting the elliptical arc segment entirely.
- if (p0.x === p1.x && p0.y === p1.y) {
- return {
- x: p0.x,
- y: p0.y,
- ellipticalArcAngle: 0
- }; // Check if angle is correct
- }
- // If rx = 0 or ry = 0 then this arc is treated as a straight line segment joining the endpoints.
- if (rx === 0 || ry === 0) {
- //return this.pointOnLine(p0, p1, t);
- return {
- x: 0,
- y: 0,
- ellipticalArcAngle: 0
- }; // Check if angle is correct
- }
- // Following "Conversion from endpoint to center parameterization"
- // http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
- // Step #1: Compute transformedPoint
- var dx = (p0.x - p1.x) / 2;
- var dy = (p0.y - p1.y) / 2;
- var transformedPoint = {
- x: Math.cos(xAxisRotationRadians) * dx + Math.sin(xAxisRotationRadians) * dy,
- y: -Math.sin(xAxisRotationRadians) * dx + Math.cos(xAxisRotationRadians) * dy
- };
- // Ensure radii are large enough
- var radiiCheck = Math.pow(transformedPoint.x, 2) / Math.pow(rx, 2) + Math.pow(transformedPoint.y, 2) / Math.pow(ry, 2);
- if (radiiCheck > 1) {
- rx = Math.sqrt(radiiCheck) * rx;
- ry = Math.sqrt(radiiCheck) * ry;
- }
- // Step #2: Compute transformedCenter
- var cSquareNumerator = Math.pow(rx, 2) * Math.pow(ry, 2) - Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) - Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
- var cSquareRootDenom = Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) + Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
- var cRadicand = cSquareNumerator / cSquareRootDenom;
- // Make sure this never drops below zero because of precision
- cRadicand = cRadicand < 0 ? 0 : cRadicand;
- var cCoef = (largeArcFlag !== sweepFlag ? 1 : -1) * Math.sqrt(cRadicand);
- var transformedCenter = {
- x: cCoef * (rx * transformedPoint.y / ry),
- y: cCoef * (-(ry * transformedPoint.x) / rx)
- };
- // Step #3: Compute center
- var center = {
- x: Math.cos(xAxisRotationRadians) * transformedCenter.x - Math.sin(xAxisRotationRadians) * transformedCenter.y + (p0.x + p1.x) / 2,
- y: Math.sin(xAxisRotationRadians) * transformedCenter.x + Math.cos(xAxisRotationRadians) * transformedCenter.y + (p0.y + p1.y) / 2
- };
- // Step #4: Compute start/sweep angles
- // Start angle of the elliptical arc prior to the stretch and rotate operations.
- // Difference between the start and end angles
- var startVector = {
- x: (transformedPoint.x - transformedCenter.x) / rx,
- y: (transformedPoint.y - transformedCenter.y) / ry
- };
- var startAngle = angleBetween$1({
- x: 1,
- y: 0
- }, startVector);
- var endVector = {
- x: (-transformedPoint.x - transformedCenter.x) / rx,
- y: (-transformedPoint.y - transformedCenter.y) / ry
- };
- var sweepAngle = angleBetween$1(startVector, endVector);
- if (!sweepFlag && sweepAngle > 0) {
- sweepAngle -= 2 * Math.PI;
- } else if (sweepFlag && sweepAngle < 0) {
- sweepAngle += 2 * Math.PI;
- }
- // We use % instead of `mod(..)` because we want it to be -360deg to 360deg(but actually in radians)
- sweepAngle %= 2 * Math.PI;
- // From http://www.w3.org/TR/SVG/implnote.html#ArcParameterizationAlternatives
- var angle = startAngle + sweepAngle * t;
- var ellipseComponentX = rx * Math.cos(angle);
- var ellipseComponentY = ry * Math.sin(angle);
- var point = {
- x: Math.cos(xAxisRotationRadians) * ellipseComponentX - Math.sin(xAxisRotationRadians) * ellipseComponentY + center.x,
- y: Math.sin(xAxisRotationRadians) * ellipseComponentX + Math.cos(xAxisRotationRadians) * ellipseComponentY + center.y,
- ellipticalArcStartAngle: startAngle,
- ellipticalArcEndAngle: startAngle + sweepAngle,
- ellipticalArcAngle: angle,
- ellipticalArcCenter: center,
- resultantRx: rx,
- resultantRy: ry
- };
- return point;
- };
- function path2Segments(path) {
- var segments = [];
- var currentPoint = null; // 当前图形
- var nextParams = null; // 下一节点的 path 参数
- var startMovePoint = null; // 开始 M 的点,可能会有多个
- var lastStartMovePointIndex = 0; // 最近一个开始点 M 的索引
- var count = path.length;
- for (var i = 0; i < count; i++) {
- var params = path[i];
- nextParams = path[i + 1];
- var command = params[0];
- // 数学定义上的参数,便于后面的计算
- var segment = {
- command: command,
- prePoint: currentPoint,
- params: params,
- startTangent: null,
- endTangent: null,
- currentPoint: null,
- nextPoint: null,
- arcParams: null,
- box: null,
- cubicParams: null
- };
- switch (command) {
- case 'M':
- startMovePoint = [params[1], params[2]];
- lastStartMovePointIndex = i;
- break;
- case 'A':
- var arcParams = getArcParams(currentPoint, params);
- segment.arcParams = arcParams;
- break;
- }
- if (command === 'Z') {
- // 有了 Z 后,当前节点从开始 M 的点开始
- currentPoint = startMovePoint;
- // 如果当前点的命令为 Z,相当于当前点为最近一个 M 点,则下一个点直接指向最近一个 M 点的下一个点
- nextParams = path[lastStartMovePointIndex + 1];
- } else {
- var len = params.length;
- currentPoint = [params[len - 2], params[len - 1]];
- }
- if (nextParams && nextParams[0] === 'Z') {
- // 如果下一个点的命令为 Z,则下一个点直接指向最近一个 M 点
- nextParams = path[lastStartMovePointIndex];
- if (segments[lastStartMovePointIndex]) {
- // 如果下一个点的命令为 Z,则最近一个 M 点的前一个点为当前点
- segments[lastStartMovePointIndex].prePoint = currentPoint;
- }
- }
- segment.currentPoint = currentPoint;
- // 如果当前点与最近一个 M 点相同,则最近一个 M 点的前一个点为当前点的前一个点
- if (segments[lastStartMovePointIndex] && isSamePoint(currentPoint, segments[lastStartMovePointIndex].currentPoint)) {
- segments[lastStartMovePointIndex].prePoint = segment.prePoint;
- }
- var nextPoint = nextParams ? [nextParams[nextParams.length - 2], nextParams[nextParams.length - 1]] : null;
- segment.nextPoint = nextPoint;
- // Add startTangent and endTangent
- var prePoint = segment.prePoint;
- if (['L', 'H', 'V'].includes(command)) {
- segment.startTangent = [prePoint[0] - currentPoint[0], prePoint[1] - currentPoint[1]];
- segment.endTangent = [currentPoint[0] - prePoint[0], currentPoint[1] - prePoint[1]];
- } else if (command === 'Q') {
- // 二次贝塞尔曲线只有一个控制点
- var cp = [params[1], params[2]];
- // 二次贝塞尔曲线的终点为 currentPoint
- segment.startTangent = [prePoint[0] - cp[0], prePoint[1] - cp[1]];
- segment.endTangent = [currentPoint[0] - cp[0], currentPoint[1] - cp[1]];
- } else if (command === 'T') {
- var preSegment = segments[i - 1];
- var _cp = toSymmetry(preSegment.currentPoint, prePoint);
- if (preSegment.command === 'Q') {
- segment.command = 'Q';
- segment.startTangent = [prePoint[0] - _cp[0], prePoint[1] - _cp[1]];
- segment.endTangent = [currentPoint[0] - _cp[0], currentPoint[1] - _cp[1]];
- } else {
- // @ts-ignore
- segment.command = 'TL';
- segment.startTangent = [prePoint[0] - currentPoint[0], prePoint[1] - currentPoint[1]];
- segment.endTangent = [currentPoint[0] - prePoint[0], currentPoint[1] - prePoint[1]];
- }
- } else if (command === 'C') {
- // 三次贝塞尔曲线有两个控制点
- var cp1 = [params[1], params[2]];
- var cp2 = [params[3], params[4]];
- segment.startTangent = [prePoint[0] - cp1[0], prePoint[1] - cp1[1]];
- segment.endTangent = [currentPoint[0] - cp2[0], currentPoint[1] - cp2[1]];
- // horizontal line, eg. ['C', 100, 100, 100, 100, 200, 200]
- if (segment.startTangent[0] === 0 && segment.startTangent[1] === 0) {
- segment.startTangent = [cp1[0] - cp2[0], cp1[1] - cp2[1]];
- }
- if (segment.endTangent[0] === 0 && segment.endTangent[1] === 0) {
- segment.endTangent = [cp2[0] - cp1[0], cp2[1] - cp1[1]];
- }
- } else if (command === 'S') {
- var _preSegment = segments[i - 1];
- var _cp2 = toSymmetry(_preSegment.currentPoint, prePoint);
- var _cp3 = [params[1], params[2]];
- if (_preSegment.command === 'C') {
- segment.command = 'C'; // 将 S 命令变换为 C 命令
- segment.startTangent = [prePoint[0] - _cp2[0], prePoint[1] - _cp2[1]];
- segment.endTangent = [currentPoint[0] - _cp3[0], currentPoint[1] - _cp3[1]];
- } else {
- // @ts-ignore
- segment.command = 'SQ'; // 将 S 命令变换为 SQ 命令
- segment.startTangent = [prePoint[0] - _cp3[0], prePoint[1] - _cp3[1]];
- segment.endTangent = [currentPoint[0] - _cp3[0], currentPoint[1] - _cp3[1]];
- }
- } else if (command === 'A') {
- var _getTangentAtRatio = getTangentAtRatio(segment, 0),
- dx1 = _getTangentAtRatio.x,
- dy1 = _getTangentAtRatio.y;
- var _getTangentAtRatio2 = getTangentAtRatio(segment, 1, false),
- dx2 = _getTangentAtRatio2.x,
- dy2 = _getTangentAtRatio2.y;
- segment.startTangent = [dx1, dy1];
- segment.endTangent = [dx2, dy2];
- }
- segments.push(segment);
- }
- return segments;
- }
- /**
- * Use length instead of ratio
- */
- function getTangentAtRatio(segment, ratio, sign) {
- if (sign === void 0) {
- sign = true;
- }
- var _segment$arcParams = segment.arcParams,
- _segment$arcParams$rx = _segment$arcParams.rx,
- rx = _segment$arcParams$rx === void 0 ? 0 : _segment$arcParams$rx,
- _segment$arcParams$ry = _segment$arcParams.ry,
- ry = _segment$arcParams$ry === void 0 ? 0 : _segment$arcParams$ry,
- xRotation = _segment$arcParams.xRotation,
- arcFlag = _segment$arcParams.arcFlag,
- sweepFlag = _segment$arcParams.sweepFlag;
- var p1 = pointOnEllipticalArc({
- x: segment.prePoint[0],
- y: segment.prePoint[1]
- }, rx, ry, xRotation, !!arcFlag, !!sweepFlag, {
- x: segment.currentPoint[0],
- y: segment.currentPoint[1]
- }, ratio);
- var p2 = pointOnEllipticalArc({
- x: segment.prePoint[0],
- y: segment.prePoint[1]
- }, rx, ry, xRotation, !!arcFlag, !!sweepFlag, {
- x: segment.currentPoint[0],
- y: segment.currentPoint[1]
- }, sign ? ratio + 0.005 : ratio - 0.005);
- var xDist = p2.x - p1.x;
- var yDist = p2.y - p1.y;
- var dist = Math.sqrt(xDist * xDist + yDist * yDist);
- return {
- x: -xDist / dist,
- y: -yDist / dist
- };
- }
- // 向量长度
- function vMag(v) {
- return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
- }
- // u.v/|u||v|,计算夹角的余弦值
- function vRatio(u, v) {
- // 当存在一个向量的长度为 0 时,夹角也为 0,即夹角的余弦值为 1
- return vMag(u) * vMag(v) ? (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)) : 1;
- }
- // 向量角度
- function vAngle(u, v) {
- return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
- }
- function getArcParams(startPoint, params) {
- var rx = params[1];
- var ry = params[2];
- var xRotation = mod(deg2rad(params[3]), Math.PI * 2);
- var arcFlag = params[4];
- var sweepFlag = params[5];
- // 弧形起点坐标
- var x1 = startPoint[0];
- var y1 = startPoint[1];
- // 弧形终点坐标
- var x2 = params[6];
- var y2 = params[7];
- var xp = Math.cos(xRotation) * (x1 - x2) / 2.0 + Math.sin(xRotation) * (y1 - y2) / 2.0;
- var yp = -1 * Math.sin(xRotation) * (x1 - x2) / 2.0 + Math.cos(xRotation) * (y1 - y2) / 2.0;
- var lambda = xp * xp / (rx * rx) + yp * yp / (ry * ry);
- if (lambda > 1) {
- rx *= Math.sqrt(lambda);
- ry *= Math.sqrt(lambda);
- }
- var diff = rx * rx * (yp * yp) + ry * ry * (xp * xp);
- var f = diff ? Math.sqrt((rx * rx * (ry * ry) - diff) / diff) : 1;
- if (arcFlag === sweepFlag) {
- f *= -1;
- }
- if (isNaN(f)) {
- f = 0;
- }
- // 旋转前的起点坐标,且当长半轴和短半轴的长度为 0 时,坐标按 (0, 0) 处理
- var cxp = ry ? f * rx * yp / ry : 0;
- var cyp = rx ? f * -ry * xp / rx : 0;
- // 椭圆圆心坐标
- var cx = (x1 + x2) / 2.0 + Math.cos(xRotation) * cxp - Math.sin(xRotation) * cyp;
- var cy = (y1 + y2) / 2.0 + Math.sin(xRotation) * cxp + Math.cos(xRotation) * cyp;
- // 起始点的单位向量
- var u = [(xp - cxp) / rx, (yp - cyp) / ry];
- // 终止点的单位向量
- var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
- // 计算起始点和圆心的连线,与 x 轴正方向的夹角
- var theta = vAngle([1, 0], u);
- // 计算圆弧起始点和终止点与椭圆圆心连线的夹角
- var dTheta = vAngle(u, v);
- if (vRatio(u, v) <= -1) {
- dTheta = Math.PI;
- }
- if (vRatio(u, v) >= 1) {
- dTheta = 0;
- }
- if (sweepFlag === 0 && dTheta > 0) {
- dTheta = dTheta - 2 * Math.PI;
- }
- if (sweepFlag === 1 && dTheta < 0) {
- dTheta = dTheta + 2 * Math.PI;
- }
- return {
- cx: cx,
- cy: cy,
- // 弧形的起点和终点相同时,长轴和短轴的长度按 0 处理
- rx: isSamePoint(startPoint, [x2, y2]) ? 0 : rx,
- ry: isSamePoint(startPoint, [x2, y2]) ? 0 : ry,
- startAngle: theta,
- endAngle: theta + dTheta,
- xRotation: xRotation,
- arcFlag: arcFlag,
- sweepFlag: sweepFlag
- };
- }
- function commandsToPathString(commands, object, transform) {
- var _object$parsedStyle = object.parsedStyle,
- _object$parsedStyle$d = _object$parsedStyle.defX,
- defX = _object$parsedStyle$d === void 0 ? 0 : _object$parsedStyle$d,
- _object$parsedStyle$d2 = _object$parsedStyle.defY,
- defY = _object$parsedStyle$d2 === void 0 ? 0 : _object$parsedStyle$d2;
- return commands.reduce(function (prev, cur) {
- var path = '';
- if (cur[0] === 'M' || cur[0] === 'L') {
- var p = fromValues$2(cur[1] - defX, cur[2] - defY, 0);
- if (transform) {
- transformMat4(p, p, transform);
- }
- path = "" + cur[0] + p[0] + "," + p[1];
- } else if (cur[0] === 'Z') {
- path = cur[0];
- } else if (cur[0] === 'C') {
- var p1 = fromValues$2(cur[1] - defX, cur[2] - defY, 0);
- var p2 = fromValues$2(cur[3] - defX, cur[4] - defY, 0);
- var p3 = fromValues$2(cur[5] - defX, cur[6] - defY, 0);
- if (transform) {
- transformMat4(p1, p1, transform);
- transformMat4(p2, p2, transform);
- transformMat4(p3, p3, transform);
- }
- path = "" + cur[0] + p1[0] + "," + p1[1] + "," + p2[0] + "," + p2[1] + "," + p3[0] + "," + p3[1];
- } else if (cur[0] === 'A') {
- var c = fromValues$2(cur[6] - defX, cur[7] - defY, 0);
- if (transform) {
- transformMat4(c, c, transform);
- }
- path = "" + cur[0] + cur[1] + "," + cur[2] + "," + cur[3] + "," + cur[4] + "," + cur[5] + "," + c[0] + "," + c[1];
- } else if (cur[0] === 'Q') {
- var _p = fromValues$2(cur[1] - defX, cur[2] - defY, 0);
- var _p2 = fromValues$2(cur[3] - defX, cur[4] - defY, 0);
- if (transform) {
- transformMat4(_p, _p, transform);
- transformMat4(_p2, _p2, transform);
- }
- path = "" + cur[0] + cur[1] + "," + cur[2] + "," + cur[3] + "," + cur[4] + "}";
- }
- return prev += path;
- }, '');
- }
- function lineToCommands(x1, y1, x2, y2) {
- return [['M', x1, y1], ['L', x2, y2]];
- }
- function ellipseToCommands(rx, ry, cx, cy) {
- var factor = (-1 + Math.sqrt(2)) / 3 * 4;
- var dx = rx * factor;
- var dy = ry * factor;
- var left = cx - rx;
- var right = cx + rx;
- var top = cy - ry;
- var bottom = cy + ry;
- return [['M', left, cy], ['C', left, cy - dy, cx - dx, top, cx, top], ['C', cx + dx, top, right, cy - dy, right, cy], ['C', right, cy + dy, cx + dx, bottom, cx, bottom], ['C', cx - dx, bottom, left, cy + dy, left, cy], ['Z']];
- }
- function polygonToCommands(points, closed) {
- var result = points.map(function (point, i) {
- return [i === 0 ? 'M' : 'L', point[0], point[1]];
- });
- if (closed) {
- result.push(['Z']);
- }
- return result;
- }
- function rectToCommands(width, height, x, y, radius) {
- // @see https://gist.github.com/danielpquinn/dd966af424030d47e476
- if (radius) {
- var tlr = radius[0],
- trr = radius[1],
- brr = radius[2],
- blr = radius[3];
- var signX = width > 0 ? 1 : -1;
- var signY = height > 0 ? 1 : -1;
- // sweep-flag @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Tutorial/Paths#arcs
- var sweepFlag = signX + signY !== 0 ? 1 : 0;
- return [['M', signX * tlr + x, y], ['L', width - signX * trr + x, y], trr ? ['A', trr, trr, 0, 0, sweepFlag, width + x, signY * trr + y] : null, ['L', width + x, height - signY * brr + y], brr ? ['A', brr, brr, 0, 0, sweepFlag, width + x - signX * brr, height + y] : null, ['L', x + signX * blr, height + y], blr ? ['A', blr, blr, 0, 0, sweepFlag, x, height + y - signY * blr] : null, ['L', x, signY * tlr + y], tlr ? ['A', tlr, tlr, 0, 0, sweepFlag, signX * tlr + x, y] : null, ['Z']].filter(function (command) {
- return command;
- });
- }
- return [['M', x, y], ['L', x + width, y], ['L', x + width, y + height], ['L', x, y + height], ['Z']];
- }
- /**
- * convert object to path, should account for:
- * * transform & origin
- * * anchor
- * * lineWidth
- */
- function convertToPath(object, transform) {
- if (transform === void 0) {
- transform = object.getLocalTransform();
- }
- var commands = [];
- switch (object.nodeName) {
- case exports.Shape.LINE:
- var _object$parsedStyle2 = object.parsedStyle,
- x1 = _object$parsedStyle2.x1,
- y1 = _object$parsedStyle2.y1,
- x2 = _object$parsedStyle2.x2,
- y2 = _object$parsedStyle2.y2;
- commands = lineToCommands(x1, y1, x2, y2);
- break;
- case exports.Shape.CIRCLE:
- {
- var _object$parsedStyle3 = object.parsedStyle,
- r = _object$parsedStyle3.r,
- cx = _object$parsedStyle3.cx,
- cy = _object$parsedStyle3.cy;
- commands = ellipseToCommands(r, r, cx, cy);
- break;
- }
- case exports.Shape.ELLIPSE:
- {
- var _object$parsedStyle4 = object.parsedStyle,
- rx = _object$parsedStyle4.rx,
- ry = _object$parsedStyle4.ry,
- _cx = _object$parsedStyle4.cx,
- _cy = _object$parsedStyle4.cy;
- commands = ellipseToCommands(rx, ry, _cx, _cy);
- break;
- }
- case exports.Shape.POLYLINE:
- case exports.Shape.POLYGON:
- var points = object.parsedStyle.points;
- commands = polygonToCommands(points.points, object.nodeName === exports.Shape.POLYGON);
- break;
- case exports.Shape.RECT:
- var _object$parsedStyle5 = object.parsedStyle,
- width = _object$parsedStyle5.width,
- height = _object$parsedStyle5.height,
- x = _object$parsedStyle5.x,
- y = _object$parsedStyle5.y,
- radius = _object$parsedStyle5.radius;
- var hasRadius = radius && radius.some(function (r) {
- return r !== 0;
- });
- commands = rectToCommands(width, height, x, y, hasRadius && radius.map(function (r) {
- return clamp(r, 0, Math.min(Math.abs(width) / 2, Math.abs(height) / 2));
- }));
- break;
- case exports.Shape.PATH:
- var absolutePath = object.parsedStyle.path.absolutePath;
- commands = [].concat(absolutePath);
- break;
- }
- if (commands.length) {
- return commandsToPathString(commands, object, transform);
- }
- }
- function translatePathToString(absolutePath, defX, defY, startOffsetX, startOffsetY, endOffsetX, endOffsetY) {
- if (startOffsetX === void 0) {
- startOffsetX = 0;
- }
- if (startOffsetY === void 0) {
- startOffsetY = 0;
- }
- if (endOffsetX === void 0) {
- endOffsetX = 0;
- }
- if (endOffsetY === void 0) {
- endOffsetY = 0;
- }
- var newValue = absolutePath.map(function (params, i) {
- var command = params[0];
- var nextSegment = absolutePath[i + 1];
- var useStartOffset = i === 0 && (startOffsetX !== 0 || startOffsetY !== 0);
- var useEndOffset = (i === absolutePath.length - 1 || nextSegment && (nextSegment[0] === 'M' || nextSegment[0] === 'Z')) && endOffsetX !== 0 && endOffsetY !== 0;
- switch (command) {
- case 'M':
- // Use start marker offset
- if (useStartOffset) {
- return "M " + (params[1] - defX + startOffsetX) + "," + (params[2] - defY + startOffsetY) + " L " + (params[1] - defX) + "," + (params[2] - defY);
- } else {
- return "M " + (params[1] - defX) + "," + (params[2] - defY);
- }
- case 'L':
- return "L " + (params[1] - defX + (useEndOffset ? endOffsetX : 0)) + "," + (params[2] - defY + (useEndOffset ? endOffsetY : 0));
- case 'Q':
- return "Q " + (params[1] - defX) + " " + (params[2] - defY) + "," + (params[3] - defX) + " " + (params[4] - defY) + (useEndOffset ? " L " + (params[3] - defX + endOffsetX) + "," + (params[4] - defY + endOffsetY) : '');
- case 'C':
- return "C " + (params[1] - defX) + " " + (params[2] - defY) + "," + (params[3] - defX) + " " + (params[4] - defY) + "," + (params[5] - defX) + " " + (params[6] - defY) + (useEndOffset ? " L " + (params[5] - defX + endOffsetX) + "," + (params[6] - defY + endOffsetY) : '');
- case 'A':
- return "A " + params[1] + " " + params[2] + " " + params[3] + " " + params[4] + " " + params[5] + " " + (params[6] - defX) + " " + (params[7] - defY) + (useEndOffset ? " L " + (params[6] - defX + endOffsetX) + "," + (params[7] - defY + endOffsetY) : '');
- case 'Z':
- return 'Z';
- }
- }).join(' ');
- if (~newValue.indexOf('NaN')) {
- return '';
- }
- return newValue;
- }
- function isFillOrStrokeAffected(pointerEvents, fill, stroke) {
- // account for pointerEvents
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
- var hasFill = false;
- var hasStroke = false;
- var isFillOtherThanNone = !!fill && !fill.isNone;
- var isStrokeOtherThanNone = !!stroke && !stroke.isNone;
- if (pointerEvents === 'visiblepainted' || pointerEvents === 'painted' || pointerEvents === 'auto') {
- hasFill = isFillOtherThanNone;
- hasStroke = isStrokeOtherThanNone;
- } else if (pointerEvents === 'visiblefill' || pointerEvents === 'fill') {
- hasFill = true;
- } else if (pointerEvents === 'visiblestroke' || pointerEvents === 'stroke') {
- hasStroke = true;
- } else if (pointerEvents === 'visible' || pointerEvents === 'all') {
- // The values of the fill and stroke do not affect event processing.
- hasFill = true;
- hasStroke = true;
- }
- return [hasFill, hasStroke];
- }
- var AsyncParallelHook = /*#__PURE__*/function () {
- function AsyncParallelHook() {
- this.callbacks = [];
- }
- var _proto = AsyncParallelHook.prototype;
- _proto.getCallbacksNum = function getCallbacksNum() {
- return this.callbacks.length;
- };
- _proto.tapPromise = function tapPromise(options, fn) {
- this.callbacks.push(fn);
- };
- _proto.promise = function promise() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- return Promise.all(this.callbacks.map(function (callback) {
- return callback.apply(void 0, args);
- }));
- };
- return AsyncParallelHook;
- }();
- var AsyncSeriesWaterfallHook = /*#__PURE__*/function () {
- function AsyncSeriesWaterfallHook() {
- this.callbacks = [];
- }
- var _proto = AsyncSeriesWaterfallHook.prototype;
- _proto.tapPromise = function tapPromise(options, fn) {
- this.callbacks.push(fn);
- };
- _proto.promise = /*#__PURE__*/function () {
- var _promise = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
- var _this$callbacks,
- result,
- i,
- callback,
- _args = arguments;
- return _regeneratorRuntime().wrap(function _callee$(_context) {
- while (1) switch (_context.prev = _context.next) {
- case 0:
- if (!this.callbacks.length) {
- _context.next = 14;
- break;
- }
- _context.next = 3;
- return (_this$callbacks = this.callbacks)[0].apply(_this$callbacks, _args);
- case 3:
- result = _context.sent;
- i = 0;
- case 5:
- if (!(i < this.callbacks.length - 1)) {
- _context.next = 13;
- break;
- }
- callback = this.callbacks[i]; // @ts-ignore
- _context.next = 9;
- return callback(result);
- case 9:
- result = _context.sent;
- case 10:
- i++;
- _context.next = 5;
- break;
- case 13:
- return _context.abrupt("return", result);
- case 14:
- return _context.abrupt("return", null);
- case 15:
- case "end":
- return _context.stop();
- }
- }, _callee, this);
- }));
- function promise() {
- return _promise.apply(this, arguments);
- }
- return promise;
- }();
- return AsyncSeriesWaterfallHook;
- }();
- var SyncHook = /*#__PURE__*/function () {
- function SyncHook() {
- this.callbacks = [];
- }
- var _proto = SyncHook.prototype;
- _proto.tap = function tap(options, fn) {
- this.callbacks.push(fn);
- };
- _proto.call = function call() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- this.callbacks.forEach(function (callback) {
- callback.apply(void 0, args);
- });
- };
- return SyncHook;
- }();
- var SyncWaterfallHook = /*#__PURE__*/function () {
- function SyncWaterfallHook() {
- this.callbacks = [];
- }
- var _proto = SyncWaterfallHook.prototype;
- _proto.tap = function tap(options, fn) {
- this.callbacks.push(fn);
- };
- _proto.call = function call() {
- if (this.callbacks.length) {
- var _this$callbacks;
- var result = (_this$callbacks = this.callbacks)[0].apply(_this$callbacks, arguments);
- for (var i = 0; i < this.callbacks.length - 1; i++) {
- var callback = this.callbacks[i];
- // @ts-ignore
- result = callback(result);
- }
- return result;
- }
- return null;
- };
- return SyncWaterfallHook;
- }();
- var genericFontFamilies = ['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui'];
- var stringRegExp = /([\"\'])[^\'\"]+\1/;
- function toFontString(attributes) {
- var fontSize = attributes.fontSize,
- fontFamily = attributes.fontFamily,
- fontStyle = attributes.fontStyle,
- fontVariant = attributes.fontVariant,
- fontWeight = attributes.fontWeight;
- // build canvas api font setting from individual components. Convert a numeric this.fontSize to px
- // const fontSizeString: string = isNumber(fontSize) ? `${fontSize}px` : fontSize.toString();
- var fontSizeString = isNumber(fontSize) && fontSize + "px" || '16px';
- // Clean-up fontFamily property by quoting each font name
- // this will support font names with spaces
- var fontFamilies = fontFamily.split(',');
- for (var i = fontFamilies.length - 1; i >= 0; i--) {
- // Trim any extra white-space
- var _fontFamily = fontFamilies[i].trim();
- // Check if font already contains strings
- if (!stringRegExp.test(_fontFamily) && genericFontFamilies.indexOf(_fontFamily) < 0) {
- _fontFamily = "\"" + _fontFamily + "\"";
- }
- fontFamilies[i] = _fontFamily;
- }
- return fontStyle + " " + fontVariant + " " + fontWeight + " " + fontSizeString + " " + fontFamilies.join(',');
- }
- /**
- * Thanks for following contributor of codes
- * https://gist.github.com/1866474
- * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
- * http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
- * https://github.com/Financial-Times/polyfill-library/blob/master/polyfills/requestAnimationFrame/polyfill.js
- **/
- var uId = 1;
- var uniqueId = function uniqueId() {
- return uId++;
- };
- // We use `self` instead of `window` for `WebWorker` support.
- var root = typeof self === 'object' && self.self == self ? self :
- // @ts-ignore
- typeof global === 'object' && global.global == global ?
- // @ts-ignore
- global : {};
- var nowOffset = Date.now();
- // use performance api if exist, otherwise use Date.now.
- // Date.now polyfill required.
- var pnow = function pnow() {
- if (root.performance && typeof root.performance.now === 'function') {
- return root.performance.now();
- }
- // fallback
- return Date.now() - nowOffset;
- };
- var reservedCBs = {};
- var lastTime = Date.now();
- var polyfillRaf = function polyfillRaf(callback) {
- if (typeof callback !== 'function') {
- throw new TypeError(callback + ' is not a function');
- }
- var currentTime = Date.now();
- var gap = currentTime - lastTime;
- var delay = gap > 16 ? 0 : 16 - gap;
- var id = uniqueId();
- reservedCBs[id] = callback;
- // keys(reservedCBs).length > 1 의미는 이미 setTimeout 이 걸려있는 경우.
- // 함께 callback 이 실행될 수 있게 reservedCBs 에만 추가해주고 return
- if (Object.keys(reservedCBs).length > 1) return id;
- setTimeout(function () {
- lastTime = currentTime;
- var copied = reservedCBs;
- reservedCBs = {};
- Object.keys(copied).forEach(function (key) {
- return copied[key](pnow());
- });
- }, delay);
- return id;
- };
- var polyfillCaf = function polyfillCaf(id) {
- delete reservedCBs[id];
- };
- var vendorPrefixes = ['', 'webkit', 'moz', 'ms', 'o'];
- var getRequestAnimationFrame = function getRequestAnimationFrame(vp) {
- if (typeof vp !== 'string') return polyfillRaf;
- if (vp === '') return root['requestAnimationFrame'];
- return root[vp + 'RequestAnimationFrame'];
- };
- var getCancelAnimationFrame = function getCancelAnimationFrame(vp) {
- if (typeof vp !== 'string') return polyfillCaf;
- if (vp === '') return root['cancelAnimationFrame'];
- return root[vp + 'CancelAnimationFrame'] || root[vp + 'CancelRequestAnimationFrame'];
- };
- var find = function find(arr, predicate) {
- var i = 0;
- while (arr[i] !== void 0) {
- if (predicate(arr[i])) return arr[i];
- i = i + 1;
- }
- };
- var vp = find(vendorPrefixes, function (vp) {
- return !!getRequestAnimationFrame(vp);
- });
- var raf = getRequestAnimationFrame(vp);
- var caf = getCancelAnimationFrame(vp);
- root.requestAnimationFrame = raf;
- root.cancelAnimationFrame = caf;
- var regexLG = /^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i;
- var regexRG = /^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i;
- var regexPR = /^p\s*\(\s*([axyn])\s*\)\s*(.*)/i;
- var regexColorStop = /[\d.]+:(#[^\s]+|[^\)]+\))/gi;
- function spaceColorStops(colorStops) {
- var _colorStops$length;
- var length = colorStops.length;
- colorStops[length - 1].length = (_colorStops$length = colorStops[length - 1].length) !== null && _colorStops$length !== void 0 ? _colorStops$length : {
- type: '%',
- value: '100'
- };
- if (length > 1) {
- var _colorStops$0$length;
- colorStops[0].length = (_colorStops$0$length = colorStops[0].length) !== null && _colorStops$0$length !== void 0 ? _colorStops$0$length : {
- type: '%',
- value: '0'
- };
- }
- var previousIndex = 0;
- var previousOffset = Number(colorStops[0].length.value);
- for (var i = 1; i < length; i++) {
- var _colorStops$i$length;
- // support '%' & 'px'
- var offset = (_colorStops$i$length = colorStops[i].length) === null || _colorStops$i$length === void 0 ? void 0 : _colorStops$i$length.value;
- if (!isNil(offset) && !isNil(previousOffset)) {
- for (var j = 1; j < i - previousIndex; j++) colorStops[previousIndex + j].length = {
- type: '%',
- value: "" + (previousOffset + (Number(offset) - previousOffset) * j / (i - previousIndex))
- };
- previousIndex = i;
- previousOffset = Number(offset);
- }
- }
- }
- // The position of the gradient line's starting point.
- // different from CSS side(to top) @see https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#values
- var SideOrCornerToDegMap = {
- left: 270 - 90,
- top: 0 - 90,
- bottom: 180 - 90,
- right: 90 - 90,
- 'left top': 315 - 90,
- 'top left': 315 - 90,
- 'left bottom': 225 - 90,
- 'bottom left': 225 - 90,
- 'right top': 45 - 90,
- 'top right': 45 - 90,
- 'right bottom': 135 - 90,
- 'bottom right': 135 - 90
- };
- var angleToDeg = memoize(function (orientation) {
- var angle;
- if (orientation.type === 'angular') {
- angle = Number(orientation.value);
- } else {
- angle = SideOrCornerToDegMap[orientation.value] || 0;
- }
- return getOrCreateUnitValue(angle, 'deg');
- });
- var positonToCSSUnitValue = memoize(function (position) {
- var cx = 50;
- var cy = 50;
- var unitX = '%';
- var unitY = '%';
- if ((position === null || position === void 0 ? void 0 : position.type) === 'position') {
- var _position$value = position.value,
- x = _position$value.x,
- y = _position$value.y;
- if ((x === null || x === void 0 ? void 0 : x.type) === 'position-keyword') {
- if (x.value === 'left') {
- cx = 0;
- } else if (x.value === 'center') {
- cx = 50;
- } else if (x.value === 'right') {
- cx = 100;
- } else if (x.value === 'top') {
- cy = 0;
- } else if (x.value === 'bottom') {
- cy = 100;
- }
- }
- if ((y === null || y === void 0 ? void 0 : y.type) === 'position-keyword') {
- if (y.value === 'left') {
- cx = 0;
- } else if (y.value === 'center') {
- cy = 50;
- } else if (y.value === 'right') {
- cx = 100;
- } else if (y.value === 'top') {
- cy = 0;
- } else if (y.value === 'bottom') {
- cy = 100;
- }
- }
- if ((x === null || x === void 0 ? void 0 : x.type) === 'px' || (x === null || x === void 0 ? void 0 : x.type) === '%' || (x === null || x === void 0 ? void 0 : x.type) === 'em') {
- unitX = x === null || x === void 0 ? void 0 : x.type;
- cx = Number(x.value);
- }
- if ((y === null || y === void 0 ? void 0 : y.type) === 'px' || (y === null || y === void 0 ? void 0 : y.type) === '%' || (y === null || y === void 0 ? void 0 : y.type) === 'em') {
- unitY = y === null || y === void 0 ? void 0 : y.type;
- cy = Number(y.value);
- }
- }
- return {
- cx: getOrCreateUnitValue(cx, unitX),
- cy: getOrCreateUnitValue(cy, unitY)
- };
- });
- var parseGradient$1 = memoize(function (colorStr) {
- if (colorStr.indexOf('linear') > -1 || colorStr.indexOf('radial') > -1) {
- var ast = parseGradient(colorStr);
- return ast.map(function (_ref) {
- var type = _ref.type,
- orientation = _ref.orientation,
- colorStops = _ref.colorStops;
- spaceColorStops(colorStops);
- var steps = colorStops.map(function (colorStop) {
- // TODO: only support % for now, should calc percentage of axis length when using px/em
- return {
- offset: getOrCreateUnitValue(Number(colorStop.length.value), '%'),
- color: colorStopToString(colorStop)
- };
- });
- if (type === 'linear-gradient') {
- return new CSSGradientValue(exports.GradientType.LinearGradient, {
- angle: orientation ? angleToDeg(orientation) : Odeg,
- steps: steps
- });
- } else if (type === 'radial-gradient') {
- if (!orientation) {
- orientation = [{
- type: 'shape',
- value: 'circle'
- }];
- }
- if (orientation[0].type === 'shape' && orientation[0].value === 'circle') {
- var _positonToCSSUnitValu = positonToCSSUnitValue(orientation[0].at),
- cx = _positonToCSSUnitValu.cx,
- cy = _positonToCSSUnitValu.cy;
- var size;
- if (orientation[0].style) {
- var _orientation$0$style = orientation[0].style,
- _type = _orientation$0$style.type,
- value = _orientation$0$style.value;
- if (_type === 'extent-keyword') {
- size = getOrCreateKeyword(value);
- } else {
- size = getOrCreateUnitValue(value, _type);
- }
- }
- return new CSSGradientValue(exports.GradientType.RadialGradient, {
- cx: cx,
- cy: cy,
- size: size,
- steps: steps
- });
- }
- // TODO: support ellipse shape
- // TODO: repeating-linear-gradient & repeating-radial-gradient
- // } else if (type === 'repeating-linear-gradient') {
- // } else if (type === 'repeating-radial-gradient') {
- }
- });
- }
- // legacy format, should be deprecated later
- var type = colorStr[0];
- if (colorStr[1] === '(' || colorStr[2] === '(') {
- if (type === 'l') {
- var arr = regexLG.exec(colorStr);
- if (arr) {
- var _arr$2$match;
- var steps = ((_arr$2$match = arr[2].match(regexColorStop)) === null || _arr$2$match === void 0 ? void 0 : _arr$2$match.map(function (stop) {
- return stop.split(':');
- })) || [];
- return [new CSSGradientValue(exports.GradientType.LinearGradient, {
- angle: getOrCreateUnitValue(parseFloat(arr[1]), 'deg'),
- steps: steps.map(function (_ref2) {
- var offset = _ref2[0],
- color = _ref2[1];
- return {
- offset: getOrCreateUnitValue(Number(offset) * 100, '%'),
- color: color
- };
- })
- })];
- }
- } else if (type === 'r') {
- var parsedRadialGradient = parseRadialGradient(colorStr);
- if (parsedRadialGradient) {
- if (isString(parsedRadialGradient)) {
- colorStr = parsedRadialGradient;
- } else {
- return [new CSSGradientValue(exports.GradientType.RadialGradient, parsedRadialGradient)];
- }
- }
- } else if (type === 'p') {
- return parsePattern(colorStr);
- }
- }
- });
- function parseRadialGradient(gradientStr) {
- var arr = regexRG.exec(gradientStr);
- if (arr) {
- var _arr$4$match;
- var steps = ((_arr$4$match = arr[4].match(regexColorStop)) === null || _arr$4$match === void 0 ? void 0 : _arr$4$match.map(function (stop) {
- return stop.split(':');
- })) || [];
- return {
- cx: getOrCreateUnitValue(50, '%'),
- cy: getOrCreateUnitValue(50, '%'),
- steps: steps.map(function (_ref3) {
- var offset = _ref3[0],
- color = _ref3[1];
- return {
- offset: getOrCreateUnitValue(Number(offset) * 100, '%'),
- color: color
- };
- })
- };
- }
- return null;
- }
- function parsePattern(patternStr) {
- var arr = regexPR.exec(patternStr);
- if (arr) {
- var repetition = arr[1];
- var src = arr[2];
- switch (repetition) {
- case 'a':
- repetition = 'repeat';
- break;
- case 'x':
- repetition = 'repeat-x';
- break;
- case 'y':
- repetition = 'repeat-y';
- break;
- case 'n':
- repetition = 'no-repeat';
- break;
- default:
- repetition = 'no-repeat';
- }
- return {
- image: src,
- // @ts-ignore
- repetition: repetition
- };
- }
- return null;
- }
- function isCSSGradientValue(object) {
- return !!object.type && !!object.value;
- }
- function isPattern(object) {
- return object && !!object.image;
- }
- function isCSSRGB(object) {
- return object && !isNil(object.r) && !isNil(object.g) && !isNil(object.b);
- }
- /**
- * @see https://github.com/WebKit/WebKit/blob/main/Source/WebCore/css/parser/CSSParser.cpp#L97
- */
- var parseColor = memoize(function (colorStr) {
- if (isPattern(colorStr)) {
- return _extends({
- repetition: 'repeat'
- }, colorStr);
- }
- if (isNil(colorStr)) {
- colorStr = '';
- }
- if (colorStr === 'transparent') {
- // transparent black
- return transparentColor;
- } else if (colorStr === 'currentColor') {
- // @see https://github.com/adobe-webplatform/Snap.svg/issues/526
- colorStr = 'black';
- }
- // support CSS gradient syntax
- var g = parseGradient$1(colorStr);
- if (g) {
- return g;
- }
- // constants
- var color$1 = color(colorStr);
- var rgba = [0, 0, 0, 0];
- if (color$1 !== null) {
- rgba[0] = color$1.r || 0;
- rgba[1] = color$1.g || 0;
- rgba[2] = color$1.b || 0;
- rgba[3] = color$1.opacity;
- }
- // return new CSSRGB(...rgba);
- return getOrCreateRGBA.apply(void 0, rgba);
- });
- function mergeColors(left, right) {
- // only support constant value, exclude gradient & pattern
- if (!isCSSRGB(left) || !isCSSRGB(right)) {
- return;
- }
- return [[Number(left.r), Number(left.g), Number(left.b), Number(left.alpha)], [Number(right.r), Number(right.g), Number(right.b), Number(right.alpha)], function (color) {
- var rgba = color.slice();
- if (rgba[3]) {
- for (var i = 0; i < 3; i++) rgba[i] = Math.round(clamp(rgba[i], 0, 255));
- }
- rgba[3] = clamp(rgba[3], 0, 1);
- return "rgba(" + rgba.join(',') + ")";
- }];
- }
- function parseDimension(unitRegExp, string) {
- if (isNil(string)) {
- return getOrCreateUnitValue(0, 'px');
- }
- string = ("" + string).trim().toLowerCase();
- if (isFinite(Number(string))) {
- if ('px'.search(unitRegExp) >= 0) {
- return getOrCreateUnitValue(Number(string), 'px');
- } else if ('deg'.search(unitRegExp) >= 0) {
- return getOrCreateUnitValue(Number(string), 'deg');
- }
- }
- var matchedUnits = [];
- string = string.replace(unitRegExp, function (match) {
- matchedUnits.push(match);
- return 'U' + match;
- });
- var taggedUnitRegExp = 'U(' + unitRegExp.source + ')';
- return matchedUnits.map(function (unit) {
- return getOrCreateUnitValue(Number(string.replace(new RegExp('U' + unit, 'g'), '').replace(new RegExp(taggedUnitRegExp, 'g'), '*0')), unit);
- })[0];
- }
- /**
- * <length>
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length
- * length with only absolute unit, eg. 1px
- */
- var parseLength = memoize(function (css) {
- return parseDimension(new RegExp('px', 'g'), css);
- });
- /**
- * <percentage>
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/percentage
- */
- var parserPercentage = memoize(function (css) {
- return parseDimension(new RegExp('%', 'g'), css);
- });
- /**
- * length with absolute or relative unit,
- * eg. 1px, 0.7em, 50%, calc(100% - 200px);
- *
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length-percentage
- */
- // export const parseLengthOrPercentage = memoize((css: string): CSSUnitValue => {
- // if (isNumber(css) || isFinite(Number(css))) {
- // return getOrCreateUnitValue(Number(css), 'px');
- // }
- // return parseDimension(new RegExp('px|%|em|rem', 'g'), css) as CSSUnitValue;
- // });
- var parseLengthOrPercentage = function parseLengthOrPercentage(css) {
- if (isNumber(css) || isFinite(Number(css))) {
- // Number(css) is NaN
- return getOrCreateUnitValue(Number(css) || 0, 'px');
- // return Number(css);
- }
- return parseDimension(new RegExp('px|%|em|rem', 'g'), css);
- };
- var parseAngle = memoize(function (css) {
- return parseDimension(new RegExp('deg|rad|grad|turn', 'g'), css);
- });
- /**
- * merge CSSUnitValue
- *
- * @example
- * 10px + 20px = 30px
- * 10deg + 10rad
- * 10% + 20% = 30%
- */
- function mergeDimensions(left, right, target, nonNegative, index) {
- if (index === void 0) {
- index = 0;
- }
- var unit = '';
- var leftValue = left.value || 0;
- var rightValue = right.value || 0;
- var canonicalUnit = toCanonicalUnit(left.unit);
- var leftCanonicalUnitValue = left.convertTo(canonicalUnit);
- var rightCanonicalUnitValue = right.convertTo(canonicalUnit);
- if (leftCanonicalUnitValue && rightCanonicalUnitValue) {
- leftValue = leftCanonicalUnitValue.value;
- rightValue = rightCanonicalUnitValue.value;
- unit = unitTypeToString(left.unit);
- } else {
- // format '%' to 'px'
- if (CSSUnitValue.isLength(left.unit) || CSSUnitValue.isLength(right.unit)) {
- leftValue = convertPercentUnit(left, index, target);
- rightValue = convertPercentUnit(right, index, target);
- unit = 'px';
- }
- }
- // // format 'rad' 'turn' to 'deg'
- // if (CSSUnitValue.isAngle(left.unit) || CSSUnitValue.isAngle(right.unit)) {
- // leftValue = convertAngleUnit(left);
- // rightValue = convertAngleUnit(right);
- // unit = 'deg';
- // }
- return [leftValue, rightValue, function (value) {
- if (nonNegative) {
- value = Math.max(value, 0);
- }
- return value + unit;
- }];
- }
- function convertAngleUnit(value) {
- var deg = 0;
- if (value.unit === exports.UnitType.kDegrees) {
- deg = value.value;
- } else if (value.unit === exports.UnitType.kRadians) {
- deg = rad2deg(Number(value.value));
- } else if (value.unit === exports.UnitType.kTurns) {
- deg = turn2deg(Number(value.value));
- }
- return deg;
- }
- function parseDimensionArrayFormat(string, size) {
- var parsed;
- if (Array.isArray(string)) {
- // [1, '2px', 3]
- parsed = string.map(function (segment) {
- return Number(segment);
- });
- } else if (isString(string)) {
- parsed = string.split(' ').map(function (segment) {
- return Number(segment);
- });
- } else if (isNumber(string)) {
- parsed = [string];
- }
- if (size === 2) {
- if (parsed.length === 1) {
- return [parsed[0], parsed[0]];
- } else {
- return [parsed[0], parsed[1]];
- }
- } else {
- if (parsed.length === 1) {
- return [parsed[0], parsed[0], parsed[0], parsed[0]];
- } else if (parsed.length === 2) {
- return [parsed[0], parsed[1], parsed[0], parsed[1]];
- } else if (parsed.length === 3) {
- return [parsed[0], parsed[1], parsed[2], parsed[1]];
- } else {
- return [parsed[0], parsed[1], parsed[2], parsed[3]];
- }
- }
- }
- function parseDimensionArray(string) {
- if (isString(string)) {
- // "1px 2px 3px"
- return string.split(' ').map(function (segment) {
- return parseLengthOrPercentage(segment);
- });
- } else {
- // [1, '2px', 3]
- return string.map(function (segment) {
- return parseLengthOrPercentage(segment.toString());
- });
- }
- }
- // export function mergeDimensionList(
- // left: CSSUnitValue[],
- // right: CSSUnitValue[],
- // target: IElement | null,
- // ): [number[], number[], (list: number[]) => string] | undefined {
- // if (left.length !== right.length) {
- // return;
- // }
- // const unit = left[0].unit;
- // return [
- // left.map((l) => l.value),
- // right.map((l) => l.value),
- // (values: number[]) => {
- // return values.map((n) => new CSSUnitValue(n, unit)).join(' ');
- // },
- // ];
- // }
- function convertPercentUnit(valueWithUnit, vec3Index, target) {
- if (valueWithUnit.value === 0) {
- return 0;
- }
- if (valueWithUnit.unit === exports.UnitType.kPixels) {
- return Number(valueWithUnit.value);
- } else if (valueWithUnit.unit === exports.UnitType.kPercentage && target) {
- var bounds = target.nodeName === exports.Shape.GROUP ? target.getLocalBounds() :
- // : target.getGeometryBounds();
- target.geometry.contentBounds;
- return valueWithUnit.value / 100 * bounds.halfExtents[vec3Index] * 2;
- }
- return 0;
- }
- var parseParam = function parseParam(css) {
- return parseDimension(/deg|rad|grad|turn|px|%/g, css);
- };
- var supportedFilters = ['blur', 'brightness', 'drop-shadow', 'contrast', 'grayscale', 'sepia', 'saturate', 'hue-rotate', 'invert'];
- function parseFilter(filterStr) {
- if (filterStr === void 0) {
- filterStr = '';
- }
- filterStr = filterStr.toLowerCase().trim();
- if (filterStr === 'none') {
- return [];
- }
- var filterRegExp = /\s*([\w-]+)\(([^)]*)\)/g;
- var result = [];
- var match;
- var prevLastIndex = 0;
- while (match = filterRegExp.exec(filterStr)) {
- if (match.index !== prevLastIndex) {
- return [];
- }
- prevLastIndex = match.index + match[0].length;
- if (supportedFilters.indexOf(match[1]) > -1) {
- result.push({
- name: match[1],
- params: match[2].split(' ').map(function (p) {
- return parseParam(p) || parseColor(p);
- })
- });
- }
- if (filterRegExp.lastIndex === filterStr.length) {
- return result;
- }
- }
- return [];
- }
- function numberToString(x) {
- // scale(0.00000001) -> scale(0)
- // return x.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
- return x.toString();
- }
- /**
- * parse string or number to CSSUnitValue(numeric)
- *
- * eg.
- * * 0 -> CSSUnitValue(0)
- * * '2' -> CSSUnitValue(2)
- */
- var parseNumber = memoize(function (string) {
- if (typeof string === 'number') {
- return getOrCreateUnitValue(string);
- }
- if (/^\s*[-+]?(\d*\.)?\d+\s*$/.test(string)) {
- return getOrCreateUnitValue(Number(string));
- } else {
- return getOrCreateUnitValue(0);
- }
- });
- /**
- * separate string to array
- * eg.
- * * [0.5, 0.5] -> [CSSUnitValue, CSSUnitValue]
- */
- var parseNumberList = memoize(function (string) {
- if (isString(string)) {
- return string.split(' ').map(parseNumber);
- } else {
- return string.map(parseNumber);
- }
- });
- function mergeNumbers(left, right) {
- return [left, right, numberToString];
- }
- function clampedMergeNumbers(min, max) {
- return function (left, right) {
- return [left, right, function (x) {
- return numberToString(clamp(x, min, max));
- }];
- };
- }
- function mergeNumberLists(left, right) {
- if (left.length !== right.length) {
- return;
- }
- return [left, right, function (numberList) {
- return numberList;
- }];
- }
- var internalParsePath = function internalParsePath(path) {
- // empty path
- if (path === '' || Array.isArray(path) && path.length === 0) {
- return {
- absolutePath: [],
- hasArc: false,
- segments: [],
- polygons: [],
- polylines: [],
- curve: null,
- totalLength: 0,
- rect: {
- x: 0,
- y: 0,
- width: 0,
- height: 0
- }
- };
- }
- var absolutePath;
- try {
- absolutePath = normalizePath(path);
- } catch (e) {
- absolutePath = normalizePath('');
- console.error("[g]: Invalid SVG Path definition: " + path);
- }
- var hasArc = hasArcOrBezier(absolutePath);
- var _extractPolygons = extractPolygons(absolutePath),
- polygons = _extractPolygons.polygons,
- polylines = _extractPolygons.polylines;
- // for later use
- var segments = path2Segments(absolutePath);
- // Only calculate bbox here since we don't need length now.
- var _getPathBBox = getPathBBox(segments, 0),
- x = _getPathBBox.x,
- y = _getPathBBox.y,
- width = _getPathBBox.width,
- height = _getPathBBox.height;
- return {
- absolutePath: absolutePath,
- hasArc: hasArc,
- segments: segments,
- polygons: polygons,
- polylines: polylines,
- // curve,
- // Delay the calculation of length.
- totalLength: 0,
- rect: {
- x: Number.isFinite(x) ? x : 0,
- y: Number.isFinite(y) ? y : 0,
- width: Number.isFinite(width) ? width : 0,
- height: Number.isFinite(height) ? height : 0
- }
- };
- };
- var memoizedParsePath = memoize(internalParsePath);
- function parsePath(path, object) {
- var result = isString(path) ? memoizedParsePath(path) : internalParsePath(path);
- if (object) {
- object.parsedStyle.defX = result.rect.x;
- object.parsedStyle.defY = result.rect.y;
- }
- return result;
- }
- function mergePaths(left, right, object) {
- var curve1 = left.curve;
- var curve2 = right.curve;
- if (!curve1 || curve1.length === 0) {
- // convert to curves to do morphing & picking later
- // @see http://thednp.github.io/kute.js/svgCubicMorph.html
- curve1 = path2Curve(left.absolutePath, false);
- left.curve = curve1;
- }
- if (!curve2 || curve2.length === 0) {
- curve2 = path2Curve(right.absolutePath, false);
- right.curve = curve2;
- }
- var curves = [curve1, curve2];
- if (curve1.length !== curve2.length) {
- curves = equalizeSegments(curve1, curve2);
- }
- var curve0 = getDrawDirection(curves[0]) !== getDrawDirection(curves[1]) ? reverseCurve(curves[0]) : clonePath(curves[0]);
- return [curve0, getRotatedCurve(curves[1], curve0), function (pathArray) {
- // need converting to path string?
- return pathArray;
- }];
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Attribute/points
- *
- * @example
- * points="100,10 250,150 200,110"
- */
- function parsePoints(pointsOrStr, object) {
- var points;
- if (isString(pointsOrStr)) {
- points = pointsOrStr.split(' ').map(function (pointStr) {
- var _pointStr$split = pointStr.split(','),
- x = _pointStr$split[0],
- y = _pointStr$split[1];
- return [Number(x), Number(y)];
- });
- } else {
- points = pointsOrStr;
- }
- var segments = [];
- var tempLength = 0;
- var segmentT;
- var segmentL;
- var totalLength = polyline.length(points);
- points.forEach(function (p, i) {
- if (points[i + 1]) {
- segmentT = [0, 0];
- segmentT[0] = tempLength / totalLength;
- segmentL = line.length(p[0], p[1], points[i + 1][0], points[i + 1][1]);
- tempLength += segmentL;
- segmentT[1] = tempLength / totalLength;
- segments.push(segmentT);
- }
- });
- var minX = Math.min.apply(Math, points.map(function (point) {
- return point[0];
- }));
- var minY = Math.min.apply(Math, points.map(function (point) {
- return point[1];
- }));
- if (object) {
- object.parsedStyle.defX = minX;
- object.parsedStyle.defY = minY;
- }
- return {
- points: points,
- totalLength: totalLength,
- segments: segments
- };
- }
- function mergePoints(left, right) {
- return [left.points, right.points, function (points) {
- return points;
- }];
- }
- var _ = null;
- function cast(pattern) {
- return function (contents) {
- var i = 0;
- return pattern.map(function (x) {
- return x === _ ? contents[i++] : x;
- });
- };
- }
- function id(x) {
- return x;
- }
- // type: [argTypes, convertTo3D, convertTo2D]
- // In the argument types string, lowercase characters represent optional arguments
- var transformFunctions = {
- // @ts-ignore
- matrix: ['NNNNNN', [_, _, 0, 0, _, _, 0, 0, 0, 0, 1, 0, _, _, 0, 1], id],
- matrix3d: ['NNNNNNNNNNNNNNNN', id],
- rotate: ['A'],
- rotatex: ['A'],
- rotatey: ['A'],
- rotatez: ['A'],
- rotate3d: ['NNNA'],
- perspective: ['L'],
- scale: ['Nn', cast([_, _, new CSSUnitValue(1)]), id],
- scalex: ['N', cast([_, new CSSUnitValue(1), new CSSUnitValue(1)]), cast([_, new CSSUnitValue(1)])],
- scaley: ['N', cast([new CSSUnitValue(1), _, new CSSUnitValue(1)]), cast([new CSSUnitValue(1), _])],
- scalez: ['N', cast([new CSSUnitValue(1), new CSSUnitValue(1), _])],
- scale3d: ['NNN', id],
- skew: ['Aa', null, id],
- skewx: ['A', null, cast([_, Odeg])],
- skewy: ['A', null, cast([Odeg, _])],
- translate: ['Tt', cast([_, _, Opx]), id],
- translatex: ['T', cast([_, Opx, Opx]), cast([_, Opx])],
- translatey: ['T', cast([Opx, _, Opx]), cast([Opx, _])],
- translatez: ['L', cast([Opx, Opx, _])],
- translate3d: ['TTL', id]
- };
- /**
- * none
- * scale(1) scale(1, 2)
- * scaleX(1)
- */
- function parseTransform(string) {
- string = (string || 'none').toLowerCase().trim();
- if (string === 'none') {
- return [];
- }
- var transformRegExp = /\s*(\w+)\(([^)]*)\)/g;
- var result = [];
- var match;
- var prevLastIndex = 0;
- while (match = transformRegExp.exec(string)) {
- if (match.index !== prevLastIndex) {
- return [];
- }
- prevLastIndex = match.index + match[0].length;
- var functionName = match[1]; // scale
- var functionData = transformFunctions[functionName]; // scale(1, 2)
- if (!functionData) {
- // invalid, eg. scale()
- return [];
- }
- var args = match[2].split(','); // 1,2
- var argTypes = functionData[0]; // Nn
- if (argTypes.length < args.length) {
- // scale(N, n)
- return [];
- }
- var parsedArgs = [];
- for (var i = 0; i < argTypes.length; i++) {
- var arg = args[i];
- var type = argTypes[i];
- var parsedArg = void 0;
- if (!arg) {
- // @ts-ignore
- parsedArg = {
- a: Odeg,
- n: parsedArgs[0],
- t: Opx
- }[type];
- } else {
- // @ts-ignore
- parsedArg = {
- A: function A(s) {
- return s.trim() === '0' ? Odeg : parseAngle(s);
- },
- N: parseNumber,
- T: parseLengthOrPercentage,
- L: parseLength
- }[type.toUpperCase()](arg);
- }
- if (parsedArg === undefined) {
- return [];
- }
- parsedArgs.push(parsedArg);
- }
- result.push({
- t: functionName,
- d: parsedArgs
- }); // { t: scale, d: [1, 2] }
- if (transformRegExp.lastIndex === string.length) {
- return result;
- }
- }
- return [];
- }
- function convertItemToMatrix(item) {
- var x;
- var y;
- var z;
- var angle;
- switch (item.t) {
- case 'rotatex':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- return [1, 0, 0, 0, 0, Math.cos(angle), Math.sin(angle), 0, 0, -Math.sin(angle), Math.cos(angle), 0, 0, 0, 0, 1];
- case 'rotatey':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- return [Math.cos(angle), 0, -Math.sin(angle), 0, 0, 1, 0, 0, Math.sin(angle), 0, Math.cos(angle), 0, 0, 0, 0, 1];
- case 'rotate':
- case 'rotatez':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- return [Math.cos(angle), Math.sin(angle), 0, 0, -Math.sin(angle), Math.cos(angle), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'rotate3d':
- x = item.d[0].value;
- y = item.d[1].value;
- z = item.d[2].value;
- angle = deg2rad(convertAngleUnit(item.d[3]));
- var sqrLength = x * x + y * y + z * z;
- if (sqrLength === 0) {
- x = 1;
- y = 0;
- z = 0;
- } else if (sqrLength !== 1) {
- var length = Math.sqrt(sqrLength);
- x /= length;
- y /= length;
- z /= length;
- }
- var s = Math.sin(angle / 2);
- var sc = s * Math.cos(angle / 2);
- var sq = s * s;
- return [1 - 2 * (y * y + z * z) * sq, 2 * (x * y * sq + z * sc), 2 * (x * z * sq - y * sc), 0, 2 * (x * y * sq - z * sc), 1 - 2 * (x * x + z * z) * sq, 2 * (y * z * sq + x * sc), 0, 2 * (x * z * sq + y * sc), 2 * (y * z * sq - x * sc), 1 - 2 * (x * x + y * y) * sq, 0, 0, 0, 0, 1];
- case 'scale':
- return [item.d[0].value, 0, 0, 0, 0, item.d[1].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'scalex':
- return [item.d[0].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'scaley':
- return [1, 0, 0, 0, 0, item.d[0].value, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'scalez':
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, item.d[0].value, 0, 0, 0, 0, 1];
- case 'scale3d':
- return [item.d[0].value, 0, 0, 0, 0, item.d[1].value, 0, 0, 0, 0, item.d[2].value, 0, 0, 0, 0, 1];
- case 'skew':
- var xAngle = deg2rad(convertAngleUnit(item.d[0]));
- var yAngle = deg2rad(convertAngleUnit(item.d[1]));
- return [1, Math.tan(yAngle), 0, 0, Math.tan(xAngle), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'skewx':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- return [1, 0, 0, 0, Math.tan(angle), 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'skewy':
- angle = deg2rad(convertAngleUnit(item.d[0]));
- return [1, Math.tan(angle), 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- case 'translate':
- // TODO: pass target
- x = convertPercentUnit(item.d[0], 0, null) || 0;
- y = convertPercentUnit(item.d[1], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, 0, 1];
- case 'translatex':
- x = convertPercentUnit(item.d[0], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, 0, 0, 1];
- case 'translatey':
- y = convertPercentUnit(item.d[0], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, y, 0, 1];
- case 'translatez':
- z = convertPercentUnit(item.d[0], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, z, 1];
- case 'translate3d':
- x = convertPercentUnit(item.d[0], 0, null) || 0;
- y = convertPercentUnit(item.d[1], 0, null) || 0;
- z = convertPercentUnit(item.d[2], 0, null) || 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
- case 'perspective':
- var t = convertPercentUnit(item.d[0], 0, null) || 0;
- var p = t ? -1 / t : 0;
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, p, 0, 0, 0, 1];
- case 'matrix':
- return [item.d[0].value, item.d[1].value, 0, 0, item.d[2].value, item.d[3].value, 0, 0, 0, 0, 1, 0, item.d[4].value, item.d[5].value, 0, 1];
- case 'matrix3d':
- return item.d.map(function (d) {
- return d.value;
- });
- }
- }
- function multiplyMatrices(a, b) {
- return [a[0] * b[0] + a[4] * b[1] + a[8] * b[2] + a[12] * b[3], a[1] * b[0] + a[5] * b[1] + a[9] * b[2] + a[13] * b[3], a[2] * b[0] + a[6] * b[1] + a[10] * b[2] + a[14] * b[3], a[3] * b[0] + a[7] * b[1] + a[11] * b[2] + a[15] * b[3], a[0] * b[4] + a[4] * b[5] + a[8] * b[6] + a[12] * b[7], a[1] * b[4] + a[5] * b[5] + a[9] * b[6] + a[13] * b[7], a[2] * b[4] + a[6] * b[5] + a[10] * b[6] + a[14] * b[7], a[3] * b[4] + a[7] * b[5] + a[11] * b[6] + a[15] * b[7], a[0] * b[8] + a[4] * b[9] + a[8] * b[10] + a[12] * b[11], a[1] * b[8] + a[5] * b[9] + a[9] * b[10] + a[13] * b[11], a[2] * b[8] + a[6] * b[9] + a[10] * b[10] + a[14] * b[11], a[3] * b[8] + a[7] * b[9] + a[11] * b[10] + a[15] * b[11], a[0] * b[12] + a[4] * b[13] + a[8] * b[14] + a[12] * b[15], a[1] * b[12] + a[5] * b[13] + a[9] * b[14] + a[13] * b[15], a[2] * b[12] + a[6] * b[13] + a[10] * b[14] + a[14] * b[15], a[3] * b[12] + a[7] * b[13] + a[11] * b[14] + a[15] * b[15]];
- }
- function convertToMatrix(transformList) {
- if (transformList.length === 0) {
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
- }
- return transformList.map(convertItemToMatrix).reduce(multiplyMatrices);
- }
- function makeMatrixDecomposition(transformList) {
- var translate = [0, 0, 0];
- var scale = [1, 1, 1];
- var skew = [0, 0, 0];
- var perspective = [0, 0, 0, 1];
- var quaternion = [0, 0, 0, 1];
- // @ts-ignore
- decomposeMat4(convertToMatrix(transformList), translate, scale, skew, perspective, quaternion);
- return [[translate, scale, skew, quaternion, perspective]];
- }
- var composeMatrix = function () {
- function multiply(a, b) {
- var result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]];
- for (var i = 0; i < 4; i++) {
- for (var j = 0; j < 4; j++) {
- for (var k = 0; k < 4; k++) {
- result[i][j] += b[i][k] * a[k][j];
- }
- }
- }
- return result;
- }
- function is2D(m) {
- return m[0][2] == 0 && m[0][3] == 0 && m[1][2] == 0 && m[1][3] == 0 && m[2][0] == 0 && m[2][1] == 0 && m[2][2] == 1 && m[2][3] == 0 && m[3][2] == 0 && m[3][3] == 1;
- }
- function composeMatrix(translate, scale, skew, quat, perspective) {
- var matrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
- for (var i = 0; i < 4; i++) {
- matrix[i][3] = perspective[i];
- }
- for (var _i = 0; _i < 3; _i++) {
- for (var j = 0; j < 3; j++) {
- matrix[3][_i] += translate[j] * matrix[j][_i];
- }
- }
- var x = quat[0],
- y = quat[1],
- z = quat[2],
- w = quat[3];
- var rotMatrix = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
- rotMatrix[0][0] = 1 - 2 * (y * y + z * z);
- rotMatrix[0][1] = 2 * (x * y - z * w);
- rotMatrix[0][2] = 2 * (x * z + y * w);
- rotMatrix[1][0] = 2 * (x * y + z * w);
- rotMatrix[1][1] = 1 - 2 * (x * x + z * z);
- rotMatrix[1][2] = 2 * (y * z - x * w);
- rotMatrix[2][0] = 2 * (x * z - y * w);
- rotMatrix[2][1] = 2 * (y * z + x * w);
- rotMatrix[2][2] = 1 - 2 * (x * x + y * y);
- matrix = multiply(matrix, rotMatrix);
- var temp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
- if (skew[2]) {
- temp[2][1] = skew[2];
- matrix = multiply(matrix, temp);
- }
- if (skew[1]) {
- temp[2][1] = 0;
- temp[2][0] = skew[0];
- matrix = multiply(matrix, temp);
- }
- if (skew[0]) {
- temp[2][0] = 0;
- temp[1][0] = skew[0];
- matrix = multiply(matrix, temp);
- }
- for (var _i2 = 0; _i2 < 3; _i2++) {
- for (var _j = 0; _j < 3; _j++) {
- matrix[_i2][_j] *= scale[_i2];
- }
- }
- if (is2D(matrix)) {
- return [matrix[0][0], matrix[0][1], matrix[1][0], matrix[1][1], matrix[3][0], matrix[3][1]];
- }
- return matrix[0].concat(matrix[1], matrix[2], matrix[3]);
- }
- return composeMatrix;
- }();
- function numberToLongString(x) {
- return x.toFixed(6).replace('.000000', '');
- }
- function mergeMatrices(left, right) {
- var leftArgs;
- var rightArgs;
- // @ts-ignore
- if (left.decompositionPair !== right) {
- // @ts-ignore
- left.decompositionPair = right;
- // @ts-ignore
- leftArgs = makeMatrixDecomposition(left);
- }
- // @ts-ignore
- if (right.decompositionPair !== left) {
- // @ts-ignore
- right.decompositionPair = left;
- // @ts-ignore
- rightArgs = makeMatrixDecomposition(right);
- }
- if (leftArgs[0] === null || rightArgs[0] === null) return [
- // @ts-ignore
- [false],
- // @ts-ignore
- [true],
- // @ts-ignore
- function (x) {
- return x ? right[0].d : left[0].d;
- }];
- leftArgs[0].push(0);
- rightArgs[0].push(1);
- return [leftArgs, rightArgs,
- // @ts-ignore
- function (list) {
- // @ts-ignore
- var q = quat(leftArgs[0][3], rightArgs[0][3], list[5]);
- var mat = composeMatrix(list[0], list[1], list[2], q, list[4]);
- var stringifiedArgs = mat.map(numberToLongString).join(',');
- return stringifiedArgs;
- }];
- }
- function dot$2(v1, v2) {
- var result = 0;
- for (var i = 0; i < v1.length; i++) {
- result += v1[i] * v2[i];
- }
- return result;
- }
- function quat(fromQ, toQ, f) {
- var product = dot$2(fromQ, toQ);
- product = clamp(product, -1.0, 1.0);
- var quat = [];
- if (product === 1.0) {
- quat = fromQ;
- } else {
- var theta = Math.acos(product);
- var w = Math.sin(f * theta) * 1 / Math.sqrt(1 - product * product);
- for (var i = 0; i < 4; i++) {
- quat.push(fromQ[i] * (Math.cos(f * theta) - product * w) + toQ[i] * w);
- }
- }
- return quat;
- }
- // scalex/y/z -> scale
- function typeTo2D(type) {
- return type.replace(/[xy]/, '');
- }
- // scalex/y/z -> scale3d
- function typeTo3D(type) {
- return type.replace(/(x|y|z|3d)?$/, '3d');
- }
- var isMatrixOrPerspective = function isMatrixOrPerspective(lt, rt) {
- return lt === 'perspective' && rt === 'perspective' || (lt === 'matrix' || lt === 'matrix3d') && (rt === 'matrix' || rt === 'matrix3d');
- };
- function mergeTransforms(left, right, target) {
- var flipResults = false;
- // padding empty transform, eg. merge 'scale(10)' with 'none' -> scale(1)
- if (!left.length || !right.length) {
- if (!left.length) {
- flipResults = true;
- left = right;
- right = [];
- }
- var _loop = function _loop() {
- var _left$i = left[i],
- type = _left$i.t,
- args = _left$i.d;
- // none -> scale(1)/translateX(0)
- var defaultValue = type.substring(0, 5) === 'scale' ? 1 : 0;
- right.push({
- t: type,
- d: args.map(function (arg) {
- if (typeof arg === 'number') {
- return getOrCreateUnitValue(defaultValue);
- }
- return getOrCreateUnitValue(defaultValue, arg.unit);
- // {
- // unit: arg.unit,
- // value: defaultValue,
- // };
- })
- });
- };
- for (var i = 0; i < left.length; i++) {
- _loop();
- }
- }
- var leftResult = [];
- var rightResult = [];
- var types = [];
- // merge matrix() with matrix3d()
- if (left.length !== right.length) {
- var merged = mergeMatrices(left, right);
- // @ts-ignore
- leftResult = [merged[0]];
- // @ts-ignore
- rightResult = [merged[1]];
- types = [['matrix', [merged[2]]]];
- } else {
- for (var _i3 = 0; _i3 < left.length; _i3++) {
- var leftType = left[_i3].t;
- var rightType = right[_i3].t;
- var leftArgs = left[_i3].d;
- var rightArgs = right[_i3].d;
- var leftFunctionData = transformFunctions[leftType];
- var rightFunctionData = transformFunctions[rightType];
- var type = void 0;
- if (isMatrixOrPerspective(leftType, rightType)) {
- var _merged = mergeMatrices([left[_i3]], [right[_i3]]);
- // @ts-ignore
- leftResult.push(_merged[0]);
- // @ts-ignore
- rightResult.push(_merged[1]);
- types.push(['matrix', [_merged[2]]]);
- continue;
- } else if (leftType === rightType) {
- type = leftType;
- } else if (leftFunctionData[2] && rightFunctionData[2] && typeTo2D(leftType) === typeTo2D(rightType)) {
- type = typeTo2D(leftType);
- // @ts-ignore
- leftArgs = leftFunctionData[2](leftArgs);
- // @ts-ignore
- rightArgs = rightFunctionData[2](rightArgs);
- } else if (leftFunctionData[1] && rightFunctionData[1] && typeTo3D(leftType) === typeTo3D(rightType)) {
- type = typeTo3D(leftType);
- // @ts-ignore
- leftArgs = leftFunctionData[1](leftArgs);
- // @ts-ignore
- rightArgs = rightFunctionData[1](rightArgs);
- } else {
- var _merged2 = mergeMatrices(left, right);
- // @ts-ignore
- leftResult = [_merged2[0]];
- // @ts-ignore
- rightResult = [_merged2[1]];
- types = [['matrix', [_merged2[2]]]];
- break;
- }
- var leftArgsCopy = [];
- var rightArgsCopy = [];
- var stringConversions = [];
- for (var j = 0; j < leftArgs.length; j++) {
- // const merge = leftArgs[j].unit === UnitType.kNumber ? mergeDimensions : mergeDimensions;
- var _merged3 = mergeDimensions(leftArgs[j], rightArgs[j], target, false, j);
- leftArgsCopy[j] = _merged3[0];
- rightArgsCopy[j] = _merged3[1];
- stringConversions.push(_merged3[2]);
- }
- leftResult.push(leftArgsCopy);
- rightResult.push(rightArgsCopy);
- types.push([type, stringConversions]);
- }
- }
- if (flipResults) {
- var tmp = leftResult;
- leftResult = rightResult;
- rightResult = tmp;
- }
- return [leftResult, rightResult, function (list) {
- return list.map(function (args, i) {
- var stringifiedArgs = args.map(function (arg, j) {
- return types[i][1][j](arg);
- }).join(',');
- if (types[i][0] === 'matrix' && stringifiedArgs.split(',').length === 16) {
- types[i][0] = 'matrix3d';
- }
- if (types[i][0] === 'matrix3d' && stringifiedArgs.split(',').length === 6) {
- types[i][0] = 'matrix';
- }
- return types[i][0] + '(' + stringifiedArgs + ')';
- }).join(' ');
- }];
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
- * eg. 'center' 'top left' '50px 50px'
- */
- var parseTransformOrigin = memoize(function (value) {
- if (isString(value)) {
- if (value === 'text-anchor') {
- return [getOrCreateUnitValue(0, 'px'), getOrCreateUnitValue(0, 'px')];
- }
- var values = value.split(' ');
- if (values.length === 1) {
- if (values[0] === 'top' || values[0] === 'bottom') {
- // 'top' -> 'center top'
- values[1] = values[0];
- values[0] = 'center';
- } else {
- // '50px' -> '50px center'
- values[1] = 'center';
- }
- }
- if (values.length !== 2) {
- return null;
- }
- // eg. center bottom
- return [parseLengthOrPercentage(convertKeyword2Percent(values[0])), parseLengthOrPercentage(convertKeyword2Percent(values[1]))];
- } else {
- return [getOrCreateUnitValue(value[0] || 0, 'px'), getOrCreateUnitValue(value[1] || 0, 'px')];
- }
- });
- function convertKeyword2Percent(keyword) {
- if (keyword === 'center') {
- return '50%';
- } else if (keyword === 'left' || keyword === 'top') {
- return '0';
- } else if (keyword === 'right' || keyword === 'bottom') {
- return '100%';
- }
- return keyword;
- }
- var CSSPropertyAngle = /*#__PURE__*/function () {
- function CSSPropertyAngle() {
- this.parser = parseAngle;
- this.parserWithCSSDisabled = null;
- this.mixer = mergeNumbers;
- }
- var _proto = CSSPropertyAngle.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- return convertAngleUnit(parsed);
- };
- return CSSPropertyAngle;
- }();
- /**
- * clipPath / textPath / offsetPath
- */
- var CSSPropertyClipPath = /*#__PURE__*/function () {
- function CSSPropertyClipPath() {}
- var _proto = CSSPropertyClipPath.prototype;
- _proto.calculator = function calculator(name, oldPath, newPath, object) {
- // unset
- if (newPath instanceof CSSKeywordValue) {
- newPath = null;
- }
- runtime.sceneGraphService.updateDisplayObjectDependency(name, oldPath, newPath, object);
- if (name === 'clipPath') {
- // should affect children
- object.forEach(function (leaf) {
- if (leaf.childNodes.length === 0) {
- runtime.sceneGraphService.dirtifyToRoot(leaf);
- }
- });
- }
- return newPath;
- };
- return CSSPropertyClipPath;
- }();
- var CSSPropertyColor = /*#__PURE__*/function () {
- function CSSPropertyColor() {
- this.parser = parseColor;
- this.parserWithCSSDisabled = parseColor;
- this.mixer = mergeColors;
- }
- var _proto = CSSPropertyColor.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- if (parsed instanceof CSSKeywordValue) {
- // 'unset' 'none'
- return parsed.value === 'none' ? noneColor : transparentColor;
- }
- return parsed;
- };
- return CSSPropertyColor;
- }();
- var CSSPropertyFilter = /*#__PURE__*/function () {
- function CSSPropertyFilter() {
- this.parser = parseFilter;
- }
- var _proto = CSSPropertyFilter.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed) {
- // unset or none
- if (parsed instanceof CSSKeywordValue) {
- return [];
- }
- return parsed;
- };
- return CSSPropertyFilter;
- }();
- function getFontSize(object) {
- var fontSize = object.parsedStyle.fontSize;
- return isNil(fontSize) ? null : fontSize;
- }
- /**
- * <length> & <percentage>
- */
- var CSSPropertyLengthOrPercentage = /*#__PURE__*/function () {
- function CSSPropertyLengthOrPercentage() {
- this.parser = parseLengthOrPercentage;
- this.parserWithCSSDisabled = null;
- this.mixer = mergeNumbers;
- }
- var _proto = CSSPropertyLengthOrPercentage.prototype;
- /**
- * according to parent's bounds
- *
- * @example
- * CSS.percent(50) -> CSS.px(0.5 * parent.width)
- */
- _proto.calculator = function calculator(name, oldParsed, computed, object, registry) {
- if (isNumber(computed)) {
- return computed;
- }
- if (CSSUnitValue.isRelativeUnit(computed.unit)) {
- if (computed.unit === exports.UnitType.kPercentage) {
- // TODO: merge dimensions
- return 0;
- } else if (computed.unit === exports.UnitType.kEms) {
- if (object.parentNode) {
- var fontSize = getFontSize(object.parentNode);
- if (fontSize) {
- fontSize *= computed.value;
- return fontSize;
- } else {
- registry.addUnresolveProperty(object, name);
- }
- } else {
- registry.addUnresolveProperty(object, name);
- }
- return 0;
- } else if (computed.unit === exports.UnitType.kRems) {
- var _object$ownerDocument;
- if (object === null || object === void 0 ? void 0 : (_object$ownerDocument = object.ownerDocument) === null || _object$ownerDocument === void 0 ? void 0 : _object$ownerDocument.documentElement) {
- var _fontSize = getFontSize(object.ownerDocument.documentElement);
- if (_fontSize) {
- _fontSize *= computed.value;
- return _fontSize;
- } else {
- registry.addUnresolveProperty(object, name);
- }
- } else {
- registry.addUnresolveProperty(object, name);
- }
- return 0;
- }
- } else {
- // remove listener if exists
- // registry.unregisterParentGeometryBoundsChangedHandler(object, name);
- // return absolute value
- return computed.value;
- }
- };
- return CSSPropertyLengthOrPercentage;
- }();
- /**
- * format to Tuple2<CSSUnitValue>
- *
- * @example
- * rect.style.lineDash = 10;
- * rect.style.lineDash = [10, 10];
- * rect.style.lineDash = '10 10';
- */
- var CSSPropertyLengthOrPercentage12 = /*#__PURE__*/function () {
- function CSSPropertyLengthOrPercentage12() {
- this.mixer = mergeNumberLists;
- }
- var _proto = CSSPropertyLengthOrPercentage12.prototype;
- _proto.parser = function parser(radius) {
- var parsed = parseDimensionArray(isNumber(radius) ? [radius] : radius);
- var formatted;
- if (parsed.length === 1) {
- formatted = [parsed[0], parsed[0]];
- } else {
- formatted = [parsed[0], parsed[1]];
- }
- return formatted;
- };
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.map(function (c) {
- return c.value;
- });
- };
- return CSSPropertyLengthOrPercentage12;
- }();
- /**
- * used in rounded rect
- *
- * @example
- * rect.style.radius = 10;
- * rect.style.radius = '10 10';
- * rect.style.radius = '10 10 10 10';
- */
- var CSSPropertyLengthOrPercentage14 = /*#__PURE__*/function () {
- function CSSPropertyLengthOrPercentage14() {
- this.mixer = mergeNumberLists;
- }
- var _proto = CSSPropertyLengthOrPercentage14.prototype;
- _proto.parser = function parser(radius) {
- var parsed = parseDimensionArray(isNumber(radius) ? [radius] : radius);
- var formatted;
- // format to Tuple<CSSUnitValue>
- if (parsed.length === 1) {
- formatted = [parsed[0], parsed[0], parsed[0], parsed[0]];
- } else if (parsed.length === 2) {
- formatted = [parsed[0], parsed[1], parsed[0], parsed[1]];
- } else if (parsed.length === 3) {
- formatted = [parsed[0], parsed[1], parsed[2], parsed[1]];
- } else {
- formatted = [parsed[0], parsed[1], parsed[2], parsed[3]];
- }
- return formatted;
- };
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.map(function (c) {
- return c.value;
- });
- };
- return CSSPropertyLengthOrPercentage14;
- }();
- /**
- * local position
- */
- var CSSPropertyLocalPosition = /*#__PURE__*/function (_CSSPropertyLengthOrP) {
- _inheritsLoose(CSSPropertyLocalPosition, _CSSPropertyLengthOrP);
- function CSSPropertyLocalPosition() {
- return _CSSPropertyLengthOrP.apply(this, arguments) || this;
- }
- var _proto = CSSPropertyLocalPosition.prototype;
- /**
- * update local position
- */
- _proto.postProcessor = function postProcessor(object, attributes) {
- var x;
- var y;
- var z;
- switch (object.nodeName) {
- case exports.Shape.CIRCLE:
- case exports.Shape.ELLIPSE:
- var _object$parsedStyle = object.parsedStyle,
- cx = _object$parsedStyle.cx,
- cy = _object$parsedStyle.cy,
- cz = _object$parsedStyle.cz;
- if (!isNil(cx)) {
- x = cx;
- }
- if (!isNil(cy)) {
- y = cy;
- }
- if (!isNil(cz)) {
- z = cz;
- }
- break;
- case exports.Shape.LINE:
- var _object$parsedStyle2 = object.parsedStyle,
- x1 = _object$parsedStyle2.x1,
- x2 = _object$parsedStyle2.x2,
- y1 = _object$parsedStyle2.y1,
- y2 = _object$parsedStyle2.y2;
- var minX = Math.min(x1, x2);
- var minY = Math.min(y1, y2);
- x = minX;
- y = minY;
- z = 0;
- break;
- case exports.Shape.RECT:
- case exports.Shape.IMAGE:
- case exports.Shape.GROUP:
- case exports.Shape.HTML:
- case exports.Shape.TEXT:
- case exports.Shape.MESH:
- if (!isNil(object.parsedStyle.x)) {
- x = object.parsedStyle.x;
- }
- if (!isNil(object.parsedStyle.y)) {
- y = object.parsedStyle.y;
- }
- if (!isNil(object.parsedStyle.z)) {
- z = object.parsedStyle.z;
- }
- break;
- }
- if (object.nodeName !== exports.Shape.PATH && object.nodeName !== exports.Shape.POLYLINE && object.nodeName !== exports.Shape.POLYGON) {
- object.parsedStyle.defX = x || 0;
- object.parsedStyle.defY = y || 0;
- }
- var needResetLocalPosition = !isNil(x) || !isNil(y) || !isNil(z);
- // only if `transform` won't be processed later
- if (needResetLocalPosition && attributes.indexOf('transform') === -1) {
- // account for current transform if needed
- var transform = object.parsedStyle.transform;
- if (transform && transform.length) {
- parsedTransformToMat4(transform, object);
- } else {
- var _object$getLocalPosit = object.getLocalPosition(),
- ox = _object$getLocalPosit[0],
- oy = _object$getLocalPosit[1],
- oz = _object$getLocalPosit[2];
- object.setLocalPosition(isNil(x) ? ox : x, isNil(y) ? oy : y, isNil(z) ? oz : z);
- }
- }
- };
- return CSSPropertyLocalPosition;
- }(CSSPropertyLengthOrPercentage);
- var CSSPropertyMarker = /*#__PURE__*/function () {
- function CSSPropertyMarker() {}
- var _proto = CSSPropertyMarker.prototype;
- _proto.calculator = function calculator(name, oldMarker, newMarker, object) {
- var _newMarker;
- // unset
- if (newMarker instanceof CSSKeywordValue) {
- newMarker = null;
- }
- var cloned = (_newMarker = newMarker) === null || _newMarker === void 0 ? void 0 : _newMarker.cloneNode(true);
- if (cloned) {
- // FIXME: SVG should not inherit parent's style, add a flag here
- cloned.style.isMarker = true;
- }
- return cloned;
- };
- return CSSPropertyMarker;
- }();
- var CSSPropertyNumber = /*#__PURE__*/function () {
- function CSSPropertyNumber() {
- this.mixer = mergeNumbers;
- this.parser = parseNumber;
- this.parserWithCSSDisabled = null;
- }
- var _proto = CSSPropertyNumber.prototype;
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.value;
- };
- return CSSPropertyNumber;
- }();
- var CSSPropertyOffsetDistance = /*#__PURE__*/function () {
- function CSSPropertyOffsetDistance() {
- this.parser = parseNumber;
- this.parserWithCSSDisabled = null;
- this.mixer = clampedMergeNumbers(0, 1);
- }
- var _proto = CSSPropertyOffsetDistance.prototype;
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.value;
- };
- _proto.postProcessor = function postProcessor(object) {
- var _object$parsedStyle = object.parsedStyle,
- offsetPath = _object$parsedStyle.offsetPath,
- offsetDistance = _object$parsedStyle.offsetDistance;
- if (!offsetPath) {
- return;
- }
- var nodeName = offsetPath.nodeName;
- if (nodeName === exports.Shape.LINE || nodeName === exports.Shape.PATH || nodeName === exports.Shape.POLYLINE) {
- // set position in world space
- var point = offsetPath.getPoint(offsetDistance);
- if (point) {
- object.parsedStyle.defX = point.x;
- object.parsedStyle.defY = point.y;
- object.setLocalPosition(point.x, point.y);
- }
- }
- };
- return CSSPropertyOffsetDistance;
- }();
- /**
- * opacity
- */
- var CSSPropertyOpacity = /*#__PURE__*/function () {
- function CSSPropertyOpacity() {
- this.parser = parseNumber;
- this.parserWithCSSDisabled = null;
- this.mixer = clampedMergeNumbers(0, 1);
- }
- var _proto = CSSPropertyOpacity.prototype;
- _proto.calculator = function calculator(name, oldParsed, computed) {
- return computed.value;
- };
- return CSSPropertyOpacity;
- }();
- /**
- * Axis-Aligned Bounding Box
- * 为了便于后续 Frustum Culling,通过查找表定义 p-vertex 和 n-vertex
- * @see https://github.com/antvis/GWebGPUEngine/issues/3
- */
- var AABB = /*#__PURE__*/function () {
- function AABB() {
- this.center = [0, 0, 0];
- this.halfExtents = [0, 0, 0];
- this.min = [0, 0, 0];
- this.max = [0, 0, 0];
- }
- AABB.isEmpty = function isEmpty(aabb) {
- return !aabb || aabb.halfExtents[0] === 0 && aabb.halfExtents[1] === 0 && aabb.halfExtents[2] === 0;
- };
- var _proto = AABB.prototype;
- // center: vec3 = vec3.create();
- // halfExtents: vec3 = vec3.create();
- // min: vec3 = vec3.create();
- // max: vec3 = vec3.create();
- _proto.update = function update(center, halfExtents) {
- copyVec3(this.center, center);
- copyVec3(this.halfExtents, halfExtents);
- subVec3(this.min, this.center, this.halfExtents);
- addVec3(this.max, this.center, this.halfExtents);
- // vec3.copy(this.center, center);
- // vec3.copy(this.halfExtents, halfExtents);
- // vec3.sub(this.min, this.center, this.halfExtents);
- // vec3.add(this.max, this.center, this.halfExtents);
- };
- _proto.setMinMax = function setMinMax(min, max) {
- // vec3.add(this.center, max, min);
- // vec3.scale(this.center, this.center, 0.5);
- // vec3.sub(this.halfExtents, max, min);
- // vec3.scale(this.halfExtents, this.halfExtents, 0.5);
- // vec3.copy(this.min, min);
- // vec3.copy(this.max, max);
- addVec3(this.center, max, min);
- scaleVec3(this.center, this.center, 0.5);
- subVec3(this.halfExtents, max, min);
- scaleVec3(this.halfExtents, this.halfExtents, 0.5);
- copyVec3(this.min, min);
- copyVec3(this.max, max);
- };
- _proto.getMin = function getMin() {
- return this.min;
- };
- _proto.getMax = function getMax() {
- return this.max;
- };
- _proto.add = function add(aabb) {
- if (AABB.isEmpty(aabb)) {
- return;
- }
- if (AABB.isEmpty(this)) {
- this.setMinMax(aabb.getMin(), aabb.getMax());
- return;
- }
- var tc = this.center;
- var tcx = tc[0];
- var tcy = tc[1];
- var tcz = tc[2];
- var th = this.halfExtents;
- var thx = th[0];
- var thy = th[1];
- var thz = th[2];
- var tminx = tcx - thx;
- var tmaxx = tcx + thx;
- var tminy = tcy - thy;
- var tmaxy = tcy + thy;
- var tminz = tcz - thz;
- var tmaxz = tcz + thz;
- var oc = aabb.center;
- var ocx = oc[0];
- var ocy = oc[1];
- var ocz = oc[2];
- var oh = aabb.halfExtents;
- var ohx = oh[0];
- var ohy = oh[1];
- var ohz = oh[2];
- var ominx = ocx - ohx;
- var omaxx = ocx + ohx;
- var ominy = ocy - ohy;
- var omaxy = ocy + ohy;
- var ominz = ocz - ohz;
- var omaxz = ocz + ohz;
- if (ominx < tminx) {
- tminx = ominx;
- }
- if (omaxx > tmaxx) {
- tmaxx = omaxx;
- }
- if (ominy < tminy) {
- tminy = ominy;
- }
- if (omaxy > tmaxy) {
- tmaxy = omaxy;
- }
- if (ominz < tminz) {
- tminz = ominz;
- }
- if (omaxz > tmaxz) {
- tmaxz = omaxz;
- }
- tc[0] = (tminx + tmaxx) * 0.5;
- tc[1] = (tminy + tmaxy) * 0.5;
- tc[2] = (tminz + tmaxz) * 0.5;
- th[0] = (tmaxx - tminx) * 0.5;
- th[1] = (tmaxy - tminy) * 0.5;
- th[2] = (tmaxz - tminz) * 0.5;
- this.min[0] = tminx;
- this.min[1] = tminy;
- this.min[2] = tminz;
- this.max[0] = tmaxx;
- this.max[1] = tmaxy;
- this.max[2] = tmaxz;
- };
- _proto.setFromTransformedAABB = function setFromTransformedAABB(aabb, m) {
- var bc = this.center;
- var br = this.halfExtents;
- var ac = aabb.center;
- var ar = aabb.halfExtents;
- var mx0 = m[0];
- var mx1 = m[4];
- var mx2 = m[8];
- var my0 = m[1];
- var my1 = m[5];
- var my2 = m[9];
- var mz0 = m[2];
- var mz1 = m[6];
- var mz2 = m[10];
- var mx0a = Math.abs(mx0);
- var mx1a = Math.abs(mx1);
- var mx2a = Math.abs(mx2);
- var my0a = Math.abs(my0);
- var my1a = Math.abs(my1);
- var my2a = Math.abs(my2);
- var mz0a = Math.abs(mz0);
- var mz1a = Math.abs(mz1);
- var mz2a = Math.abs(mz2);
- bc[0] = m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2];
- bc[1] = m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2];
- bc[2] = m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2];
- // vec3.set(
- // bc,
- // m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2],
- // m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2],
- // m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2],
- // );
- br[0] = mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2];
- br[1] = my0a * ar[0] + my1a * ar[1] + my2a * ar[2];
- br[2] = mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2];
- // vec3.set(
- // br,
- // mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2],
- // my0a * ar[0] + my1a * ar[1] + my2a * ar[2],
- // mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2],
- // );
- // this.min = vec3.sub(this.min, bc, br);
- // this.max = vec3.add(this.max, bc, br);
- subVec3(this.min, bc, br);
- addVec3(this.max, bc, br);
- };
- _proto.intersects = function intersects(aabb) {
- var aMax = this.getMax();
- var aMin = this.getMin();
- var bMax = aabb.getMax();
- var bMin = aabb.getMin();
- return aMin[0] <= bMax[0] && aMax[0] >= bMin[0] && aMin[1] <= bMax[1] && aMax[1] >= bMin[1] && aMin[2] <= bMax[2] && aMax[2] >= bMin[2];
- };
- _proto.intersection = function intersection(aabb) {
- if (!this.intersects(aabb)) {
- return null;
- }
- var intersection = new AABB();
- // const min = vec3.max(vec3.create(), this.getMin(), aabb.getMin());
- // const max = vec3.min(vec3.create(), this.getMax(), aabb.getMax());
- var min = maxVec3([0, 0, 0], this.getMin(), aabb.getMin());
- var max = minVec3([0, 0, 0], this.getMax(), aabb.getMax());
- intersection.setMinMax(min, max);
- return intersection;
- }
- // containsPoint(point: vec3) {
- // const min = this.getMin();
- // const max = this.getMax();
- // return !(
- // point[0] < min[0] ||
- // point[0] > max[0] ||
- // point[1] < min[1] ||
- // point[1] > max[1] ||
- // point[2] < min[2] ||
- // point[2] > max[2]
- // );
- // }
- /**
- * get n-vertex
- * @param plane plane of CullingVolume
- */;
- _proto.getNegativeFarPoint = function getNegativeFarPoint(plane) {
- if (plane.pnVertexFlag === 0x111) {
- return copyVec3([0, 0, 0], this.min);
- // return vec3.copy(vec3.create(), this.min);
- } else if (plane.pnVertexFlag === 0x110) {
- return [this.min[0], this.min[1], this.max[2]];
- // return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x101) {
- return [this.min[0], this.max[1], this.min[2]];
- // return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x100) {
- return [this.min[0], this.max[1], this.max[2]];
- // return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x011) {
- return [this.max[0], this.min[1], this.min[2]];
- // return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x010) {
- return [this.max[0], this.min[1], this.max[2]];
- // return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x001) {
- return [this.max[0], this.max[1], this.min[2]];
- // return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
- } else {
- return [this.max[0], this.max[1], this.max[2]];
- // return vec3.fromValues(this.max[0], this.max[1], this.max[2]);
- }
- }
- /**
- * get p-vertex
- * @param plane plane of CullingVolume
- */;
- _proto.getPositiveFarPoint = function getPositiveFarPoint(plane) {
- if (plane.pnVertexFlag === 0x111) {
- return copyVec3([0, 0, 0], this.max);
- // return vec3.copy(vec3.create(), this.max);
- } else if (plane.pnVertexFlag === 0x110) {
- return [this.max[0], this.max[1], this.min[2]];
- // return vec3.fromValues(this.max[0], this.max[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x101) {
- return [this.max[0], this.min[1], this.max[2]];
- // return vec3.fromValues(this.max[0], this.min[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x100) {
- return [this.max[0], this.min[1], this.min[2]];
- // return vec3.fromValues(this.max[0], this.min[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x011) {
- return [this.min[0], this.max[1], this.max[2]];
- // return vec3.fromValues(this.min[0], this.max[1], this.max[2]);
- } else if (plane.pnVertexFlag === 0x010) {
- return [this.min[0], this.max[1], this.min[2]];
- // return vec3.fromValues(this.min[0], this.max[1], this.min[2]);
- } else if (plane.pnVertexFlag === 0x001) {
- return [this.min[0], this.min[1], this.max[2]];
- // return vec3.fromValues(this.min[0], this.min[1], this.max[2]);
- } else {
- return [this.min[0], this.min[1], this.min[2]];
- // return vec3.fromValues(this.min[0], this.min[1], this.min[2]);
- }
- };
- return AABB;
- }();
- var Plane = /*#__PURE__*/function () {
- function Plane(distance, normal) {
- this.distance = void 0;
- this.normal = void 0;
- /**
- * lookup table for p-vertex & n-vertex when doing frustum culling
- */
- this.pnVertexFlag = void 0;
- this.distance = distance || 0;
- this.normal = normal || fromValues$2(0, 1, 0);
- this.updatePNVertexFlag();
- }
- var _proto = Plane.prototype;
- _proto.updatePNVertexFlag = function updatePNVertexFlag() {
- this.pnVertexFlag = (Number(this.normal[0] >= 0) << 8) + (Number(this.normal[1] >= 0) << 4) + Number(this.normal[2] >= 0);
- };
- _proto.distanceToPoint = function distanceToPoint(point) {
- return dot(point, this.normal) - this.distance;
- };
- _proto.normalize = function normalize() {
- var invLen = 1 / len(this.normal);
- scale$1(this.normal, this.normal, invLen);
- this.distance *= invLen;
- };
- _proto.intersectsLine = function intersectsLine(start, end, point) {
- var d0 = this.distanceToPoint(start);
- var d1 = this.distanceToPoint(end);
- var t = d0 / (d0 - d1);
- var intersects = t >= 0 && t <= 1;
- if (intersects && point) {
- lerp(point, start, end, t);
- }
- return intersects;
- };
- return Plane;
- }();
- (function (Mask) {
- Mask[Mask["OUTSIDE"] = 4294967295] = "OUTSIDE";
- Mask[Mask["INSIDE"] = 0] = "INSIDE";
- Mask[Mask["INDETERMINATE"] = 2147483647] = "INDETERMINATE";
- })(exports.Mask || (exports.Mask = {}));
- var Frustum = /*#__PURE__*/function () {
- function Frustum(planes) {
- this.planes = [];
- if (planes) {
- this.planes = planes;
- } else {
- for (var i = 0; i < 6; i++) {
- this.planes.push(new Plane());
- }
- }
- }
- /**
- * extract 6 planes from projectionMatrix
- * @see http://www8.cs.umu.se/kurser/5DV051/HT12/lab/plane_extraction.pdf
- */
- var _proto = Frustum.prototype;
- _proto.extractFromVPMatrix = function extractFromVPMatrix(projectionMatrix) {
- // @ts-ignore
- var m0 = projectionMatrix[0],
- m1 = projectionMatrix[1],
- m2 = projectionMatrix[2],
- m3 = projectionMatrix[3],
- m4 = projectionMatrix[4],
- m5 = projectionMatrix[5],
- m6 = projectionMatrix[6],
- m7 = projectionMatrix[7],
- m8 = projectionMatrix[8],
- m9 = projectionMatrix[9],
- m10 = projectionMatrix[10],
- m11 = projectionMatrix[11],
- m12 = projectionMatrix[12],
- m13 = projectionMatrix[13],
- m14 = projectionMatrix[14],
- m15 = projectionMatrix[15];
- // right
- set$1(this.planes[0].normal, m3 - m0, m7 - m4, m11 - m8);
- this.planes[0].distance = m15 - m12;
- // left
- set$1(this.planes[1].normal, m3 + m0, m7 + m4, m11 + m8);
- this.planes[1].distance = m15 + m12;
- // bottom
- set$1(this.planes[2].normal, m3 + m1, m7 + m5, m11 + m9);
- this.planes[2].distance = m15 + m13;
- // top
- set$1(this.planes[3].normal, m3 - m1, m7 - m5, m11 - m9);
- this.planes[3].distance = m15 - m13;
- // far
- set$1(this.planes[4].normal, m3 - m2, m7 - m6, m11 - m10);
- this.planes[4].distance = m15 - m14;
- // near
- set$1(this.planes[5].normal, m3 + m2, m7 + m6, m11 + m10);
- this.planes[5].distance = m15 + m14;
- this.planes.forEach(function (plane) {
- plane.normalize();
- plane.updatePNVertexFlag();
- });
- };
- return Frustum;
- }();
- var Point = /*#__PURE__*/function () {
- function Point(x, y) {
- if (x === void 0) {
- x = 0;
- }
- if (y === void 0) {
- y = 0;
- }
- this.x = 0;
- this.y = 0;
- this.x = x;
- this.y = y;
- }
- var _proto = Point.prototype;
- _proto.clone = function clone() {
- return new Point(this.x, this.y);
- };
- _proto.copyFrom = function copyFrom(p) {
- this.x = p.x;
- this.y = p.y;
- };
- return Point;
- }();
- var Rectangle = /*#__PURE__*/function () {
- function Rectangle(x, y, width, height) {
- this.x = void 0;
- this.y = void 0;
- this.width = void 0;
- this.height = void 0;
- this.left = void 0;
- this.right = void 0;
- this.top = void 0;
- this.bottom = void 0;
- this.x = x;
- this.y = y;
- this.width = width;
- this.height = height;
- this.left = x;
- this.right = x + width;
- this.top = y;
- this.bottom = y + height;
- }
- var _proto = Rectangle.prototype;
- _proto.toJSON = function toJSON() {};
- return Rectangle;
- }();
- var CSSPropertyPath = /*#__PURE__*/function () {
- function CSSPropertyPath() {
- /**
- * path2Curve
- */
- this.parser = parsePath;
- this.parserWithCSSDisabled = parsePath;
- this.mixer = mergePaths;
- }
- var _proto = CSSPropertyPath.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed) {
- // unset
- if (parsed instanceof CSSKeywordValue && parsed.value === 'unset') {
- return {
- absolutePath: [],
- hasArc: false,
- segments: [],
- polygons: [],
- polylines: [],
- curve: null,
- totalLength: 0,
- rect: new Rectangle(0, 0, 0, 0)
- };
- }
- return parsed;
- };
- /**
- * update local position
- */
- _proto.postProcessor = function postProcessor(object, attributes) {
- if (object.nodeName === exports.Shape.PATH && attributes.indexOf('transform') === -1) {
- var _object$parsedStyle = object.parsedStyle,
- _object$parsedStyle$d = _object$parsedStyle.defX,
- defX = _object$parsedStyle$d === void 0 ? 0 : _object$parsedStyle$d,
- _object$parsedStyle$d2 = _object$parsedStyle.defY,
- defY = _object$parsedStyle$d2 === void 0 ? 0 : _object$parsedStyle$d2;
- object.setLocalPosition(defX, defY);
- }
- };
- return CSSPropertyPath;
- }();
- var CSSPropertyPoints = /*#__PURE__*/function () {
- function CSSPropertyPoints() {
- this.parser = parsePoints;
- this.mixer = mergePoints;
- }
- var _proto = CSSPropertyPoints.prototype;
- /**
- * update local position
- */
- _proto.postProcessor = function postProcessor(object, attributes) {
- if ((object.nodeName === exports.Shape.POLYGON || object.nodeName === exports.Shape.POLYLINE) && attributes.indexOf('transform') === -1) {
- var _object$parsedStyle = object.parsedStyle,
- defX = _object$parsedStyle.defX,
- defY = _object$parsedStyle.defY;
- object.setLocalPosition(defX, defY);
- }
- };
- return CSSPropertyPoints;
- }();
- var CSSPropertyShadowBlur = /*#__PURE__*/function (_CSSPropertyLengthOrP) {
- _inheritsLoose(CSSPropertyShadowBlur, _CSSPropertyLengthOrP);
- function CSSPropertyShadowBlur() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _CSSPropertyLengthOrP.call.apply(_CSSPropertyLengthOrP, [this].concat(args)) || this;
- _this.mixer = clampedMergeNumbers(0, Infinity);
- return _this;
- }
- return CSSPropertyShadowBlur;
- }(CSSPropertyLengthOrPercentage);
- var CSSPropertyText = /*#__PURE__*/function () {
- function CSSPropertyText() {}
- var _proto = CSSPropertyText.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- if (parsed instanceof CSSKeywordValue) {
- if (parsed.value === 'unset') {
- return '';
- } else {
- return parsed.value;
- }
- }
- // allow number as valid text content
- return "" + parsed;
- };
- _proto.postProcessor = function postProcessor(object) {
- object.nodeValue = "" + object.parsedStyle.text || '';
- };
- return CSSPropertyText;
- }();
- /**
- * it must transform after text get parsed
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-transform
- */
- var CSSPropertyTextTransform = /*#__PURE__*/function () {
- function CSSPropertyTextTransform() {}
- var _proto = CSSPropertyTextTransform.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- var rawText = object.getAttribute('text');
- if (rawText) {
- var transformedText = rawText;
- if (parsed.value === 'capitalize') {
- transformedText = rawText.charAt(0).toUpperCase() + rawText.slice(1);
- } else if (parsed.value === 'lowercase') {
- transformedText = rawText.toLowerCase();
- } else if (parsed.value === 'uppercase') {
- transformedText = rawText.toUpperCase();
- }
- object.parsedStyle.text = transformedText;
- }
- return parsed.value;
- };
- return CSSPropertyTextTransform;
- }();
- /**
- * @see /zh/docs/api/animation#支持变换的属性
- *
- * support the following formats like CSS Transform:
- *
- * scale
- * * scale(x, y)
- * * scaleX(x)
- * * scaleY(x)
- * * scaleZ(z)
- * * scale3d(x, y, z)
- *
- * translate (unit: none, px, %(relative to its bounds))
- * * translate(x, y) eg. translate(0, 0) translate(0, 30px) translate(100%, 100%)
- * * translateX(0)
- * * translateY(0)
- * * translateZ(0)
- * * translate3d(0, 0, 0)
- *
- * rotate (unit: deg rad turn)
- * * rotate(0.5turn) rotate(30deg) rotate(1rad)
- *
- * none
- *
- * unsupported for now:
- * * calc() eg. translate(calc(100% + 10px))
- * * matrix/matrix3d()
- * * skew/skewX/skewY
- * * perspective
- */
- var CSSPropertyTransform = /*#__PURE__*/function () {
- function CSSPropertyTransform() {
- this.parser = parseTransform;
- this.parserWithCSSDisabled = parseTransform;
- this.mixer = mergeTransforms;
- }
- var _proto = CSSPropertyTransform.prototype;
- _proto.calculator = function calculator(name, oldParsed, parsed, object) {
- // 'none'
- if (parsed instanceof CSSKeywordValue) {
- return [];
- }
- return parsed;
- };
- _proto.postProcessor = function postProcessor(object) {
- var transform = object.parsedStyle.transform;
- parsedTransformToMat4(transform, object);
- };
- return CSSPropertyTransform;
- }();
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
- * @example
- * [10px, 10px] [10%, 10%]
- */
- var CSSPropertyTransformOrigin = function CSSPropertyTransformOrigin() {
- this.parser = parseTransformOrigin;
- };
- /**
- * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
- */
- (function (Strategy) {
- Strategy[Strategy["Standard"] = 0] = "Standard";
- })(exports.Strategy || (exports.Strategy = {}));
- (function (SortReason) {
- SortReason[SortReason["ADDED"] = 0] = "ADDED";
- SortReason[SortReason["REMOVED"] = 1] = "REMOVED";
- SortReason[SortReason["Z_INDEX_CHANGED"] = 2] = "Z_INDEX_CHANGED";
- })(exports.SortReason || (exports.SortReason = {}));
- var CSSPropertyZIndex = /*#__PURE__*/function () {
- function CSSPropertyZIndex() {
- this.parser = parseNumber;
- }
- var _proto = CSSPropertyZIndex.prototype;
- _proto.calculator = function calculator(name, oldParsed, computed, object) {
- return computed.value;
- };
- _proto.postProcessor = function postProcessor(object) {
- if (object.parentNode) {
- var parentEntity = object.parentNode;
- var parentRenderable = parentEntity.renderable;
- var parentSortable = parentEntity.sortable;
- if (parentRenderable) {
- parentRenderable.dirty = true;
- }
- // need re-sort on parent
- if (parentSortable) {
- parentSortable.dirty = true;
- parentSortable.dirtyReason = exports.SortReason.Z_INDEX_CHANGED;
- }
- }
- };
- return CSSPropertyZIndex;
- }();
- /**
- * canvas.customElements
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
- */
- var CustomElementRegistry = /*#__PURE__*/function () {
- function CustomElementRegistry() {
- this.registry = {};
- this.define(exports.Shape.CIRCLE, Circle);
- this.define(exports.Shape.ELLIPSE, Ellipse);
- this.define(exports.Shape.RECT, Rect);
- this.define(exports.Shape.IMAGE, Image);
- this.define(exports.Shape.LINE, Line);
- this.define(exports.Shape.GROUP, Group);
- this.define(exports.Shape.PATH, Path);
- this.define(exports.Shape.POLYGON, Polygon);
- this.define(exports.Shape.POLYLINE, Polyline);
- this.define(exports.Shape.TEXT, Text);
- this.define(exports.Shape.HTML, HTML);
- }
- var _proto = CustomElementRegistry.prototype;
- _proto.define = function define(name, constructor) {
- this.registry[name] = constructor;
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/get
- */;
- _proto.get = function get(name) {
- return this.registry[name];
- };
- return CustomElementRegistry;
- }();
- function isFederatedEvent(value) {
- return !!value.type;
- }
- /**
- * An DOM-compatible synthetic event implementation that is "forwarded" on behalf of an original
- * FederatedEvent or native {@link https://dom.spec.whatwg.org/#event Event}.
- */
- var FederatedEvent = /*#__PURE__*/function () {
- /**
- * The event boundary which manages this event. Propagation can only occur
- * within the boundary's jurisdiction.
- */
- function FederatedEvent(manager) {
- /**
- * The type of event, supports the following:
- * * pointerdown
- * * touchstart
- * * mousedown
- * * rightdown
- * * ...
- */
- this.type = void 0;
- /**
- * The propagation phase.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase
- */
- this.eventPhase = FederatedEvent.prototype.NONE;
- /**
- * can be used to implement event delegation
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
- */
- this.target = void 0;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/bubbles
- */
- this.bubbles = true;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/cancelBubble
- */
- this.cancelBubble = true;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable
- */
- this.cancelable = false;
- /** the event target when listeners binded */
- this.currentTarget = void 0;
- /** Flags whether the default response of the user agent was prevent through this event. */
- this.defaultPrevented = false;
- /**
- * timestamp when the event created
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/timeStamp
- */
- this.timeStamp = void 0;
- /**
- * the original event.
- */
- this.nativeEvent = void 0;
- /** The original event that caused this event, if any. */
- this.originalEvent = void 0;
- /** Flags whether propagation was stopped. */
- this.propagationStopped = false;
- /** Flags whether propagation was immediately stopped. */
- this.propagationImmediatelyStopped = false;
- this.manager = void 0;
- /** Event-specific detail */
- this.detail = void 0;
- /**
- * The coordinates of the evnet relative to the nearest DOM layer.
- * This is a non-standard property.
- */
- this.layer = new Point();
- /**
- * The coordinates of the event relative to the DOM document.
- * This is a non-standard property.
- * relative to the DOM document.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/pageX
- */
- this.page = new Point();
- /**
- * relative to Canvas, origin is left-top
- */
- this.canvas = new Point();
- /**
- * relative to Viewport, account for Camera
- */
- this.viewport = new Point();
- this.path = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view
- */
- this.view = void 0;
- this.which = void 0;
- this.returnValue = void 0;
- this.srcElement = void 0;
- this.composed = false;
- this.isTrusted = void 0;
- this.NONE = 0;
- this.CAPTURING_PHASE = 1;
- this.AT_TARGET = 2;
- this.BUBBLING_PHASE = 3;
- this.manager = manager;
- }
- var _proto = FederatedEvent.prototype;
- /**
- * The propagation path for this event
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/composedPath
- *
- * So composedPath()[0] represents the original target.
- * @see https://polymer-library.polymer-project.org/3.0/docs/devguide/events#retargeting
- */
- _proto.composedPath = function composedPath() {
- if (this.manager && (!this.path || this.path[0] !== this.target)) {
- this.path = this.target ? this.manager.propagationPath(this.target) : [];
- }
- return this.path;
- }
- /**
- * @deprecated
- */;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/preventDefault
- */
- _proto.preventDefault = function preventDefault() {
- if (this.nativeEvent instanceof Event && this.nativeEvent.cancelable) {
- this.nativeEvent.preventDefault();
- }
- this.defaultPrevented = true;
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopImmediatePropagation
- */;
- _proto.stopImmediatePropagation = function stopImmediatePropagation() {
- this.propagationImmediatelyStopped = true;
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopPropagation
- */;
- _proto.stopPropagation = function stopPropagation() {
- this.propagationStopped = true;
- };
- /**
- * added for compatibility with DOM Event,
- * deprecated props and methods
- */
- _proto.initEvent = function initEvent() {};
- _proto.initUIEvent = function initUIEvent() {};
- _proto.clone = function clone() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _createClass(FederatedEvent, [{
- key: "name",
- get:
- /**
- * @deprecated
- */
- function get() {
- return this.type;
- }
- }, {
- key: "layerX",
- get: function get() {
- return this.layer.x;
- }
- }, {
- key: "layerY",
- get: function get() {
- return this.layer.y;
- }
- }, {
- key: "pageX",
- get: function get() {
- return this.page.x;
- }
- }, {
- key: "pageY",
- get: function get() {
- return this.page.y;
- }
- }, {
- key: "x",
- get: function get() {
- return this.canvas.x;
- }
- }, {
- key: "y",
- get: function get() {
- return this.canvas.y;
- }
- }, {
- key: "canvasX",
- get: function get() {
- return this.canvas.x;
- }
- }, {
- key: "canvasY",
- get: function get() {
- return this.canvas.y;
- }
- }, {
- key: "viewportX",
- get: function get() {
- return this.viewport.x;
- }
- }, {
- key: "viewportY",
- get: function get() {
- return this.viewport.y;
- }
- }, {
- key: "propagationPath",
- get: function get() {
- return this.composedPath();
- }
- }]);
- return FederatedEvent;
- }();
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
- *
- * @example
- const event = new CustomEvent('build', { detail: { prop1: 'xx' } });
- circle.addEventListener('build', (e) => {
- e.target; // circle
- e.detail; // { prop1: 'xx' }
- });
- circle.dispatchEvent(event);
- */
- var CustomEvent = /*#__PURE__*/function (_FederatedEvent) {
- _inheritsLoose(CustomEvent, _FederatedEvent);
- // eslint-disable-next-line @typescript-eslint/ban-types
- function CustomEvent(eventName, object) {
- var _this;
- _this = _FederatedEvent.call(this, null) || this;
- _this.type = eventName;
- _this.detail = object;
- // compatible with G 3.0
- Object.assign(_assertThisInitialized(_this), object);
- return _this;
- }
- return CustomEvent;
- }(FederatedEvent);
- var eventemitter3 = createCommonjsModule(function (module) {
- var has = Object.prototype.hasOwnProperty
- , prefix = '~';
- /**
- * Constructor to create a storage for our `EE` objects.
- * An `Events` instance is a plain object whose properties are event names.
- *
- * @constructor
- * @private
- */
- function Events() {}
- //
- // We try to not inherit from `Object.prototype`. In some engines creating an
- // instance in this way is faster than calling `Object.create(null)` directly.
- // If `Object.create(null)` is not supported we prefix the event names with a
- // character to make sure that the built-in object properties are not
- // overridden or used as an attack vector.
- //
- if (Object.create) {
- Events.prototype = Object.create(null);
- //
- // This hack is needed because the `__proto__` property is still inherited in
- // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
- //
- if (!new Events().__proto__) prefix = false;
- }
- /**
- * Representation of a single event listener.
- *
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
- * @constructor
- * @private
- */
- function EE(fn, context, once) {
- this.fn = fn;
- this.context = context;
- this.once = once || false;
- }
- /**
- * Add a listener for a given event.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} context The context to invoke the listener with.
- * @param {Boolean} once Specify if the listener is a one-time listener.
- * @returns {EventEmitter}
- * @private
- */
- function addListener(emitter, event, fn, context, once) {
- if (typeof fn !== 'function') {
- throw new TypeError('The listener must be a function');
- }
- var listener = new EE(fn, context || emitter, once)
- , evt = prefix ? prefix + event : event;
- if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
- else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
- else emitter._events[evt] = [emitter._events[evt], listener];
- return emitter;
- }
- /**
- * Clear event by name.
- *
- * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
- * @param {(String|Symbol)} evt The Event name.
- * @private
- */
- function clearEvent(emitter, evt) {
- if (--emitter._eventsCount === 0) emitter._events = new Events();
- else delete emitter._events[evt];
- }
- /**
- * Minimal `EventEmitter` interface that is molded against the Node.js
- * `EventEmitter` interface.
- *
- * @constructor
- * @public
- */
- function EventEmitter() {
- this._events = new Events();
- this._eventsCount = 0;
- }
- /**
- * Return an array listing the events for which the emitter has registered
- * listeners.
- *
- * @returns {Array}
- * @public
- */
- EventEmitter.prototype.eventNames = function eventNames() {
- var names = []
- , events
- , name;
- if (this._eventsCount === 0) return names;
- for (name in (events = this._events)) {
- if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
- }
- if (Object.getOwnPropertySymbols) {
- return names.concat(Object.getOwnPropertySymbols(events));
- }
- return names;
- };
- /**
- * Return the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Array} The registered listeners.
- * @public
- */
- EventEmitter.prototype.listeners = function listeners(event) {
- var evt = prefix ? prefix + event : event
- , handlers = this._events[evt];
- if (!handlers) return [];
- if (handlers.fn) return [handlers.fn];
- for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
- ee[i] = handlers[i].fn;
- }
- return ee;
- };
- /**
- * Return the number of listeners listening to a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Number} The number of listeners.
- * @public
- */
- EventEmitter.prototype.listenerCount = function listenerCount(event) {
- var evt = prefix ? prefix + event : event
- , listeners = this._events[evt];
- if (!listeners) return 0;
- if (listeners.fn) return 1;
- return listeners.length;
- };
- /**
- * Calls each of the listeners registered for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @returns {Boolean} `true` if the event had listeners, else `false`.
- * @public
- */
- EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
- var evt = prefix ? prefix + event : event;
- if (!this._events[evt]) return false;
- var listeners = this._events[evt]
- , len = arguments.length
- , args
- , i;
- if (listeners.fn) {
- if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
- switch (len) {
- case 1: return listeners.fn.call(listeners.context), true;
- case 2: return listeners.fn.call(listeners.context, a1), true;
- case 3: return listeners.fn.call(listeners.context, a1, a2), true;
- case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
- case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
- case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
- }
- for (i = 1, args = new Array(len -1); i < len; i++) {
- args[i - 1] = arguments[i];
- }
- listeners.fn.apply(listeners.context, args);
- } else {
- var length = listeners.length
- , j;
- for (i = 0; i < length; i++) {
- if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
- switch (len) {
- case 1: listeners[i].fn.call(listeners[i].context); break;
- case 2: listeners[i].fn.call(listeners[i].context, a1); break;
- case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
- case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
- default:
- if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
- args[j - 1] = arguments[j];
- }
- listeners[i].fn.apply(listeners[i].context, args);
- }
- }
- }
- return true;
- };
- /**
- * Add a listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.on = function on(event, fn, context) {
- return addListener(this, event, fn, context, false);
- };
- /**
- * Add a one-time listener for a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn The listener function.
- * @param {*} [context=this] The context to invoke the listener with.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.once = function once(event, fn, context) {
- return addListener(this, event, fn, context, true);
- };
- /**
- * Remove the listeners of a given event.
- *
- * @param {(String|Symbol)} event The event name.
- * @param {Function} fn Only remove the listeners that match this function.
- * @param {*} context Only remove the listeners that have this context.
- * @param {Boolean} once Only remove one-time listeners.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
- var evt = prefix ? prefix + event : event;
- if (!this._events[evt]) return this;
- if (!fn) {
- clearEvent(this, evt);
- return this;
- }
- var listeners = this._events[evt];
- if (listeners.fn) {
- if (
- listeners.fn === fn &&
- (!once || listeners.once) &&
- (!context || listeners.context === context)
- ) {
- clearEvent(this, evt);
- }
- } else {
- for (var i = 0, events = [], length = listeners.length; i < length; i++) {
- if (
- listeners[i].fn !== fn ||
- (once && !listeners[i].once) ||
- (context && listeners[i].context !== context)
- ) {
- events.push(listeners[i]);
- }
- }
- //
- // Reset the array, or remove it completely if we have no more listeners.
- //
- if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
- else clearEvent(this, evt);
- }
- return this;
- };
- /**
- * Remove all listeners, or those of the specified event.
- *
- * @param {(String|Symbol)} [event] The event name.
- * @returns {EventEmitter} `this`.
- * @public
- */
- EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
- var evt;
- if (event) {
- evt = prefix ? prefix + event : event;
- if (this._events[evt]) clearEvent(this, evt);
- } else {
- this._events = new Events();
- this._eventsCount = 0;
- }
- return this;
- };
- //
- // Alias methods names because people roll like that.
- //
- EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
- EventEmitter.prototype.addListener = EventEmitter.prototype.on;
- //
- // Expose the prefix.
- //
- EventEmitter.prefixed = prefix;
- //
- // Allow `EventEmitter` to be imported as module namespace.
- //
- EventEmitter.EventEmitter = EventEmitter;
- //
- // Expose the module.
- //
- {
- module.exports = EventEmitter;
- }
- });
- var DELEGATION_SPLITTER = ':';
- /**
- * Objects that can receive events and may have listeners for them.
- * eg. Element, Canvas, DisplayObject
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
- */
- var EventTarget = /*#__PURE__*/function () {
- function EventTarget() {
- /**
- * event emitter
- */
- this.emitter = new eventemitter3();
- }
- var _proto = EventTarget.prototype;
- /**
- * @deprecated
- * @alias addEventListener
- */
- _proto.on = function on(type, listener, options) {
- this.addEventListener(type, listener, options);
- return this;
- }
- /**
- * support `capture` & `once` in options
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener
- */;
- _proto.addEventListener = function addEventListener(type, listener, options) {
- var capture = isBoolean(options) && options || isObject(options) && options.capture;
- var once = isObject(options) && options.once;
- var context = isFunction(listener) ? undefined : listener;
- // compatible with G 3.0
- // support using delegate name in event type, eg. 'node:click'
- var useDelegatedName = false;
- var delegatedName = '';
- if (type.indexOf(DELEGATION_SPLITTER) > -1) {
- var _type$split = type.split(DELEGATION_SPLITTER),
- name = _type$split[0],
- eventType = _type$split[1];
- type = eventType;
- delegatedName = name;
- useDelegatedName = true;
- }
- type = capture ? type + "capture" : type;
- listener = isFunction(listener) ? listener : listener.handleEvent;
- // compatible with G 3.0
- if (useDelegatedName) {
- var originListener = listener;
- listener = function listener() {
- var _args$0$target;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- if (((_args$0$target = args[0].target) === null || _args$0$target === void 0 ? void 0 : _args$0$target.name) !== delegatedName) {
- return;
- }
- // @ts-ignore
- originListener.apply(void 0, args);
- };
- }
- if (once) {
- this.emitter.once(type, listener, context);
- } else {
- this.emitter.on(type, listener, context);
- }
- return this;
- }
- /**
- * @deprecated
- * @alias removeEventListener
- */;
- _proto.off = function off(type, listener, options) {
- if (type) {
- this.removeEventListener(type, listener, options);
- } else {
- // remove all listeners
- this.removeAllEventListeners();
- }
- return this;
- };
- _proto.removeAllEventListeners = function removeAllEventListeners() {
- this.emitter.removeAllListeners();
- };
- _proto.removeEventListener = function removeEventListener(type, listener, options) {
- var _listener;
- var capture = isBoolean(options) && options || isObject(options) && options.capture;
- var context = isFunction(listener) ? undefined : listener;
- type = capture ? type + "capture" : type;
- listener = isFunction(listener) ? listener : (_listener = listener) === null || _listener === void 0 ? void 0 : _listener.handleEvent;
- this.emitter.off(type, listener, context);
- return this;
- }
- /**
- * @deprecated
- * @alias dispatchEvent
- */
- // eslint-disable-next-line @typescript-eslint/ban-types
- ;
- _proto.emit = function emit(eventName, object) {
- this.dispatchEvent(new CustomEvent(eventName, object));
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
- */;
- _proto.dispatchEvent = function dispatchEvent(e, skipPropagate) {
- if (skipPropagate === void 0) {
- skipPropagate = false;
- }
- if (!isFederatedEvent(e)) {
- throw new Error('DisplayObject cannot propagate events outside of the Federated Events API');
- }
- // should account for Element / Document / Canvas
- var canvas;
- // @ts-ignore
- if (this.document) {
- canvas = this;
- // @ts-ignore
- } else if (this.defaultView) {
- canvas = this.defaultView;
- } else {
- var _this$ownerDocument;
- canvas = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.defaultView;
- }
- // assign event manager
- if (canvas) {
- var _e$manager;
- e.manager = canvas.getEventService() || null;
- if (!e.manager) {
- return false;
- }
- e.defaultPrevented = false;
- e.path = [];
- if (!skipPropagate) {
- e.target = this;
- }
- (_e$manager = e.manager) === null || _e$manager === void 0 ? void 0 : _e$manager.dispatchEvent(e, e.type, skipPropagate);
- }
- return !e.defaultPrevented;
- };
- return EventTarget;
- }();
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node
- */
- var Node = /*#__PURE__*/function (_EventTarget) {
- _inheritsLoose(Node, _EventTarget);
- function Node() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
- _this.shadow = false;
- /**
- * points to canvas.document
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument
- */
- _this.ownerDocument = null;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isConnected
- * @example
- circle.isConnected; // false
- canvas.appendChild(circle);
- circle.isConnected; // true
- */
- _this.isConnected = false;
- /**
- * Returns node's node document's document base URL.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node
- */
- _this.baseURI = '';
- /**
- * Returns the children.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes
- */
- _this.childNodes = [];
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
- */
- _this.nodeType = 0;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeName
- */
- _this.nodeName = '';
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeValue
- */
- _this.nodeValue = null;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/ParentNode
- */
- _this.parentNode = null;
- return _this;
- }
- Node.isNode = function isNode(target) {
- return !!target.childNodes;
- };
- var _proto = Node.prototype;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/getRootNode
- */
- _proto.getRootNode = function getRootNode(opts) {
- if (opts === void 0) {
- opts = {};
- }
- if (this.parentNode) {
- return this.parentNode.getRootNode(opts);
- }
- if (opts.composed && this.host) {
- return this.host.getRootNode(opts);
- }
- return this;
- };
- _proto.hasChildNodes = function hasChildNodes() {
- return this.childNodes.length > 0;
- };
- _proto.isDefaultNamespace = function isDefaultNamespace(namespace) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.lookupNamespaceURI = function lookupNamespaceURI(prefix) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.lookupPrefix = function lookupPrefix(namespace) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.normalize = function normalize() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isEqualNode
- */;
- _proto.isEqualNode = function isEqualNode(otherNode) {
- // TODO: compare 2 nodes, not sameness
- return this === otherNode;
- };
- _proto.isSameNode = function isSameNode(otherNode) {
- return this.isEqualNode(otherNode);
- };
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
- * @see https://github.com/b-fuze/deno-dom/blob/master/src/dom/node.ts#L338
- */
- _proto.compareDocumentPosition = function compareDocumentPosition(other) {
- if (other === this) {
- // same node
- return 0;
- }
- // if (!(other instanceof Node)) {
- // throw new TypeError(
- // 'Node.compareDocumentPosition: Argument 1 does not implement interface Node.',
- // );
- // }
- var node1Root = other;
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- var node2Root = this;
- var node1Hierarchy = [node1Root];
- var node2Hierarchy = [node2Root];
- while ((_node1Root$parentNode = node1Root.parentNode) !== null && _node1Root$parentNode !== void 0 ? _node1Root$parentNode : node2Root.parentNode) {
- var _node1Root$parentNode;
- node1Root = node1Root.parentNode ? (node1Hierarchy.push(node1Root.parentNode), node1Root.parentNode) : node1Root;
- node2Root = node2Root.parentNode ? (node2Hierarchy.push(node2Root.parentNode), node2Root.parentNode) : node2Root;
- }
- // Check if they don't share the same root node
- if (node1Root !== node2Root) {
- return Node.DOCUMENT_POSITION_DISCONNECTED | Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | Node.DOCUMENT_POSITION_PRECEDING;
- }
- var longerHierarchy = node1Hierarchy.length > node2Hierarchy.length ? node1Hierarchy : node2Hierarchy;
- var shorterHierarchy = longerHierarchy === node1Hierarchy ? node2Hierarchy : node1Hierarchy;
- // Check if either is a container of the other
- if (longerHierarchy[longerHierarchy.length - shorterHierarchy.length] === shorterHierarchy[0]) {
- return longerHierarchy === node1Hierarchy ?
- // other is a child of this
- Node.DOCUMENT_POSITION_CONTAINED_BY | Node.DOCUMENT_POSITION_FOLLOWING :
- // this is a child of other
- Node.DOCUMENT_POSITION_CONTAINS | Node.DOCUMENT_POSITION_PRECEDING;
- }
- // Find their first common ancestor and see whether they
- // are preceding or following
- var longerStart = longerHierarchy.length - shorterHierarchy.length;
- for (var i = shorterHierarchy.length - 1; i >= 0; i--) {
- var shorterHierarchyNode = shorterHierarchy[i];
- var longerHierarchyNode = longerHierarchy[longerStart + i];
- // We found the first common ancestor
- if (longerHierarchyNode !== shorterHierarchyNode) {
- var siblings = shorterHierarchyNode.parentNode.childNodes;
- if (siblings.indexOf(shorterHierarchyNode) < siblings.indexOf(longerHierarchyNode)) {
- // Shorter is before longer
- if (shorterHierarchy === node1Hierarchy) {
- // Other is before this
- return Node.DOCUMENT_POSITION_PRECEDING;
- } else {
- // This is before other
- return Node.DOCUMENT_POSITION_FOLLOWING;
- }
- } else {
- // Longer is before shorter
- if (longerHierarchy === node1Hierarchy) {
- // Other is before this
- return Node.DOCUMENT_POSITION_PRECEDING;
- } else {
- // Other is after this
- return Node.DOCUMENT_POSITION_FOLLOWING;
- }
- }
- }
- }
- return Node.DOCUMENT_POSITION_FOLLOWING;
- }
- /**
- * @deprecated
- * @alias contains
- */;
- _proto.contain = function contain(other) {
- return this.contains(other);
- };
- _proto.contains = function contains(other) {
- // the node itself, one of its direct children
- var tmp = other;
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
- while (tmp && this !== tmp) {
- tmp = tmp.parentNode;
- }
- return !!tmp;
- };
- _proto.getAncestor = function getAncestor(n) {
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- var temp = this;
- while (n > 0 && temp) {
- temp = temp.parentNode;
- n--;
- }
- return temp;
- };
- _proto.forEach = function forEach(callback, assigned) {
- if (assigned === void 0) {
- assigned = false;
- }
- if (!callback(this)) {
- (assigned ? this.childNodes.slice() : this.childNodes).forEach(function (child) {
- child.forEach(callback);
- });
- }
- };
- _createClass(Node, [{
- key: "textContent",
- get:
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/textContent
- */
- function get() {
- var out = '';
- if (this.nodeName === exports.Shape.TEXT) {
- // @ts-ignore
- out += this.style.text;
- }
- for (var _iterator = _createForOfIteratorHelperLoose(this.childNodes), _step; !(_step = _iterator()).done;) {
- var child = _step.value;
- if (child.nodeName === exports.Shape.TEXT) {
- out += child.nodeValue;
- } else {
- out += child.textContent;
- }
- }
- return out;
- },
- set: function set(content) {
- var _this2 = this;
- // remove all children
- this.childNodes.slice().forEach(function (child) {
- _this2.removeChild(child);
- });
- if (this.nodeName === exports.Shape.TEXT) {
- // @ts-ignore
- this.style.text = "" + content;
- }
- }
- }, {
- key: "parent",
- get:
- /**
- * @deprecated
- * @alias parentNode
- */
- function get() {
- return this.parentNode;
- }
- }, {
- key: "parentElement",
- get: function get() {
- return null;
- }
- }, {
- key: "nextSibling",
- get: function get() {
- return null;
- }
- }, {
- key: "previousSibling",
- get: function get() {
- return null;
- }
- }, {
- key: "firstChild",
- get: function get() {
- return this.childNodes.length > 0 ? this.childNodes[0] : null;
- }
- }, {
- key: "lastChild",
- get: function get() {
- return this.childNodes.length > 0 ? this.childNodes[this.childNodes.length - 1] : null;
- }
- }]);
- return Node;
- }(EventTarget);
- /**
- * Both nodes are in different documents or different trees in the same document.
- */
- Node.DOCUMENT_POSITION_DISCONNECTED = 1;
- /**
- * otherNode precedes the node in either a pre-order depth-first traversal
- * of a tree containing both (e.g., as an ancestor or previous sibling or a descendant of a previous sibling or previous sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering.
- */
- Node.DOCUMENT_POSITION_PRECEDING = 2;
- /**
- * otherNode follows the node in either a pre-order depth-first traversal of a tree containing both (e.g., as a descendant or following sibling or a descendant of a following sibling or following sibling of an ancestor) or (if they are disconnected) in an arbitrary but consistent ordering.
- */
- Node.DOCUMENT_POSITION_FOLLOWING = 4;
- /**
- * otherNode is an ancestor of the node.
- */
- Node.DOCUMENT_POSITION_CONTAINS = 8;
- /**
- * otherNode is a descendant of the node.
- */
- Node.DOCUMENT_POSITION_CONTAINED_BY = 16;
- /**
- * The result relies upon arbitrary and/or implementation-specific behavior and is not guaranteed to be portable.
- */
- Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 32;
- /**
- * the entry of DOM tree
- * Document -> Node -> EventTarget
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document
- */
- var Document = /*#__PURE__*/function (_Node) {
- _inheritsLoose(Document, _Node);
- function Document() {
- var _this;
- _this = _Node.call(this) || this;
- /**
- * only document has defaultView, points to canvas,
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView
- */
- _this.defaultView = null;
- /**
- * the root element of document, eg. <html>
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement
- */
- _this.documentElement = void 0;
- /**
- * document.timeline in WAAPI
- */
- _this.timeline = void 0;
- _this.ownerDocument = null;
- _this.nodeName = 'document';
- // create timeline
- try {
- _this.timeline = new runtime.AnimationTimeline(_assertThisInitialized(_this));
- } catch (e) {}
- /**
- * for inherited properties, the initial value is used on the root element only,
- * as long as no specified value is supplied.
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial_value
- */
- var initialStyle = {};
- BUILT_IN_PROPERTIES.forEach(function (_ref) {
- var n = _ref.n,
- inh = _ref.inh,
- d = _ref.d;
- if (inh && d) {
- initialStyle[n] = isFunction(d) ? d(exports.Shape.GROUP) : d;
- }
- });
- // like <html> in DOM tree
- _this.documentElement = new Group({
- id: 'g-root',
- style: initialStyle
- });
- _this.documentElement.ownerDocument = _assertThisInitialized(_this);
- _this.documentElement.parentNode = _assertThisInitialized(_this);
- _this.childNodes = [_this.documentElement];
- return _this;
- }
- var _proto = Document.prototype;
- /**
- * @example const circle = document.createElement('circle', { style: { r: 10 } });
- */
- _proto.createElement = function createElement(tagName, options) {
- // @observablehq/plot will create <svg>
- if (tagName === 'svg') {
- return this.documentElement;
- }
- // d3 will use <tspan>
- var clazz = this.defaultView.customElements.get(tagName);
- if (!clazz) {
- console.warn('Unsupported tagName: ', tagName);
- clazz = tagName === 'tspan' ? Text : Group;
- }
- var shape = new clazz(options);
- shape.ownerDocument = this;
- return shape;
- };
- _proto.createElementNS = function createElementNS(namespaceURI, tagName, options) {
- return this.createElement(tagName, options);
- };
- _proto.cloneNode = function cloneNode(deep) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.destroy = function destroy() {
- try {
- this.documentElement.destroyChildren();
- this.timeline.destroy();
- } catch (e) {}
- }
- /**
- * Picking 2D graphics with RBush based on BBox, fast but inaccurate.
- */;
- _proto.elementsFromBBox = function elementsFromBBox(minX, minY, maxX, maxY) {
- var rBush = this.defaultView.context.rBushRoot;
- var rBushNodes = rBush.search({
- minX: minX,
- minY: minY,
- maxX: maxX,
- maxY: maxY
- });
- var hitTestList = [];
- rBushNodes.forEach(function (_ref2) {
- var displayObject = _ref2.displayObject;
- var pointerEvents = displayObject.parsedStyle.pointerEvents;
- // account for `visibility`
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
- var isVisibilityAffected = ['auto', 'visiblepainted', 'visiblefill', 'visiblestroke', 'visible'].includes(pointerEvents);
- if ((!isVisibilityAffected || isVisibilityAffected && displayObject.isVisible()) && !displayObject.isCulled() && displayObject.isInteractive()) {
- hitTestList.push(displayObject);
- }
- });
- // find group with max z-index
- hitTestList.sort(function (a, b) {
- return b.sortable.renderOrder - a.sortable.renderOrder;
- });
- return hitTestList;
- };
- _proto.elementFromPointSync = function elementFromPointSync(x, y) {
- var _this$defaultView$can = this.defaultView.canvas2Viewport({
- x: x,
- y: y
- }),
- viewportX = _this$defaultView$can.x,
- viewportY = _this$defaultView$can.y;
- var _this$defaultView$get = this.defaultView.getConfig(),
- width = _this$defaultView$get.width,
- height = _this$defaultView$get.height;
- // outside canvas' viewport
- if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
- return null;
- }
- var _this$defaultView$vie = this.defaultView.viewport2Client({
- x: viewportX,
- y: viewportY
- }),
- clientX = _this$defaultView$vie.x,
- clientY = _this$defaultView$vie.y;
- var _this$defaultView$get2 = this.defaultView.getRenderingService().hooks.pickSync.call({
- topmost: true,
- position: {
- x: x,
- y: y,
- viewportX: viewportX,
- viewportY: viewportY,
- clientX: clientX,
- clientY: clientY
- },
- picked: []
- }),
- picked = _this$defaultView$get2.picked;
- return picked && picked[0] || this.documentElement;
- }
- /**
- * Do picking with API instead of triggering interactive events.
- *
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementFromPoint
- */;
- _proto.elementFromPoint =
- /*#__PURE__*/
- function () {
- var _elementFromPoint = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(x, y) {
- var _this$defaultView$can2, viewportX, viewportY, _this$defaultView$get3, width, height, _this$defaultView$vie2, clientX, clientY, _yield$this$defaultVi, picked;
- return _regeneratorRuntime().wrap(function _callee$(_context) {
- while (1) switch (_context.prev = _context.next) {
- case 0:
- _this$defaultView$can2 = this.defaultView.canvas2Viewport({
- x: x,
- y: y
- }), viewportX = _this$defaultView$can2.x, viewportY = _this$defaultView$can2.y;
- _this$defaultView$get3 = this.defaultView.getConfig(), width = _this$defaultView$get3.width, height = _this$defaultView$get3.height; // outside canvas' viewport
- if (!(viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height)) {
- _context.next = 4;
- break;
- }
- return _context.abrupt("return", null);
- case 4:
- _this$defaultView$vie2 = this.defaultView.viewport2Client({
- x: viewportX,
- y: viewportY
- }), clientX = _this$defaultView$vie2.x, clientY = _this$defaultView$vie2.y;
- _context.next = 7;
- return this.defaultView.getRenderingService().hooks.pick.promise({
- topmost: true,
- position: {
- x: x,
- y: y,
- viewportX: viewportX,
- viewportY: viewportY,
- clientX: clientX,
- clientY: clientY
- },
- picked: []
- });
- case 7:
- _yield$this$defaultVi = _context.sent;
- picked = _yield$this$defaultVi.picked;
- return _context.abrupt("return", picked && picked[0] || this.documentElement);
- case 10:
- case "end":
- return _context.stop();
- }
- }, _callee, this);
- }));
- function elementFromPoint(_x, _x2) {
- return _elementFromPoint.apply(this, arguments);
- }
- return elementFromPoint;
- }();
- _proto.elementsFromPointSync = function elementsFromPointSync(x, y) {
- var _this$defaultView$can3 = this.defaultView.canvas2Viewport({
- x: x,
- y: y
- }),
- viewportX = _this$defaultView$can3.x,
- viewportY = _this$defaultView$can3.y;
- var _this$defaultView$get4 = this.defaultView.getConfig(),
- width = _this$defaultView$get4.width,
- height = _this$defaultView$get4.height;
- // outside canvas' viewport
- if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
- return [];
- }
- var _this$defaultView$vie3 = this.defaultView.viewport2Client({
- x: viewportX,
- y: viewportY
- }),
- clientX = _this$defaultView$vie3.x,
- clientY = _this$defaultView$vie3.y;
- var _this$defaultView$get5 = this.defaultView.getRenderingService().hooks.pickSync.call({
- topmost: false,
- position: {
- x: x,
- y: y,
- viewportX: viewportX,
- viewportY: viewportY,
- clientX: clientX,
- clientY: clientY
- },
- picked: []
- }),
- picked = _this$defaultView$get5.picked;
- if (picked[picked.length - 1] !== this.documentElement) {
- picked.push(this.documentElement);
- }
- return picked;
- }
- /**
- * Do picking with API instead of triggering interactive events.
- *
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementsFromPoint
- */;
- _proto.elementsFromPoint =
- /*#__PURE__*/
- function () {
- var _elementsFromPoint = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(x, y) {
- var _this$defaultView$can4, viewportX, viewportY, _this$defaultView$get6, width, height, _this$defaultView$vie4, clientX, clientY, _yield$this$defaultVi2, picked;
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
- while (1) switch (_context2.prev = _context2.next) {
- case 0:
- _this$defaultView$can4 = this.defaultView.canvas2Viewport({
- x: x,
- y: y
- }), viewportX = _this$defaultView$can4.x, viewportY = _this$defaultView$can4.y;
- _this$defaultView$get6 = this.defaultView.getConfig(), width = _this$defaultView$get6.width, height = _this$defaultView$get6.height; // outside canvas' viewport
- if (!(viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height)) {
- _context2.next = 4;
- break;
- }
- return _context2.abrupt("return", []);
- case 4:
- _this$defaultView$vie4 = this.defaultView.viewport2Client({
- x: viewportX,
- y: viewportY
- }), clientX = _this$defaultView$vie4.x, clientY = _this$defaultView$vie4.y;
- _context2.next = 7;
- return this.defaultView.getRenderingService().hooks.pick.promise({
- topmost: false,
- position: {
- x: x,
- y: y,
- viewportX: viewportX,
- viewportY: viewportY,
- clientX: clientX,
- clientY: clientY
- },
- picked: []
- });
- case 7:
- _yield$this$defaultVi2 = _context2.sent;
- picked = _yield$this$defaultVi2.picked;
- if (picked[picked.length - 1] !== this.documentElement) {
- picked.push(this.documentElement);
- }
- return _context2.abrupt("return", picked);
- case 11:
- case "end":
- return _context2.stop();
- }
- }, _callee2, this);
- }));
- function elementsFromPoint(_x3, _x4) {
- return _elementsFromPoint.apply(this, arguments);
- }
- return elementsFromPoint;
- }()
- /**
- * eg. Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.
- */
- ;
- _proto.appendChild = function appendChild(newChild, index) {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.insertBefore = function insertBefore(newChild, refChild) {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.removeChild = function removeChild(oldChild, destroy) {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.replaceChild = function replaceChild(newChild, oldChild, destroy) {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.append = function append() {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- };
- _proto.prepend = function prepend() {
- throw new Error(ERROR_MSG_USE_DOCUMENT_ELEMENT);
- }
- /**
- * Execute query on documentElement.
- */;
- _proto.getElementById = function getElementById(id) {
- return this.documentElement.getElementById(id);
- };
- _proto.getElementsByName = function getElementsByName(name) {
- return this.documentElement.getElementsByName(name);
- };
- _proto.getElementsByTagName = function getElementsByTagName(tagName) {
- return this.documentElement.getElementsByTagName(tagName);
- };
- _proto.getElementsByClassName = function getElementsByClassName(className) {
- return this.documentElement.getElementsByClassName(className);
- };
- _proto.querySelector = function querySelector(selectors) {
- return this.documentElement.querySelector(selectors);
- };
- _proto.querySelectorAll = function querySelectorAll(selectors) {
- return this.documentElement.querySelectorAll(selectors);
- };
- _proto.find = function find(filter) {
- return this.documentElement.find(filter);
- };
- _proto.findAll = function findAll(filter) {
- return this.documentElement.findAll(filter);
- };
- _createClass(Document, [{
- key: "children",
- get: function get() {
- return this.childNodes;
- }
- }, {
- key: "childElementCount",
- get: function get() {
- return this.childNodes.length;
- }
- }, {
- key: "firstElementChild",
- get: function get() {
- return this.firstChild;
- }
- }, {
- key: "lastElementChild",
- get: function get() {
- return this.lastChild;
- }
- }]);
- return Document;
- }(Node);
- /**
- * built-in events for element
- * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent
- *
- * TODO: use MutationObserver instead
- * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
- */
- (function (ElementEvent) {
- ElementEvent["REPARENT"] = "reparent";
- ElementEvent["DESTROY"] = "destroy";
- /**
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMAttrModified
- */
- ElementEvent["ATTR_MODIFIED"] = "DOMAttrModified";
- /**
- * it has been inserted
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted
- */
- ElementEvent["INSERTED"] = "DOMNodeInserted";
- /**
- * it is being removed
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemoved
- */
- ElementEvent["REMOVED"] = "removed";
- /**
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnodeinsertedintodocument
- */
- ElementEvent["MOUNTED"] = "DOMNodeInsertedIntoDocument";
- /**
- * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnoderemovedfromdocument
- */
- ElementEvent["UNMOUNTED"] = "DOMNodeRemovedFromDocument";
- ElementEvent["BOUNDS_CHANGED"] = "bounds-changed";
- ElementEvent["CULLED"] = "culled";
- })(exports.ElementEvent || (exports.ElementEvent = {}));
- var MutationEvent = /*#__PURE__*/function (_FederatedEvent) {
- _inheritsLoose(MutationEvent, _FederatedEvent);
- function MutationEvent(typeArg, relatedNode, prevValue, newValue, attrName, attrChange, prevParsedValue, newParsedValue) {
- var _this;
- _this = _FederatedEvent.call(this, null) || this;
- _this.relatedNode = void 0;
- _this.prevValue = void 0;
- _this.newValue = void 0;
- _this.attrName = void 0;
- _this.attrChange = void 0;
- _this.prevParsedValue = void 0;
- _this.newParsedValue = void 0;
- _this.relatedNode = relatedNode;
- _this.prevValue = prevValue;
- _this.newValue = newValue;
- _this.attrName = attrName;
- _this.attrChange = attrChange;
- _this.prevParsedValue = prevParsedValue;
- _this.newParsedValue = newParsedValue;
- _this.type = typeArg;
- return _this;
- }
- return MutationEvent;
- }(FederatedEvent);
- MutationEvent.ADDITION = 2;
- MutationEvent.MODIFICATION = 1;
- MutationEvent.REMOVAL = 3;
- var entityCounter = 0;
- function resetEntityCounter() {
- entityCounter = 0;
- }
- var insertedEvent = new MutationEvent(exports.ElementEvent.INSERTED, null, '', '', '', 0, '', '');
- var removedEvent = new MutationEvent(exports.ElementEvent.REMOVED, null, '', '', '', 0, '', '');
- var destroyEvent = new CustomEvent(exports.ElementEvent.DESTROY);
- /**
- * Has following capabilities:
- * * Node insert/remove, eg. appendChild, removeChild, remove...
- * * Query eg. querySelector getElementById...
- * * Animation
- */
- var Element = /*#__PURE__*/function (_Node) {
- _inheritsLoose(Element, _Node);
- function Element() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _Node.call.apply(_Node, [this].concat(args)) || this;
- /**
- * Unique id.
- */
- _this.entity = entityCounter++;
- _this.renderable = {
- bounds: undefined,
- boundsDirty: true,
- renderBounds: undefined,
- renderBoundsDirty: true,
- dirtyRenderBounds: undefined,
- dirty: false,
- proxyNodeName: undefined
- };
- _this.cullable = {
- strategy: exports.Strategy.Standard,
- visibilityPlaneMask: -1,
- visible: true,
- enable: true
- };
- _this.transformable = {
- dirtyFlag: false,
- localDirtyFlag: false,
- frozen: false,
- localPosition: [0, 0, 0],
- localRotation: [0, 0, 0, 1],
- localScale: [1, 1, 1],
- localTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
- localSkew: [0, 0],
- position: [0, 0, 0],
- rotation: [0, 0, 0, 1],
- scaling: [1, 1, 1],
- worldTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
- origin: [0, 0, 0]
- };
- _this.sortable = {
- dirty: false,
- sorted: undefined,
- renderOrder: 0,
- dirtyChildren: [],
- dirtyReason: undefined
- };
- _this.geometry = {
- contentBounds: undefined,
- renderBounds: undefined
- };
- _this.rBushNode = {
- aabb: undefined
- };
- /**
- * used with `getElementById()`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/id
- */
- _this.id = void 0;
- /**
- * used in `getElementsByName`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
- */
- _this.name = void 0;
- /**
- * https://developer.mozilla.org/zh-CN/docs/Web/API/Element/namespaceURI
- */
- _this.namespaceURI = 'g';
- _this.scrollLeft = 0;
- _this.scrollTop = 0;
- /**
- * We don't support border now
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop
- */
- _this.clientTop = 0;
- _this.clientLeft = 0;
- /**
- * is destroyed or not
- */
- _this.destroyed = false;
- /**
- * compatible with `style`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
- */
- _this.style = {};
- _this.computedStyle = runtime.enableCSSParsing ? {
- anchor: unsetKeywordValue,
- opacity: unsetKeywordValue,
- fillOpacity: unsetKeywordValue,
- strokeOpacity: unsetKeywordValue,
- fill: unsetKeywordValue,
- stroke: unsetKeywordValue,
- transform: unsetKeywordValue,
- transformOrigin: unsetKeywordValue,
- visibility: unsetKeywordValue,
- pointerEvents: unsetKeywordValue,
- lineWidth: unsetKeywordValue,
- lineCap: unsetKeywordValue,
- lineJoin: unsetKeywordValue,
- increasedLineWidthForHitTesting: unsetKeywordValue,
- fontSize: unsetKeywordValue,
- fontFamily: unsetKeywordValue,
- fontStyle: unsetKeywordValue,
- fontWeight: unsetKeywordValue,
- fontVariant: unsetKeywordValue,
- textAlign: unsetKeywordValue,
- textBaseline: unsetKeywordValue,
- textTransform: unsetKeywordValue,
- zIndex: unsetKeywordValue,
- filter: unsetKeywordValue,
- shadowType: unsetKeywordValue
- } : null;
- /**
- * Renderers will use these used values.
- */
- _this.parsedStyle = {
- // opacity: '',
- // fillOpacity: '',
- // strokeOpacity: '',
- // transformOrigin: '',
- // visibility: '',
- // pointerEvents: '',
- // lineWidth: '',
- // lineCap: '',
- // lineJoin: '',
- // increasedLineWidthForHitTesting: '',
- // fontSize: '',
- // fontFamily: '',
- // fontStyle: '',
- // fontWeight: '',
- // fontVariant: '',
- // textAlign: '',
- // textBaseline: '',
- // textTransform: '',
- };
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes
- */
- _this.attributes = {};
- return _this;
- }
- Element.isElement = function isElement(target) {
- return !!target.getAttribute;
- };
- var _proto = Element.prototype;
- _proto.cloneNode = function cloneNode(deep) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.appendChild = function appendChild(child, index) {
- var _this$ownerDocument;
- if (child.destroyed) {
- throw new Error(ERROR_MSG_APPEND_DESTROYED_ELEMENT);
- }
- runtime.sceneGraphService.attach(child, this, index);
- if ((_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.defaultView) {
- this.ownerDocument.defaultView.mountChildren(child);
- }
- insertedEvent.relatedNode = this;
- child.dispatchEvent(insertedEvent);
- return child;
- };
- _proto.insertBefore = function insertBefore(newChild, refChild) {
- if (!refChild) {
- this.appendChild(newChild);
- } else {
- var index = this.childNodes.indexOf(refChild);
- this.appendChild(newChild, index - 1);
- }
- return newChild;
- };
- _proto.replaceChild = function replaceChild(newChild, oldChild) {
- var index = this.childNodes.indexOf(oldChild);
- this.removeChild(oldChild);
- this.appendChild(newChild, index);
- return oldChild;
- };
- _proto.removeChild = function removeChild(child) {
- var _child$ownerDocument;
- // should emit on itself before detach
- removedEvent.relatedNode = this;
- child.dispatchEvent(removedEvent);
- if ((_child$ownerDocument = child.ownerDocument) === null || _child$ownerDocument === void 0 ? void 0 : _child$ownerDocument.defaultView) {
- child.ownerDocument.defaultView.unmountChildren(child);
- }
- // remove from scene graph
- runtime.sceneGraphService.detach(child);
- return child;
- }
- /**
- * Remove all children which can be appended to its original parent later again.
- */;
- _proto.removeChildren = function removeChildren() {
- for (var i = this.childNodes.length - 1; i >= 0; i--) {
- var child = this.childNodes[i];
- this.removeChild(child);
- }
- }
- /**
- * Recursively destroy all children which can not be appended to its original parent later again.
- */;
- _proto.destroyChildren = function destroyChildren() {
- for (var i = this.childNodes.length - 1; i >= 0; i--) {
- var child = this.childNodes[i];
- if (child.childNodes.length) {
- child.destroyChildren();
- }
- child.destroy();
- }
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
- */;
- _proto.matches = function matches(selector) {
- return runtime.sceneGraphService.matches(selector, this);
- };
- _proto.getElementById = function getElementById(id) {
- return runtime.sceneGraphService.querySelector("#" + id, this);
- };
- _proto.getElementsByName = function getElementsByName(name) {
- return runtime.sceneGraphService.querySelectorAll("[name=\"" + name + "\"]", this);
- };
- _proto.getElementsByClassName = function getElementsByClassName(className) {
- return runtime.sceneGraphService.querySelectorAll("." + className, this);
- };
- _proto.getElementsByTagName = function getElementsByTagName(tagName) {
- return runtime.sceneGraphService.querySelectorAll(tagName, this);
- };
- _proto.querySelector = function querySelector(selectors) {
- return runtime.sceneGraphService.querySelector(selectors, this);
- };
- _proto.querySelectorAll = function querySelectorAll(selectors) {
- return runtime.sceneGraphService.querySelectorAll(selectors, this);
- }
- /**
- * should traverses the element and its parents (heading toward the document root)
- * until it finds a node that matches the specified CSS selector.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/closest
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#polyfill
- */;
- _proto.closest = function closest(selectors) {
- var el = this;
- do {
- if (runtime.sceneGraphService.matches(selectors, el)) return el;
- el = el.parentElement;
- } while (el !== null);
- return null;
- }
- /**
- * search in scene group, but should not include itself
- */;
- _proto.find = function find(filter) {
- var _this2 = this;
- var target = null;
- this.forEach(function (object) {
- if (object !== _this2 && filter(object)) {
- target = object;
- return true;
- }
- return false;
- });
- return target;
- };
- _proto.findAll = function findAll(filter) {
- var _this3 = this;
- var objects = [];
- this.forEach(function (object) {
- if (object !== _this3 && filter(object)) {
- objects.push(object);
- }
- });
- return objects;
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/after
- */;
- _proto.after = function after() {
- var _this4 = this;
- if (this.parentNode) {
- var index = this.parentNode.childNodes.indexOf(this);
- for (var _len2 = arguments.length, nodes = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
- nodes[_key2] = arguments[_key2];
- }
- nodes.forEach(function (node, i) {
- var _this4$parentNode;
- return (_this4$parentNode = _this4.parentNode) === null || _this4$parentNode === void 0 ? void 0 : _this4$parentNode.appendChild(node, index + i + 1);
- });
- }
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/before
- */;
- _proto.before = function before() {
- if (this.parentNode) {
- var index = this.parentNode.childNodes.indexOf(this);
- for (var _len3 = arguments.length, nodes = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
- nodes[_key3] = arguments[_key3];
- }
- var first = nodes[0],
- rest = nodes.slice(1);
- this.parentNode.appendChild(first, index);
- first.after.apply(first, rest);
- }
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceWith
- */;
- _proto.replaceWith = function replaceWith() {
- this.after.apply(this, arguments);
- this.remove();
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/append
- */;
- _proto.append = function append() {
- var _this5 = this;
- for (var _len4 = arguments.length, nodes = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
- nodes[_key4] = arguments[_key4];
- }
- nodes.forEach(function (node) {
- return _this5.appendChild(node);
- });
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/prepend
- */;
- _proto.prepend = function prepend() {
- var _this6 = this;
- for (var _len5 = arguments.length, nodes = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
- nodes[_key5] = arguments[_key5];
- }
- nodes.forEach(function (node, i) {
- return _this6.appendChild(node, i);
- });
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceChildren
- */;
- _proto.replaceChildren = function replaceChildren() {
- while (this.childNodes.length && this.firstChild) {
- this.removeChild(this.firstChild);
- }
- this.append.apply(this, arguments);
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/remove
- */;
- _proto.remove = function remove() {
- if (this.parentNode) {
- return this.parentNode.removeChild(this);
- }
- return this;
- };
- _proto.destroy = function destroy() {
- // destroy itself before remove
- this.dispatchEvent(destroyEvent);
- // remove from scenegraph first
- this.remove();
- // remove event listeners
- this.emitter.removeAllListeners();
- this.destroyed = true;
- };
- _proto.getGeometryBounds = function getGeometryBounds() {
- return runtime.sceneGraphService.getGeometryBounds(this);
- };
- _proto.getRenderBounds = function getRenderBounds() {
- return runtime.sceneGraphService.getBounds(this, true);
- }
- /**
- * get bounds in world space, account for children
- */;
- _proto.getBounds = function getBounds() {
- return runtime.sceneGraphService.getBounds(this);
- }
- /**
- * get bounds in local space, account for children
- */;
- _proto.getLocalBounds = function getLocalBounds() {
- return runtime.sceneGraphService.getLocalBounds(this);
- }
- /**
- * account for context's bounds in client space,
- * but not accounting for children
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
- */;
- _proto.getBoundingClientRect = function getBoundingClientRect() {
- return runtime.sceneGraphService.getBoundingClientRect(this);
- }
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getClientRects
- */;
- _proto.getClientRects = function getClientRects() {
- return [this.getBoundingClientRect()];
- };
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap
- * eg. circle.computedStyleMap().get('fill');
- */
- _proto.computedStyleMap = function computedStyleMap() {
- return new Map(Object.entries(this.computedStyle));
- };
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames
- */
- _proto.getAttributeNames = function getAttributeNames() {
- return Object.keys(this.attributes);
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
- */;
- _proto.getAttribute = function getAttribute(name) {
- // @see https://github.com/antvis/G/issues/1267
- if (isSymbol(name)) {
- return runtime.enableCSSParsing ? null : undefined;
- }
- var value = this.attributes[name];
- if (value === undefined) {
- var attributeName = formatAttributeName(name);
- value = this.attributes[attributeName];
- // if the given attribute does not exist, the value returned will either be null or ""
- return runtime.enableCSSParsing ? isNil(value) ? null : value : value;
- } else {
- return value;
- }
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
- */;
- _proto.hasAttribute = function hasAttribute(qualifiedName) {
- return this.getAttributeNames().includes(qualifiedName);
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes
- */;
- _proto.hasAttributes = function hasAttributes() {
- return !!this.getAttributeNames().length;
- }
- /**
- * should use removeAttribute() instead of setting the attribute value to null either directly or using setAttribute(). Many attributes will not behave as expected if you set them to null.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute
- */;
- _proto.removeAttribute = function removeAttribute(attributeName) {
- this.setAttribute(attributeName, null);
- delete this.attributes[attributeName];
- }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
- */;
- _proto.setAttribute = function setAttribute(attributeName, value, force) {
- this.attributes[attributeName] = value;
- };
- _proto.getAttributeNS = function getAttributeNS(namespace, localName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.getAttributeNode = function getAttributeNode(qualifiedName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.getAttributeNodeNS = function getAttributeNodeNS(namespace, localName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.hasAttributeNS = function hasAttributeNS(namespace, localName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.removeAttributeNS = function removeAttributeNS(namespace, localName) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.removeAttributeNode = function removeAttributeNode(attr) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.setAttributeNS = function setAttributeNS(namespace, qualifiedName, value) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.setAttributeNode = function setAttributeNode(attr) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.setAttributeNodeNS = function setAttributeNodeNS(attr) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.toggleAttribute = function toggleAttribute(qualifiedName, force) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _createClass(Element, [{
- key: "className",
- get:
- /**
- * used in `getElementsByClassName`
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
- */
- function get() {
- // @ts-ignore
- return this.getAttribute('class') || '';
- },
- set: function set(className) {
- this.setAttribute('class', className);
- }
- }, {
- key: "classList",
- get:
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
- */
- function get() {
- return this.className.split(' ').filter(function (c) {
- return c !== '';
- });
- }
- }, {
- key: "tagName",
- get: function get() {
- return this.nodeName;
- }
- }, {
- key: "children",
- get: function get() {
- return this.childNodes;
- }
- }, {
- key: "childElementCount",
- get: function get() {
- return this.childNodes.length;
- }
- }, {
- key: "firstElementChild",
- get: function get() {
- return this.firstChild;
- }
- }, {
- key: "lastElementChild",
- get: function get() {
- return this.lastChild;
- }
- }, {
- key: "parentElement",
- get: function get() {
- return this.parentNode;
- }
- }, {
- key: "nextSibling",
- get: function get() {
- if (this.parentNode) {
- var index = this.parentNode.childNodes.indexOf(this);
- return this.parentNode.childNodes[index + 1] || null;
- }
- return null;
- }
- }, {
- key: "previousSibling",
- get: function get() {
- if (this.parentNode) {
- var index = this.parentNode.childNodes.indexOf(this);
- return this.parentNode.childNodes[index - 1] || null;
- }
- return null;
- }
- }]);
- return Element;
- }(Node);
- var FederatedMouseEvent = /*#__PURE__*/function (_FederatedEvent) {
- _inheritsLoose(FederatedMouseEvent, _FederatedEvent);
- function FederatedMouseEvent() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _FederatedEvent.call.apply(_FederatedEvent, [this].concat(args)) || this;
- /** Whether the "alt" key was pressed when this mouse event occurred. */
- _this.altKey = void 0;
- /** The specific button that was pressed in this mouse event. */
- _this.button = void 0;
- /** The button depressed when this event occurred. */
- _this.buttons = void 0;
- /** Whether the "control" key was pressed when this mouse event occurred. */
- _this.ctrlKey = void 0;
- /** Whether the "meta" key was pressed when this mouse event occurred. */
- _this.metaKey = void 0;
- /** This is currently not implemented in the Federated Events API. */
- _this.relatedTarget = void 0;
- /** Whether the "shift" key was pressed when this mouse event occurred. */
- _this.shiftKey = void 0;
- /**
- * The coordinates of the mouse event relative to the canvas.
- */
- _this.client = new Point();
- /**
- * The movement in this pointer relative to the last `mousemove` event.
- */
- _this.movement = new Point();
- /**
- * The offset of the pointer coordinates w.r.t. target DisplayObject in world space. This is
- * not supported at the moment.
- */
- _this.offset = new Point();
- /**
- * The pointer coordinates in world space.
- */
- _this.global = new Point();
- /**
- * The pointer coordinates in sceen space.
- */
- _this.screen = new Point();
- return _this;
- }
- var _proto = FederatedMouseEvent.prototype;
- _proto.getModifierState = function getModifierState(key) {
- return 'getModifierState' in this.nativeEvent && this.nativeEvent.getModifierState(key);
- };
- _proto.initMouseEvent = function initMouseEvent() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _createClass(FederatedMouseEvent, [{
- key: "clientX",
- get: function get() {
- return this.client.x;
- }
- }, {
- key: "clientY",
- get: function get() {
- return this.client.y;
- }
- }, {
- key: "movementX",
- get: function get() {
- return this.movement.x;
- }
- }, {
- key: "movementY",
- get: function get() {
- return this.movement.y;
- }
- }, {
- key: "offsetX",
- get: function get() {
- return this.offset.x;
- }
- }, {
- key: "offsetY",
- get: function get() {
- return this.offset.y;
- }
- }, {
- key: "globalX",
- get: function get() {
- return this.global.x;
- }
- }, {
- key: "globalY",
- get: function get() {
- return this.global.y;
- }
- }, {
- key: "screenX",
- get: function get() {
- return this.screen.x;
- }
- }, {
- key: "screenY",
- get: function get() {
- return this.screen.y;
- }
- }]);
- return FederatedMouseEvent;
- }(FederatedEvent);
- var FederatedPointerEvent = /*#__PURE__*/function (_FederatedMouseEvent) {
- _inheritsLoose(FederatedPointerEvent, _FederatedMouseEvent);
- function FederatedPointerEvent() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _FederatedMouseEvent.call.apply(_FederatedMouseEvent, [this].concat(args)) || this;
- /**
- * The unique identifier of the pointer.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
- */
- _this.pointerId = void 0;
- /**
- * The width of the pointer's contact along the x-axis, measured in CSS pixels.
- * radiusX of TouchEvents will be represented by this value.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width
- */
- _this.width = 0;
- /**
- * The height of the pointer's contact along the y-axis, measured in CSS pixels.
- * radiusY of TouchEvents will be represented by this value.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height
- */
- _this.height = 0;
- /**
- * Indicates whether or not the pointer device that created the event is the primary pointer.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary
- */
- _this.isPrimary = false;
- /**
- * The type of pointer that triggered the event.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType
- */
- _this.pointerType = void 0;
- /**
- * Pressure applied by the pointing device during the event.
- *s
- * A Touch's force property will be represented by this value.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
- */
- _this.pressure = void 0;
- /**
- * Barrel pressure on a stylus pointer.
- *
- * @see https://w3c.github.io/pointerevents/#pointerevent-interface
- */
- _this.tangentialPressure = void 0;
- /**
- * The angle, in degrees, between the pointer device and the screen.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX
- */
- _this.tiltX = void 0;
- /**
- * The angle, in degrees, between the pointer device and the screen.
- *
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY
- */
- _this.tiltY = void 0;
- /**
- * Twist of a stylus pointer.
- *
- * @see https://w3c.github.io/pointerevents/#pointerevent-interface
- */
- _this.twist = void 0;
- return _this;
- }
- var _proto = FederatedPointerEvent.prototype;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/getCoalescedEvents
- */
- _proto.getCoalescedEvents = function getCoalescedEvents() {
- if (this.type === 'pointermove' || this.type === 'mousemove' || this.type === 'touchmove') {
- return [this];
- }
- return [];
- }
- /**
- * @see https://chromestatus.com/feature/5765569655603200
- */;
- _proto.getPredictedEvents = function getPredictedEvents() {
- throw new Error('getPredictedEvents is not supported!');
- }
- /**
- * @see https://github.com/antvis/G/issues/1115
- * We currently reuses event objects in the event system,
- * avoiding the creation of a large number of event objects.
- * Reused objects are only used to carry different data,
- * such as coordinate information, native event objects,
- * and therefore the lifecycle is limited to the event handler,
- * which can lead to unintended consequences if an attempt is made to cache the entire event object.
- *
- * Therefore, while keeping the above performance considerations in mind, it is possible to provide a clone method that creates a new object when the user really wants to cache it, e.g.
- */;
- _proto.clone = function clone() {
- return this.manager.clonePointerEvent(this);
- };
- return FederatedPointerEvent;
- }(FederatedMouseEvent);
- var FederatedWheelEvent = /*#__PURE__*/function (_FederatedMouseEvent) {
- _inheritsLoose(FederatedWheelEvent, _FederatedMouseEvent);
- function FederatedWheelEvent() {
- var _this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- _this = _FederatedMouseEvent.call.apply(_FederatedMouseEvent, [this].concat(args)) || this;
- /**
- * The units of `deltaX`, `deltaY`, and `deltaZ`. This is one of `DOM_DELTA_LINE`,
- * `DOM_DELTA_PAGE`, `DOM_DELTA_PIXEL`.
- */
- _this.deltaMode = void 0;
- /** Horizontal scroll amount */
- _this.deltaX = void 0;
- /** Vertical scroll amount */
- _this.deltaY = void 0;
- /** z-axis scroll amount. */
- _this.deltaZ = void 0;
- /** Units specified in lines. */
- _this.DOM_DELTA_LINE = 0;
- /** Units specified in pages. */
- _this.DOM_DELTA_PAGE = 1;
- /** Units specified in pixels. */
- _this.DOM_DELTA_PIXEL = 2;
- return _this;
- }
- var _proto = FederatedWheelEvent.prototype;
- _proto.clone = function clone() {
- return this.manager.cloneWheelEvent(this);
- };
- return FederatedWheelEvent;
- }(FederatedMouseEvent);
- function isDisplayObject(value) {
- return !!(value === null || value === void 0 ? void 0 : value.nodeName);
- }
- var mutationEvent = new MutationEvent(exports.ElementEvent.ATTR_MODIFIED, null, null, null, null, MutationEvent.MODIFICATION, null, null);
- var DEFAULT_STYLE_PROPS = {
- anchor: '',
- opacity: '',
- fillOpacity: '',
- strokeOpacity: '',
- fill: '',
- stroke: '',
- transform: '',
- transformOrigin: '',
- visibility: '',
- pointerEvents: '',
- lineWidth: '',
- lineCap: '',
- lineJoin: '',
- increasedLineWidthForHitTesting: '',
- fontSize: '',
- fontFamily: '',
- fontStyle: '',
- fontWeight: '',
- fontVariant: '',
- textAlign: '',
- textBaseline: '',
- textTransform: '',
- zIndex: '',
- filter: '',
- shadowType: ''
- };
- var DEFAULT_PARSED_STYLE_PROPS = {
- anchor: [0, 0],
- fill: noneColor,
- stroke: noneColor,
- transform: [],
- zIndex: 0,
- filter: [],
- shadowType: 'outer',
- miterLimit: 10
- };
- var DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED = _extends({}, DEFAULT_PARSED_STYLE_PROPS, {
- opacity: 1,
- fillOpacity: 1,
- strokeOpacity: 1,
- visibility: 'visible',
- pointerEvents: 'auto',
- lineWidth: 1,
- lineCap: 'butt',
- lineJoin: 'miter',
- increasedLineWidthForHitTesting: 0,
- fillRule: 'nonzero'
- // TODO: transformOrigin
- });
- var INHERITABLE_BASE_STYLE_PROPS = ['opacity', 'fillOpacity', 'strokeOpacity', 'transformOrigin', 'visibility', 'pointerEvents', 'lineWidth', 'lineCap', 'lineJoin', 'increasedLineWidthForHitTesting'];
- var INHERITABLE_STYLE_PROPS = [].concat(INHERITABLE_BASE_STYLE_PROPS, ['fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'fontVariant', 'textAlign', 'textBaseline', 'textTransform']);
- var DATASET_PREFIX = 'data-';
- /**
- * prototype chains: DisplayObject -> Element -> Node -> EventTarget
- *
- * mixins: Animatable, Transformable, Visible
- * @see https://github.com/tannerntannern/ts-mixer/blob/master/README.md#mixing-generic-classes
- *
- * Provide abilities in scene graph, such as:
- * * transform `translate/rotate/scale`
- * * add/remove child
- * * visibility and z-index
- *
- * Those abilities are implemented with those components: `Transform/Sortable/Visible`.
- *
- * Emit following events:
- * * init
- * * destroy
- * * attributeChanged
- */
- var DisplayObject = /*#__PURE__*/function (_Element) {
- _inheritsLoose(DisplayObject, _Element);
- function DisplayObject(config) {
- var _this$config$capture;
- var _this;
- _this = _Element.call(this) || this;
- // assign name, id to config
- // eg. group.get('name')
- /**
- * contains style props in constructor's params, eg. fill, stroke...
- */
- _this.config = void 0;
- _this.isCustomElement = false;
- _this.isMutationObserved = false;
- /**
- * push to active animations after calling `animate()`
- */
- _this.activeAnimations = [];
- /**
- * Use data-* attribute.
- * @see https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
- * @example
- * group.dataset.prop1 = 1;
- * group.getAttribute('data-prop1'); // 1
- */
- _this.dataset = void 0;
- /**
- * Use `this.style.clipPath` instead.
- * @deprecated
- */
- _this.getClip = function () {
- return this.style.clipPath || null;
- };
- _this.config = config;
- // compatible with G 3.0
- _this.config.interactive = (_this$config$capture = _this.config.capture) !== null && _this$config$capture !== void 0 ? _this$config$capture : _this.config.interactive;
- // init scene graph node
- _this.id = _this.config.id || '';
- _this.name = _this.config.name || '';
- if (_this.config.className || _this.config.class) {
- _this.className = _this.config.className || _this.config.class;
- }
- _this.nodeName = _this.config.type || exports.Shape.GROUP;
- // compatible with G 3.0
- _this.config.style = _this.config.style || _this.config.attrs || {};
- Object.assign(_this.config.style, _this.config.attrs);
- // this.config.style = {
- // // ...DEFAULT_STYLE_PROPS,
- // ...this.config.style,
- // ...this.config.attrs,
- // };
- if (_this.config.visible != null) {
- _this.config.style.visibility = _this.config.visible === false ? 'hidden' : 'visible';
- }
- if (_this.config.interactive != null) {
- _this.config.style.pointerEvents = _this.config.interactive === false ? 'none' : 'auto';
- }
- // merge parsed value
- Object.assign(_this.parsedStyle, runtime.enableCSSParsing ? DEFAULT_PARSED_STYLE_PROPS : DEFAULT_PARSED_STYLE_PROPS_CSS_DISABLED, _this.config.initialParsedStyle);
- if (runtime.enableCSSParsing) {
- Object.assign(_this.attributes, DEFAULT_STYLE_PROPS);
- }
- // start to process attributes
- _this.initAttributes(_this.config.style);
- var Proxy = runtime.globalThis.Proxy ? runtime.globalThis.Proxy : function () {};
- if (runtime.enableDataset) {
- _this.dataset = new Proxy({}, {
- get: function get(target, name) {
- var formattedName = "" + DATASET_PREFIX + kebabize(name);
- if (target[formattedName] !== undefined) {
- return target[formattedName];
- }
- return _this.getAttribute(formattedName);
- },
- set: function set(_, prop, value) {
- _this.setAttribute("" + DATASET_PREFIX + kebabize(prop), value);
- return true;
- }
- });
- }
- if (runtime.enableStyleSyntax) {
- _this.style = new Proxy(
- // @ts-ignore
- {
- // ...this.attributes,
- setProperty: function setProperty(propertyName, value) {
- _this.setAttribute(propertyName, value);
- },
- getPropertyValue: function getPropertyValue(propertyName) {
- return _this.getAttribute(propertyName);
- },
- removeProperty: function removeProperty(propertyName) {
- _this.removeAttribute(propertyName);
- },
- item: function item() {
- return '';
- }
- }, {
- get: function get(target, name) {
- if (target[name] !== undefined) {
- // if (name in target) {
- return target[name];
- }
- return _this.getAttribute(name);
- },
- set: function set(_, prop, value) {
- _this.setAttribute(prop, value);
- return true;
- }
- });
- }
- return _this;
- }
- var _proto = DisplayObject.prototype;
- _proto.destroy = function destroy() {
- _Element.prototype.destroy.call(this);
- // stop all active animations
- this.getAnimations().forEach(function (animation) {
- animation.cancel();
- });
- // FIXME
- // this.renderable = null;
- // this.cullable = null;
- // this.transformable = null;
- // this.rBushNode = null;
- // this.geometry = null;
- // this.sortable = null;
- };
- _proto.cloneNode = function cloneNode(deep, customCloneFunc) {
- var clonedStyle = _extends({}, this.attributes);
- for (var attributeName in clonedStyle) {
- var attribute = clonedStyle[attributeName];
- // @see https://github.com/antvis/G/issues/1095
- if (isDisplayObject(attribute) &&
- // share the same clipPath if possible
- attributeName !== 'clipPath' && attributeName !== 'offsetPath' && attributeName !== 'textPath') {
- clonedStyle[attributeName] = attribute.cloneNode(deep);
- }
- // TODO: clone other type
- if (customCloneFunc) {
- clonedStyle[attributeName] = customCloneFunc(attributeName, attribute);
- }
- }
- var cloned = new this.constructor({
- // copy id & name
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode#notes
- id: this.id,
- name: this.name,
- className: this.name,
- interactive: this.interactive,
- style: clonedStyle
- });
- // apply transform
- cloned.setLocalTransform(this.getLocalTransform());
- if (deep) {
- this.children.forEach(function (child) {
- // skip marker
- if (!child.style.isMarker) {
- var clonedChild = child.cloneNode(deep);
- cloned.appendChild(clonedChild);
- }
- });
- }
- return cloned;
- };
- _proto.initAttributes = function initAttributes(attributes) {
- if (attributes === void 0) {
- attributes = {};
- }
- var renderable = this.renderable;
- var options = {
- forceUpdateGeometry: true
- // usedAttributes:
- // // only Group / Text should account for text relative props
- // this.tagName === Shape.GROUP || this.tagName === Shape.TEXT
- // ? INHERITABLE_STYLE_PROPS
- // : INHERITABLE_BASE_STYLE_PROPS,
- };
- if (runtime.enableCSSParsing) {
- // @ts-ignore
- options.usedAttributes = INHERITABLE_STYLE_PROPS;
- }
- // account for FCP, process properties as less as possible
- var formattedAttributes = {};
- for (var name in attributes) {
- var attributeName = formatAttributeName(name);
- formattedAttributes[attributeName] = attributes[name];
- }
- runtime.styleValueRegistry.processProperties(this, formattedAttributes, options);
- // redraw at next frame
- renderable.dirty = true;
- };
- _proto.setAttribute = function setAttribute(name, value, force) {
- if (force === void 0) {
- force = false;
- }
- var attributeName = formatAttributeName(name);
- // ignore undefined value
- if (isUndefined(value)) {
- return;
- }
- if (force || value !== this.attributes[attributeName]) {
- this.internalSetAttribute(attributeName, value);
- _Element.prototype.setAttribute.call(this, attributeName, value);
- }
- }
- /**
- * called when attributes get changed or initialized
- */;
- _proto.internalSetAttribute = function internalSetAttribute(name, value, parseOptions) {
- var _runtime$styleValueRe;
- if (parseOptions === void 0) {
- parseOptions = {};
- }
- var renderable = this.renderable;
- var oldValue = this.attributes[name];
- var oldParsedValue = this.parsedStyle[name];
- runtime.styleValueRegistry.processProperties(this, (_runtime$styleValueRe = {}, _runtime$styleValueRe[name] = value, _runtime$styleValueRe), parseOptions);
- // redraw at next frame
- renderable.dirty = true;
- var newParsedValue = this.parsedStyle[name];
- if (this.isConnected) {
- mutationEvent.relatedNode = this;
- mutationEvent.prevValue = oldValue;
- mutationEvent.newValue = value;
- mutationEvent.attrName = name;
- mutationEvent.prevParsedValue = oldParsedValue;
- mutationEvent.newParsedValue = newParsedValue;
- if (this.isMutationObserved) {
- this.dispatchEvent(mutationEvent);
- } else {
- mutationEvent.target = this;
- this.ownerDocument.defaultView.dispatchEvent(mutationEvent, true);
- }
- }
- if ((this.isCustomElement && this.isConnected || !this.isCustomElement) && this.attributeChangedCallback) {
- this.attributeChangedCallback(name, oldValue, value, oldParsedValue, newParsedValue);
- }
- }
- // #region transformable
- /**
- * returns different values than getBoundingClientRect(), as the latter returns value relative to the viewport
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox
- *
- * FIXME: It is worth noting that getBBox responds to original untransformed values of a drawn object.
- * @see https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#getBBox
- */;
- _proto.getBBox = function getBBox() {
- var aabb = this.getBounds();
- var _aabb$getMin = aabb.getMin(),
- left = _aabb$getMin[0],
- top = _aabb$getMin[1];
- var _aabb$getMax = aabb.getMax(),
- right = _aabb$getMax[0],
- bottom = _aabb$getMax[1];
- return new Rectangle(left, top, right - left, bottom - top);
- };
- _proto.setOrigin = function setOrigin(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.setOrigin(this, createVec3(position, y, z));
- return this;
- };
- _proto.getOrigin = function getOrigin() {
- return runtime.sceneGraphService.getOrigin(this);
- }
- /**
- * set position in world space
- */;
- _proto.setPosition = function setPosition(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.setPosition(this, createVec3(position, y, z));
- return this;
- }
- /**
- * set position in local space
- */;
- _proto.setLocalPosition = function setLocalPosition(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.setLocalPosition(this, createVec3(position, y, z));
- return this;
- }
- /**
- * translate in world space
- */;
- _proto.translate = function translate(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.translate(this, createVec3(position, y, z));
- return this;
- }
- /**
- * translate in local space
- */;
- _proto.translateLocal = function translateLocal(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- runtime.sceneGraphService.translateLocal(this, createVec3(position, y, z));
- return this;
- };
- _proto.getPosition = function getPosition() {
- return runtime.sceneGraphService.getPosition(this);
- };
- _proto.getLocalPosition = function getLocalPosition() {
- return runtime.sceneGraphService.getLocalPosition(this);
- }
- /**
- * compatible with G 3.0
- *
- * scaling in local space
- * scale(10) = scale(10, 10, 10)
- *
- * we can't set scale in world space
- */;
- _proto.scale = function scale(scaling, y, z) {
- return this.scaleLocal(scaling, y, z);
- };
- _proto.scaleLocal = function scaleLocal(scaling, y, z) {
- if (typeof scaling === 'number') {
- y = y || scaling;
- z = z || scaling;
- scaling = createVec3(scaling, y, z);
- }
- runtime.sceneGraphService.scaleLocal(this, scaling);
- return this;
- }
- /**
- * set scaling in local space
- */;
- _proto.setLocalScale = function setLocalScale(scaling, y, z) {
- if (typeof scaling === 'number') {
- y = y || scaling;
- z = z || scaling;
- scaling = createVec3(scaling, y, z);
- }
- runtime.sceneGraphService.setLocalScale(this, scaling);
- return this;
- }
- /**
- * get scaling in local space
- */;
- _proto.getLocalScale = function getLocalScale() {
- return runtime.sceneGraphService.getLocalScale(this);
- }
- /**
- * get scaling in world space
- */;
- _proto.getScale = function getScale() {
- return runtime.sceneGraphService.getScale(this);
- }
- /**
- * only return degrees of Z axis in world space
- */;
- _proto.getEulerAngles = function getEulerAngles() {
- var _getEuler = getEuler(create$2(), runtime.sceneGraphService.getWorldTransform(this)),
- ez = _getEuler[2];
- return rad2deg(ez);
- }
- /**
- * only return degrees of Z axis in local space
- */;
- _proto.getLocalEulerAngles = function getLocalEulerAngles() {
- var _getEuler2 = getEuler(create$2(), runtime.sceneGraphService.getLocalRotation(this)),
- ez = _getEuler2[2];
- return rad2deg(ez);
- }
- /**
- * set euler angles(degrees) in world space
- */;
- _proto.setEulerAngles = function setEulerAngles(z) {
- runtime.sceneGraphService.setEulerAngles(this, 0, 0, z);
- return this;
- }
- /**
- * set euler angles(degrees) in local space
- */;
- _proto.setLocalEulerAngles = function setLocalEulerAngles(z) {
- runtime.sceneGraphService.setLocalEulerAngles(this, 0, 0, z);
- return this;
- };
- _proto.rotateLocal = function rotateLocal(x, y, z) {
- if (isNil(y) && isNil(z)) {
- runtime.sceneGraphService.rotateLocal(this, 0, 0, x);
- } else {
- runtime.sceneGraphService.rotateLocal(this, x, y, z);
- }
- return this;
- };
- _proto.rotate = function rotate(x, y, z) {
- if (isNil(y) && isNil(z)) {
- runtime.sceneGraphService.rotate(this, 0, 0, x);
- } else {
- runtime.sceneGraphService.rotate(this, x, y, z);
- }
- return this;
- };
- _proto.setRotation = function setRotation(rotation, y, z, w) {
- runtime.sceneGraphService.setRotation(this, rotation, y, z, w);
- return this;
- };
- _proto.setLocalRotation = function setLocalRotation(rotation, y, z, w) {
- runtime.sceneGraphService.setLocalRotation(this, rotation, y, z, w);
- return this;
- };
- _proto.setLocalSkew = function setLocalSkew(skew, y) {
- runtime.sceneGraphService.setLocalSkew(this, skew, y);
- return this;
- };
- _proto.getRotation = function getRotation() {
- return runtime.sceneGraphService.getRotation(this);
- };
- _proto.getLocalRotation = function getLocalRotation() {
- return runtime.sceneGraphService.getLocalRotation(this);
- };
- _proto.getLocalSkew = function getLocalSkew() {
- return runtime.sceneGraphService.getLocalSkew(this);
- };
- _proto.getLocalTransform = function getLocalTransform() {
- return runtime.sceneGraphService.getLocalTransform(this);
- };
- _proto.getWorldTransform = function getWorldTransform() {
- return runtime.sceneGraphService.getWorldTransform(this);
- };
- _proto.setLocalTransform = function setLocalTransform(transform) {
- runtime.sceneGraphService.setLocalTransform(this, transform);
- return this;
- };
- _proto.resetLocalTransform = function resetLocalTransform() {
- runtime.sceneGraphService.resetLocalTransform(this);
- }
- // #endregion transformable
- // #region animatable
- /**
- * returns an array of all Animation objects affecting this element
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAnimations
- */;
- _proto.getAnimations = function getAnimations() {
- return this.activeAnimations;
- }
- /**
- * create an animation with WAAPI
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/animate
- */;
- _proto.animate = function animate(keyframes, options) {
- var _this$ownerDocument;
- var timeline = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : _this$ownerDocument.timeline;
- if (timeline) {
- return timeline.play(this, keyframes, options);
- }
- return null;
- }
- // #endregion animatable
- // #region visible
- /**
- * shortcut for Used value of `visibility`
- */;
- _proto.isVisible = function isVisible() {
- var _this$parsedStyle;
- return ((_this$parsedStyle = this.parsedStyle) === null || _this$parsedStyle === void 0 ? void 0 : _this$parsedStyle.visibility) === 'visible';
- };
- _proto.isInteractive = function isInteractive() {
- var _this$parsedStyle2;
- return ((_this$parsedStyle2 = this.parsedStyle) === null || _this$parsedStyle2 === void 0 ? void 0 : _this$parsedStyle2.pointerEvents) !== 'none';
- };
- _proto.isCulled = function isCulled() {
- return !!(this.cullable && this.cullable.enable && !this.cullable.visible);
- }
- /**
- * bring to front in current group
- */;
- _proto.toFront = function toFront() {
- if (this.parentNode) {
- this.style.zIndex = Math.max.apply(Math, this.parentNode.children.map(function (child) {
- return Number(child.style.zIndex);
- })) + 1;
- }
- return this;
- }
- /**
- * send to back in current group
- */;
- _proto.toBack = function toBack() {
- if (this.parentNode) {
- this.style.zIndex = Math.min.apply(Math, this.parentNode.children.map(function (child) {
- return Number(child.style.zIndex);
- })) - 1;
- }
- return this;
- }
- // #endregion visible
- // #region deprecated
- /**
- * compatible with G 3.0
- * @alias object.config
- * @deprecated
- */;
- _proto.getConfig = function getConfig() {
- return this.config;
- };
- _proto.attr = function attr() {
- var _this2 = this;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
- var name = args[0],
- value = args[1];
- if (!name) {
- return this.attributes;
- }
- if (isObject(name)) {
- Object.keys(name).forEach(function (key) {
- _this2.setAttribute(key, name[key]);
- });
- return this;
- }
- if (args.length === 2) {
- this.setAttribute(name, value);
- return this;
- }
- return this.attributes[name];
- }
- /**
- * return 3x3 matrix in world space
- * @deprecated
- */;
- _proto.getMatrix = function getMatrix(transformMat4) {
- var transform = transformMat4 || this.getWorldTransform();
- var _mat4$getTranslation = getTranslation(create$2(), transform),
- tx = _mat4$getTranslation[0],
- ty = _mat4$getTranslation[1];
- var _mat4$getScaling = getScaling(create$2(), transform),
- sx = _mat4$getScaling[0],
- sy = _mat4$getScaling[1];
- var rotation = getRotation(create$4(), transform);
- var _getEuler3 = getEuler(create$2(), rotation),
- eux = _getEuler3[0],
- euz = _getEuler3[2];
- // gimbal lock at 90 degrees
- return fromRotationTranslationScale$1(eux || euz, tx, ty, sx, sy);
- }
- /**
- * return 3x3 matrix in local space
- * @deprecated
- */;
- _proto.getLocalMatrix = function getLocalMatrix() {
- return this.getMatrix(this.getLocalTransform());
- }
- /**
- * set 3x3 matrix in world space
- * @deprecated
- */;
- _proto.setMatrix = function setMatrix(mat) {
- var _decompose = decompose(mat),
- tx = _decompose[0],
- ty = _decompose[1],
- scalingX = _decompose[2],
- scalingY = _decompose[3],
- angle = _decompose[4];
- this.setEulerAngles(angle).setPosition(tx, ty).setLocalScale(scalingX, scalingY);
- }
- /**
- * set 3x3 matrix in local space
- * @deprecated
- */;
- _proto.setLocalMatrix = function setLocalMatrix(mat) {
- var _decompose2 = decompose(mat),
- tx = _decompose2[0],
- ty = _decompose2[1],
- scalingX = _decompose2[2],
- scalingY = _decompose2[3],
- angle = _decompose2[4];
- this.setLocalEulerAngles(angle).setLocalPosition(tx, ty).setLocalScale(scalingX, scalingY);
- }
- /**
- * Use `visibility: visible` instead.
- * @deprecated
- */;
- _proto.show = function show() {
- if (runtime.enableCSSParsing) {
- this.style.visibility = 'visible';
- } else {
- this.forEach(function (object) {
- object.style.visibility = 'visible';
- });
- }
- }
- /**
- * Use `visibility: hidden` instead.
- * @deprecated
- */;
- _proto.hide = function hide() {
- if (runtime.enableCSSParsing) {
- this.style.visibility = 'hidden';
- } else {
- this.forEach(function (object) {
- object.style.visibility = 'hidden';
- });
- }
- }
- /**
- * Use `childElementCount` instead.
- * @deprecated
- */;
- _proto.getCount = function getCount() {
- return this.childElementCount;
- }
- /**
- * Use `parentElement` instead.
- * @deprecated
- */;
- _proto.getParent = function getParent() {
- return this.parentElement;
- }
- /**
- * Use `children` instead.
- * @deprecated
- */;
- _proto.getChildren = function getChildren() {
- return this.children;
- }
- /**
- * Use `firstElementChild` instead.
- * @deprecated
- */;
- _proto.getFirst = function getFirst() {
- return this.firstElementChild;
- }
- /**
- * Use `lastElementChild` instead.
- * @deprecated
- */;
- _proto.getLast = function getLast() {
- return this.lastElementChild;
- }
- /**
- * Use `this.children[index]` instead.
- * @deprecated
- */;
- _proto.getChildByIndex = function getChildByIndex(index) {
- return this.children[index] || null;
- }
- /**
- * Use `appendChild` instead.
- * @deprecated
- */;
- _proto.add = function add(child, index) {
- return this.appendChild(child, index);
- }
- /**
- * Use `this.style.clipPath` instead.
- * @deprecated
- */;
- _proto.setClip = function setClip(clipPath) {
- this.style.clipPath = clipPath;
- };
- /**
- * @deprecated
- */
- _proto.set = function set(name, value) {
- // @ts-ignore
- this.config[name] = value;
- }
- /**
- * @deprecated
- */;
- _proto.get = function get(name) {
- return this.config[name];
- }
- /**
- * Use `setPosition` instead.
- * @deprecated
- */;
- _proto.moveTo = function moveTo(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- this.setPosition(position, y, z);
- return this;
- }
- /**
- * Use `setPosition` instead.
- * @deprecated
- */;
- _proto.move = function move(position, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- this.setPosition(position, y, z);
- return this;
- }
- /**
- * Use `this.style.zIndex` instead.
- * @deprecated
- */;
- _proto.setZIndex = function setZIndex(zIndex) {
- this.style.zIndex = zIndex;
- return this;
- };
- _createClass(DisplayObject, [{
- key: "interactive",
- get: function get() {
- return this.isInteractive();
- },
- set: function set(b) {
- this.style.pointerEvents = b ? 'auto' : 'none';
- }
- }]);
- return DisplayObject;
- }(Element);
- var _excluded = ["style"];
- var Circle = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Circle, _DisplayObject);
- function Circle(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded);
- return _DisplayObject.call(this, _extends({
- type: exports.Shape.CIRCLE,
- style: runtime.enableCSSParsing ? _extends({
- cx: '',
- cy: '',
- r: ''
- }, style) : _extends({}, style),
- initialParsedStyle: {
- anchor: [0.5, 0.5],
- transformOrigin: runtime.enableCSSParsing ? null : [PECENTAGE_50, PECENTAGE_50]
- }
- }, rest)) || this;
- }
- return Circle;
- }(DisplayObject);
- var _excluded$1 = ["style"];
- /**
- * shadow root
- * @see https://yuque.antfin-inc.com/antv/czqvg5/pgqipg
- */
- var CustomElement = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(CustomElement, _DisplayObject);
- // private shadowNodes: DisplayObject[] = [];
- function CustomElement(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$1);
- _this = _DisplayObject.call(this, _extends({
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- // static get observedAttributes(): string[] {
- // return [];
- // }
- _this.isCustomElement = true;
- return _this;
- }
- return CustomElement;
- }(DisplayObject);
- var _excluded$2 = ["style"];
- var Ellipse = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Ellipse, _DisplayObject);
- function Ellipse(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$2);
- return _DisplayObject.call(this, _extends({
- type: exports.Shape.ELLIPSE,
- style: runtime.enableCSSParsing ? _extends({
- cx: '',
- cy: '',
- rx: '',
- ry: ''
- }, style) : _extends({}, style),
- initialParsedStyle: {
- anchor: [0.5, 0.5],
- transformOrigin: runtime.enableCSSParsing ? null : [PECENTAGE_50, PECENTAGE_50]
- }
- }, rest)) || this;
- }
- return Ellipse;
- }(DisplayObject);
- var _excluded$3 = ["style"];
- /**
- * its attributes are inherited by its children.
- * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g
- *
- * @example
- * <g fill="white" stroke="green" stroke-width="5">
- <circle cx="40" cy="40" r="25" />
- <circle cx="60" cy="60" r="25" />
- </g>
- */
- var Group = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Group, _DisplayObject);
- function Group(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$3);
- return _DisplayObject.call(this, _extends({
- type: exports.Shape.GROUP,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- width: '',
- height: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- }
- return Group;
- }(DisplayObject);
- var _excluded$4 = ["style"];
- /**
- * HTML container
- * @see https://github.com/pmndrs/drei#html
- */
- var HTML = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(HTML, _DisplayObject);
- function HTML(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$4);
- _this = _DisplayObject.call(this, _extends({
- type: exports.Shape.HTML,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- width: 'auto',
- height: 'auto',
- innerHTML: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- _this.cullable.enable = false;
- return _this;
- }
- /**
- * return wrapper HTMLElement
- * * <div> in g-webgl/canvas
- * * <foreignObject> in g-svg
- */
- var _proto = HTML.prototype;
- _proto.getDomElement = function getDomElement() {
- return this.parsedStyle.$el;
- }
- /**
- * override with $el.getBoundingClientRect
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
- */;
- _proto.getBoundingClientRect = function getBoundingClientRect() {
- return this.parsedStyle.$el.getBoundingClientRect();
- };
- _proto.getClientRects = function getClientRects() {
- return [this.getBoundingClientRect()];
- };
- _proto.getBounds = function getBounds() {
- var _this$ownerDocument, _this$ownerDocument$d;
- var clientRect = this.getBoundingClientRect();
- // calc context's offset
- // @ts-ignore
- var canvasRect = (_this$ownerDocument = this.ownerDocument) === null || _this$ownerDocument === void 0 ? void 0 : (_this$ownerDocument$d = _this$ownerDocument.defaultView) === null || _this$ownerDocument$d === void 0 ? void 0 : _this$ownerDocument$d.getContextService().getBoundingClientRect();
- if (canvasRect) {
- var minX = clientRect.left - canvasRect.left;
- var minY = clientRect.top - canvasRect.top;
- var aabb = new AABB();
- // aabb.setMinMax(
- // vec3.fromValues(minX, minY, 0),
- // vec3.fromValues(minX + clientRect.width, minY + clientRect.height, 0),
- // );
- aabb.setMinMax([minX, minY, 0], [minX + clientRect.width, minY + clientRect.height, 0]);
- return aabb;
- }
- return null;
- };
- _proto.getLocalBounds = function getLocalBounds() {
- if (this.parentNode) {
- var parentInvert = invert(create$1(), this.parentNode.getWorldTransform());
- var bounds = this.getBounds();
- if (!AABB.isEmpty(bounds)) {
- var localBounds = new AABB();
- localBounds.setFromTransformedAABB(bounds, parentInvert);
- return localBounds;
- }
- }
- return this.getBounds();
- };
- return HTML;
- }(DisplayObject);
- var _excluded$5 = ["style"];
- var Image = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Image, _DisplayObject);
- function Image(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$5);
- return _DisplayObject.call(this, _extends({
- type: exports.Shape.IMAGE,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- img: '',
- width: '',
- height: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- }
- return Image;
- }(DisplayObject);
- var _excluded$6 = ["style"];
- /**
- * Create a line connecting two points.
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/line
- *
- * Also support for using marker.
- */
- var Line = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Line, _DisplayObject);
- function Line(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$6);
- _this = _DisplayObject.call(this, _extends({
- type: exports.Shape.LINE,
- style: _extends({
- x1: 0,
- y1: 0,
- x2: 0,
- y2: 0,
- z1: 0,
- z2: 0,
- isBillboard: false
- }, style)
- }, rest)) || this;
- _this.markerStartAngle = 0;
- _this.markerEndAngle = 0;
- var _this$parsedStyle = _this.parsedStyle,
- markerStart = _this$parsedStyle.markerStart,
- markerEnd = _this$parsedStyle.markerEnd;
- if (markerStart && isDisplayObject(markerStart)) {
- _this.markerStartAngle = markerStart.getLocalEulerAngles();
- _this.appendChild(markerStart);
- }
- if (markerEnd && isDisplayObject(markerEnd)) {
- _this.markerEndAngle = markerEnd.getLocalEulerAngles();
- _this.appendChild(markerEnd);
- }
- _this.transformMarker(true);
- _this.transformMarker(false);
- return _this;
- }
- var _proto = Line.prototype;
- _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
- if (attrName === 'x1' || attrName === 'y1' || attrName === 'x2' || attrName === 'y2' || attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
- this.transformMarker(true);
- this.transformMarker(false);
- } else if (attrName === 'markerStart') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerStartAngle = 0;
- prevParsedValue.remove();
- }
- // CSSKeyword 'unset'
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerStartAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(true);
- }
- } else if (attrName === 'markerEnd') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerEndAngle = 0;
- prevParsedValue.remove();
- }
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerEndAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(false);
- }
- }
- };
- _proto.transformMarker = function transformMarker(isStart) {
- var _this$parsedStyle2 = this.parsedStyle,
- markerStart = _this$parsedStyle2.markerStart,
- markerEnd = _this$parsedStyle2.markerEnd,
- markerStartOffset = _this$parsedStyle2.markerStartOffset,
- markerEndOffset = _this$parsedStyle2.markerEndOffset,
- x1 = _this$parsedStyle2.x1,
- x2 = _this$parsedStyle2.x2,
- y1 = _this$parsedStyle2.y1,
- y2 = _this$parsedStyle2.y2,
- defX = _this$parsedStyle2.defX,
- defY = _this$parsedStyle2.defY;
- var marker = isStart ? markerStart : markerEnd;
- if (!marker || !isDisplayObject(marker)) {
- return;
- }
- var rad = 0;
- var x;
- var y;
- var ox;
- var oy;
- var offset;
- var originalAngle;
- if (isStart) {
- ox = x1 - defX;
- oy = y1 - defY;
- x = x2 - x1;
- y = y2 - y1;
- offset = markerStartOffset || 0;
- originalAngle = this.markerStartAngle;
- } else {
- ox = x2 - defX;
- oy = y2 - defY;
- x = x1 - x2;
- y = y1 - y2;
- offset = markerEndOffset || 0;
- originalAngle = this.markerEndAngle;
- }
- rad = Math.atan2(y, x);
- // account for markerOffset
- marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
- marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
- };
- _proto.getPoint = function getPoint(ratio, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- // TODO: account for z1/z2 in 3D line
- var _this$parsedStyle3 = this.parsedStyle,
- x1 = _this$parsedStyle3.x1,
- y1 = _this$parsedStyle3.y1,
- x2 = _this$parsedStyle3.x2,
- y2 = _this$parsedStyle3.y2,
- defX = _this$parsedStyle3.defX,
- defY = _this$parsedStyle3.defY;
- var _LineUtil$pointAt = line.pointAt(x1, y1, x2, y2, ratio),
- x = _LineUtil$pointAt.x,
- y = _LineUtil$pointAt.y;
- var transformed = transformMat4(create$2(), fromValues$2(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
- // apply local transformation
- return new Point(transformed[0], transformed[1]);
- };
- _proto.getPointAtLength = function getPointAtLength(distance, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- return this.getPoint(distance / this.getTotalLength(), inWorldSpace);
- };
- _proto.getTotalLength = function getTotalLength() {
- // TODO: account for z1/z2 in 3D line
- var _this$parsedStyle4 = this.parsedStyle,
- x1 = _this$parsedStyle4.x1,
- y1 = _this$parsedStyle4.y1,
- x2 = _this$parsedStyle4.x2,
- y2 = _this$parsedStyle4.y2;
- return line.length(x1, y1, x2, y2);
- };
- return Line;
- }(DisplayObject);
- var _excluded$7 = ["style"];
- var EMPTY_PARSED_PATH = {
- absolutePath: [],
- hasArc: false,
- segments: [],
- polygons: [],
- polylines: [],
- curve: null,
- totalLength: 0,
- rect: new Rectangle(0, 0, 0, 0)
- };
- var Path = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Path, _DisplayObject);
- function Path(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$7);
- _this = _DisplayObject.call(this, _extends({
- type: exports.Shape.PATH,
- style: runtime.enableCSSParsing ? _extends({
- path: '',
- miterLimit: ''
- }, style) : _extends({}, style),
- initialParsedStyle: runtime.enableCSSParsing ? null : {
- miterLimit: 4,
- path: _extends({}, EMPTY_PARSED_PATH)
- }
- }, rest)) || this;
- _this.markerStartAngle = 0;
- _this.markerEndAngle = 0;
- /**
- * markers placed at the mid
- */
- _this.markerMidList = [];
- var _this$parsedStyle = _this.parsedStyle,
- markerStart = _this$parsedStyle.markerStart,
- markerEnd = _this$parsedStyle.markerEnd,
- markerMid = _this$parsedStyle.markerMid;
- if (markerStart && isDisplayObject(markerStart)) {
- _this.markerStartAngle = markerStart.getLocalEulerAngles();
- _this.appendChild(markerStart);
- }
- if (markerMid && isDisplayObject(markerMid)) {
- _this.placeMarkerMid(markerMid);
- }
- if (markerEnd && isDisplayObject(markerEnd)) {
- _this.markerEndAngle = markerEnd.getLocalEulerAngles();
- _this.appendChild(markerEnd);
- }
- _this.transformMarker(true);
- _this.transformMarker(false);
- return _this;
- }
- var _proto = Path.prototype;
- _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
- if (attrName === 'path') {
- // recalc markers
- this.transformMarker(true);
- this.transformMarker(false);
- this.placeMarkerMid(this.parsedStyle.markerMid);
- } else if (attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
- this.transformMarker(true);
- this.transformMarker(false);
- } else if (attrName === 'markerStart') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerStartAngle = 0;
- prevParsedValue.remove();
- }
- // CSSKeyword 'unset'
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerStartAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(true);
- }
- } else if (attrName === 'markerEnd') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerEndAngle = 0;
- prevParsedValue.remove();
- }
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerEndAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(false);
- }
- } else if (attrName === 'markerMid') {
- this.placeMarkerMid(newParsedValue);
- }
- };
- _proto.transformMarker = function transformMarker(isStart) {
- var _this$parsedStyle2 = this.parsedStyle,
- markerStart = _this$parsedStyle2.markerStart,
- markerEnd = _this$parsedStyle2.markerEnd,
- markerStartOffset = _this$parsedStyle2.markerStartOffset,
- markerEndOffset = _this$parsedStyle2.markerEndOffset,
- defX = _this$parsedStyle2.defX,
- defY = _this$parsedStyle2.defY;
- var marker = isStart ? markerStart : markerEnd;
- if (!marker || !isDisplayObject(marker)) {
- return;
- }
- var rad = 0;
- var x;
- var y;
- var ox;
- var oy;
- var offset;
- var originalAngle;
- if (isStart) {
- var _this$getStartTangent = this.getStartTangent(),
- p1 = _this$getStartTangent[0],
- p2 = _this$getStartTangent[1];
- ox = p2[0] - defX;
- oy = p2[1] - defY;
- x = p1[0] - p2[0];
- y = p1[1] - p2[1];
- offset = markerStartOffset || 0;
- originalAngle = this.markerStartAngle;
- } else {
- var _this$getEndTangent = this.getEndTangent(),
- _p = _this$getEndTangent[0],
- _p2 = _this$getEndTangent[1];
- ox = _p2[0] - defX;
- oy = _p2[1] - defY;
- x = _p[0] - _p2[0];
- y = _p[1] - _p2[1];
- offset = markerEndOffset || 0;
- originalAngle = this.markerEndAngle;
- }
- rad = Math.atan2(y, x);
- // account for markerOffset
- marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
- marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
- };
- _proto.placeMarkerMid = function placeMarkerMid(marker) {
- var _this$parsedStyle3 = this.parsedStyle,
- segments = _this$parsedStyle3.path.segments,
- defX = _this$parsedStyle3.defX,
- defY = _this$parsedStyle3.defY;
- // clear all existed markers
- this.markerMidList.forEach(function (marker) {
- marker.remove();
- });
- if (marker && isDisplayObject(marker)) {
- for (var i = 1; i < segments.length - 1; i++) {
- var _segments$i$currentPo = segments[i].currentPoint,
- ox = _segments$i$currentPo[0],
- oy = _segments$i$currentPo[1];
- var cloned = i === 1 ? marker : marker.cloneNode(true);
- this.markerMidList.push(cloned);
- this.appendChild(cloned);
- cloned.setLocalPosition(ox - defX, oy - defY);
- // TODO: orient of marker
- }
- }
- }
- /**
- * Returns the total length of the path.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getTotalLength
- */;
- _proto.getTotalLength = function getTotalLength() {
- return getOrCalculatePathTotalLength(this);
- }
- /**
- * Returns the point at a given distance along the path.
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getPointAtLength
- */;
- _proto.getPointAtLength = function getPointAtLength$1(distance, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- var _this$parsedStyle4 = this.parsedStyle,
- defX = _this$parsedStyle4.defX,
- defY = _this$parsedStyle4.defY,
- absolutePath = _this$parsedStyle4.path.absolutePath;
- var _getPointAtLength2 = getPointAtLength(absolutePath, distance),
- x = _getPointAtLength2.x,
- y = _getPointAtLength2.y;
- var transformed = transformMat4(create$2(), fromValues$2(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
- // apply local transformation
- return new Point(transformed[0], transformed[1]);
- }
- /**
- * Returns the point at a given ratio of the total length in path.
- */;
- _proto.getPoint = function getPoint(ratio, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- return this.getPointAtLength(ratio * getOrCalculatePathTotalLength(this), inWorldSpace);
- }
- /**
- * Get start tangent vector
- */;
- _proto.getStartTangent = function getStartTangent() {
- var segments = this.parsedStyle.path.segments;
- var result = [];
- if (segments.length > 1) {
- var startPoint = segments[0].currentPoint;
- var endPoint = segments[1].currentPoint;
- var tangent = segments[1].startTangent;
- result = [];
- if (tangent) {
- result.push([startPoint[0] - tangent[0], startPoint[1] - tangent[1]]);
- result.push([startPoint[0], startPoint[1]]);
- } else {
- result.push([endPoint[0], endPoint[1]]);
- result.push([startPoint[0], startPoint[1]]);
- }
- }
- return result;
- }
- /**
- * Get end tangent vector
- */;
- _proto.getEndTangent = function getEndTangent() {
- var segments = this.parsedStyle.path.segments;
- var length = segments.length;
- var result = [];
- if (length > 1) {
- var startPoint = segments[length - 2].currentPoint;
- var endPoint = segments[length - 1].currentPoint;
- var tangent = segments[length - 1].endTangent;
- result = [];
- if (tangent) {
- result.push([endPoint[0] - tangent[0], endPoint[1] - tangent[1]]);
- result.push([endPoint[0], endPoint[1]]);
- } else {
- result.push([startPoint[0], startPoint[1]]);
- result.push([endPoint[0], endPoint[1]]);
- }
- }
- return result;
- };
- return Path;
- }(DisplayObject);
- var _excluded$8 = ["style"];
- var Polygon = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Polygon, _DisplayObject);
- function Polygon(_temp) {
- var _this;
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$8);
- _this = _DisplayObject.call(this, _extends({
- type: exports.Shape.POLYGON,
- style: runtime.enableCSSParsing ? _extends({
- points: '',
- miterLimit: '',
- isClosed: true
- }, style) : _extends({}, style),
- initialParsedStyle: runtime.enableCSSParsing ? null : {
- points: {
- points: [],
- totalLength: 0,
- segments: []
- },
- miterLimit: 4,
- isClosed: true
- }
- }, rest)) || this;
- _this.markerStartAngle = 0;
- _this.markerEndAngle = 0;
- /**
- * markers placed at the mid
- */
- _this.markerMidList = [];
- var _this$parsedStyle = _this.parsedStyle,
- markerStart = _this$parsedStyle.markerStart,
- markerEnd = _this$parsedStyle.markerEnd,
- markerMid = _this$parsedStyle.markerMid;
- if (markerStart && isDisplayObject(markerStart)) {
- _this.markerStartAngle = markerStart.getLocalEulerAngles();
- _this.appendChild(markerStart);
- }
- if (markerMid && isDisplayObject(markerMid)) {
- _this.placeMarkerMid(markerMid);
- }
- if (markerEnd && isDisplayObject(markerEnd)) {
- _this.markerEndAngle = markerEnd.getLocalEulerAngles();
- _this.appendChild(markerEnd);
- }
- _this.transformMarker(true);
- _this.transformMarker(false);
- return _this;
- }
- var _proto = Polygon.prototype;
- _proto.attributeChangedCallback = function attributeChangedCallback(attrName, oldValue, newValue, prevParsedValue, newParsedValue) {
- if (attrName === 'points') {
- // recalc markers
- this.transformMarker(true);
- this.transformMarker(false);
- this.placeMarkerMid(this.parsedStyle.markerMid);
- } else if (attrName === 'markerStartOffset' || attrName === 'markerEndOffset') {
- this.transformMarker(true);
- this.transformMarker(false);
- } else if (attrName === 'markerStart') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerStartAngle = 0;
- prevParsedValue.remove();
- }
- // CSSKeyword 'unset'
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerStartAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(true);
- }
- } else if (attrName === 'markerEnd') {
- if (prevParsedValue && isDisplayObject(prevParsedValue)) {
- this.markerEndAngle = 0;
- prevParsedValue.remove();
- }
- if (newParsedValue && isDisplayObject(newParsedValue)) {
- this.markerEndAngle = newParsedValue.getLocalEulerAngles();
- this.appendChild(newParsedValue);
- this.transformMarker(false);
- }
- } else if (attrName === 'markerMid') {
- this.placeMarkerMid(newParsedValue);
- }
- };
- _proto.transformMarker = function transformMarker(isStart) {
- var _this$parsedStyle2 = this.parsedStyle,
- markerStart = _this$parsedStyle2.markerStart,
- markerEnd = _this$parsedStyle2.markerEnd,
- markerStartOffset = _this$parsedStyle2.markerStartOffset,
- markerEndOffset = _this$parsedStyle2.markerEndOffset,
- points = _this$parsedStyle2.points.points,
- defX = _this$parsedStyle2.defX,
- defY = _this$parsedStyle2.defY;
- var marker = isStart ? markerStart : markerEnd;
- if (!marker || !isDisplayObject(marker)) {
- return;
- }
- var rad = 0;
- var x;
- var y;
- var ox;
- var oy;
- var offset;
- var originalAngle;
- ox = points[0][0] - defX;
- oy = points[0][1] - defY;
- if (isStart) {
- x = points[1][0] - points[0][0];
- y = points[1][1] - points[0][1];
- offset = markerStartOffset || 0;
- originalAngle = this.markerStartAngle;
- } else {
- var length = points.length;
- if (!this.parsedStyle.isClosed) {
- ox = points[length - 1][0] - defX;
- oy = points[length - 1][1] - defY;
- x = points[length - 2][0] - points[length - 1][0];
- y = points[length - 2][1] - points[length - 1][1];
- } else {
- x = points[length - 1][0] - points[0][0];
- y = points[length - 1][1] - points[0][1];
- }
- offset = markerEndOffset || 0;
- originalAngle = this.markerEndAngle;
- }
- rad = Math.atan2(y, x);
- // account for markerOffset
- marker.setLocalEulerAngles(rad * 180 / Math.PI + originalAngle);
- marker.setLocalPosition(ox + Math.cos(rad) * offset, oy + Math.sin(rad) * offset);
- };
- _proto.placeMarkerMid = function placeMarkerMid(marker) {
- var _this$parsedStyle3 = this.parsedStyle,
- points = _this$parsedStyle3.points.points,
- defX = _this$parsedStyle3.defX,
- defY = _this$parsedStyle3.defY;
- // clear all existed markers
- this.markerMidList.forEach(function (marker) {
- marker.remove();
- });
- this.markerMidList = [];
- if (marker && isDisplayObject(marker)) {
- for (var i = 1; i < (this.parsedStyle.isClosed ? points.length : points.length - 1); i++) {
- var ox = points[i][0] - defX;
- var oy = points[i][1] - defY;
- var cloned = i === 1 ? marker : marker.cloneNode(true);
- this.markerMidList.push(cloned);
- this.appendChild(cloned);
- cloned.setLocalPosition(ox, oy);
- // TODO: orient of marker
- }
- }
- };
- return Polygon;
- }(DisplayObject);
- var _excluded$9 = ["style"];
- /**
- * Polyline inherits the marker-related capabilities of Polygon.
- */
- var Polyline = /*#__PURE__*/function (_Polygon) {
- _inheritsLoose(Polyline, _Polygon);
- function Polyline(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$9);
- return _Polygon.call(this, _extends({
- type: exports.Shape.POLYLINE,
- style: runtime.enableCSSParsing ? _extends({
- points: '',
- miterLimit: '',
- isClosed: false
- }, style) : _extends({}, style),
- initialParsedStyle: runtime.enableCSSParsing ? null : {
- points: {
- points: [],
- totalLength: 0,
- segments: []
- },
- miterLimit: 4,
- isClosed: false
- }
- }, rest)) || this;
- }
- var _proto = Polyline.prototype;
- _proto.getTotalLength = function getTotalLength() {
- return this.parsedStyle.points.totalLength;
- };
- _proto.getPointAtLength = function getPointAtLength(distance, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- return this.getPoint(distance / this.getTotalLength(), inWorldSpace);
- };
- _proto.getPoint = function getPoint(ratio, inWorldSpace) {
- if (inWorldSpace === void 0) {
- inWorldSpace = false;
- }
- var _this$parsedStyle = this.parsedStyle,
- defX = _this$parsedStyle.defX,
- defY = _this$parsedStyle.defY,
- _this$parsedStyle$poi = _this$parsedStyle.points,
- points = _this$parsedStyle$poi.points,
- segments = _this$parsedStyle$poi.segments;
- var subt = 0;
- var index = 0;
- segments.forEach(function (v, i) {
- if (ratio >= v[0] && ratio <= v[1]) {
- subt = (ratio - v[0]) / (v[1] - v[0]);
- index = i;
- }
- });
- var _LineUtil$pointAt = line.pointAt(points[index][0], points[index][1], points[index + 1][0], points[index + 1][1], subt),
- x = _LineUtil$pointAt.x,
- y = _LineUtil$pointAt.y;
- var transformed = transformMat4(create$2(), fromValues$2(x - defX, y - defY, 0), inWorldSpace ? this.getWorldTransform() : this.getLocalTransform());
- // apply local transformation
- return new Point(transformed[0], transformed[1]);
- };
- _proto.getStartTangent = function getStartTangent() {
- var points = this.parsedStyle.points.points;
- var result = [];
- result.push([points[1][0], points[1][1]]);
- result.push([points[0][0], points[0][1]]);
- return result;
- };
- _proto.getEndTangent = function getEndTangent() {
- var points = this.parsedStyle.points.points;
- var l = points.length - 1;
- var result = [];
- result.push([points[l - 1][0], points[l - 1][1]]);
- result.push([points[l][0], points[l][1]]);
- return result;
- };
- return Polyline;
- }(Polygon);
- var _excluded$a = ["style"];
- var Rect = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Rect, _DisplayObject);
- function Rect(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$a);
- return _DisplayObject.call(this, _extends({
- type: exports.Shape.RECT,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- width: '',
- height: '',
- radius: ''
- }, style) : _extends({}, style)
- }, rest)) || this;
- }
- return Rect;
- }(DisplayObject);
- var _excluded$b = ["style"];
- /**
- * <text> @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextElement
- */
- var Text = /*#__PURE__*/function (_DisplayObject) {
- _inheritsLoose(Text, _DisplayObject);
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement#constants
- */
- // LENGTHADJUST_SPACING: number = 1;
- // LENGTHADJUST_SPACINGANDGLYPHS: number = 2;
- // LENGTHADJUST_UNKNOWN: number = 0;
- function Text(_temp) {
- var _ref = _temp === void 0 ? {} : _temp,
- style = _ref.style,
- rest = _objectWithoutPropertiesLoose(_ref, _excluded$b);
- return _DisplayObject.call(this, _extends({
- type: exports.Shape.TEXT,
- style: runtime.enableCSSParsing ? _extends({
- x: '',
- y: '',
- text: '',
- fontSize: '',
- fontFamily: '',
- fontStyle: '',
- fontWeight: '',
- fontVariant: '',
- textAlign: '',
- textBaseline: '',
- textTransform: '',
- fill: 'black',
- letterSpacing: '',
- lineHeight: '',
- miterLimit: '',
- // whiteSpace: 'pre',
- wordWrap: false,
- wordWrapWidth: 0,
- leading: 0,
- dx: '',
- dy: '',
- isBillboard: false,
- sizeAttenuation: true
- }, style) : _extends({
- fill: 'black'
- }, style),
- initialParsedStyle: runtime.enableCSSParsing ? {} : {
- x: 0,
- y: 0,
- fontSize: 16,
- fontFamily: 'sans-serif',
- fontStyle: 'normal',
- fontWeight: 'normal',
- fontVariant: 'normal',
- lineHeight: 0,
- letterSpacing: 0,
- textBaseline: 'alphabetic',
- textAlign: 'start',
- wordWrap: false,
- wordWrapWidth: 0,
- leading: 0,
- dx: 0,
- dy: 0,
- isBillboard: false,
- sizeAttenuation: true
- }
- }, rest)) || this;
- }
- // lengthAdjust: SVGAnimatedEnumeration;
- // textLength: SVGAnimatedLength;
- // getCharNumAtPosition(point?: DOMPointInit): number {
- // throw new Error('Method not implemented.');
- // }
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement
- */
- var _proto = Text.prototype;
- _proto.getComputedTextLength = function getComputedTextLength() {
- var _this$parsedStyle$met;
- return ((_this$parsedStyle$met = this.parsedStyle.metrics) === null || _this$parsedStyle$met === void 0 ? void 0 : _this$parsedStyle$met.maxLineWidth) || 0;
- }
- // getEndPositionOfChar(charnum: number): DOMPoint {
- // throw new Error('Method not implemented.');
- // }
- // getExtentOfChar(charnum: number): DOMRect {
- // throw new Error('Method not implemented.');
- // }
- // getNumberOfChars(): number {
- // throw new Error('Method not implemented.');
- // }
- // getRotationOfChar(charnum: number): number {
- // throw new Error('Method not implemented.');
- // }
- // getStartPositionOfChar(charnum: number): DOMPoint {
- // throw new Error('Method not implemented.');
- // }
- // getSubStringLength(charnum: number, nchars: number): number {
- // throw new Error('Method not implemented.');
- // }
- // selectSubString(charnum: number, nchars: number): void {
- // throw new Error('Method not implemented.');
- // }
- ;
- _proto.getLineBoundingRects = function getLineBoundingRects() {
- var _this$parsedStyle$met2;
- return ((_this$parsedStyle$met2 = this.parsedStyle.metrics) === null || _this$parsedStyle$met2 === void 0 ? void 0 : _this$parsedStyle$met2.lineMetrics) || [];
- };
- _proto.isOverflowing = function isOverflowing() {
- return !!this.parsedStyle.isOverflowing;
- };
- return Text;
- }(DisplayObject);
- /**
- * Blink used them in code generation(css_properties.json5)
- */
- var BUILT_IN_PROPERTIES = [{
- /**
- * used in CSS Layout API
- * eg. `display: 'flex'`
- */
- n: 'display',
- k: ['none']
- }, {
- /**
- * range [0.0, 1.0]
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/opacity
- */
- n: 'opacity',
- int: true,
- inh: true,
- d: '1',
- syntax: exports.PropertySyntax.OPACITY_VALUE
- }, {
- /**
- * inheritable, range [0.0, 1.0]
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity
- * @see https://svgwg.org/svg2-draft/painting.html#FillOpacity
- */
- n: 'fillOpacity',
- int: true,
- inh: true,
- d: '1',
- syntax: exports.PropertySyntax.OPACITY_VALUE
- }, {
- /**
- * inheritable, range [0.0, 1.0]
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-opacity
- * @see https://svgwg.org/svg2-draft/painting.html#StrokeOpacity
- */
- n: 'strokeOpacity',
- int: true,
- inh: true,
- d: '1',
- syntax: exports.PropertySyntax.OPACITY_VALUE
- }, {
- /**
- * background-color is not inheritable
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
- */
- n: 'fill',
- int: true,
- k: ['none'],
- d: 'none',
- syntax: exports.PropertySyntax.PAINT
- }, {
- n: 'fillRule',
- k: ['nonzero', 'evenodd'],
- d: 'nonzero'
- },
- /**
- * default to none
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke#usage_notes
- */
- {
- n: 'stroke',
- int: true,
- k: ['none'],
- d: 'none',
- syntax: exports.PropertySyntax.PAINT,
- /**
- * Stroke 'none' won't affect geometry but others will.
- */
- l: true
- }, {
- n: 'shadowType',
- k: ['inner', 'outer', 'both'],
- d: 'outer',
- l: true
- }, {
- n: 'shadowColor',
- int: true,
- syntax: exports.PropertySyntax.COLOR
- }, {
- n: 'shadowOffsetX',
- int: true,
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'shadowOffsetY',
- int: true,
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'shadowBlur',
- int: true,
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.SHADOW_BLUR
- }, {
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-width
- */
- n: 'lineWidth',
- int: true,
- inh: true,
- d: '1',
- l: true,
- a: ['strokeWidth'],
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'increasedLineWidthForHitTesting',
- inh: true,
- d: '0',
- l: true,
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'lineJoin',
- inh: true,
- l: true,
- a: ['strokeLinejoin'],
- k: ['miter', 'bevel', 'round'],
- d: 'miter'
- }, {
- n: 'lineCap',
- inh: true,
- l: true,
- a: ['strokeLinecap'],
- k: ['butt', 'round', 'square'],
- d: 'butt'
- }, {
- n: 'lineDash',
- int: true,
- inh: true,
- k: ['none'],
- a: ['strokeDasharray'],
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE_12
- }, {
- n: 'lineDashOffset',
- int: true,
- inh: true,
- d: '0',
- a: ['strokeDashoffset'],
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'offsetPath',
- syntax: exports.PropertySyntax.DEFINED_PATH
- }, {
- n: 'offsetDistance',
- int: true,
- syntax: exports.PropertySyntax.OFFSET_DISTANCE
- }, {
- n: 'dx',
- int: true,
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'dy',
- int: true,
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'zIndex',
- ind: true,
- int: true,
- d: '0',
- k: ['auto'],
- syntax: exports.PropertySyntax.Z_INDEX
- }, {
- n: 'visibility',
- k: ['visible', 'hidden'],
- ind: true,
- inh: true,
- /**
- * support interpolation
- * @see https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#interpolation
- */
- int: true,
- d: 'visible'
- }, {
- n: 'pointerEvents',
- inh: true,
- k: ['none', 'auto', 'stroke', 'fill', 'painted', 'visible', 'visiblestroke', 'visiblefill', 'visiblepainted',
- // 'bounding-box',
- 'all'],
- d: 'auto'
- }, {
- n: 'filter',
- ind: true,
- l: true,
- k: ['none'],
- d: 'none',
- syntax: exports.PropertySyntax.FILTER
- }, {
- n: 'clipPath',
- syntax: exports.PropertySyntax.DEFINED_PATH
- }, {
- n: 'textPath',
- syntax: exports.PropertySyntax.DEFINED_PATH
- }, {
- n: 'textPathSide',
- k: ['left', 'right'],
- d: 'left'
- }, {
- n: 'textPathStartOffset',
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'transform',
- p: 100,
- int: true,
- k: ['none'],
- d: 'none',
- syntax: exports.PropertySyntax.TRANSFORM
- }, {
- n: 'transformOrigin',
- p: 100,
- // int: true,
- d: function d(nodeName) {
- if (nodeName === exports.Shape.CIRCLE || nodeName === exports.Shape.ELLIPSE) {
- return 'center';
- }
- if (nodeName === exports.Shape.TEXT) {
- return 'text-anchor';
- }
- return 'left top';
- },
- l: true,
- syntax: exports.PropertySyntax.TRANSFORM_ORIGIN
- }, {
- n: 'anchor',
- p: 99,
- d: function d(nodeName) {
- if (nodeName === exports.Shape.CIRCLE || nodeName === exports.Shape.ELLIPSE) {
- return '0.5 0.5';
- }
- return '0 0';
- },
- l: true,
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE_12
- },
- // <circle> & <ellipse>
- {
- n: 'cx',
- int: true,
- d: '0',
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- n: 'cy',
- int: true,
- d: '0',
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- n: 'cz',
- int: true,
- d: '0',
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- n: 'r',
- int: true,
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'rx',
- int: true,
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'ry',
- int: true,
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- },
- // Rect Image Group
- {
- // x in local space
- n: 'x',
- int: true,
- d: '0',
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- // y in local space
- n: 'y',
- int: true,
- d: '0',
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- // z in local space
- n: 'z',
- int: true,
- d: '0',
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- n: 'width',
- int: true,
- l: true,
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/width
- */
- k: ['auto', 'fit-content', 'min-content', 'max-content'],
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'height',
- int: true,
- l: true,
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/height
- */
- k: ['auto', 'fit-content', 'min-content', 'max-content'],
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'radius',
- int: true,
- l: true,
- d: '0',
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE_14
- },
- // Line
- {
- n: 'x1',
- int: true,
- l: true,
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- n: 'y1',
- int: true,
- l: true,
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- n: 'z1',
- int: true,
- l: true,
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- n: 'x2',
- int: true,
- l: true,
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- n: 'y2',
- int: true,
- l: true,
- syntax: exports.PropertySyntax.COORDINATE
- }, {
- n: 'z2',
- int: true,
- l: true,
- syntax: exports.PropertySyntax.COORDINATE
- },
- // Path
- {
- n: 'path',
- int: true,
- l: true,
- d: '',
- a: ['d'],
- syntax: exports.PropertySyntax.PATH,
- p: 50
- },
- // Polyline & Polygon
- {
- n: 'points',
- /**
- * support interpolation
- */
- int: true,
- l: true,
- syntax: exports.PropertySyntax.LIST_OF_POINTS,
- p: 50
- },
- // Text
- {
- n: 'text',
- l: true,
- d: '',
- syntax: exports.PropertySyntax.TEXT,
- p: 50
- }, {
- n: 'textTransform',
- l: true,
- inh: true,
- k: ['capitalize', 'uppercase', 'lowercase', 'none'],
- d: 'none',
- syntax: exports.PropertySyntax.TEXT_TRANSFORM,
- p: 51 // it must get parsed after text
- }, {
- n: 'font',
- l: true
- }, {
- n: 'fontSize',
- int: true,
- inh: true,
- /**
- * @see https://www.w3schools.com/css/css_font_size.asp
- */
- d: '16px',
- l: true,
- syntax: exports.PropertySyntax.LENGTH_PERCENTAGE
- }, {
- n: 'fontFamily',
- l: true,
- inh: true,
- d: 'sans-serif'
- }, {
- n: 'fontStyle',
- l: true,
- inh: true,
- k: ['normal', 'italic', 'oblique'],
- d: 'normal'
- }, {
- n: 'fontWeight',
- l: true,
- inh: true,
- k: ['normal', 'bold', 'bolder', 'lighter'],
- d: 'normal'
- }, {
- n: 'fontVariant',
- l: true,
- inh: true,
- k: ['normal', 'small-caps'],
- d: 'normal'
- }, {
- n: 'lineHeight',
- l: true,
- syntax: exports.PropertySyntax.LENGTH,
- int: true,
- d: '0'
- }, {
- n: 'letterSpacing',
- l: true,
- syntax: exports.PropertySyntax.LENGTH,
- int: true,
- d: '0'
- }, {
- n: 'miterLimit',
- l: true,
- syntax: exports.PropertySyntax.NUMBER,
- d: function d(nodeName) {
- if (nodeName === exports.Shape.PATH || nodeName === exports.Shape.POLYGON || nodeName === exports.Shape.POLYLINE) {
- return '4';
- }
- return '10';
- }
- }, {
- n: 'wordWrap',
- l: true
- }, {
- n: 'wordWrapWidth',
- l: true
- }, {
- n: 'maxLines',
- l: true
- }, {
- n: 'textOverflow',
- l: true,
- d: 'clip'
- }, {
- n: 'leading',
- l: true
- }, {
- n: 'textBaseline',
- l: true,
- inh: true,
- k: ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'],
- d: 'alphabetic'
- }, {
- n: 'textAlign',
- l: true,
- inh: true,
- k: ['start', 'center', 'middle', 'end', 'left', 'right'],
- d: 'start'
- },
- // {
- // n: 'whiteSpace',
- // l: true,
- // },
- {
- n: 'markerStart',
- syntax: exports.PropertySyntax.MARKER
- }, {
- n: 'markerEnd',
- syntax: exports.PropertySyntax.MARKER
- }, {
- n: 'markerMid',
- syntax: exports.PropertySyntax.MARKER
- }, {
- n: 'markerStartOffset',
- syntax: exports.PropertySyntax.LENGTH,
- l: true,
- int: true,
- d: '0'
- }, {
- n: 'markerEndOffset',
- syntax: exports.PropertySyntax.LENGTH,
- l: true,
- int: true,
- d: '0'
- }];
- var GEOMETRY_ATTRIBUTE_NAMES = BUILT_IN_PROPERTIES.filter(function (n) {
- return !!n.l;
- }).map(function (n) {
- return n.n;
- });
- var propertyMetadataCache = {};
- var unresolvedProperties = new WeakMap();
- // const uniqueAttributeSet = new Set<string>();
- // const tmpVec3a = vec3.create();
- // const tmpVec3b = vec3.create();
- // const tmpVec3c = vec3.create();
- var isPropertyResolved = function isPropertyResolved(object, name) {
- var properties = unresolvedProperties.get(object);
- if (!properties || properties.length === 0) {
- return true;
- }
- return properties.includes(name);
- };
- var DefaultStyleValueRegistry = /*#__PURE__*/function () {
- /**
- * need recalc later
- */
- // dirty = false;
- function DefaultStyleValueRegistry() {
- var _this = this;
- BUILT_IN_PROPERTIES.forEach(function (property) {
- _this.registerMetadata(property);
- });
- }
- var _proto = DefaultStyleValueRegistry.prototype;
- _proto.registerMetadata = function registerMetadata(metadata) {
- [metadata.n].concat(metadata.a || []).forEach(function (name) {
- propertyMetadataCache[name] = metadata;
- });
- };
- _proto.unregisterMetadata = function unregisterMetadata(name) {
- delete propertyMetadataCache[name];
- };
- _proto.getPropertySyntax = function getPropertySyntax(syntax) {
- return runtime.CSSPropertySyntaxFactory[syntax];
- }
- /**
- * * parse value, eg.
- * fill: 'red' => CSSRGB
- * translateX: '10px' => CSSUnitValue { unit: 'px', value: 10 }
- * fontSize: '2em' => { unit: 'px', value: 32 }
- *
- * * calculate used value
- * * post process
- */;
- _proto.processProperties = function processProperties(object, attributes, options) {
- var _this2 = this;
- if (options === void 0) {
- options = {
- skipUpdateAttribute: false,
- skipParse: false,
- forceUpdateGeometry: false,
- usedAttributes: []
- };
- }
- if (!runtime.enableCSSParsing) {
- Object.assign(object.attributes, attributes);
- var _attributeNames = Object.keys(attributes);
- // clipPath
- var oldClipPath = object.parsedStyle.clipPath;
- var oldOffsetPath = object.parsedStyle.offsetPath;
- object.parsedStyle = Object.assign(object.parsedStyle, attributes);
- var _needUpdateGeometry = !!options.forceUpdateGeometry;
- if (!_needUpdateGeometry) {
- for (var i = 0; i < GEOMETRY_ATTRIBUTE_NAMES.length; i++) {
- if (GEOMETRY_ATTRIBUTE_NAMES[i] in attributes) {
- _needUpdateGeometry = true;
- break;
- }
- }
- }
- if (attributes.fill) {
- object.parsedStyle.fill = parseColor(attributes.fill);
- }
- if (attributes.stroke) {
- object.parsedStyle.stroke = parseColor(attributes.stroke);
- }
- if (attributes.shadowColor) {
- object.parsedStyle.shadowColor = parseColor(attributes.shadowColor);
- }
- if (attributes.filter) {
- object.parsedStyle.filter = parseFilter(attributes.filter);
- }
- // Rect
- // @ts-ignore
- if (!isNil(attributes.radius)) {
- // @ts-ignore
- object.parsedStyle.radius = parseDimensionArrayFormat(
- // @ts-ignore
- attributes.radius, 4);
- }
- // Polyline
- if (!isNil(attributes.lineDash)) {
- object.parsedStyle.lineDash = parseDimensionArrayFormat(attributes.lineDash, 2);
- }
- // @ts-ignore
- if (attributes.points) {
- // @ts-ignore
- object.parsedStyle.points = parsePoints(attributes.points, object);
- }
- // Path
- // @ts-ignore
- if (attributes.path === '') {
- object.parsedStyle.path = _extends({}, EMPTY_PARSED_PATH);
- }
- // @ts-ignore
- if (attributes.path) {
- object.parsedStyle.path = parsePath(
- // @ts-ignore
- attributes.path, object);
- }
- // Text
- if (attributes.textTransform) {
- runtime.CSSPropertySyntaxFactory['<text-transform>'].calculator(null, null, {
- value: attributes.textTransform
- }, object, null);
- }
- if (attributes.clipPath) {
- runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('clipPath', oldClipPath, attributes.clipPath, object, this);
- }
- if (attributes.offsetPath) {
- runtime.CSSPropertySyntaxFactory['<defined-path>'].calculator('offsetPath', oldOffsetPath, attributes.offsetPath, object, this);
- }
- if (attributes.anchor) {
- object.parsedStyle.anchor = parseDimensionArrayFormat(
- // @ts-ignorex
- attributes.anchor, 2);
- }
- if (attributes.transform) {
- object.parsedStyle.transform = parseTransform(attributes.transform);
- }
- if (attributes.transformOrigin) {
- object.parsedStyle.transformOrigin = parseTransformOrigin(attributes.transformOrigin);
- }
- // Marker
- // @ts-ignore
- if (attributes.markerStart) {
- // @ts-ignore
- object.parsedStyle.markerStart = runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,
- // @ts-ignore
- attributes.markerStart,
- // @ts-ignore
- attributes.markerStart, null, null);
- }
- // @ts-ignore
- if (attributes.markerEnd) {
- // @ts-ignore
- object.parsedStyle.markerEnd = runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,
- // @ts-ignore
- attributes.markerEnd,
- // @ts-ignore
- attributes.markerEnd, null, null);
- }
- // @ts-ignore
- if (attributes.markerMid) {
- // @ts-ignore
- object.parsedStyle.markerMid = runtime.CSSPropertySyntaxFactory['<marker>'].calculator('',
- // @ts-ignore
- attributes.markerMid,
- // @ts-ignore
- attributes.markerMid, null, null);
- }
- if (
- // Circle & Ellipse
- (object.nodeName === exports.Shape.CIRCLE || object.nodeName === exports.Shape.ELLIPSE) && (
- // @ts-ignore
- !isNil(attributes.cx) ||
- // @ts-ignore
- !isNil(attributes.cy)) || (object.nodeName === exports.Shape.RECT || object.nodeName === exports.Shape.IMAGE || object.nodeName === exports.Shape.GROUP || object.nodeName === exports.Shape.HTML || object.nodeName === exports.Shape.TEXT || object.nodeName === exports.Shape.MESH) && (
- // @ts-ignore
- !isNil(attributes.x) ||
- // @ts-ignore
- !isNil(attributes.y) ||
- // @ts-ignore
- !isNil(attributes.z)) ||
- // Line
- object.nodeName === exports.Shape.LINE && (
- // @ts-ignore
- !isNil(attributes.x1) ||
- // @ts-ignore
- !isNil(attributes.y1) ||
- // @ts-ignore
- !isNil(attributes.z1) ||
- // @ts-ignore
- !isNil(attributes.x2) ||
- // @ts-ignore
- !isNil(attributes.y2) ||
- // @ts-ignore
- !isNil(attributes.z2))) {
- runtime.CSSPropertySyntaxFactory['<coordinate>'].postProcessor(object, _attributeNames);
- }
- if (!isNil(attributes.zIndex)) {
- runtime.CSSPropertySyntaxFactory['<z-index>'].postProcessor(object, _attributeNames);
- }
- // @ts-ignore
- if (attributes.path) {
- runtime.CSSPropertySyntaxFactory['<path>'].postProcessor(object, _attributeNames);
- }
- // @ts-ignore
- if (attributes.points) {
- runtime.CSSPropertySyntaxFactory['<list-of-points>'].postProcessor(object, _attributeNames);
- }
- if (!isNil(attributes.offsetDistance)) {
- runtime.CSSPropertySyntaxFactory['<offset-distance>'].postProcessor(object, _attributeNames);
- }
- if (attributes.transform) {
- runtime.CSSPropertySyntaxFactory['<transform>'].postProcessor(object, _attributeNames);
- }
- if (_needUpdateGeometry) {
- this.updateGeometry(object);
- }
- return;
- }
- var _options = options,
- skipUpdateAttribute = _options.skipUpdateAttribute,
- skipParse = _options.skipParse,
- forceUpdateGeometry = _options.forceUpdateGeometry,
- usedAttributes = _options.usedAttributes;
- var needUpdateGeometry = forceUpdateGeometry;
- var attributeNames = Object.keys(attributes);
- attributeNames.forEach(function (attributeName) {
- var _propertyMetadataCach;
- if (!skipUpdateAttribute) {
- object.attributes[attributeName] = attributes[attributeName];
- }
- if (!needUpdateGeometry && ((_propertyMetadataCach = propertyMetadataCache[attributeName]) === null || _propertyMetadataCach === void 0 ? void 0 : _propertyMetadataCach.l)) {
- needUpdateGeometry = true;
- }
- });
- if (!skipParse) {
- attributeNames.forEach(function (name) {
- object.computedStyle[name] = _this2.parseProperty(name, object.attributes[name], object);
- });
- }
- // let hasUnresolvedProperties = false;
- // parse according to priority
- // path 50
- // points 50
- // text 50
- // textTransform 51
- // anchor 99
- // transform 100
- // transformOrigin 100
- if (usedAttributes === null || usedAttributes === void 0 ? void 0 : usedAttributes.length) {
- // uniqueAttributeSet.clear();
- attributeNames = Array.from(new Set(attributeNames.concat(usedAttributes)));
- }
- // [
- // 'path',
- // 'points',
- // 'text',
- // 'textTransform',
- // 'anchor',
- // 'transform',
- // 'transformOrigin',
- // ].forEach((name) => {
- // const index = attributeNames.indexOf(name);
- // if (index > -1) {
- // attributeNames.splice(index, 1);
- // attributeNames.push(name);
- // }
- // });
- attributeNames.forEach(function (name) {
- // some style props maybe deleted after parsing such as `anchor` in Text
- if (name in object.computedStyle) {
- object.parsedStyle[name] = _this2.computeProperty(name, object.computedStyle[name], object);
- }
- });
- // if (hasUnresolvedProperties) {
- // this.dirty = true;
- // return;
- // }
- // update geometry
- if (needUpdateGeometry) {
- // object.geometry.dirty = true;
- // runtime.sceneGraphService.dirtifyToRoot(object);
- this.updateGeometry(object);
- }
- attributeNames.forEach(function (name) {
- if (name in object.parsedStyle) {
- _this2.postProcessProperty(name, object, attributeNames);
- }
- });
- if (runtime.enableCSSParsing && object.children.length) {
- attributeNames.forEach(function (name) {
- if (name in object.parsedStyle && _this2.isPropertyInheritable(name)) {
- // update children's inheritable
- object.children.forEach(function (child) {
- child.internalSetAttribute(name, null, {
- skipUpdateAttribute: true,
- skipParse: true
- });
- });
- }
- });
- }
- }
- /**
- * string -> parsed value
- */;
- _proto.parseProperty = function parseProperty(name, value, object) {
- var metadata = propertyMetadataCache[name];
- var computed = value;
- if (value === '' || isNil(value)) {
- value = 'unset';
- }
- if (value === 'unset' || value === 'initial' || value === 'inherit') {
- // computed = new CSSKeywordValue(value);
- computed = getOrCreateKeyword(value);
- } else {
- if (metadata) {
- var keywords = metadata.k,
- syntax = metadata.syntax;
- var handler = syntax && this.getPropertySyntax(syntax);
- // use keywords
- if (keywords && keywords.indexOf(value) > -1) {
- // computed = new CSSKeywordValue(value);
- computed = getOrCreateKeyword(value);
- } else if (handler && handler.parser) {
- // try to parse it to CSSStyleValue, eg. '10px' -> CSS.px(10)
- computed = handler.parser(value, object);
- }
- }
- }
- return computed;
- }
- /**
- * computed value -> used value
- */;
- _proto.computeProperty = function computeProperty(name, computed, object) {
- var metadata = propertyMetadataCache[name];
- var isDocumentElement = object.id === 'g-root';
- // let used: CSSStyleValue = computed instanceof CSSStyleValue ? computed.clone() : computed;
- var used = computed;
- if (metadata) {
- var syntax = metadata.syntax,
- inherited = metadata.inh,
- defaultValue = metadata.d;
- if (computed instanceof CSSKeywordValue) {
- var value = computed.value;
- /**
- * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/unset
- */
- if (value === 'unset') {
- if (inherited && !isDocumentElement) {
- value = 'inherit';
- } else {
- value = 'initial';
- }
- }
- if (value === 'initial') {
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial
- if (!isNil(defaultValue)) {
- computed = this.parseProperty(name, isFunction(defaultValue) ? defaultValue(object.nodeName) : defaultValue, object);
- }
- } else if (value === 'inherit') {
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/inherit
- // behave like `inherit`
- var resolved = this.tryToResolveProperty(object, name, {
- inherited: true
- });
- if (!isNil(resolved)) {
- // object.parsedStyle[name] = resolved;
- // return false;
- return resolved;
- } else {
- this.addUnresolveProperty(object, name);
- return;
- }
- }
- }
- var handler = syntax && this.getPropertySyntax(syntax);
- if (handler && handler.calculator) {
- // convert computed value to used value
- var oldParsedValue = object.parsedStyle[name];
- used = handler.calculator(name, oldParsedValue, computed, object, this);
- } else if (computed instanceof CSSKeywordValue) {
- used = computed.value;
- } else {
- used = computed;
- }
- }
- // object.parsedStyle[name] = used;
- // return false;
- return used;
- };
- _proto.postProcessProperty = function postProcessProperty(name, object, attributes) {
- var metadata = propertyMetadataCache[name];
- if (metadata && metadata.syntax) {
- var handler = metadata.syntax && this.getPropertySyntax(metadata.syntax);
- var propertyHandler = handler;
- if (propertyHandler && propertyHandler.postProcessor) {
- propertyHandler.postProcessor(object, attributes);
- }
- }
- }
- /**
- * resolve later
- */;
- _proto.addUnresolveProperty = function addUnresolveProperty(object, name) {
- var properties = unresolvedProperties.get(object);
- if (!properties) {
- unresolvedProperties.set(object, []);
- properties = unresolvedProperties.get(object);
- }
- if (properties.indexOf(name) === -1) {
- properties.push(name);
- }
- };
- _proto.tryToResolveProperty = function tryToResolveProperty(object, name, options) {
- if (options === void 0) {
- options = {};
- }
- var _options2 = options,
- inherited = _options2.inherited;
- if (inherited) {
- if (object.parentElement && isPropertyResolved(object.parentElement, name)) {
- // const computedValue = object.parentElement.computedStyle[name];
- var usedValue = object.parentElement.parsedStyle[name];
- if (
- // usedValue instanceof CSSKeywordValue &&
- usedValue === 'unset' || usedValue === 'initial' || usedValue === 'inherit') {
- return;
- }
- // else if (
- // usedValue instanceof CSSUnitValue &&
- // CSSUnitValue.isRelativeUnit(usedValue.unit)
- // ) {
- // return false;
- // }
- return usedValue;
- }
- }
- return;
- };
- _proto.recalc = function recalc(object) {
- var properties = unresolvedProperties.get(object);
- if (properties && properties.length) {
- var attributes = {};
- properties.forEach(function (property) {
- attributes[property] = object.attributes[property];
- });
- this.processProperties(object, attributes);
- unresolvedProperties.delete(object);
- }
- }
- /**
- * update geometry when relative props changed,
- * eg. r of Circle, width/height of Rect
- */;
- _proto.updateGeometry = function updateGeometry(object) {
- var nodeName = object.nodeName;
- var geometryUpdater = runtime.geometryUpdaterFactory[nodeName];
- if (geometryUpdater) {
- var geometry = object.geometry;
- if (!geometry.contentBounds) {
- geometry.contentBounds = new AABB();
- }
- if (!geometry.renderBounds) {
- geometry.renderBounds = new AABB();
- }
- var parsedStyle = object.parsedStyle;
- var _geometryUpdater$upda = geometryUpdater.update(parsedStyle, object),
- width = _geometryUpdater$upda.width,
- height = _geometryUpdater$upda.height,
- _geometryUpdater$upda2 = _geometryUpdater$upda.depth,
- depth = _geometryUpdater$upda2 === void 0 ? 0 : _geometryUpdater$upda2,
- _geometryUpdater$upda3 = _geometryUpdater$upda.offsetX,
- offsetX = _geometryUpdater$upda3 === void 0 ? 0 : _geometryUpdater$upda3,
- _geometryUpdater$upda4 = _geometryUpdater$upda.offsetY,
- offsetY = _geometryUpdater$upda4 === void 0 ? 0 : _geometryUpdater$upda4,
- _geometryUpdater$upda5 = _geometryUpdater$upda.offsetZ,
- offsetZ = _geometryUpdater$upda5 === void 0 ? 0 : _geometryUpdater$upda5;
- // init with content box
- var halfExtents = [Math.abs(width) / 2, Math.abs(height) / 2, depth / 2];
- // const halfExtents = vec3.set(
- // tmpVec3a,
- // Math.abs(width) / 2,
- // Math.abs(height) / 2,
- // depth / 2,
- // );
- // anchor is center by default, don't account for lineWidth here
- var stroke = parsedStyle.stroke,
- lineWidth = parsedStyle.lineWidth,
- increasedLineWidthForHitTesting = parsedStyle.increasedLineWidthForHitTesting,
- shadowType = parsedStyle.shadowType,
- shadowColor = parsedStyle.shadowColor,
- _parsedStyle$filter = parsedStyle.filter,
- filter = _parsedStyle$filter === void 0 ? [] : _parsedStyle$filter,
- transformOrigin = parsedStyle.transformOrigin;
- var anchor = parsedStyle.anchor;
- // <Text> use textAlign & textBaseline instead of anchor
- if (nodeName === exports.Shape.TEXT) {
- delete parsedStyle.anchor;
- } else if (nodeName === exports.Shape.MESH) {
- parsedStyle.anchor[2] = 0.5;
- }
- var center = [(1 - (anchor && anchor[0] || 0) * 2) * width / 2 + offsetX, (1 - (anchor && anchor[1] || 0) * 2) * height / 2 + offsetY, (1 - (anchor && anchor[2] || 0) * 2) * halfExtents[2] + offsetZ];
- // const center = vec3.set(
- // tmpVec3b,
- // ((1 - ((anchor && anchor[0]) || 0) * 2) * width) / 2 + offsetX,
- // ((1 - ((anchor && anchor[1]) || 0) * 2) * height) / 2 + offsetY,
- // (1 - ((anchor && anchor[2]) || 0) * 2) * halfExtents[2] + offsetZ,
- // );
- // update geometry's AABB
- geometry.contentBounds.update(center, halfExtents);
- // @see https://github.molgen.mpg.de/git-mirror/cairo/blob/master/src/cairo-stroke-style.c#L97..L128
- var expansion = nodeName === exports.Shape.POLYLINE || nodeName === exports.Shape.POLYGON || nodeName === exports.Shape.PATH ? Math.SQRT2 : 0.5;
- // if (lineCap?.value === 'square') {
- // expansion = Math.SQRT1_2;
- // }
- // if (lineJoin?.value === 'miter' && expansion < Math.SQRT2 * miterLimit) {
- // expansion = Math.SQRT1_2 * miterLimit;
- // }
- // append border only if stroke existed
- var hasStroke = stroke && !stroke.isNone;
- if (hasStroke) {
- var halfLineWidth = ((lineWidth || 0) + (increasedLineWidthForHitTesting || 0)) * expansion;
- // halfExtents[0] += halfLineWidth[0];
- // halfExtents[1] += halfLineWidth[1];
- halfExtents[0] += halfLineWidth;
- halfExtents[1] += halfLineWidth;
- // vec3.add(
- // halfExtents,
- // halfExtents,
- // vec3.set(tmpVec3c, halfLineWidth, halfLineWidth, 0),
- // );
- }
- geometry.renderBounds.update(center, halfExtents);
- // account for shadow, only support constant value now
- if (shadowColor && shadowType && shadowType !== 'inner') {
- var _geometry$renderBound = geometry.renderBounds,
- min = _geometry$renderBound.min,
- max = _geometry$renderBound.max;
- var shadowBlur = parsedStyle.shadowBlur,
- shadowOffsetX = parsedStyle.shadowOffsetX,
- shadowOffsetY = parsedStyle.shadowOffsetY;
- var shadowBlurInPixels = shadowBlur || 0;
- var shadowOffsetXInPixels = shadowOffsetX || 0;
- var shadowOffsetYInPixels = shadowOffsetY || 0;
- var shadowLeft = min[0] - shadowBlurInPixels + shadowOffsetXInPixels;
- var shadowRight = max[0] + shadowBlurInPixels + shadowOffsetXInPixels;
- var shadowTop = min[1] - shadowBlurInPixels + shadowOffsetYInPixels;
- var shadowBottom = max[1] + shadowBlurInPixels + shadowOffsetYInPixels;
- min[0] = Math.min(min[0], shadowLeft);
- max[0] = Math.max(max[0], shadowRight);
- min[1] = Math.min(min[1], shadowTop);
- max[1] = Math.max(max[1], shadowBottom);
- geometry.renderBounds.setMinMax(min, max);
- }
- // account for filter, eg. blur(5px), drop-shadow()
- filter.forEach(function (_ref) {
- var name = _ref.name,
- params = _ref.params;
- if (name === 'blur') {
- var blurRadius = params[0].value;
- geometry.renderBounds.update(geometry.renderBounds.center, addVec3(geometry.renderBounds.halfExtents, geometry.renderBounds.halfExtents, [blurRadius, blurRadius, 0]));
- } else if (name === 'drop-shadow') {
- var _shadowOffsetX = params[0].value;
- var _shadowOffsetY = params[1].value;
- var _shadowBlur = params[2].value;
- var _geometry$renderBound2 = geometry.renderBounds,
- _min = _geometry$renderBound2.min,
- _max = _geometry$renderBound2.max;
- var _shadowLeft = _min[0] - _shadowBlur + _shadowOffsetX;
- var _shadowRight = _max[0] + _shadowBlur + _shadowOffsetX;
- var _shadowTop = _min[1] - _shadowBlur + _shadowOffsetY;
- var _shadowBottom = _max[1] + _shadowBlur + _shadowOffsetY;
- _min[0] = Math.min(_min[0], _shadowLeft);
- _max[0] = Math.max(_max[0], _shadowRight);
- _min[1] = Math.min(_min[1], _shadowTop);
- _max[1] = Math.max(_max[1], _shadowBottom);
- geometry.renderBounds.setMinMax(_min, _max);
- }
- });
- anchor = parsedStyle.anchor;
- // if (nodeName === Shape.RECT) {
- // account for negative width / height of Rect
- // @see https://github.com/antvis/g/issues/957
- var flipY = width < 0;
- var flipX = height < 0;
- // } else {
- // }
- // set transform origin
- var usedOriginXValue = (flipY ? -1 : 1) * (transformOrigin ? convertPercentUnit(transformOrigin[0], 0, object) : 0);
- var usedOriginYValue = (flipX ? -1 : 1) * (transformOrigin ? convertPercentUnit(transformOrigin[1], 1, object) : 0);
- usedOriginXValue = usedOriginXValue - (flipY ? -1 : 1) * (anchor && anchor[0] || 0) * geometry.contentBounds.halfExtents[0] * 2;
- usedOriginYValue = usedOriginYValue - (flipX ? -1 : 1) * (anchor && anchor[1] || 0) * geometry.contentBounds.halfExtents[1] * 2;
- object.setOrigin(usedOriginXValue, usedOriginYValue);
- // FIXME setOrigin may have already dirtified to root.
- runtime.sceneGraphService.dirtifyToRoot(object);
- }
- };
- _proto.isPropertyInheritable = function isPropertyInheritable(name) {
- var metadata = propertyMetadataCache[name];
- if (!metadata) {
- return false;
- }
- return metadata.inh;
- };
- return DefaultStyleValueRegistry;
- }();
- /**
- * Different type of cameras, eg. simple camera used in 2D scene or
- * advanced camera which can do actions & switch between landmarks.
- */
- (function (CameraType) {
- /**
- * Performs all the rotational operations with the focal point instead of the camera position.
- * This type of camera is useful in applications(like CAD) where 3D objects are being designed or explored.
- * Camera cannot orbits over the north & south poles.
- * @see http://voxelent.com/tutorial-cameras/
- *
- * In Three.js it's used in OrbitControls.
- * @see https://threejs.org/docs/#examples/zh/controls/OrbitControls
- */
- CameraType[CameraType["ORBITING"] = 0] = "ORBITING";
- /**
- * It's similar to the ORBITING camera, but it allows the camera to orbit over the north or south poles.
- *
- * In Three.js it's used in OrbitControls.
- * @see https://threejs.org/docs/#examples/en/controls/TrackballControls
- */
- CameraType[CameraType["EXPLORING"] = 1] = "EXPLORING";
- /**
- * Performs all the rotational operations with the camera position.
- * It's useful in first person shooting games.
- * Camera cannot orbits over the north & south poles.
- *
- * In Three.js it's used in FirstPersonControls.
- * @see https://threejs.org/docs/#examples/en/controls/FirstPersonControls
- */
- CameraType[CameraType["TRACKING"] = 2] = "TRACKING";
- })(exports.CameraType || (exports.CameraType = {}));
- (function (CameraTrackingMode) {
- CameraTrackingMode[CameraTrackingMode["DEFAULT"] = 0] = "DEFAULT";
- CameraTrackingMode[CameraTrackingMode["ROTATIONAL"] = 1] = "ROTATIONAL";
- CameraTrackingMode[CameraTrackingMode["TRANSLATIONAL"] = 2] = "TRANSLATIONAL";
- CameraTrackingMode[CameraTrackingMode["CINEMATIC"] = 3] = "CINEMATIC";
- })(exports.CameraTrackingMode || (exports.CameraTrackingMode = {}));
- (function (CameraProjectionMode) {
- CameraProjectionMode[CameraProjectionMode["ORTHOGRAPHIC"] = 0] = "ORTHOGRAPHIC";
- CameraProjectionMode[CameraProjectionMode["PERSPECTIVE"] = 1] = "PERSPECTIVE";
- })(exports.CameraProjectionMode || (exports.CameraProjectionMode = {}));
- var CameraEvent = {
- UPDATED: 'updated'
- };
- var MIN_DISTANCE = 0.0002;
- /**
- * 参考「WebGL Insights - 23.Designing Cameras for WebGL Applications」,基于 Responsible Camera 思路设计
- * @see https://github.com/d13g0/nucleo.js/blob/master/source/camera/Camera.js
- *
- * 保存相机参数,定义相机动作:
- * 1. dolly 沿 n 轴移动
- * 2. pan 沿 u v 轴移动
- * 3. rotate 以方位角旋转
- * 4. 移动到 Landmark,具有平滑的动画效果,其间禁止其他用户交互
- */
- var Camera = /*#__PURE__*/function () {
- function Camera() {
- this.canvas = void 0;
- this.eventEmitter = new eventemitter3();
- /**
- * 相机矩阵
- */
- this.matrix = create$1();
- /**
- * u 轴
- * @see http://learnwebgl.brown37.net/07_cameras/camera_introduction.html#a-camera-definition
- */
- this.right = fromValues$2(1, 0, 0);
- /**
- * v 轴 +Y is down
- */
- this.up = fromValues$2(0, 1, 0);
- /**
- * n 轴 +Z is inside
- */
- this.forward = fromValues$2(0, 0, 1);
- /**
- * 相机位置
- */
- this.position = fromValues$2(0, 0, 1);
- /**
- * 视点位置
- */
- this.focalPoint = fromValues$2(0, 0, 0);
- /**
- * 视点到相机位置的向量
- * focalPoint - position
- */
- this.distanceVector = fromValues$2(0, 0, -1);
- /**
- * 相机位置到视点距离
- * length(focalPoint - position)
- */
- this.distance = 1;
- /**
- * @see https://en.wikipedia.org/wiki/Azimuth
- */
- this.azimuth = 0;
- this.elevation = 0;
- this.roll = 0;
- this.relAzimuth = 0;
- this.relElevation = 0;
- this.relRoll = 0;
- /**
- * 沿 n 轴移动时,保证移动速度从快到慢
- */
- this.dollyingStep = 0;
- this.maxDistance = Infinity;
- this.minDistance = -Infinity;
- /**
- * zoom factor of the camera, default is 1
- * eg. https://threejs.org/docs/#api/en/cameras/OrthographicCamera.zoom
- */
- this.zoom = 1;
- /**
- * invert the horizontal coordinate system HCS
- */
- this.rotateWorld = false;
- /**
- * 投影矩阵参数
- */
- /**
- * field of view [0-360]
- * @see http://en.wikipedia.org/wiki/Angle_of_view
- */
- this.fov = 30;
- this.near = 0.1;
- this.far = 1000;
- this.aspect = 1;
- this.left = void 0;
- this.rright = void 0;
- this.top = void 0;
- this.bottom = void 0;
- this.projectionMatrix = create$1();
- this.projectionMatrixInverse = create$1();
- this.jitteredProjectionMatrix = undefined;
- this.view = void 0;
- this.enableUpdate = true;
- // protected following = undefined;
- this.type = exports.CameraType.EXPLORING;
- this.trackingMode = exports.CameraTrackingMode.DEFAULT;
- this.projectionMode = exports.CameraProjectionMode.PERSPECTIVE;
- /**
- * for culling use
- */
- this.frustum = new Frustum();
- /**
- * ortho matrix for Canvas2D & SVG
- */
- this.orthoMatrix = create$1();
- }
- var _proto = Camera.prototype;
- // constructor(type = CameraType.EXPLORING, trackingMode = CameraTrackingMode.DEFAULT) {
- // this.setType(type, trackingMode);
- // }
- _proto.isOrtho = function isOrtho() {
- return this.projectionMode === exports.CameraProjectionMode.ORTHOGRAPHIC;
- };
- _proto.getProjectionMode = function getProjectionMode() {
- return this.projectionMode;
- };
- _proto.getPerspective = function getPerspective() {
- // account for TAA
- return this.jitteredProjectionMatrix || this.projectionMatrix;
- };
- _proto.getPerspectiveInverse = function getPerspectiveInverse() {
- return this.projectionMatrixInverse;
- };
- _proto.getFrustum = function getFrustum() {
- return this.frustum;
- };
- _proto.getPosition = function getPosition() {
- return this.position;
- };
- _proto.getFocalPoint = function getFocalPoint() {
- return this.focalPoint;
- };
- _proto.getDollyingStep = function getDollyingStep() {
- return this.dollyingStep;
- };
- _proto.getNear = function getNear() {
- return this.near;
- };
- _proto.getFar = function getFar() {
- return this.far;
- };
- _proto.getZoom = function getZoom() {
- return this.zoom;
- };
- _proto.getOrthoMatrix = function getOrthoMatrix() {
- return this.orthoMatrix;
- };
- _proto.getView = function getView() {
- return this.view;
- };
- _proto.setEnableUpdate = function setEnableUpdate(enabled) {
- this.enableUpdate = enabled;
- };
- _proto.setType = function setType(type, trackingMode) {
- this.type = type;
- if (this.type === exports.CameraType.EXPLORING) {
- this.setWorldRotation(true);
- } else {
- this.setWorldRotation(false);
- }
- this._getAngles();
- if (this.type === exports.CameraType.TRACKING && trackingMode !== undefined) {
- this.setTrackingMode(trackingMode);
- }
- return this;
- };
- _proto.setProjectionMode = function setProjectionMode(projectionMode) {
- this.projectionMode = projectionMode;
- return this;
- };
- _proto.setTrackingMode = function setTrackingMode(trackingMode) {
- if (this.type !== exports.CameraType.TRACKING) {
- throw new Error('Impossible to set a tracking mode if the camera is not of tracking type');
- }
- this.trackingMode = trackingMode;
- return this;
- }
- /**
- * If flag is true, it reverses the azimuth and elevation angles.
- * Subsequent calls to rotate, setAzimuth, setElevation,
- * changeAzimuth or changeElevation will cause the inverted effect.
- * setRoll or changeRoll is not affected by this method.
- *
- * This inversion is useful when one wants to simulate that the world
- * is moving, instead of the camera.
- *
- * By default the camera angles are not reversed.
- * @param {Boolean} flag the boolean flag to reverse the angles.
- */;
- _proto.setWorldRotation = function setWorldRotation(flag) {
- this.rotateWorld = flag;
- this._getAngles();
- return this;
- }
- /**
- * 计算 MV 矩阵,为相机矩阵的逆矩阵
- */;
- _proto.getViewTransform = function getViewTransform() {
- return invert(create$1(), this.matrix);
- };
- _proto.getWorldTransform = function getWorldTransform() {
- return this.matrix;
- };
- _proto.jitterProjectionMatrix = function jitterProjectionMatrix(x, y) {
- var translation = fromTranslation(create$1(), [x, y, 0]);
- this.jitteredProjectionMatrix = multiply(create$1(), translation, this.projectionMatrix);
- };
- _proto.clearJitterProjectionMatrix = function clearJitterProjectionMatrix() {
- this.jitteredProjectionMatrix = undefined;
- }
- /**
- * 设置相机矩阵
- */;
- _proto.setMatrix = function setMatrix(matrix) {
- this.matrix = matrix;
- this._update();
- return this;
- };
- _proto.setFov = function setFov(fov) {
- this.setPerspective(this.near, this.far, fov, this.aspect);
- return this;
- };
- _proto.setAspect = function setAspect(aspect) {
- this.setPerspective(this.near, this.far, this.fov, aspect);
- return this;
- };
- _proto.setNear = function setNear(near) {
- if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(near, this.far, this.fov, this.aspect);
- } else {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, near, this.far);
- }
- return this;
- };
- _proto.setFar = function setFar(far) {
- if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(this.near, far, this.fov, this.aspect);
- } else {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, far);
- }
- return this;
- }
- /**
- * Sets an offset in a larger frustum, used in PixelPicking
- */;
- _proto.setViewOffset = function setViewOffset(fullWidth, fullHeight, x, y, width, height) {
- this.aspect = fullWidth / fullHeight;
- if (this.view === undefined) {
- this.view = {
- enabled: true,
- fullWidth: 1,
- fullHeight: 1,
- offsetX: 0,
- offsetY: 0,
- width: 1,
- height: 1
- };
- }
- this.view.enabled = true;
- this.view.fullWidth = fullWidth;
- this.view.fullHeight = fullHeight;
- this.view.offsetX = x;
- this.view.offsetY = y;
- this.view.width = width;
- this.view.height = height;
- if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(this.near, this.far, this.fov, this.aspect);
- } else {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
- }
- return this;
- };
- _proto.clearViewOffset = function clearViewOffset() {
- if (this.view !== undefined) {
- this.view.enabled = false;
- }
- if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(this.near, this.far, this.fov, this.aspect);
- } else {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
- }
- return this;
- };
- _proto.setZoom = function setZoom(zoom) {
- this.zoom = zoom;
- if (this.projectionMode === exports.CameraProjectionMode.ORTHOGRAPHIC) {
- this.setOrthographic(this.left, this.rright, this.top, this.bottom, this.near, this.far);
- } else if (this.projectionMode === exports.CameraProjectionMode.PERSPECTIVE) {
- this.setPerspective(this.near, this.far, this.fov, this.aspect);
- }
- return this;
- }
- /**
- * Zoom by specified point in viewport coordinates.
- */;
- _proto.setZoomByViewportPoint = function setZoomByViewportPoint(zoom, viewportPoint) {
- var _this$canvas$viewport = this.canvas.viewport2Canvas({
- x: viewportPoint[0],
- y: viewportPoint[1]
- }),
- ox = _this$canvas$viewport.x,
- oy = _this$canvas$viewport.y;
- var roll = this.roll;
- this.rotate(0, 0, -roll);
- this.setPosition(ox, oy);
- this.setFocalPoint(ox, oy);
- this.setZoom(zoom);
- this.rotate(0, 0, roll);
- var _this$canvas$viewport2 = this.canvas.viewport2Canvas({
- x: viewportPoint[0],
- y: viewportPoint[1]
- }),
- cx = _this$canvas$viewport2.x,
- cy = _this$canvas$viewport2.y;
- // project to rotated axis
- var dvec = fromValues$2(cx - ox, cy - oy, 0);
- var dx = dot(dvec, this.right) / length(this.right);
- var dy = dot(dvec, this.up) / length(this.up);
- this.pan(-dx, -dy);
- return this;
- };
- _proto.setPerspective = function setPerspective(near, far, fov, aspect) {
- var _this$view;
- this.projectionMode = exports.CameraProjectionMode.PERSPECTIVE;
- this.fov = fov;
- this.near = near;
- this.far = far;
- this.aspect = aspect;
- var top = this.near * Math.tan(deg2rad(0.5 * this.fov)) / this.zoom;
- var height = 2 * top;
- var width = this.aspect * height;
- var left = -0.5 * width;
- if ((_this$view = this.view) === null || _this$view === void 0 ? void 0 : _this$view.enabled) {
- var fullWidth = this.view.fullWidth;
- var fullHeight = this.view.fullHeight;
- left += this.view.offsetX * width / fullWidth;
- top -= this.view.offsetY * height / fullHeight;
- width *= this.view.width / fullWidth;
- height *= this.view.height / fullHeight;
- }
- makePerspective(this.projectionMatrix, left, left + width, top, top - height, near, this.far);
- // flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
- scale(this.projectionMatrix, this.projectionMatrix, fromValues$2(1, -1, 1));
- invert(this.projectionMatrixInverse, this.projectionMatrix);
- this.triggerUpdate();
- return this;
- };
- _proto.setOrthographic = function setOrthographic(l, r, t, b, near, far) {
- var _this$view2;
- this.projectionMode = exports.CameraProjectionMode.ORTHOGRAPHIC;
- this.rright = r;
- this.left = l;
- this.top = t;
- this.bottom = b;
- this.near = near;
- this.far = far;
- var dx = (this.rright - this.left) / (2 * this.zoom);
- var dy = (this.top - this.bottom) / (2 * this.zoom);
- var cx = (this.rright + this.left) / 2;
- var cy = (this.top + this.bottom) / 2;
- var left = cx - dx;
- var right = cx + dx;
- var top = cy + dy;
- var bottom = cy - dy;
- if ((_this$view2 = this.view) === null || _this$view2 === void 0 ? void 0 : _this$view2.enabled) {
- var scaleW = (this.rright - this.left) / this.view.fullWidth / this.zoom;
- var scaleH = (this.top - this.bottom) / this.view.fullHeight / this.zoom;
- left += scaleW * this.view.offsetX;
- right = left + scaleW * this.view.width;
- top -= scaleH * this.view.offsetY;
- bottom = top - scaleH * this.view.height;
- }
- ortho(this.projectionMatrix, left, right, bottom, top, near, far);
- // flipY since the origin of OpenGL/WebGL is bottom-left compared with top-left in Canvas2D
- scale(this.projectionMatrix, this.projectionMatrix, fromValues$2(1, -1, 1));
- invert(this.projectionMatrixInverse, this.projectionMatrix);
- this._getOrthoMatrix();
- this.triggerUpdate();
- return this;
- }
- /**
- * Move the camera in world coordinates.
- * It will keep looking at the current focal point.
- *
- * support scalars or vectors.
- * @example
- * setPosition(1, 2, 3);
- * setPosition([1, 2, 3]);
- */;
- _proto.setPosition = function setPosition(x, y, z) {
- if (y === void 0) {
- y = this.position[1];
- }
- if (z === void 0) {
- z = this.position[2];
- }
- var position = createVec3(x, y, z);
- this._setPosition(position);
- this.setFocalPoint(this.focalPoint);
- this.triggerUpdate();
- return this;
- }
- /**
- * Sets the focal point of this camera in world coordinates.
- *
- * support scalars or vectors.
- * @example
- * setFocalPoint(1, 2, 3);
- * setFocalPoint([1, 2, 3]);
- */;
- _proto.setFocalPoint = function setFocalPoint(x, y, z) {
- if (y === void 0) {
- y = this.focalPoint[1];
- }
- if (z === void 0) {
- z = this.focalPoint[2];
- }
- var up = fromValues$2(0, 1, 0);
- this.focalPoint = createVec3(x, y, z);
- if (this.trackingMode === exports.CameraTrackingMode.CINEMATIC) {
- var d = subtract$1(create$2(), this.focalPoint, this.position);
- x = d[0];
- y = d[1];
- z = d[2];
- var r = length(d);
- var el = rad2deg(Math.asin(y / r));
- var az = 90 + rad2deg(Math.atan2(z, x));
- var m = create$1();
- rotateY(m, m, deg2rad(az));
- rotateX(m, m, deg2rad(el));
- up = transformMat4(create$2(), [0, 1, 0], m);
- }
- invert(this.matrix, lookAt(create$1(), this.position, this.focalPoint, up));
- this._getAxes();
- this._getDistance();
- this._getAngles();
- this.triggerUpdate();
- return this;
- };
- _proto.getDistance = function getDistance() {
- return this.distance;
- };
- _proto.getDistanceVector = function getDistanceVector() {
- return this.distanceVector;
- }
- /**
- * Moves the camera towards/from the focal point.
- */;
- _proto.setDistance = function setDistance(d) {
- if (this.distance === d || d < 0) {
- return this;
- }
- this.distance = d;
- if (this.distance < MIN_DISTANCE) {
- this.distance = MIN_DISTANCE;
- }
- this.dollyingStep = this.distance / 100;
- var pos = create$2();
- d = this.distance;
- var n = this.forward;
- var f = this.focalPoint;
- pos[0] = d * n[0] + f[0];
- pos[1] = d * n[1] + f[1];
- pos[2] = d * n[2] + f[2];
- this._setPosition(pos);
- this.triggerUpdate();
- return this;
- };
- _proto.setMaxDistance = function setMaxDistance(d) {
- this.maxDistance = d;
- return this;
- };
- _proto.setMinDistance = function setMinDistance(d) {
- this.minDistance = d;
- return this;
- }
- /**
- * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
- * the azimuth in degrees
- */;
- _proto.setAzimuth = function setAzimuth(az) {
- this.azimuth = getAngle(az);
- this.computeMatrix();
- this._getAxes();
- if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
- this._getPosition();
- } else if (this.type === exports.CameraType.TRACKING) {
- this._getFocalPoint();
- }
- this.triggerUpdate();
- return this;
- };
- _proto.getAzimuth = function getAzimuth() {
- return this.azimuth;
- }
- /**
- * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
- */;
- _proto.setElevation = function setElevation(el) {
- this.elevation = getAngle(el);
- this.computeMatrix();
- this._getAxes();
- if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
- this._getPosition();
- } else if (this.type === exports.CameraType.TRACKING) {
- this._getFocalPoint();
- }
- this.triggerUpdate();
- return this;
- };
- _proto.getElevation = function getElevation() {
- return this.elevation;
- }
- /**
- * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
- */;
- _proto.setRoll = function setRoll(angle) {
- this.roll = getAngle(angle);
- this.computeMatrix();
- this._getAxes();
- if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
- this._getPosition();
- } else if (this.type === exports.CameraType.TRACKING) {
- this._getFocalPoint();
- }
- this.triggerUpdate();
- return this;
- };
- _proto.getRoll = function getRoll() {
- return this.roll;
- }
- /**
- * 根据相机矩阵重新计算各种相机参数
- */;
- _proto._update = function _update() {
- this._getAxes();
- this._getPosition();
- this._getDistance();
- this._getAngles();
- this._getOrthoMatrix();
- this.triggerUpdate();
- }
- /**
- * 计算相机矩阵
- */;
- _proto.computeMatrix = function computeMatrix() {
- // 使用四元数描述 3D 旋转
- // @see https://xiaoiver.github.io/coding/2018/12/28/Camera-%E8%AE%BE%E8%AE%A1-%E4%B8%80.html
- var rotZ = setAxisAngle(create$4(), [0, 0, 1], deg2rad(this.roll));
- identity(this.matrix);
- // only consider HCS for EXPLORING and ORBITING cameras
- var rotX = setAxisAngle(create$4(), [1, 0, 0], deg2rad((this.rotateWorld && this.type !== exports.CameraType.TRACKING || this.type === exports.CameraType.TRACKING ? 1 : -1) * this.elevation));
- var rotY = setAxisAngle(create$4(), [0, 1, 0], deg2rad((this.rotateWorld && this.type !== exports.CameraType.TRACKING || this.type === exports.CameraType.TRACKING ? 1 : -1) * this.azimuth));
- var rotQ = multiply$2(create$4(), rotY, rotX);
- rotQ = multiply$2(create$4(), rotQ, rotZ);
- var rotMatrix = fromQuat(create$1(), rotQ);
- if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
- translate(this.matrix, this.matrix, this.focalPoint);
- multiply(this.matrix, this.matrix, rotMatrix);
- translate(this.matrix, this.matrix, [0, 0, this.distance]);
- } else if (this.type === exports.CameraType.TRACKING) {
- translate(this.matrix, this.matrix, this.position);
- multiply(this.matrix, this.matrix, rotMatrix);
- }
- }
- /**
- * Sets the camera position in the camera matrix
- */;
- _proto._setPosition = function _setPosition(x, y, z) {
- this.position = createVec3(x, y, z);
- var m = this.matrix;
- m[12] = this.position[0];
- m[13] = this.position[1];
- m[14] = this.position[2];
- m[15] = 1;
- this._getOrthoMatrix();
- }
- /**
- * Recalculates axes based on the current matrix
- */;
- _proto._getAxes = function _getAxes() {
- copy$1(this.right, createVec3(transformMat4$1(create$3(), [1, 0, 0, 0], this.matrix)));
- copy$1(this.up, createVec3(transformMat4$1(create$3(), [0, 1, 0, 0], this.matrix)));
- copy$1(this.forward, createVec3(transformMat4$1(create$3(), [0, 0, 1, 0], this.matrix)));
- normalize(this.right, this.right);
- normalize(this.up, this.up);
- normalize(this.forward, this.forward);
- }
- /**
- * Recalculates euler angles based on the current state
- */;
- _proto._getAngles = function _getAngles() {
- // Recalculates angles
- var x = this.distanceVector[0];
- var y = this.distanceVector[1];
- var z = this.distanceVector[2];
- var r = length(this.distanceVector);
- // FAST FAIL: If there is no distance we cannot compute angles
- if (r === 0) {
- this.elevation = 0;
- this.azimuth = 0;
- return;
- }
- if (this.type === exports.CameraType.TRACKING) {
- this.elevation = rad2deg(Math.asin(y / r));
- this.azimuth = rad2deg(Math.atan2(-x, -z));
- } else {
- if (this.rotateWorld) {
- this.elevation = rad2deg(Math.asin(y / r));
- this.azimuth = rad2deg(Math.atan2(-x, -z));
- } else {
- this.elevation = -rad2deg(Math.asin(y / r));
- this.azimuth = -rad2deg(Math.atan2(-x, -z));
- }
- }
- }
- /**
- * 重新计算相机位置,只有 ORBITING 模式相机位置才会发生变化
- */;
- _proto._getPosition = function _getPosition() {
- copy$1(this.position, createVec3(transformMat4$1(create$3(), [0, 0, 0, 1], this.matrix)));
- // 相机位置变化,需要重新计算视距
- this._getDistance();
- }
- /**
- * 重新计算视点,只有 TRACKING 模式视点才会发生变化
- */;
- _proto._getFocalPoint = function _getFocalPoint() {
- transformMat3(this.distanceVector, [0, 0, -this.distance], fromMat4(create(), this.matrix));
- add$1(this.focalPoint, this.position, this.distanceVector);
- // 视点变化,需要重新计算视距
- this._getDistance();
- }
- /**
- * 重新计算视距
- */;
- _proto._getDistance = function _getDistance() {
- this.distanceVector = subtract$1(create$2(), this.focalPoint, this.position);
- this.distance = length(this.distanceVector);
- this.dollyingStep = this.distance / 100;
- };
- _proto._getOrthoMatrix = function _getOrthoMatrix() {
- if (this.projectionMode !== exports.CameraProjectionMode.ORTHOGRAPHIC) {
- return;
- }
- var position = this.position;
- var rotZ = setAxisAngle(create$4(), [0, 0, 1], -this.roll * Math.PI / 180);
- fromRotationTranslationScaleOrigin(this.orthoMatrix, rotZ, fromValues$2((this.rright - this.left) / 2 - position[0], (this.top - this.bottom) / 2 - position[1], 0), fromValues$2(this.zoom, this.zoom, 1), position);
- };
- _proto.triggerUpdate = function triggerUpdate() {
- if (this.enableUpdate) {
- // update frustum
- var viewMatrix = this.getViewTransform();
- var vpMatrix = multiply(create$1(), this.getPerspective(), viewMatrix);
- this.getFrustum().extractFromVPMatrix(vpMatrix);
- this.eventEmitter.emit(CameraEvent.UPDATED);
- }
- };
- _proto.rotate = function rotate(azimuth, elevation, roll) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.pan = function pan(tx, ty) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.dolly = function dolly(value) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.createLandmark = function createLandmark(name, params) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.gotoLandmark = function gotoLandmark(name, options) {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- _proto.cancelLandmarkAnimation = function cancelLandmarkAnimation() {
- throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
- };
- return Camera;
- }();
- var CircleUpdater = /*#__PURE__*/function () {
- function CircleUpdater() {}
- var _proto = CircleUpdater.prototype;
- _proto.update = function update(parsedStyle, object) {
- var r = parsedStyle.r;
- var width = r * 2;
- var height = r * 2;
- return {
- width: width,
- height: height
- };
- };
- return CircleUpdater;
- }();
- var EllipseUpdater = /*#__PURE__*/function () {
- function EllipseUpdater() {}
- var _proto = EllipseUpdater.prototype;
- _proto.update = function update(parsedStyle, object) {
- var rx = parsedStyle.rx,
- ry = parsedStyle.ry;
- var width = rx * 2;
- var height = ry * 2;
- return {
- width: width,
- height: height
- };
- };
- return EllipseUpdater;
- }();
- var LineUpdater = /*#__PURE__*/function () {
- function LineUpdater() {}
- var _proto = LineUpdater.prototype;
- _proto.update = function update(parsedStyle) {
- var x1 = parsedStyle.x1,
- y1 = parsedStyle.y1,
- x2 = parsedStyle.x2,
- y2 = parsedStyle.y2;
- var minX = Math.min(x1, x2);
- var maxX = Math.max(x1, x2);
- var minY = Math.min(y1, y2);
- var maxY = Math.max(y1, y2);
- var width = maxX - minX;
- var height = maxY - minY;
- return {
- width: width,
- height: height
- };
- };
- return LineUpdater;
- }();
- var PathUpdater = /*#__PURE__*/function () {
- function PathUpdater() {}
- var _proto = PathUpdater.prototype;
- _proto.update = function update(parsedStyle) {
- var path = parsedStyle.path;
- var _path$rect = path.rect,
- width = _path$rect.width,
- height = _path$rect.height;
- return {
- width: width,
- height: height
- };
- };
- return PathUpdater;
- }();
- var PolylineUpdater = /*#__PURE__*/function () {
- function PolylineUpdater() {}
- var _proto = PolylineUpdater.prototype;
- _proto.update = function update(parsedStyle) {
- var points = parsedStyle.points.points;
- // FIXME: account for miter lineJoin
- var minX = Math.min.apply(Math, points.map(function (point) {
- return point[0];
- }));
- var maxX = Math.max.apply(Math, points.map(function (point) {
- return point[0];
- }));
- var minY = Math.min.apply(Math, points.map(function (point) {
- return point[1];
- }));
- var maxY = Math.max.apply(Math, points.map(function (point) {
- return point[1];
- }));
- var width = maxX - minX;
- var height = maxY - minY;
- return {
- width: width,
- height: height
- };
- };
- return PolylineUpdater;
- }();
- var RectUpdater = /*#__PURE__*/function () {
- function RectUpdater() {}
- var _proto = RectUpdater.prototype;
- _proto.update = function update(parsedStyle, object) {
- var img = parsedStyle.img,
- _parsedStyle$width = parsedStyle.width,
- width = _parsedStyle$width === void 0 ? 0 : _parsedStyle$width,
- _parsedStyle$height = parsedStyle.height,
- height = _parsedStyle$height === void 0 ? 0 : _parsedStyle$height;
- var contentWidth = width;
- var contentHeight = height;
- // resize with HTMLImageElement's size
- if (img && !isString(img)) {
- if (!contentWidth) {
- contentWidth = img.width;
- parsedStyle.width = contentWidth;
- }
- if (!contentHeight) {
- contentHeight = img.height;
- parsedStyle.height = contentHeight;
- }
- }
- return {
- width: contentWidth,
- height: contentHeight
- };
- };
- return RectUpdater;
- }();
- var TextUpdater = /*#__PURE__*/function () {
- function TextUpdater(globalRuntime) {
- this.globalRuntime = void 0;
- this.globalRuntime = globalRuntime;
- }
- var _proto = TextUpdater.prototype;
- _proto.isReadyToMeasure = function isReadyToMeasure(parsedStyle, object) {
- var text = parsedStyle.text,
- textAlign = parsedStyle.textAlign,
- textBaseline = parsedStyle.textBaseline,
- fontSize = parsedStyle.fontSize,
- fontStyle = parsedStyle.fontStyle,
- fontWeight = parsedStyle.fontWeight,
- fontVariant = parsedStyle.fontVariant,
- lineWidth = parsedStyle.lineWidth;
- return text && fontSize && fontStyle && fontWeight && fontVariant && textAlign && textBaseline && !isNil(lineWidth);
- };
- _proto.update = function update(parsedStyle, object) {
- var _object$ownerDocument, _object$ownerDocument2;
- var text = parsedStyle.text,
- textAlign = parsedStyle.textAlign,
- lineWidth = parsedStyle.lineWidth,
- textBaseline = parsedStyle.textBaseline,
- dx = parsedStyle.dx,
- dy = parsedStyle.dy;
- var _ref = (object === null || object === void 0 ? void 0 : (_object$ownerDocument = object.ownerDocument) === null || _object$ownerDocument === void 0 ? void 0 : (_object$ownerDocument2 = _object$ownerDocument.defaultView) === null || _object$ownerDocument2 === void 0 ? void 0 : _object$ownerDocument2.getConfig()) || {},
- offscreenCanvas = _ref.offscreenCanvas;
- if (!this.isReadyToMeasure(parsedStyle, object)) {
- parsedStyle.metrics = {
- font: '',
- width: 0,
- height: 0,
- lines: [],
- lineWidths: [],
- lineHeight: 0,
- maxLineWidth: 0,
- fontProperties: {
- ascent: 0,
- descent: 0,
- fontSize: 0
- },
- lineMetrics: []
- };
- return {
- width: 0,
- height: 0,
- x: 0,
- y: 0,
- offsetX: 0,
- offsetY: 0
- };
- }
- var metrics = this.globalRuntime.textService.measureText(text, parsedStyle, offscreenCanvas);
- parsedStyle.metrics = metrics;
- var width = metrics.width,
- height = metrics.height,
- lineHeight = metrics.lineHeight,
- fontProperties = metrics.fontProperties;
- // anchor is left-top by default
- var halfExtents = [width / 2, height / 2, 0];
- // default 'left'
- var anchor = [0, 1];
- var lineXOffset = 0;
- if (textAlign === 'center' || textAlign === 'middle') {
- lineXOffset = lineWidth / 2;
- anchor = [0.5, 1];
- } else if (textAlign === 'right' || textAlign === 'end') {
- lineXOffset = lineWidth;
- anchor = [1, 1];
- }
- var lineYOffset = 0;
- if (textBaseline === 'middle') {
- // eslint-disable-next-line prefer-destructuring
- lineYOffset = halfExtents[1];
- } else if (textBaseline === 'top' || textBaseline === 'hanging') {
- lineYOffset = halfExtents[1] * 2;
- } else if (textBaseline === 'alphabetic') {
- // prevent calling getImageData for ascent metrics
- lineYOffset = runtime.enableCSSParsing ? lineHeight - fontProperties.ascent : 0;
- } else if (textBaseline === 'bottom' || textBaseline === 'ideographic') {
- lineYOffset = 0;
- }
- // TODO: ideographic & bottom
- if (dx) {
- lineXOffset += dx;
- }
- if (dy) {
- lineYOffset += dy;
- }
- // update anchor
- parsedStyle.anchor = [anchor[0], anchor[1], 0];
- return {
- width: halfExtents[0] * 2,
- height: halfExtents[1] * 2,
- offsetX: lineXOffset,
- offsetY: lineYOffset
- };
- };
- return TextUpdater;
- }();
- var PROPAGATION_LIMIT = 2048;
- var EventService = /*#__PURE__*/function () {
- function EventService(globalRuntime, context) {
- var _this = this;
- this.globalRuntime = void 0;
- this.context = void 0;
- this.rootTarget = void 0;
- this.emitter = new eventemitter3();
- this.cursor = 'default';
- this.mappingTable = {};
- this.mappingState = {
- trackingData: {}
- };
- this.eventPool = new Map();
- this.pickHandler = void 0;
- this.tmpMatrix = create$1();
- this.tmpVec3 = create$2();
- this.onPointerDown = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var e = _this.createPointerEvent(from);
- _this.dispatchEvent(e, 'pointerdown');
- if (e.pointerType === 'touch') {
- _this.dispatchEvent(e, 'touchstart');
- } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
- var isRightButton = e.button === 2;
- _this.dispatchEvent(e, isRightButton ? 'rightdown' : 'mousedown');
- }
- var trackingData = _this.trackingData(from.pointerId);
- trackingData.pressTargetsByButton[from.button] = e.composedPath();
- _this.freeEvent(e);
- };
- this.onPointerUp = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var now = performance.now();
- var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
- _this.dispatchEvent(e, 'pointerup');
- if (e.pointerType === 'touch') {
- _this.dispatchEvent(e, 'touchend');
- } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
- var isRightButton = e.button === 2;
- _this.dispatchEvent(e, isRightButton ? 'rightup' : 'mouseup');
- }
- var trackingData = _this.trackingData(from.pointerId);
- var pressTarget = _this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
- var clickTarget = pressTarget;
- // pointerupoutside only bubbles. It only bubbles upto the parent that doesn't contain
- // the pointerup location.
- if (pressTarget && !e.composedPath().includes(pressTarget)) {
- var currentTarget = pressTarget;
- while (currentTarget && !e.composedPath().includes(currentTarget)) {
- e.currentTarget = currentTarget;
- _this.notifyTarget(e, 'pointerupoutside');
- if (e.pointerType === 'touch') {
- _this.notifyTarget(e, 'touchendoutside');
- } else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
- var _isRightButton = e.button === 2;
- _this.notifyTarget(e, _isRightButton ? 'rightupoutside' : 'mouseupoutside');
- }
- if (Node.isNode(currentTarget)) {
- currentTarget = currentTarget.parentNode;
- }
- }
- delete trackingData.pressTargetsByButton[from.button];
- // currentTarget is the most specific ancestor holding both the pointerdown and pointerup
- // targets. That is - it's our click target!
- clickTarget = currentTarget;
- }
- if (clickTarget) {
- var _e$detail;
- var clickEvent = _this.clonePointerEvent(e, 'click');
- clickEvent.target = clickTarget;
- clickEvent.path = [];
- if (!trackingData.clicksByButton[from.button]) {
- trackingData.clicksByButton[from.button] = {
- clickCount: 0,
- target: clickEvent.target,
- timeStamp: now
- };
- }
- var clickHistory = trackingData.clicksByButton[from.button];
- if (clickHistory.target === clickEvent.target && now - clickHistory.timeStamp < 200) {
- ++clickHistory.clickCount;
- } else {
- clickHistory.clickCount = 1;
- }
- clickHistory.target = clickEvent.target;
- clickHistory.timeStamp = now;
- clickEvent.detail = clickHistory.clickCount;
- // @see https://github.com/antvis/G/issues/1091
- if (!((_e$detail = e.detail) === null || _e$detail === void 0 ? void 0 : _e$detail.preventClick)) {
- if (!_this.context.config.useNativeClickEvent && (clickEvent.pointerType === 'mouse' || clickEvent.pointerType === 'touch')) {
- _this.dispatchEvent(clickEvent, 'click');
- }
- _this.dispatchEvent(clickEvent, 'pointertap');
- }
- _this.freeEvent(clickEvent);
- }
- _this.freeEvent(e);
- };
- this.onPointerMove = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
- var isMouse = e.pointerType === 'mouse' || e.pointerType === 'pen';
- var trackingData = _this.trackingData(from.pointerId);
- var outTarget = _this.findMountedTarget(trackingData.overTargets);
- // First pointerout/pointerleave
- if (trackingData.overTargets && outTarget !== e.target) {
- // pointerout always occurs on the overTarget when the pointer hovers over another element.
- var outType = from.type === 'mousemove' ? 'mouseout' : 'pointerout';
- var outEvent = _this.createPointerEvent(from, outType, outTarget || undefined);
- _this.dispatchEvent(outEvent, 'pointerout');
- if (isMouse) _this.dispatchEvent(outEvent, 'mouseout');
- // If the pointer exits overTarget and its descendants, then a pointerleave event is also fired. This event
- // is dispatched to all ancestors that no longer capture the pointer.
- if (!e.composedPath().includes(outTarget)) {
- var leaveEvent = _this.createPointerEvent(from, 'pointerleave', outTarget || undefined);
- leaveEvent.eventPhase = leaveEvent.AT_TARGET;
- while (leaveEvent.target && !e.composedPath().includes(leaveEvent.target)) {
- leaveEvent.currentTarget = leaveEvent.target;
- _this.notifyTarget(leaveEvent);
- if (isMouse) {
- _this.notifyTarget(leaveEvent, 'mouseleave');
- }
- if (Node.isNode(leaveEvent.target)) {
- leaveEvent.target = leaveEvent.target.parentNode;
- }
- }
- _this.freeEvent(leaveEvent);
- }
- _this.freeEvent(outEvent);
- }
- // Then pointerover
- if (outTarget !== e.target) {
- // pointerover always occurs on the new overTarget
- var overType = from.type === 'mousemove' ? 'mouseover' : 'pointerover';
- var overEvent = _this.clonePointerEvent(e, overType); // clone faster
- _this.dispatchEvent(overEvent, 'pointerover');
- if (isMouse) _this.dispatchEvent(overEvent, 'mouseover');
- // Probe whether the newly hovered Node is an ancestor of the original overTarget.
- var overTargetAncestor = outTarget && Node.isNode(outTarget) && outTarget.parentNode;
- while (overTargetAncestor && overTargetAncestor !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
- if (overTargetAncestor === e.target) break;
- overTargetAncestor = overTargetAncestor.parentNode;
- }
- // The pointer has entered a non-ancestor of the original overTarget. This means we need a pointerentered
- // event.
- var didPointerEnter = !overTargetAncestor || overTargetAncestor === (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode);
- if (didPointerEnter) {
- var enterEvent = _this.clonePointerEvent(e, 'pointerenter');
- enterEvent.eventPhase = enterEvent.AT_TARGET;
- while (enterEvent.target && enterEvent.target !== outTarget && enterEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
- enterEvent.currentTarget = enterEvent.target;
- _this.notifyTarget(enterEvent);
- if (isMouse) _this.notifyTarget(enterEvent, 'mouseenter');
- if (Node.isNode(enterEvent.target)) {
- enterEvent.target = enterEvent.target.parentNode;
- }
- }
- _this.freeEvent(enterEvent);
- }
- _this.freeEvent(overEvent);
- }
- // Then pointermove
- _this.dispatchEvent(e, 'pointermove');
- if (e.pointerType === 'touch') _this.dispatchEvent(e, 'touchmove');
- if (isMouse) {
- _this.dispatchEvent(e, 'mousemove');
- _this.cursor = _this.getCursor(e.target);
- }
- trackingData.overTargets = e.composedPath();
- _this.freeEvent(e);
- };
- this.onPointerOut = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var trackingData = _this.trackingData(from.pointerId);
- if (trackingData.overTargets) {
- var isMouse = from.pointerType === 'mouse' || from.pointerType === 'pen';
- var outTarget = _this.findMountedTarget(trackingData.overTargets);
- // pointerout first
- var outEvent = _this.createPointerEvent(from, 'pointerout', outTarget || undefined);
- _this.dispatchEvent(outEvent);
- if (isMouse) _this.dispatchEvent(outEvent, 'mouseout');
- // pointerleave(s) are also dispatched b/c the pointer must've left rootTarget and its descendants to
- // get an upstream pointerout event (upstream events do not know rootTarget has descendants).
- var leaveEvent = _this.createPointerEvent(from, 'pointerleave', outTarget || undefined);
- leaveEvent.eventPhase = leaveEvent.AT_TARGET;
- while (leaveEvent.target && leaveEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
- leaveEvent.currentTarget = leaveEvent.target;
- _this.notifyTarget(leaveEvent);
- if (isMouse) {
- _this.notifyTarget(leaveEvent, 'mouseleave');
- }
- if (Node.isNode(leaveEvent.target)) {
- leaveEvent.target = leaveEvent.target.parentNode;
- }
- }
- trackingData.overTargets = null;
- _this.freeEvent(outEvent);
- _this.freeEvent(leaveEvent);
- }
- _this.cursor = null;
- };
- this.onPointerOver = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var trackingData = _this.trackingData(from.pointerId);
- var e = _this.createPointerEvent(from);
- var isMouse = e.pointerType === 'mouse' || e.pointerType === 'pen';
- _this.dispatchEvent(e, 'pointerover');
- if (isMouse) _this.dispatchEvent(e, 'mouseover');
- if (e.pointerType === 'mouse') _this.cursor = _this.getCursor(e.target);
- // pointerenter events must be fired since the pointer entered from upstream.
- var enterEvent = _this.clonePointerEvent(e, 'pointerenter');
- enterEvent.eventPhase = enterEvent.AT_TARGET;
- while (enterEvent.target && enterEvent.target !== (Node.isNode(_this.rootTarget) && _this.rootTarget.parentNode)) {
- enterEvent.currentTarget = enterEvent.target;
- _this.notifyTarget(enterEvent);
- if (isMouse) {
- // mouseenter should not bubble
- // @see https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event#usage_notes
- _this.notifyTarget(enterEvent, 'mouseenter');
- }
- if (Node.isNode(enterEvent.target)) {
- enterEvent.target = enterEvent.target.parentNode;
- }
- }
- trackingData.overTargets = e.composedPath();
- _this.freeEvent(e);
- _this.freeEvent(enterEvent);
- };
- this.onPointerUpOutside = function (from) {
- // if (!(from instanceof FederatedPointerEvent)) {
- // return;
- // }
- var trackingData = _this.trackingData(from.pointerId);
- var pressTarget = _this.findMountedTarget(trackingData.pressTargetsByButton[from.button]);
- var e = _this.createPointerEvent(from);
- if (pressTarget) {
- var currentTarget = pressTarget;
- while (currentTarget) {
- e.currentTarget = currentTarget;
- _this.notifyTarget(e, 'pointerupoutside');
- if (e.pointerType === 'touch') ; else if (e.pointerType === 'mouse' || e.pointerType === 'pen') {
- _this.notifyTarget(e, e.button === 2 ? 'rightupoutside' : 'mouseupoutside');
- }
- if (Node.isNode(currentTarget)) {
- currentTarget = currentTarget.parentNode;
- }
- }
- delete trackingData.pressTargetsByButton[from.button];
- }
- _this.freeEvent(e);
- };
- this.onWheel = function (from) {
- // if (!(from instanceof FederatedWheelEvent)) {
- // return;
- // }
- var wheelEvent = _this.createWheelEvent(from);
- _this.dispatchEvent(wheelEvent);
- _this.freeEvent(wheelEvent);
- };
- this.onClick = function (from) {
- if (_this.context.config.useNativeClickEvent) {
- var e = _this.createPointerEvent(from);
- _this.dispatchEvent(e);
- _this.freeEvent(e);
- }
- };
- this.onPointerCancel = function (from) {
- var e = _this.createPointerEvent(from, undefined, undefined, _this.context.config.alwaysTriggerPointerEventOnCanvas ? _this.rootTarget : undefined);
- _this.dispatchEvent(e);
- _this.freeEvent(e);
- };
- this.globalRuntime = globalRuntime;
- this.context = context;
- }
- var _proto = EventService.prototype;
- _proto.init = function init() {
- this.rootTarget = this.context.renderingContext.root.parentNode; // document
- this.addEventMapping('pointerdown', this.onPointerDown);
- this.addEventMapping('pointerup', this.onPointerUp);
- this.addEventMapping('pointermove', this.onPointerMove);
- this.addEventMapping('pointerout', this.onPointerOut);
- this.addEventMapping('pointerleave', this.onPointerOut);
- this.addEventMapping('pointercancel', this.onPointerCancel);
- this.addEventMapping('pointerover', this.onPointerOver);
- this.addEventMapping('pointerupoutside', this.onPointerUpOutside);
- this.addEventMapping('wheel', this.onWheel);
- this.addEventMapping('click', this.onClick);
- };
- _proto.destroy = function destroy() {
- this.emitter.removeAllListeners();
- this.mappingTable = {};
- this.mappingState = {};
- this.eventPool.clear();
- };
- _proto.client2Viewport = function client2Viewport(client) {
- var bbox = this.context.contextService.getBoundingClientRect();
- return new Point(client.x - ((bbox === null || bbox === void 0 ? void 0 : bbox.left) || 0), client.y - ((bbox === null || bbox === void 0 ? void 0 : bbox.top) || 0));
- };
- _proto.viewport2Client = function viewport2Client(canvas) {
- var bbox = this.context.contextService.getBoundingClientRect();
- return new Point(canvas.x + ((bbox === null || bbox === void 0 ? void 0 : bbox.left) || 0), canvas.y + ((bbox === null || bbox === void 0 ? void 0 : bbox.top) || 0));
- };
- _proto.viewport2Canvas = function viewport2Canvas(_ref) {
- var x = _ref.x,
- y = _ref.y;
- var canvas = this.rootTarget.defaultView;
- var camera = canvas.getCamera();
- var _this$context$config = this.context.config,
- width = _this$context$config.width,
- height = _this$context$config.height;
- var projectionMatrixInverse = camera.getPerspectiveInverse();
- var worldMatrix = camera.getWorldTransform();
- var vpMatrix = multiply(this.tmpMatrix, worldMatrix, projectionMatrixInverse);
- var viewport = set$1(this.tmpVec3, x / width * 2 - 1, (1 - y / height) * 2 - 1, 0);
- transformMat4(viewport, viewport, vpMatrix);
- return new Point(viewport[0], viewport[1]);
- };
- _proto.canvas2Viewport = function canvas2Viewport(canvasP) {
- var canvas = this.rootTarget.defaultView;
- var camera = canvas.getCamera();
- // World -> Clip
- var projectionMatrix = camera.getPerspective();
- var viewMatrix = camera.getViewTransform();
- var vpMatrix = multiply(this.tmpMatrix, projectionMatrix, viewMatrix);
- var clip = set$1(this.tmpVec3, canvasP.x, canvasP.y, 0);
- transformMat4(this.tmpVec3, this.tmpVec3, vpMatrix);
- // Clip -> NDC -> Viewport, flip Y
- var _this$context$config2 = this.context.config,
- width = _this$context$config2.width,
- height = _this$context$config2.height;
- return new Point((clip[0] + 1) / 2 * width, (1 - (clip[1] + 1) / 2) * height);
- };
- _proto.setPickHandler = function setPickHandler(pickHandler) {
- this.pickHandler = pickHandler;
- };
- _proto.addEventMapping = function addEventMapping(type, fn) {
- if (!this.mappingTable[type]) {
- this.mappingTable[type] = [];
- }
- this.mappingTable[type].push({
- fn: fn,
- priority: 0
- });
- this.mappingTable[type].sort(function (a, b) {
- return a.priority - b.priority;
- });
- };
- _proto.mapEvent = function mapEvent(e) {
- if (!this.rootTarget) {
- return;
- }
- var mappers = this.mappingTable[e.type];
- if (mappers) {
- for (var i = 0, j = mappers.length; i < j; i++) {
- mappers[i].fn(e);
- }
- } else {
- console.warn("[EventService]: Event mapping not defined for " + e.type);
- }
- };
- _proto.dispatchEvent = function dispatchEvent(e, type, skipPropagate) {
- // Canvas should skip
- if (!skipPropagate) {
- e.propagationStopped = false;
- e.propagationImmediatelyStopped = false;
- this.propagate(e, type);
- } else {
- // target phase
- e.eventPhase = e.AT_TARGET;
- var canvas = this.rootTarget.defaultView || null;
- e.currentTarget = canvas;
- this.notifyListeners(e, type);
- }
- this.emitter.emit(type || e.type, e);
- };
- _proto.propagate = function propagate(e, type) {
- if (!e.target) {
- return;
- }
- // [target, parent, root, Canvas]
- var composedPath = e.composedPath();
- // event flow: capture -> target -> bubbling
- // capture phase
- e.eventPhase = e.CAPTURING_PHASE;
- for (var i = composedPath.length - 1; i >= 1; i--) {
- e.currentTarget = composedPath[i];
- this.notifyTarget(e, type);
- if (e.propagationStopped || e.propagationImmediatelyStopped) return;
- }
- // target phase
- e.eventPhase = e.AT_TARGET;
- e.currentTarget = e.target;
- this.notifyTarget(e, type);
- if (e.propagationStopped || e.propagationImmediatelyStopped) return;
- // find current target in composed path
- var index = composedPath.indexOf(e.currentTarget);
- // bubbling phase
- e.eventPhase = e.BUBBLING_PHASE;
- for (var _i = index + 1; _i < composedPath.length; _i++) {
- e.currentTarget = composedPath[_i];
- this.notifyTarget(e, type);
- if (e.propagationStopped || e.propagationImmediatelyStopped) return;
- }
- };
- _proto.propagationPath = function propagationPath(target) {
- var propagationPath = [target];
- var canvas = this.rootTarget.defaultView || null;
- if (canvas && canvas === target) {
- propagationPath.unshift(canvas.document);
- return propagationPath;
- }
- for (var i = 0; i < PROPAGATION_LIMIT && target !== this.rootTarget; i++) {
- // if (Node.isNode(target) && !target.parentNode) {
- // throw new Error('Cannot find propagation path to disconnected target');
- // }
- if (Node.isNode(target) && target.parentNode) {
- // [target, parent, parent, root]
- propagationPath.push(target.parentNode);
- target = target.parentNode;
- }
- }
- if (canvas) {
- // @ts-ignore
- propagationPath.push(canvas);
- }
- return propagationPath;
- };
- _proto.hitTest = function hitTest(position) {
- var viewportX = position.viewportX,
- viewportY = position.viewportY;
- var _this$context$config3 = this.context.config,
- width = _this$context$config3.width,
- height = _this$context$config3.height;
- // outside canvas
- if (viewportX < 0 || viewportY < 0 || viewportX > width || viewportY > height) {
- return null;
- }
- return this.pickHandler(position) || this.rootTarget ||
- // return Document
- null;
- }
- /**
- * whether the native event trigger came from Canvas,
- * should account for HTML shape
- */;
- _proto.isNativeEventFromCanvas = function isNativeEventFromCanvas(event) {
- var _event$nativeEvent;
- var $el = this.context.contextService.getDomElement();
- var target = (_event$nativeEvent = event.nativeEvent) === null || _event$nativeEvent === void 0 ? void 0 : _event$nativeEvent.target;
- if (target) {
- // from <canvas>
- if (target === $el) {
- return true;
- }
- // from <svg>
- if ($el && $el.contains) {
- return $el.contains(target);
- }
- }
- if (event.nativeEvent.composedPath) {
- return event.nativeEvent.composedPath().indexOf($el) > -1;
- }
- // account for Touch
- return false;
- }
- /**
- * Find HTML from composed path in native UI event.
- */;
- _proto.getExistedHTML = function getExistedHTML(event) {
- if (event.nativeEvent.composedPath) {
- for (var _iterator = _createForOfIteratorHelperLoose(event.nativeEvent.composedPath()), _step; !(_step = _iterator()).done;) {
- var eventTarget = _step.value;
- var existed = runtime.nativeHTMLMap.get(eventTarget);
- if (existed) {
- return existed;
- }
- }
- }
- return null;
- };
- _proto.pickTarget = function pickTarget(event) {
- return this.hitTest({
- clientX: event.clientX,
- clientY: event.clientY,
- viewportX: event.viewportX,
- viewportY: event.viewportY,
- x: event.canvasX,
- y: event.canvasY
- });
- };
- _proto.createPointerEvent = function createPointerEvent(from, type, target, fallbackTarget) {
- var event = this.allocateEvent(FederatedPointerEvent);
- this.copyPointerData(from, event);
- this.copyMouseData(from, event);
- this.copyData(from, event);
- event.nativeEvent = from.nativeEvent;
- event.originalEvent = from;
- var existedHTML = this.getExistedHTML(event);
- event.target = target !== null && target !== void 0 ? target : existedHTML || this.isNativeEventFromCanvas(event) && this.pickTarget(event) || fallbackTarget;
- if (typeof type === 'string') {
- event.type = type;
- }
- return event;
- };
- _proto.createWheelEvent = function createWheelEvent(from) {
- var event = this.allocateEvent(FederatedWheelEvent);
- this.copyWheelData(from, event);
- this.copyMouseData(from, event);
- this.copyData(from, event);
- event.nativeEvent = from.nativeEvent;
- event.originalEvent = from;
- var existedHTML = this.getExistedHTML(event);
- event.target = existedHTML || this.isNativeEventFromCanvas(event) && this.pickTarget(event);
- return event;
- };
- _proto.trackingData = function trackingData(id) {
- if (!this.mappingState.trackingData[id]) {
- this.mappingState.trackingData[id] = {
- pressTargetsByButton: {},
- clicksByButton: {},
- overTarget: null
- };
- }
- return this.mappingState.trackingData[id];
- };
- _proto.cloneWheelEvent = function cloneWheelEvent(from) {
- var event = this.allocateEvent(FederatedWheelEvent);
- event.nativeEvent = from.nativeEvent;
- event.originalEvent = from.originalEvent;
- this.copyWheelData(from, event);
- this.copyMouseData(from, event);
- this.copyData(from, event);
- event.target = from.target;
- event.path = from.composedPath().slice();
- event.type = from.type;
- return event;
- };
- _proto.clonePointerEvent = function clonePointerEvent(from, type) {
- var event = this.allocateEvent(FederatedPointerEvent);
- event.nativeEvent = from.nativeEvent;
- event.originalEvent = from.originalEvent;
- this.copyPointerData(from, event);
- this.copyMouseData(from, event);
- this.copyData(from, event);
- event.target = from.target;
- event.path = from.composedPath().slice();
- event.type = type !== null && type !== void 0 ? type : event.type;
- return event;
- };
- _proto.copyPointerData = function copyPointerData(from, to) {
- // if (
- // !(
- // from instanceof FederatedPointerEvent &&
- // to instanceof FederatedPointerEvent
- // )
- // )
- // return;
- to.pointerId = from.pointerId;
- to.width = from.width;
- to.height = from.height;
- to.isPrimary = from.isPrimary;
- to.pointerType = from.pointerType;
- to.pressure = from.pressure;
- to.tangentialPressure = from.tangentialPressure;
- to.tiltX = from.tiltX;
- to.tiltY = from.tiltY;
- to.twist = from.twist;
- };
- _proto.copyMouseData = function copyMouseData(from, to) {
- // if (
- // !(
- // from instanceof FederatedMouseEvent && to instanceof FederatedMouseEvent
- // )
- // )
- // return;
- to.altKey = from.altKey;
- to.button = from.button;
- to.buttons = from.buttons;
- to.ctrlKey = from.ctrlKey;
- to.metaKey = from.metaKey;
- to.shiftKey = from.shiftKey;
- to.client.copyFrom(from.client);
- to.movement.copyFrom(from.movement);
- to.canvas.copyFrom(from.canvas);
- to.screen.copyFrom(from.screen);
- to.global.copyFrom(from.global);
- to.offset.copyFrom(from.offset);
- };
- _proto.copyWheelData = function copyWheelData(from, to) {
- to.deltaMode = from.deltaMode;
- to.deltaX = from.deltaX;
- to.deltaY = from.deltaY;
- to.deltaZ = from.deltaZ;
- };
- _proto.copyData = function copyData(from, to) {
- to.isTrusted = from.isTrusted;
- to.timeStamp = performance.now();
- to.type = from.type;
- to.detail = from.detail;
- to.view = from.view;
- to.page.copyFrom(from.page);
- to.viewport.copyFrom(from.viewport);
- };
- _proto.allocateEvent = function allocateEvent(constructor) {
- if (!this.eventPool.has(constructor)) {
- this.eventPool.set(constructor, []);
- }
- // @ts-ignore
- var event = this.eventPool.get(constructor).pop() || new constructor(this);
- event.eventPhase = event.NONE;
- event.currentTarget = null;
- event.path = [];
- event.target = null;
- return event;
- };
- _proto.freeEvent = function freeEvent(event) {
- if (event.manager !== this) throw new Error('It is illegal to free an event not managed by this EventBoundary!');
- var constructor = event.constructor;
- if (!this.eventPool.has(constructor)) {
- this.eventPool.set(constructor, []);
- }
- // @ts-ignore
- this.eventPool.get(constructor).push(event);
- };
- _proto.notifyTarget = function notifyTarget(e, type) {
- var _type;
- type = (_type = type) !== null && _type !== void 0 ? _type : e.type;
- var key = e.eventPhase === e.CAPTURING_PHASE || e.eventPhase === e.AT_TARGET ? type + "capture" : type;
- this.notifyListeners(e, key);
- if (e.eventPhase === e.AT_TARGET) {
- this.notifyListeners(e, type);
- }
- };
- _proto.notifyListeners = function notifyListeners(e, type) {
- // hack EventEmitter, stops if the `propagationImmediatelyStopped` flag is set
- // @ts-ignore
- var emitter = e.currentTarget.emitter;
- // @ts-ignore
- var listeners = emitter._events[type];
- if (!listeners) return;
- if ('fn' in listeners) {
- if (listeners.once) {
- emitter.removeListener(type, listeners.fn, undefined, true);
- }
- listeners.fn.call(e.currentTarget || listeners.context, e);
- // listeners.fn.call(listeners.context, e);
- } else {
- for (var i = 0; i < listeners.length && !e.propagationImmediatelyStopped; i++) {
- if (listeners[i].once) {
- emitter.removeListener(type, listeners[i].fn, undefined, true);
- }
- listeners[i].fn.call(e.currentTarget || listeners[i].context, e);
- // listeners[i].fn.call(listeners[i].context, e);
- }
- }
- }
- /**
- * some detached nodes may exist in propagation path, need to skip them
- */;
- _proto.findMountedTarget = function findMountedTarget(propagationPath) {
- if (!propagationPath) {
- return null;
- }
- var currentTarget = propagationPath[propagationPath.length - 1];
- for (var i = propagationPath.length - 2; i >= 0; i--) {
- var target = propagationPath[i];
- if (target === this.rootTarget || Node.isNode(target) && target.parentNode === currentTarget) {
- currentTarget = propagationPath[i];
- } else {
- break;
- }
- }
- return currentTarget;
- };
- _proto.getCursor = function getCursor(target) {
- var tmp = target;
- while (tmp) {
- var cursor = Element.isElement(tmp) && tmp.getAttribute('cursor');
- if (cursor) {
- return cursor;
- }
- tmp = Node.isNode(tmp) && tmp.parentNode;
- }
- };
- return EventService;
- }();
- /**
- * used in following scenes:
- * - g `ctx.measureText`
- * - g-plugin-canvas-picker `ctx.isPointInPath`
- * - g-plugin-device-renderer `ctx.createLinearGradient` and generate texture
- *
- * @see https://blog.scottlogic.com/2020/03/19/offscreen-canvas.html
- */
- var OffscreenCanvasCreator = /*#__PURE__*/function () {
- function OffscreenCanvasCreator() {
- this.canvas = void 0;
- this.context = void 0;
- }
- var _proto = OffscreenCanvasCreator.prototype;
- _proto.getOrCreateCanvas = function getOrCreateCanvas(offscreenCanvas, contextAttributes) {
- if (this.canvas) {
- return this.canvas;
- }
- // user-defined offscreen canvas
- if (offscreenCanvas) {
- this.canvas = offscreenCanvas;
- this.context = this.canvas.getContext('2d', contextAttributes);
- } else {
- try {
- // OffscreenCanvas2D measureText can be up to 40% faster.
- this.canvas = new window.OffscreenCanvas(0, 0);
- this.context = this.canvas.getContext('2d', contextAttributes);
- if (!this.context || !this.context.measureText) {
- this.canvas = document.createElement('canvas');
- this.context = this.canvas.getContext('2d');
- }
- } catch (ex) {
- this.canvas = document.createElement('canvas');
- this.context = this.canvas.getContext('2d', contextAttributes);
- }
- }
- this.canvas.width = 10;
- this.canvas.height = 10;
- return this.canvas;
- };
- _proto.getOrCreateContext = function getOrCreateContext(offscreenCanvas, contextAttributes) {
- if (this.context) {
- return this.context;
- }
- this.getOrCreateCanvas(offscreenCanvas, contextAttributes);
- return this.context;
- };
- return OffscreenCanvasCreator;
- }();
- /**
- * why we need re-render
- */
- (function (RenderReason) {
- RenderReason[RenderReason["CAMERA_CHANGED"] = 0] = "CAMERA_CHANGED";
- RenderReason[RenderReason["DISPLAY_OBJECT_CHANGED"] = 1] = "DISPLAY_OBJECT_CHANGED";
- RenderReason[RenderReason["NONE"] = 2] = "NONE";
- })(exports.RenderReason || (exports.RenderReason = {}));
- /**
- * Use frame renderer implemented by `g-canvas/svg/webgl`, in every frame we do followings:
- * * update & merge dirty rectangles
- * * begin frame
- * * filter by visible
- * * sort by z-index in scene graph
- * * culling with strategies registered in `g-canvas/webgl`
- * * end frame
- */
- var RenderingService = /*#__PURE__*/function () {
- function RenderingService(globalRuntime, context) {
- this.globalRuntime = void 0;
- this.context = void 0;
- this.inited = false;
- this.stats = {
- /**
- * total display objects in scenegraph
- */
- total: 0,
- /**
- * number of display objects need to render in current frame
- */
- rendered: 0
- };
- this.zIndexCounter = 0;
- this.hooks = {
- /**
- * called before any frame rendered
- */
- init: new SyncHook(),
- initAsync: new AsyncParallelHook(),
- /**
- * only dirty object which has sth changed will be rendered
- */
- dirtycheck: new SyncWaterfallHook(),
- /**
- * do culling
- */
- cull: new SyncWaterfallHook(),
- /**
- * called at beginning of each frame, won't get called if nothing to re-render
- */
- beginFrame: new SyncHook(),
- /**
- * called before every dirty object get rendered
- */
- beforeRender: new SyncHook(),
- /**
- * called when every dirty object rendering even it's culled
- */
- render: new SyncHook(),
- /**
- * called after every dirty object get rendered
- */
- afterRender: new SyncHook(),
- endFrame: new SyncHook(),
- destroy: new SyncHook(),
- /**
- * use async but faster method such as GPU-based picking in `g-plugin-device-renderer`
- */
- pick: new AsyncSeriesWaterfallHook(),
- /**
- * Unsafe but sync version of pick.
- */
- pickSync: new SyncWaterfallHook(),
- /**
- * used in event system
- */
- pointerDown: new SyncHook(),
- pointerUp: new SyncHook(),
- pointerMove: new SyncHook(),
- pointerOut: new SyncHook(),
- pointerOver: new SyncHook(),
- pointerWheel: new SyncHook(),
- pointerCancel: new SyncHook(),
- click: new SyncHook()
- };
- this.globalRuntime = globalRuntime;
- this.context = context;
- }
- var _proto = RenderingService.prototype;
- _proto.init = function init(callback) {
- var _this = this;
- var context = _extends({}, this.globalRuntime, this.context);
- // register rendering plugins
- this.context.renderingPlugins.forEach(function (plugin) {
- plugin.apply(context, runtime);
- });
- this.hooks.init.call();
- if (this.hooks.initAsync.getCallbacksNum() === 0) {
- this.inited = true;
- callback();
- } else {
- this.hooks.initAsync.promise().then(function () {
- _this.inited = true;
- callback();
- });
- }
- };
- _proto.getStats = function getStats() {
- return this.stats;
- }
- /**
- * Meet the following conditions:
- * * disable DirtyRectangleRendering
- * * camera changed
- */;
- _proto.disableDirtyRectangleRendering = function disableDirtyRectangleRendering() {
- var renderer = this.context.config.renderer;
- var _renderer$getConfig = renderer.getConfig(),
- enableDirtyRectangleRendering = _renderer$getConfig.enableDirtyRectangleRendering;
- return !enableDirtyRectangleRendering || this.context.renderingContext.renderReasons.has(exports.RenderReason.CAMERA_CHANGED);
- };
- _proto.render = function render(canvasConfig, rerenderCallback) {
- var _this2 = this;
- this.stats.total = 0;
- this.stats.rendered = 0;
- this.zIndexCounter = 0;
- var renderingContext = this.context.renderingContext;
- this.globalRuntime.sceneGraphService.syncHierarchy(renderingContext.root);
- this.globalRuntime.sceneGraphService.triggerPendingEvents();
- if (renderingContext.renderReasons.size && this.inited) {
- this.renderDisplayObject(renderingContext.root, canvasConfig, renderingContext);
- this.hooks.beginFrame.call();
- renderingContext.renderListCurrentFrame.forEach(function (object) {
- _this2.hooks.beforeRender.call(object);
- _this2.hooks.render.call(object);
- _this2.hooks.afterRender.call(object);
- });
- this.hooks.endFrame.call();
- renderingContext.renderListCurrentFrame = [];
- renderingContext.renderReasons.clear();
- rerenderCallback();
- }
- // console.log('stats', this.stats);
- };
- _proto.renderDisplayObject = function renderDisplayObject(displayObject, canvasConfig, renderingContext) {
- var _this3 = this;
- var _canvasConfig$rendere = canvasConfig.renderer.getConfig(),
- enableDirtyCheck = _canvasConfig$rendere.enableDirtyCheck,
- enableCulling = _canvasConfig$rendere.enableCulling;
- // recalc style values
- if (this.globalRuntime.enableCSSParsing) {
- this.globalRuntime.styleValueRegistry.recalc(displayObject);
- }
- // TODO: relayout
- // dirtycheck first
- var objectChanged = enableDirtyCheck ? this.hooks.dirtycheck.call(displayObject) : displayObject;
- if (objectChanged) {
- var objectToRender = enableCulling ? this.hooks.cull.call(objectChanged, this.context.camera) : objectChanged;
- if (objectToRender) {
- this.stats.rendered++;
- renderingContext.renderListCurrentFrame.push(objectToRender);
- }
- }
- displayObject.renderable.dirty = false;
- displayObject.sortable.renderOrder = this.zIndexCounter++;
- this.stats.total++;
- // sort is very expensive, use cached result if possible
- var sortable = displayObject.sortable;
- if (sortable.dirty) {
- this.sort(displayObject, sortable);
- sortable.dirty = false;
- sortable.dirtyChildren = [];
- sortable.dirtyReason = undefined;
- }
- // recursive rendering its children
- (sortable.sorted || displayObject.childNodes).forEach(function (child) {
- _this3.renderDisplayObject(child, canvasConfig, renderingContext);
- });
- };
- _proto.sort = function sort(displayObject, sortable) {
- if (sortable.sorted && sortable.dirtyReason !== exports.SortReason.Z_INDEX_CHANGED) {
- // avoid re-sorting the whole children list
- sortable.dirtyChildren.forEach(function (child) {
- var index = displayObject.childNodes.indexOf(child);
- if (index === -1) {
- // remove from sorted list
- var _index = sortable.sorted.indexOf(child);
- if (_index >= 0) {
- sortable.sorted.splice(_index, 1);
- }
- } else {
- if (sortable.sorted.length === 0) {
- sortable.sorted.push(child);
- } else {
- var _index2 = sortedIndex(sortable.sorted, child);
- sortable.sorted.splice(_index2, 0, child);
- }
- }
- });
- } else {
- sortable.sorted = displayObject.childNodes.slice().sort(sortByZIndex);
- }
- };
- _proto.destroy = function destroy() {
- this.inited = false;
- this.hooks.destroy.call();
- this.globalRuntime.sceneGraphService.clearPendingEvents();
- };
- _proto.dirtify = function dirtify() {
- // need re-render
- this.context.renderingContext.renderReasons.add(exports.RenderReason.DISPLAY_OBJECT_CHANGED);
- };
- return RenderingService;
- }();
- var ATTRIBUTE_REGEXP = /\[\s*(.*)=(.*)\s*\]/;
- /**
- * support the following DOM API:
- * * getElementById
- * * getElementsByClassName
- * * getElementsByName
- * * getElementsByTag
- * * querySelector
- * * querySelectorAll
- */
- var DefaultSceneGraphSelector = /*#__PURE__*/function () {
- function DefaultSceneGraphSelector() {}
- var _proto = DefaultSceneGraphSelector.prototype;
- _proto.selectOne = function selectOne(query, root) {
- var _this = this;
- if (query.startsWith('.')) {
- return root.find(function (node) {
- // return !node.shadow && node.id === query.substring(1);
- return ((node === null || node === void 0 ? void 0 : node.classList) || []).indexOf(_this.getIdOrClassname(query)) > -1;
- });
- } else if (query.startsWith('#')) {
- // getElementById('id')
- return root.find(function (node) {
- // return !node.shadow && node.id === query.substring(1);
- return node.id === _this.getIdOrClassname(query);
- });
- } else if (query.startsWith('[')) {
- var _this$getAttribute = this.getAttribute(query),
- name = _this$getAttribute.name,
- value = _this$getAttribute.value;
- if (name) {
- // getElementByName();
- return root.find(function (node) {
- return root !== node && (name === 'name' ? node.name === value : _this.attributeToString(node, name) === value);
- });
- } else {
- return null;
- }
- } else {
- // getElementsByTag('circle');
- return root.find(function (node) {
- return root !== node && node.nodeName === query;
- });
- }
- };
- _proto.selectAll = function selectAll(query, root) {
- var _this2 = this;
- // only support `[name="${name}"]` `.className` `#id`
- if (query.startsWith('.')) {
- // getElementsByClassName('className');
- // should not include itself
- return root.findAll(function (node) {
- return root !== node && ((node === null || node === void 0 ? void 0 : node.classList) || []).indexOf(_this2.getIdOrClassname(query)) > -1;
- });
- } else if (query.startsWith('#')) {
- return root.findAll(function (node) {
- return root !== node && node.id === _this2.getIdOrClassname(query);
- });
- } else if (query.startsWith('[')) {
- var _this$getAttribute2 = this.getAttribute(query),
- name = _this$getAttribute2.name,
- value = _this$getAttribute2.value;
- if (name) {
- // getElementsByName();
- return root.findAll(function (node) {
- return root !== node && (name === 'name' ? node.name === value : _this2.attributeToString(node, name) === value);
- });
- } else {
- return [];
- }
- } else {
- // getElementsByTag('circle');
- return root.findAll(function (node) {
- return root !== node && node.nodeName === query;
- });
- }
- };
- _proto.is = function is(query, node) {
- // a simple `matches` implementation
- if (query.startsWith('.')) {
- return node.className === this.getIdOrClassname(query);
- } else if (query.startsWith('#')) {
- return node.id === this.getIdOrClassname(query);
- } else if (query.startsWith('[')) {
- var _this$getAttribute3 = this.getAttribute(query),
- name = _this$getAttribute3.name,
- value = _this$getAttribute3.value;
- return name === 'name' ? node.name === value : this.attributeToString(node, name) === value;
- } else {
- return node.nodeName === query;
- }
- };
- _proto.getIdOrClassname = function getIdOrClassname(query) {
- return query.substring(1);
- };
- _proto.getAttribute = function getAttribute(query) {
- var matches = query.match(ATTRIBUTE_REGEXP);
- var name = '';
- var value = '';
- if (matches && matches.length > 2) {
- name = matches[1].replace(/"/g, '');
- value = matches[2].replace(/"/g, '');
- }
- return {
- name: name,
- value: value
- };
- };
- _proto.attributeToString = function attributeToString(node, name) {
- if (!node.getAttribute) {
- return '';
- }
- var value = node.getAttribute(name);
- if (isNil(value)) {
- return '';
- }
- if (value.toString) {
- return value.toString();
- }
- return '';
- };
- return DefaultSceneGraphSelector;
- }();
- function markRenderableDirty(e) {
- var renderable = e.renderable;
- if (renderable) {
- renderable.renderBoundsDirty = true;
- renderable.boundsDirty = true;
- }
- }
- var reparentEvent = new MutationEvent(exports.ElementEvent.REPARENT, null, '', '', '', 0, '', '');
- /**
- * update transform in scene graph
- *
- * @see https://community.khronos.org/t/scene-graphs/50542/7
- */
- var DefaultSceneGraphService = /*#__PURE__*/function () {
- function DefaultSceneGraphService(runtime) {
- var _this = this;
- this.runtime = void 0;
- this.pendingEvents = [];
- this.boundsChangedEvent = new CustomEvent(exports.ElementEvent.BOUNDS_CHANGED);
- /**
- * rotate in world space
- */
- this.rotate = function () {
- var parentInvertRotation = create$4();
- return function (element, degrees, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof degrees === 'number') {
- degrees = fromValues$2(degrees, y, z);
- }
- var transform = element.transformable;
- if (element.parentNode === null || !element.parentNode.transformable) {
- _this.rotateLocal(element, degrees);
- } else {
- var rotation = create$4();
- fromEuler(rotation, degrees[0], degrees[1], degrees[2]);
- var rot = _this.getRotation(element);
- var parentRot = _this.getRotation(element.parentNode);
- copy$3(parentInvertRotation, parentRot);
- invert$1(parentInvertRotation, parentInvertRotation);
- multiply$2(rotation, parentInvertRotation, rotation);
- multiply$2(transform.localRotation, rotation, rot);
- normalize$2(transform.localRotation, transform.localRotation);
- _this.dirtifyLocal(element, transform);
- }
- };
- }();
- /**
- * rotate in local space
- * @see @see https://docs.microsoft.com/en-us/windows/win32/api/directxmath/nf-directxmath-xmquaternionrotationrollpitchyaw
- */
- this.rotateLocal = function () {
- var rotation = create$4();
- return function (element, degrees, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof degrees === 'number') {
- degrees = fromValues$2(degrees, y, z);
- }
- var transform = element.transformable;
- fromEuler(rotation, degrees[0], degrees[1], degrees[2]);
- mul$1(transform.localRotation, transform.localRotation, rotation);
- _this.dirtifyLocal(element, transform);
- };
- }();
- /**
- * set euler angles(degrees) in world space
- */
- this.setEulerAngles = function () {
- var invParentRot = create$4();
- return function (element, degrees, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof degrees === 'number') {
- degrees = fromValues$2(degrees, y, z);
- }
- var transform = element.transformable;
- if (element.parentNode === null || !element.parentNode.transformable) {
- _this.setLocalEulerAngles(element, degrees);
- } else {
- fromEuler(transform.localRotation, degrees[0], degrees[1], degrees[2]);
- var parentRotation = _this.getRotation(element.parentNode);
- copy$3(invParentRot, invert$1(create$4(), parentRotation));
- mul$1(transform.localRotation, transform.localRotation, invParentRot);
- _this.dirtifyLocal(element, transform);
- }
- };
- }();
- /**
- * translate in local space
- *
- * @example
- * ```
- * translateLocal(x, y, z)
- * translateLocal(vec3(x, y, z))
- * ```
- */
- this.translateLocal = function () {
- return function (element, translation, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof translation === 'number') {
- translation = fromValues$2(translation, y, z);
- }
- var transform = element.transformable;
- if (equals$1(translation, create$2())) {
- return;
- }
- transformQuat(translation, translation, transform.localRotation);
- add$1(transform.localPosition, transform.localPosition, translation);
- _this.dirtifyLocal(element, transform);
- };
- }();
- /**
- * move to position in world space
- *
- * 对应 g 原版的 move/moveTo
- * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L684-L689
- */
- this.setPosition = function () {
- var parentInvertMatrix = create$1();
- var tmpPosition = create$2();
- return function (element, position) {
- var transform = element.transformable;
- tmpPosition[0] = position[0];
- tmpPosition[1] = position[1];
- tmpPosition[2] = position[2] || 0;
- if (equals$1(_this.getPosition(element), tmpPosition)) {
- return;
- }
- copy$1(transform.position, tmpPosition);
- if (element.parentNode === null || !element.parentNode.transformable) {
- copy$1(transform.localPosition, tmpPosition);
- } else {
- var parentTransform = element.parentNode.transformable;
- copy(parentInvertMatrix, parentTransform.worldTransform);
- invert(parentInvertMatrix, parentInvertMatrix);
- transformMat4(transform.localPosition, tmpPosition, parentInvertMatrix);
- }
- _this.dirtifyLocal(element, transform);
- };
- }();
- /**
- * move to position in local space
- */
- this.setLocalPosition = function () {
- var tmpPosition = create$2();
- return function (element, position) {
- var transform = element.transformable;
- tmpPosition[0] = position[0];
- tmpPosition[1] = position[1];
- tmpPosition[2] = position[2] || 0;
- if (equals$1(transform.localPosition, tmpPosition)) {
- return;
- }
- copy$1(transform.localPosition, tmpPosition);
- _this.dirtifyLocal(element, transform);
- };
- }();
- /**
- * translate in world space
- *
- * @example
- * ```
- * translate(x, y, z)
- * translate(vec3(x, y, z))
- * ```
- *
- * 对应 g 原版的 translate 2D
- * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L665-L676
- */
- this.translate = function () {
- var zeroVec3 = create$2();
- var tmpVec3 = create$2();
- var tr = create$2();
- return function (element, translation, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof translation === 'number') {
- translation = set$1(tmpVec3, translation, y, z);
- }
- if (equals$1(translation, zeroVec3)) {
- return;
- }
- add$1(tr, _this.getPosition(element), translation);
- _this.setPosition(element, tr);
- };
- }();
- this.setRotation = function () {
- var parentInvertRotation = create$4();
- return function (element, rotation, y, z, w) {
- var transform = element.transformable;
- if (typeof rotation === 'number') {
- rotation = fromValues$4(rotation, y, z, w);
- }
- if (element.parentNode === null || !element.parentNode.transformable) {
- _this.setLocalRotation(element, rotation);
- } else {
- var parentRot = _this.getRotation(element.parentNode);
- copy$3(parentInvertRotation, parentRot);
- invert$1(parentInvertRotation, parentInvertRotation);
- multiply$2(transform.localRotation, parentInvertRotation, rotation);
- normalize$2(transform.localRotation, transform.localRotation);
- _this.dirtifyLocal(element, transform);
- }
- };
- };
- this.displayObjectDependencyMap = new WeakMap();
- this.calcLocalTransform = function () {
- var tmpMat = create$1();
- var tmpPosition = create$2();
- var tmpQuat = fromValues$4(0, 0, 0, 1);
- return function (transform) {
- var hasSkew = transform.localSkew[0] !== 0 || transform.localSkew[1] !== 0;
- if (hasSkew) {
- fromRotationTranslationScaleOrigin(transform.localTransform, transform.localRotation, transform.localPosition, fromValues$2(1, 1, 1), transform.origin);
- // apply skew2D
- if (transform.localSkew[0] !== 0 || transform.localSkew[1] !== 0) {
- var tmpMat4 = identity(tmpMat);
- tmpMat4[4] = Math.tan(transform.localSkew[0]);
- tmpMat4[1] = Math.tan(transform.localSkew[1]);
- multiply(transform.localTransform, transform.localTransform, tmpMat4);
- }
- var scaling = fromRotationTranslationScaleOrigin(tmpMat, tmpQuat, tmpPosition, transform.localScale, transform.origin);
- multiply(transform.localTransform, transform.localTransform, scaling);
- } else {
- // @see https://github.com/mattdesl/css-mat4/blob/master/index.js
- fromRotationTranslationScaleOrigin(transform.localTransform, transform.localRotation, transform.localPosition, transform.localScale, transform.origin);
- }
- };
- }();
- this.runtime = runtime;
- }
- var _proto = DefaultSceneGraphService.prototype;
- _proto.matches = function matches(query, root) {
- return this.runtime.sceneGraphSelector.is(query, root);
- };
- _proto.querySelector = function querySelector(query, root) {
- return this.runtime.sceneGraphSelector.selectOne(query, root);
- };
- _proto.querySelectorAll = function querySelectorAll(query, root) {
- return this.runtime.sceneGraphSelector.selectAll(query, root);
- // .filter((node) => !node.shadow);
- };
- _proto.attach = function attach(child, parent, index) {
- var _sortable$sorted, _child$style;
- var detached = false;
- if (child.parentNode) {
- detached = child.parentNode !== parent;
- this.detach(child);
- }
- child.parentNode = parent;
- if (!isNil(index)) {
- child.parentNode.childNodes.splice(index, 0, child);
- } else {
- child.parentNode.childNodes.push(child);
- }
- // parent needs re-sort
- var sortable = parent.sortable;
- if ((sortable === null || sortable === void 0 ? void 0 : (_sortable$sorted = sortable.sorted) === null || _sortable$sorted === void 0 ? void 0 : _sortable$sorted.length) || ((_child$style = child.style) === null || _child$style === void 0 ? void 0 : _child$style.zIndex)) {
- if (sortable.dirtyChildren.indexOf(child) === -1) {
- sortable.dirtyChildren.push(child);
- }
- // if (sortable) {
- // only child has z-Index
- sortable.dirty = true;
- sortable.dirtyReason = exports.SortReason.ADDED;
- }
- // this.updateGraphDepth(child);
- var transform = child.transformable;
- if (transform) {
- this.dirtifyWorld(child, transform);
- }
- if (transform.frozen) {
- this.unfreezeParentToRoot(child);
- }
- if (detached) {
- child.dispatchEvent(reparentEvent);
- }
- };
- _proto.detach = function detach(child) {
- if (child.parentNode) {
- var _sortable$sorted2, _child$style2;
- var transform = child.transformable;
- // if (transform) {
- // const worldTransform = this.getWorldTransform(child, transform);
- // mat4.getScaling(transform.localScale, worldTransform);
- // mat4.getTranslation(transform.localPosition, worldTransform);
- // mat4.getRotation(transform.localRotation, worldTransform);
- // transform.localDirtyFlag = true;
- // }
- // parent needs re-sort
- var sortable = child.parentNode.sortable;
- // if (sortable) {
- if ((sortable === null || sortable === void 0 ? void 0 : (_sortable$sorted2 = sortable.sorted) === null || _sortable$sorted2 === void 0 ? void 0 : _sortable$sorted2.length) || ((_child$style2 = child.style) === null || _child$style2 === void 0 ? void 0 : _child$style2.zIndex)) {
- if (sortable.dirtyChildren.indexOf(child) === -1) {
- sortable.dirtyChildren.push(child);
- }
- sortable.dirty = true;
- sortable.dirtyReason = exports.SortReason.REMOVED;
- }
- var index = child.parentNode.childNodes.indexOf(child);
- if (index > -1) {
- child.parentNode.childNodes.splice(index, 1);
- }
- if (transform) {
- this.dirtifyWorld(child, transform);
- }
- child.parentNode = null;
- }
- };
- _proto.getOrigin = function getOrigin(element) {
- return element.transformable.origin;
- }
- /**
- * same as pivot in Pixi.js
- *
- * @see https://stackoverflow.com/questions/40748452/how-to-change-css-transform-origin-but-preserve-transformation
- */;
- _proto.setOrigin = function setOrigin(element, origin, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof origin === 'number') {
- origin = [origin, y, z];
- }
- var transform = element.transformable;
- if (origin[0] === transform.origin[0] && origin[1] === transform.origin[1] && origin[2] === transform.origin[2]) {
- return;
- }
- var originVec = transform.origin;
- // const delta = vec3.subtract(vec3.create(), origin, originVec);
- // vec3.add(transform.localPosition, transform.localPosition, delta);
- // update origin
- originVec[0] = origin[0];
- originVec[1] = origin[1];
- originVec[2] = origin[2] || 0;
- this.dirtifyLocal(element, transform);
- };
- /**
- * set euler angles(degrees) in local space
- */
- _proto.setLocalEulerAngles = function setLocalEulerAngles(element, degrees, y, z) {
- if (y === void 0) {
- y = 0;
- }
- if (z === void 0) {
- z = 0;
- }
- if (typeof degrees === 'number') {
- degrees = fromValues$2(degrees, y, z);
- }
- var transform = element.transformable;
- fromEuler(transform.localRotation, degrees[0], degrees[1], degrees[2]);
- this.dirtifyLocal(element, transform);
- };
- /**
- * scale in local space
- */
- _proto.scaleLocal = function scaleLocal(element, scaling) {
- var transform = element.transformable;
- multiply$1(transform.localScale, transform.localScale, fromValues$2(scaling[0], scaling[1], scaling[2] || 1));
- this.dirtifyLocal(element, transform);
- };
- _proto.setLocalScale = function setLocalScale(element, scaling) {
- var transform = element.transformable;
- var updatedScaling = fromValues$2(scaling[0], scaling[1], scaling[2] || transform.localScale[2]);
- if (equals$1(updatedScaling, transform.localScale)) {
- return;
- }
- copy$1(transform.localScale, updatedScaling);
- this.dirtifyLocal(element, transform);
- };
- _proto.setLocalRotation = function setLocalRotation(element, rotation, y, z, w) {
- if (typeof rotation === 'number') {
- rotation = fromValues$4(rotation, y, z, w);
- }
- var transform = element.transformable;
- copy$3(transform.localRotation, rotation);
- this.dirtifyLocal(element, transform);
- };
- _proto.setLocalSkew = function setLocalSkew(element, skew, y) {
- if (typeof skew === 'number') {
- skew = fromValues$5(skew, y);
- }
- var transform = element.transformable;
- copy$4(transform.localSkew, skew);
- this.dirtifyLocal(element, transform);
- };
- _proto.dirtifyLocal = function dirtifyLocal(element, transform) {
- if (!transform.localDirtyFlag) {
- transform.localDirtyFlag = true;
- if (!transform.dirtyFlag) {
- this.dirtifyWorld(element, transform);
- }
- }
- };
- _proto.dirtifyWorld = function dirtifyWorld(element, transform) {
- if (!transform.dirtyFlag) {
- this.unfreezeParentToRoot(element);
- }
- this.dirtifyWorldInternal(element, transform);
- this.dirtifyToRoot(element, true);
- };
- _proto.triggerPendingEvents = function triggerPendingEvents() {
- var _this2 = this;
- var set = new Set();
- var trigger = function trigger(element, detail) {
- if (element.isConnected && !set.has(element.entity)) {
- _this2.boundsChangedEvent.detail = detail;
- _this2.boundsChangedEvent.target = element;
- if (element.isMutationObserved) {
- element.dispatchEvent(_this2.boundsChangedEvent);
- } else {
- element.ownerDocument.defaultView.dispatchEvent(_this2.boundsChangedEvent, true);
- }
- set.add(element.entity);
- }
- };
- this.pendingEvents.forEach(function (_ref) {
- var element = _ref[0],
- detail = _ref[1];
- if (detail.affectChildren) {
- element.forEach(function (e) {
- trigger(e, detail);
- });
- } else {
- trigger(element, detail);
- }
- });
- this.clearPendingEvents();
- set.clear();
- };
- _proto.clearPendingEvents = function clearPendingEvents() {
- this.pendingEvents = [];
- };
- _proto.dirtifyToRoot = function dirtifyToRoot(element, affectChildren) {
- if (affectChildren === void 0) {
- affectChildren = false;
- }
- var p = element;
- // only need to re-render itself
- if (p.renderable) {
- p.renderable.dirty = true;
- }
- while (p) {
- markRenderableDirty(p);
- p = p.parentNode;
- }
- if (affectChildren) {
- element.forEach(function (e) {
- markRenderableDirty(e);
- });
- }
- // inform dependencies
- this.informDependentDisplayObjects(element);
- // reuse the same custom event
- this.pendingEvents.push([element, {
- affectChildren: affectChildren
- }]);
- };
- _proto.updateDisplayObjectDependency = function updateDisplayObjectDependency(name, oldPath, newPath, object) {
- // clear ref to old clip path
- if (oldPath && oldPath !== newPath) {
- var oldDependencyMap = this.displayObjectDependencyMap.get(oldPath);
- if (oldDependencyMap && oldDependencyMap[name]) {
- var index = oldDependencyMap[name].indexOf(object);
- oldDependencyMap[name].splice(index, 1);
- }
- }
- if (newPath) {
- var newDependencyMap = this.displayObjectDependencyMap.get(newPath);
- if (!newDependencyMap) {
- this.displayObjectDependencyMap.set(newPath, {});
- newDependencyMap = this.displayObjectDependencyMap.get(newPath);
- }
- if (!newDependencyMap[name]) {
- newDependencyMap[name] = [];
- }
- newDependencyMap[name].push(object);
- }
- };
- _proto.informDependentDisplayObjects = function informDependentDisplayObjects(object) {
- var _this3 = this;
- var dependencyMap = this.displayObjectDependencyMap.get(object);
- if (dependencyMap) {
- Object.keys(dependencyMap).forEach(function (name) {
- dependencyMap[name].forEach(function (target) {
- _this3.dirtifyToRoot(target, true);
- target.dispatchEvent(new MutationEvent(exports.ElementEvent.ATTR_MODIFIED, target, _this3, _this3, name, MutationEvent.MODIFICATION, _this3, _this3));
- if (target.isCustomElement && target.isConnected) {
- if (target.attributeChangedCallback) {
- target.attributeChangedCallback(name, _this3, _this3);
- }
- }
- });
- });
- }
- };
- _proto.getPosition = function getPosition(element) {
- var transform = element.transformable;
- return getTranslation(transform.position, this.getWorldTransform(element, transform));
- };
- _proto.getRotation = function getRotation$1(element) {
- var transform = element.transformable;
- return getRotation(transform.rotation, this.getWorldTransform(element, transform));
- };
- _proto.getScale = function getScale(element) {
- var transform = element.transformable;
- return getScaling(transform.scaling, this.getWorldTransform(element, transform));
- };
- _proto.getWorldTransform = function getWorldTransform(element, transform) {
- if (transform === void 0) {
- transform = element.transformable;
- }
- if (!transform.localDirtyFlag && !transform.dirtyFlag) {
- return transform.worldTransform;
- }
- if (element.parentNode && element.parentNode.transformable) {
- this.getWorldTransform(element.parentNode);
- }
- this.sync(element, transform);
- return transform.worldTransform;
- };
- _proto.getLocalPosition = function getLocalPosition(element) {
- return element.transformable.localPosition;
- };
- _proto.getLocalRotation = function getLocalRotation(element) {
- return element.transformable.localRotation;
- };
- _proto.getLocalScale = function getLocalScale(element) {
- return element.transformable.localScale;
- };
- _proto.getLocalSkew = function getLocalSkew(element) {
- return element.transformable.localSkew;
- };
- _proto.getLocalTransform = function getLocalTransform(element) {
- var transform = element.transformable;
- if (transform.localDirtyFlag) {
- this.calcLocalTransform(transform);
- transform.localDirtyFlag = false;
- }
- return transform.localTransform;
- };
- _proto.setLocalTransform = function setLocalTransform(element, transform) {
- var t = getTranslation(create$2(), transform);
- var r = getRotation(create$4(), transform);
- var s = getScaling(create$2(), transform);
- this.setLocalScale(element, s);
- this.setLocalPosition(element, t);
- this.setLocalRotation(element, r);
- };
- _proto.resetLocalTransform = function resetLocalTransform(element) {
- this.setLocalScale(element, [1, 1, 1]);
- this.setLocalPosition(element, [0, 0, 0]);
- this.setLocalEulerAngles(element, [0, 0, 0]);
- this.setLocalSkew(element, [0, 0]);
- };
- _proto.getTransformedGeometryBounds = function getTransformedGeometryBounds(element, render, existedAABB) {
- if (render === void 0) {
- render = false;
- }
- var bounds = this.getGeometryBounds(element, render);
- if (!AABB.isEmpty(bounds)) {
- var aabb = existedAABB || new AABB();
- aabb.setFromTransformedAABB(bounds, this.getWorldTransform(element));
- return aabb;
- } else {
- return null;
- }
- }
- /**
- * won't account for children
- */;
- _proto.getGeometryBounds = function getGeometryBounds(element, render) {
- if (render === void 0) {
- render = false;
- }
- var geometry = element.geometry;
- var bounds = render ? geometry.renderBounds : geometry.contentBounds || null;
- // return (bounds && new AABB(bounds.center, bounds.halfExtents)) || new AABB();
- return bounds || new AABB();
- }
- /**
- * account for children in world space
- */;
- _proto.getBounds = function getBounds(element, render) {
- var _this4 = this;
- if (render === void 0) {
- render = false;
- }
- var renderable = element.renderable;
- if (!renderable.boundsDirty && !render && renderable.bounds) {
- return renderable.bounds;
- }
- if (!renderable.renderBoundsDirty && render && renderable.renderBounds) {
- return renderable.renderBounds;
- }
- // reuse existed if possible
- var existedAABB = render ? renderable.renderBounds : renderable.bounds;
- // reset with geometry's aabb
- var aabb = this.getTransformedGeometryBounds(element, render, existedAABB);
- // merge children's aabbs
- var children = element.childNodes;
- children.forEach(function (child) {
- var childBounds = _this4.getBounds(child, render);
- if (childBounds) {
- if (!aabb) {
- aabb = existedAABB || new AABB();
- aabb.update(childBounds.center, childBounds.halfExtents);
- } else {
- aabb.add(childBounds);
- }
- }
- });
- if (render) {
- // FIXME: account for clip path
- var clipped = findClosestClipPathTarget(element);
- if (clipped) {
- // use bounds under world space
- var clipPathBounds = clipped.parsedStyle.clipPath.getBounds(render);
- if (!aabb) {
- aabb = clipPathBounds;
- } else if (clipPathBounds) {
- aabb = clipPathBounds.intersection(aabb);
- }
- }
- }
- if (!aabb) {
- aabb = new AABB();
- }
- if (aabb) {
- if (render) {
- renderable.renderBounds = aabb;
- } else {
- renderable.bounds = aabb;
- }
- }
- if (render) {
- renderable.renderBoundsDirty = false;
- } else {
- renderable.boundsDirty = false;
- }
- return aabb;
- }
- /**
- * account for children in local space
- */;
- _proto.getLocalBounds = function getLocalBounds(element) {
- if (element.parentNode) {
- var parentInvert = create$1();
- if (element.parentNode.transformable) {
- parentInvert = invert(create$1(), this.getWorldTransform(element.parentNode));
- }
- var bounds = this.getBounds(element);
- if (!AABB.isEmpty(bounds)) {
- var localBounds = new AABB();
- localBounds.setFromTransformedAABB(bounds, parentInvert);
- return localBounds;
- }
- }
- return this.getBounds(element);
- };
- _proto.getBoundingClientRect = function getBoundingClientRect(element) {
- var _element$ownerDocumen, _element$ownerDocumen2;
- var aabb;
- var bounds = this.getGeometryBounds(element);
- if (!AABB.isEmpty(bounds)) {
- aabb = new AABB();
- // apply transformation to aabb
- aabb.setFromTransformedAABB(bounds, this.getWorldTransform(element));
- }
- // calc context's offset
- var bbox = (_element$ownerDocumen = element.ownerDocument) === null || _element$ownerDocumen === void 0 ? void 0 : (_element$ownerDocumen2 = _element$ownerDocumen.defaultView) === null || _element$ownerDocumen2 === void 0 ? void 0 : _element$ownerDocumen2.getContextService().getBoundingClientRect();
- if (aabb) {
- var _aabb$getMin = aabb.getMin(),
- left = _aabb$getMin[0],
- top = _aabb$getMin[1];
- var _aabb$getMax = aabb.getMax(),
- right = _aabb$getMax[0],
- bottom = _aabb$getMax[1];
- return new Rectangle(left + ((bbox === null || bbox === void 0 ? void 0 : bbox.left) || 0), top + ((bbox === null || bbox === void 0 ? void 0 : bbox.top) || 0), right - left, bottom - top);
- }
- return new Rectangle((bbox === null || bbox === void 0 ? void 0 : bbox.left) || 0, (bbox === null || bbox === void 0 ? void 0 : bbox.top) || 0, 0, 0);
- };
- _proto.dirtifyWorldInternal = function dirtifyWorldInternal(element, transform) {
- var _this5 = this;
- if (!transform.dirtyFlag) {
- transform.dirtyFlag = true;
- transform.frozen = false;
- element.childNodes.forEach(function (child) {
- var childTransform = child.transformable;
- if (!childTransform.dirtyFlag) {
- _this5.dirtifyWorldInternal(child, childTransform);
- }
- });
- var renderable = element.renderable;
- if (renderable) {
- renderable.renderBoundsDirty = true;
- renderable.boundsDirty = true;
- renderable.dirty = true;
- }
- }
- };
- _proto.syncHierarchy = function syncHierarchy(element) {
- var transform = element.transformable;
- if (transform.frozen) {
- return;
- }
- transform.frozen = true;
- if (transform.localDirtyFlag || transform.dirtyFlag) {
- this.sync(element, transform);
- }
- var children = element.childNodes;
- for (var i = 0; i < children.length; i++) {
- this.syncHierarchy(children[i]);
- }
- };
- _proto.sync = function sync(element, transform) {
- if (transform.localDirtyFlag) {
- this.calcLocalTransform(transform);
- transform.localDirtyFlag = false;
- }
- if (transform.dirtyFlag) {
- var parent = element.parentNode;
- var parentTransform = parent && parent.transformable;
- if (parent === null || !parentTransform) {
- copy(transform.worldTransform, transform.localTransform);
- } else {
- // TODO: should we support scale compensation?
- // @see https://github.com/playcanvas/engine/issues/1077#issuecomment-359765557
- multiply(transform.worldTransform, parentTransform.worldTransform, transform.localTransform);
- }
- transform.dirtyFlag = false;
- }
- };
- _proto.unfreezeParentToRoot = function unfreezeParentToRoot(child) {
- var p = child.parentNode;
- while (p) {
- var transform = p.transformable;
- if (transform) {
- transform.frozen = false;
- }
- p = p.parentNode;
- }
- };
- return DefaultSceneGraphService;
- }();
- var TEXT_METRICS = {
- MetricsString: '|ÉqÅ',
- BaselineSymbol: 'M',
- BaselineMultiplier: 1.4,
- HeightMultiplier: 2,
- Newlines: [0x000a, 0x000d // carriage return
- ],
- BreakingSpaces: [0x0009, 0x0020, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2008, 0x2009, 0x200a, 0x205f, 0x3000 // ideographic space
- ]
- };
- var LATIN_REGEX = /[a-zA-Z0-9\u00C0-\u00D6\u00D8-\u00f6\u00f8-\u00ff!"#$%&'()*+,-./:;]/;
- // Line breaking rules in CJK (Kinsoku Shori)
- // Refer from https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
- var regexCannotStartZhCn = /[!%),.:;?\]}¢°·'""†‡›℃∶、。〃〆〕〗〞﹚﹜!"%'),.:;?!]}~]/;
- var regexCannotEndZhCn = /[$(£¥·'"〈《「『【〔〖〝﹙﹛$(.[{£¥]/;
- var regexCannotStartZhTw = /[!),.:;?\]}¢·–—'"•"、。〆〞〕〉》」︰︱︲︳﹐﹑﹒﹔﹕﹖﹘﹚﹜!),.:;?︶︸︺︼︾﹀﹂﹗]|}、]/;
- var regexCannotEndZhTw = /[([{£¥'"‵〈《「『〔〝︴﹙﹛({︵︷︹︻︽︿﹁﹃﹏]/;
- var regexCannotStartJaJp = /[)\]}〕〉》」』】〙〗〟'"⦆»ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎゕゖㇰㇱㇲㇳㇴㇵㇶㇷㇸㇹㇺㇻㇼㇽㇾㇿ々〻‐゠–〜?!‼⁇⁈⁉・、:;,。.]/;
- var regexCannotEndJaJp = /[([{〔〈《「『【〘〖〝'"⦅«—...‥〳〴〵]/;
- var regexCannotStartKoKr = /[!%),.:;?\]}¢°'"†‡℃〆〈《「『〕!%),.:;?]}]/;
- var regexCannotEndKoKr = /[$([{£¥'"々〇〉》」〔$([{⦆¥₩#]/;
- var regexCannotStart = new RegExp(regexCannotStartZhCn.source + "|" + regexCannotStartZhTw.source + "|" + regexCannotStartJaJp.source + "|" + regexCannotStartKoKr.source);
- var regexCannotEnd = new RegExp(regexCannotEndZhCn.source + "|" + regexCannotEndZhTw.source + "|" + regexCannotEndJaJp.source + "|" + regexCannotEndKoKr.source);
- /**
- * Borrow from pixi/packages/text/src/TextMetrics.ts
- */
- var TextService = /*#__PURE__*/function () {
- function TextService(runtime) {
- var _this = this;
- this.runtime = void 0;
- /**
- * font metrics cache
- */
- this.fontMetricsCache = {};
- this.shouldBreakByKinsokuShorui = function (char, nextChar) {
- if (_this.isBreakingSpace(nextChar)) return false;
- if (char) {
- // Line breaking rules in CJK (Kinsoku Shori)
- if (regexCannotEnd.exec(nextChar) || regexCannotStart.exec(char)) {
- return true;
- }
- }
- return false;
- };
- this.trimByKinsokuShorui = function (prev) {
- var next = [].concat(prev);
- var prevLine = next[next.length - 2];
- if (!prevLine) {
- return prev;
- }
- var lastChar = prevLine[prevLine.length - 1];
- next[next.length - 2] = prevLine.slice(0, -1);
- next[next.length - 1] = lastChar + next[next.length - 1];
- return next;
- };
- this.runtime = runtime;
- }
- var _proto = TextService.prototype;
- /**
- * Calculates the ascent, descent and fontSize of a given font-style.
- */
- _proto.measureFont = function measureFont(font, offscreenCanvas) {
- // as this method is used for preparing assets, don't recalculate things if we don't need to
- if (this.fontMetricsCache[font]) {
- return this.fontMetricsCache[font];
- }
- var properties = {
- ascent: 0,
- descent: 0,
- fontSize: 0
- };
- var canvas = this.runtime.offscreenCanvas.getOrCreateCanvas(offscreenCanvas);
- var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas, {
- willReadFrequently: true
- });
- context.font = font;
- var metricsString = TEXT_METRICS.MetricsString + TEXT_METRICS.BaselineSymbol;
- var width = Math.ceil(context.measureText(metricsString).width);
- var baseline = Math.ceil(context.measureText(TEXT_METRICS.BaselineSymbol).width);
- var height = TEXT_METRICS.HeightMultiplier * baseline;
- baseline = baseline * TEXT_METRICS.BaselineMultiplier | 0;
- // @ts-ignore
- canvas.width = width;
- // @ts-ignore
- canvas.height = height;
- context.fillStyle = '#f00';
- context.fillRect(0, 0, width, height);
- context.font = font;
- context.textBaseline = 'alphabetic';
- context.fillStyle = '#000';
- context.fillText(metricsString, 0, baseline);
- var imagedata = context.getImageData(0, 0, width || 1, height || 1).data;
- var pixels = imagedata.length;
- var line = width * 4;
- var i = 0;
- var idx = 0;
- var stop = false;
- // ascent. scan from top to bottom until we find a non red pixel
- for (i = 0; i < baseline; ++i) {
- for (var j = 0; j < line; j += 4) {
- if (imagedata[idx + j] !== 255) {
- stop = true;
- break;
- }
- }
- if (!stop) {
- idx += line;
- } else {
- break;
- }
- }
- properties.ascent = baseline - i;
- idx = pixels - line;
- stop = false;
- // descent. scan from bottom to top until we find a non red pixel
- for (i = height; i > baseline; --i) {
- for (var _j = 0; _j < line; _j += 4) {
- if (imagedata[idx + _j] !== 255) {
- stop = true;
- break;
- }
- }
- if (!stop) {
- idx -= line;
- } else {
- break;
- }
- }
- properties.descent = i - baseline;
- properties.fontSize = properties.ascent + properties.descent;
- this.fontMetricsCache[font] = properties;
- return properties;
- };
- _proto.measureText = function measureText(text, parsedStyle, offscreenCanvas) {
- var fontSize = parsedStyle.fontSize,
- wordWrap = parsedStyle.wordWrap,
- strokeHeight = parsedStyle.lineHeight,
- lineWidth = parsedStyle.lineWidth,
- textBaseline = parsedStyle.textBaseline,
- textAlign = parsedStyle.textAlign,
- letterSpacing = parsedStyle.letterSpacing,
- textPath = parsedStyle.textPath,
- textPathSide = parsedStyle.textPathSide,
- textPathStartOffset = parsedStyle.textPathStartOffset,
- _parsedStyle$leading = parsedStyle.leading,
- leading = _parsedStyle$leading === void 0 ? 0 : _parsedStyle$leading;
- var font = toFontString(parsedStyle);
- // if (runtime.enableCSSParsing) {
- var fontProperties = this.measureFont(font, offscreenCanvas);
- // fallback in case UA disallow canvas data extraction
- // (toDataURI, getImageData functions)
- if (fontProperties.fontSize === 0) {
- fontProperties.fontSize = fontSize;
- fontProperties.ascent = fontSize;
- }
- // } else {
- // fontProperties = {
- // fontSize,
- // };
- // }
- var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);
- context.font = font;
- // no overflowing by default
- parsedStyle.isOverflowing = false;
- var outputText = wordWrap ? this.wordWrap(text, parsedStyle, offscreenCanvas) : text;
- var lines = outputText.split(/(?:\r\n|\r|\n)/);
- var lineWidths = new Array(lines.length);
- var maxLineWidth = 0;
- // account for textPath
- if (textPath) {
- var totalPathLength = textPath.getTotalLength();
- // const startingPoint = textPath.getPoint(0);
- for (var i = 0; i < lines.length; i++) {
- var width = context.measureText(lines[i]).width + (lines[i].length - 1) * letterSpacing;
- // for (
- // let i = reverse ? lines[0].length - 1 : 0;
- // reverse ? i >= 0 : i < lines[0].length;
- // reverse ? i-- : i++
- // ) {
- // graphemeInfo = lineBounds[i];
- // if (positionInPath > totalPathLength) {
- // positionInPath %= totalPathLength;
- // } else if (positionInPath < 0) {
- // positionInPath += totalPathLength;
- // }
- // // it would probably much faster to send all the grapheme position for a line
- // // and calculate path position/angle at once.
- // this.setGraphemeOnPath(
- // positionInPath,
- // graphemeInfo,
- // startingPoint
- // );
- // positionInPath += graphemeInfo.kernedWidth;
- // }
- }
- } else {
- for (var _i = 0; _i < lines.length; _i++) {
- // char width + letterSpacing
- var _lineWidth = context.measureText(lines[_i]).width + (lines[_i].length - 1) * letterSpacing;
- lineWidths[_i] = _lineWidth;
- maxLineWidth = Math.max(maxLineWidth, _lineWidth);
- }
- var _width = maxLineWidth + lineWidth;
- // if (dropShadow) {
- // width += dropShadowDistance;
- // }
- var lineHeight = strokeHeight || fontProperties.fontSize + lineWidth;
- var height = Math.max(lineHeight, fontProperties.fontSize + lineWidth) + (lines.length - 1) * (lineHeight + leading);
- // if (dropShadow) {
- // height += dropShadowDistance;
- // }
- lineHeight += leading;
- // handle vertical text baseline
- var offsetY = 0;
- if (textBaseline === 'middle') {
- offsetY = -height / 2;
- } else if (textBaseline === 'bottom' || textBaseline === 'alphabetic' || textBaseline === 'ideographic') {
- offsetY = -height;
- } else if (textBaseline === 'top' || textBaseline === 'hanging') {
- offsetY = 0;
- }
- return {
- font: font,
- width: _width,
- height: height,
- lines: lines,
- lineWidths: lineWidths,
- lineHeight: lineHeight,
- maxLineWidth: maxLineWidth,
- fontProperties: fontProperties,
- lineMetrics: lineWidths.map(function (width, i) {
- var offsetX = 0;
- // handle horizontal text align
- if (textAlign === 'center' || textAlign === 'middle') {
- offsetX -= width / 2;
- } else if (textAlign === 'right' || textAlign === 'end') {
- offsetX -= width;
- }
- return new Rectangle(offsetX - lineWidth / 2, offsetY + i * lineHeight, width + lineWidth, lineHeight);
- })
- };
- }
- };
- _proto.setGraphemeOnPath = function setGraphemeOnPath() {};
- _proto.wordWrap = function wordWrap(text, parsedStyle, offscreenCanvas) {
- var _this2 = this;
- var _parsedStyle$wordWrap = parsedStyle.wordWrapWidth,
- wordWrapWidth = _parsedStyle$wordWrap === void 0 ? 0 : _parsedStyle$wordWrap,
- letterSpacing = parsedStyle.letterSpacing,
- _parsedStyle$maxLines = parsedStyle.maxLines,
- maxLines = _parsedStyle$maxLines === void 0 ? Infinity : _parsedStyle$maxLines,
- textOverflow = parsedStyle.textOverflow;
- var context = this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);
- var maxWidth = wordWrapWidth + letterSpacing;
- var ellipsis = '';
- if (textOverflow === 'ellipsis') {
- ellipsis = '...';
- } else if (textOverflow && textOverflow !== 'clip') {
- ellipsis = textOverflow;
- }
- var lines = [];
- var currentIndex = 0;
- var currentWidth = 0;
- var cache = {};
- var calcWidth = function calcWidth(char) {
- return _this2.getFromCache(char, letterSpacing, cache, context);
- };
- var ellipsisWidth = Array.from(ellipsis).reduce(function (prev, cur) {
- return prev + calcWidth(cur);
- }, 0);
- var chars = Array.from(text);
- for (var i = 0; i < chars.length; i++) {
- var char = chars[i];
- var prevChar = text[i - 1];
- var nextChar = text[i + 1];
- var charWidth = calcWidth(char);
- if (this.isNewline(char)) {
- currentIndex++;
- // exceed maxLines, break immediately
- if (currentIndex >= maxLines) {
- parsedStyle.isOverflowing = true;
- break;
- }
- currentWidth = 0;
- lines[currentIndex] = '';
- continue;
- }
- if (currentWidth > 0 && currentWidth + charWidth > maxWidth) {
- if (currentIndex + 1 >= maxLines) {
- parsedStyle.isOverflowing = true;
- // If there is not enough space to display the string itself, it is clipped.
- // @see https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow#values
- if (ellipsisWidth > 0 && ellipsisWidth <= maxWidth) {
- // Backspace from line's end.
- var currentLineLength = lines[currentIndex].length;
- var lastLineWidth = 0;
- var lastLineIndex = currentLineLength;
- for (var _i2 = 0; _i2 < currentLineLength; _i2++) {
- var width = calcWidth(lines[currentIndex][_i2]);
- if (lastLineWidth + width + ellipsisWidth > maxWidth) {
- lastLineIndex = _i2;
- break;
- }
- lastLineWidth += width;
- }
- lines[currentIndex] = (lines[currentIndex] || '').slice(0, lastLineIndex) + ellipsis;
- }
- break;
- }
- currentIndex++;
- currentWidth = 0;
- lines[currentIndex] = '';
- if (this.isBreakingSpace(char)) {
- continue;
- }
- if (!this.canBreakInLastChar(char)) {
- lines = this.trimToBreakable(lines);
- currentWidth = this.sumTextWidthByCache(lines[currentIndex] || '', cache);
- }
- if (this.shouldBreakByKinsokuShorui(char, nextChar)) {
- lines = this.trimByKinsokuShorui(lines);
- currentWidth += calcWidth(prevChar || '');
- }
- }
- currentWidth += charWidth;
- lines[currentIndex] = (lines[currentIndex] || '') + char;
- }
- return lines.join('\n');
- };
- _proto.isBreakingSpace = function isBreakingSpace(char) {
- if (typeof char !== 'string') {
- return false;
- }
- return TEXT_METRICS.BreakingSpaces.indexOf(char.charCodeAt(0)) >= 0;
- };
- _proto.isNewline = function isNewline(char) {
- if (typeof char !== 'string') {
- return false;
- }
- return TEXT_METRICS.Newlines.indexOf(char.charCodeAt(0)) >= 0;
- };
- _proto.trimToBreakable = function trimToBreakable(prev) {
- var next = [].concat(prev);
- var prevLine = next[next.length - 2];
- var index = this.findBreakableIndex(prevLine);
- if (index === -1 || !prevLine) return next;
- var trimmedChar = prevLine.slice(index, index + 1);
- var isTrimmedWithSpace = this.isBreakingSpace(trimmedChar);
- var trimFrom = index + 1;
- var trimTo = index + (isTrimmedWithSpace ? 0 : 1);
- next[next.length - 1] += prevLine.slice(trimFrom, prevLine.length);
- next[next.length - 2] = prevLine.slice(0, trimTo);
- return next;
- };
- _proto.canBreakInLastChar = function canBreakInLastChar(char) {
- if (char && LATIN_REGEX.test(char)) return false;
- return true;
- };
- _proto.sumTextWidthByCache = function sumTextWidthByCache(text, cache) {
- return text.split('').reduce(function (sum, c) {
- if (!cache[c]) throw Error('cannot count the word without cache');
- return sum + cache[c];
- }, 0);
- };
- _proto.findBreakableIndex = function findBreakableIndex(line) {
- for (var i = line.length - 1; i >= 0; i--) {
- if (!LATIN_REGEX.test(line[i])) return i;
- }
- return -1;
- };
- _proto.getFromCache = function getFromCache(key, letterSpacing, cache, context) {
- var width = cache[key];
- if (typeof width !== 'number') {
- var spacing = key.length * letterSpacing;
- width = context.measureText(key).width + spacing;
- cache[key] = width;
- }
- return width;
- };
- return TextService;
- }();
- var _this = undefined;
- var runtime = {};
- /**
- * Replace with IoC container
- */
- var geometryUpdaterFactory = function () {
- var _ref;
- var rectUpdater = new RectUpdater();
- var polylineUpdater = new PolylineUpdater();
- return _ref = {}, _ref[exports.Shape.CIRCLE] = new CircleUpdater(), _ref[exports.Shape.ELLIPSE] = new EllipseUpdater(), _ref[exports.Shape.RECT] = rectUpdater, _ref[exports.Shape.IMAGE] = rectUpdater, _ref[exports.Shape.GROUP] = rectUpdater, _ref[exports.Shape.LINE] = new LineUpdater(), _ref[exports.Shape.TEXT] = new TextUpdater(runtime), _ref[exports.Shape.POLYLINE] = polylineUpdater, _ref[exports.Shape.POLYGON] = polylineUpdater, _ref[exports.Shape.PATH] = new PathUpdater(), _ref[exports.Shape.HTML] = null, _ref[exports.Shape.MESH] = null, _ref;
- }();
- var CSSPropertySyntaxFactory = function () {
- var _ref2;
- var color = new CSSPropertyColor();
- var length = new CSSPropertyLengthOrPercentage();
- return _ref2 = {}, _ref2[exports.PropertySyntax.PERCENTAGE] = null, _ref2[exports.PropertySyntax.NUMBER] = new CSSPropertyNumber(), _ref2[exports.PropertySyntax.ANGLE] = new CSSPropertyAngle(), _ref2[exports.PropertySyntax.DEFINED_PATH] = new CSSPropertyClipPath(), _ref2[exports.PropertySyntax.PAINT] = color, _ref2[exports.PropertySyntax.COLOR] = color, _ref2[exports.PropertySyntax.FILTER] = new CSSPropertyFilter(), _ref2[exports.PropertySyntax.LENGTH] = length, _ref2[exports.PropertySyntax.LENGTH_PERCENTAGE] = length, _ref2[exports.PropertySyntax.LENGTH_PERCENTAGE_12] = new CSSPropertyLengthOrPercentage12(), _ref2[exports.PropertySyntax.LENGTH_PERCENTAGE_14] = new CSSPropertyLengthOrPercentage14(), _ref2[exports.PropertySyntax.COORDINATE] = new CSSPropertyLocalPosition(), _ref2[exports.PropertySyntax.OFFSET_DISTANCE] = new CSSPropertyOffsetDistance(), _ref2[exports.PropertySyntax.OPACITY_VALUE] = new CSSPropertyOpacity(), _ref2[exports.PropertySyntax.PATH] = new CSSPropertyPath(), _ref2[exports.PropertySyntax.LIST_OF_POINTS] = new CSSPropertyPoints(), _ref2[exports.PropertySyntax.SHADOW_BLUR] = new CSSPropertyShadowBlur(), _ref2[exports.PropertySyntax.TEXT] = new CSSPropertyText(), _ref2[exports.PropertySyntax.TEXT_TRANSFORM] = new CSSPropertyTextTransform(), _ref2[exports.PropertySyntax.TRANSFORM] = new CSSPropertyTransform(), _ref2[exports.PropertySyntax.TRANSFORM_ORIGIN] = new CSSPropertyTransformOrigin(), _ref2[exports.PropertySyntax.Z_INDEX] = new CSSPropertyZIndex(), _ref2[exports.PropertySyntax.MARKER] = new CSSPropertyMarker(), _ref2;
- }();
- var getGlobalThis = function getGlobalThis() {
- if (typeof globalThis !== 'undefined') return globalThis;
- if (typeof self !== 'undefined') return self;
- if (typeof window !== 'undefined') return window;
- // @ts-ignore
- if (typeof global !== 'undefined') return global;
- if (typeof _this !== 'undefined') return _this;
- throw new Error('Unable to locate global `this`');
- };
- /**
- * Camera
- * `g-camera-api` will provide an advanced implementation
- */
- runtime.CameraContribution = Camera;
- /**
- * `g-web-animations-api` will provide an AnimationTimeline
- */
- runtime.AnimationTimeline = null;
- runtime.EasingFunction = null;
- runtime.offscreenCanvas = new OffscreenCanvasCreator();
- runtime.nativeHTMLMap = new WeakMap();
- runtime.sceneGraphSelector = new DefaultSceneGraphSelector();
- runtime.sceneGraphService = new DefaultSceneGraphService(runtime);
- runtime.textService = new TextService(runtime);
- runtime.geometryUpdaterFactory = geometryUpdaterFactory;
- runtime.CSSPropertySyntaxFactory = CSSPropertySyntaxFactory;
- runtime.styleValueRegistry = new DefaultStyleValueRegistry();
- runtime.layoutRegistry = null;
- runtime.globalThis = getGlobalThis();
- runtime.enableCSSParsing = true;
- runtime.enableDataset = false;
- runtime.enableStyleSyntax = true;
- var AbstractRendererPlugin = /*#__PURE__*/function () {
- function AbstractRendererPlugin() {
- this.context = void 0;
- this.plugins = [];
- }
- var _proto = AbstractRendererPlugin.prototype;
- _proto.addRenderingPlugin = function addRenderingPlugin(plugin) {
- this.plugins.push(plugin);
- this.context.renderingPlugins.push(plugin);
- };
- _proto.removeAllRenderingPlugins = function removeAllRenderingPlugins() {
- var _this = this;
- this.plugins.forEach(function (plugin) {
- var index = _this.context.renderingPlugins.indexOf(plugin);
- if (index >= 0) {
- _this.context.renderingPlugins.splice(index, 1);
- }
- });
- };
- return AbstractRendererPlugin;
- }();
- var AbstractRenderer = /*#__PURE__*/function () {
- function AbstractRenderer(config) {
- this.plugins = [];
- this.config = void 0;
- this.config = _extends({
- /**
- * only dirty object will cause re-render
- */
- enableDirtyCheck: true,
- enableCulling: false,
- /**
- * enable auto rendering by default
- */
- enableAutoRendering: true,
- /**
- * enable dirty rectangle rendering by default
- */
- enableDirtyRectangleRendering: true,
- enableDirtyRectangleRenderingDebug: false
- }, config);
- }
- var _proto2 = AbstractRenderer.prototype;
- _proto2.registerPlugin = function registerPlugin(plugin) {
- var index = this.plugins.findIndex(function (p) {
- return p === plugin;
- });
- if (index === -1) {
- this.plugins.push(plugin);
- }
- };
- _proto2.unregisterPlugin = function unregisterPlugin(plugin) {
- var index = this.plugins.findIndex(function (p) {
- return p === plugin;
- });
- if (index > -1) {
- this.plugins.splice(index, 1);
- }
- };
- _proto2.getPlugins = function getPlugins() {
- return this.plugins;
- };
- _proto2.getPlugin = function getPlugin(name) {
- return this.plugins.find(function (plugin) {
- return plugin.name === name;
- });
- };
- _proto2.getConfig = function getConfig() {
- return this.config;
- };
- _proto2.setConfig = function setConfig(config) {
- Object.assign(this.config, config);
- };
- return AbstractRenderer;
- }();
- /**
- * apply following rules:
- * 1. `visibility` in scenegraph node
- * 2. other custom culling strategies, eg. frustum culling
- */
- var CullingPlugin = /*#__PURE__*/function () {
- function CullingPlugin(strategies) {
- this.strategies = void 0;
- this.strategies = strategies;
- }
- var _proto = CullingPlugin.prototype;
- _proto.apply = function apply(context) {
- var camera = context.camera,
- renderingService = context.renderingService,
- renderingContext = context.renderingContext;
- var strategies = this.strategies;
- renderingService.hooks.cull.tap(CullingPlugin.tag, function (object) {
- if (object) {
- var cullable = object.cullable;
- // cullable.visible = true;
- // const renderBounds = object.getRenderBounds();
- // if (AABB.isEmpty(renderBounds)) {
- // cullable.visible = false;
- // } else {
- // const isShape2D = shape2D.indexOf(object.nodeName as Shape) > -1;
- // const [p0, p1, p2, p3] = camera.getFrustum().planes;
- // tmpAABB.setMinMax([-p1.distance, -p3.distance, 0], [p0.distance, p2.distance, 0]);
- // cullable.visible = isShape2D ? renderBounds.intersects(tmpAABB) : true;
- // }
- if (strategies.length === 0) {
- cullable.visible = renderingContext.unculledEntities.indexOf(object.entity) > -1;
- } else {
- // eg. implemented by g-webgl(frustum culling)
- cullable.visible = strategies.every(function (strategy) {
- return strategy.isVisible(camera, object);
- });
- }
- if (!object.isCulled() && object.isVisible()) {
- return object;
- } else {
- // if (this.renderingContext.renderListLastFrame.indexOf(object) > -1) {
- object.dispatchEvent(new CustomEvent(exports.ElementEvent.CULLED));
- // }
- }
- return null;
- }
- return object;
- });
- renderingService.hooks.afterRender.tap(CullingPlugin.tag, function (object) {
- object.cullable.visibilityPlaneMask = -1;
- });
- };
- return CullingPlugin;
- }();
- CullingPlugin.tag = 'Culling';
- /**
- * Filter dirty renderables and calculate the "dirty rectangle" which will be clear when frame began
- */
- var DirtyCheckPlugin = /*#__PURE__*/function () {
- function DirtyCheckPlugin() {}
- var _proto = DirtyCheckPlugin.prototype;
- _proto.apply = function apply(context) {
- var renderingService = context.renderingService;
- renderingService.hooks.dirtycheck.tap(DirtyCheckPlugin.tag, function (object) {
- if (object) {
- var renderable = object.renderable;
- var isDirty = renderable.dirty || renderingService.disableDirtyRectangleRendering();
- if (isDirty) {
- return object;
- } else {
- return null;
- }
- }
- return object;
- });
- };
- return DirtyCheckPlugin;
- }();
- DirtyCheckPlugin.tag = 'DirtyCheck';
- /**
- * support mouse & touch events
- * @see https://github.com/pixijs/pixi.js/blob/dev/packages/interaction/README.md
- *
- * also provide some extra events such as `drag`
- */
- var EventPlugin = /*#__PURE__*/function () {
- function EventPlugin() {
- var _this = this;
- this.autoPreventDefault = false;
- this.rootPointerEvent = new FederatedPointerEvent(null);
- this.rootWheelEvent = new FederatedWheelEvent(null);
- this.context = void 0;
- this.onPointerMove = function (nativeEvent) {
- var _this$context$renderi, _this$context$renderi2;
- var canvas = (_this$context$renderi = _this.context.renderingContext.root) === null || _this$context$renderi === void 0 ? void 0 : (_this$context$renderi2 = _this$context$renderi.ownerDocument) === null || _this$context$renderi2 === void 0 ? void 0 : _this$context$renderi2.defaultView;
- if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
- var normalizedEvents = _this.normalizeToPointerEvent(nativeEvent, canvas);
- for (var _iterator = _createForOfIteratorHelperLoose(normalizedEvents), _step; !(_step = _iterator()).done;) {
- var normalizedEvent = _step.value;
- var event = _this.bootstrapEvent(_this.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
- _this.context.eventService.mapEvent(event);
- }
- _this.setCursor(_this.context.eventService.cursor);
- };
- this.onClick = function (nativeEvent) {
- var _this$context$renderi3, _this$context$renderi4;
- var canvas = (_this$context$renderi3 = _this.context.renderingContext.root) === null || _this$context$renderi3 === void 0 ? void 0 : (_this$context$renderi4 = _this$context$renderi3.ownerDocument) === null || _this$context$renderi4 === void 0 ? void 0 : _this$context$renderi4.defaultView;
- var normalizedEvents = _this.normalizeToPointerEvent(nativeEvent, canvas);
- for (var _iterator2 = _createForOfIteratorHelperLoose(normalizedEvents), _step2; !(_step2 = _iterator2()).done;) {
- var normalizedEvent = _step2.value;
- var event = _this.bootstrapEvent(_this.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
- _this.context.eventService.mapEvent(event);
- }
- _this.setCursor(_this.context.eventService.cursor);
- };
- }
- var _proto = EventPlugin.prototype;
- _proto.apply = function apply(context) {
- var _this2 = this;
- this.context = context;
- var renderingService = context.renderingService;
- var canvas = this.context.renderingContext.root.ownerDocument.defaultView;
- this.context.eventService.setPickHandler(function (position) {
- var _this2$context$render = _this2.context.renderingService.hooks.pickSync.call({
- position: position,
- picked: [],
- topmost: true // we only concern the topmost element
- }),
- picked = _this2$context$render.picked;
- return picked[0] || null;
- });
- renderingService.hooks.pointerWheel.tap(EventPlugin.tag, function (nativeEvent) {
- var wheelEvent = _this2.normalizeWheelEvent(nativeEvent);
- _this2.context.eventService.mapEvent(wheelEvent);
- });
- renderingService.hooks.pointerDown.tap(EventPlugin.tag, function (nativeEvent) {
- if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
- var events = _this2.normalizeToPointerEvent(nativeEvent, canvas);
- if (_this2.autoPreventDefault && events[0].isNormalized) {
- var cancelable = nativeEvent.cancelable || !('cancelable' in nativeEvent);
- if (cancelable) {
- nativeEvent.preventDefault();
- }
- }
- for (var _iterator3 = _createForOfIteratorHelperLoose(events), _step3; !(_step3 = _iterator3()).done;) {
- var event = _step3.value;
- var federatedEvent = _this2.bootstrapEvent(_this2.rootPointerEvent, event, canvas, nativeEvent);
- _this2.context.eventService.mapEvent(federatedEvent);
- }
- _this2.setCursor(_this2.context.eventService.cursor);
- });
- renderingService.hooks.pointerUp.tap(EventPlugin.tag, function (nativeEvent) {
- if (canvas.supportsTouchEvents && nativeEvent.pointerType === 'touch') return;
- // account for element in SVG
- var $element = _this2.context.contextService.getDomElement();
- var outside = 'outside';
- try {
- outside = $element && nativeEvent.target && nativeEvent.target !== $element && $element.contains && !$element.contains(nativeEvent.target) ? 'outside' : '';
- } catch (e) {
- // nativeEvent.target maybe not Node, such as Window
- // @see https://github.com/antvis/G/issues/1235
- }
- var normalizedEvents = _this2.normalizeToPointerEvent(nativeEvent, canvas);
- for (var _iterator4 = _createForOfIteratorHelperLoose(normalizedEvents), _step4; !(_step4 = _iterator4()).done;) {
- var normalizedEvent = _step4.value;
- var event = _this2.bootstrapEvent(_this2.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
- event.type += outside;
- _this2.context.eventService.mapEvent(event);
- }
- _this2.setCursor(_this2.context.eventService.cursor);
- });
- renderingService.hooks.pointerMove.tap(EventPlugin.tag, this.onPointerMove);
- renderingService.hooks.pointerOver.tap(EventPlugin.tag, this.onPointerMove);
- renderingService.hooks.pointerOut.tap(EventPlugin.tag, this.onPointerMove);
- renderingService.hooks.click.tap(EventPlugin.tag, this.onClick);
- renderingService.hooks.pointerCancel.tap(EventPlugin.tag, function (nativeEvent) {
- var normalizedEvents = _this2.normalizeToPointerEvent(nativeEvent, canvas);
- for (var _iterator5 = _createForOfIteratorHelperLoose(normalizedEvents), _step5; !(_step5 = _iterator5()).done;) {
- var normalizedEvent = _step5.value;
- var event = _this2.bootstrapEvent(_this2.rootPointerEvent, normalizedEvent, canvas, nativeEvent);
- _this2.context.eventService.mapEvent(event);
- }
- _this2.setCursor(_this2.context.eventService.cursor);
- });
- };
- _proto.getViewportXY = function getViewportXY(nativeEvent) {
- var x;
- var y;
- /**
- * Should account for CSS Transform applied on container.
- * @see https://github.com/antvis/G/issues/1161
- * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/offsetX
- */
- var offsetX = nativeEvent.offsetX,
- offsetY = nativeEvent.offsetY,
- clientX = nativeEvent.clientX,
- clientY = nativeEvent.clientY;
- if (this.context.config.supportsCSSTransform && !isNil(offsetX) && !isNil(offsetY)) {
- x = offsetX;
- y = offsetY;
- } else {
- var point = this.context.eventService.client2Viewport(new Point(clientX, clientY));
- x = point.x;
- y = point.y;
- }
- return {
- x: x,
- y: y
- };
- };
- _proto.bootstrapEvent = function bootstrapEvent(event, normalizedEvent, view, nativeEvent) {
- event.view = view;
- event.originalEvent = null;
- event.nativeEvent = nativeEvent;
- event.pointerId = normalizedEvent.pointerId;
- event.width = normalizedEvent.width;
- event.height = normalizedEvent.height;
- event.isPrimary = normalizedEvent.isPrimary;
- event.pointerType = normalizedEvent.pointerType;
- event.pressure = normalizedEvent.pressure;
- event.tangentialPressure = normalizedEvent.tangentialPressure;
- event.tiltX = normalizedEvent.tiltX;
- event.tiltY = normalizedEvent.tiltY;
- event.twist = normalizedEvent.twist;
- this.transferMouseData(event, normalizedEvent);
- var _this$getViewportXY = this.getViewportXY(normalizedEvent),
- x = _this$getViewportXY.x,
- y = _this$getViewportXY.y;
- event.viewport.x = x;
- event.viewport.y = y;
- var _this$context$eventSe = this.context.eventService.viewport2Canvas(event.viewport),
- canvasX = _this$context$eventSe.x,
- canvasY = _this$context$eventSe.y;
- event.canvas.x = canvasX;
- event.canvas.y = canvasY;
- event.global.copyFrom(event.canvas);
- event.offset.copyFrom(event.canvas);
- event.isTrusted = nativeEvent.isTrusted;
- if (event.type === 'pointerleave') {
- event.type = 'pointerout';
- }
- if (event.type.startsWith('mouse')) {
- event.type = event.type.replace('mouse', 'pointer');
- }
- if (event.type.startsWith('touch')) {
- event.type = TOUCH_TO_POINTER[event.type] || event.type;
- }
- return event;
- };
- _proto.normalizeWheelEvent = function normalizeWheelEvent(nativeEvent) {
- var event = this.rootWheelEvent;
- this.transferMouseData(event, nativeEvent);
- event.deltaMode = nativeEvent.deltaMode;
- event.deltaX = nativeEvent.deltaX;
- event.deltaY = nativeEvent.deltaY;
- event.deltaZ = nativeEvent.deltaZ;
- var _this$getViewportXY2 = this.getViewportXY(nativeEvent),
- x = _this$getViewportXY2.x,
- y = _this$getViewportXY2.y;
- event.viewport.x = x;
- event.viewport.y = y;
- var _this$context$eventSe2 = this.context.eventService.viewport2Canvas(event.viewport),
- canvasX = _this$context$eventSe2.x,
- canvasY = _this$context$eventSe2.y;
- event.canvas.x = canvasX;
- event.canvas.y = canvasY;
- event.global.copyFrom(event.canvas);
- event.offset.copyFrom(event.canvas);
- event.nativeEvent = nativeEvent;
- event.type = nativeEvent.type;
- return event;
- }
- /**
- * Transfers base & mouse event data from the nativeEvent to the federated event.
- */;
- _proto.transferMouseData = function transferMouseData(event, nativeEvent) {
- event.isTrusted = nativeEvent.isTrusted;
- event.srcElement = nativeEvent.srcElement;
- event.timeStamp = performance.now();
- event.type = nativeEvent.type;
- event.altKey = nativeEvent.altKey;
- event.metaKey = nativeEvent.metaKey;
- event.shiftKey = nativeEvent.shiftKey;
- event.ctrlKey = nativeEvent.ctrlKey;
- event.button = nativeEvent.button;
- event.buttons = nativeEvent.buttons;
- event.client.x = nativeEvent.clientX;
- event.client.y = nativeEvent.clientY;
- event.movement.x = nativeEvent.movementX;
- event.movement.y = nativeEvent.movementY;
- event.page.x = nativeEvent.pageX;
- event.page.y = nativeEvent.pageY;
- event.screen.x = nativeEvent.screenX;
- event.screen.y = nativeEvent.screenY;
- event.relatedTarget = null;
- };
- _proto.setCursor = function setCursor(cursor) {
- this.context.contextService.applyCursorStyle(cursor || this.context.config.cursor || 'default');
- };
- _proto.normalizeToPointerEvent = function normalizeToPointerEvent(event, canvas) {
- var normalizedEvents = [];
- if (canvas.isTouchEvent(event)) {
- for (var i = 0; i < event.changedTouches.length; i++) {
- var touch = event.changedTouches[i];
- // use changedTouches instead of touches since touchend has no touches
- // @see https://stackoverflow.com/a/10079076
- if (isUndefined(touch.button)) touch.button = 0;
- if (isUndefined(touch.buttons)) touch.buttons = 1;
- if (isUndefined(touch.isPrimary)) {
- touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart';
- }
- if (isUndefined(touch.width)) touch.width = touch.radiusX || 1;
- if (isUndefined(touch.height)) touch.height = touch.radiusY || 1;
- if (isUndefined(touch.tiltX)) touch.tiltX = 0;
- if (isUndefined(touch.tiltY)) touch.tiltY = 0;
- if (isUndefined(touch.pointerType)) touch.pointerType = 'touch';
- // @see https://developer.mozilla.org/zh-CN/docs/Web/API/Touch/identifier
- if (isUndefined(touch.pointerId)) touch.pointerId = touch.identifier || 0;
- if (isUndefined(touch.pressure)) touch.pressure = touch.force || 0.5;
- if (isUndefined(touch.twist)) touch.twist = 0;
- if (isUndefined(touch.tangentialPressure)) touch.tangentialPressure = 0;
- touch.isNormalized = true;
- touch.type = event.type;
- normalizedEvents.push(touch);
- }
- } else if (canvas.isMouseEvent(event)) {
- var tempEvent = event;
- if (isUndefined(tempEvent.isPrimary)) tempEvent.isPrimary = true;
- if (isUndefined(tempEvent.width)) tempEvent.width = 1;
- if (isUndefined(tempEvent.height)) tempEvent.height = 1;
- if (isUndefined(tempEvent.tiltX)) tempEvent.tiltX = 0;
- if (isUndefined(tempEvent.tiltY)) tempEvent.tiltY = 0;
- if (isUndefined(tempEvent.pointerType)) tempEvent.pointerType = 'mouse';
- if (isUndefined(tempEvent.pointerId)) tempEvent.pointerId = MOUSE_POINTER_ID;
- if (isUndefined(tempEvent.pressure)) tempEvent.pressure = 0.5;
- if (isUndefined(tempEvent.twist)) tempEvent.twist = 0;
- if (isUndefined(tempEvent.tangentialPressure)) tempEvent.tangentialPressure = 0;
- tempEvent.isNormalized = true;
- normalizedEvents.push(tempEvent);
- } else {
- normalizedEvents.push(event);
- }
- return normalizedEvents;
- };
- return EventPlugin;
- }();
- EventPlugin.tag = 'Event';
- // group is not a 2d shape
- var shape2D = [exports.Shape.CIRCLE, exports.Shape.ELLIPSE, exports.Shape.IMAGE, exports.Shape.RECT, exports.Shape.LINE, exports.Shape.POLYLINE, exports.Shape.POLYGON, exports.Shape.TEXT, exports.Shape.PATH, exports.Shape.HTML];
- var FrustumCullingStrategy = /*#__PURE__*/function () {
- function FrustumCullingStrategy() {}
- var _proto = FrustumCullingStrategy.prototype;
- _proto.isVisible = function isVisible(camera, object) {
- var _object$parentNode, _object$parentNode$cu;
- // return true;
- var cullable = object.cullable;
- if (!cullable.enable) {
- return true;
- }
- var renderBounds = object.getRenderBounds();
- if (AABB.isEmpty(renderBounds)) {
- return false;
- }
- // get VP matrix from camera
- var frustum = camera.getFrustum();
- var parentVisibilityPlaneMask = (_object$parentNode = object.parentNode) === null || _object$parentNode === void 0 ? void 0 : (_object$parentNode$cu = _object$parentNode.cullable) === null || _object$parentNode$cu === void 0 ? void 0 : _object$parentNode$cu.visibilityPlaneMask;
- cullable.visibilityPlaneMask = this.computeVisibilityWithPlaneMask(object, renderBounds, parentVisibilityPlaneMask || exports.Mask.INDETERMINATE, frustum.planes);
- cullable.visible = cullable.visibilityPlaneMask !== exports.Mask.OUTSIDE;
- return cullable.visible;
- }
- /**
- *
- * @see「Optimized View Frustum Culling Algorithms for Bounding Boxes」
- * @see https://github.com/antvis/GWebGPUEngine/issues/3
- *
- * * 基础相交测试 the basic intersection test
- * * 标记 masking @see https://cesium.com/blog/2015/08/04/fast-hierarchical-culling/
- * * TODO: 平面一致性测试 the plane-coherency test
- * * TODO: 支持 mesh 指定自身的剔除策略,参考 Babylon.js @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
- *
- * @param aabb aabb
- * @param parentPlaneMask mask of parent
- * @param planes planes of frustum
- */;
- _proto.computeVisibilityWithPlaneMask = function computeVisibilityWithPlaneMask(object, aabb, parentPlaneMask, planes) {
- if (parentPlaneMask === exports.Mask.OUTSIDE || parentPlaneMask === exports.Mask.INSIDE) {
- // 父节点完全位于视锥内或者外部,直接返回
- return parentPlaneMask;
- }
- // Start with MASK_INSIDE (all zeros) so that after the loop, the return value can be compared with MASK_INSIDE.
- // (Because if there are fewer than 31 planes, the upper bits wont be changed.)
- var mask = exports.Mask.INSIDE;
- var isShape2D = shape2D.indexOf(object.nodeName) > -1;
- // Use viewport culling for 2D shapes
- // @see https://github.com/antvis/g/issues/914
- for (var k = 0, len = planes.length; k < len; ++k) {
- // For k greater than 31 (since 31 is the maximum number of INSIDE/INTERSECTING bits we can store), skip the optimization.
- var flag = 1 << k;
- if ((parentPlaneMask & flag) === 0) {
- // 父节点处于当前面内部,可以跳过
- continue;
- }
- // skip near & far planes when testing 2D shapes
- if (isShape2D && (k === 4 || k === 5)) {
- continue;
- }
- // p-vertex n-vertex <-|plane p-vertex n-vertex
- // 使用 p-vertex 和 n-vertex 加速,避免进行平面和 aabb 全部顶点的相交检测
- var _planes$k = planes[k],
- normal = _planes$k.normal,
- distance = _planes$k.distance;
- if (dot(normal, aabb.getPositiveFarPoint(planes[k])) + distance < 0) {
- return exports.Mask.OUTSIDE;
- }
- if (dot(normal, aabb.getNegativeFarPoint(planes[k])) + distance < 0) {
- // 和当前面相交,对应位置为1,继续检测下一个面
- mask |= flag;
- }
- }
- return mask;
- };
- return FrustumCullingStrategy;
- }();
- var PrepareRendererPlugin = /*#__PURE__*/function () {
- function PrepareRendererPlugin() {
- this.rBush = void 0;
- /**
- * sync to RBush later
- */
- this.toSync = new Set();
- }
- var _proto = PrepareRendererPlugin.prototype;
- // private isFirstTimeRendering = true;
- // private syncing = false;
- _proto.apply = function apply(context) {
- var _this = this;
- var renderingService = context.renderingService,
- renderingContext = context.renderingContext,
- rBushRoot = context.rBushRoot;
- var canvas = renderingContext.root.ownerDocument.defaultView;
- this.rBush = rBushRoot;
- var handleAttributeChanged = function handleAttributeChanged(e) {
- var object = e.target;
- object.renderable.dirty = true;
- renderingService.dirtify();
- };
- var handleBoundsChanged = function handleBoundsChanged(e) {
- var affectChildren = e.detail.affectChildren;
- var object = e.target;
- if (affectChildren) {
- object.forEach(function (node) {
- _this.toSync.add(node);
- });
- }
- var p = object;
- while (p) {
- if (p.renderable) {
- _this.toSync.add(p);
- }
- p = p.parentElement;
- }
- // this.pushToSync(e.composedPath().slice(0, -2) as DisplayObject[]);
- renderingService.dirtify();
- };
- var handleMounted = function handleMounted(e) {
- var object = e.target;
- if (runtime.enableCSSParsing) {
- // recalc style values
- runtime.styleValueRegistry.recalc(object);
- }
- runtime.sceneGraphService.dirtifyToRoot(object);
- renderingService.dirtify();
- };
- var handleUnmounted = function handleUnmounted(e) {
- var object = e.target;
- var rBushNode = object.rBushNode;
- if (rBushNode.aabb) {
- _this.rBush.remove(rBushNode.aabb);
- }
- _this.toSync.delete(object);
- runtime.sceneGraphService.dirtifyToRoot(object);
- renderingService.dirtify();
- };
- renderingService.hooks.init.tap(PrepareRendererPlugin.tag, function () {
- canvas.addEventListener(exports.ElementEvent.MOUNTED, handleMounted);
- canvas.addEventListener(exports.ElementEvent.UNMOUNTED, handleUnmounted);
- canvas.addEventListener(exports.ElementEvent.ATTR_MODIFIED, handleAttributeChanged);
- canvas.addEventListener(exports.ElementEvent.BOUNDS_CHANGED, handleBoundsChanged);
- });
- renderingService.hooks.destroy.tap(PrepareRendererPlugin.tag, function () {
- canvas.removeEventListener(exports.ElementEvent.MOUNTED, handleMounted);
- canvas.removeEventListener(exports.ElementEvent.UNMOUNTED, handleUnmounted);
- canvas.removeEventListener(exports.ElementEvent.ATTR_MODIFIED, handleAttributeChanged);
- canvas.removeEventListener(exports.ElementEvent.BOUNDS_CHANGED, handleBoundsChanged);
- _this.toSync.clear();
- });
- renderingService.hooks.endFrame.tap(PrepareRendererPlugin.tag, function () {
- // if (this.isFirstTimeRendering) {
- // this.isFirstTimeRendering = false;
- // this.syncing = true;
- // // @see https://github.com/antvis/G/issues/1117
- // setTimeout(() => {
- // this.syncRTree();
- // console.log('fcp...');
- // });
- // } else {
- // console.log('next...');
- _this.syncRTree();
- // }
- });
- };
- _proto.syncRTree = function syncRTree() {
- var _this2 = this;
- // if (this.syncing) {
- // return;
- // }
- // bounds changed, need re-inserting its children
- var bulk = [];
- Array.from(this.toSync)
- // some objects may be removed since last frame
- .filter(function (object) {
- return object.isConnected;
- }).forEach(function (node) {
- var rBushNode = node.rBushNode;
- // clear dirty node
- if (rBushNode && rBushNode.aabb) {
- _this2.rBush.remove(rBushNode.aabb);
- }
- var renderBounds = node.getRenderBounds();
- if (renderBounds) {
- var _renderBounds$getMin = renderBounds.getMin(),
- minX = _renderBounds$getMin[0],
- minY = _renderBounds$getMin[1];
- var _renderBounds$getMax = renderBounds.getMax(),
- maxX = _renderBounds$getMax[0],
- maxY = _renderBounds$getMax[1];
- if (!rBushNode.aabb) {
- rBushNode.aabb = {};
- }
- rBushNode.aabb.displayObject = node;
- rBushNode.aabb.minX = minX;
- rBushNode.aabb.minY = minY;
- rBushNode.aabb.maxX = maxX;
- rBushNode.aabb.maxY = maxY;
- }
- if (rBushNode.aabb) {
- // TODO: NaN occurs when width/height of Rect is 0
- if (!isNaN(rBushNode.aabb.maxX) && !isNaN(rBushNode.aabb.maxX) && !isNaN(rBushNode.aabb.minX) && !isNaN(rBushNode.aabb.minY)) {
- bulk.push(rBushNode.aabb);
- }
- }
- });
- // use bulk inserting, which is ~2-3 times faster
- // @see https://github.com/mourner/rbush#bulk-inserting-data
- this.rBush.load(bulk);
- bulk.length = 0;
- this.toSync.clear();
- // this.syncing = false;
- };
- return PrepareRendererPlugin;
- }();
- PrepareRendererPlugin.tag = 'Prepare';
- function isCanvas(value) {
- return !!value.document;
- }
- (function (CanvasEvent) {
- CanvasEvent["READY"] = "ready";
- CanvasEvent["BEFORE_RENDER"] = "beforerender";
- CanvasEvent["RERENDER"] = "rerender";
- CanvasEvent["AFTER_RENDER"] = "afterrender";
- CanvasEvent["BEFORE_DESTROY"] = "beforedestroy";
- CanvasEvent["AFTER_DESTROY"] = "afterdestroy";
- CanvasEvent["RESIZE"] = "resize";
- CanvasEvent["DIRTY_RECTANGLE"] = "dirtyrectangle";
- CanvasEvent["RENDERER_CHANGED"] = "rendererchanged";
- })(exports.CanvasEvent || (exports.CanvasEvent = {}));
- var DEFAULT_CAMERA_Z = 500;
- var DEFAULT_CAMERA_NEAR = 0.1;
- var DEFAULT_CAMERA_FAR = 1000;
- /**
- * reuse custom event preventing from re-create them in every frame
- */
- var mountedEvent = new CustomEvent(exports.ElementEvent.MOUNTED);
- var unmountedEvent = new CustomEvent(exports.ElementEvent.UNMOUNTED);
- var beforeRenderEvent = new CustomEvent(exports.CanvasEvent.BEFORE_RENDER);
- var rerenderEvent = new CustomEvent(exports.CanvasEvent.RERENDER);
- var afterRenderEvent = new CustomEvent(exports.CanvasEvent.AFTER_RENDER);
- /**
- * can be treated like Window in DOM
- * provide some extra methods like `window`, such as:
- * * `window.requestAnimationFrame`
- * * `window.devicePixelRatio`
- *
- * prototype chains: Canvas(Window) -> EventTarget
- */
- var Canvas = /*#__PURE__*/function (_EventTarget) {
- _inheritsLoose(Canvas, _EventTarget);
- function Canvas(config) {
- var _this;
- _this = _EventTarget.call(this) || this;
- // create document
- /**
- * window.document
- */
- _this.document = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
- */
- _this.customElements = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
- */
- _this.requestAnimationFrame = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
- */
- _this.cancelAnimationFrame = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
- */
- _this.devicePixelRatio = void 0;
- /**
- * whether the runtime supports PointerEvent?
- * if not, the event system won't trigger pointer events like `pointerdown`
- */
- _this.supportsPointerEvents = void 0;
- /**
- * whether the runtime supports TouchEvent?
- * if not, the event system won't trigger touch events like `touchstart`
- */
- _this.supportsTouchEvents = void 0;
- /**
- * is this native event a TouchEvent?
- */
- _this.isTouchEvent = void 0;
- /**
- * is this native event a MouseEvent?
- */
- _this.isMouseEvent = void 0;
- /**
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Element
- */
- _this.Element = DisplayObject;
- /**
- * rAF in auto rendering
- */
- _this.frameId = void 0;
- _this.inited = false;
- _this.readyPromise = void 0;
- _this.resolveReadyPromise = void 0;
- _this.context = {};
- _this.document = new Document();
- _this.document.defaultView = _assertThisInitialized(_this);
- // create registry of custom elements
- _this.customElements = new CustomElementRegistry();
- var container = config.container,
- canvas = config.canvas,
- offscreenCanvas = config.offscreenCanvas,
- width = config.width,
- height = config.height,
- devicePixelRatio = config.devicePixelRatio,
- renderer = config.renderer,
- background = config.background,
- cursor = config.cursor,
- document = config.document,
- requestAnimationFrame = config.requestAnimationFrame,
- cancelAnimationFrame = config.cancelAnimationFrame,
- createImage = config.createImage,
- supportsPointerEvents = config.supportsPointerEvents,
- supportsTouchEvents = config.supportsTouchEvents,
- supportsCSSTransform = config.supportsCSSTransform,
- useNativeClickEvent = config.useNativeClickEvent,
- alwaysTriggerPointerEventOnCanvas = config.alwaysTriggerPointerEventOnCanvas,
- isTouchEvent = config.isTouchEvent,
- isMouseEvent = config.isMouseEvent;
- cleanExistedCanvas(container, _assertThisInitialized(_this));
- var canvasWidth = width;
- var canvasHeight = height;
- var dpr = devicePixelRatio;
- // use user-defined <canvas> or OffscreenCanvas
- if (canvas) {
- // infer width & height with dpr
- dpr = devicePixelRatio || isBrowser && window.devicePixelRatio || 1;
- dpr = dpr >= 1 ? Math.ceil(dpr) : 1;
- canvasWidth = width || getWidth(canvas) || canvas.width / dpr;
- canvasHeight = height || getHeight(canvas) || canvas.height / dpr;
- }
- /**
- * implements `Window` interface
- */
- _this.devicePixelRatio = dpr;
- _this.requestAnimationFrame = requestAnimationFrame !== null && requestAnimationFrame !== void 0 ? requestAnimationFrame : raf.bind(runtime.globalThis);
- _this.cancelAnimationFrame = cancelAnimationFrame !== null && cancelAnimationFrame !== void 0 ? cancelAnimationFrame : caf.bind(runtime.globalThis);
- /**
- * limits query
- */
- // the following feature-detect from hammer.js
- // @see https://github.com/hammerjs/hammer.js/blob/master/src/inputjs/input-consts.js#L5
- _this.supportsTouchEvents = supportsTouchEvents !== null && supportsTouchEvents !== void 0 ? supportsTouchEvents : 'ontouchstart' in runtime.globalThis;
- _this.supportsPointerEvents = supportsPointerEvents !== null && supportsPointerEvents !== void 0 ? supportsPointerEvents : !!runtime.globalThis.PointerEvent;
- _this.isTouchEvent = isTouchEvent !== null && isTouchEvent !== void 0 ? isTouchEvent : function (event) {
- return _this.supportsTouchEvents && event instanceof runtime.globalThis.TouchEvent;
- };
- _this.isMouseEvent = isMouseEvent !== null && isMouseEvent !== void 0 ? isMouseEvent : function (event) {
- return !runtime.globalThis.MouseEvent || event instanceof runtime.globalThis.MouseEvent && (!_this.supportsPointerEvents || !(event instanceof runtime.globalThis.PointerEvent));
- };
- _this.initRenderingContext({
- container: container,
- canvas: canvas,
- width: canvasWidth,
- height: canvasHeight,
- renderer: renderer,
- offscreenCanvas: offscreenCanvas,
- devicePixelRatio: dpr,
- cursor: cursor || 'default',
- background: background || 'transparent',
- createImage: createImage,
- document: document,
- supportsCSSTransform: supportsCSSTransform,
- useNativeClickEvent: useNativeClickEvent,
- alwaysTriggerPointerEventOnCanvas: alwaysTriggerPointerEventOnCanvas
- });
- _this.initDefaultCamera(canvasWidth, canvasHeight);
- _this.initRenderer(renderer, true);
- return _this;
- }
- var _proto = Canvas.prototype;
- _proto.initRenderingContext = function initRenderingContext(mergedConfig) {
- this.context.config = mergedConfig;
- // bind rendering context, shared by all renderers
- this.context.renderingContext = {
- /**
- * the root node in scene graph
- */
- root: this.document.documentElement,
- renderListCurrentFrame: [],
- unculledEntities: [],
- renderReasons: new Set(),
- force: false,
- dirty: false
- };
- };
- _proto.initDefaultCamera = function initDefaultCamera(width, height) {
- var _this2 = this;
- // set a default ortho camera
- var camera = new runtime.CameraContribution();
- camera.setType(exports.CameraType.EXPLORING, exports.CameraTrackingMode.DEFAULT).setPosition(width / 2, height / 2, DEFAULT_CAMERA_Z).setFocalPoint(width / 2, height / 2, 0).setOrthographic(width / -2, width / 2, height / 2, height / -2, DEFAULT_CAMERA_NEAR, DEFAULT_CAMERA_FAR);
- // keep ref since it will use raf in camera animation
- camera.canvas = this;
- // redraw when camera changed
- camera.eventEmitter.on(CameraEvent.UPDATED, function () {
- _this2.context.renderingContext.renderReasons.add(exports.RenderReason.CAMERA_CHANGED);
- });
- // bind camera
- this.context.camera = camera;
- };
- _proto.getConfig = function getConfig() {
- return this.context.config;
- }
- /**
- * get the root displayObject in scenegraph
- * @alias this.document.documentElement
- */;
- _proto.getRoot = function getRoot() {
- return this.document.documentElement;
- }
- /**
- * get the camera of canvas
- */;
- _proto.getCamera = function getCamera() {
- return this.context.camera;
- };
- _proto.getContextService = function getContextService() {
- return this.context.contextService;
- };
- _proto.getEventService = function getEventService() {
- return this.context.eventService;
- };
- _proto.getRenderingService = function getRenderingService() {
- return this.context.renderingService;
- };
- _proto.getRenderingContext = function getRenderingContext() {
- return this.context.renderingContext;
- };
- _proto.getStats = function getStats() {
- return this.getRenderingService().getStats();
- }
- // /**
- // * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle
- // */
- // getComputedStyle(node: DisplayObject) {
- // return node.computedStyle;
- // }
- ;
- /**
- * `cleanUp` means clean all the internal services of Canvas which happens when calling `canvas.destroy()`.
- */
- _proto.destroy = function destroy(cleanUp, skipTriggerEvent) {
- if (cleanUp === void 0) {
- cleanUp = true;
- }
- if (skipTriggerEvent === void 0) {
- skipTriggerEvent = false;
- }
- if (!skipTriggerEvent) {
- this.dispatchEvent(new CustomEvent(exports.CanvasEvent.BEFORE_DESTROY));
- }
- if (this.frameId) {
- var cancelRAF = this.getConfig().cancelAnimationFrame || cancelAnimationFrame;
- cancelRAF(this.frameId);
- }
- // unmount all children
- var root = this.getRoot();
- this.unmountChildren(root);
- if (cleanUp) {
- // destroy Document
- this.document.destroy();
- this.getEventService().destroy();
- }
- // destroy services
- this.getRenderingService().destroy();
- this.getContextService().destroy();
- // clear root after renderservice destroyed
- if (cleanUp && this.context.rBushRoot) {
- // clear rbush
- this.context.rBushRoot.clear();
- this.context.rBushRoot = null;
- this.context.renderingContext.root = null;
- }
- if (!skipTriggerEvent) {
- this.dispatchEvent(new CustomEvent(exports.CanvasEvent.AFTER_DESTROY));
- }
- }
- /**
- * compatible with G 3.0
- * @deprecated
- * @alias resize
- */;
- _proto.changeSize = function changeSize(width, height) {
- this.resize(width, height);
- };
- _proto.resize = function resize(width, height) {
- // update canvas' config
- var canvasConfig = this.context.config;
- canvasConfig.width = width;
- canvasConfig.height = height;
- // resize context
- this.getContextService().resize(width, height);
- // resize camera
- var camera = this.context.camera;
- var projectionMode = camera.getProjectionMode();
- camera.setPosition(width / 2, height / 2, DEFAULT_CAMERA_Z).setFocalPoint(width / 2, height / 2, 0);
- if (projectionMode === exports.CameraProjectionMode.ORTHOGRAPHIC) {
- camera.setOrthographic(width / -2, width / 2, height / 2, height / -2, camera.getNear(), camera.getFar());
- } else {
- camera.setAspect(width / height);
- }
- this.dispatchEvent(new CustomEvent(exports.CanvasEvent.RESIZE, {
- width: width,
- height: height
- }));
- }
- // proxy to document.documentElement
- ;
- _proto.appendChild = function appendChild(child, index) {
- return this.document.documentElement.appendChild(child, index);
- };
- _proto.insertBefore = function insertBefore(newChild, refChild) {
- return this.document.documentElement.insertBefore(newChild, refChild);
- };
- _proto.removeChild = function removeChild(child) {
- return this.document.documentElement.removeChild(child);
- }
- /**
- * Remove all children which can be appended to its original parent later again.
- */;
- _proto.removeChildren = function removeChildren() {
- this.document.documentElement.removeChildren();
- }
- /**
- * Recursively destroy all children which can not be appended to its original parent later again.
- * But the canvas remains running which means display objects can be appended later.
- */;
- _proto.destroyChildren = function destroyChildren() {
- this.document.documentElement.destroyChildren();
- };
- _proto.render = function render() {
- var _this3 = this;
- this.dispatchEvent(beforeRenderEvent);
- var renderingService = this.getRenderingService();
- renderingService.render(this.getConfig(), function () {
- // trigger actual rerender event
- // @see https://github.com/antvis/G/issues/1268
- _this3.dispatchEvent(rerenderEvent);
- });
- this.dispatchEvent(afterRenderEvent);
- };
- _proto.run = function run() {
- var _this4 = this;
- var tick = function tick() {
- _this4.render();
- _this4.frameId = _this4.requestAnimationFrame(tick);
- };
- tick();
- };
- _proto.initRenderer = function initRenderer(renderer, firstContentfullPaint) {
- var _this5 = this;
- if (firstContentfullPaint === void 0) {
- firstContentfullPaint = false;
- }
- if (!renderer) {
- throw new Error('Renderer is required.');
- }
- // reset
- this.inited = false;
- this.readyPromise = undefined;
- // FIXME: should re-create here?
- this.context.rBushRoot = new rbush();
- // reset rendering plugins
- this.context.renderingPlugins = [];
- this.context.renderingPlugins.push(new EventPlugin(), new PrepareRendererPlugin(), new DirtyCheckPlugin(), new CullingPlugin([new FrustumCullingStrategy()]));
- //
- this.loadRendererContainerModule(renderer);
- // init context service
- this.context.contextService = new this.context.ContextService(_extends({}, runtime, this.context));
- // init rendering service
- this.context.renderingService = new RenderingService(runtime, this.context);
- // init event service
- this.context.eventService = new EventService(runtime, this.context);
- this.context.eventService.init();
- if (this.context.contextService.init) {
- this.context.contextService.init();
- this.initRenderingService(renderer, firstContentfullPaint, true);
- } else {
- this.context.contextService.initAsync().then(function () {
- _this5.initRenderingService(renderer, firstContentfullPaint);
- });
- }
- };
- _proto.initRenderingService = function initRenderingService(renderer, firstContentfullPaint, async) {
- var _this6 = this;
- if (firstContentfullPaint === void 0) {
- firstContentfullPaint = false;
- }
- if (async === void 0) {
- async = false;
- }
- this.context.renderingService.init(function () {
- _this6.inited = true;
- if (firstContentfullPaint) {
- if (async) {
- _this6.requestAnimationFrame(function () {
- _this6.dispatchEvent(new CustomEvent(exports.CanvasEvent.READY));
- });
- } else {
- _this6.dispatchEvent(new CustomEvent(exports.CanvasEvent.READY));
- }
- if (_this6.readyPromise) {
- _this6.resolveReadyPromise();
- }
- } else {
- _this6.dispatchEvent(new CustomEvent(exports.CanvasEvent.RENDERER_CHANGED));
- }
- if (!firstContentfullPaint) {
- _this6.getRoot().forEach(function (node) {
- var renderable = node.renderable;
- if (renderable) {
- renderable.renderBoundsDirty = true;
- renderable.boundsDirty = true;
- renderable.dirty = true;
- }
- });
- }
- // keep current scenegraph unchanged, just trigger mounted event
- _this6.mountChildren(_this6.getRoot());
- if (renderer.getConfig().enableAutoRendering) {
- _this6.run();
- }
- });
- };
- _proto.loadRendererContainerModule = function loadRendererContainerModule(renderer) {
- var _this7 = this;
- // load other container modules provided by g-canvas/g-svg/g-webgl
- var plugins = renderer.getPlugins();
- plugins.forEach(function (plugin) {
- plugin.context = _this7.context;
- plugin.init(runtime);
- });
- };
- _proto.setRenderer = function setRenderer(renderer) {
- // update canvas' config
- var canvasConfig = this.getConfig();
- if (canvasConfig.renderer === renderer) {
- return;
- }
- var oldRenderer = canvasConfig.renderer;
- canvasConfig.renderer = renderer;
- // keep all children undestroyed
- this.destroy(false, true);
- // destroy all plugins, reverse will mutate origin array
- [].concat(oldRenderer === null || oldRenderer === void 0 ? void 0 : oldRenderer.getPlugins()).reverse().forEach(function (plugin) {
- plugin.destroy(runtime);
- });
- this.initRenderer(renderer);
- };
- _proto.setCursor = function setCursor(cursor) {
- var canvasConfig = this.getConfig();
- canvasConfig.cursor = cursor;
- this.getContextService().applyCursorStyle(cursor);
- };
- _proto.unmountChildren = function unmountChildren(parent) {
- var _this8 = this;
- // unmountChildren recursively
- parent.childNodes.forEach(function (child) {
- _this8.unmountChildren(child);
- });
- if (this.inited) {
- if (parent.isMutationObserved) {
- parent.dispatchEvent(unmountedEvent);
- } else {
- unmountedEvent.target = parent;
- this.dispatchEvent(unmountedEvent, true);
- }
- // skip document.documentElement
- if (parent !== this.document.documentElement) {
- parent.ownerDocument = null;
- }
- parent.isConnected = false;
- }
- // trigger after unmounted
- if (parent.isCustomElement) {
- if (parent.disconnectedCallback) {
- parent.disconnectedCallback();
- }
- }
- };
- _proto.mountChildren = function mountChildren(parent) {
- var _this9 = this;
- if (this.inited) {
- if (!parent.isConnected) {
- parent.ownerDocument = this.document;
- parent.isConnected = true;
- if (parent.isMutationObserved) {
- parent.dispatchEvent(mountedEvent);
- } else {
- mountedEvent.target = parent;
- this.dispatchEvent(mountedEvent, true);
- }
- }
- } else {
- console.warn("[g]: You are trying to call `canvas.appendChild` before canvas' initialization finished. You can either await `canvas.ready` or listen to `CanvasEvent.READY` manually.", 'appended child: ', parent.nodeName);
- }
- // recursively mount children
- parent.childNodes.forEach(function (child) {
- _this9.mountChildren(child);
- });
- // trigger after mounted
- if (parent.isCustomElement) {
- if (parent.connectedCallback) {
- parent.connectedCallback();
- }
- }
- };
- _proto.client2Viewport = function client2Viewport(client) {
- return this.getEventService().client2Viewport(client);
- };
- _proto.viewport2Client = function viewport2Client(canvas) {
- return this.getEventService().viewport2Client(canvas);
- };
- _proto.viewport2Canvas = function viewport2Canvas(viewport) {
- return this.getEventService().viewport2Canvas(viewport);
- };
- _proto.canvas2Viewport = function canvas2Viewport(canvas) {
- return this.getEventService().canvas2Viewport(canvas);
- }
- /**
- * @deprecated
- * @alias client2Viewport
- */;
- _proto.getPointByClient = function getPointByClient(clientX, clientY) {
- return this.client2Viewport({
- x: clientX,
- y: clientY
- });
- }
- /**
- * @deprecated
- * @alias viewport2Client
- */;
- _proto.getClientByPoint = function getClientByPoint(x, y) {
- return this.viewport2Client({
- x: x,
- y: y
- });
- };
- _createClass(Canvas, [{
- key: "ready",
- get: function get() {
- var _this10 = this;
- if (!this.readyPromise) {
- this.readyPromise = new Promise(function (resolve) {
- _this10.resolveReadyPromise = function () {
- resolve(_this10);
- };
- });
- if (this.inited) {
- this.resolveReadyPromise();
- }
- }
- return this.readyPromise;
- }
- }]);
- return Canvas;
- }(EventTarget);
- exports.AABB = AABB;
- exports.AbstractRenderer = AbstractRenderer;
- exports.AbstractRendererPlugin = AbstractRendererPlugin;
- exports.BUILT_IN_PROPERTIES = BUILT_IN_PROPERTIES;
- exports.CSS = CSS;
- exports.CSSGradientValue = CSSGradientValue;
- exports.CSSKeywordValue = CSSKeywordValue;
- exports.CSSRGB = CSSRGB;
- exports.CSSStyleValue = CSSStyleValue;
- exports.CSSUnitValue = CSSUnitValue;
- exports.Camera = Camera;
- exports.CameraEvent = CameraEvent;
- exports.Canvas = Canvas;
- exports.Circle = Circle;
- exports.CircleUpdater = CircleUpdater;
- exports.CustomElement = CustomElement;
- exports.CustomElementRegistry = CustomElementRegistry;
- exports.CustomEvent = CustomEvent;
- exports.DefaultSceneGraphSelector = DefaultSceneGraphSelector;
- exports.DefaultSceneGraphService = DefaultSceneGraphService;
- exports.DisplayObject = DisplayObject;
- exports.Document = Document;
- exports.EMPTY_PARSED_PATH = EMPTY_PARSED_PATH;
- exports.ERROR_MSG_METHOD_NOT_IMPLEMENTED = ERROR_MSG_METHOD_NOT_IMPLEMENTED;
- exports.Element = Element;
- exports.Ellipse = Ellipse;
- exports.EllipseUpdater = EllipseUpdater;
- exports.EventService = EventService;
- exports.EventTarget = EventTarget;
- exports.FederatedEvent = FederatedEvent;
- exports.FederatedMouseEvent = FederatedMouseEvent;
- exports.FederatedPointerEvent = FederatedPointerEvent;
- exports.FederatedWheelEvent = FederatedWheelEvent;
- exports.Frustum = Frustum;
- exports.Group = Group;
- exports.HTML = HTML;
- exports.Image = Image;
- exports.Line = Line;
- exports.LineUpdater = LineUpdater;
- exports.MutationEvent = MutationEvent;
- exports.Node = Node;
- exports.OffscreenCanvasCreator = OffscreenCanvasCreator;
- exports.Path = Path;
- exports.PathUpdater = PathUpdater;
- exports.Plane = Plane;
- exports.Point = Point;
- exports.Polygon = Polygon;
- exports.Polyline = Polyline;
- exports.PolylineUpdater = PolylineUpdater;
- exports.RBush = rbush;
- exports.Rect = Rect;
- exports.RectUpdater = RectUpdater;
- exports.Rectangle = Rectangle;
- exports.RenderingService = RenderingService;
- exports.Text = Text;
- exports.TextService = TextService;
- exports.TextUpdater = TextUpdater;
- exports.computeLinearGradient = computeLinearGradient;
- exports.computeRadialGradient = computeRadialGradient;
- exports.convertToPath = convertToPath;
- exports.createVec3 = createVec3;
- exports.decompose = decompose;
- exports.definedProps = definedProps;
- exports.deg2rad = deg2rad;
- exports.deg2turn = deg2turn;
- exports.findClosestClipPathTarget = findClosestClipPathTarget;
- exports.fromRotationTranslationScale = fromRotationTranslationScale$1;
- exports.getAngle = getAngle;
- exports.getEuler = getEuler;
- exports.getOrCalculatePathTotalLength = getOrCalculatePathTotalLength;
- exports.grad2deg = grad2deg;
- exports.isBrowser = isBrowser;
- exports.isCSSGradientValue = isCSSGradientValue;
- exports.isCSSRGB = isCSSRGB;
- exports.isCanvas = isCanvas;
- exports.isDisplayObject = isDisplayObject;
- exports.isFederatedEvent = isFederatedEvent;
- exports.isFillOrStrokeAffected = isFillOrStrokeAffected;
- exports.isPattern = isPattern;
- exports.mergeColors = mergeColors;
- exports.parseColor = parseColor;
- exports.parseLength = parseLength;
- exports.parsePath = parsePath;
- exports.parseTransform = parseTransform;
- exports.parsedTransformToMat4 = parsedTransformToMat4;
- exports.propertyMetadataCache = propertyMetadataCache;
- exports.rad2deg = rad2deg;
- exports.resetEntityCounter = resetEntityCounter;
- exports.runtime = runtime;
- exports.setDOMSize = setDOMSize;
- exports.translatePathToString = translatePathToString;
- exports.turn2deg = turn2deg;
- Object.defineProperty(exports, '__esModule', { value: true });
- })));
|