index.umd.js 701 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.G = {}));
  5. }(this, (function (exports) { 'use strict';
  6. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  7. function createCommonjsModule(fn, basedir, module) {
  8. return module = {
  9. path: basedir,
  10. exports: {},
  11. require: function (path, base) {
  12. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  13. }
  14. }, fn(module, module.exports), module.exports;
  15. }
  16. function commonjsRequire () {
  17. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  18. }
  19. var rbush = createCommonjsModule(function (module, exports) {
  20. (function (global, factory) {
  21. module.exports = factory() ;
  22. }(commonjsGlobal, function () {
  23. function quickselect(arr, k, left, right, compare) {
  24. quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);
  25. }
  26. function quickselectStep(arr, k, left, right, compare) {
  27. while (right > left) {
  28. if (right - left > 600) {
  29. var n = right - left + 1;
  30. var m = k - left + 1;
  31. var z = Math.log(n);
  32. var s = 0.5 * Math.exp(2 * z / 3);
  33. var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);
  34. var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));
  35. var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));
  36. quickselectStep(arr, k, newLeft, newRight, compare);
  37. }
  38. var t = arr[k];
  39. var i = left;
  40. var j = right;
  41. swap(arr, left, k);
  42. if (compare(arr[right], t) > 0) { swap(arr, left, right); }
  43. while (i < j) {
  44. swap(arr, i, j);
  45. i++;
  46. j--;
  47. while (compare(arr[i], t) < 0) { i++; }
  48. while (compare(arr[j], t) > 0) { j--; }
  49. }
  50. if (compare(arr[left], t) === 0) { swap(arr, left, j); }
  51. else {
  52. j++;
  53. swap(arr, j, right);
  54. }
  55. if (j <= k) { left = j + 1; }
  56. if (k <= j) { right = j - 1; }
  57. }
  58. }
  59. function swap(arr, i, j) {
  60. var tmp = arr[i];
  61. arr[i] = arr[j];
  62. arr[j] = tmp;
  63. }
  64. function defaultCompare(a, b) {
  65. return a < b ? -1 : a > b ? 1 : 0;
  66. }
  67. var RBush = function RBush(maxEntries) {
  68. if ( maxEntries === void 0 ) maxEntries = 9;
  69. // max entries in a node is 9 by default; min node fill is 40% for best performance
  70. this._maxEntries = Math.max(4, maxEntries);
  71. this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));
  72. this.clear();
  73. };
  74. RBush.prototype.all = function all () {
  75. return this._all(this.data, []);
  76. };
  77. RBush.prototype.search = function search (bbox) {
  78. var node = this.data;
  79. var result = [];
  80. if (!intersects(bbox, node)) { return result; }
  81. var toBBox = this.toBBox;
  82. var nodesToSearch = [];
  83. while (node) {
  84. for (var i = 0; i < node.children.length; i++) {
  85. var child = node.children[i];
  86. var childBBox = node.leaf ? toBBox(child) : child;
  87. if (intersects(bbox, childBBox)) {
  88. if (node.leaf) { result.push(child); }
  89. else if (contains(bbox, childBBox)) { this._all(child, result); }
  90. else { nodesToSearch.push(child); }
  91. }
  92. }
  93. node = nodesToSearch.pop();
  94. }
  95. return result;
  96. };
  97. RBush.prototype.collides = function collides (bbox) {
  98. var node = this.data;
  99. if (!intersects(bbox, node)) { return false; }
  100. var nodesToSearch = [];
  101. while (node) {
  102. for (var i = 0; i < node.children.length; i++) {
  103. var child = node.children[i];
  104. var childBBox = node.leaf ? this.toBBox(child) : child;
  105. if (intersects(bbox, childBBox)) {
  106. if (node.leaf || contains(bbox, childBBox)) { return true; }
  107. nodesToSearch.push(child);
  108. }
  109. }
  110. node = nodesToSearch.pop();
  111. }
  112. return false;
  113. };
  114. RBush.prototype.load = function load (data) {
  115. if (!(data && data.length)) { return this; }
  116. if (data.length < this._minEntries) {
  117. for (var i = 0; i < data.length; i++) {
  118. this.insert(data[i]);
  119. }
  120. return this;
  121. }
  122. // recursively build the tree with the given data from scratch using OMT algorithm
  123. var node = this._build(data.slice(), 0, data.length - 1, 0);
  124. if (!this.data.children.length) {
  125. // save as is if tree is empty
  126. this.data = node;
  127. } else if (this.data.height === node.height) {
  128. // split root if trees have the same height
  129. this._splitRoot(this.data, node);
  130. } else {
  131. if (this.data.height < node.height) {
  132. // swap trees if inserted one is bigger
  133. var tmpNode = this.data;
  134. this.data = node;
  135. node = tmpNode;
  136. }
  137. // insert the small tree into the large tree at appropriate level
  138. this._insert(node, this.data.height - node.height - 1, true);
  139. }
  140. return this;
  141. };
  142. RBush.prototype.insert = function insert (item) {
  143. if (item) { this._insert(item, this.data.height - 1); }
  144. return this;
  145. };
  146. RBush.prototype.clear = function clear () {
  147. this.data = createNode([]);
  148. return this;
  149. };
  150. RBush.prototype.remove = function remove (item, equalsFn) {
  151. if (!item) { return this; }
  152. var node = this.data;
  153. var bbox = this.toBBox(item);
  154. var path = [];
  155. var indexes = [];
  156. var i, parent, goingUp;
  157. // depth-first iterative tree traversal
  158. while (node || path.length) {
  159. if (!node) { // go up
  160. node = path.pop();
  161. parent = path[path.length - 1];
  162. i = indexes.pop();
  163. goingUp = true;
  164. }
  165. if (node.leaf) { // check current node
  166. var index = findItem(item, node.children, equalsFn);
  167. if (index !== -1) {
  168. // item found, remove the item and condense tree upwards
  169. node.children.splice(index, 1);
  170. path.push(node);
  171. this._condense(path);
  172. return this;
  173. }
  174. }
  175. if (!goingUp && !node.leaf && contains(node, bbox)) { // go down
  176. path.push(node);
  177. indexes.push(i);
  178. i = 0;
  179. parent = node;
  180. node = node.children[0];
  181. } else if (parent) { // go right
  182. i++;
  183. node = parent.children[i];
  184. goingUp = false;
  185. } else { node = null; } // nothing found
  186. }
  187. return this;
  188. };
  189. RBush.prototype.toBBox = function toBBox (item) { return item; };
  190. RBush.prototype.compareMinX = function compareMinX (a, b) { return a.minX - b.minX; };
  191. RBush.prototype.compareMinY = function compareMinY (a, b) { return a.minY - b.minY; };
  192. RBush.prototype.toJSON = function toJSON () { return this.data; };
  193. RBush.prototype.fromJSON = function fromJSON (data) {
  194. this.data = data;
  195. return this;
  196. };
  197. RBush.prototype._all = function _all (node, result) {
  198. var nodesToSearch = [];
  199. while (node) {
  200. if (node.leaf) { result.push.apply(result, node.children); }
  201. else { nodesToSearch.push.apply(nodesToSearch, node.children); }
  202. node = nodesToSearch.pop();
  203. }
  204. return result;
  205. };
  206. RBush.prototype._build = function _build (items, left, right, height) {
  207. var N = right - left + 1;
  208. var M = this._maxEntries;
  209. var node;
  210. if (N <= M) {
  211. // reached leaf level; return leaf
  212. node = createNode(items.slice(left, right + 1));
  213. calcBBox(node, this.toBBox);
  214. return node;
  215. }
  216. if (!height) {
  217. // target height of the bulk-loaded tree
  218. height = Math.ceil(Math.log(N) / Math.log(M));
  219. // target number of root entries to maximize storage utilization
  220. M = Math.ceil(N / Math.pow(M, height - 1));
  221. }
  222. node = createNode([]);
  223. node.leaf = false;
  224. node.height = height;
  225. // split the items into M mostly square tiles
  226. var N2 = Math.ceil(N / M);
  227. var N1 = N2 * Math.ceil(Math.sqrt(M));
  228. multiSelect(items, left, right, N1, this.compareMinX);
  229. for (var i = left; i <= right; i += N1) {
  230. var right2 = Math.min(i + N1 - 1, right);
  231. multiSelect(items, i, right2, N2, this.compareMinY);
  232. for (var j = i; j <= right2; j += N2) {
  233. var right3 = Math.min(j + N2 - 1, right2);
  234. // pack each entry recursively
  235. node.children.push(this._build(items, j, right3, height - 1));
  236. }
  237. }
  238. calcBBox(node, this.toBBox);
  239. return node;
  240. };
  241. RBush.prototype._chooseSubtree = function _chooseSubtree (bbox, node, level, path) {
  242. while (true) {
  243. path.push(node);
  244. if (node.leaf || path.length - 1 === level) { break; }
  245. var minArea = Infinity;
  246. var minEnlargement = Infinity;
  247. var targetNode = (void 0);
  248. for (var i = 0; i < node.children.length; i++) {
  249. var child = node.children[i];
  250. var area = bboxArea(child);
  251. var enlargement = enlargedArea(bbox, child) - area;
  252. // choose entry with the least area enlargement
  253. if (enlargement < minEnlargement) {
  254. minEnlargement = enlargement;
  255. minArea = area < minArea ? area : minArea;
  256. targetNode = child;
  257. } else if (enlargement === minEnlargement) {
  258. // otherwise choose one with the smallest area
  259. if (area < minArea) {
  260. minArea = area;
  261. targetNode = child;
  262. }
  263. }
  264. }
  265. node = targetNode || node.children[0];
  266. }
  267. return node;
  268. };
  269. RBush.prototype._insert = function _insert (item, level, isNode) {
  270. var bbox = isNode ? item : this.toBBox(item);
  271. var insertPath = [];
  272. // find the best node for accommodating the item, saving all nodes along the path too
  273. var node = this._chooseSubtree(bbox, this.data, level, insertPath);
  274. // put the item into the node
  275. node.children.push(item);
  276. extend(node, bbox);
  277. // split on node overflow; propagate upwards if necessary
  278. while (level >= 0) {
  279. if (insertPath[level].children.length > this._maxEntries) {
  280. this._split(insertPath, level);
  281. level--;
  282. } else { break; }
  283. }
  284. // adjust bboxes along the insertion path
  285. this._adjustParentBBoxes(bbox, insertPath, level);
  286. };
  287. // split overflowed node into two
  288. RBush.prototype._split = function _split (insertPath, level) {
  289. var node = insertPath[level];
  290. var M = node.children.length;
  291. var m = this._minEntries;
  292. this._chooseSplitAxis(node, m, M);
  293. var splitIndex = this._chooseSplitIndex(node, m, M);
  294. var newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));
  295. newNode.height = node.height;
  296. newNode.leaf = node.leaf;
  297. calcBBox(node, this.toBBox);
  298. calcBBox(newNode, this.toBBox);
  299. if (level) { insertPath[level - 1].children.push(newNode); }
  300. else { this._splitRoot(node, newNode); }
  301. };
  302. RBush.prototype._splitRoot = function _splitRoot (node, newNode) {
  303. // split root node
  304. this.data = createNode([node, newNode]);
  305. this.data.height = node.height + 1;
  306. this.data.leaf = false;
  307. calcBBox(this.data, this.toBBox);
  308. };
  309. RBush.prototype._chooseSplitIndex = function _chooseSplitIndex (node, m, M) {
  310. var index;
  311. var minOverlap = Infinity;
  312. var minArea = Infinity;
  313. for (var i = m; i <= M - m; i++) {
  314. var bbox1 = distBBox(node, 0, i, this.toBBox);
  315. var bbox2 = distBBox(node, i, M, this.toBBox);
  316. var overlap = intersectionArea(bbox1, bbox2);
  317. var area = bboxArea(bbox1) + bboxArea(bbox2);
  318. // choose distribution with minimum overlap
  319. if (overlap < minOverlap) {
  320. minOverlap = overlap;
  321. index = i;
  322. minArea = area < minArea ? area : minArea;
  323. } else if (overlap === minOverlap) {
  324. // otherwise choose distribution with minimum area
  325. if (area < minArea) {
  326. minArea = area;
  327. index = i;
  328. }
  329. }
  330. }
  331. return index || M - m;
  332. };
  333. // sorts node children by the best axis for split
  334. RBush.prototype._chooseSplitAxis = function _chooseSplitAxis (node, m, M) {
  335. var compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;
  336. var compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;
  337. var xMargin = this._allDistMargin(node, m, M, compareMinX);
  338. var yMargin = this._allDistMargin(node, m, M, compareMinY);
  339. // if total distributions margin value is minimal for x, sort by minX,
  340. // otherwise it's already sorted by minY
  341. if (xMargin < yMargin) { node.children.sort(compareMinX); }
  342. };
  343. // total margin of all possible split distributions where each node is at least m full
  344. RBush.prototype._allDistMargin = function _allDistMargin (node, m, M, compare) {
  345. node.children.sort(compare);
  346. var toBBox = this.toBBox;
  347. var leftBBox = distBBox(node, 0, m, toBBox);
  348. var rightBBox = distBBox(node, M - m, M, toBBox);
  349. var margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);
  350. for (var i = m; i < M - m; i++) {
  351. var child = node.children[i];
  352. extend(leftBBox, node.leaf ? toBBox(child) : child);
  353. margin += bboxMargin(leftBBox);
  354. }
  355. for (var i$1 = M - m - 1; i$1 >= m; i$1--) {
  356. var child$1 = node.children[i$1];
  357. extend(rightBBox, node.leaf ? toBBox(child$1) : child$1);
  358. margin += bboxMargin(rightBBox);
  359. }
  360. return margin;
  361. };
  362. RBush.prototype._adjustParentBBoxes = function _adjustParentBBoxes (bbox, path, level) {
  363. // adjust bboxes along the given tree path
  364. for (var i = level; i >= 0; i--) {
  365. extend(path[i], bbox);
  366. }
  367. };
  368. RBush.prototype._condense = function _condense (path) {
  369. // go through the path, removing empty nodes and updating bboxes
  370. for (var i = path.length - 1, siblings = (void 0); i >= 0; i--) {
  371. if (path[i].children.length === 0) {
  372. if (i > 0) {
  373. siblings = path[i - 1].children;
  374. siblings.splice(siblings.indexOf(path[i]), 1);
  375. } else { this.clear(); }
  376. } else { calcBBox(path[i], this.toBBox); }
  377. }
  378. };
  379. function findItem(item, items, equalsFn) {
  380. if (!equalsFn) { return items.indexOf(item); }
  381. for (var i = 0; i < items.length; i++) {
  382. if (equalsFn(item, items[i])) { return i; }
  383. }
  384. return -1;
  385. }
  386. // calculate node's bbox from bboxes of its children
  387. function calcBBox(node, toBBox) {
  388. distBBox(node, 0, node.children.length, toBBox, node);
  389. }
  390. // min bounding rectangle of node children from k to p-1
  391. function distBBox(node, k, p, toBBox, destNode) {
  392. if (!destNode) { destNode = createNode(null); }
  393. destNode.minX = Infinity;
  394. destNode.minY = Infinity;
  395. destNode.maxX = -Infinity;
  396. destNode.maxY = -Infinity;
  397. for (var i = k; i < p; i++) {
  398. var child = node.children[i];
  399. extend(destNode, node.leaf ? toBBox(child) : child);
  400. }
  401. return destNode;
  402. }
  403. function extend(a, b) {
  404. a.minX = Math.min(a.minX, b.minX);
  405. a.minY = Math.min(a.minY, b.minY);
  406. a.maxX = Math.max(a.maxX, b.maxX);
  407. a.maxY = Math.max(a.maxY, b.maxY);
  408. return a;
  409. }
  410. function compareNodeMinX(a, b) { return a.minX - b.minX; }
  411. function compareNodeMinY(a, b) { return a.minY - b.minY; }
  412. function bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }
  413. function bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }
  414. function enlargedArea(a, b) {
  415. return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *
  416. (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));
  417. }
  418. function intersectionArea(a, b) {
  419. var minX = Math.max(a.minX, b.minX);
  420. var minY = Math.max(a.minY, b.minY);
  421. var maxX = Math.min(a.maxX, b.maxX);
  422. var maxY = Math.min(a.maxY, b.maxY);
  423. return Math.max(0, maxX - minX) *
  424. Math.max(0, maxY - minY);
  425. }
  426. function contains(a, b) {
  427. return a.minX <= b.minX &&
  428. a.minY <= b.minY &&
  429. b.maxX <= a.maxX &&
  430. b.maxY <= a.maxY;
  431. }
  432. function intersects(a, b) {
  433. return b.minX <= a.maxX &&
  434. b.minY <= a.maxY &&
  435. b.maxX >= a.minX &&
  436. b.maxY >= a.minY;
  437. }
  438. function createNode(children) {
  439. return {
  440. children: children,
  441. height: 1,
  442. leaf: true,
  443. minX: Infinity,
  444. minY: Infinity,
  445. maxX: -Infinity,
  446. maxY: -Infinity
  447. };
  448. }
  449. // sort an array so that items come in groups of n unsorted items, with groups sorted between each other;
  450. // combines selection algorithm with binary divide & conquer approach
  451. function multiSelect(arr, left, right, n, compare) {
  452. var stack = [left, right];
  453. while (stack.length) {
  454. right = stack.pop();
  455. left = stack.pop();
  456. if (right - left <= n) { continue; }
  457. var mid = left + Math.ceil((right - left) / n / 2) * n;
  458. quickselect(arr, mid, left, right, compare);
  459. stack.push(left, mid, mid, right);
  460. }
  461. }
  462. return RBush;
  463. }));
  464. });
  465. /**
  466. * Common utilities
  467. * @module glMatrix
  468. */
  469. // Configuration Constants
  470. var EPSILON = 0.000001;
  471. var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  472. if (!Math.hypot) Math.hypot = function () {
  473. var y = 0,
  474. i = arguments.length;
  475. while (i--) {
  476. y += arguments[i] * arguments[i];
  477. }
  478. return Math.sqrt(y);
  479. };
  480. /**
  481. * 3x3 Matrix
  482. * @module mat3
  483. */
  484. /**
  485. * Creates a new identity mat3
  486. *
  487. * @returns {mat3} a new 3x3 matrix
  488. */
  489. function create() {
  490. var out = new ARRAY_TYPE(9);
  491. if (ARRAY_TYPE != Float32Array) {
  492. out[1] = 0;
  493. out[2] = 0;
  494. out[3] = 0;
  495. out[5] = 0;
  496. out[6] = 0;
  497. out[7] = 0;
  498. }
  499. out[0] = 1;
  500. out[4] = 1;
  501. out[8] = 1;
  502. return out;
  503. }
  504. /**
  505. * Copies the upper-left 3x3 values into the given mat3.
  506. *
  507. * @param {mat3} out the receiving 3x3 matrix
  508. * @param {ReadonlyMat4} a the source 4x4 matrix
  509. * @returns {mat3} out
  510. */
  511. function fromMat4(out, a) {
  512. out[0] = a[0];
  513. out[1] = a[1];
  514. out[2] = a[2];
  515. out[3] = a[4];
  516. out[4] = a[5];
  517. out[5] = a[6];
  518. out[6] = a[8];
  519. out[7] = a[9];
  520. out[8] = a[10];
  521. return out;
  522. }
  523. /**
  524. * Create a new mat3 with the given values
  525. *
  526. * @param {Number} m00 Component in column 0, row 0 position (index 0)
  527. * @param {Number} m01 Component in column 0, row 1 position (index 1)
  528. * @param {Number} m02 Component in column 0, row 2 position (index 2)
  529. * @param {Number} m10 Component in column 1, row 0 position (index 3)
  530. * @param {Number} m11 Component in column 1, row 1 position (index 4)
  531. * @param {Number} m12 Component in column 1, row 2 position (index 5)
  532. * @param {Number} m20 Component in column 2, row 0 position (index 6)
  533. * @param {Number} m21 Component in column 2, row 1 position (index 7)
  534. * @param {Number} m22 Component in column 2, row 2 position (index 8)
  535. * @returns {mat3} A new mat3
  536. */
  537. function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
  538. var out = new ARRAY_TYPE(9);
  539. out[0] = m00;
  540. out[1] = m01;
  541. out[2] = m02;
  542. out[3] = m10;
  543. out[4] = m11;
  544. out[5] = m12;
  545. out[6] = m20;
  546. out[7] = m21;
  547. out[8] = m22;
  548. return out;
  549. }
  550. /**
  551. * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied.
  552. * @module mat4
  553. */
  554. /**
  555. * Creates a new identity mat4
  556. *
  557. * @returns {mat4} a new 4x4 matrix
  558. */
  559. function create$1() {
  560. var out = new ARRAY_TYPE(16);
  561. if (ARRAY_TYPE != Float32Array) {
  562. out[1] = 0;
  563. out[2] = 0;
  564. out[3] = 0;
  565. out[4] = 0;
  566. out[6] = 0;
  567. out[7] = 0;
  568. out[8] = 0;
  569. out[9] = 0;
  570. out[11] = 0;
  571. out[12] = 0;
  572. out[13] = 0;
  573. out[14] = 0;
  574. }
  575. out[0] = 1;
  576. out[5] = 1;
  577. out[10] = 1;
  578. out[15] = 1;
  579. return out;
  580. }
  581. /**
  582. * Creates a new mat4 initialized with values from an existing matrix
  583. *
  584. * @param {ReadonlyMat4} a matrix to clone
  585. * @returns {mat4} a new 4x4 matrix
  586. */
  587. function clone(a) {
  588. var out = new ARRAY_TYPE(16);
  589. out[0] = a[0];
  590. out[1] = a[1];
  591. out[2] = a[2];
  592. out[3] = a[3];
  593. out[4] = a[4];
  594. out[5] = a[5];
  595. out[6] = a[6];
  596. out[7] = a[7];
  597. out[8] = a[8];
  598. out[9] = a[9];
  599. out[10] = a[10];
  600. out[11] = a[11];
  601. out[12] = a[12];
  602. out[13] = a[13];
  603. out[14] = a[14];
  604. out[15] = a[15];
  605. return out;
  606. }
  607. /**
  608. * Copy the values from one mat4 to another
  609. *
  610. * @param {mat4} out the receiving matrix
  611. * @param {ReadonlyMat4} a the source matrix
  612. * @returns {mat4} out
  613. */
  614. function copy(out, a) {
  615. out[0] = a[0];
  616. out[1] = a[1];
  617. out[2] = a[2];
  618. out[3] = a[3];
  619. out[4] = a[4];
  620. out[5] = a[5];
  621. out[6] = a[6];
  622. out[7] = a[7];
  623. out[8] = a[8];
  624. out[9] = a[9];
  625. out[10] = a[10];
  626. out[11] = a[11];
  627. out[12] = a[12];
  628. out[13] = a[13];
  629. out[14] = a[14];
  630. out[15] = a[15];
  631. return out;
  632. }
  633. /**
  634. * Create a new mat4 with the given values
  635. *
  636. * @param {Number} m00 Component in column 0, row 0 position (index 0)
  637. * @param {Number} m01 Component in column 0, row 1 position (index 1)
  638. * @param {Number} m02 Component in column 0, row 2 position (index 2)
  639. * @param {Number} m03 Component in column 0, row 3 position (index 3)
  640. * @param {Number} m10 Component in column 1, row 0 position (index 4)
  641. * @param {Number} m11 Component in column 1, row 1 position (index 5)
  642. * @param {Number} m12 Component in column 1, row 2 position (index 6)
  643. * @param {Number} m13 Component in column 1, row 3 position (index 7)
  644. * @param {Number} m20 Component in column 2, row 0 position (index 8)
  645. * @param {Number} m21 Component in column 2, row 1 position (index 9)
  646. * @param {Number} m22 Component in column 2, row 2 position (index 10)
  647. * @param {Number} m23 Component in column 2, row 3 position (index 11)
  648. * @param {Number} m30 Component in column 3, row 0 position (index 12)
  649. * @param {Number} m31 Component in column 3, row 1 position (index 13)
  650. * @param {Number} m32 Component in column 3, row 2 position (index 14)
  651. * @param {Number} m33 Component in column 3, row 3 position (index 15)
  652. * @returns {mat4} A new mat4
  653. */
  654. function fromValues$1(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  655. var out = new ARRAY_TYPE(16);
  656. out[0] = m00;
  657. out[1] = m01;
  658. out[2] = m02;
  659. out[3] = m03;
  660. out[4] = m10;
  661. out[5] = m11;
  662. out[6] = m12;
  663. out[7] = m13;
  664. out[8] = m20;
  665. out[9] = m21;
  666. out[10] = m22;
  667. out[11] = m23;
  668. out[12] = m30;
  669. out[13] = m31;
  670. out[14] = m32;
  671. out[15] = m33;
  672. return out;
  673. }
  674. /**
  675. * Set the components of a mat4 to the given values
  676. *
  677. * @param {mat4} out the receiving matrix
  678. * @param {Number} m00 Component in column 0, row 0 position (index 0)
  679. * @param {Number} m01 Component in column 0, row 1 position (index 1)
  680. * @param {Number} m02 Component in column 0, row 2 position (index 2)
  681. * @param {Number} m03 Component in column 0, row 3 position (index 3)
  682. * @param {Number} m10 Component in column 1, row 0 position (index 4)
  683. * @param {Number} m11 Component in column 1, row 1 position (index 5)
  684. * @param {Number} m12 Component in column 1, row 2 position (index 6)
  685. * @param {Number} m13 Component in column 1, row 3 position (index 7)
  686. * @param {Number} m20 Component in column 2, row 0 position (index 8)
  687. * @param {Number} m21 Component in column 2, row 1 position (index 9)
  688. * @param {Number} m22 Component in column 2, row 2 position (index 10)
  689. * @param {Number} m23 Component in column 2, row 3 position (index 11)
  690. * @param {Number} m30 Component in column 3, row 0 position (index 12)
  691. * @param {Number} m31 Component in column 3, row 1 position (index 13)
  692. * @param {Number} m32 Component in column 3, row 2 position (index 14)
  693. * @param {Number} m33 Component in column 3, row 3 position (index 15)
  694. * @returns {mat4} out
  695. */
  696. function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
  697. out[0] = m00;
  698. out[1] = m01;
  699. out[2] = m02;
  700. out[3] = m03;
  701. out[4] = m10;
  702. out[5] = m11;
  703. out[6] = m12;
  704. out[7] = m13;
  705. out[8] = m20;
  706. out[9] = m21;
  707. out[10] = m22;
  708. out[11] = m23;
  709. out[12] = m30;
  710. out[13] = m31;
  711. out[14] = m32;
  712. out[15] = m33;
  713. return out;
  714. }
  715. /**
  716. * Set a mat4 to the identity matrix
  717. *
  718. * @param {mat4} out the receiving matrix
  719. * @returns {mat4} out
  720. */
  721. function identity(out) {
  722. out[0] = 1;
  723. out[1] = 0;
  724. out[2] = 0;
  725. out[3] = 0;
  726. out[4] = 0;
  727. out[5] = 1;
  728. out[6] = 0;
  729. out[7] = 0;
  730. out[8] = 0;
  731. out[9] = 0;
  732. out[10] = 1;
  733. out[11] = 0;
  734. out[12] = 0;
  735. out[13] = 0;
  736. out[14] = 0;
  737. out[15] = 1;
  738. return out;
  739. }
  740. /**
  741. * Transpose the values of a mat4
  742. *
  743. * @param {mat4} out the receiving matrix
  744. * @param {ReadonlyMat4} a the source matrix
  745. * @returns {mat4} out
  746. */
  747. function transpose(out, a) {
  748. // If we are transposing ourselves we can skip a few steps but have to cache some values
  749. if (out === a) {
  750. var a01 = a[1],
  751. a02 = a[2],
  752. a03 = a[3];
  753. var a12 = a[6],
  754. a13 = a[7];
  755. var a23 = a[11];
  756. out[1] = a[4];
  757. out[2] = a[8];
  758. out[3] = a[12];
  759. out[4] = a01;
  760. out[6] = a[9];
  761. out[7] = a[13];
  762. out[8] = a02;
  763. out[9] = a12;
  764. out[11] = a[14];
  765. out[12] = a03;
  766. out[13] = a13;
  767. out[14] = a23;
  768. } else {
  769. out[0] = a[0];
  770. out[1] = a[4];
  771. out[2] = a[8];
  772. out[3] = a[12];
  773. out[4] = a[1];
  774. out[5] = a[5];
  775. out[6] = a[9];
  776. out[7] = a[13];
  777. out[8] = a[2];
  778. out[9] = a[6];
  779. out[10] = a[10];
  780. out[11] = a[14];
  781. out[12] = a[3];
  782. out[13] = a[7];
  783. out[14] = a[11];
  784. out[15] = a[15];
  785. }
  786. return out;
  787. }
  788. /**
  789. * Inverts a mat4
  790. *
  791. * @param {mat4} out the receiving matrix
  792. * @param {ReadonlyMat4} a the source matrix
  793. * @returns {mat4} out
  794. */
  795. function invert(out, a) {
  796. var a00 = a[0],
  797. a01 = a[1],
  798. a02 = a[2],
  799. a03 = a[3];
  800. var a10 = a[4],
  801. a11 = a[5],
  802. a12 = a[6],
  803. a13 = a[7];
  804. var a20 = a[8],
  805. a21 = a[9],
  806. a22 = a[10],
  807. a23 = a[11];
  808. var a30 = a[12],
  809. a31 = a[13],
  810. a32 = a[14],
  811. a33 = a[15];
  812. var b00 = a00 * a11 - a01 * a10;
  813. var b01 = a00 * a12 - a02 * a10;
  814. var b02 = a00 * a13 - a03 * a10;
  815. var b03 = a01 * a12 - a02 * a11;
  816. var b04 = a01 * a13 - a03 * a11;
  817. var b05 = a02 * a13 - a03 * a12;
  818. var b06 = a20 * a31 - a21 * a30;
  819. var b07 = a20 * a32 - a22 * a30;
  820. var b08 = a20 * a33 - a23 * a30;
  821. var b09 = a21 * a32 - a22 * a31;
  822. var b10 = a21 * a33 - a23 * a31;
  823. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  824. var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  825. if (!det) {
  826. return null;
  827. }
  828. det = 1.0 / det;
  829. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  830. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  831. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  832. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  833. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  834. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  835. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  836. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  837. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  838. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  839. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  840. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  841. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  842. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  843. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  844. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  845. return out;
  846. }
  847. /**
  848. * Calculates the adjugate of a mat4
  849. *
  850. * @param {mat4} out the receiving matrix
  851. * @param {ReadonlyMat4} a the source matrix
  852. * @returns {mat4} out
  853. */
  854. function adjoint(out, a) {
  855. var a00 = a[0],
  856. a01 = a[1],
  857. a02 = a[2],
  858. a03 = a[3];
  859. var a10 = a[4],
  860. a11 = a[5],
  861. a12 = a[6],
  862. a13 = a[7];
  863. var a20 = a[8],
  864. a21 = a[9],
  865. a22 = a[10],
  866. a23 = a[11];
  867. var a30 = a[12],
  868. a31 = a[13],
  869. a32 = a[14],
  870. a33 = a[15];
  871. out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);
  872. out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));
  873. out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);
  874. out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));
  875. out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));
  876. out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);
  877. out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));
  878. out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);
  879. out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);
  880. out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));
  881. out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);
  882. out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));
  883. out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));
  884. out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);
  885. out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));
  886. out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);
  887. return out;
  888. }
  889. /**
  890. * Calculates the determinant of a mat4
  891. *
  892. * @param {ReadonlyMat4} a the source matrix
  893. * @returns {Number} determinant of a
  894. */
  895. function determinant(a) {
  896. var a00 = a[0],
  897. a01 = a[1],
  898. a02 = a[2],
  899. a03 = a[3];
  900. var a10 = a[4],
  901. a11 = a[5],
  902. a12 = a[6],
  903. a13 = a[7];
  904. var a20 = a[8],
  905. a21 = a[9],
  906. a22 = a[10],
  907. a23 = a[11];
  908. var a30 = a[12],
  909. a31 = a[13],
  910. a32 = a[14],
  911. a33 = a[15];
  912. var b00 = a00 * a11 - a01 * a10;
  913. var b01 = a00 * a12 - a02 * a10;
  914. var b02 = a00 * a13 - a03 * a10;
  915. var b03 = a01 * a12 - a02 * a11;
  916. var b04 = a01 * a13 - a03 * a11;
  917. var b05 = a02 * a13 - a03 * a12;
  918. var b06 = a20 * a31 - a21 * a30;
  919. var b07 = a20 * a32 - a22 * a30;
  920. var b08 = a20 * a33 - a23 * a30;
  921. var b09 = a21 * a32 - a22 * a31;
  922. var b10 = a21 * a33 - a23 * a31;
  923. var b11 = a22 * a33 - a23 * a32; // Calculate the determinant
  924. return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  925. }
  926. /**
  927. * Multiplies two mat4s
  928. *
  929. * @param {mat4} out the receiving matrix
  930. * @param {ReadonlyMat4} a the first operand
  931. * @param {ReadonlyMat4} b the second operand
  932. * @returns {mat4} out
  933. */
  934. function multiply(out, a, b) {
  935. var a00 = a[0],
  936. a01 = a[1],
  937. a02 = a[2],
  938. a03 = a[3];
  939. var a10 = a[4],
  940. a11 = a[5],
  941. a12 = a[6],
  942. a13 = a[7];
  943. var a20 = a[8],
  944. a21 = a[9],
  945. a22 = a[10],
  946. a23 = a[11];
  947. var a30 = a[12],
  948. a31 = a[13],
  949. a32 = a[14],
  950. a33 = a[15]; // Cache only the current line of the second matrix
  951. var b0 = b[0],
  952. b1 = b[1],
  953. b2 = b[2],
  954. b3 = b[3];
  955. out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  956. out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  957. out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  958. out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  959. b0 = b[4];
  960. b1 = b[5];
  961. b2 = b[6];
  962. b3 = b[7];
  963. out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  964. out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  965. out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  966. out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  967. b0 = b[8];
  968. b1 = b[9];
  969. b2 = b[10];
  970. b3 = b[11];
  971. out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  972. out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  973. out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  974. out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  975. b0 = b[12];
  976. b1 = b[13];
  977. b2 = b[14];
  978. b3 = b[15];
  979. out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
  980. out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
  981. out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
  982. out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
  983. return out;
  984. }
  985. /**
  986. * Translate a mat4 by the given vector
  987. *
  988. * @param {mat4} out the receiving matrix
  989. * @param {ReadonlyMat4} a the matrix to translate
  990. * @param {ReadonlyVec3} v vector to translate by
  991. * @returns {mat4} out
  992. */
  993. function translate(out, a, v) {
  994. var x = v[0],
  995. y = v[1],
  996. z = v[2];
  997. var a00, a01, a02, a03;
  998. var a10, a11, a12, a13;
  999. var a20, a21, a22, a23;
  1000. if (a === out) {
  1001. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  1002. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  1003. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  1004. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  1005. } else {
  1006. a00 = a[0];
  1007. a01 = a[1];
  1008. a02 = a[2];
  1009. a03 = a[3];
  1010. a10 = a[4];
  1011. a11 = a[5];
  1012. a12 = a[6];
  1013. a13 = a[7];
  1014. a20 = a[8];
  1015. a21 = a[9];
  1016. a22 = a[10];
  1017. a23 = a[11];
  1018. out[0] = a00;
  1019. out[1] = a01;
  1020. out[2] = a02;
  1021. out[3] = a03;
  1022. out[4] = a10;
  1023. out[5] = a11;
  1024. out[6] = a12;
  1025. out[7] = a13;
  1026. out[8] = a20;
  1027. out[9] = a21;
  1028. out[10] = a22;
  1029. out[11] = a23;
  1030. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  1031. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  1032. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  1033. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  1034. }
  1035. return out;
  1036. }
  1037. /**
  1038. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  1039. *
  1040. * @param {mat4} out the receiving matrix
  1041. * @param {ReadonlyMat4} a the matrix to scale
  1042. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  1043. * @returns {mat4} out
  1044. **/
  1045. function scale(out, a, v) {
  1046. var x = v[0],
  1047. y = v[1],
  1048. z = v[2];
  1049. out[0] = a[0] * x;
  1050. out[1] = a[1] * x;
  1051. out[2] = a[2] * x;
  1052. out[3] = a[3] * x;
  1053. out[4] = a[4] * y;
  1054. out[5] = a[5] * y;
  1055. out[6] = a[6] * y;
  1056. out[7] = a[7] * y;
  1057. out[8] = a[8] * z;
  1058. out[9] = a[9] * z;
  1059. out[10] = a[10] * z;
  1060. out[11] = a[11] * z;
  1061. out[12] = a[12];
  1062. out[13] = a[13];
  1063. out[14] = a[14];
  1064. out[15] = a[15];
  1065. return out;
  1066. }
  1067. /**
  1068. * Rotates a mat4 by the given angle around the given axis
  1069. *
  1070. * @param {mat4} out the receiving matrix
  1071. * @param {ReadonlyMat4} a the matrix to rotate
  1072. * @param {Number} rad the angle to rotate the matrix by
  1073. * @param {ReadonlyVec3} axis the axis to rotate around
  1074. * @returns {mat4} out
  1075. */
  1076. function rotate(out, a, rad, axis) {
  1077. var x = axis[0],
  1078. y = axis[1],
  1079. z = axis[2];
  1080. var len = Math.hypot(x, y, z);
  1081. var s, c, t;
  1082. var a00, a01, a02, a03;
  1083. var a10, a11, a12, a13;
  1084. var a20, a21, a22, a23;
  1085. var b00, b01, b02;
  1086. var b10, b11, b12;
  1087. var b20, b21, b22;
  1088. if (len < EPSILON) {
  1089. return null;
  1090. }
  1091. len = 1 / len;
  1092. x *= len;
  1093. y *= len;
  1094. z *= len;
  1095. s = Math.sin(rad);
  1096. c = Math.cos(rad);
  1097. t = 1 - c;
  1098. a00 = a[0];
  1099. a01 = a[1];
  1100. a02 = a[2];
  1101. a03 = a[3];
  1102. a10 = a[4];
  1103. a11 = a[5];
  1104. a12 = a[6];
  1105. a13 = a[7];
  1106. a20 = a[8];
  1107. a21 = a[9];
  1108. a22 = a[10];
  1109. a23 = a[11]; // Construct the elements of the rotation matrix
  1110. b00 = x * x * t + c;
  1111. b01 = y * x * t + z * s;
  1112. b02 = z * x * t - y * s;
  1113. b10 = x * y * t - z * s;
  1114. b11 = y * y * t + c;
  1115. b12 = z * y * t + x * s;
  1116. b20 = x * z * t + y * s;
  1117. b21 = y * z * t - x * s;
  1118. b22 = z * z * t + c; // Perform rotation-specific matrix multiplication
  1119. out[0] = a00 * b00 + a10 * b01 + a20 * b02;
  1120. out[1] = a01 * b00 + a11 * b01 + a21 * b02;
  1121. out[2] = a02 * b00 + a12 * b01 + a22 * b02;
  1122. out[3] = a03 * b00 + a13 * b01 + a23 * b02;
  1123. out[4] = a00 * b10 + a10 * b11 + a20 * b12;
  1124. out[5] = a01 * b10 + a11 * b11 + a21 * b12;
  1125. out[6] = a02 * b10 + a12 * b11 + a22 * b12;
  1126. out[7] = a03 * b10 + a13 * b11 + a23 * b12;
  1127. out[8] = a00 * b20 + a10 * b21 + a20 * b22;
  1128. out[9] = a01 * b20 + a11 * b21 + a21 * b22;
  1129. out[10] = a02 * b20 + a12 * b21 + a22 * b22;
  1130. out[11] = a03 * b20 + a13 * b21 + a23 * b22;
  1131. if (a !== out) {
  1132. // If the source and destination differ, copy the unchanged last row
  1133. out[12] = a[12];
  1134. out[13] = a[13];
  1135. out[14] = a[14];
  1136. out[15] = a[15];
  1137. }
  1138. return out;
  1139. }
  1140. /**
  1141. * Rotates a matrix by the given angle around the X axis
  1142. *
  1143. * @param {mat4} out the receiving matrix
  1144. * @param {ReadonlyMat4} a the matrix to rotate
  1145. * @param {Number} rad the angle to rotate the matrix by
  1146. * @returns {mat4} out
  1147. */
  1148. function rotateX(out, a, rad) {
  1149. var s = Math.sin(rad);
  1150. var c = Math.cos(rad);
  1151. var a10 = a[4];
  1152. var a11 = a[5];
  1153. var a12 = a[6];
  1154. var a13 = a[7];
  1155. var a20 = a[8];
  1156. var a21 = a[9];
  1157. var a22 = a[10];
  1158. var a23 = a[11];
  1159. if (a !== out) {
  1160. // If the source and destination differ, copy the unchanged rows
  1161. out[0] = a[0];
  1162. out[1] = a[1];
  1163. out[2] = a[2];
  1164. out[3] = a[3];
  1165. out[12] = a[12];
  1166. out[13] = a[13];
  1167. out[14] = a[14];
  1168. out[15] = a[15];
  1169. } // Perform axis-specific matrix multiplication
  1170. out[4] = a10 * c + a20 * s;
  1171. out[5] = a11 * c + a21 * s;
  1172. out[6] = a12 * c + a22 * s;
  1173. out[7] = a13 * c + a23 * s;
  1174. out[8] = a20 * c - a10 * s;
  1175. out[9] = a21 * c - a11 * s;
  1176. out[10] = a22 * c - a12 * s;
  1177. out[11] = a23 * c - a13 * s;
  1178. return out;
  1179. }
  1180. /**
  1181. * Rotates a matrix by the given angle around the Y axis
  1182. *
  1183. * @param {mat4} out the receiving matrix
  1184. * @param {ReadonlyMat4} a the matrix to rotate
  1185. * @param {Number} rad the angle to rotate the matrix by
  1186. * @returns {mat4} out
  1187. */
  1188. function rotateY(out, a, rad) {
  1189. var s = Math.sin(rad);
  1190. var c = Math.cos(rad);
  1191. var a00 = a[0];
  1192. var a01 = a[1];
  1193. var a02 = a[2];
  1194. var a03 = a[3];
  1195. var a20 = a[8];
  1196. var a21 = a[9];
  1197. var a22 = a[10];
  1198. var a23 = a[11];
  1199. if (a !== out) {
  1200. // If the source and destination differ, copy the unchanged rows
  1201. out[4] = a[4];
  1202. out[5] = a[5];
  1203. out[6] = a[6];
  1204. out[7] = a[7];
  1205. out[12] = a[12];
  1206. out[13] = a[13];
  1207. out[14] = a[14];
  1208. out[15] = a[15];
  1209. } // Perform axis-specific matrix multiplication
  1210. out[0] = a00 * c - a20 * s;
  1211. out[1] = a01 * c - a21 * s;
  1212. out[2] = a02 * c - a22 * s;
  1213. out[3] = a03 * c - a23 * s;
  1214. out[8] = a00 * s + a20 * c;
  1215. out[9] = a01 * s + a21 * c;
  1216. out[10] = a02 * s + a22 * c;
  1217. out[11] = a03 * s + a23 * c;
  1218. return out;
  1219. }
  1220. /**
  1221. * Rotates a matrix by the given angle around the Z axis
  1222. *
  1223. * @param {mat4} out the receiving matrix
  1224. * @param {ReadonlyMat4} a the matrix to rotate
  1225. * @param {Number} rad the angle to rotate the matrix by
  1226. * @returns {mat4} out
  1227. */
  1228. function rotateZ(out, a, rad) {
  1229. var s = Math.sin(rad);
  1230. var c = Math.cos(rad);
  1231. var a00 = a[0];
  1232. var a01 = a[1];
  1233. var a02 = a[2];
  1234. var a03 = a[3];
  1235. var a10 = a[4];
  1236. var a11 = a[5];
  1237. var a12 = a[6];
  1238. var a13 = a[7];
  1239. if (a !== out) {
  1240. // If the source and destination differ, copy the unchanged last row
  1241. out[8] = a[8];
  1242. out[9] = a[9];
  1243. out[10] = a[10];
  1244. out[11] = a[11];
  1245. out[12] = a[12];
  1246. out[13] = a[13];
  1247. out[14] = a[14];
  1248. out[15] = a[15];
  1249. } // Perform axis-specific matrix multiplication
  1250. out[0] = a00 * c + a10 * s;
  1251. out[1] = a01 * c + a11 * s;
  1252. out[2] = a02 * c + a12 * s;
  1253. out[3] = a03 * c + a13 * s;
  1254. out[4] = a10 * c - a00 * s;
  1255. out[5] = a11 * c - a01 * s;
  1256. out[6] = a12 * c - a02 * s;
  1257. out[7] = a13 * c - a03 * s;
  1258. return out;
  1259. }
  1260. /**
  1261. * Creates a matrix from a vector translation
  1262. * This is equivalent to (but much faster than):
  1263. *
  1264. * mat4.identity(dest);
  1265. * mat4.translate(dest, dest, vec);
  1266. *
  1267. * @param {mat4} out mat4 receiving operation result
  1268. * @param {ReadonlyVec3} v Translation vector
  1269. * @returns {mat4} out
  1270. */
  1271. function fromTranslation(out, v) {
  1272. out[0] = 1;
  1273. out[1] = 0;
  1274. out[2] = 0;
  1275. out[3] = 0;
  1276. out[4] = 0;
  1277. out[5] = 1;
  1278. out[6] = 0;
  1279. out[7] = 0;
  1280. out[8] = 0;
  1281. out[9] = 0;
  1282. out[10] = 1;
  1283. out[11] = 0;
  1284. out[12] = v[0];
  1285. out[13] = v[1];
  1286. out[14] = v[2];
  1287. out[15] = 1;
  1288. return out;
  1289. }
  1290. /**
  1291. * Creates a matrix from a vector scaling
  1292. * This is equivalent to (but much faster than):
  1293. *
  1294. * mat4.identity(dest);
  1295. * mat4.scale(dest, dest, vec);
  1296. *
  1297. * @param {mat4} out mat4 receiving operation result
  1298. * @param {ReadonlyVec3} v Scaling vector
  1299. * @returns {mat4} out
  1300. */
  1301. function fromScaling(out, v) {
  1302. out[0] = v[0];
  1303. out[1] = 0;
  1304. out[2] = 0;
  1305. out[3] = 0;
  1306. out[4] = 0;
  1307. out[5] = v[1];
  1308. out[6] = 0;
  1309. out[7] = 0;
  1310. out[8] = 0;
  1311. out[9] = 0;
  1312. out[10] = v[2];
  1313. out[11] = 0;
  1314. out[12] = 0;
  1315. out[13] = 0;
  1316. out[14] = 0;
  1317. out[15] = 1;
  1318. return out;
  1319. }
  1320. /**
  1321. * Creates a matrix from a given angle around a given axis
  1322. * This is equivalent to (but much faster than):
  1323. *
  1324. * mat4.identity(dest);
  1325. * mat4.rotate(dest, dest, rad, axis);
  1326. *
  1327. * @param {mat4} out mat4 receiving operation result
  1328. * @param {Number} rad the angle to rotate the matrix by
  1329. * @param {ReadonlyVec3} axis the axis to rotate around
  1330. * @returns {mat4} out
  1331. */
  1332. function fromRotation(out, rad, axis) {
  1333. var x = axis[0],
  1334. y = axis[1],
  1335. z = axis[2];
  1336. var len = Math.hypot(x, y, z);
  1337. var s, c, t;
  1338. if (len < EPSILON) {
  1339. return null;
  1340. }
  1341. len = 1 / len;
  1342. x *= len;
  1343. y *= len;
  1344. z *= len;
  1345. s = Math.sin(rad);
  1346. c = Math.cos(rad);
  1347. t = 1 - c; // Perform rotation-specific matrix multiplication
  1348. out[0] = x * x * t + c;
  1349. out[1] = y * x * t + z * s;
  1350. out[2] = z * x * t - y * s;
  1351. out[3] = 0;
  1352. out[4] = x * y * t - z * s;
  1353. out[5] = y * y * t + c;
  1354. out[6] = z * y * t + x * s;
  1355. out[7] = 0;
  1356. out[8] = x * z * t + y * s;
  1357. out[9] = y * z * t - x * s;
  1358. out[10] = z * z * t + c;
  1359. out[11] = 0;
  1360. out[12] = 0;
  1361. out[13] = 0;
  1362. out[14] = 0;
  1363. out[15] = 1;
  1364. return out;
  1365. }
  1366. /**
  1367. * Creates a matrix from the given angle around the X axis
  1368. * This is equivalent to (but much faster than):
  1369. *
  1370. * mat4.identity(dest);
  1371. * mat4.rotateX(dest, dest, rad);
  1372. *
  1373. * @param {mat4} out mat4 receiving operation result
  1374. * @param {Number} rad the angle to rotate the matrix by
  1375. * @returns {mat4} out
  1376. */
  1377. function fromXRotation(out, rad) {
  1378. var s = Math.sin(rad);
  1379. var c = Math.cos(rad); // Perform axis-specific matrix multiplication
  1380. out[0] = 1;
  1381. out[1] = 0;
  1382. out[2] = 0;
  1383. out[3] = 0;
  1384. out[4] = 0;
  1385. out[5] = c;
  1386. out[6] = s;
  1387. out[7] = 0;
  1388. out[8] = 0;
  1389. out[9] = -s;
  1390. out[10] = c;
  1391. out[11] = 0;
  1392. out[12] = 0;
  1393. out[13] = 0;
  1394. out[14] = 0;
  1395. out[15] = 1;
  1396. return out;
  1397. }
  1398. /**
  1399. * Creates a matrix from the given angle around the Y axis
  1400. * This is equivalent to (but much faster than):
  1401. *
  1402. * mat4.identity(dest);
  1403. * mat4.rotateY(dest, dest, rad);
  1404. *
  1405. * @param {mat4} out mat4 receiving operation result
  1406. * @param {Number} rad the angle to rotate the matrix by
  1407. * @returns {mat4} out
  1408. */
  1409. function fromYRotation(out, rad) {
  1410. var s = Math.sin(rad);
  1411. var c = Math.cos(rad); // Perform axis-specific matrix multiplication
  1412. out[0] = c;
  1413. out[1] = 0;
  1414. out[2] = -s;
  1415. out[3] = 0;
  1416. out[4] = 0;
  1417. out[5] = 1;
  1418. out[6] = 0;
  1419. out[7] = 0;
  1420. out[8] = s;
  1421. out[9] = 0;
  1422. out[10] = c;
  1423. out[11] = 0;
  1424. out[12] = 0;
  1425. out[13] = 0;
  1426. out[14] = 0;
  1427. out[15] = 1;
  1428. return out;
  1429. }
  1430. /**
  1431. * Creates a matrix from the given angle around the Z axis
  1432. * This is equivalent to (but much faster than):
  1433. *
  1434. * mat4.identity(dest);
  1435. * mat4.rotateZ(dest, dest, rad);
  1436. *
  1437. * @param {mat4} out mat4 receiving operation result
  1438. * @param {Number} rad the angle to rotate the matrix by
  1439. * @returns {mat4} out
  1440. */
  1441. function fromZRotation(out, rad) {
  1442. var s = Math.sin(rad);
  1443. var c = Math.cos(rad); // Perform axis-specific matrix multiplication
  1444. out[0] = c;
  1445. out[1] = s;
  1446. out[2] = 0;
  1447. out[3] = 0;
  1448. out[4] = -s;
  1449. out[5] = c;
  1450. out[6] = 0;
  1451. out[7] = 0;
  1452. out[8] = 0;
  1453. out[9] = 0;
  1454. out[10] = 1;
  1455. out[11] = 0;
  1456. out[12] = 0;
  1457. out[13] = 0;
  1458. out[14] = 0;
  1459. out[15] = 1;
  1460. return out;
  1461. }
  1462. /**
  1463. * Creates a matrix from a quaternion rotation and vector translation
  1464. * This is equivalent to (but much faster than):
  1465. *
  1466. * mat4.identity(dest);
  1467. * mat4.translate(dest, vec);
  1468. * let quatMat = mat4.create();
  1469. * quat4.toMat4(quat, quatMat);
  1470. * mat4.multiply(dest, quatMat);
  1471. *
  1472. * @param {mat4} out mat4 receiving operation result
  1473. * @param {quat4} q Rotation quaternion
  1474. * @param {ReadonlyVec3} v Translation vector
  1475. * @returns {mat4} out
  1476. */
  1477. function fromRotationTranslation(out, q, v) {
  1478. // Quaternion math
  1479. var x = q[0],
  1480. y = q[1],
  1481. z = q[2],
  1482. w = q[3];
  1483. var x2 = x + x;
  1484. var y2 = y + y;
  1485. var z2 = z + z;
  1486. var xx = x * x2;
  1487. var xy = x * y2;
  1488. var xz = x * z2;
  1489. var yy = y * y2;
  1490. var yz = y * z2;
  1491. var zz = z * z2;
  1492. var wx = w * x2;
  1493. var wy = w * y2;
  1494. var wz = w * z2;
  1495. out[0] = 1 - (yy + zz);
  1496. out[1] = xy + wz;
  1497. out[2] = xz - wy;
  1498. out[3] = 0;
  1499. out[4] = xy - wz;
  1500. out[5] = 1 - (xx + zz);
  1501. out[6] = yz + wx;
  1502. out[7] = 0;
  1503. out[8] = xz + wy;
  1504. out[9] = yz - wx;
  1505. out[10] = 1 - (xx + yy);
  1506. out[11] = 0;
  1507. out[12] = v[0];
  1508. out[13] = v[1];
  1509. out[14] = v[2];
  1510. out[15] = 1;
  1511. return out;
  1512. }
  1513. /**
  1514. * Creates a new mat4 from a dual quat.
  1515. *
  1516. * @param {mat4} out Matrix
  1517. * @param {ReadonlyQuat2} a Dual Quaternion
  1518. * @returns {mat4} mat4 receiving operation result
  1519. */
  1520. function fromQuat2(out, a) {
  1521. var translation = new ARRAY_TYPE(3);
  1522. var bx = -a[0],
  1523. by = -a[1],
  1524. bz = -a[2],
  1525. bw = a[3],
  1526. ax = a[4],
  1527. ay = a[5],
  1528. az = a[6],
  1529. aw = a[7];
  1530. var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense
  1531. if (magnitude > 0) {
  1532. translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;
  1533. translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;
  1534. translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;
  1535. } else {
  1536. translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;
  1537. translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;
  1538. translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;
  1539. }
  1540. fromRotationTranslation(out, a, translation);
  1541. return out;
  1542. }
  1543. /**
  1544. * Returns the translation vector component of a transformation
  1545. * matrix. If a matrix is built with fromRotationTranslation,
  1546. * the returned vector will be the same as the translation vector
  1547. * originally supplied.
  1548. * @param {vec3} out Vector to receive translation component
  1549. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  1550. * @return {vec3} out
  1551. */
  1552. function getTranslation(out, mat) {
  1553. out[0] = mat[12];
  1554. out[1] = mat[13];
  1555. out[2] = mat[14];
  1556. return out;
  1557. }
  1558. /**
  1559. * Returns the scaling factor component of a transformation
  1560. * matrix. If a matrix is built with fromRotationTranslationScale
  1561. * with a normalized Quaternion paramter, the returned vector will be
  1562. * the same as the scaling vector
  1563. * originally supplied.
  1564. * @param {vec3} out Vector to receive scaling factor component
  1565. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  1566. * @return {vec3} out
  1567. */
  1568. function getScaling(out, mat) {
  1569. var m11 = mat[0];
  1570. var m12 = mat[1];
  1571. var m13 = mat[2];
  1572. var m21 = mat[4];
  1573. var m22 = mat[5];
  1574. var m23 = mat[6];
  1575. var m31 = mat[8];
  1576. var m32 = mat[9];
  1577. var m33 = mat[10];
  1578. out[0] = Math.hypot(m11, m12, m13);
  1579. out[1] = Math.hypot(m21, m22, m23);
  1580. out[2] = Math.hypot(m31, m32, m33);
  1581. return out;
  1582. }
  1583. /**
  1584. * Returns a quaternion representing the rotational component
  1585. * of a transformation matrix. If a matrix is built with
  1586. * fromRotationTranslation, the returned quaternion will be the
  1587. * same as the quaternion originally supplied.
  1588. * @param {quat} out Quaternion to receive the rotation component
  1589. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  1590. * @return {quat} out
  1591. */
  1592. function getRotation(out, mat) {
  1593. var scaling = new ARRAY_TYPE(3);
  1594. getScaling(scaling, mat);
  1595. var is1 = 1 / scaling[0];
  1596. var is2 = 1 / scaling[1];
  1597. var is3 = 1 / scaling[2];
  1598. var sm11 = mat[0] * is1;
  1599. var sm12 = mat[1] * is2;
  1600. var sm13 = mat[2] * is3;
  1601. var sm21 = mat[4] * is1;
  1602. var sm22 = mat[5] * is2;
  1603. var sm23 = mat[6] * is3;
  1604. var sm31 = mat[8] * is1;
  1605. var sm32 = mat[9] * is2;
  1606. var sm33 = mat[10] * is3;
  1607. var trace = sm11 + sm22 + sm33;
  1608. var S = 0;
  1609. if (trace > 0) {
  1610. S = Math.sqrt(trace + 1.0) * 2;
  1611. out[3] = 0.25 * S;
  1612. out[0] = (sm23 - sm32) / S;
  1613. out[1] = (sm31 - sm13) / S;
  1614. out[2] = (sm12 - sm21) / S;
  1615. } else if (sm11 > sm22 && sm11 > sm33) {
  1616. S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;
  1617. out[3] = (sm23 - sm32) / S;
  1618. out[0] = 0.25 * S;
  1619. out[1] = (sm12 + sm21) / S;
  1620. out[2] = (sm31 + sm13) / S;
  1621. } else if (sm22 > sm33) {
  1622. S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;
  1623. out[3] = (sm31 - sm13) / S;
  1624. out[0] = (sm12 + sm21) / S;
  1625. out[1] = 0.25 * S;
  1626. out[2] = (sm23 + sm32) / S;
  1627. } else {
  1628. S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;
  1629. out[3] = (sm12 - sm21) / S;
  1630. out[0] = (sm31 + sm13) / S;
  1631. out[1] = (sm23 + sm32) / S;
  1632. out[2] = 0.25 * S;
  1633. }
  1634. return out;
  1635. }
  1636. /**
  1637. * Creates a matrix from a quaternion rotation, vector translation and vector scale
  1638. * This is equivalent to (but much faster than):
  1639. *
  1640. * mat4.identity(dest);
  1641. * mat4.translate(dest, vec);
  1642. * let quatMat = mat4.create();
  1643. * quat4.toMat4(quat, quatMat);
  1644. * mat4.multiply(dest, quatMat);
  1645. * mat4.scale(dest, scale)
  1646. *
  1647. * @param {mat4} out mat4 receiving operation result
  1648. * @param {quat4} q Rotation quaternion
  1649. * @param {ReadonlyVec3} v Translation vector
  1650. * @param {ReadonlyVec3} s Scaling vector
  1651. * @returns {mat4} out
  1652. */
  1653. function fromRotationTranslationScale(out, q, v, s) {
  1654. // Quaternion math
  1655. var x = q[0],
  1656. y = q[1],
  1657. z = q[2],
  1658. w = q[3];
  1659. var x2 = x + x;
  1660. var y2 = y + y;
  1661. var z2 = z + z;
  1662. var xx = x * x2;
  1663. var xy = x * y2;
  1664. var xz = x * z2;
  1665. var yy = y * y2;
  1666. var yz = y * z2;
  1667. var zz = z * z2;
  1668. var wx = w * x2;
  1669. var wy = w * y2;
  1670. var wz = w * z2;
  1671. var sx = s[0];
  1672. var sy = s[1];
  1673. var sz = s[2];
  1674. out[0] = (1 - (yy + zz)) * sx;
  1675. out[1] = (xy + wz) * sx;
  1676. out[2] = (xz - wy) * sx;
  1677. out[3] = 0;
  1678. out[4] = (xy - wz) * sy;
  1679. out[5] = (1 - (xx + zz)) * sy;
  1680. out[6] = (yz + wx) * sy;
  1681. out[7] = 0;
  1682. out[8] = (xz + wy) * sz;
  1683. out[9] = (yz - wx) * sz;
  1684. out[10] = (1 - (xx + yy)) * sz;
  1685. out[11] = 0;
  1686. out[12] = v[0];
  1687. out[13] = v[1];
  1688. out[14] = v[2];
  1689. out[15] = 1;
  1690. return out;
  1691. }
  1692. /**
  1693. * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin
  1694. * This is equivalent to (but much faster than):
  1695. *
  1696. * mat4.identity(dest);
  1697. * mat4.translate(dest, vec);
  1698. * mat4.translate(dest, origin);
  1699. * let quatMat = mat4.create();
  1700. * quat4.toMat4(quat, quatMat);
  1701. * mat4.multiply(dest, quatMat);
  1702. * mat4.scale(dest, scale)
  1703. * mat4.translate(dest, negativeOrigin);
  1704. *
  1705. * @param {mat4} out mat4 receiving operation result
  1706. * @param {quat4} q Rotation quaternion
  1707. * @param {ReadonlyVec3} v Translation vector
  1708. * @param {ReadonlyVec3} s Scaling vector
  1709. * @param {ReadonlyVec3} o The origin vector around which to scale and rotate
  1710. * @returns {mat4} out
  1711. */
  1712. function fromRotationTranslationScaleOrigin(out, q, v, s, o) {
  1713. // Quaternion math
  1714. var x = q[0],
  1715. y = q[1],
  1716. z = q[2],
  1717. w = q[3];
  1718. var x2 = x + x;
  1719. var y2 = y + y;
  1720. var z2 = z + z;
  1721. var xx = x * x2;
  1722. var xy = x * y2;
  1723. var xz = x * z2;
  1724. var yy = y * y2;
  1725. var yz = y * z2;
  1726. var zz = z * z2;
  1727. var wx = w * x2;
  1728. var wy = w * y2;
  1729. var wz = w * z2;
  1730. var sx = s[0];
  1731. var sy = s[1];
  1732. var sz = s[2];
  1733. var ox = o[0];
  1734. var oy = o[1];
  1735. var oz = o[2];
  1736. var out0 = (1 - (yy + zz)) * sx;
  1737. var out1 = (xy + wz) * sx;
  1738. var out2 = (xz - wy) * sx;
  1739. var out4 = (xy - wz) * sy;
  1740. var out5 = (1 - (xx + zz)) * sy;
  1741. var out6 = (yz + wx) * sy;
  1742. var out8 = (xz + wy) * sz;
  1743. var out9 = (yz - wx) * sz;
  1744. var out10 = (1 - (xx + yy)) * sz;
  1745. out[0] = out0;
  1746. out[1] = out1;
  1747. out[2] = out2;
  1748. out[3] = 0;
  1749. out[4] = out4;
  1750. out[5] = out5;
  1751. out[6] = out6;
  1752. out[7] = 0;
  1753. out[8] = out8;
  1754. out[9] = out9;
  1755. out[10] = out10;
  1756. out[11] = 0;
  1757. out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);
  1758. out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);
  1759. out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);
  1760. out[15] = 1;
  1761. return out;
  1762. }
  1763. /**
  1764. * Calculates a 4x4 matrix from the given quaternion
  1765. *
  1766. * @param {mat4} out mat4 receiving operation result
  1767. * @param {ReadonlyQuat} q Quaternion to create matrix from
  1768. *
  1769. * @returns {mat4} out
  1770. */
  1771. function fromQuat(out, q) {
  1772. var x = q[0],
  1773. y = q[1],
  1774. z = q[2],
  1775. w = q[3];
  1776. var x2 = x + x;
  1777. var y2 = y + y;
  1778. var z2 = z + z;
  1779. var xx = x * x2;
  1780. var yx = y * x2;
  1781. var yy = y * y2;
  1782. var zx = z * x2;
  1783. var zy = z * y2;
  1784. var zz = z * z2;
  1785. var wx = w * x2;
  1786. var wy = w * y2;
  1787. var wz = w * z2;
  1788. out[0] = 1 - yy - zz;
  1789. out[1] = yx + wz;
  1790. out[2] = zx - wy;
  1791. out[3] = 0;
  1792. out[4] = yx - wz;
  1793. out[5] = 1 - xx - zz;
  1794. out[6] = zy + wx;
  1795. out[7] = 0;
  1796. out[8] = zx + wy;
  1797. out[9] = zy - wx;
  1798. out[10] = 1 - xx - yy;
  1799. out[11] = 0;
  1800. out[12] = 0;
  1801. out[13] = 0;
  1802. out[14] = 0;
  1803. out[15] = 1;
  1804. return out;
  1805. }
  1806. /**
  1807. * Generates a frustum matrix with the given bounds
  1808. *
  1809. * @param {mat4} out mat4 frustum matrix will be written into
  1810. * @param {Number} left Left bound of the frustum
  1811. * @param {Number} right Right bound of the frustum
  1812. * @param {Number} bottom Bottom bound of the frustum
  1813. * @param {Number} top Top bound of the frustum
  1814. * @param {Number} near Near bound of the frustum
  1815. * @param {Number} far Far bound of the frustum
  1816. * @returns {mat4} out
  1817. */
  1818. function frustum(out, left, right, bottom, top, near, far) {
  1819. var rl = 1 / (right - left);
  1820. var tb = 1 / (top - bottom);
  1821. var nf = 1 / (near - far);
  1822. out[0] = near * 2 * rl;
  1823. out[1] = 0;
  1824. out[2] = 0;
  1825. out[3] = 0;
  1826. out[4] = 0;
  1827. out[5] = near * 2 * tb;
  1828. out[6] = 0;
  1829. out[7] = 0;
  1830. out[8] = (right + left) * rl;
  1831. out[9] = (top + bottom) * tb;
  1832. out[10] = (far + near) * nf;
  1833. out[11] = -1;
  1834. out[12] = 0;
  1835. out[13] = 0;
  1836. out[14] = far * near * 2 * nf;
  1837. out[15] = 0;
  1838. return out;
  1839. }
  1840. /**
  1841. * Generates a perspective projection matrix with the given bounds.
  1842. * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
  1843. * which matches WebGL/OpenGL's clip volume.
  1844. * Passing null/undefined/no value for far will generate infinite projection matrix.
  1845. *
  1846. * @param {mat4} out mat4 frustum matrix will be written into
  1847. * @param {number} fovy Vertical field of view in radians
  1848. * @param {number} aspect Aspect ratio. typically viewport width/height
  1849. * @param {number} near Near bound of the frustum
  1850. * @param {number} far Far bound of the frustum, can be null or Infinity
  1851. * @returns {mat4} out
  1852. */
  1853. function perspectiveNO(out, fovy, aspect, near, far) {
  1854. var f = 1.0 / Math.tan(fovy / 2),
  1855. nf;
  1856. out[0] = f / aspect;
  1857. out[1] = 0;
  1858. out[2] = 0;
  1859. out[3] = 0;
  1860. out[4] = 0;
  1861. out[5] = f;
  1862. out[6] = 0;
  1863. out[7] = 0;
  1864. out[8] = 0;
  1865. out[9] = 0;
  1866. out[11] = -1;
  1867. out[12] = 0;
  1868. out[13] = 0;
  1869. out[15] = 0;
  1870. if (far != null && far !== Infinity) {
  1871. nf = 1 / (near - far);
  1872. out[10] = (far + near) * nf;
  1873. out[14] = 2 * far * near * nf;
  1874. } else {
  1875. out[10] = -1;
  1876. out[14] = -2 * near;
  1877. }
  1878. return out;
  1879. }
  1880. /**
  1881. * Alias for {@link mat4.perspectiveNO}
  1882. * @function
  1883. */
  1884. var perspective = perspectiveNO;
  1885. /**
  1886. * Generates a perspective projection matrix suitable for WebGPU with the given bounds.
  1887. * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],
  1888. * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.
  1889. * Passing null/undefined/no value for far will generate infinite projection matrix.
  1890. *
  1891. * @param {mat4} out mat4 frustum matrix will be written into
  1892. * @param {number} fovy Vertical field of view in radians
  1893. * @param {number} aspect Aspect ratio. typically viewport width/height
  1894. * @param {number} near Near bound of the frustum
  1895. * @param {number} far Far bound of the frustum, can be null or Infinity
  1896. * @returns {mat4} out
  1897. */
  1898. function perspectiveZO(out, fovy, aspect, near, far) {
  1899. var f = 1.0 / Math.tan(fovy / 2),
  1900. nf;
  1901. out[0] = f / aspect;
  1902. out[1] = 0;
  1903. out[2] = 0;
  1904. out[3] = 0;
  1905. out[4] = 0;
  1906. out[5] = f;
  1907. out[6] = 0;
  1908. out[7] = 0;
  1909. out[8] = 0;
  1910. out[9] = 0;
  1911. out[11] = -1;
  1912. out[12] = 0;
  1913. out[13] = 0;
  1914. out[15] = 0;
  1915. if (far != null && far !== Infinity) {
  1916. nf = 1 / (near - far);
  1917. out[10] = far * nf;
  1918. out[14] = far * near * nf;
  1919. } else {
  1920. out[10] = -1;
  1921. out[14] = -near;
  1922. }
  1923. return out;
  1924. }
  1925. /**
  1926. * Generates a perspective projection matrix with the given field of view.
  1927. * This is primarily useful for generating projection matrices to be used
  1928. * with the still experiemental WebVR API.
  1929. *
  1930. * @param {mat4} out mat4 frustum matrix will be written into
  1931. * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees
  1932. * @param {number} near Near bound of the frustum
  1933. * @param {number} far Far bound of the frustum
  1934. * @returns {mat4} out
  1935. */
  1936. function perspectiveFromFieldOfView(out, fov, near, far) {
  1937. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  1938. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  1939. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  1940. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  1941. var xScale = 2.0 / (leftTan + rightTan);
  1942. var yScale = 2.0 / (upTan + downTan);
  1943. out[0] = xScale;
  1944. out[1] = 0.0;
  1945. out[2] = 0.0;
  1946. out[3] = 0.0;
  1947. out[4] = 0.0;
  1948. out[5] = yScale;
  1949. out[6] = 0.0;
  1950. out[7] = 0.0;
  1951. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  1952. out[9] = (upTan - downTan) * yScale * 0.5;
  1953. out[10] = far / (near - far);
  1954. out[11] = -1.0;
  1955. out[12] = 0.0;
  1956. out[13] = 0.0;
  1957. out[14] = far * near / (near - far);
  1958. out[15] = 0.0;
  1959. return out;
  1960. }
  1961. /**
  1962. * Generates a orthogonal projection matrix with the given bounds.
  1963. * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],
  1964. * which matches WebGL/OpenGL's clip volume.
  1965. *
  1966. * @param {mat4} out mat4 frustum matrix will be written into
  1967. * @param {number} left Left bound of the frustum
  1968. * @param {number} right Right bound of the frustum
  1969. * @param {number} bottom Bottom bound of the frustum
  1970. * @param {number} top Top bound of the frustum
  1971. * @param {number} near Near bound of the frustum
  1972. * @param {number} far Far bound of the frustum
  1973. * @returns {mat4} out
  1974. */
  1975. function orthoNO(out, left, right, bottom, top, near, far) {
  1976. var lr = 1 / (left - right);
  1977. var bt = 1 / (bottom - top);
  1978. var nf = 1 / (near - far);
  1979. out[0] = -2 * lr;
  1980. out[1] = 0;
  1981. out[2] = 0;
  1982. out[3] = 0;
  1983. out[4] = 0;
  1984. out[5] = -2 * bt;
  1985. out[6] = 0;
  1986. out[7] = 0;
  1987. out[8] = 0;
  1988. out[9] = 0;
  1989. out[10] = 2 * nf;
  1990. out[11] = 0;
  1991. out[12] = (left + right) * lr;
  1992. out[13] = (top + bottom) * bt;
  1993. out[14] = (far + near) * nf;
  1994. out[15] = 1;
  1995. return out;
  1996. }
  1997. /**
  1998. * Alias for {@link mat4.orthoNO}
  1999. * @function
  2000. */
  2001. var ortho = orthoNO;
  2002. /**
  2003. * Generates a orthogonal projection matrix with the given bounds.
  2004. * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],
  2005. * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.
  2006. *
  2007. * @param {mat4} out mat4 frustum matrix will be written into
  2008. * @param {number} left Left bound of the frustum
  2009. * @param {number} right Right bound of the frustum
  2010. * @param {number} bottom Bottom bound of the frustum
  2011. * @param {number} top Top bound of the frustum
  2012. * @param {number} near Near bound of the frustum
  2013. * @param {number} far Far bound of the frustum
  2014. * @returns {mat4} out
  2015. */
  2016. function orthoZO(out, left, right, bottom, top, near, far) {
  2017. var lr = 1 / (left - right);
  2018. var bt = 1 / (bottom - top);
  2019. var nf = 1 / (near - far);
  2020. out[0] = -2 * lr;
  2021. out[1] = 0;
  2022. out[2] = 0;
  2023. out[3] = 0;
  2024. out[4] = 0;
  2025. out[5] = -2 * bt;
  2026. out[6] = 0;
  2027. out[7] = 0;
  2028. out[8] = 0;
  2029. out[9] = 0;
  2030. out[10] = nf;
  2031. out[11] = 0;
  2032. out[12] = (left + right) * lr;
  2033. out[13] = (top + bottom) * bt;
  2034. out[14] = near * nf;
  2035. out[15] = 1;
  2036. return out;
  2037. }
  2038. /**
  2039. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  2040. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  2041. *
  2042. * @param {mat4} out mat4 frustum matrix will be written into
  2043. * @param {ReadonlyVec3} eye Position of the viewer
  2044. * @param {ReadonlyVec3} center Point the viewer is looking at
  2045. * @param {ReadonlyVec3} up vec3 pointing up
  2046. * @returns {mat4} out
  2047. */
  2048. function lookAt(out, eye, center, up) {
  2049. var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
  2050. var eyex = eye[0];
  2051. var eyey = eye[1];
  2052. var eyez = eye[2];
  2053. var upx = up[0];
  2054. var upy = up[1];
  2055. var upz = up[2];
  2056. var centerx = center[0];
  2057. var centery = center[1];
  2058. var centerz = center[2];
  2059. if (Math.abs(eyex - centerx) < EPSILON && Math.abs(eyey - centery) < EPSILON && Math.abs(eyez - centerz) < EPSILON) {
  2060. return identity(out);
  2061. }
  2062. z0 = eyex - centerx;
  2063. z1 = eyey - centery;
  2064. z2 = eyez - centerz;
  2065. len = 1 / Math.hypot(z0, z1, z2);
  2066. z0 *= len;
  2067. z1 *= len;
  2068. z2 *= len;
  2069. x0 = upy * z2 - upz * z1;
  2070. x1 = upz * z0 - upx * z2;
  2071. x2 = upx * z1 - upy * z0;
  2072. len = Math.hypot(x0, x1, x2);
  2073. if (!len) {
  2074. x0 = 0;
  2075. x1 = 0;
  2076. x2 = 0;
  2077. } else {
  2078. len = 1 / len;
  2079. x0 *= len;
  2080. x1 *= len;
  2081. x2 *= len;
  2082. }
  2083. y0 = z1 * x2 - z2 * x1;
  2084. y1 = z2 * x0 - z0 * x2;
  2085. y2 = z0 * x1 - z1 * x0;
  2086. len = Math.hypot(y0, y1, y2);
  2087. if (!len) {
  2088. y0 = 0;
  2089. y1 = 0;
  2090. y2 = 0;
  2091. } else {
  2092. len = 1 / len;
  2093. y0 *= len;
  2094. y1 *= len;
  2095. y2 *= len;
  2096. }
  2097. out[0] = x0;
  2098. out[1] = y0;
  2099. out[2] = z0;
  2100. out[3] = 0;
  2101. out[4] = x1;
  2102. out[5] = y1;
  2103. out[6] = z1;
  2104. out[7] = 0;
  2105. out[8] = x2;
  2106. out[9] = y2;
  2107. out[10] = z2;
  2108. out[11] = 0;
  2109. out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
  2110. out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
  2111. out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
  2112. out[15] = 1;
  2113. return out;
  2114. }
  2115. /**
  2116. * Generates a matrix that makes something look at something else.
  2117. *
  2118. * @param {mat4} out mat4 frustum matrix will be written into
  2119. * @param {ReadonlyVec3} eye Position of the viewer
  2120. * @param {ReadonlyVec3} center Point the viewer is looking at
  2121. * @param {ReadonlyVec3} up vec3 pointing up
  2122. * @returns {mat4} out
  2123. */
  2124. function targetTo(out, eye, target, up) {
  2125. var eyex = eye[0],
  2126. eyey = eye[1],
  2127. eyez = eye[2],
  2128. upx = up[0],
  2129. upy = up[1],
  2130. upz = up[2];
  2131. var z0 = eyex - target[0],
  2132. z1 = eyey - target[1],
  2133. z2 = eyez - target[2];
  2134. var len = z0 * z0 + z1 * z1 + z2 * z2;
  2135. if (len > 0) {
  2136. len = 1 / Math.sqrt(len);
  2137. z0 *= len;
  2138. z1 *= len;
  2139. z2 *= len;
  2140. }
  2141. var x0 = upy * z2 - upz * z1,
  2142. x1 = upz * z0 - upx * z2,
  2143. x2 = upx * z1 - upy * z0;
  2144. len = x0 * x0 + x1 * x1 + x2 * x2;
  2145. if (len > 0) {
  2146. len = 1 / Math.sqrt(len);
  2147. x0 *= len;
  2148. x1 *= len;
  2149. x2 *= len;
  2150. }
  2151. out[0] = x0;
  2152. out[1] = x1;
  2153. out[2] = x2;
  2154. out[3] = 0;
  2155. out[4] = z1 * x2 - z2 * x1;
  2156. out[5] = z2 * x0 - z0 * x2;
  2157. out[6] = z0 * x1 - z1 * x0;
  2158. out[7] = 0;
  2159. out[8] = z0;
  2160. out[9] = z1;
  2161. out[10] = z2;
  2162. out[11] = 0;
  2163. out[12] = eyex;
  2164. out[13] = eyey;
  2165. out[14] = eyez;
  2166. out[15] = 1;
  2167. return out;
  2168. }
  2169. /**
  2170. * Returns a string representation of a mat4
  2171. *
  2172. * @param {ReadonlyMat4} a matrix to represent as a string
  2173. * @returns {String} string representation of the matrix
  2174. */
  2175. function str(a) {
  2176. 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] + ")";
  2177. }
  2178. /**
  2179. * Returns Frobenius norm of a mat4
  2180. *
  2181. * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of
  2182. * @returns {Number} Frobenius norm
  2183. */
  2184. function frob(a) {
  2185. 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]);
  2186. }
  2187. /**
  2188. * Adds two mat4's
  2189. *
  2190. * @param {mat4} out the receiving matrix
  2191. * @param {ReadonlyMat4} a the first operand
  2192. * @param {ReadonlyMat4} b the second operand
  2193. * @returns {mat4} out
  2194. */
  2195. function add(out, a, b) {
  2196. out[0] = a[0] + b[0];
  2197. out[1] = a[1] + b[1];
  2198. out[2] = a[2] + b[2];
  2199. out[3] = a[3] + b[3];
  2200. out[4] = a[4] + b[4];
  2201. out[5] = a[5] + b[5];
  2202. out[6] = a[6] + b[6];
  2203. out[7] = a[7] + b[7];
  2204. out[8] = a[8] + b[8];
  2205. out[9] = a[9] + b[9];
  2206. out[10] = a[10] + b[10];
  2207. out[11] = a[11] + b[11];
  2208. out[12] = a[12] + b[12];
  2209. out[13] = a[13] + b[13];
  2210. out[14] = a[14] + b[14];
  2211. out[15] = a[15] + b[15];
  2212. return out;
  2213. }
  2214. /**
  2215. * Subtracts matrix b from matrix a
  2216. *
  2217. * @param {mat4} out the receiving matrix
  2218. * @param {ReadonlyMat4} a the first operand
  2219. * @param {ReadonlyMat4} b the second operand
  2220. * @returns {mat4} out
  2221. */
  2222. function subtract(out, a, b) {
  2223. out[0] = a[0] - b[0];
  2224. out[1] = a[1] - b[1];
  2225. out[2] = a[2] - b[2];
  2226. out[3] = a[3] - b[3];
  2227. out[4] = a[4] - b[4];
  2228. out[5] = a[5] - b[5];
  2229. out[6] = a[6] - b[6];
  2230. out[7] = a[7] - b[7];
  2231. out[8] = a[8] - b[8];
  2232. out[9] = a[9] - b[9];
  2233. out[10] = a[10] - b[10];
  2234. out[11] = a[11] - b[11];
  2235. out[12] = a[12] - b[12];
  2236. out[13] = a[13] - b[13];
  2237. out[14] = a[14] - b[14];
  2238. out[15] = a[15] - b[15];
  2239. return out;
  2240. }
  2241. /**
  2242. * Multiply each element of the matrix by a scalar.
  2243. *
  2244. * @param {mat4} out the receiving matrix
  2245. * @param {ReadonlyMat4} a the matrix to scale
  2246. * @param {Number} b amount to scale the matrix's elements by
  2247. * @returns {mat4} out
  2248. */
  2249. function multiplyScalar(out, a, b) {
  2250. out[0] = a[0] * b;
  2251. out[1] = a[1] * b;
  2252. out[2] = a[2] * b;
  2253. out[3] = a[3] * b;
  2254. out[4] = a[4] * b;
  2255. out[5] = a[5] * b;
  2256. out[6] = a[6] * b;
  2257. out[7] = a[7] * b;
  2258. out[8] = a[8] * b;
  2259. out[9] = a[9] * b;
  2260. out[10] = a[10] * b;
  2261. out[11] = a[11] * b;
  2262. out[12] = a[12] * b;
  2263. out[13] = a[13] * b;
  2264. out[14] = a[14] * b;
  2265. out[15] = a[15] * b;
  2266. return out;
  2267. }
  2268. /**
  2269. * Adds two mat4's after multiplying each element of the second operand by a scalar value.
  2270. *
  2271. * @param {mat4} out the receiving vector
  2272. * @param {ReadonlyMat4} a the first operand
  2273. * @param {ReadonlyMat4} b the second operand
  2274. * @param {Number} scale the amount to scale b's elements by before adding
  2275. * @returns {mat4} out
  2276. */
  2277. function multiplyScalarAndAdd(out, a, b, scale) {
  2278. out[0] = a[0] + b[0] * scale;
  2279. out[1] = a[1] + b[1] * scale;
  2280. out[2] = a[2] + b[2] * scale;
  2281. out[3] = a[3] + b[3] * scale;
  2282. out[4] = a[4] + b[4] * scale;
  2283. out[5] = a[5] + b[5] * scale;
  2284. out[6] = a[6] + b[6] * scale;
  2285. out[7] = a[7] + b[7] * scale;
  2286. out[8] = a[8] + b[8] * scale;
  2287. out[9] = a[9] + b[9] * scale;
  2288. out[10] = a[10] + b[10] * scale;
  2289. out[11] = a[11] + b[11] * scale;
  2290. out[12] = a[12] + b[12] * scale;
  2291. out[13] = a[13] + b[13] * scale;
  2292. out[14] = a[14] + b[14] * scale;
  2293. out[15] = a[15] + b[15] * scale;
  2294. return out;
  2295. }
  2296. /**
  2297. * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)
  2298. *
  2299. * @param {ReadonlyMat4} a The first matrix.
  2300. * @param {ReadonlyMat4} b The second matrix.
  2301. * @returns {Boolean} True if the matrices are equal, false otherwise.
  2302. */
  2303. function exactEquals(a, b) {
  2304. 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];
  2305. }
  2306. /**
  2307. * Returns whether or not the matrices have approximately the same elements in the same position.
  2308. *
  2309. * @param {ReadonlyMat4} a The first matrix.
  2310. * @param {ReadonlyMat4} b The second matrix.
  2311. * @returns {Boolean} True if the matrices are equal, false otherwise.
  2312. */
  2313. function equals(a, b) {
  2314. var a0 = a[0],
  2315. a1 = a[1],
  2316. a2 = a[2],
  2317. a3 = a[3];
  2318. var a4 = a[4],
  2319. a5 = a[5],
  2320. a6 = a[6],
  2321. a7 = a[7];
  2322. var a8 = a[8],
  2323. a9 = a[9],
  2324. a10 = a[10],
  2325. a11 = a[11];
  2326. var a12 = a[12],
  2327. a13 = a[13],
  2328. a14 = a[14],
  2329. a15 = a[15];
  2330. var b0 = b[0],
  2331. b1 = b[1],
  2332. b2 = b[2],
  2333. b3 = b[3];
  2334. var b4 = b[4],
  2335. b5 = b[5],
  2336. b6 = b[6],
  2337. b7 = b[7];
  2338. var b8 = b[8],
  2339. b9 = b[9],
  2340. b10 = b[10],
  2341. b11 = b[11];
  2342. var b12 = b[12],
  2343. b13 = b[13],
  2344. b14 = b[14],
  2345. b15 = b[15];
  2346. 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));
  2347. }
  2348. /**
  2349. * Alias for {@link mat4.multiply}
  2350. * @function
  2351. */
  2352. var mul = multiply;
  2353. /**
  2354. * Alias for {@link mat4.subtract}
  2355. * @function
  2356. */
  2357. var sub = subtract;
  2358. var mat4 = /*#__PURE__*/Object.freeze({
  2359. __proto__: null,
  2360. create: create$1,
  2361. clone: clone,
  2362. copy: copy,
  2363. fromValues: fromValues$1,
  2364. set: set,
  2365. identity: identity,
  2366. transpose: transpose,
  2367. invert: invert,
  2368. adjoint: adjoint,
  2369. determinant: determinant,
  2370. multiply: multiply,
  2371. translate: translate,
  2372. scale: scale,
  2373. rotate: rotate,
  2374. rotateX: rotateX,
  2375. rotateY: rotateY,
  2376. rotateZ: rotateZ,
  2377. fromTranslation: fromTranslation,
  2378. fromScaling: fromScaling,
  2379. fromRotation: fromRotation,
  2380. fromXRotation: fromXRotation,
  2381. fromYRotation: fromYRotation,
  2382. fromZRotation: fromZRotation,
  2383. fromRotationTranslation: fromRotationTranslation,
  2384. fromQuat2: fromQuat2,
  2385. getTranslation: getTranslation,
  2386. getScaling: getScaling,
  2387. getRotation: getRotation,
  2388. fromRotationTranslationScale: fromRotationTranslationScale,
  2389. fromRotationTranslationScaleOrigin: fromRotationTranslationScaleOrigin,
  2390. fromQuat: fromQuat,
  2391. frustum: frustum,
  2392. perspectiveNO: perspectiveNO,
  2393. perspective: perspective,
  2394. perspectiveZO: perspectiveZO,
  2395. perspectiveFromFieldOfView: perspectiveFromFieldOfView,
  2396. orthoNO: orthoNO,
  2397. ortho: ortho,
  2398. orthoZO: orthoZO,
  2399. lookAt: lookAt,
  2400. targetTo: targetTo,
  2401. str: str,
  2402. frob: frob,
  2403. add: add,
  2404. subtract: subtract,
  2405. multiplyScalar: multiplyScalar,
  2406. multiplyScalarAndAdd: multiplyScalarAndAdd,
  2407. exactEquals: exactEquals,
  2408. equals: equals,
  2409. mul: mul,
  2410. sub: sub
  2411. });
  2412. /**
  2413. * 3 Dimensional Vector
  2414. * @module vec3
  2415. */
  2416. /**
  2417. * Creates a new, empty vec3
  2418. *
  2419. * @returns {vec3} a new 3D vector
  2420. */
  2421. function create$2() {
  2422. var out = new ARRAY_TYPE(3);
  2423. if (ARRAY_TYPE != Float32Array) {
  2424. out[0] = 0;
  2425. out[1] = 0;
  2426. out[2] = 0;
  2427. }
  2428. return out;
  2429. }
  2430. /**
  2431. * Creates a new vec3 initialized with values from an existing vector
  2432. *
  2433. * @param {ReadonlyVec3} a vector to clone
  2434. * @returns {vec3} a new 3D vector
  2435. */
  2436. function clone$1(a) {
  2437. var out = new ARRAY_TYPE(3);
  2438. out[0] = a[0];
  2439. out[1] = a[1];
  2440. out[2] = a[2];
  2441. return out;
  2442. }
  2443. /**
  2444. * Calculates the length of a vec3
  2445. *
  2446. * @param {ReadonlyVec3} a vector to calculate length of
  2447. * @returns {Number} length of a
  2448. */
  2449. function length(a) {
  2450. var x = a[0];
  2451. var y = a[1];
  2452. var z = a[2];
  2453. return Math.hypot(x, y, z);
  2454. }
  2455. /**
  2456. * Creates a new vec3 initialized with the given values
  2457. *
  2458. * @param {Number} x X component
  2459. * @param {Number} y Y component
  2460. * @param {Number} z Z component
  2461. * @returns {vec3} a new 3D vector
  2462. */
  2463. function fromValues$2(x, y, z) {
  2464. var out = new ARRAY_TYPE(3);
  2465. out[0] = x;
  2466. out[1] = y;
  2467. out[2] = z;
  2468. return out;
  2469. }
  2470. /**
  2471. * Copy the values from one vec3 to another
  2472. *
  2473. * @param {vec3} out the receiving vector
  2474. * @param {ReadonlyVec3} a the source vector
  2475. * @returns {vec3} out
  2476. */
  2477. function copy$1(out, a) {
  2478. out[0] = a[0];
  2479. out[1] = a[1];
  2480. out[2] = a[2];
  2481. return out;
  2482. }
  2483. /**
  2484. * Set the components of a vec3 to the given values
  2485. *
  2486. * @param {vec3} out the receiving vector
  2487. * @param {Number} x X component
  2488. * @param {Number} y Y component
  2489. * @param {Number} z Z component
  2490. * @returns {vec3} out
  2491. */
  2492. function set$1(out, x, y, z) {
  2493. out[0] = x;
  2494. out[1] = y;
  2495. out[2] = z;
  2496. return out;
  2497. }
  2498. /**
  2499. * Adds two vec3's
  2500. *
  2501. * @param {vec3} out the receiving vector
  2502. * @param {ReadonlyVec3} a the first operand
  2503. * @param {ReadonlyVec3} b the second operand
  2504. * @returns {vec3} out
  2505. */
  2506. function add$1(out, a, b) {
  2507. out[0] = a[0] + b[0];
  2508. out[1] = a[1] + b[1];
  2509. out[2] = a[2] + b[2];
  2510. return out;
  2511. }
  2512. /**
  2513. * Subtracts vector b from vector a
  2514. *
  2515. * @param {vec3} out the receiving vector
  2516. * @param {ReadonlyVec3} a the first operand
  2517. * @param {ReadonlyVec3} b the second operand
  2518. * @returns {vec3} out
  2519. */
  2520. function subtract$1(out, a, b) {
  2521. out[0] = a[0] - b[0];
  2522. out[1] = a[1] - b[1];
  2523. out[2] = a[2] - b[2];
  2524. return out;
  2525. }
  2526. /**
  2527. * Multiplies two vec3's
  2528. *
  2529. * @param {vec3} out the receiving vector
  2530. * @param {ReadonlyVec3} a the first operand
  2531. * @param {ReadonlyVec3} b the second operand
  2532. * @returns {vec3} out
  2533. */
  2534. function multiply$1(out, a, b) {
  2535. out[0] = a[0] * b[0];
  2536. out[1] = a[1] * b[1];
  2537. out[2] = a[2] * b[2];
  2538. return out;
  2539. }
  2540. /**
  2541. * Scales a vec3 by a scalar number
  2542. *
  2543. * @param {vec3} out the receiving vector
  2544. * @param {ReadonlyVec3} a the vector to scale
  2545. * @param {Number} b amount to scale the vector by
  2546. * @returns {vec3} out
  2547. */
  2548. function scale$1(out, a, b) {
  2549. out[0] = a[0] * b;
  2550. out[1] = a[1] * b;
  2551. out[2] = a[2] * b;
  2552. return out;
  2553. }
  2554. /**
  2555. * Calculates the euclidian distance between two vec3's
  2556. *
  2557. * @param {ReadonlyVec3} a the first operand
  2558. * @param {ReadonlyVec3} b the second operand
  2559. * @returns {Number} distance between a and b
  2560. */
  2561. function distance(a, b) {
  2562. var x = b[0] - a[0];
  2563. var y = b[1] - a[1];
  2564. var z = b[2] - a[2];
  2565. return Math.hypot(x, y, z);
  2566. }
  2567. /**
  2568. * Normalize a vec3
  2569. *
  2570. * @param {vec3} out the receiving vector
  2571. * @param {ReadonlyVec3} a vector to normalize
  2572. * @returns {vec3} out
  2573. */
  2574. function normalize(out, a) {
  2575. var x = a[0];
  2576. var y = a[1];
  2577. var z = a[2];
  2578. var len = x * x + y * y + z * z;
  2579. if (len > 0) {
  2580. //TODO: evaluate use of glm_invsqrt here?
  2581. len = 1 / Math.sqrt(len);
  2582. }
  2583. out[0] = a[0] * len;
  2584. out[1] = a[1] * len;
  2585. out[2] = a[2] * len;
  2586. return out;
  2587. }
  2588. /**
  2589. * Calculates the dot product of two vec3's
  2590. *
  2591. * @param {ReadonlyVec3} a the first operand
  2592. * @param {ReadonlyVec3} b the second operand
  2593. * @returns {Number} dot product of a and b
  2594. */
  2595. function dot(a, b) {
  2596. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  2597. }
  2598. /**
  2599. * Computes the cross product of two vec3's
  2600. *
  2601. * @param {vec3} out the receiving vector
  2602. * @param {ReadonlyVec3} a the first operand
  2603. * @param {ReadonlyVec3} b the second operand
  2604. * @returns {vec3} out
  2605. */
  2606. function cross(out, a, b) {
  2607. var ax = a[0],
  2608. ay = a[1],
  2609. az = a[2];
  2610. var bx = b[0],
  2611. by = b[1],
  2612. bz = b[2];
  2613. out[0] = ay * bz - az * by;
  2614. out[1] = az * bx - ax * bz;
  2615. out[2] = ax * by - ay * bx;
  2616. return out;
  2617. }
  2618. /**
  2619. * Performs a linear interpolation between two vec3's
  2620. *
  2621. * @param {vec3} out the receiving vector
  2622. * @param {ReadonlyVec3} a the first operand
  2623. * @param {ReadonlyVec3} b the second operand
  2624. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  2625. * @returns {vec3} out
  2626. */
  2627. function lerp(out, a, b, t) {
  2628. var ax = a[0];
  2629. var ay = a[1];
  2630. var az = a[2];
  2631. out[0] = ax + t * (b[0] - ax);
  2632. out[1] = ay + t * (b[1] - ay);
  2633. out[2] = az + t * (b[2] - az);
  2634. return out;
  2635. }
  2636. /**
  2637. * Transforms the vec3 with a mat4.
  2638. * 4th vector component is implicitly '1'
  2639. *
  2640. * @param {vec3} out the receiving vector
  2641. * @param {ReadonlyVec3} a the vector to transform
  2642. * @param {ReadonlyMat4} m matrix to transform with
  2643. * @returns {vec3} out
  2644. */
  2645. function transformMat4(out, a, m) {
  2646. var x = a[0],
  2647. y = a[1],
  2648. z = a[2];
  2649. var w = m[3] * x + m[7] * y + m[11] * z + m[15];
  2650. w = w || 1.0;
  2651. out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;
  2652. out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;
  2653. out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;
  2654. return out;
  2655. }
  2656. /**
  2657. * Transforms the vec3 with a mat3.
  2658. *
  2659. * @param {vec3} out the receiving vector
  2660. * @param {ReadonlyVec3} a the vector to transform
  2661. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  2662. * @returns {vec3} out
  2663. */
  2664. function transformMat3(out, a, m) {
  2665. var x = a[0],
  2666. y = a[1],
  2667. z = a[2];
  2668. out[0] = x * m[0] + y * m[3] + z * m[6];
  2669. out[1] = x * m[1] + y * m[4] + z * m[7];
  2670. out[2] = x * m[2] + y * m[5] + z * m[8];
  2671. return out;
  2672. }
  2673. /**
  2674. * Transforms the vec3 with a quat
  2675. * Can also be used for dual quaternions. (Multiply it with the real part)
  2676. *
  2677. * @param {vec3} out the receiving vector
  2678. * @param {ReadonlyVec3} a the vector to transform
  2679. * @param {ReadonlyQuat} q quaternion to transform with
  2680. * @returns {vec3} out
  2681. */
  2682. function transformQuat(out, a, q) {
  2683. // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  2684. var qx = q[0],
  2685. qy = q[1],
  2686. qz = q[2],
  2687. qw = q[3];
  2688. var x = a[0],
  2689. y = a[1],
  2690. z = a[2]; // var qvec = [qx, qy, qz];
  2691. // var uv = vec3.cross([], qvec, a);
  2692. var uvx = qy * z - qz * y,
  2693. uvy = qz * x - qx * z,
  2694. uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);
  2695. var uuvx = qy * uvz - qz * uvy,
  2696. uuvy = qz * uvx - qx * uvz,
  2697. uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);
  2698. var w2 = qw * 2;
  2699. uvx *= w2;
  2700. uvy *= w2;
  2701. uvz *= w2; // vec3.scale(uuv, uuv, 2);
  2702. uuvx *= 2;
  2703. uuvy *= 2;
  2704. uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));
  2705. out[0] = x + uvx + uuvx;
  2706. out[1] = y + uvy + uuvy;
  2707. out[2] = z + uvz + uuvz;
  2708. return out;
  2709. }
  2710. /**
  2711. * Returns whether or not the vectors have approximately the same elements in the same position.
  2712. *
  2713. * @param {ReadonlyVec3} a The first vector.
  2714. * @param {ReadonlyVec3} b The second vector.
  2715. * @returns {Boolean} True if the vectors are equal, false otherwise.
  2716. */
  2717. function equals$1(a, b) {
  2718. var a0 = a[0],
  2719. a1 = a[1],
  2720. a2 = a[2];
  2721. var b0 = b[0],
  2722. b1 = b[1],
  2723. b2 = b[2];
  2724. 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));
  2725. }
  2726. /**
  2727. * Alias for {@link vec3.distance}
  2728. * @function
  2729. */
  2730. var dist = distance;
  2731. /**
  2732. * Alias for {@link vec3.length}
  2733. * @function
  2734. */
  2735. var len = length;
  2736. /**
  2737. * Perform some operation over an array of vec3s.
  2738. *
  2739. * @param {Array} a the array of vectors to iterate over
  2740. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  2741. * @param {Number} offset Number of elements to skip at the beginning of the array
  2742. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  2743. * @param {Function} fn Function to call for each vector in the array
  2744. * @param {Object} [arg] additional argument to pass to fn
  2745. * @returns {Array} a
  2746. * @function
  2747. */
  2748. var forEach = function () {
  2749. var vec = create$2();
  2750. return function (a, stride, offset, count, fn, arg) {
  2751. var i, l;
  2752. if (!stride) {
  2753. stride = 3;
  2754. }
  2755. if (!offset) {
  2756. offset = 0;
  2757. }
  2758. if (count) {
  2759. l = Math.min(count * stride + offset, a.length);
  2760. } else {
  2761. l = a.length;
  2762. }
  2763. for (i = offset; i < l; i += stride) {
  2764. vec[0] = a[i];
  2765. vec[1] = a[i + 1];
  2766. vec[2] = a[i + 2];
  2767. fn(vec, vec, arg);
  2768. a[i] = vec[0];
  2769. a[i + 1] = vec[1];
  2770. a[i + 2] = vec[2];
  2771. }
  2772. return a;
  2773. };
  2774. }();
  2775. /**
  2776. * 4 Dimensional Vector
  2777. * @module vec4
  2778. */
  2779. /**
  2780. * Creates a new, empty vec4
  2781. *
  2782. * @returns {vec4} a new 4D vector
  2783. */
  2784. function create$3() {
  2785. var out = new ARRAY_TYPE(4);
  2786. if (ARRAY_TYPE != Float32Array) {
  2787. out[0] = 0;
  2788. out[1] = 0;
  2789. out[2] = 0;
  2790. out[3] = 0;
  2791. }
  2792. return out;
  2793. }
  2794. /**
  2795. * Creates a new vec4 initialized with the given values
  2796. *
  2797. * @param {Number} x X component
  2798. * @param {Number} y Y component
  2799. * @param {Number} z Z component
  2800. * @param {Number} w W component
  2801. * @returns {vec4} a new 4D vector
  2802. */
  2803. function fromValues$3(x, y, z, w) {
  2804. var out = new ARRAY_TYPE(4);
  2805. out[0] = x;
  2806. out[1] = y;
  2807. out[2] = z;
  2808. out[3] = w;
  2809. return out;
  2810. }
  2811. /**
  2812. * Copy the values from one vec4 to another
  2813. *
  2814. * @param {vec4} out the receiving vector
  2815. * @param {ReadonlyVec4} a the source vector
  2816. * @returns {vec4} out
  2817. */
  2818. function copy$2(out, a) {
  2819. out[0] = a[0];
  2820. out[1] = a[1];
  2821. out[2] = a[2];
  2822. out[3] = a[3];
  2823. return out;
  2824. }
  2825. /**
  2826. * Normalize a vec4
  2827. *
  2828. * @param {vec4} out the receiving vector
  2829. * @param {ReadonlyVec4} a vector to normalize
  2830. * @returns {vec4} out
  2831. */
  2832. function normalize$1(out, a) {
  2833. var x = a[0];
  2834. var y = a[1];
  2835. var z = a[2];
  2836. var w = a[3];
  2837. var len = x * x + y * y + z * z + w * w;
  2838. if (len > 0) {
  2839. len = 1 / Math.sqrt(len);
  2840. }
  2841. out[0] = x * len;
  2842. out[1] = y * len;
  2843. out[2] = z * len;
  2844. out[3] = w * len;
  2845. return out;
  2846. }
  2847. /**
  2848. * Transforms the vec4 with a mat4.
  2849. *
  2850. * @param {vec4} out the receiving vector
  2851. * @param {ReadonlyVec4} a the vector to transform
  2852. * @param {ReadonlyMat4} m matrix to transform with
  2853. * @returns {vec4} out
  2854. */
  2855. function transformMat4$1(out, a, m) {
  2856. var x = a[0],
  2857. y = a[1],
  2858. z = a[2],
  2859. w = a[3];
  2860. out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;
  2861. out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;
  2862. out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;
  2863. out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;
  2864. return out;
  2865. }
  2866. /**
  2867. * Perform some operation over an array of vec4s.
  2868. *
  2869. * @param {Array} a the array of vectors to iterate over
  2870. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  2871. * @param {Number} offset Number of elements to skip at the beginning of the array
  2872. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  2873. * @param {Function} fn Function to call for each vector in the array
  2874. * @param {Object} [arg] additional argument to pass to fn
  2875. * @returns {Array} a
  2876. * @function
  2877. */
  2878. var forEach$1 = function () {
  2879. var vec = create$3();
  2880. return function (a, stride, offset, count, fn, arg) {
  2881. var i, l;
  2882. if (!stride) {
  2883. stride = 4;
  2884. }
  2885. if (!offset) {
  2886. offset = 0;
  2887. }
  2888. if (count) {
  2889. l = Math.min(count * stride + offset, a.length);
  2890. } else {
  2891. l = a.length;
  2892. }
  2893. for (i = offset; i < l; i += stride) {
  2894. vec[0] = a[i];
  2895. vec[1] = a[i + 1];
  2896. vec[2] = a[i + 2];
  2897. vec[3] = a[i + 3];
  2898. fn(vec, vec, arg);
  2899. a[i] = vec[0];
  2900. a[i + 1] = vec[1];
  2901. a[i + 2] = vec[2];
  2902. a[i + 3] = vec[3];
  2903. }
  2904. return a;
  2905. };
  2906. }();
  2907. /**
  2908. * Quaternion
  2909. * @module quat
  2910. */
  2911. /**
  2912. * Creates a new identity quat
  2913. *
  2914. * @returns {quat} a new quaternion
  2915. */
  2916. function create$4() {
  2917. var out = new ARRAY_TYPE(4);
  2918. if (ARRAY_TYPE != Float32Array) {
  2919. out[0] = 0;
  2920. out[1] = 0;
  2921. out[2] = 0;
  2922. }
  2923. out[3] = 1;
  2924. return out;
  2925. }
  2926. /**
  2927. * Sets a quat from the given angle and rotation axis,
  2928. * then returns it.
  2929. *
  2930. * @param {quat} out the receiving quaternion
  2931. * @param {ReadonlyVec3} axis the axis around which to rotate
  2932. * @param {Number} rad the angle in radians
  2933. * @returns {quat} out
  2934. **/
  2935. function setAxisAngle(out, axis, rad) {
  2936. rad = rad * 0.5;
  2937. var s = Math.sin(rad);
  2938. out[0] = s * axis[0];
  2939. out[1] = s * axis[1];
  2940. out[2] = s * axis[2];
  2941. out[3] = Math.cos(rad);
  2942. return out;
  2943. }
  2944. /**
  2945. * Multiplies two quat's
  2946. *
  2947. * @param {quat} out the receiving quaternion
  2948. * @param {ReadonlyQuat} a the first operand
  2949. * @param {ReadonlyQuat} b the second operand
  2950. * @returns {quat} out
  2951. */
  2952. function multiply$2(out, a, b) {
  2953. var ax = a[0],
  2954. ay = a[1],
  2955. az = a[2],
  2956. aw = a[3];
  2957. var bx = b[0],
  2958. by = b[1],
  2959. bz = b[2],
  2960. bw = b[3];
  2961. out[0] = ax * bw + aw * bx + ay * bz - az * by;
  2962. out[1] = ay * bw + aw * by + az * bx - ax * bz;
  2963. out[2] = az * bw + aw * bz + ax * by - ay * bx;
  2964. out[3] = aw * bw - ax * bx - ay * by - az * bz;
  2965. return out;
  2966. }
  2967. /**
  2968. * Performs a spherical linear interpolation between two quat
  2969. *
  2970. * @param {quat} out the receiving quaternion
  2971. * @param {ReadonlyQuat} a the first operand
  2972. * @param {ReadonlyQuat} b the second operand
  2973. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  2974. * @returns {quat} out
  2975. */
  2976. function slerp(out, a, b, t) {
  2977. // benchmarks:
  2978. // http://jsperf.com/quaternion-slerp-implementations
  2979. var ax = a[0],
  2980. ay = a[1],
  2981. az = a[2],
  2982. aw = a[3];
  2983. var bx = b[0],
  2984. by = b[1],
  2985. bz = b[2],
  2986. bw = b[3];
  2987. var omega, cosom, sinom, scale0, scale1; // calc cosine
  2988. cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)
  2989. if (cosom < 0.0) {
  2990. cosom = -cosom;
  2991. bx = -bx;
  2992. by = -by;
  2993. bz = -bz;
  2994. bw = -bw;
  2995. } // calculate coefficients
  2996. if (1.0 - cosom > EPSILON) {
  2997. // standard case (slerp)
  2998. omega = Math.acos(cosom);
  2999. sinom = Math.sin(omega);
  3000. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  3001. scale1 = Math.sin(t * omega) / sinom;
  3002. } else {
  3003. // "from" and "to" quaternions are very close
  3004. // ... so we can do a linear interpolation
  3005. scale0 = 1.0 - t;
  3006. scale1 = t;
  3007. } // calculate final values
  3008. out[0] = scale0 * ax + scale1 * bx;
  3009. out[1] = scale0 * ay + scale1 * by;
  3010. out[2] = scale0 * az + scale1 * bz;
  3011. out[3] = scale0 * aw + scale1 * bw;
  3012. return out;
  3013. }
  3014. /**
  3015. * Calculates the inverse of a quat
  3016. *
  3017. * @param {quat} out the receiving quaternion
  3018. * @param {ReadonlyQuat} a quat to calculate inverse of
  3019. * @returns {quat} out
  3020. */
  3021. function invert$1(out, a) {
  3022. var a0 = a[0],
  3023. a1 = a[1],
  3024. a2 = a[2],
  3025. a3 = a[3];
  3026. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  3027. var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  3028. out[0] = -a0 * invDot;
  3029. out[1] = -a1 * invDot;
  3030. out[2] = -a2 * invDot;
  3031. out[3] = a3 * invDot;
  3032. return out;
  3033. }
  3034. /**
  3035. * Creates a quaternion from the given 3x3 rotation matrix.
  3036. *
  3037. * NOTE: The resultant quaternion is not normalized, so you should be sure
  3038. * to renormalize the quaternion yourself where necessary.
  3039. *
  3040. * @param {quat} out the receiving quaternion
  3041. * @param {ReadonlyMat3} m rotation matrix
  3042. * @returns {quat} out
  3043. * @function
  3044. */
  3045. function fromMat3(out, m) {
  3046. // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  3047. // article "Quaternion Calculus and Fast Animation".
  3048. var fTrace = m[0] + m[4] + m[8];
  3049. var fRoot;
  3050. if (fTrace > 0.0) {
  3051. // |w| > 1/2, may as well choose w > 1/2
  3052. fRoot = Math.sqrt(fTrace + 1.0); // 2w
  3053. out[3] = 0.5 * fRoot;
  3054. fRoot = 0.5 / fRoot; // 1/(4w)
  3055. out[0] = (m[5] - m[7]) * fRoot;
  3056. out[1] = (m[6] - m[2]) * fRoot;
  3057. out[2] = (m[1] - m[3]) * fRoot;
  3058. } else {
  3059. // |w| <= 1/2
  3060. var i = 0;
  3061. if (m[4] > m[0]) i = 1;
  3062. if (m[8] > m[i * 3 + i]) i = 2;
  3063. var j = (i + 1) % 3;
  3064. var k = (i + 2) % 3;
  3065. fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);
  3066. out[i] = 0.5 * fRoot;
  3067. fRoot = 0.5 / fRoot;
  3068. out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;
  3069. out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;
  3070. out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;
  3071. }
  3072. return out;
  3073. }
  3074. /**
  3075. * Creates a quaternion from the given euler angle x, y, z.
  3076. *
  3077. * @param {quat} out the receiving quaternion
  3078. * @param {x} Angle to rotate around X axis in degrees.
  3079. * @param {y} Angle to rotate around Y axis in degrees.
  3080. * @param {z} Angle to rotate around Z axis in degrees.
  3081. * @returns {quat} out
  3082. * @function
  3083. */
  3084. function fromEuler(out, x, y, z) {
  3085. var halfToRad = 0.5 * Math.PI / 180.0;
  3086. x *= halfToRad;
  3087. y *= halfToRad;
  3088. z *= halfToRad;
  3089. var sx = Math.sin(x);
  3090. var cx = Math.cos(x);
  3091. var sy = Math.sin(y);
  3092. var cy = Math.cos(y);
  3093. var sz = Math.sin(z);
  3094. var cz = Math.cos(z);
  3095. out[0] = sx * cy * cz - cx * sy * sz;
  3096. out[1] = cx * sy * cz + sx * cy * sz;
  3097. out[2] = cx * cy * sz - sx * sy * cz;
  3098. out[3] = cx * cy * cz + sx * sy * sz;
  3099. return out;
  3100. }
  3101. /**
  3102. * Creates a new quat initialized with the given values
  3103. *
  3104. * @param {Number} x X component
  3105. * @param {Number} y Y component
  3106. * @param {Number} z Z component
  3107. * @param {Number} w W component
  3108. * @returns {quat} a new quaternion
  3109. * @function
  3110. */
  3111. var fromValues$4 = fromValues$3;
  3112. /**
  3113. * Copy the values from one quat to another
  3114. *
  3115. * @param {quat} out the receiving quaternion
  3116. * @param {ReadonlyQuat} a the source quaternion
  3117. * @returns {quat} out
  3118. * @function
  3119. */
  3120. var copy$3 = copy$2;
  3121. /**
  3122. * Alias for {@link quat.multiply}
  3123. * @function
  3124. */
  3125. var mul$1 = multiply$2;
  3126. /**
  3127. * Normalize a quat
  3128. *
  3129. * @param {quat} out the receiving quaternion
  3130. * @param {ReadonlyQuat} a quaternion to normalize
  3131. * @returns {quat} out
  3132. * @function
  3133. */
  3134. var normalize$2 = normalize$1;
  3135. /**
  3136. * Sets a quaternion to represent the shortest rotation from one
  3137. * vector to another.
  3138. *
  3139. * Both vectors are assumed to be unit length.
  3140. *
  3141. * @param {quat} out the receiving quaternion.
  3142. * @param {ReadonlyVec3} a the initial vector
  3143. * @param {ReadonlyVec3} b the destination vector
  3144. * @returns {quat} out
  3145. */
  3146. var rotationTo = function () {
  3147. var tmpvec3 = create$2();
  3148. var xUnitVec3 = fromValues$2(1, 0, 0);
  3149. var yUnitVec3 = fromValues$2(0, 1, 0);
  3150. return function (out, a, b) {
  3151. var dot$1 = dot(a, b);
  3152. if (dot$1 < -0.999999) {
  3153. cross(tmpvec3, xUnitVec3, a);
  3154. if (len(tmpvec3) < 0.000001) cross(tmpvec3, yUnitVec3, a);
  3155. normalize(tmpvec3, tmpvec3);
  3156. setAxisAngle(out, tmpvec3, Math.PI);
  3157. return out;
  3158. } else if (dot$1 > 0.999999) {
  3159. out[0] = 0;
  3160. out[1] = 0;
  3161. out[2] = 0;
  3162. out[3] = 1;
  3163. return out;
  3164. } else {
  3165. cross(tmpvec3, a, b);
  3166. out[0] = tmpvec3[0];
  3167. out[1] = tmpvec3[1];
  3168. out[2] = tmpvec3[2];
  3169. out[3] = 1 + dot$1;
  3170. return normalize$2(out, out);
  3171. }
  3172. };
  3173. }();
  3174. /**
  3175. * Performs a spherical linear interpolation with two control points
  3176. *
  3177. * @param {quat} out the receiving quaternion
  3178. * @param {ReadonlyQuat} a the first operand
  3179. * @param {ReadonlyQuat} b the second operand
  3180. * @param {ReadonlyQuat} c the third operand
  3181. * @param {ReadonlyQuat} d the fourth operand
  3182. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  3183. * @returns {quat} out
  3184. */
  3185. var sqlerp = function () {
  3186. var temp1 = create$4();
  3187. var temp2 = create$4();
  3188. return function (out, a, b, c, d, t) {
  3189. slerp(temp1, a, d, t);
  3190. slerp(temp2, b, c, t);
  3191. slerp(out, temp1, temp2, 2 * t * (1 - t));
  3192. return out;
  3193. };
  3194. }();
  3195. /**
  3196. * Sets the specified quaternion with values corresponding to the given
  3197. * axes. Each axis is a vec3 and is expected to be unit length and
  3198. * perpendicular to all other specified axes.
  3199. *
  3200. * @param {ReadonlyVec3} view the vector representing the viewing direction
  3201. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  3202. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  3203. * @returns {quat} out
  3204. */
  3205. var setAxes = function () {
  3206. var matr = create();
  3207. return function (out, view, right, up) {
  3208. matr[0] = right[0];
  3209. matr[3] = right[1];
  3210. matr[6] = right[2];
  3211. matr[1] = up[0];
  3212. matr[4] = up[1];
  3213. matr[7] = up[2];
  3214. matr[2] = -view[0];
  3215. matr[5] = -view[1];
  3216. matr[8] = -view[2];
  3217. return normalize$2(out, fromMat3(out, matr));
  3218. };
  3219. }();
  3220. /**
  3221. * 2 Dimensional Vector
  3222. * @module vec2
  3223. */
  3224. /**
  3225. * Creates a new, empty vec2
  3226. *
  3227. * @returns {vec2} a new 2D vector
  3228. */
  3229. function create$5() {
  3230. var out = new ARRAY_TYPE(2);
  3231. if (ARRAY_TYPE != Float32Array) {
  3232. out[0] = 0;
  3233. out[1] = 0;
  3234. }
  3235. return out;
  3236. }
  3237. /**
  3238. * Creates a new vec2 initialized with the given values
  3239. *
  3240. * @param {Number} x X component
  3241. * @param {Number} y Y component
  3242. * @returns {vec2} a new 2D vector
  3243. */
  3244. function fromValues$5(x, y) {
  3245. var out = new ARRAY_TYPE(2);
  3246. out[0] = x;
  3247. out[1] = y;
  3248. return out;
  3249. }
  3250. /**
  3251. * Copy the values from one vec2 to another
  3252. *
  3253. * @param {vec2} out the receiving vector
  3254. * @param {ReadonlyVec2} a the source vector
  3255. * @returns {vec2} out
  3256. */
  3257. function copy$4(out, a) {
  3258. out[0] = a[0];
  3259. out[1] = a[1];
  3260. return out;
  3261. }
  3262. /**
  3263. * Normalize a vec2
  3264. *
  3265. * @param {vec2} out the receiving vector
  3266. * @param {ReadonlyVec2} a vector to normalize
  3267. * @returns {vec2} out
  3268. */
  3269. function normalize$3(out, a) {
  3270. var x = a[0],
  3271. y = a[1];
  3272. var len = x * x + y * y;
  3273. if (len > 0) {
  3274. //TODO: evaluate use of glm_invsqrt here?
  3275. len = 1 / Math.sqrt(len);
  3276. }
  3277. out[0] = a[0] * len;
  3278. out[1] = a[1] * len;
  3279. return out;
  3280. }
  3281. /**
  3282. * Calculates the dot product of two vec2's
  3283. *
  3284. * @param {ReadonlyVec2} a the first operand
  3285. * @param {ReadonlyVec2} b the second operand
  3286. * @returns {Number} dot product of a and b
  3287. */
  3288. function dot$1(a, b) {
  3289. return a[0] * b[0] + a[1] * b[1];
  3290. }
  3291. /**
  3292. * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)
  3293. *
  3294. * @param {ReadonlyVec2} a The first vector.
  3295. * @param {ReadonlyVec2} b The second vector.
  3296. * @returns {Boolean} True if the vectors are equal, false otherwise.
  3297. */
  3298. function exactEquals$1(a, b) {
  3299. return a[0] === b[0] && a[1] === b[1];
  3300. }
  3301. /**
  3302. * Perform some operation over an array of vec2s.
  3303. *
  3304. * @param {Array} a the array of vectors to iterate over
  3305. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  3306. * @param {Number} offset Number of elements to skip at the beginning of the array
  3307. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  3308. * @param {Function} fn Function to call for each vector in the array
  3309. * @param {Object} [arg] additional argument to pass to fn
  3310. * @returns {Array} a
  3311. * @function
  3312. */
  3313. var forEach$2 = function () {
  3314. var vec = create$5();
  3315. return function (a, stride, offset, count, fn, arg) {
  3316. var i, l;
  3317. if (!stride) {
  3318. stride = 2;
  3319. }
  3320. if (!offset) {
  3321. offset = 0;
  3322. }
  3323. if (count) {
  3324. l = Math.min(count * stride + offset, a.length);
  3325. } else {
  3326. l = a.length;
  3327. }
  3328. for (i = offset; i < l; i += stride) {
  3329. vec[0] = a[i];
  3330. vec[1] = a[i + 1];
  3331. fn(vec, vec, arg);
  3332. a[i] = vec[0];
  3333. a[i + 1] = vec[1];
  3334. }
  3335. return a;
  3336. };
  3337. }();
  3338. function clonePath(path) {
  3339. return path.map(function (x) { return (Array.isArray(x) ? [].concat(x) : x); });
  3340. }
  3341. /******************************************************************************
  3342. Copyright (c) Microsoft Corporation.
  3343. Permission to use, copy, modify, and/or distribute this software for any
  3344. purpose with or without fee is hereby granted.
  3345. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  3346. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  3347. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  3348. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  3349. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  3350. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  3351. PERFORMANCE OF THIS SOFTWARE.
  3352. ***************************************************************************** */
  3353. var __assign = function() {
  3354. __assign = Object.assign || function __assign(t) {
  3355. for (var s, i = 1, n = arguments.length; i < n; i++) {
  3356. s = arguments[i];
  3357. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
  3358. }
  3359. return t;
  3360. };
  3361. return __assign.apply(this, arguments);
  3362. };
  3363. var paramsParser = {
  3364. x1: 0,
  3365. y1: 0,
  3366. x2: 0,
  3367. y2: 0,
  3368. x: 0,
  3369. y: 0,
  3370. qx: null,
  3371. qy: null,
  3372. };
  3373. function fixArc(pathArray, allPathCommands, i) {
  3374. if (pathArray[i].length > 7) {
  3375. pathArray[i].shift();
  3376. var pi = pathArray[i];
  3377. // const ni = i + 1;
  3378. var ni = i;
  3379. while (pi.length) {
  3380. // if created multiple C:s, their original seg is saved
  3381. allPathCommands[i] = 'A';
  3382. // @ts-ignore
  3383. pathArray.splice((ni += 1), 0, ['C'].concat(pi.splice(0, 6)));
  3384. }
  3385. pathArray.splice(i, 1);
  3386. }
  3387. }
  3388. var paramsCount = {
  3389. a: 7,
  3390. c: 6,
  3391. h: 1,
  3392. l: 2,
  3393. m: 2,
  3394. r: 4,
  3395. q: 4,
  3396. s: 4,
  3397. t: 2,
  3398. v: 1,
  3399. z: 0,
  3400. };
  3401. /**
  3402. * Iterates an array to check if it's an actual `PathArray`.
  3403. */
  3404. function isPathArray(path) {
  3405. return (Array.isArray(path) &&
  3406. path.every(function (seg) {
  3407. var lk = seg[0].toLowerCase();
  3408. return paramsCount[lk] === seg.length - 1 && 'achlmqstvz'.includes(lk);
  3409. }));
  3410. }
  3411. /**
  3412. * Iterates an array to check if it's a `PathArray`
  3413. * with all absolute values.
  3414. */
  3415. function isAbsoluteArray(path) {
  3416. return (isPathArray(path) &&
  3417. // @ts-ignore -- `isPathArray` also checks if it's `Array`
  3418. path.every(function (_a) {
  3419. var x = _a[0];
  3420. return x === x.toUpperCase();
  3421. }));
  3422. }
  3423. /**
  3424. * Iterates an array to check if it's a `PathArray`
  3425. * with all segments are in non-shorthand notation
  3426. * with absolute values.
  3427. */
  3428. function isNormalizedArray(path) {
  3429. return isAbsoluteArray(path) && path.every(function (_a) {
  3430. var pc = _a[0];
  3431. return 'ACLMQZ'.includes(pc);
  3432. });
  3433. }
  3434. /**
  3435. * Breaks the parsing of a pathString once a segment is finalized.
  3436. */
  3437. function finalizeSegment(path) {
  3438. var pathCommand = path.pathValue[path.segmentStart];
  3439. var LK = pathCommand.toLowerCase();
  3440. var data = path.data;
  3441. while (data.length >= paramsCount[LK]) {
  3442. // overloaded `moveTo`
  3443. // https://github.com/rveciana/svg-path-properties/blob/master/src/parse.ts
  3444. if (LK === 'm' && data.length > 2) {
  3445. // @ts-ignore
  3446. path.segments.push([pathCommand].concat(data.splice(0, 2)));
  3447. LK = 'l';
  3448. pathCommand = pathCommand === 'm' ? 'l' : 'L';
  3449. }
  3450. else {
  3451. // @ts-ignore
  3452. path.segments.push([pathCommand].concat(data.splice(0, paramsCount[LK])));
  3453. }
  3454. if (!paramsCount[LK]) {
  3455. break;
  3456. }
  3457. }
  3458. }
  3459. /**
  3460. * Validates an A (arc-to) specific path command value.
  3461. * Usually a `large-arc-flag` or `sweep-flag`.
  3462. */
  3463. function scanFlag(path) {
  3464. var index = path.index, pathValue = path.pathValue;
  3465. var code = pathValue.charCodeAt(index);
  3466. if (code === 0x30 /* 0 */) {
  3467. path.param = 0;
  3468. path.index += 1;
  3469. return;
  3470. }
  3471. if (code === 0x31 /* 1 */) {
  3472. path.param = 1;
  3473. path.index += 1;
  3474. return;
  3475. }
  3476. path.err = "[path-util]: invalid Arc flag \"" + pathValue[index] + "\", expecting 0 or 1 at index " + index;
  3477. }
  3478. /**
  3479. * Checks if the character is or belongs to a number.
  3480. * [0-9]|+|-|.
  3481. */
  3482. function isDigitStart(code) {
  3483. return ((code >= 48 && code <= 57) /* 0..9 */ || code === 0x2b /* + */ || code === 0x2d /* - */ || code === 0x2e); /* . */
  3484. }
  3485. function isDigit(code) {
  3486. return code >= 48 && code <= 57; // 0..9
  3487. }
  3488. /**
  3489. * Validates every character of the path string,
  3490. * every path command, negative numbers or floating point numbers.
  3491. */
  3492. function scanParam(path) {
  3493. var max = path.max, pathValue = path.pathValue, start = path.index;
  3494. var index = start;
  3495. var zeroFirst = false;
  3496. var hasCeiling = false;
  3497. var hasDecimal = false;
  3498. var hasDot = false;
  3499. var ch;
  3500. if (index >= max) {
  3501. // path.err = 'SvgPath: missed param (at pos ' + index + ')';
  3502. path.err = "[path-util]: Invalid path value at index " + index + ", \"pathValue\" is missing param";
  3503. return;
  3504. }
  3505. ch = pathValue.charCodeAt(index);
  3506. if (ch === 0x2b /* + */ || ch === 0x2d /* - */) {
  3507. index += 1;
  3508. // ch = (index < max) ? pathValue.charCodeAt(index) : 0;
  3509. ch = pathValue.charCodeAt(index);
  3510. }
  3511. // This logic is shamelessly borrowed from Esprima
  3512. // https://github.com/ariya/esprimas
  3513. if (!isDigit(ch) && ch !== 0x2e /* . */) {
  3514. // path.err = 'SvgPath: param should start with 0..9 or `.` (at pos ' + index + ')';
  3515. path.err = "[path-util]: Invalid path value at index " + index + ", \"" + pathValue[index] + "\" is not a number";
  3516. return;
  3517. }
  3518. if (ch !== 0x2e /* . */) {
  3519. zeroFirst = ch === 0x30 /* 0 */;
  3520. index += 1;
  3521. ch = pathValue.charCodeAt(index);
  3522. if (zeroFirst && index < max) {
  3523. // decimal number starts with '0' such as '09' is illegal.
  3524. if (ch && isDigit(ch)) {
  3525. // path.err = 'SvgPath: numbers started with `0` such as `09`
  3526. // are illegal (at pos ' + start + ')';
  3527. path.err = "[path-util]: Invalid path value at index " + start + ", \"" + pathValue[start] + "\" illegal number";
  3528. return;
  3529. }
  3530. }
  3531. while (index < max && isDigit(pathValue.charCodeAt(index))) {
  3532. index += 1;
  3533. hasCeiling = true;
  3534. }
  3535. ch = pathValue.charCodeAt(index);
  3536. }
  3537. if (ch === 0x2e /* . */) {
  3538. hasDot = true;
  3539. index += 1;
  3540. while (isDigit(pathValue.charCodeAt(index))) {
  3541. index += 1;
  3542. hasDecimal = true;
  3543. }
  3544. ch = pathValue.charCodeAt(index);
  3545. }
  3546. if (ch === 0x65 /* e */ || ch === 0x45 /* E */) {
  3547. if (hasDot && !hasCeiling && !hasDecimal) {
  3548. path.err = "[path-util]: Invalid path value at index " + index + ", \"" + pathValue[index] + "\" invalid float exponent";
  3549. return;
  3550. }
  3551. index += 1;
  3552. ch = pathValue.charCodeAt(index);
  3553. if (ch === 0x2b /* + */ || ch === 0x2d /* - */) {
  3554. index += 1;
  3555. }
  3556. if (index < max && isDigit(pathValue.charCodeAt(index))) {
  3557. while (index < max && isDigit(pathValue.charCodeAt(index))) {
  3558. index += 1;
  3559. }
  3560. }
  3561. else {
  3562. path.err = "[path-util]: Invalid path value at index " + index + ", \"" + pathValue[index] + "\" invalid integer exponent";
  3563. return;
  3564. }
  3565. }
  3566. path.index = index;
  3567. path.param = +path.pathValue.slice(start, index);
  3568. }
  3569. /**
  3570. * Checks if the character is a space.
  3571. */
  3572. function isSpace(ch) {
  3573. var specialSpaces = [
  3574. 0x1680, 0x180e, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x202f,
  3575. 0x205f, 0x3000, 0xfeff,
  3576. ];
  3577. /* istanbul ignore next */
  3578. return (ch === 0x0a ||
  3579. ch === 0x0d ||
  3580. ch === 0x2028 ||
  3581. ch === 0x2029 || // Line terminators
  3582. // White spaces
  3583. ch === 0x20 ||
  3584. ch === 0x09 ||
  3585. ch === 0x0b ||
  3586. ch === 0x0c ||
  3587. ch === 0xa0 ||
  3588. (ch >= 0x1680 && specialSpaces.includes(ch)));
  3589. }
  3590. /**
  3591. * Points the parser to the next character in the
  3592. * path string every time it encounters any kind of
  3593. * space character.
  3594. */
  3595. function skipSpaces(path) {
  3596. var pathValue = path.pathValue, max = path.max;
  3597. while (path.index < max && isSpace(pathValue.charCodeAt(path.index))) {
  3598. path.index += 1;
  3599. }
  3600. }
  3601. /**
  3602. * Checks if the character is a path command.
  3603. */
  3604. function isPathCommand(code) {
  3605. // eslint-disable-next-line no-bitwise -- Impossible to satisfy
  3606. switch (code | 0x20) {
  3607. case 0x6d /* m */:
  3608. case 0x7a /* z */:
  3609. case 0x6c /* l */:
  3610. case 0x68 /* h */:
  3611. case 0x76 /* v */:
  3612. case 0x63 /* c */:
  3613. case 0x73 /* s */:
  3614. case 0x71 /* q */:
  3615. case 0x74 /* t */:
  3616. case 0x61 /* a */:
  3617. // case 0x72/* r */:
  3618. return true;
  3619. default:
  3620. return false;
  3621. }
  3622. }
  3623. /**
  3624. * Checks if the character is an A (arc-to) path command.
  3625. */
  3626. function isArcCommand(code) {
  3627. return (code | 0x20) === 0x61;
  3628. }
  3629. /**
  3630. * Scans every character in the path string to determine
  3631. * where a segment starts and where it ends.
  3632. */
  3633. function scanSegment(path) {
  3634. var max = path.max, pathValue = path.pathValue, index = path.index;
  3635. var cmdCode = pathValue.charCodeAt(index);
  3636. var reqParams = paramsCount[pathValue[index].toLowerCase()];
  3637. path.segmentStart = index;
  3638. if (!isPathCommand(cmdCode)) {
  3639. path.err = "[path-util]: Invalid path value \"" + pathValue[index] + "\" is not a path command";
  3640. return;
  3641. }
  3642. path.index += 1;
  3643. skipSpaces(path);
  3644. path.data = [];
  3645. if (!reqParams) {
  3646. // Z
  3647. finalizeSegment(path);
  3648. return;
  3649. }
  3650. for (;;) {
  3651. for (var i = reqParams; i > 0; i -= 1) {
  3652. if (isArcCommand(cmdCode) && (i === 3 || i === 4))
  3653. scanFlag(path);
  3654. else
  3655. scanParam(path);
  3656. if (path.err.length) {
  3657. return;
  3658. }
  3659. path.data.push(path.param);
  3660. skipSpaces(path);
  3661. // after ',' param is mandatory
  3662. if (path.index < max && pathValue.charCodeAt(path.index) === 0x2c /* , */) {
  3663. path.index += 1;
  3664. skipSpaces(path);
  3665. }
  3666. }
  3667. if (path.index >= path.max) {
  3668. break;
  3669. }
  3670. // Stop on next segment
  3671. if (!isDigitStart(pathValue.charCodeAt(path.index))) {
  3672. break;
  3673. }
  3674. }
  3675. finalizeSegment(path);
  3676. }
  3677. /**
  3678. * The `PathParser` is used by the `parsePathString` static method
  3679. * to generate a `pathArray`.
  3680. */
  3681. var PathParser = /** @class */ (function () {
  3682. function PathParser(pathString) {
  3683. this.pathValue = pathString;
  3684. // @ts-ignore
  3685. this.segments = [];
  3686. this.max = pathString.length;
  3687. this.index = 0;
  3688. this.param = 0.0;
  3689. this.segmentStart = 0;
  3690. this.data = [];
  3691. this.err = '';
  3692. }
  3693. return PathParser;
  3694. }());
  3695. /**
  3696. * Parses a path string value and returns an array
  3697. * of segments we like to call `pathArray`.
  3698. */
  3699. function parsePathString(pathInput) {
  3700. if (isPathArray(pathInput)) {
  3701. return clonePath(pathInput);
  3702. }
  3703. var path = new PathParser(pathInput);
  3704. skipSpaces(path);
  3705. while (path.index < path.max && !path.err.length) {
  3706. scanSegment(path);
  3707. }
  3708. return path.err ? path.err : path.segments;
  3709. }
  3710. function path2Absolute(pathInput) {
  3711. if (isAbsoluteArray(pathInput)) {
  3712. return clonePath(pathInput);
  3713. }
  3714. var path = parsePathString(pathInput);
  3715. // if (!path || !path.length) {
  3716. // return [['M', 0, 0]];
  3717. // }
  3718. var x = 0;
  3719. var y = 0;
  3720. var mx = 0;
  3721. var my = 0;
  3722. // @ts-ignore
  3723. return path.map(function (segment) {
  3724. var values = segment.slice(1).map(Number);
  3725. var pathCommand = segment[0];
  3726. var absCommand = pathCommand.toUpperCase();
  3727. if (pathCommand === 'M') {
  3728. x = values[0], y = values[1];
  3729. mx = x;
  3730. my = y;
  3731. return ['M', x, y];
  3732. }
  3733. var absoluteSegment;
  3734. if (pathCommand !== absCommand) {
  3735. switch (absCommand) {
  3736. case 'A':
  3737. absoluteSegment = [
  3738. absCommand,
  3739. values[0],
  3740. values[1],
  3741. values[2],
  3742. values[3],
  3743. values[4],
  3744. values[5] + x,
  3745. values[6] + y,
  3746. ];
  3747. break;
  3748. case 'V':
  3749. absoluteSegment = [absCommand, values[0] + y];
  3750. break;
  3751. case 'H':
  3752. absoluteSegment = [absCommand, values[0] + x];
  3753. break;
  3754. default: {
  3755. // use brakets for `eslint: no-case-declaration`
  3756. // https://stackoverflow.com/a/50753272/803358
  3757. var absValues = values.map(function (n, j) { return n + (j % 2 ? y : x); });
  3758. // for n, l, c, s, q, t
  3759. // @ts-ignore
  3760. absoluteSegment = [absCommand].concat(absValues);
  3761. }
  3762. }
  3763. }
  3764. else {
  3765. // @ts-ignore
  3766. absoluteSegment = [absCommand].concat(values);
  3767. }
  3768. var segLength = absoluteSegment.length;
  3769. switch (absCommand) {
  3770. case 'Z':
  3771. x = mx;
  3772. y = my;
  3773. break;
  3774. case 'H':
  3775. x = absoluteSegment[1];
  3776. break;
  3777. case 'V':
  3778. y = absoluteSegment[1];
  3779. break;
  3780. default:
  3781. x = absoluteSegment[segLength - 2];
  3782. y = absoluteSegment[segLength - 1];
  3783. if (absCommand === 'M') {
  3784. mx = x;
  3785. my = y;
  3786. }
  3787. }
  3788. return absoluteSegment;
  3789. });
  3790. }
  3791. /**
  3792. * Normalizes a single segment of a `PathArray` object.
  3793. * eg. H/V -> L, T -> Q
  3794. */
  3795. function normalizeSegment(segment, params) {
  3796. var pathCommand = segment[0];
  3797. var px1 = params.x1, py1 = params.y1, px2 = params.x2, py2 = params.y2;
  3798. var values = segment.slice(1).map(Number);
  3799. var result = segment;
  3800. if (!'TQ'.includes(pathCommand)) {
  3801. // optional but good to be cautious
  3802. params.qx = null;
  3803. params.qy = null;
  3804. }
  3805. if (pathCommand === 'H') {
  3806. result = ['L', segment[1], py1];
  3807. }
  3808. else if (pathCommand === 'V') {
  3809. result = ['L', px1, segment[1]];
  3810. }
  3811. else if (pathCommand === 'S') {
  3812. var x1 = px1 * 2 - px2;
  3813. var y1 = py1 * 2 - py2;
  3814. params.x1 = x1;
  3815. params.y1 = y1;
  3816. result = ['C', x1, y1].concat(values);
  3817. }
  3818. else if (pathCommand === 'T') {
  3819. var qx = px1 * 2 - params.qx;
  3820. var qy = py1 * 2 - params.qy;
  3821. params.qx = qx;
  3822. params.qy = qy;
  3823. result = ['Q', qx, qy].concat(values);
  3824. }
  3825. else if (pathCommand === 'Q') {
  3826. var nqx = values[0], nqy = values[1];
  3827. params.qx = nqx;
  3828. params.qy = nqy;
  3829. }
  3830. return result;
  3831. }
  3832. /**
  3833. * @example
  3834. * const path = 'M0 0 H50';
  3835. * const normalizedPath = SVGPathCommander.normalizePath(path);
  3836. * // result => [['M', 0, 0], ['L', 50, 0]]
  3837. */
  3838. function normalizePath(pathInput) {
  3839. if (isNormalizedArray(pathInput)) {
  3840. return clonePath(pathInput);
  3841. }
  3842. var path = path2Absolute(pathInput);
  3843. var params = __assign({}, paramsParser);
  3844. for (var i = 0; i < path.length; i += 1) {
  3845. // Save current path command
  3846. path[i] = normalizeSegment(path[i], params);
  3847. var segment = path[i];
  3848. var seglen = segment.length;
  3849. params.x1 = +segment[seglen - 2];
  3850. params.y1 = +segment[seglen - 1];
  3851. params.x2 = +segment[seglen - 4] || params.x1;
  3852. params.y2 = +segment[seglen - 3] || params.y1;
  3853. }
  3854. return path;
  3855. }
  3856. /**
  3857. * Iterates an array to check if it's a `PathArray`
  3858. * with all C (cubic bezier) segments.
  3859. *
  3860. * @param {string | PathArray} path the `Array` to be checked
  3861. * @returns {boolean} iteration result
  3862. */
  3863. function isCurveArray(path) {
  3864. return isNormalizedArray(path) && path.every(function (_a) {
  3865. var pc = _a[0];
  3866. return 'MC'.includes(pc);
  3867. });
  3868. }
  3869. function rotateVector(x, y, rad) {
  3870. var X = x * Math.cos(rad) - y * Math.sin(rad);
  3871. var Y = x * Math.sin(rad) + y * Math.cos(rad);
  3872. return { x: X, y: Y };
  3873. }
  3874. /**
  3875. * Converts A (arc-to) segments to C (cubic-bezier-to).
  3876. *
  3877. * For more information of where this math came from visit:
  3878. * http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  3879. */
  3880. function arcToCubic(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, recursive) {
  3881. var x1 = X1;
  3882. var y1 = Y1;
  3883. var rx = RX;
  3884. var ry = RY;
  3885. var x2 = X2;
  3886. var y2 = Y2;
  3887. // for more information of where this Math came from visit:
  3888. // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
  3889. var d120 = (Math.PI * 120) / 180;
  3890. var rad = (Math.PI / 180) * (+angle || 0);
  3891. /** @type {number[]} */
  3892. var res = [];
  3893. var xy;
  3894. var f1;
  3895. var f2;
  3896. var cx;
  3897. var cy;
  3898. if (!recursive) {
  3899. xy = rotateVector(x1, y1, -rad);
  3900. x1 = xy.x;
  3901. y1 = xy.y;
  3902. xy = rotateVector(x2, y2, -rad);
  3903. x2 = xy.x;
  3904. y2 = xy.y;
  3905. var x = (x1 - x2) / 2;
  3906. var y = (y1 - y2) / 2;
  3907. var h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
  3908. if (h > 1) {
  3909. h = Math.sqrt(h);
  3910. rx *= h;
  3911. ry *= h;
  3912. }
  3913. var rx2 = rx * rx;
  3914. var ry2 = ry * ry;
  3915. var k = (LAF === SF ? -1 : 1) *
  3916. Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x)));
  3917. cx = (k * rx * y) / ry + (x1 + x2) / 2;
  3918. cy = (k * -ry * x) / rx + (y1 + y2) / 2;
  3919. // eslint-disable-next-line no-bitwise -- Impossible to satisfy no-bitwise
  3920. f1 = Math.asin(((((y1 - cy) / ry) * Math.pow(10, 9)) >> 0) / Math.pow(10, 9));
  3921. // eslint-disable-next-line no-bitwise -- Impossible to satisfy no-bitwise
  3922. f2 = Math.asin(((((y2 - cy) / ry) * Math.pow(10, 9)) >> 0) / Math.pow(10, 9));
  3923. f1 = x1 < cx ? Math.PI - f1 : f1;
  3924. f2 = x2 < cx ? Math.PI - f2 : f2;
  3925. if (f1 < 0)
  3926. f1 = Math.PI * 2 + f1;
  3927. if (f2 < 0)
  3928. f2 = Math.PI * 2 + f2;
  3929. if (SF && f1 > f2) {
  3930. f1 -= Math.PI * 2;
  3931. }
  3932. if (!SF && f2 > f1) {
  3933. f2 -= Math.PI * 2;
  3934. }
  3935. }
  3936. else {
  3937. f1 = recursive[0], f2 = recursive[1], cx = recursive[2], cy = recursive[3];
  3938. }
  3939. var df = f2 - f1;
  3940. if (Math.abs(df) > d120) {
  3941. var f2old = f2;
  3942. var x2old = x2;
  3943. var y2old = y2;
  3944. f2 = f1 + d120 * (SF && f2 > f1 ? 1 : -1);
  3945. x2 = cx + rx * Math.cos(f2);
  3946. y2 = cy + ry * Math.sin(f2);
  3947. res = arcToCubic(x2, y2, rx, ry, angle, 0, SF, x2old, y2old, [f2, f2old, cx, cy]);
  3948. }
  3949. df = f2 - f1;
  3950. var c1 = Math.cos(f1);
  3951. var s1 = Math.sin(f1);
  3952. var c2 = Math.cos(f2);
  3953. var s2 = Math.sin(f2);
  3954. var t = Math.tan(df / 4);
  3955. var hx = (4 / 3) * rx * t;
  3956. var hy = (4 / 3) * ry * t;
  3957. var m1 = [x1, y1];
  3958. var m2 = [x1 + hx * s1, y1 - hy * c1];
  3959. var m3 = [x2 + hx * s2, y2 - hy * c2];
  3960. var m4 = [x2, y2];
  3961. m2[0] = 2 * m1[0] - m2[0];
  3962. m2[1] = 2 * m1[1] - m2[1];
  3963. if (recursive) {
  3964. return m2.concat(m3, m4, res);
  3965. // return [...m2, ...m3, ...m4, ...res];
  3966. }
  3967. res = m2.concat(m3, m4, res);
  3968. // res = [...m2, ...m3, ...m4, ...res];
  3969. var newres = [];
  3970. for (var i = 0, ii = res.length; i < ii; i += 1) {
  3971. newres[i] = i % 2 ? rotateVector(res[i - 1], res[i], rad).y : rotateVector(res[i], res[i + 1], rad).x;
  3972. }
  3973. return newres;
  3974. }
  3975. // const TAU = Math.PI * 2;
  3976. // const mapToEllipse = (
  3977. // { x, y }: { x: number; y: number },
  3978. // rx: number,
  3979. // ry: number,
  3980. // cosphi: number,
  3981. // sinphi: number,
  3982. // centerx: number,
  3983. // centery: number,
  3984. // ) => {
  3985. // x *= rx;
  3986. // y *= ry;
  3987. // const xp = cosphi * x - sinphi * y;
  3988. // const yp = sinphi * x + cosphi * y;
  3989. // return {
  3990. // x: xp + centerx,
  3991. // y: yp + centery,
  3992. // };
  3993. // };
  3994. // const approxUnitArc = (ang1: number, ang2: number) => {
  3995. // // If 90 degree circular arc, use a constant
  3996. // // as derived from http://spencermortensen.com/articles/bezier-circle
  3997. // const a =
  3998. // ang2 === 1.5707963267948966
  3999. // ? 0.551915024494
  4000. // : ang2 === -1.5707963267948966
  4001. // ? -0.551915024494
  4002. // : (4 / 3) * Math.tan(ang2 / 4);
  4003. // const x1 = Math.cos(ang1);
  4004. // const y1 = Math.sin(ang1);
  4005. // const x2 = Math.cos(ang1 + ang2);
  4006. // const y2 = Math.sin(ang1 + ang2);
  4007. // return [
  4008. // {
  4009. // x: x1 - y1 * a,
  4010. // y: y1 + x1 * a,
  4011. // },
  4012. // {
  4013. // x: x2 + y2 * a,
  4014. // y: y2 - x2 * a,
  4015. // },
  4016. // {
  4017. // x: x2,
  4018. // y: y2,
  4019. // },
  4020. // ];
  4021. // };
  4022. // const vectorAngle = (ux: number, uy: number, vx: number, vy: number) => {
  4023. // const sign = ux * vy - uy * vx < 0 ? -1 : 1;
  4024. // let dot = ux * vx + uy * vy;
  4025. // if (dot > 1) {
  4026. // dot = 1;
  4027. // }
  4028. // if (dot < -1) {
  4029. // dot = -1;
  4030. // }
  4031. // return sign * Math.acos(dot);
  4032. // };
  4033. // const getArcCenter = (
  4034. // px: any,
  4035. // py: any,
  4036. // cx: any,
  4037. // cy: any,
  4038. // rx: number,
  4039. // ry: number,
  4040. // largeArcFlag: number,
  4041. // sweepFlag: number,
  4042. // sinphi: number,
  4043. // cosphi: number,
  4044. // pxp: number,
  4045. // pyp: number,
  4046. // ) => {
  4047. // const rxsq = Math.pow(rx, 2);
  4048. // const rysq = Math.pow(ry, 2);
  4049. // const pxpsq = Math.pow(pxp, 2);
  4050. // const pypsq = Math.pow(pyp, 2);
  4051. // let radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq;
  4052. // if (radicant < 0) {
  4053. // radicant = 0;
  4054. // }
  4055. // radicant /= rxsq * pypsq + rysq * pxpsq;
  4056. // radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);
  4057. // const centerxp = ((radicant * rx) / ry) * pyp;
  4058. // const centeryp = ((radicant * -ry) / rx) * pxp;
  4059. // const centerx = cosphi * centerxp - sinphi * centeryp + (px + cx) / 2;
  4060. // const centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2;
  4061. // const vx1 = (pxp - centerxp) / rx;
  4062. // const vy1 = (pyp - centeryp) / ry;
  4063. // const vx2 = (-pxp - centerxp) / rx;
  4064. // const vy2 = (-pyp - centeryp) / ry;
  4065. // const ang1 = vectorAngle(1, 0, vx1, vy1);
  4066. // let ang2 = vectorAngle(vx1, vy1, vx2, vy2);
  4067. // if (sweepFlag === 0 && ang2 > 0) {
  4068. // ang2 -= TAU;
  4069. // }
  4070. // if (sweepFlag === 1 && ang2 < 0) {
  4071. // ang2 += TAU;
  4072. // }
  4073. // return [centerx, centery, ang1, ang2];
  4074. // };
  4075. // const arcToBezier = ({ px, py, cx, cy, rx, ry, xAxisRotation = 0, largeArcFlag = 0, sweepFlag = 0 }) => {
  4076. // const curves = [];
  4077. // if (rx === 0 || ry === 0) {
  4078. // return [{ x1: 0, y1: 0, x2: 0, y2: 0, x: cx, y: cy }];
  4079. // }
  4080. // const sinphi = Math.sin((xAxisRotation * TAU) / 360);
  4081. // const cosphi = Math.cos((xAxisRotation * TAU) / 360);
  4082. // const pxp = (cosphi * (px - cx)) / 2 + (sinphi * (py - cy)) / 2;
  4083. // const pyp = (-sinphi * (px - cx)) / 2 + (cosphi * (py - cy)) / 2;
  4084. // if (pxp === 0 && pyp === 0) {
  4085. // return [{ x1: 0, y1: 0, x2: 0, y2: 0, x: cx, y: cy }];
  4086. // }
  4087. // rx = Math.abs(rx);
  4088. // ry = Math.abs(ry);
  4089. // const lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2);
  4090. // if (lambda > 1) {
  4091. // rx *= Math.sqrt(lambda);
  4092. // ry *= Math.sqrt(lambda);
  4093. // }
  4094. // let [centerx, centery, ang1, ang2] = getArcCenter(
  4095. // px,
  4096. // py,
  4097. // cx,
  4098. // cy,
  4099. // rx,
  4100. // ry,
  4101. // largeArcFlag,
  4102. // sweepFlag,
  4103. // sinphi,
  4104. // cosphi,
  4105. // pxp,
  4106. // pyp,
  4107. // );
  4108. // // If 'ang2' == 90.0000000001, then `ratio` will evaluate to
  4109. // // 1.0000000001. This causes `segments` to be greater than one, which is an
  4110. // // unecessary split, and adds extra points to the bezier curve. To alleviate
  4111. // // this issue, we round to 1.0 when the ratio is close to 1.0.
  4112. // let ratio = Math.abs(ang2) / (TAU / 4);
  4113. // if (Math.abs(1.0 - ratio) < 0.0000001) {
  4114. // ratio = 1.0;
  4115. // }
  4116. // const segments = Math.max(Math.ceil(ratio), 1);
  4117. // ang2 /= segments;
  4118. // for (let i = 0; i < segments; i++) {
  4119. // curves.push(approxUnitArc(ang1, ang2));
  4120. // ang1 += ang2;
  4121. // }
  4122. // return curves.map((curve) => {
  4123. // const { x: x1, y: y1 } = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery);
  4124. // const { x: x2, y: y2 } = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery);
  4125. // const { x, y } = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery);
  4126. // return { x1, y1, x2, y2, x, y };
  4127. // });
  4128. // };
  4129. // export function arcToCubic(
  4130. // x1: number,
  4131. // y1: number,
  4132. // rx: number,
  4133. // ry: number,
  4134. // angle: number,
  4135. // LAF: number,
  4136. // SF: number,
  4137. // x2: number,
  4138. // y2: number,
  4139. // ) {
  4140. // const curves = arcToBezier({
  4141. // px: x1,
  4142. // py: y1,
  4143. // cx: x2,
  4144. // cy: y2,
  4145. // rx,
  4146. // ry,
  4147. // xAxisRotation: angle,
  4148. // largeArcFlag: LAF,
  4149. // sweepFlag: SF,
  4150. // });
  4151. // return curves.reduce((prev, cur) => {
  4152. // const { x1, y1, x2, y2, x, y } = cur;
  4153. // prev.push(x1, y1, x2, y2, x, y);
  4154. // return prev;
  4155. // }, [] as number[]);
  4156. // }
  4157. function quadToCubic(x1, y1, qx, qy, x2, y2) {
  4158. var r13 = 1 / 3;
  4159. var r23 = 2 / 3;
  4160. return [
  4161. r13 * x1 + r23 * qx,
  4162. r13 * y1 + r23 * qy,
  4163. r13 * x2 + r23 * qx,
  4164. r13 * y2 + r23 * qy,
  4165. x2,
  4166. y2, // x,y
  4167. ];
  4168. }
  4169. function midPoint(a, b, t) {
  4170. var ax = a[0];
  4171. var ay = a[1];
  4172. var bx = b[0];
  4173. var by = b[1];
  4174. return [ax + (bx - ax) * t, ay + (by - ay) * t];
  4175. }
  4176. function distanceSquareRoot(a, b) {
  4177. return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]));
  4178. }
  4179. /**
  4180. * Returns a {x,y} point at a given length, the total length and
  4181. * the minimum and maximum {x,y} coordinates of a line (L,V,H,Z) segment.
  4182. */
  4183. function segmentLineFactory(x1, y1, x2, y2, distance) {
  4184. var length = distanceSquareRoot([x1, y1], [x2, y2]);
  4185. var point = { x: 0, y: 0 };
  4186. if (typeof distance === 'number') {
  4187. if (distance <= 0) {
  4188. point = { x: x1, y: y1 };
  4189. }
  4190. else if (distance >= length) {
  4191. point = { x: x2, y: y2 };
  4192. }
  4193. else {
  4194. var _a = midPoint([x1, y1], [x2, y2], distance / length), x = _a[0], y = _a[1];
  4195. point = { x: x, y: y };
  4196. }
  4197. }
  4198. return {
  4199. length: length,
  4200. point: point,
  4201. min: {
  4202. x: Math.min(x1, x2),
  4203. y: Math.min(y1, y2),
  4204. },
  4205. max: {
  4206. x: Math.max(x1, x2),
  4207. y: Math.max(y1, y2),
  4208. },
  4209. };
  4210. }
  4211. function lineToCubic(x1, y1, x2, y2) {
  4212. var t = 0.5;
  4213. var p0 = [x1, y1];
  4214. var p1 = [x2, y2];
  4215. var p2 = midPoint(p0, p1, t);
  4216. var p3 = midPoint(p1, p2, t);
  4217. var p4 = midPoint(p2, p3, t);
  4218. var p5 = midPoint(p3, p4, t);
  4219. var p6 = midPoint(p4, p5, t);
  4220. // const seg1 = [...p0, ...p2, ...p4, ...p6, t];
  4221. // @ts-ignore
  4222. var cp1 = segmentLineFactory(p0[0], p0[1], p2[0], p2[1], p4[0]).point;
  4223. // const seg2 = [...p6, ...p5, ...p3, ...p1, 0];
  4224. // @ts-ignore
  4225. var cp2 = segmentLineFactory(p6[0], p6[1], p5[0], p5[1], p3[0]).point;
  4226. return [cp1.x, cp1.y, cp2.x, cp2.y, x2, y2];
  4227. }
  4228. function segmentToCubic(segment, params) {
  4229. var pathCommand = segment[0];
  4230. var values = segment.slice(1).map(Number);
  4231. var x = values[0], y = values[1];
  4232. var args;
  4233. var px1 = params.x1, py1 = params.y1, px = params.x, py = params.y;
  4234. if (!'TQ'.includes(pathCommand)) {
  4235. params.qx = null;
  4236. params.qy = null;
  4237. }
  4238. switch (pathCommand) {
  4239. case 'M':
  4240. params.x = x;
  4241. params.y = y;
  4242. return segment;
  4243. case 'A':
  4244. args = [px1, py1].concat(values);
  4245. // @ts-ignore
  4246. return ['C'].concat(arcToCubic(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]));
  4247. case 'Q':
  4248. params.qx = x;
  4249. params.qy = y;
  4250. args = [px1, py1].concat(values);
  4251. // @ts-ignore
  4252. return ['C'].concat(quadToCubic(args[0], args[1], args[2], args[3], args[4], args[5]));
  4253. case 'L':
  4254. // @ts-ignore
  4255. return ['C'].concat(lineToCubic(px1, py1, x, y));
  4256. case 'Z':
  4257. // prevent NaN from divide 0
  4258. if (px1 === px && py1 === py) {
  4259. return ['C', px1, py1, px, py, px, py];
  4260. }
  4261. // @ts-ignore
  4262. return ['C'].concat(lineToCubic(px1, py1, px, py));
  4263. }
  4264. return segment;
  4265. }
  4266. // import { fixPath } from '../process/fix-path';
  4267. function path2Curve(pathInput, needZCommandIndexes) {
  4268. if (needZCommandIndexes === void 0) { needZCommandIndexes = false; }
  4269. if (isCurveArray(pathInput)) {
  4270. var cloned = clonePath(pathInput);
  4271. if (needZCommandIndexes) {
  4272. return [cloned, []];
  4273. }
  4274. else {
  4275. return cloned;
  4276. }
  4277. }
  4278. // fixPath will remove 'Z' command
  4279. // const path = fixPath(normalizePath(pathInput));
  4280. var path = normalizePath(pathInput);
  4281. var params = __assign({}, paramsParser);
  4282. var allPathCommands = [];
  4283. var pathCommand = '';
  4284. var ii = path.length;
  4285. var segment;
  4286. var seglen;
  4287. var zCommandIndexes = [];
  4288. for (var i = 0; i < ii; i += 1) {
  4289. if (path[i])
  4290. pathCommand = path[i][0];
  4291. allPathCommands[i] = pathCommand;
  4292. var curveSegment = segmentToCubic(path[i], params);
  4293. path[i] = curveSegment;
  4294. fixArc(path, allPathCommands, i);
  4295. ii = path.length; // solves curveArrays ending in Z
  4296. // keep Z command account for lineJoin
  4297. // @see https://github.com/antvis/util/issues/68
  4298. if (pathCommand === 'Z') {
  4299. zCommandIndexes.push(i);
  4300. }
  4301. segment = path[i];
  4302. seglen = segment.length;
  4303. params.x1 = +segment[seglen - 2];
  4304. params.y1 = +segment[seglen - 1];
  4305. params.x2 = +segment[seglen - 4] || params.x1;
  4306. params.y2 = +segment[seglen - 3] || params.y1;
  4307. }
  4308. // validate
  4309. if (needZCommandIndexes) {
  4310. return [path, zCommandIndexes];
  4311. }
  4312. else {
  4313. return path;
  4314. }
  4315. }
  4316. // reverse CURVE based pathArray segments only
  4317. function reverseCurve(pathArray) {
  4318. var rotatedCurve = pathArray
  4319. .slice(1)
  4320. .map(function (x, i, curveOnly) {
  4321. // @ts-ignore
  4322. return !i ? pathArray[0].slice(1).concat(x.slice(1)) : curveOnly[i - 1].slice(-2).concat(x.slice(1));
  4323. })
  4324. // @ts-ignore
  4325. .map(function (x) { return x.map(function (y, i) { return x[x.length - i - 2 * (1 - (i % 2))]; }); })
  4326. .reverse();
  4327. return [['M'].concat(rotatedCurve[0].slice(0, 2))].concat(rotatedCurve.map(function (x) { return ['C'].concat(x.slice(2)); }));
  4328. }
  4329. function angleBetween(v0, v1) {
  4330. var v0x = v0.x, v0y = v0.y;
  4331. var v1x = v1.x, v1y = v1.y;
  4332. var p = v0x * v1x + v0y * v1y;
  4333. var n = Math.sqrt((Math.pow(v0x, 2) + Math.pow(v0y, 2)) * (Math.pow(v1x, 2) + Math.pow(v1y, 2)));
  4334. var sign = v0x * v1y - v0y * v1x < 0 ? -1 : 1;
  4335. var angle = sign * Math.acos(p / n);
  4336. return angle;
  4337. }
  4338. /**
  4339. * Returns a {x,y} point at a given length, the total length and
  4340. * the minimum and maximum {x,y} coordinates of a C (cubic-bezier) segment.
  4341. * @see https://github.com/MadLittleMods/svg-curve-lib/blob/master/src/js/svg-curve-lib.js
  4342. */
  4343. function getPointAtArcSegmentLength(x1, y1, RX, RY, angle, LAF, SF, x, y, t) {
  4344. var abs = Math.abs, sin = Math.sin, cos = Math.cos, sqrt = Math.sqrt, PI = Math.PI;
  4345. var rx = abs(RX);
  4346. var ry = abs(RY);
  4347. var xRot = ((angle % 360) + 360) % 360;
  4348. var xRotRad = xRot * (PI / 180);
  4349. if (x1 === x && y1 === y) {
  4350. return { x: x1, y: y1 };
  4351. }
  4352. if (rx === 0 || ry === 0) {
  4353. return segmentLineFactory(x1, y1, x, y, t).point;
  4354. }
  4355. var dx = (x1 - x) / 2;
  4356. var dy = (y1 - y) / 2;
  4357. var transformedPoint = {
  4358. x: cos(xRotRad) * dx + sin(xRotRad) * dy,
  4359. y: -sin(xRotRad) * dx + cos(xRotRad) * dy,
  4360. };
  4361. var radiiCheck = Math.pow(transformedPoint.x, 2) / Math.pow(rx, 2) + Math.pow(transformedPoint.y, 2) / Math.pow(ry, 2);
  4362. if (radiiCheck > 1) {
  4363. rx *= sqrt(radiiCheck);
  4364. ry *= sqrt(radiiCheck);
  4365. }
  4366. 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);
  4367. var cSquareRootDenom = Math.pow(rx, 2) * Math.pow(transformedPoint.y, 2) + Math.pow(ry, 2) * Math.pow(transformedPoint.x, 2);
  4368. var cRadicand = cSquareNumerator / cSquareRootDenom;
  4369. cRadicand = cRadicand < 0 ? 0 : cRadicand;
  4370. var cCoef = (LAF !== SF ? 1 : -1) * sqrt(cRadicand);
  4371. var transformedCenter = {
  4372. x: cCoef * ((rx * transformedPoint.y) / ry),
  4373. y: cCoef * (-(ry * transformedPoint.x) / rx),
  4374. };
  4375. var center = {
  4376. x: cos(xRotRad) * transformedCenter.x - sin(xRotRad) * transformedCenter.y + (x1 + x) / 2,
  4377. y: sin(xRotRad) * transformedCenter.x + cos(xRotRad) * transformedCenter.y + (y1 + y) / 2,
  4378. };
  4379. var startVector = {
  4380. x: (transformedPoint.x - transformedCenter.x) / rx,
  4381. y: (transformedPoint.y - transformedCenter.y) / ry,
  4382. };
  4383. var startAngle = angleBetween({ x: 1, y: 0 }, startVector);
  4384. var endVector = {
  4385. x: (-transformedPoint.x - transformedCenter.x) / rx,
  4386. y: (-transformedPoint.y - transformedCenter.y) / ry,
  4387. };
  4388. var sweepAngle = angleBetween(startVector, endVector);
  4389. if (!SF && sweepAngle > 0) {
  4390. sweepAngle -= 2 * PI;
  4391. }
  4392. else if (SF && sweepAngle < 0) {
  4393. sweepAngle += 2 * PI;
  4394. }
  4395. sweepAngle %= 2 * PI;
  4396. var alpha = startAngle + sweepAngle * t;
  4397. var ellipseComponentX = rx * cos(alpha);
  4398. var ellipseComponentY = ry * sin(alpha);
  4399. var point = {
  4400. x: cos(xRotRad) * ellipseComponentX - sin(xRotRad) * ellipseComponentY + center.x,
  4401. y: sin(xRotRad) * ellipseComponentX + cos(xRotRad) * ellipseComponentY + center.y,
  4402. };
  4403. // to be used later
  4404. // point.ellipticalArcStartAngle = startAngle;
  4405. // point.ellipticalArcEndAngle = startAngle + sweepAngle;
  4406. // point.ellipticalArcAngle = alpha;
  4407. // point.ellipticalArcCenter = center;
  4408. // point.resultantRx = rx;
  4409. // point.resultantRy = ry;
  4410. return point;
  4411. }
  4412. /**
  4413. * Returns a {x,y} point at a given length, the total length and
  4414. * the shape minimum and maximum {x,y} coordinates of an A (arc-to) segment.
  4415. *
  4416. * For better performance, it can skip calculate bbox or length in some scenario.
  4417. */
  4418. function segmentArcFactory(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, distance, options) {
  4419. var _a;
  4420. 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;
  4421. var distanceIsNumber = typeof distance === 'number';
  4422. var x = X1;
  4423. var y = Y1;
  4424. var LENGTH = 0;
  4425. var prev = [x, y, LENGTH];
  4426. var cur = [x, y];
  4427. var t = 0;
  4428. var POINT = { x: 0, y: 0 };
  4429. var POINTS = [{ x: x, y: y }];
  4430. if (distanceIsNumber && distance <= 0) {
  4431. POINT = { x: x, y: y };
  4432. }
  4433. // bad perf when size > 100
  4434. for (var j = 0; j <= sampleSize; j += 1) {
  4435. t = j / sampleSize;
  4436. (_a = getPointAtArcSegmentLength(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, t), x = _a.x, y = _a.y);
  4437. if (bbox) {
  4438. POINTS.push({ x: x, y: y });
  4439. }
  4440. if (length) {
  4441. LENGTH += distanceSquareRoot(cur, [x, y]);
  4442. }
  4443. cur = [x, y];
  4444. if (distanceIsNumber && LENGTH >= distance && distance > prev[2]) {
  4445. var dv = (LENGTH - distance) / (LENGTH - prev[2]);
  4446. POINT = {
  4447. x: cur[0] * (1 - dv) + prev[0] * dv,
  4448. y: cur[1] * (1 - dv) + prev[1] * dv,
  4449. };
  4450. }
  4451. prev = [x, y, LENGTH];
  4452. }
  4453. if (distanceIsNumber && distance >= LENGTH) {
  4454. POINT = { x: X2, y: Y2 };
  4455. }
  4456. return {
  4457. length: LENGTH,
  4458. point: POINT,
  4459. min: {
  4460. x: Math.min.apply(null, POINTS.map(function (n) { return n.x; })),
  4461. y: Math.min.apply(null, POINTS.map(function (n) { return n.y; })),
  4462. },
  4463. max: {
  4464. x: Math.max.apply(null, POINTS.map(function (n) { return n.x; })),
  4465. y: Math.max.apply(null, POINTS.map(function (n) { return n.y; })),
  4466. },
  4467. };
  4468. }
  4469. /**
  4470. * Returns a {x,y} point at a given length, the total length and
  4471. * the minimum and maximum {x,y} coordinates of a C (cubic-bezier) segment.
  4472. */
  4473. function getPointAtCubicSegmentLength(x1, y1, c1x, c1y, c2x, c2y, x2, y2, t) {
  4474. var t1 = 1 - t;
  4475. return {
  4476. 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,
  4477. 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,
  4478. };
  4479. }
  4480. /**
  4481. * Returns the length of a C (cubic-bezier) segment
  4482. * or an {x,y} point at a given length.
  4483. */
  4484. function segmentCubicFactory(x1, y1, c1x, c1y, c2x, c2y, x2, y2, distance, options) {
  4485. var _a;
  4486. 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;
  4487. var distanceIsNumber = typeof distance === 'number';
  4488. var x = x1;
  4489. var y = y1;
  4490. var LENGTH = 0;
  4491. var prev = [x, y, LENGTH];
  4492. var cur = [x, y];
  4493. var t = 0;
  4494. var POINT = { x: 0, y: 0 };
  4495. var POINTS = [{ x: x, y: y }];
  4496. if (distanceIsNumber && distance <= 0) {
  4497. POINT = { x: x, y: y };
  4498. }
  4499. // bad perf when size = 300
  4500. for (var j = 0; j <= sampleSize; j += 1) {
  4501. t = j / sampleSize;
  4502. (_a = getPointAtCubicSegmentLength(x1, y1, c1x, c1y, c2x, c2y, x2, y2, t), x = _a.x, y = _a.y);
  4503. if (bbox) {
  4504. POINTS.push({ x: x, y: y });
  4505. }
  4506. if (length) {
  4507. LENGTH += distanceSquareRoot(cur, [x, y]);
  4508. }
  4509. cur = [x, y];
  4510. if (distanceIsNumber && LENGTH >= distance && distance > prev[2]) {
  4511. var dv = (LENGTH - distance) / (LENGTH - prev[2]);
  4512. POINT = {
  4513. x: cur[0] * (1 - dv) + prev[0] * dv,
  4514. y: cur[1] * (1 - dv) + prev[1] * dv,
  4515. };
  4516. }
  4517. prev = [x, y, LENGTH];
  4518. }
  4519. if (distanceIsNumber && distance >= LENGTH) {
  4520. POINT = { x: x2, y: y2 };
  4521. }
  4522. return {
  4523. length: LENGTH,
  4524. point: POINT,
  4525. min: {
  4526. x: Math.min.apply(null, POINTS.map(function (n) { return n.x; })),
  4527. y: Math.min.apply(null, POINTS.map(function (n) { return n.y; })),
  4528. },
  4529. max: {
  4530. x: Math.max.apply(null, POINTS.map(function (n) { return n.x; })),
  4531. y: Math.max.apply(null, POINTS.map(function (n) { return n.y; })),
  4532. },
  4533. };
  4534. }
  4535. /**
  4536. * Returns the {x,y} coordinates of a point at a
  4537. * given length of a quadratic-bezier segment.
  4538. *
  4539. * @see https://github.com/substack/point-at-length
  4540. */
  4541. function getPointAtQuadSegmentLength(x1, y1, cx, cy, x2, y2, t) {
  4542. var t1 = 1 - t;
  4543. return {
  4544. x: Math.pow(t1, 2) * x1 + 2 * t1 * t * cx + Math.pow(t, 2) * x2,
  4545. y: Math.pow(t1, 2) * y1 + 2 * t1 * t * cy + Math.pow(t, 2) * y2,
  4546. };
  4547. }
  4548. /**
  4549. * Returns a {x,y} point at a given length, the total length and
  4550. * the minimum and maximum {x,y} coordinates of a Q (quadratic-bezier) segment.
  4551. */
  4552. function segmentQuadFactory(x1, y1, qx, qy, x2, y2, distance, options) {
  4553. var _a;
  4554. 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;
  4555. var distanceIsNumber = typeof distance === 'number';
  4556. var x = x1;
  4557. var y = y1;
  4558. var LENGTH = 0;
  4559. var prev = [x, y, LENGTH];
  4560. var cur = [x, y];
  4561. var t = 0;
  4562. var POINT = { x: 0, y: 0 };
  4563. var POINTS = [{ x: x, y: y }];
  4564. if (distanceIsNumber && distance <= 0) {
  4565. POINT = { x: x, y: y };
  4566. }
  4567. for (var j = 0; j <= sampleSize; j += 1) {
  4568. t = j / sampleSize;
  4569. (_a = getPointAtQuadSegmentLength(x1, y1, qx, qy, x2, y2, t), x = _a.x, y = _a.y);
  4570. if (bbox) {
  4571. POINTS.push({ x: x, y: y });
  4572. }
  4573. if (length) {
  4574. LENGTH += distanceSquareRoot(cur, [x, y]);
  4575. }
  4576. cur = [x, y];
  4577. if (distanceIsNumber && LENGTH >= distance && distance > prev[2]) {
  4578. var dv = (LENGTH - distance) / (LENGTH - prev[2]);
  4579. POINT = {
  4580. x: cur[0] * (1 - dv) + prev[0] * dv,
  4581. y: cur[1] * (1 - dv) + prev[1] * dv,
  4582. };
  4583. }
  4584. prev = [x, y, LENGTH];
  4585. }
  4586. /* istanbul ignore else */
  4587. if (distanceIsNumber && distance >= LENGTH) {
  4588. POINT = { x: x2, y: y2 };
  4589. }
  4590. return {
  4591. length: LENGTH,
  4592. point: POINT,
  4593. min: {
  4594. x: Math.min.apply(null, POINTS.map(function (n) { return n.x; })),
  4595. y: Math.min.apply(null, POINTS.map(function (n) { return n.y; })),
  4596. },
  4597. max: {
  4598. x: Math.max.apply(null, POINTS.map(function (n) { return n.x; })),
  4599. y: Math.max.apply(null, POINTS.map(function (n) { return n.y; })),
  4600. },
  4601. };
  4602. }
  4603. /**
  4604. * Returns a {x,y} point at a given length
  4605. * of a shape, the shape total length and
  4606. * the shape minimum and maximum {x,y} coordinates.
  4607. */
  4608. function pathLengthFactory(pathInput, distance, options) {
  4609. var _a, _b, _c, _d, _e, _f;
  4610. var path = normalizePath(pathInput);
  4611. var distanceIsNumber = typeof distance === 'number';
  4612. var isM;
  4613. var data = [];
  4614. var pathCommand;
  4615. var x = 0;
  4616. var y = 0;
  4617. var mx = 0;
  4618. var my = 0;
  4619. var seg;
  4620. var MIN = [];
  4621. var MAX = [];
  4622. var length = 0;
  4623. var min = { x: 0, y: 0 };
  4624. var max = min;
  4625. var point = min;
  4626. var POINT = min;
  4627. var LENGTH = 0;
  4628. for (var i = 0, ll = path.length; i < ll; i += 1) {
  4629. seg = path[i];
  4630. pathCommand = seg[0];
  4631. isM = pathCommand === 'M';
  4632. data = !isM ? [x, y].concat(seg.slice(1)) : data;
  4633. // this segment is always ZERO
  4634. /* istanbul ignore else */
  4635. if (isM) {
  4636. // remember mx, my for Z
  4637. mx = seg[1], my = seg[2];
  4638. min = { x: mx, y: my };
  4639. max = min;
  4640. length = 0;
  4641. if (distanceIsNumber && distance < 0.001) {
  4642. POINT = min;
  4643. }
  4644. }
  4645. else if (pathCommand === 'L') {
  4646. (_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);
  4647. }
  4648. else if (pathCommand === 'A') {
  4649. (_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);
  4650. }
  4651. else if (pathCommand === 'C') {
  4652. (_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);
  4653. }
  4654. else if (pathCommand === 'Q') {
  4655. (_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);
  4656. }
  4657. else if (pathCommand === 'Z') {
  4658. data = [x, y, mx, my];
  4659. (_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);
  4660. }
  4661. if (distanceIsNumber && LENGTH < distance && LENGTH + length >= distance) {
  4662. POINT = point;
  4663. }
  4664. MAX.push(max);
  4665. MIN.push(min);
  4666. LENGTH += length;
  4667. _f = pathCommand !== 'Z' ? seg.slice(-2) : [mx, my], x = _f[0], y = _f[1];
  4668. }
  4669. // native `getPointAtLength` behavior when the given distance
  4670. // is higher than total length
  4671. if (distanceIsNumber && distance >= LENGTH) {
  4672. POINT = { x: x, y: y };
  4673. }
  4674. return {
  4675. length: LENGTH,
  4676. point: POINT,
  4677. min: {
  4678. x: Math.min.apply(null, MIN.map(function (n) { return n.x; })),
  4679. y: Math.min.apply(null, MIN.map(function (n) { return n.y; })),
  4680. },
  4681. max: {
  4682. x: Math.max.apply(null, MAX.map(function (n) { return n.x; })),
  4683. y: Math.max.apply(null, MAX.map(function (n) { return n.y; })),
  4684. },
  4685. };
  4686. }
  4687. /**
  4688. * Returns the shape total length, or the equivalent to `shape.getTotalLength()`.
  4689. *
  4690. * The `normalizePath` version is lighter, faster, more efficient and more accurate
  4691. * with paths that are not `curveArray`.
  4692. */
  4693. function getTotalLength(pathInput, options) {
  4694. return pathLengthFactory(pathInput, undefined, __assign(__assign({}, options), { bbox: false, length: true })).length;
  4695. }
  4696. function getRotations(a) {
  4697. var segCount = a.length;
  4698. var pointCount = segCount - 1;
  4699. return a.map(function (f, idx) {
  4700. return a.map(function (p, i) {
  4701. var oldSegIdx = idx + i;
  4702. var seg;
  4703. if (i === 0 || (a[oldSegIdx] && a[oldSegIdx][0] === 'M')) {
  4704. seg = a[oldSegIdx];
  4705. return ['M'].concat(seg.slice(-2));
  4706. }
  4707. if (oldSegIdx >= segCount)
  4708. oldSegIdx -= pointCount;
  4709. return a[oldSegIdx];
  4710. });
  4711. });
  4712. }
  4713. function getRotatedCurve(a, b) {
  4714. var segCount = a.length - 1;
  4715. var lineLengths = [];
  4716. var computedIndex = 0;
  4717. var sumLensSqrd = 0;
  4718. var rotations = getRotations(a);
  4719. rotations.forEach(function (r, i) {
  4720. a.slice(1).forEach(function (s, j) {
  4721. // @ts-ignore
  4722. sumLensSqrd += distanceSquareRoot(a[(i + j) % segCount].slice(-2), b[j % segCount].slice(-2));
  4723. });
  4724. lineLengths[i] = sumLensSqrd;
  4725. sumLensSqrd = 0;
  4726. });
  4727. computedIndex = lineLengths.indexOf(Math.min.apply(null, lineLengths));
  4728. return rotations[computedIndex];
  4729. }
  4730. /**
  4731. * Returns the area of a single cubic-bezier segment.
  4732. *
  4733. * http://objectmix.com/graphics/133553-area-closed-bezier-curve.html
  4734. */
  4735. function getCubicSegArea(x1, y1, c1x, c1y, c2x, c2y, x2, y2) {
  4736. // https://stackoverflow.com/a/15845996
  4737. return ((3 *
  4738. ((y2 - y1) * (c1x + c2x) -
  4739. (x2 - x1) * (c1y + c2y) +
  4740. c1y * (x1 - c2x) -
  4741. c1x * (y1 - c2y) +
  4742. y2 * (c2x + x1 / 3) -
  4743. x2 * (c2y + y1 / 3))) /
  4744. 20);
  4745. }
  4746. /**
  4747. * Returns the area of a shape.
  4748. * @author Jürg Lehni & Jonathan Puckey
  4749. *
  4750. * @see https://github.com/paperjs/paper.js/blob/develop/src/path/Path.js
  4751. */
  4752. function getPathArea(path) {
  4753. var x = 0;
  4754. var y = 0;
  4755. var len = 0;
  4756. return path2Curve(path)
  4757. .map(function (seg) {
  4758. var _a;
  4759. switch (seg[0]) {
  4760. case 'M':
  4761. x = seg[1], y = seg[2];
  4762. return 0;
  4763. default:
  4764. // @ts-ignore
  4765. var _b = seg.slice(1), c1x = _b[0], c1y = _b[1], c2x = _b[2], c2y = _b[3], x2 = _b[4], y2 = _b[5];
  4766. len = getCubicSegArea(x, y, c1x, c1y, c2x, c2y, x2, y2);
  4767. _a = seg.slice(-2), x = _a[0], y = _a[1];
  4768. return len;
  4769. }
  4770. })
  4771. .reduce(function (a, b) { return a + b; }, 0);
  4772. }
  4773. // export function getPathArea(pathArray: AbsoluteArray) {
  4774. // let x = 0;
  4775. // let y = 0;
  4776. // let mx = 0;
  4777. // let my = 0;
  4778. // let len = 0;
  4779. // return pathArray
  4780. // .map((seg) => {
  4781. // switch (seg[0]) {
  4782. // case 'M':
  4783. // case 'Z':
  4784. // mx = seg[0] === 'M' ? seg[1] : mx;
  4785. // my = seg[0] === 'M' ? seg[2] : my;
  4786. // x = mx;
  4787. // y = my;
  4788. // return 0;
  4789. // default:
  4790. // // @ts-ignore
  4791. // len = getCubicSegArea.apply(0, [x, y].concat(seg.slice(1)));
  4792. // [x, y] = seg.slice(-2) as [number, number];
  4793. // return len;
  4794. // }
  4795. // })
  4796. // .reduce((a, b) => a + b, 0);
  4797. // }
  4798. function getDrawDirection(pathArray) {
  4799. return getPathArea(pathArray) >= 0;
  4800. }
  4801. /**
  4802. * Returns [x,y] coordinates of a point at a given length of a shape.
  4803. */
  4804. function getPointAtLength(pathInput, distance, options) {
  4805. return pathLengthFactory(pathInput, distance, __assign(__assign({}, options), { bbox: false, length: true })).point;
  4806. }
  4807. function splitCubic(pts, t) {
  4808. if (t === void 0) { t = 0.5; }
  4809. var p0 = pts.slice(0, 2);
  4810. var p1 = pts.slice(2, 4);
  4811. var p2 = pts.slice(4, 6);
  4812. var p3 = pts.slice(6, 8);
  4813. var p4 = midPoint(p0, p1, t);
  4814. var p5 = midPoint(p1, p2, t);
  4815. var p6 = midPoint(p2, p3, t);
  4816. var p7 = midPoint(p4, p5, t);
  4817. var p8 = midPoint(p5, p6, t);
  4818. var p9 = midPoint(p7, p8, t);
  4819. return [
  4820. // @ts-ignore
  4821. ['C'].concat(p4, p7, p9),
  4822. // @ts-ignore
  4823. ['C'].concat(p8, p6, p3),
  4824. ];
  4825. }
  4826. function getCurveArray(segments) {
  4827. return segments.map(function (segment, i, pathArray) {
  4828. // @ts-ignore
  4829. var segmentData = i && pathArray[i - 1].slice(-2).concat(segment.slice(1));
  4830. // @ts-ignore
  4831. var curveLength = i
  4832. ? segmentCubicFactory(segmentData[0], segmentData[1], segmentData[2], segmentData[3], segmentData[4], segmentData[5], segmentData[6], segmentData[7], segmentData[8], { bbox: false }).length
  4833. : 0;
  4834. var subsegs;
  4835. if (i) {
  4836. // must be [segment,segment]
  4837. subsegs = curveLength ? splitCubic(segmentData) : [segment, segment];
  4838. }
  4839. else {
  4840. subsegs = [segment];
  4841. }
  4842. return {
  4843. s: segment,
  4844. ss: subsegs,
  4845. l: curveLength,
  4846. };
  4847. });
  4848. }
  4849. function equalizeSegments(path1, path2, TL) {
  4850. var c1 = getCurveArray(path1);
  4851. var c2 = getCurveArray(path2);
  4852. var L1 = c1.length;
  4853. var L2 = c2.length;
  4854. var l1 = c1.filter(function (x) { return x.l; }).length;
  4855. var l2 = c2.filter(function (x) { return x.l; }).length;
  4856. var m1 = c1.filter(function (x) { return x.l; }).reduce(function (a, _a) {
  4857. var l = _a.l;
  4858. return a + l;
  4859. }, 0) / l1 || 0;
  4860. var m2 = c2.filter(function (x) { return x.l; }).reduce(function (a, _a) {
  4861. var l = _a.l;
  4862. return a + l;
  4863. }, 0) / l2 || 0;
  4864. var tl = TL || Math.max(L1, L2);
  4865. var mm = [m1, m2];
  4866. var dif = [tl - L1, tl - L2];
  4867. var canSplit = 0;
  4868. var result = [c1, c2].map(function (x, i) {
  4869. // @ts-ignore
  4870. return x.l === tl
  4871. ? x.map(function (y) { return y.s; })
  4872. : x
  4873. .map(function (y, j) {
  4874. canSplit = j && dif[i] && y.l >= mm[i];
  4875. dif[i] -= canSplit ? 1 : 0;
  4876. return canSplit ? y.ss : [y.s];
  4877. })
  4878. .flat();
  4879. });
  4880. return result[0].length === result[1].length ? result : equalizeSegments(result[0], result[1], tl);
  4881. }
  4882. // isFinite,
  4883. var isNil = function (value) {
  4884. /**
  4885. * isNil(null) => true
  4886. * isNil() => true
  4887. */
  4888. return value === null || value === undefined;
  4889. };
  4890. var toString = {}.toString;
  4891. var isType = function (value, type) { return toString.call(value) === '[object ' + type + ']'; };
  4892. var isArray = (function (value) {
  4893. return Array.isArray ? Array.isArray(value) : isType(value, 'Array');
  4894. });
  4895. var isObject = (function (value) {
  4896. /**
  4897. * isObject({}) => true
  4898. * isObject([1, 2, 3]) => true
  4899. * isObject(Function) => true
  4900. * isObject(null) => false
  4901. */
  4902. var type = typeof value;
  4903. return (value !== null && type === 'object') || type === 'function';
  4904. });
  4905. /**
  4906. * @param {Array} arr The array to iterate over.
  4907. * @return {*} Returns the maximum value.
  4908. * @example
  4909. *
  4910. * max([1, 2]);
  4911. * // => 2
  4912. *
  4913. * max([]);
  4914. * // => undefined
  4915. *
  4916. * const data = new Array(1250010).fill(1).map((d,idx) => idx);
  4917. *
  4918. * max(data);
  4919. * // => 1250010
  4920. * // Math.max(...data) will encounter "Maximum call stack size exceeded" error
  4921. */
  4922. var max = (function (arr) {
  4923. if (!isArray(arr)) {
  4924. return undefined;
  4925. }
  4926. return arr.reduce(function (prev, curr) {
  4927. return Math.max(prev, curr);
  4928. }, arr[0]);
  4929. });
  4930. /**
  4931. * @param {Array} arr The array to iterate over.
  4932. * @return {*} Returns the minimum value.
  4933. * @example
  4934. *
  4935. * min([1, 2]);
  4936. * // => 1
  4937. *
  4938. * min([]);
  4939. * // => undefined
  4940. *
  4941. * const data = new Array(1250010).fill(1).map((d,idx) => idx);
  4942. *
  4943. * min(data);
  4944. * // => 1250010
  4945. * // Math.min(...data) will encounter "Maximum call stack size exceeded" error
  4946. */
  4947. var min = (function (arr) {
  4948. if (!isArray(arr)) {
  4949. return undefined;
  4950. }
  4951. return arr.reduce(function (prev, curr) {
  4952. return Math.min(prev, curr);
  4953. }, arr[0]);
  4954. });
  4955. var isString = (function (str) {
  4956. return isType(str, 'String');
  4957. });
  4958. var clamp = function (a, min, max) {
  4959. if (a < min) {
  4960. return min;
  4961. }
  4962. else if (a > max) {
  4963. return max;
  4964. }
  4965. return a;
  4966. };
  4967. /**
  4968. * 判断是否数字
  4969. * @return {Boolean} 是否数字
  4970. */
  4971. var isNumber = function (value) {
  4972. return isType(value, 'Number');
  4973. };
  4974. var PRECISION = 0.00001; // numbers less than this is considered as 0
  4975. function isNumberEqual(a, b, precision) {
  4976. if (precision === void 0) { precision = PRECISION; }
  4977. return Math.abs(a - b) < precision;
  4978. }
  4979. var mod = function (n, m) {
  4980. return ((n % m) + m) % m;
  4981. };
  4982. /**
  4983. * 是否是布尔类型
  4984. *
  4985. * @param {Object} value 测试的值
  4986. * @return {Boolean}
  4987. */
  4988. var isBoolean = function (value) {
  4989. return isType(value, 'Boolean');
  4990. };
  4991. var isUndefined = function (value) {
  4992. return value === undefined;
  4993. };
  4994. function define(constructor, factory, prototype) {
  4995. constructor.prototype = factory.prototype = prototype;
  4996. prototype.constructor = constructor;
  4997. }
  4998. function extend(parent, definition) {
  4999. var prototype = Object.create(parent.prototype);
  5000. for (var key in definition) prototype[key] = definition[key];
  5001. return prototype;
  5002. }
  5003. function Color() {}
  5004. var darker = 0.7;
  5005. var brighter = 1 / darker;
  5006. var reI = "\\s*([+-]?\\d+)\\s*",
  5007. reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",
  5008. reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",
  5009. reHex = /^#([0-9a-f]{3,8})$/,
  5010. reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"),
  5011. reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"),
  5012. reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"),
  5013. reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"),
  5014. reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"),
  5015. reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$");
  5016. var named = {
  5017. aliceblue: 0xf0f8ff,
  5018. antiquewhite: 0xfaebd7,
  5019. aqua: 0x00ffff,
  5020. aquamarine: 0x7fffd4,
  5021. azure: 0xf0ffff,
  5022. beige: 0xf5f5dc,
  5023. bisque: 0xffe4c4,
  5024. black: 0x000000,
  5025. blanchedalmond: 0xffebcd,
  5026. blue: 0x0000ff,
  5027. blueviolet: 0x8a2be2,
  5028. brown: 0xa52a2a,
  5029. burlywood: 0xdeb887,
  5030. cadetblue: 0x5f9ea0,
  5031. chartreuse: 0x7fff00,
  5032. chocolate: 0xd2691e,
  5033. coral: 0xff7f50,
  5034. cornflowerblue: 0x6495ed,
  5035. cornsilk: 0xfff8dc,
  5036. crimson: 0xdc143c,
  5037. cyan: 0x00ffff,
  5038. darkblue: 0x00008b,
  5039. darkcyan: 0x008b8b,
  5040. darkgoldenrod: 0xb8860b,
  5041. darkgray: 0xa9a9a9,
  5042. darkgreen: 0x006400,
  5043. darkgrey: 0xa9a9a9,
  5044. darkkhaki: 0xbdb76b,
  5045. darkmagenta: 0x8b008b,
  5046. darkolivegreen: 0x556b2f,
  5047. darkorange: 0xff8c00,
  5048. darkorchid: 0x9932cc,
  5049. darkred: 0x8b0000,
  5050. darksalmon: 0xe9967a,
  5051. darkseagreen: 0x8fbc8f,
  5052. darkslateblue: 0x483d8b,
  5053. darkslategray: 0x2f4f4f,
  5054. darkslategrey: 0x2f4f4f,
  5055. darkturquoise: 0x00ced1,
  5056. darkviolet: 0x9400d3,
  5057. deeppink: 0xff1493,
  5058. deepskyblue: 0x00bfff,
  5059. dimgray: 0x696969,
  5060. dimgrey: 0x696969,
  5061. dodgerblue: 0x1e90ff,
  5062. firebrick: 0xb22222,
  5063. floralwhite: 0xfffaf0,
  5064. forestgreen: 0x228b22,
  5065. fuchsia: 0xff00ff,
  5066. gainsboro: 0xdcdcdc,
  5067. ghostwhite: 0xf8f8ff,
  5068. gold: 0xffd700,
  5069. goldenrod: 0xdaa520,
  5070. gray: 0x808080,
  5071. green: 0x008000,
  5072. greenyellow: 0xadff2f,
  5073. grey: 0x808080,
  5074. honeydew: 0xf0fff0,
  5075. hotpink: 0xff69b4,
  5076. indianred: 0xcd5c5c,
  5077. indigo: 0x4b0082,
  5078. ivory: 0xfffff0,
  5079. khaki: 0xf0e68c,
  5080. lavender: 0xe6e6fa,
  5081. lavenderblush: 0xfff0f5,
  5082. lawngreen: 0x7cfc00,
  5083. lemonchiffon: 0xfffacd,
  5084. lightblue: 0xadd8e6,
  5085. lightcoral: 0xf08080,
  5086. lightcyan: 0xe0ffff,
  5087. lightgoldenrodyellow: 0xfafad2,
  5088. lightgray: 0xd3d3d3,
  5089. lightgreen: 0x90ee90,
  5090. lightgrey: 0xd3d3d3,
  5091. lightpink: 0xffb6c1,
  5092. lightsalmon: 0xffa07a,
  5093. lightseagreen: 0x20b2aa,
  5094. lightskyblue: 0x87cefa,
  5095. lightslategray: 0x778899,
  5096. lightslategrey: 0x778899,
  5097. lightsteelblue: 0xb0c4de,
  5098. lightyellow: 0xffffe0,
  5099. lime: 0x00ff00,
  5100. limegreen: 0x32cd32,
  5101. linen: 0xfaf0e6,
  5102. magenta: 0xff00ff,
  5103. maroon: 0x800000,
  5104. mediumaquamarine: 0x66cdaa,
  5105. mediumblue: 0x0000cd,
  5106. mediumorchid: 0xba55d3,
  5107. mediumpurple: 0x9370db,
  5108. mediumseagreen: 0x3cb371,
  5109. mediumslateblue: 0x7b68ee,
  5110. mediumspringgreen: 0x00fa9a,
  5111. mediumturquoise: 0x48d1cc,
  5112. mediumvioletred: 0xc71585,
  5113. midnightblue: 0x191970,
  5114. mintcream: 0xf5fffa,
  5115. mistyrose: 0xffe4e1,
  5116. moccasin: 0xffe4b5,
  5117. navajowhite: 0xffdead,
  5118. navy: 0x000080,
  5119. oldlace: 0xfdf5e6,
  5120. olive: 0x808000,
  5121. olivedrab: 0x6b8e23,
  5122. orange: 0xffa500,
  5123. orangered: 0xff4500,
  5124. orchid: 0xda70d6,
  5125. palegoldenrod: 0xeee8aa,
  5126. palegreen: 0x98fb98,
  5127. paleturquoise: 0xafeeee,
  5128. palevioletred: 0xdb7093,
  5129. papayawhip: 0xffefd5,
  5130. peachpuff: 0xffdab9,
  5131. peru: 0xcd853f,
  5132. pink: 0xffc0cb,
  5133. plum: 0xdda0dd,
  5134. powderblue: 0xb0e0e6,
  5135. purple: 0x800080,
  5136. rebeccapurple: 0x663399,
  5137. red: 0xff0000,
  5138. rosybrown: 0xbc8f8f,
  5139. royalblue: 0x4169e1,
  5140. saddlebrown: 0x8b4513,
  5141. salmon: 0xfa8072,
  5142. sandybrown: 0xf4a460,
  5143. seagreen: 0x2e8b57,
  5144. seashell: 0xfff5ee,
  5145. sienna: 0xa0522d,
  5146. silver: 0xc0c0c0,
  5147. skyblue: 0x87ceeb,
  5148. slateblue: 0x6a5acd,
  5149. slategray: 0x708090,
  5150. slategrey: 0x708090,
  5151. snow: 0xfffafa,
  5152. springgreen: 0x00ff7f,
  5153. steelblue: 0x4682b4,
  5154. tan: 0xd2b48c,
  5155. teal: 0x008080,
  5156. thistle: 0xd8bfd8,
  5157. tomato: 0xff6347,
  5158. turquoise: 0x40e0d0,
  5159. violet: 0xee82ee,
  5160. wheat: 0xf5deb3,
  5161. white: 0xffffff,
  5162. whitesmoke: 0xf5f5f5,
  5163. yellow: 0xffff00,
  5164. yellowgreen: 0x9acd32
  5165. };
  5166. define(Color, color, {
  5167. copy: function(channels) {
  5168. return Object.assign(new this.constructor, this, channels);
  5169. },
  5170. displayable: function() {
  5171. return this.rgb().displayable();
  5172. },
  5173. hex: color_formatHex, // Deprecated! Use color.formatHex.
  5174. formatHex: color_formatHex,
  5175. formatHsl: color_formatHsl,
  5176. formatRgb: color_formatRgb,
  5177. toString: color_formatRgb
  5178. });
  5179. function color_formatHex() {
  5180. return this.rgb().formatHex();
  5181. }
  5182. function color_formatHsl() {
  5183. return hslConvert(this).formatHsl();
  5184. }
  5185. function color_formatRgb() {
  5186. return this.rgb().formatRgb();
  5187. }
  5188. function color(format) {
  5189. var m, l;
  5190. format = (format + "").trim().toLowerCase();
  5191. return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000
  5192. : l === 3 ? new Rgb((m >> 8 & 0xf) | (m >> 4 & 0xf0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1) // #f00
  5193. : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000
  5194. : 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
  5195. : null) // invalid hex
  5196. : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0)
  5197. : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%)
  5198. : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1)
  5199. : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1)
  5200. : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%)
  5201. : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1)
  5202. : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins
  5203. : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0)
  5204. : null;
  5205. }
  5206. function rgbn(n) {
  5207. return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1);
  5208. }
  5209. function rgba(r, g, b, a) {
  5210. if (a <= 0) r = g = b = NaN;
  5211. return new Rgb(r, g, b, a);
  5212. }
  5213. function rgbConvert(o) {
  5214. if (!(o instanceof Color)) o = color(o);
  5215. if (!o) return new Rgb;
  5216. o = o.rgb();
  5217. return new Rgb(o.r, o.g, o.b, o.opacity);
  5218. }
  5219. function rgb(r, g, b, opacity) {
  5220. return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity);
  5221. }
  5222. function Rgb(r, g, b, opacity) {
  5223. this.r = +r;
  5224. this.g = +g;
  5225. this.b = +b;
  5226. this.opacity = +opacity;
  5227. }
  5228. define(Rgb, rgb, extend(Color, {
  5229. brighter: function(k) {
  5230. k = k == null ? brighter : Math.pow(brighter, k);
  5231. return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  5232. },
  5233. darker: function(k) {
  5234. k = k == null ? darker : Math.pow(darker, k);
  5235. return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity);
  5236. },
  5237. rgb: function() {
  5238. return this;
  5239. },
  5240. displayable: function() {
  5241. return (-0.5 <= this.r && this.r < 255.5)
  5242. && (-0.5 <= this.g && this.g < 255.5)
  5243. && (-0.5 <= this.b && this.b < 255.5)
  5244. && (0 <= this.opacity && this.opacity <= 1);
  5245. },
  5246. hex: rgb_formatHex, // Deprecated! Use color.formatHex.
  5247. formatHex: rgb_formatHex,
  5248. formatRgb: rgb_formatRgb,
  5249. toString: rgb_formatRgb
  5250. }));
  5251. function rgb_formatHex() {
  5252. return "#" + hex(this.r) + hex(this.g) + hex(this.b);
  5253. }
  5254. function rgb_formatRgb() {
  5255. var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
  5256. return (a === 1 ? "rgb(" : "rgba(")
  5257. + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", "
  5258. + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", "
  5259. + Math.max(0, Math.min(255, Math.round(this.b) || 0))
  5260. + (a === 1 ? ")" : ", " + a + ")");
  5261. }
  5262. function hex(value) {
  5263. value = Math.max(0, Math.min(255, Math.round(value) || 0));
  5264. return (value < 16 ? "0" : "") + value.toString(16);
  5265. }
  5266. function hsla(h, s, l, a) {
  5267. if (a <= 0) h = s = l = NaN;
  5268. else if (l <= 0 || l >= 1) h = s = NaN;
  5269. else if (s <= 0) h = NaN;
  5270. return new Hsl(h, s, l, a);
  5271. }
  5272. function hslConvert(o) {
  5273. if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity);
  5274. if (!(o instanceof Color)) o = color(o);
  5275. if (!o) return new Hsl;
  5276. if (o instanceof Hsl) return o;
  5277. o = o.rgb();
  5278. var r = o.r / 255,
  5279. g = o.g / 255,
  5280. b = o.b / 255,
  5281. min = Math.min(r, g, b),
  5282. max = Math.max(r, g, b),
  5283. h = NaN,
  5284. s = max - min,
  5285. l = (max + min) / 2;
  5286. if (s) {
  5287. if (r === max) h = (g - b) / s + (g < b) * 6;
  5288. else if (g === max) h = (b - r) / s + 2;
  5289. else h = (r - g) / s + 4;
  5290. s /= l < 0.5 ? max + min : 2 - max - min;
  5291. h *= 60;
  5292. } else {
  5293. s = l > 0 && l < 1 ? 0 : h;
  5294. }
  5295. return new Hsl(h, s, l, o.opacity);
  5296. }
  5297. function hsl(h, s, l, opacity) {
  5298. return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity);
  5299. }
  5300. function Hsl(h, s, l, opacity) {
  5301. this.h = +h;
  5302. this.s = +s;
  5303. this.l = +l;
  5304. this.opacity = +opacity;
  5305. }
  5306. define(Hsl, hsl, extend(Color, {
  5307. brighter: function(k) {
  5308. k = k == null ? brighter : Math.pow(brighter, k);
  5309. return new Hsl(this.h, this.s, this.l * k, this.opacity);
  5310. },
  5311. darker: function(k) {
  5312. k = k == null ? darker : Math.pow(darker, k);
  5313. return new Hsl(this.h, this.s, this.l * k, this.opacity);
  5314. },
  5315. rgb: function() {
  5316. var h = this.h % 360 + (this.h < 0) * 360,
  5317. s = isNaN(h) || isNaN(this.s) ? 0 : this.s,
  5318. l = this.l,
  5319. m2 = l + (l < 0.5 ? l : 1 - l) * s,
  5320. m1 = 2 * l - m2;
  5321. return new Rgb(
  5322. hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2),
  5323. hsl2rgb(h, m1, m2),
  5324. hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2),
  5325. this.opacity
  5326. );
  5327. },
  5328. displayable: function() {
  5329. return (0 <= this.s && this.s <= 1 || isNaN(this.s))
  5330. && (0 <= this.l && this.l <= 1)
  5331. && (0 <= this.opacity && this.opacity <= 1);
  5332. },
  5333. formatHsl: function() {
  5334. var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a));
  5335. return (a === 1 ? "hsl(" : "hsla(")
  5336. + (this.h || 0) + ", "
  5337. + (this.s || 0) * 100 + "%, "
  5338. + (this.l || 0) * 100 + "%"
  5339. + (a === 1 ? ")" : ", " + a + ")");
  5340. }
  5341. }));
  5342. /* From FvD 13.37, CSS Color Module Level 3 */
  5343. function hsl2rgb(h, m1, m2) {
  5344. return (h < 60 ? m1 + (m2 - m1) * h / 60
  5345. : h < 180 ? m2
  5346. : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60
  5347. : m1) * 255;
  5348. }
  5349. /**
  5350. * 两点之间的距离
  5351. * @param {number} x1 起始点 x
  5352. * @param {number} y1 起始点 y
  5353. * @param {number} x2 结束点 x
  5354. * @param {number} y2 结束点 y
  5355. * @return {number} 距离
  5356. */
  5357. function distance$1(x1, y1, x2, y2) {
  5358. var dx = x1 - x2;
  5359. var dy = y1 - y2;
  5360. return Math.sqrt(dx * dx + dy * dy);
  5361. }
  5362. function isNumberEqual$1(v1, v2) {
  5363. return Math.abs(v1 - v2) < 0.001;
  5364. }
  5365. function getBBoxByArray(xArr, yArr) {
  5366. var minX = Math.min.apply(Math, xArr);
  5367. var minY = Math.min.apply(Math, yArr);
  5368. var maxX = Math.max.apply(Math, xArr);
  5369. var maxY = Math.max.apply(Math, yArr);
  5370. return {
  5371. x: minX,
  5372. y: minY,
  5373. width: maxX - minX,
  5374. height: maxY - minY
  5375. };
  5376. }
  5377. function piMod(angle) {
  5378. return (angle + Math.PI * 2) % (Math.PI * 2);
  5379. }
  5380. var line = {
  5381. /**
  5382. * 计算线段的包围盒
  5383. * @param {number} x1 起始点 x
  5384. * @param {number} y1 起始点 y
  5385. * @param {number} x2 结束点 x
  5386. * @param {number} y2 结束点 y
  5387. * @return {object} 包围盒对象
  5388. */
  5389. box: function box(x1, y1, x2, y2) {
  5390. return getBBoxByArray([x1, x2], [y1, y2]);
  5391. },
  5392. /**
  5393. * 线段的长度
  5394. * @param {number} x1 起始点 x
  5395. * @param {number} y1 起始点 y
  5396. * @param {number} x2 结束点 x
  5397. * @param {number} y2 结束点 y
  5398. * @return {number} 距离
  5399. */
  5400. length: function length(x1, y1, x2, y2) {
  5401. return distance$1(x1, y1, x2, y2);
  5402. },
  5403. /**
  5404. * 根据比例获取点
  5405. * @param {number} x1 起始点 x
  5406. * @param {number} y1 起始点 y
  5407. * @param {number} x2 结束点 x
  5408. * @param {number} y2 结束点 y
  5409. * @param {number} t 指定比例
  5410. * @return {object} 包含 x, y 的点
  5411. */
  5412. pointAt: function pointAt(x1, y1, x2, y2, t) {
  5413. return {
  5414. x: (1 - t) * x1 + t * x2,
  5415. y: (1 - t) * y1 + t * y2
  5416. };
  5417. },
  5418. /**
  5419. * 点到线段的距离
  5420. * @param {number} x1 起始点 x
  5421. * @param {number} y1 起始点 y
  5422. * @param {number} x2 结束点 x
  5423. * @param {number} y2 结束点 y
  5424. * @param {number} x 测试点 x
  5425. * @param {number} y 测试点 y
  5426. * @return {number} 距离
  5427. */
  5428. pointDistance: function pointDistance(x1, y1, x2, y2, x, y) {
  5429. // 投影距离 x1, y1 的向量,假设 p, p1, p2 三个点,投影点为 a
  5430. // p1a = p1p.p1p2/|p1p2| * (p1p 的单位向量)
  5431. var cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);
  5432. if (cross < 0) {
  5433. return distance$1(x1, y1, x, y);
  5434. }
  5435. var lengthSquare = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
  5436. if (cross > lengthSquare) {
  5437. return distance$1(x2, y2, x, y);
  5438. }
  5439. return this.pointToLine(x1, y1, x2, y2, x, y);
  5440. },
  5441. /**
  5442. * 点到直线的距离,而不是点到线段的距离
  5443. * @param {number} x1 起始点 x
  5444. * @param {number} y1 起始点 y
  5445. * @param {number} x2 结束点 x
  5446. * @param {number} y2 结束点 y
  5447. * @param {number} x 测试点 x
  5448. * @param {number} y 测试点 y
  5449. * @return {number} 距离
  5450. */
  5451. pointToLine: function pointToLine(x1, y1, x2, y2, x, y) {
  5452. var d = [x2 - x1, y2 - y1];
  5453. // 如果端点相等,则判定点到点的距离
  5454. if (exactEquals$1(d, [0, 0])) {
  5455. return Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
  5456. }
  5457. var u = [-d[1], d[0]];
  5458. normalize$3(u, u);
  5459. var a = [x - x1, y - y1];
  5460. return Math.abs(dot$1(a, u));
  5461. },
  5462. /**
  5463. * 线段的角度
  5464. * @param {number} x1 起始点 x
  5465. * @param {number} y1 起始点 y
  5466. * @param {number} x2 结束点 x
  5467. * @param {number} y2 结束点 y
  5468. * @return {number} 导数
  5469. */
  5470. tangentAngle: function tangentAngle(x1, y1, x2, y2) {
  5471. return Math.atan2(y2 - y1, x2 - x1);
  5472. }
  5473. };
  5474. var EPSILON$1 = 0.0001;
  5475. /**
  5476. * 使用牛顿切割法求最近的点
  5477. * @param {number[]} xArr 点的 x 数组
  5478. * @param {number[]} yArr 点的 y 数组
  5479. * @param {number} x 指定的点 x
  5480. * @param {number} y 指定的点 y
  5481. * @param {Function} tCallback 差值函数
  5482. */
  5483. function nearestPoint(xArr, yArr, x, y, tCallback, length) {
  5484. var t = -1;
  5485. var d = Infinity;
  5486. var v0 = [x, y];
  5487. var segNum = 20;
  5488. if (length && length > 200) {
  5489. segNum = length / 10;
  5490. }
  5491. var increaseRate = 1 / segNum;
  5492. var interval = increaseRate / 10;
  5493. for (var i = 0; i <= segNum; i++) {
  5494. var _t = i * increaseRate;
  5495. var v1 = [tCallback.apply(void 0, xArr.concat([_t])), tCallback.apply(void 0, yArr.concat([_t]))];
  5496. var d1 = distance$1(v0[0], v0[1], v1[0], v1[1]);
  5497. if (d1 < d) {
  5498. t = _t;
  5499. d = d1;
  5500. }
  5501. }
  5502. // 提前终止
  5503. if (t === 0) {
  5504. return {
  5505. x: xArr[0],
  5506. y: yArr[0]
  5507. };
  5508. }
  5509. if (t === 1) {
  5510. var count = xArr.length;
  5511. return {
  5512. x: xArr[count - 1],
  5513. y: yArr[count - 1]
  5514. };
  5515. }
  5516. d = Infinity;
  5517. for (var _i = 0; _i < 32; _i++) {
  5518. if (interval < EPSILON$1) {
  5519. break;
  5520. }
  5521. var prev = t - interval;
  5522. var next = t + interval;
  5523. var _v = [tCallback.apply(void 0, xArr.concat([prev])), tCallback.apply(void 0, yArr.concat([prev]))];
  5524. var _d = distance$1(v0[0], v0[1], _v[0], _v[1]);
  5525. if (prev >= 0 && _d < d) {
  5526. t = prev;
  5527. d = _d;
  5528. } else {
  5529. var v2 = [tCallback.apply(void 0, xArr.concat([next])), tCallback.apply(void 0, yArr.concat([next]))];
  5530. var d2 = distance$1(v0[0], v0[1], v2[0], v2[1]);
  5531. if (next <= 1 && d2 < d) {
  5532. t = next;
  5533. d = d2;
  5534. } else {
  5535. interval *= 0.5;
  5536. }
  5537. }
  5538. }
  5539. return {
  5540. x: tCallback.apply(void 0, xArr.concat([t])),
  5541. y: tCallback.apply(void 0, yArr.concat([t]))
  5542. };
  5543. }
  5544. // 近似求解 https://community.khronos.org/t/3d-cubic-bezier-segment-length/62363/2
  5545. function snapLength(xArr, yArr) {
  5546. var totalLength = 0;
  5547. var count = xArr.length;
  5548. for (var i = 0; i < count; i++) {
  5549. var x = xArr[i];
  5550. var y = yArr[i];
  5551. var nextX = xArr[(i + 1) % count];
  5552. var nextY = yArr[(i + 1) % count];
  5553. totalLength += distance$1(x, y, nextX, nextY);
  5554. }
  5555. return totalLength / 2;
  5556. }
  5557. // 差值公式
  5558. function quadraticAt(p0, p1, p2, t) {
  5559. var onet = 1 - t;
  5560. return onet * onet * p0 + 2 * t * onet * p1 + t * t * p2;
  5561. }
  5562. // 求极值
  5563. function extrema(p0, p1, p2) {
  5564. var a = p0 + p2 - 2 * p1;
  5565. if (isNumberEqual$1(a, 0)) {
  5566. return [0.5];
  5567. }
  5568. var rst = (p0 - p1) / a;
  5569. if (rst <= 1 && rst >= 0) {
  5570. return [rst];
  5571. }
  5572. return [];
  5573. }
  5574. function derivativeAt(p0, p1, p2, t) {
  5575. return 2 * (1 - t) * (p1 - p0) + 2 * t * (p2 - p1);
  5576. }
  5577. // 分割贝塞尔曲线
  5578. function divideQuadratic(x1, y1, x2, y2, x3, y3, t) {
  5579. // 划分点
  5580. var xt = quadraticAt(x1, x2, x3, t);
  5581. var yt = quadraticAt(y1, y2, y3, t);
  5582. // 分割的第一条曲线的控制点
  5583. var controlPoint1 = line.pointAt(x1, y1, x2, y2, t);
  5584. // 分割的第二条曲线的控制点
  5585. var controlPoint2 = line.pointAt(x2, y2, x3, y3, t);
  5586. return [[x1, y1, controlPoint1.x, controlPoint1.y, xt, yt], [xt, yt, controlPoint2.x, controlPoint2.y, x3, y3]];
  5587. }
  5588. // 使用迭代法取贝塞尔曲线的长度
  5589. function quadraticLength(x1, y1, x2, y2, x3, y3, iterationCount) {
  5590. if (iterationCount === 0) {
  5591. return (distance$1(x1, y1, x2, y2) + distance$1(x2, y2, x3, y3) + distance$1(x1, y1, x3, y3)) / 2;
  5592. }
  5593. var quadratics = divideQuadratic(x1, y1, x2, y2, x3, y3, 0.5);
  5594. var left = quadratics[0];
  5595. var right = quadratics[1];
  5596. left.push(iterationCount - 1);
  5597. right.push(iterationCount - 1);
  5598. return quadraticLength.apply(void 0, left) + quadraticLength.apply(void 0, right);
  5599. }
  5600. var quadratic = {
  5601. box: function box(x1, y1, x2, y2, x3, y3) {
  5602. var xExtrema = extrema(x1, x2, x3)[0];
  5603. var yExtrema = extrema(y1, y2, y3)[0];
  5604. // 控制点不加入 box 的计算
  5605. var xArr = [x1, x3];
  5606. var yArr = [y1, y3];
  5607. if (xExtrema !== undefined) {
  5608. xArr.push(quadraticAt(x1, x2, x3, xExtrema));
  5609. }
  5610. if (yExtrema !== undefined) {
  5611. yArr.push(quadraticAt(y1, y2, y3, yExtrema));
  5612. }
  5613. return getBBoxByArray(xArr, yArr);
  5614. },
  5615. length: function length(x1, y1, x2, y2, x3, y3) {
  5616. return quadraticLength(x1, y1, x2, y2, x3, y3, 3);
  5617. },
  5618. nearestPoint: function nearestPoint$1(x1, y1, x2, y2, x3, y3, x0, y0) {
  5619. return nearestPoint([x1, x2, x3], [y1, y2, y3], x0, y0, quadraticAt);
  5620. },
  5621. pointDistance: function pointDistance(x1, y1, x2, y2, x3, y3, x0, y0) {
  5622. var point = this.nearestPoint(x1, y1, x2, y2, x3, y3, x0, y0);
  5623. return distance$1(point.x, point.y, x0, y0);
  5624. },
  5625. interpolationAt: quadraticAt,
  5626. pointAt: function pointAt(x1, y1, x2, y2, x3, y3, t) {
  5627. return {
  5628. x: quadraticAt(x1, x2, x3, t),
  5629. y: quadraticAt(y1, y2, y3, t)
  5630. };
  5631. },
  5632. divide: function divide(x1, y1, x2, y2, x3, y3, t) {
  5633. return divideQuadratic(x1, y1, x2, y2, x3, y3, t);
  5634. },
  5635. tangentAngle: function tangentAngle(x1, y1, x2, y2, x3, y3, t) {
  5636. var dx = derivativeAt(x1, x2, x3, t);
  5637. var dy = derivativeAt(y1, y2, y3, t);
  5638. var angle = Math.atan2(dy, dx);
  5639. return piMod(angle);
  5640. }
  5641. };
  5642. function cubicAt(p0, p1, p2, p3, t) {
  5643. var onet = 1 - t; // t * t * t 的性能大概是 Math.pow(t, 3) 的三倍
  5644. return onet * onet * onet * p0 + 3 * p1 * t * onet * onet + 3 * p2 * t * t * onet + p3 * t * t * t;
  5645. }
  5646. function derivativeAt$1(p0, p1, p2, p3, t) {
  5647. var onet = 1 - t;
  5648. return 3 * (onet * onet * (p1 - p0) + 2 * onet * t * (p2 - p1) + t * t * (p3 - p2));
  5649. }
  5650. function extrema$1(p0, p1, p2, p3) {
  5651. var a = -3 * p0 + 9 * p1 - 9 * p2 + 3 * p3;
  5652. var b = 6 * p0 - 12 * p1 + 6 * p2;
  5653. var c = 3 * p1 - 3 * p0;
  5654. var extremas = [];
  5655. var t1;
  5656. var t2;
  5657. var discSqrt;
  5658. if (isNumberEqual$1(a, 0)) {
  5659. if (!isNumberEqual$1(b, 0)) {
  5660. t1 = -c / b;
  5661. if (t1 >= 0 && t1 <= 1) {
  5662. extremas.push(t1);
  5663. }
  5664. }
  5665. } else {
  5666. var disc = b * b - 4 * a * c;
  5667. if (isNumberEqual$1(disc, 0)) {
  5668. extremas.push(-b / (2 * a));
  5669. } else if (disc > 0) {
  5670. discSqrt = Math.sqrt(disc);
  5671. t1 = (-b + discSqrt) / (2 * a);
  5672. t2 = (-b - discSqrt) / (2 * a);
  5673. if (t1 >= 0 && t1 <= 1) {
  5674. extremas.push(t1);
  5675. }
  5676. if (t2 >= 0 && t2 <= 1) {
  5677. extremas.push(t2);
  5678. }
  5679. }
  5680. }
  5681. return extremas;
  5682. }
  5683. // 分割贝塞尔曲线
  5684. function divideCubic(x1, y1, x2, y2, x3, y3, x4, y4, t) {
  5685. // 划分点
  5686. var xt = cubicAt(x1, x2, x3, x4, t);
  5687. var yt = cubicAt(y1, y2, y3, y4, t);
  5688. // 计算两点之间的差值点
  5689. var c1 = line.pointAt(x1, y1, x2, y2, t);
  5690. var c2 = line.pointAt(x2, y2, x3, y3, t);
  5691. var c3 = line.pointAt(x3, y3, x4, y4, t);
  5692. var c12 = line.pointAt(c1.x, c1.y, c2.x, c2.y, t);
  5693. var c23 = line.pointAt(c2.x, c2.y, c3.x, c3.y, t);
  5694. 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]];
  5695. }
  5696. // 使用迭代法取贝塞尔曲线的长度,二阶和三阶分开写,更清晰和便于调试
  5697. function cubicLength(x1, y1, x2, y2, x3, y3, x4, y4, iterationCount) {
  5698. if (iterationCount === 0) {
  5699. return snapLength([x1, x2, x3, x4], [y1, y2, y3, y4]);
  5700. }
  5701. var cubics = divideCubic(x1, y1, x2, y2, x3, y3, x4, y4, 0.5);
  5702. var left = [].concat(cubics[0], [iterationCount - 1]);
  5703. var right = [].concat(cubics[1], [iterationCount - 1]);
  5704. return cubicLength.apply(void 0, left) + cubicLength.apply(void 0, right);
  5705. }
  5706. var cubic = {
  5707. extrema: extrema$1,
  5708. box: function box(x1, y1, x2, y2, x3, y3, x4, y4) {
  5709. var xArr = [x1, x4];
  5710. var yArr = [y1, y4];
  5711. var xExtrema = extrema$1(x1, x2, x3, x4);
  5712. var yExtrema = extrema$1(y1, y2, y3, y4);
  5713. for (var i = 0; i < xExtrema.length; i++) {
  5714. xArr.push(cubicAt(x1, x2, x3, x4, xExtrema[i]));
  5715. }
  5716. for (var _i = 0; _i < yExtrema.length; _i++) {
  5717. yArr.push(cubicAt(y1, y2, y3, y4, yExtrema[_i]));
  5718. }
  5719. return getBBoxByArray(xArr, yArr);
  5720. },
  5721. length: function length(x1, y1, x2, y2, x3, y3, x4, y4) {
  5722. // 迭代三次,划分成 8 段求长度
  5723. return cubicLength(x1, y1, x2, y2, x3, y3, x4, y4, 3);
  5724. },
  5725. nearestPoint: function nearestPoint$1(x1, y1, x2, y2, x3, y3, x4, y4, x0, y0, length) {
  5726. return nearestPoint([x1, x2, x3, x4], [y1, y2, y3, y4], x0, y0, cubicAt, length);
  5727. },
  5728. pointDistance: function pointDistance(x1, y1, x2, y2, x3, y3, x4, y4, x0, y0, length) {
  5729. var point = this.nearestPoint(x1, y1, x2, y2, x3, y3, x4, y4, x0, y0, length);
  5730. return distance$1(point.x, point.y, x0, y0);
  5731. },
  5732. interpolationAt: cubicAt,
  5733. pointAt: function pointAt(x1, y1, x2, y2, x3, y3, x4, y4, t) {
  5734. return {
  5735. x: cubicAt(x1, x2, x3, x4, t),
  5736. y: cubicAt(y1, y2, y3, y4, t)
  5737. };
  5738. },
  5739. divide: function divide(x1, y1, x2, y2, x3, y3, x4, y4, t) {
  5740. return divideCubic(x1, y1, x2, y2, x3, y3, x4, y4, t);
  5741. },
  5742. tangentAngle: function tangentAngle(x1, y1, x2, y2, x3, y3, x4, y4, t) {
  5743. var dx = derivativeAt$1(x1, x2, x3, x4, t);
  5744. var dy = derivativeAt$1(y1, y2, y3, y4, t);
  5745. return piMod(Math.atan2(dy, dx));
  5746. }
  5747. };
  5748. /**
  5749. * @fileoverview 椭圆的一些计算,
  5750. * - 周长计算参考:https://www.mathsisfun.com/geometry/ellipse-perimeter.html
  5751. * - 距离计算参考:https://wet-robots.ghost.io/simple-method-for-distance-to-ellipse/
  5752. * @author dxq613@gmail.com
  5753. */
  5754. function copysign(v1, v2) {
  5755. var absv = Math.abs(v1);
  5756. return v2 > 0 ? absv : absv * -1;
  5757. }
  5758. var ellipse = {
  5759. /**
  5760. * 包围盒计算
  5761. * @param {number} x 椭圆中心 x
  5762. * @param {number} y 椭圆中心 y
  5763. * @param {number} rx 椭圆 x 方向半径
  5764. * @param {number} ry 椭圆 y 方向半径
  5765. * @return {object} 包围盒
  5766. */
  5767. box: function box(x, y, rx, ry) {
  5768. return {
  5769. x: x - rx,
  5770. y: y - ry,
  5771. width: rx * 2,
  5772. height: ry * 2
  5773. };
  5774. },
  5775. /**
  5776. * 计算周长,使用近似法
  5777. * @param {number} x 椭圆中心 x
  5778. * @param {number} y 椭圆中心 y
  5779. * @param {number} rx 椭圆 x 方向半径
  5780. * @param {number} ry 椭圆 y 方向半径
  5781. * @return {number} 椭圆周长
  5782. */
  5783. length: function length(x, y, rx, ry) {
  5784. return Math.PI * (3 * (rx + ry) - Math.sqrt((3 * rx + ry) * (rx + 3 * ry)));
  5785. },
  5786. /**
  5787. * 距离椭圆最近的点
  5788. * @param {number} x 椭圆中心 x
  5789. * @param {number} y 椭圆中心 y
  5790. * @param {number} rx 椭圆 x 方向半径
  5791. * @param {number} ry 椭圆 y 方向半径
  5792. * @param {number} x0 指定的点 x
  5793. * @param {number} y0 指定的点 y
  5794. * @return {object} 椭圆上距离指定点最近的点
  5795. */
  5796. nearestPoint: function nearestPoint(x, y, rx, ry, x0, y0) {
  5797. var a = rx;
  5798. var b = ry;
  5799. // 假如椭圆半径为0则返回圆心
  5800. if (a === 0 || b === 0) {
  5801. return {
  5802. x: x,
  5803. y: y
  5804. };
  5805. }
  5806. // 转换成 0, 0 为中心的椭圆计算
  5807. var relativeX = x0 - x;
  5808. var relativeY = y0 - y;
  5809. var px = Math.abs(relativeX);
  5810. var py = Math.abs(relativeY);
  5811. var squareA = a * a;
  5812. var squareB = b * b;
  5813. // const angle0 = Math.atan2(relativeY, relativeX);
  5814. var t = Math.PI / 4;
  5815. var nearestX = 0; // 椭圆上的任一点
  5816. var nearestY = 0;
  5817. // 迭代 4 次
  5818. for (var i = 0; i < 4; i++) {
  5819. nearestX = a * Math.cos(t);
  5820. nearestY = b * Math.sin(t);
  5821. var ex = (squareA - squareB) * Math.pow(Math.cos(t), 3) / a;
  5822. var ey = (squareB - squareA) * Math.pow(Math.sin(t), 3) / b;
  5823. var rx1 = nearestX - ex;
  5824. var ry1 = nearestY - ey;
  5825. var qx = px - ex;
  5826. var qy = py - ey;
  5827. var r = Math.hypot(ry1, rx1);
  5828. var q = Math.hypot(qy, qx);
  5829. var delta_c = r * Math.asin((rx1 * qy - ry1 * qx) / (r * q));
  5830. var delta_t = delta_c / Math.sqrt(squareA + squareB - nearestX * nearestX - nearestY * nearestY);
  5831. t += delta_t;
  5832. t = Math.min(Math.PI / 2, Math.max(0, t));
  5833. }
  5834. return {
  5835. x: x + copysign(nearestX, relativeX),
  5836. y: y + copysign(nearestY, relativeY)
  5837. };
  5838. },
  5839. /**
  5840. * 点到椭圆最近的距离
  5841. * @param {number} x 椭圆中心 x
  5842. * @param {number} y 椭圆中心 y
  5843. * @param {number} rx 椭圆 x 方向半径
  5844. * @param {number} ry 椭圆 y 方向半径
  5845. * @param {number} x0 指定的点 x
  5846. * @param {number} y0 指定的点 y
  5847. * @return {number} 点到椭圆的距离
  5848. */
  5849. pointDistance: function pointDistance(x, y, rx, ry, x0, y0) {
  5850. var nearestPoint = this.nearestPoint(x, y, rx, ry, x0, y0);
  5851. return distance$1(nearestPoint.x, nearestPoint.y, x0, y0);
  5852. },
  5853. /**
  5854. * 根据比例获取点
  5855. * @param {number} x 椭圆中心 x
  5856. * @param {number} y 椭圆中心 y
  5857. * @param {number} rx 椭圆 x 方向半径
  5858. * @param {number} ry 椭圆 y 方向半径
  5859. * @param {number} t 指定比例,x轴方向为 0
  5860. * @return {object} 点
  5861. */
  5862. pointAt: function pointAt(x, y, rx, ry, t) {
  5863. var angle = 2 * Math.PI * t; // 按照角度进行计算,而不按照周长计算
  5864. return {
  5865. x: x + rx * Math.cos(angle),
  5866. y: y + ry * Math.sin(angle)
  5867. };
  5868. },
  5869. /**
  5870. * 根据比例计算切线角度
  5871. * @param {number} x 椭圆中心 x
  5872. * @param {number} y 椭圆中心 y
  5873. * @param {number} rx 椭圆 x 方向半径
  5874. * @param {number} ry 椭圆 y 方向半径
  5875. * @param {number} t 指定比例 0 - 1 之间,x轴方向为 0。在 0-1 范围之外是循环还是返回 null,还需要调整
  5876. * @return {number} 角度,在 0 - 2PI 之间
  5877. */
  5878. tangentAngle: function tangentAngle(x, y, rx, ry, t) {
  5879. var angle = 2 * Math.PI * t; // 按照角度进行计算,而不按照周长计算
  5880. // 直接使用 x,y 的导数计算, x' = -rx * sin(t); y' = ry * cos(t);
  5881. var tangentAngle = Math.atan2(ry * Math.cos(angle), -rx * Math.sin(angle));
  5882. // 也可以使用指定点的切线方程计算,成本有些高
  5883. // const point = this.pointAt(0, 0, rx, ry, t); // 椭圆的切线同椭圆的中心不相关
  5884. // let tangentAngle = -1 * Math.atan((ry * ry * point.x) / (rx * rx * point.y));
  5885. // if (angle >= 0 && angle <= Math.PI) {
  5886. // tangentAngle += Math.PI;
  5887. // }
  5888. return piMod(tangentAngle);
  5889. }
  5890. };
  5891. // 偏导数 x
  5892. function derivativeXAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle) {
  5893. return -1 * rx * Math.cos(xRotation) * Math.sin(angle) - ry * Math.sin(xRotation) * Math.cos(angle);
  5894. }
  5895. // 偏导数 y
  5896. function derivativeYAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle) {
  5897. return -1 * rx * Math.sin(xRotation) * Math.sin(angle) + ry * Math.cos(xRotation) * Math.cos(angle);
  5898. }
  5899. // x 的极值
  5900. function xExtrema(rx, ry, xRotation) {
  5901. return Math.atan(-ry / rx * Math.tan(xRotation));
  5902. }
  5903. // y 的极值
  5904. function yExtrema(rx, ry, xRotation) {
  5905. return Math.atan(ry / (rx * Math.tan(xRotation)));
  5906. }
  5907. // 根据角度求 x 坐标
  5908. function xAt(cx, cy, rx, ry, xRotation, angle) {
  5909. return rx * Math.cos(xRotation) * Math.cos(angle) - ry * Math.sin(xRotation) * Math.sin(angle) + cx;
  5910. }
  5911. // 根据角度求 y 坐标
  5912. function yAt(cx, cy, rx, ry, xRotation, angle) {
  5913. return rx * Math.sin(xRotation) * Math.cos(angle) + ry * Math.cos(xRotation) * Math.sin(angle) + cy;
  5914. }
  5915. // 获取点在椭圆上的角度
  5916. function getAngle(rx, ry, x0, y0) {
  5917. var angle = Math.atan2(y0 * rx, x0 * ry);
  5918. // 转换到 0 - 2PI 内
  5919. return (angle + Math.PI * 2) % (Math.PI * 2);
  5920. }
  5921. // 根据角度获取,x,y
  5922. function getPoint(rx, ry, angle) {
  5923. return {
  5924. x: rx * Math.cos(angle),
  5925. y: ry * Math.sin(angle)
  5926. };
  5927. }
  5928. // 旋转
  5929. function rotate$1(x, y, angle) {
  5930. var cos = Math.cos(angle);
  5931. var sin = Math.sin(angle);
  5932. return [x * cos - y * sin, x * sin + y * cos];
  5933. }
  5934. var arc = {
  5935. /**
  5936. * 计算包围盒
  5937. * @param {number} cx 圆心 x
  5938. * @param {number} cy 圆心 y
  5939. * @param {number} rx x 轴方向的半径
  5940. * @param {number} ry y 轴方向的半径
  5941. * @param {number} xRotation 旋转角度
  5942. * @param {number} startAngle 起始角度
  5943. * @param {number} endAngle 结束角度
  5944. * @return {object} 包围盒对象
  5945. */
  5946. box: function box(cx, cy, rx, ry, xRotation, startAngle, endAngle) {
  5947. var xDim = xExtrema(rx, ry, xRotation);
  5948. var minX = Infinity;
  5949. var maxX = -Infinity;
  5950. var xs = [startAngle, endAngle];
  5951. for (var i = -Math.PI * 2; i <= Math.PI * 2; i += Math.PI) {
  5952. var xAngle = xDim + i;
  5953. if (startAngle < endAngle) {
  5954. if (startAngle < xAngle && xAngle < endAngle) {
  5955. xs.push(xAngle);
  5956. }
  5957. } else {
  5958. if (endAngle < xAngle && xAngle < startAngle) {
  5959. xs.push(xAngle);
  5960. }
  5961. }
  5962. }
  5963. for (var _i = 0; _i < xs.length; _i++) {
  5964. var x = xAt(cx, cy, rx, ry, xRotation, xs[_i]);
  5965. if (x < minX) {
  5966. minX = x;
  5967. }
  5968. if (x > maxX) {
  5969. maxX = x;
  5970. }
  5971. }
  5972. var yDim = yExtrema(rx, ry, xRotation);
  5973. var minY = Infinity;
  5974. var maxY = -Infinity;
  5975. var ys = [startAngle, endAngle];
  5976. for (var _i2 = -Math.PI * 2; _i2 <= Math.PI * 2; _i2 += Math.PI) {
  5977. var yAngle = yDim + _i2;
  5978. if (startAngle < endAngle) {
  5979. if (startAngle < yAngle && yAngle < endAngle) {
  5980. ys.push(yAngle);
  5981. }
  5982. } else {
  5983. if (endAngle < yAngle && yAngle < startAngle) {
  5984. ys.push(yAngle);
  5985. }
  5986. }
  5987. }
  5988. for (var _i3 = 0; _i3 < ys.length; _i3++) {
  5989. var y = yAt(cx, cy, rx, ry, xRotation, ys[_i3]);
  5990. if (y < minY) {
  5991. minY = y;
  5992. }
  5993. if (y > maxY) {
  5994. maxY = y;
  5995. }
  5996. }
  5997. return {
  5998. x: minX,
  5999. y: minY,
  6000. width: maxX - minX,
  6001. height: maxY - minY
  6002. };
  6003. },
  6004. /**
  6005. * 获取圆弧的长度,计算圆弧长度时不考虑旋转角度,
  6006. * 仅跟 rx, ry, startAngle, endAngle 相关
  6007. * @param {number} cx 圆心 x
  6008. * @param {number} cy 圆心 y
  6009. * @param {number} rx x 轴方向的半径
  6010. * @param {number} ry y 轴方向的半径
  6011. * @param {number} xRotation 旋转角度
  6012. * @param {number} startAngle 起始角度
  6013. * @param {number} endAngle 结束角度
  6014. */
  6015. length: function length(cx, cy, rx, ry, xRotation, startAngle, endAngle) {},
  6016. /**
  6017. * 获取指定点到圆弧的最近距离的点
  6018. * @param {number} cx 圆心 x
  6019. * @param {number} cy 圆心 y
  6020. * @param {number} rx x 轴方向的半径
  6021. * @param {number} ry y 轴方向的半径
  6022. * @param {number} xRotation 旋转角度
  6023. * @param {number} startAngle 起始角度
  6024. * @param {number} endAngle 结束角度
  6025. * @param {number} x0 指定点的 x
  6026. * @param {number} y0 指定点的 y
  6027. * @return {object} 到指定点最近距离的点
  6028. */
  6029. nearestPoint: function nearestPoint(cx, cy, rx, ry, xRotation, startAngle, endAngle, x0, y0) {
  6030. // 将最近距离问题转换成到椭圆中心 0,0 没有旋转的椭圆问题
  6031. var relativeVector = rotate$1(x0 - cx, y0 - cy, -xRotation);
  6032. var x1 = relativeVector[0],
  6033. y1 = relativeVector[1];
  6034. // 计算点到椭圆的最近的点
  6035. var relativePoint = ellipse.nearestPoint(0, 0, rx, ry, x1, y1);
  6036. // 获取点在椭圆上的角度
  6037. var angle = getAngle(rx, ry, relativePoint.x, relativePoint.y);
  6038. // 点没有在圆弧上
  6039. if (angle < startAngle) {
  6040. // 小于起始圆弧
  6041. relativePoint = getPoint(rx, ry, startAngle);
  6042. } else if (angle > endAngle) {
  6043. // 大于结束圆弧
  6044. relativePoint = getPoint(rx, ry, endAngle);
  6045. }
  6046. // 旋转到 xRotation 的角度
  6047. var vector = rotate$1(relativePoint.x, relativePoint.y, xRotation);
  6048. return {
  6049. x: vector[0] + cx,
  6050. y: vector[1] + cy
  6051. };
  6052. },
  6053. pointDistance: function pointDistance(cx, cy, rx, ry, xRotation, startAngle, endAngle, x0, y0) {
  6054. var nearestPoint = this.nearestPoint(cx, cy, rx, ry, xRotation, startAngle, endAngle, x0, y0);
  6055. return distance$1(nearestPoint.x, nearestPoint.y, x0, y0);
  6056. },
  6057. pointAt: function pointAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, t) {
  6058. var angle = (endAngle - startAngle) * t + startAngle;
  6059. return {
  6060. x: xAt(cx, cy, rx, ry, xRotation, angle),
  6061. y: yAt(cx, cy, rx, ry, xRotation, angle)
  6062. };
  6063. },
  6064. tangentAngle: function tangentAngle(cx, cy, rx, ry, xRotation, startAngle, endAngle, t) {
  6065. var angle = (endAngle - startAngle) * t + startAngle;
  6066. var dx = derivativeXAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle);
  6067. var dy = derivativeYAt(cx, cy, rx, ry, xRotation, startAngle, endAngle, angle);
  6068. return piMod(Math.atan2(dy, dx));
  6069. }
  6070. };
  6071. function analyzePoints(points) {
  6072. // 计算每段的长度和总的长度
  6073. var totalLength = 0;
  6074. var segments = [];
  6075. for (var i = 0; i < points.length - 1; i++) {
  6076. var from = points[i];
  6077. var to = points[i + 1];
  6078. var length = distance$1(from[0], from[1], to[0], to[1]);
  6079. var seg = {
  6080. from: from,
  6081. to: to,
  6082. length: length
  6083. };
  6084. segments.push(seg);
  6085. totalLength += length;
  6086. }
  6087. return {
  6088. segments: segments,
  6089. totalLength: totalLength
  6090. };
  6091. }
  6092. function lengthOfSegment(points) {
  6093. if (points.length < 2) {
  6094. return 0;
  6095. }
  6096. var totalLength = 0;
  6097. for (var i = 0; i < points.length - 1; i++) {
  6098. var from = points[i];
  6099. var to = points[i + 1];
  6100. totalLength += distance$1(from[0], from[1], to[0], to[1]);
  6101. }
  6102. return totalLength;
  6103. }
  6104. /**
  6105. * 按照比例在数据片段中获取点
  6106. * @param {array} points 点的集合
  6107. * @param {number} t 百分比 0-1
  6108. * @return {object} 点的坐标
  6109. */
  6110. function pointAtSegments(points, t) {
  6111. // 边界判断
  6112. if (t > 1 || t < 0 || points.length < 2) {
  6113. return null;
  6114. }
  6115. var _analyzePoints = analyzePoints(points),
  6116. segments = _analyzePoints.segments,
  6117. totalLength = _analyzePoints.totalLength;
  6118. // 多个点有可能重合
  6119. if (totalLength === 0) {
  6120. return {
  6121. x: points[0][0],
  6122. y: points[0][1]
  6123. };
  6124. }
  6125. // 计算比例
  6126. var startRatio = 0;
  6127. var point = null;
  6128. for (var i = 0; i < segments.length; i++) {
  6129. var seg = segments[i];
  6130. var from = seg.from,
  6131. to = seg.to;
  6132. var currentRatio = seg.length / totalLength;
  6133. if (t >= startRatio && t <= startRatio + currentRatio) {
  6134. var localRatio = (t - startRatio) / currentRatio;
  6135. point = line.pointAt(from[0], from[1], to[0], to[1], localRatio);
  6136. break;
  6137. }
  6138. startRatio += currentRatio;
  6139. }
  6140. return point;
  6141. }
  6142. /**
  6143. * 按照比例在数据片段中获取切线的角度
  6144. * @param {array} points 点的集合
  6145. * @param {number} t 百分比 0-1
  6146. */
  6147. function angleAtSegments(points, t) {
  6148. // 边界判断
  6149. if (t > 1 || t < 0 || points.length < 2) {
  6150. return 0;
  6151. }
  6152. var _analyzePoints2 = analyzePoints(points),
  6153. segments = _analyzePoints2.segments,
  6154. totalLength = _analyzePoints2.totalLength;
  6155. // 计算比例
  6156. var startRatio = 0;
  6157. var angle = 0;
  6158. for (var i = 0; i < segments.length; i++) {
  6159. var seg = segments[i];
  6160. var from = seg.from,
  6161. to = seg.to;
  6162. var currentRatio = seg.length / totalLength;
  6163. if (t >= startRatio && t <= startRatio + currentRatio) {
  6164. angle = Math.atan2(to[1] - from[1], to[0] - from[0]);
  6165. break;
  6166. }
  6167. startRatio += currentRatio;
  6168. }
  6169. return angle;
  6170. }
  6171. function distanceAtSegment(points, x, y) {
  6172. var minDistance = Infinity;
  6173. for (var i = 0; i < points.length - 1; i++) {
  6174. var point = points[i];
  6175. var nextPoint = points[i + 1];
  6176. var _distance = line.pointDistance(point[0], point[1], nextPoint[0], nextPoint[1], x, y);
  6177. if (_distance < minDistance) {
  6178. minDistance = _distance;
  6179. }
  6180. }
  6181. return minDistance;
  6182. }
  6183. var polyline = {
  6184. /**
  6185. * 计算多折线的包围盒
  6186. * @param {array} points 点的集合 [x,y] 的形式
  6187. * @return {object} 包围盒
  6188. */
  6189. box: function box(points) {
  6190. var xArr = [];
  6191. var yArr = [];
  6192. for (var i = 0; i < points.length; i++) {
  6193. var point = points[i];
  6194. xArr.push(point[0]);
  6195. yArr.push(point[1]);
  6196. }
  6197. return getBBoxByArray(xArr, yArr);
  6198. },
  6199. /**
  6200. * 计算多折线的长度
  6201. * @param {array} points 点的集合 [x,y] 的形式
  6202. * @return {object} 多条边的长度
  6203. */
  6204. length: function length(points) {
  6205. return lengthOfSegment(points);
  6206. },
  6207. /**
  6208. * 根据比例获取多折线的点
  6209. * @param {array} points 点的集合 [x,y] 的形式
  6210. * @param {number} t 在多折线的长度上的比例
  6211. * @return {object} 根据比例值计算出来的点
  6212. */
  6213. pointAt: function pointAt(points, t) {
  6214. return pointAtSegments(points, t);
  6215. },
  6216. /**
  6217. * 指定点到多折线的距离
  6218. * @param {array} points 点的集合 [x,y] 的形式
  6219. * @param {number} x 指定点的 x
  6220. * @param {number} y 指定点的 y
  6221. * @return {number} 点到多折线的距离
  6222. */
  6223. pointDistance: function pointDistance(points, x, y) {
  6224. return distanceAtSegment(points, x, y);
  6225. },
  6226. /**
  6227. * 根据比例获取多折线的切线角度
  6228. * @param {array} points 点的集合 [x,y] 的形式
  6229. * @param {number} t 在多折线的长度上的比例
  6230. * @return {object} 根据比例值计算出来的角度
  6231. */
  6232. tangentAngle: function tangentAngle(points, t) {
  6233. return angleAtSegments(points, t);
  6234. }
  6235. };
  6236. var eventemitter3 = createCommonjsModule(function (module) {
  6237. var has = Object.prototype.hasOwnProperty
  6238. , prefix = '~';
  6239. /**
  6240. * Constructor to create a storage for our `EE` objects.
  6241. * An `Events` instance is a plain object whose properties are event names.
  6242. *
  6243. * @constructor
  6244. * @private
  6245. */
  6246. function Events() {}
  6247. //
  6248. // We try to not inherit from `Object.prototype`. In some engines creating an
  6249. // instance in this way is faster than calling `Object.create(null)` directly.
  6250. // If `Object.create(null)` is not supported we prefix the event names with a
  6251. // character to make sure that the built-in object properties are not
  6252. // overridden or used as an attack vector.
  6253. //
  6254. if (Object.create) {
  6255. Events.prototype = Object.create(null);
  6256. //
  6257. // This hack is needed because the `__proto__` property is still inherited in
  6258. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  6259. //
  6260. if (!new Events().__proto__) prefix = false;
  6261. }
  6262. /**
  6263. * Representation of a single event listener.
  6264. *
  6265. * @param {Function} fn The listener function.
  6266. * @param {*} context The context to invoke the listener with.
  6267. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  6268. * @constructor
  6269. * @private
  6270. */
  6271. function EE(fn, context, once) {
  6272. this.fn = fn;
  6273. this.context = context;
  6274. this.once = once || false;
  6275. }
  6276. /**
  6277. * Add a listener for a given event.
  6278. *
  6279. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  6280. * @param {(String|Symbol)} event The event name.
  6281. * @param {Function} fn The listener function.
  6282. * @param {*} context The context to invoke the listener with.
  6283. * @param {Boolean} once Specify if the listener is a one-time listener.
  6284. * @returns {EventEmitter}
  6285. * @private
  6286. */
  6287. function addListener(emitter, event, fn, context, once) {
  6288. if (typeof fn !== 'function') {
  6289. throw new TypeError('The listener must be a function');
  6290. }
  6291. var listener = new EE(fn, context || emitter, once)
  6292. , evt = prefix ? prefix + event : event;
  6293. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  6294. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  6295. else emitter._events[evt] = [emitter._events[evt], listener];
  6296. return emitter;
  6297. }
  6298. /**
  6299. * Clear event by name.
  6300. *
  6301. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  6302. * @param {(String|Symbol)} evt The Event name.
  6303. * @private
  6304. */
  6305. function clearEvent(emitter, evt) {
  6306. if (--emitter._eventsCount === 0) emitter._events = new Events();
  6307. else delete emitter._events[evt];
  6308. }
  6309. /**
  6310. * Minimal `EventEmitter` interface that is molded against the Node.js
  6311. * `EventEmitter` interface.
  6312. *
  6313. * @constructor
  6314. * @public
  6315. */
  6316. function EventEmitter() {
  6317. this._events = new Events();
  6318. this._eventsCount = 0;
  6319. }
  6320. /**
  6321. * Return an array listing the events for which the emitter has registered
  6322. * listeners.
  6323. *
  6324. * @returns {Array}
  6325. * @public
  6326. */
  6327. EventEmitter.prototype.eventNames = function eventNames() {
  6328. var names = []
  6329. , events
  6330. , name;
  6331. if (this._eventsCount === 0) return names;
  6332. for (name in (events = this._events)) {
  6333. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  6334. }
  6335. if (Object.getOwnPropertySymbols) {
  6336. return names.concat(Object.getOwnPropertySymbols(events));
  6337. }
  6338. return names;
  6339. };
  6340. /**
  6341. * Return the listeners registered for a given event.
  6342. *
  6343. * @param {(String|Symbol)} event The event name.
  6344. * @returns {Array} The registered listeners.
  6345. * @public
  6346. */
  6347. EventEmitter.prototype.listeners = function listeners(event) {
  6348. var evt = prefix ? prefix + event : event
  6349. , handlers = this._events[evt];
  6350. if (!handlers) return [];
  6351. if (handlers.fn) return [handlers.fn];
  6352. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  6353. ee[i] = handlers[i].fn;
  6354. }
  6355. return ee;
  6356. };
  6357. /**
  6358. * Return the number of listeners listening to a given event.
  6359. *
  6360. * @param {(String|Symbol)} event The event name.
  6361. * @returns {Number} The number of listeners.
  6362. * @public
  6363. */
  6364. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  6365. var evt = prefix ? prefix + event : event
  6366. , listeners = this._events[evt];
  6367. if (!listeners) return 0;
  6368. if (listeners.fn) return 1;
  6369. return listeners.length;
  6370. };
  6371. /**
  6372. * Calls each of the listeners registered for a given event.
  6373. *
  6374. * @param {(String|Symbol)} event The event name.
  6375. * @returns {Boolean} `true` if the event had listeners, else `false`.
  6376. * @public
  6377. */
  6378. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  6379. var evt = prefix ? prefix + event : event;
  6380. if (!this._events[evt]) return false;
  6381. var listeners = this._events[evt]
  6382. , len = arguments.length
  6383. , args
  6384. , i;
  6385. if (listeners.fn) {
  6386. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  6387. switch (len) {
  6388. case 1: return listeners.fn.call(listeners.context), true;
  6389. case 2: return listeners.fn.call(listeners.context, a1), true;
  6390. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  6391. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  6392. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  6393. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  6394. }
  6395. for (i = 1, args = new Array(len -1); i < len; i++) {
  6396. args[i - 1] = arguments[i];
  6397. }
  6398. listeners.fn.apply(listeners.context, args);
  6399. } else {
  6400. var length = listeners.length
  6401. , j;
  6402. for (i = 0; i < length; i++) {
  6403. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  6404. switch (len) {
  6405. case 1: listeners[i].fn.call(listeners[i].context); break;
  6406. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  6407. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  6408. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  6409. default:
  6410. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  6411. args[j - 1] = arguments[j];
  6412. }
  6413. listeners[i].fn.apply(listeners[i].context, args);
  6414. }
  6415. }
  6416. }
  6417. return true;
  6418. };
  6419. /**
  6420. * Add a listener for a given event.
  6421. *
  6422. * @param {(String|Symbol)} event The event name.
  6423. * @param {Function} fn The listener function.
  6424. * @param {*} [context=this] The context to invoke the listener with.
  6425. * @returns {EventEmitter} `this`.
  6426. * @public
  6427. */
  6428. EventEmitter.prototype.on = function on(event, fn, context) {
  6429. return addListener(this, event, fn, context, false);
  6430. };
  6431. /**
  6432. * Add a one-time listener for a given event.
  6433. *
  6434. * @param {(String|Symbol)} event The event name.
  6435. * @param {Function} fn The listener function.
  6436. * @param {*} [context=this] The context to invoke the listener with.
  6437. * @returns {EventEmitter} `this`.
  6438. * @public
  6439. */
  6440. EventEmitter.prototype.once = function once(event, fn, context) {
  6441. return addListener(this, event, fn, context, true);
  6442. };
  6443. /**
  6444. * Remove the listeners of a given event.
  6445. *
  6446. * @param {(String|Symbol)} event The event name.
  6447. * @param {Function} fn Only remove the listeners that match this function.
  6448. * @param {*} context Only remove the listeners that have this context.
  6449. * @param {Boolean} once Only remove one-time listeners.
  6450. * @returns {EventEmitter} `this`.
  6451. * @public
  6452. */
  6453. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  6454. var evt = prefix ? prefix + event : event;
  6455. if (!this._events[evt]) return this;
  6456. if (!fn) {
  6457. clearEvent(this, evt);
  6458. return this;
  6459. }
  6460. var listeners = this._events[evt];
  6461. if (listeners.fn) {
  6462. if (
  6463. listeners.fn === fn &&
  6464. (!once || listeners.once) &&
  6465. (!context || listeners.context === context)
  6466. ) {
  6467. clearEvent(this, evt);
  6468. }
  6469. } else {
  6470. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  6471. if (
  6472. listeners[i].fn !== fn ||
  6473. (once && !listeners[i].once) ||
  6474. (context && listeners[i].context !== context)
  6475. ) {
  6476. events.push(listeners[i]);
  6477. }
  6478. }
  6479. //
  6480. // Reset the array, or remove it completely if we have no more listeners.
  6481. //
  6482. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  6483. else clearEvent(this, evt);
  6484. }
  6485. return this;
  6486. };
  6487. /**
  6488. * Remove all listeners, or those of the specified event.
  6489. *
  6490. * @param {(String|Symbol)} [event] The event name.
  6491. * @returns {EventEmitter} `this`.
  6492. * @public
  6493. */
  6494. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  6495. var evt;
  6496. if (event) {
  6497. evt = prefix ? prefix + event : event;
  6498. if (this._events[evt]) clearEvent(this, evt);
  6499. } else {
  6500. this._events = new Events();
  6501. this._eventsCount = 0;
  6502. }
  6503. return this;
  6504. };
  6505. //
  6506. // Alias methods names because people roll like that.
  6507. //
  6508. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  6509. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  6510. //
  6511. // Expose the prefix.
  6512. //
  6513. EventEmitter.prefixed = prefix;
  6514. //
  6515. // Allow `EventEmitter` to be imported as module namespace.
  6516. //
  6517. EventEmitter.EventEmitter = EventEmitter;
  6518. //
  6519. // Expose the module.
  6520. //
  6521. {
  6522. module.exports = EventEmitter;
  6523. }
  6524. });
  6525. /**
  6526. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type
  6527. */(function(PropertySyntax){/**
  6528. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#coordinate
  6529. */PropertySyntax["COORDINATE"]="<coordinate>";/**
  6530. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#color
  6531. */PropertySyntax["COLOR"]="<color>";/**
  6532. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#paint
  6533. */PropertySyntax["PAINT"]="<paint>";/**
  6534. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#number
  6535. */PropertySyntax["NUMBER"]="<number>";/**
  6536. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/angle
  6537. */PropertySyntax["ANGLE"]="<angle>";/**
  6538. * <number> with range 0..1
  6539. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#opacity_value
  6540. */PropertySyntax["OPACITY_VALUE"]="<opacity-value>";/**
  6541. * <number> with range 0..Infinity
  6542. */PropertySyntax["SHADOW_BLUR"]="<shadow-blur>";/**
  6543. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#length
  6544. */PropertySyntax["LENGTH"]="<length>";/**
  6545. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#percentage
  6546. */PropertySyntax["PERCENTAGE"]="<percentage>";PropertySyntax["LENGTH_PERCENTAGE"]="<length> | <percentage>";PropertySyntax["LENGTH_PERCENTAGE_12"]="[<length> | <percentage>]{1,2}";/**
  6547. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin#formal_syntax
  6548. */PropertySyntax["LENGTH_PERCENTAGE_14"]="[<length> | <percentage>]{1,4}";/**
  6549. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Content_type#list-of-ts
  6550. */PropertySyntax["LIST_OF_POINTS"]="<list-of-points>";PropertySyntax["PATH"]="<path>";/**
  6551. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/filter#formal_syntax
  6552. */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 _regeneratorRuntime(){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 define(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 value(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 reset(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 stop(){this.done=!0;var rootRecord=this.tryEntries[0].completion;if("throw"===rootRecord.type)throw rootRecord.arg;return this.rval;},dispatchException:function dispatchException(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 abrupt(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 complete(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 finish(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 _catch(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 delegateYield(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);}// These units are iterated through, so be careful when adding or changing the
  6553. // order.
  6554. (function(UnitType){UnitType[UnitType["kUnknown"]=0]="kUnknown";UnitType[UnitType["kNumber"]=1]="kNumber";UnitType[UnitType["kPercentage"]=2]="kPercentage";// Length units
  6555. UnitType[UnitType["kEms"]=3]="kEms";// kExs,
  6556. UnitType[UnitType["kPixels"]=4]="kPixels";// kCentimeters,
  6557. // kMillimeters,
  6558. // kInches,
  6559. // kPoints,
  6560. // kPicas,
  6561. // kQuarterMillimeters,
  6562. // https://drafts.csswg.org/css-values-4/#viewport-relative-lengths
  6563. //
  6564. // See also IsViewportPercentageLength.
  6565. // kViewportWidth,
  6566. // kViewportHeight,
  6567. // kViewportInlineSize,
  6568. // kViewportBlockSize,
  6569. // kViewportMin,
  6570. // kViewportMax,
  6571. // kSmallViewportWidth,
  6572. // kSmallViewportHeight,
  6573. // kSmallViewportInlineSize,
  6574. // kSmallViewportBlockSize,
  6575. // kSmallViewportMin,
  6576. // kSmallViewportMax,
  6577. // kLargeViewportWidth,
  6578. // kLargeViewportHeight,
  6579. // kLargeViewportInlineSize,
  6580. // kLargeViewportBlockSize,
  6581. // kLargeViewportMin,
  6582. // kLargeViewportMax,
  6583. // kDynamicViewportWidth,
  6584. // kDynamicViewportHeight,
  6585. // kDynamicViewportInlineSize,
  6586. // kDynamicViewportBlockSize,
  6587. // kDynamicViewportMin,
  6588. // kDynamicViewportMax,
  6589. // https://drafts.csswg.org/css-contain-3/#container-lengths
  6590. //
  6591. // See also IsContainerPercentageLength.
  6592. // kContainerWidth,
  6593. // kContainerHeight,
  6594. // kContainerInlineSize,
  6595. // kContainerBlockSize,
  6596. // kContainerMin,
  6597. // kContainerMax,
  6598. UnitType[UnitType["kRems"]=5]="kRems";// kChs,
  6599. // kUserUnits, // The SVG term for unitless lengths
  6600. // Angle units
  6601. UnitType[UnitType["kDegrees"]=6]="kDegrees";UnitType[UnitType["kRadians"]=7]="kRadians";UnitType[UnitType["kGradians"]=8]="kGradians";UnitType[UnitType["kTurns"]=9]="kTurns";// Time units
  6602. UnitType[UnitType["kMilliseconds"]=10]="kMilliseconds";UnitType[UnitType["kSeconds"]=11]="kSeconds";// kHertz,
  6603. // kKilohertz,
  6604. // Resolution
  6605. // kDotsPerPixel,
  6606. // kDotsPerInch,
  6607. // kDotsPerCentimeter,
  6608. // Other units
  6609. // kFraction,
  6610. UnitType[UnitType["kInteger"]=12]="kInteger";// This value is used to handle quirky margins in reflow roots (body, td,
  6611. // and th) like WinIE. The basic idea is that a stylesheet can use the value
  6612. // __qem (for quirky em) instead of em. When the quirky value is used, if
  6613. // you're in quirks mode, the margin will collapse away inside a table cell.
  6614. // This quirk is specified in the HTML spec but our impl is different.
  6615. // TODO: Remove this. crbug.com/443952
  6616. // kQuirkyEms,
  6617. })(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,
  6618. // kUResolution,
  6619. 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.
  6620. var data=[{name:'em',unit_type:exports.UnitType.kEms},// {
  6621. // name: 'ex',
  6622. // unit_type: UnitType.kExs,
  6623. // },
  6624. {name:'px',unit_type:exports.UnitType.kPixels},// {
  6625. // name: "cm",
  6626. // unit_type: UnitType.kCentimeters,
  6627. // },
  6628. // {
  6629. // name: "mm",
  6630. // unit_type: UnitType.kMillimeters,
  6631. // },
  6632. // {
  6633. // name: "q",
  6634. // unit_type: UnitType.kQuarterMillimeters,
  6635. // },
  6636. // {
  6637. // name: "in",
  6638. // unit_type: UnitType.kInches,
  6639. // },
  6640. // {
  6641. // name: "pt",
  6642. // unit_type: UnitType.kPoints,
  6643. // },
  6644. // {
  6645. // name: "pc",
  6646. // unit_type: UnitType.kPicas,
  6647. // },
  6648. {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},// {
  6649. // name: "hz",
  6650. // unit_type: UnitType.kHertz,
  6651. // },
  6652. // {
  6653. // name: "khz",
  6654. // unit_type: UnitType.kKilohertz,
  6655. // },
  6656. // {
  6657. // name: "dpi",
  6658. // unit_type: "kDotsPerInch",
  6659. // },
  6660. // {
  6661. // name: "dpcm",
  6662. // unit_type: "kDotsPerCentimeter",
  6663. // },
  6664. // {
  6665. // name: "dppx",
  6666. // unit_type: "kDotsPerPixel",
  6667. // },
  6668. // {
  6669. // name: "x",
  6670. // unit_type: "kDotsPerPixel",
  6671. // },
  6672. // {
  6673. // name: "vw",
  6674. // unit_type: "kViewportWidth",
  6675. // },
  6676. // {
  6677. // name: "vh",
  6678. // unit_type: "kViewportHeight",
  6679. // },
  6680. // {
  6681. // name: "vi",
  6682. // unit_type: "kViewportInlineSize",
  6683. // },
  6684. // {
  6685. // name: "vb",
  6686. // unit_type: "kViewportBlockSize",
  6687. // },
  6688. // {
  6689. // name: "vmin",
  6690. // unit_type: UnitType.kViewportMin,
  6691. // },
  6692. // {
  6693. // name: "vmax",
  6694. // unit_type: UnitType.kViewportMax,
  6695. // },
  6696. // {
  6697. // name: "svw",
  6698. // unit_type: "kSmallViewportWidth",
  6699. // },
  6700. // {
  6701. // name: "svh",
  6702. // unit_type: "kSmallViewportHeight",
  6703. // },
  6704. // {
  6705. // name: "svi",
  6706. // unit_type: "kSmallViewportInlineSize",
  6707. // },
  6708. // {
  6709. // name: "svb",
  6710. // unit_type: "kSmallViewportBlockSize",
  6711. // },
  6712. // {
  6713. // name: "svmin",
  6714. // unit_type: "kSmallViewportMin",
  6715. // },
  6716. // {
  6717. // name: "svmax",
  6718. // unit_type: "kSmallViewportMax",
  6719. // },
  6720. // {
  6721. // name: "lvw",
  6722. // unit_type: "kLargeViewportWidth",
  6723. // },
  6724. // {
  6725. // name: "lvh",
  6726. // unit_type: "kLargeViewportHeight",
  6727. // },
  6728. // {
  6729. // name: "lvi",
  6730. // unit_type: "kLargeViewportInlineSize",
  6731. // },
  6732. // {
  6733. // name: "lvb",
  6734. // unit_type: "kLargeViewportBlockSize",
  6735. // },
  6736. // {
  6737. // name: "lvmin",
  6738. // unit_type: UnitType.kLargeViewportMin,
  6739. // },
  6740. // {
  6741. // name: "lvmax",
  6742. // unit_type: UnitType.kLargeViewportMax,
  6743. // },
  6744. // {
  6745. // name: "dvw",
  6746. // unit_type: UnitType.kDynamicViewportWidth,
  6747. // },
  6748. // {
  6749. // name: "dvh",
  6750. // unit_type: UnitType.kDynamicViewportHeight,
  6751. // },
  6752. // {
  6753. // name: "dvi",
  6754. // unit_type: UnitType.kDynamicViewportInlineSize,
  6755. // },
  6756. // {
  6757. // name: "dvb",
  6758. // unit_type: UnitType.kDynamicViewportBlockSize,
  6759. // },
  6760. // {
  6761. // name: "dvmin",
  6762. // unit_type: UnitType.kDynamicViewportMin,
  6763. // },
  6764. // {
  6765. // name: "dvmax",
  6766. // unit_type: UnitType.kDynamicViewportMax,
  6767. // },
  6768. // {
  6769. // name: "cqw",
  6770. // unit_type: UnitType.kContainerWidth,
  6771. // },
  6772. // {
  6773. // name: "cqh",
  6774. // unit_type: UnitType.kContainerHeight,
  6775. // },
  6776. // {
  6777. // name: "cqi",
  6778. // unit_type: UnitType.kContainerInlineSize,
  6779. // },
  6780. // {
  6781. // name: "cqb",
  6782. // unit_type: UnitType.kContainerBlockSize,
  6783. // },
  6784. // {
  6785. // name: "cqmin",
  6786. // unit_type: UnitType.kContainerMin,
  6787. // },
  6788. // {
  6789. // name: "cqmax",
  6790. // unit_type: UnitType.kContainerMax,
  6791. // },
  6792. {name:'rem',unit_type:exports.UnitType.kRems},// {
  6793. // name: 'fr',
  6794. // unit_type: UnitType.kFraction,
  6795. // },
  6796. {name:'turn',unit_type:exports.UnitType.kTurns}// {
  6797. // name: 'ch',
  6798. // unit_type: UnitType.kChs,
  6799. // },
  6800. // {
  6801. // name: '__qem',
  6802. // unit_type: UnitType.kQuirkyEms,
  6803. // },
  6804. ];var CSSStyleValueType;(function(CSSStyleValueType){CSSStyleValueType[CSSStyleValueType["kUnknownType"]=0]="kUnknownType";CSSStyleValueType[CSSStyleValueType["kUnparsedType"]=1]="kUnparsedType";CSSStyleValueType[CSSStyleValueType["kKeywordType"]=2]="kKeywordType";// Start of CSSNumericValue subclasses
  6805. 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
  6806. 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[] {
  6807. // // const propertyId = cssPropertyID(propertyName);
  6808. // // if (propertyId === CSSPropertyID.kInvalid) {
  6809. // // return [];
  6810. // // }
  6811. // // const customPropertyName = propertyId === CSSPropertyID.kVariable ? propertyName : null;
  6812. // // return fromString(propertyId, customPropertyName, value);
  6813. // return [];
  6814. // }
  6815. 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:
  6816. // case UnitType.kMillimeters:
  6817. // case UnitType.kQuarterMillimeters:
  6818. // case UnitType.kInches:
  6819. // case UnitType.kPoints:
  6820. // case UnitType.kPicas:
  6821. // case UnitType.kUserUnits:
  6822. 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:
  6823. // case UnitType.kKilohertz:
  6824. // return UnitCategory.kUFrequency;
  6825. // case UnitType.kDotsPerPixel:
  6826. // case UnitType.kDotsPerInch:
  6827. // case UnitType.kDotsPerCentimeter:
  6828. // return UnitCategory.kUResolution;
  6829. default:return UnitCategory.kUOther;}};var canonicalUnitTypeForCategory=function canonicalUnitTypeForCategory(category){// The canonical unit type is chosen according to the way
  6830. // CSSPropertyParser.ValidUnit() chooses the default unit in each category
  6831. // (based on unitflags).
  6832. 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.
  6833. case UnitCategory.kUTime:return exports.UnitType.kSeconds;case UnitCategory.kUAngle:return exports.UnitType.kDegrees;// case UnitCategory.kUFrequency:
  6834. // return UnitType.kHertz;
  6835. // case UnitCategory.kUResolution:
  6836. // return UnitType.kDotsPerPixel;
  6837. default:return exports.UnitType.kUnknown;}};/**
  6838. * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/css_primitive_value.cc#353
  6839. */var conversionToCanonicalUnitsScaleFactor=function conversionToCanonicalUnitsScaleFactor(unit_type){var factor=1.0;// FIXME: the switch can be replaced by an array of scale factors.
  6840. switch(unit_type){// These are "canonical" units in their respective categories.
  6841. case exports.UnitType.kPixels:// case UnitType.kUserUnits:
  6842. case exports.UnitType.kDegrees:case exports.UnitType.kSeconds:// case UnitType.kHertz:
  6843. break;case exports.UnitType.kMilliseconds:factor=0.001;break;// case UnitType.kCentimeters:
  6844. // // factor = kCssPixelsPerCentimeter;
  6845. // break;
  6846. // case UnitType.kDotsPerCentimeter:
  6847. // // factor = 1 / kCssPixelsPerCentimeter;
  6848. // break;
  6849. // case UnitType.kMillimeters:
  6850. // // factor = kCssPixelsPerMillimeter;
  6851. // break;
  6852. // case UnitType.kQuarterMillimeters:
  6853. // // factor = kCssPixelsPerQuarterMillimeter;
  6854. // break;
  6855. // case UnitType.kInches:
  6856. // // factor = kCssPixelsPerInch;
  6857. // break;
  6858. // case UnitType.kDotsPerInch:
  6859. // // factor = 1 / kCssPixelsPerInch;
  6860. // break;
  6861. // case UnitType.kPoints:
  6862. // // factor = kCssPixelsPerPoint;
  6863. // break;
  6864. // case UnitType.kPicas:
  6865. // // factor = kCssPixelsPerPica;
  6866. // break;
  6867. 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:
  6868. return '';case exports.UnitType.kPercentage:return '%';case exports.UnitType.kEms:// case UnitType.kQuirkyEms:
  6869. return 'em';// case UnitType.kExs:
  6870. // return 'ex';
  6871. case exports.UnitType.kRems:return 'rem';// case UnitType.kChs:
  6872. // return 'ch';
  6873. case exports.UnitType.kPixels:return 'px';// case UnitType.kCentimeters:
  6874. // return 'cm';
  6875. // case UnitType.kDotsPerPixel:
  6876. // return 'dppx';
  6877. // case UnitType.kDotsPerInch:
  6878. // return 'dpi';
  6879. // case UnitType.kDotsPerCentimeter:
  6880. // return 'dpcm';
  6881. // case UnitType.kMillimeters:
  6882. // return 'mm';
  6883. // case UnitType.kQuarterMillimeters:
  6884. // return 'q';
  6885. // case UnitType.kInches:
  6886. // return 'in';
  6887. // case UnitType.kPoints:
  6888. // return 'pt';
  6889. // case UnitType.kPicas:
  6890. // return 'pc';
  6891. 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:
  6892. // return 'hz';
  6893. // case UnitType.kKilohertz:
  6894. // return 'khz';
  6895. case exports.UnitType.kTurns:return 'turn';}return '';};/**
  6896. * CSSStyleValue is the base class for all CSS values accessible from Typed OM.
  6897. * Values that are not yet supported as specific types are also returned as base CSSStyleValues.
  6898. *
  6899. * Spec @see https://drafts.css-houdini.org/css-typed-om/#stylevalue-objects
  6900. * Docs @see https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleValue
  6901. */var CSSStyleValue=/*#__PURE__*/function(){function CSSStyleValue(){}// static parse(propertyName: string, value: string): CSSStyleValue {
  6902. // return parseCSSStyleValue(propertyName, value)[0];
  6903. // }
  6904. // static parseAll(propertyName: string, value: string): CSSStyleValue[] {
  6905. // return parseCSSStyleValue(propertyName, value);
  6906. // }
  6907. 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) {
  6908. // return type >= UnitType.kViewportWidth && type <= UnitType.kDynamicViewportMax;
  6909. // }
  6910. // static isContainerPercentageLength(type: UnitType) {
  6911. // return type >= UnitType.kContainerWidth && type <= UnitType.kContainerMax;
  6912. // }
  6913. ;CSSStyleValue.isLength=function isLength(type){// return (type >= UnitType.kEms && type <= UnitType.kUserUnits) || type == UnitType.kQuirkyEms;
  6914. 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 ||
  6915. type===exports.UnitType.kRems// type === UnitType.kChs ||
  6916. // this.isViewportPercentageLength(type) ||
  6917. // this.isContainerPercentageLength(type)
  6918. ;};CSSStyleValue.isTime=function isTime(unit){return unit===exports.UnitType.kSeconds||unit===exports.UnitType.kMilliseconds;}// protected abstract toCSSValue(): CSSValue;
  6919. ;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;}();/**
  6920. * CSSColorValue is the base class used for the various CSS color interfaces.
  6921. *
  6922. * @see https://drafts.css-houdini.org/css-typed-om-1/#colorvalue-objects
  6923. */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 {
  6924. // let text = '';
  6925. // if (this.colorSpace === 'rgb') {
  6926. // text = `rgba(${this.channels.join(',')},${this.alpha})`;
  6927. // }
  6928. // return (result += text);
  6929. // }
  6930. /**
  6931. * @see https://drafts.css-houdini.org/css-typed-om-1/#dom-csscolorvalue-to
  6932. */;_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);/**
  6933. * CSSKeywordValue represents CSS Values that are specified as keywords
  6934. * eg. 'initial'
  6935. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSKeywordValue
  6936. * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_keyword_value.idl
  6937. */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
  6938. 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 =
  6939. // | 'length'
  6940. // | 'angle'
  6941. // | 'time'
  6942. // | 'frequency'
  6943. // | 'resolution'
  6944. // | 'flex'
  6945. // | 'percent';
  6946. // https://drafts.css-houdini.org/css-typed-om/#dictdef-cssnumerictype
  6947. // interface CSSNumericType {
  6948. // length: number;
  6949. // angle: number;
  6950. // time: number;
  6951. // frequency: number;
  6952. // resolution: number;
  6953. // flex: number;
  6954. // percent: number;
  6955. // percentHint: CSSNumericBaseType;
  6956. // }
  6957. 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));};/**
  6958. * CSSNumericValue is the base class for numeric and length typed CSS Values.
  6959. * @see https://drafts.css-houdini.org/css-typed-om/#numeric-objects
  6960. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSSNumericValue
  6961. * @see https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/core/css/cssom/css_numeric_value.idl
  6962. */ /**
  6963. * Represents numeric values that can be expressed as a single number plus a
  6964. * unit (or a naked number or percentage).
  6965. * @see https://drafts.css-houdini.org/css-typed-om/#cssunitvalue
  6966. */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,
  6967. // we simply convert to the canonical unit and back since we already have
  6968. // the scale factors for canonical units.
  6969. 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
  6970. 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:
  6971. // case UnitType.kExs:
  6972. case exports.UnitType.kRems:// case UnitType.kChs:
  6973. case exports.UnitType.kPixels:// case UnitType.kCentimeters:
  6974. // case UnitType.kDotsPerPixel:
  6975. // case UnitType.kDotsPerInch:
  6976. // case UnitType.kDotsPerCentimeter:
  6977. // case UnitType.kMillimeters:
  6978. // case UnitType.kQuarterMillimeters:
  6979. // case UnitType.kInches:
  6980. // case UnitType.kPoints:
  6981. // case UnitType.kPicas:
  6982. // case UnitType.kUserUnits:
  6983. case exports.UnitType.kDegrees:case exports.UnitType.kRadians:case exports.UnitType.kGradians:case exports.UnitType.kMilliseconds:case exports.UnitType.kSeconds:// case UnitType.kHertz:
  6984. // case UnitType.kKilohertz:
  6985. 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:
  6986. {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');/**
  6987. * The CSSRGB class represents the CSS rgb()/rgba() functions.
  6988. *
  6989. * @see https://drafts.css-houdini.org/css-typed-om-1/#cssrgb
  6990. */var CSSRGB=/*#__PURE__*/function(_CSSColorValue){_inheritsLoose(CSSRGB,_CSSColorValue);function CSSRGB(r,g,b,alpha,/**
  6991. * 'transparent' & 'none' has the same rgba data
  6992. */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);/**
  6993. * holds useful CSS-related methods.
  6994. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS
  6995. *
  6996. * * CSS Typed OM @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/factory_functions
  6997. * * register property @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
  6998. * * CSS Layout API
  6999. */var CSS={/**
  7000. * <number>
  7001. * @see https://drafts.csswg.org/css-values-4/#number-value
  7002. */number:function number(n){return new CSSUnitValue(n);},/**
  7003. * <percentage>
  7004. * @see https://drafts.csswg.org/css-values-4/#percentage-value
  7005. */percent:function percent(n){return new CSSUnitValue(n,'%');},/**
  7006. * <length>
  7007. */px:function px(n){return new CSSUnitValue(n,'px');},/**
  7008. * <length>
  7009. */em:function em(n){return new CSSUnitValue(n,'em');},rem:function rem(n){return new CSSUnitValue(n,'rem');},/**
  7010. * <angle>
  7011. */deg:function deg(n){return new CSSUnitValue(n,'deg');},/**
  7012. * <angle>
  7013. */grad:function grad(n){return new CSSUnitValue(n,'grad');},/**
  7014. * <angle>
  7015. */rad:function rad(n){return new CSSUnitValue(n,'rad');},/**
  7016. * <angle>
  7017. */turn:function turn(n){return new CSSUnitValue(n,'turn');},/**
  7018. * <time>
  7019. */s:function s(n){return new CSSUnitValue(n,'s');},/**
  7020. * <time>
  7021. */ms:function ms(n){return new CSSUnitValue(n,'ms');},/**
  7022. * CSS Properties & Values API
  7023. *
  7024. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS_Properties_and_Values_API
  7025. * @see https://drafts.css-houdini.org/css-properties-values-api/#registering-custom-properties
  7026. * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS/RegisterProperty
  7027. */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});},/**
  7028. * CSS Layout API
  7029. * register layout
  7030. *
  7031. * @see https://github.com/w3c/css-houdini-drafts/blob/main/css-layout-api/EXPLAINER.md
  7032. * @see https://developer.mozilla.org/en-US/docs/Web/Guide/Houdini#css_layout_api
  7033. */registerLayout:function registerLayout(name,clazz){runtime.layoutRegistry.registerLayout(name,clazz);}};/**
  7034. * CSSKeywordValue
  7035. */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];};/**
  7036. * CSSColor
  7037. */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(
  7038. // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
  7039. // return new CSSUnitValue(value, unitOrName);
  7040. // },
  7041. // (value: number, unitOrName: UnitType | string = UnitType.kNumber) => {
  7042. // return `${value}${unitOrName}`;
  7043. // },
  7044. // );
  7045. 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,'%');var canvasMap={};var defaultCanvasIdCounter=0;/**
  7046. * destroy existed canvas with the same id
  7047. */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
  7048. 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$1(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
  7049. // singularity at the north pole
  7050. 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
  7051. // singularity at the south pole
  7052. 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
  7053. 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
  7054. z=0;x=-Math.atan2(m[4]/sy,m[5]/sy);}}else {// Not a unique solution
  7055. z=0;x=Math.atan2(m[4]/sy,m[5]/sy);}out[0]=x;out[1]=y;out[2]=z;return out;}/**
  7056. * @see https://github.com/toji/gl-matrix/issues/329
  7057. * @see https://doc.babylonjs.com/divingDeeper/mesh/transforms/center_origin/rotation_conventions
  7058. */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
  7059. // @see https://www.w3.org/TR/css-transforms-1/#decomposing-a-2d-matrix
  7060. var scalingX=Math.sqrt(row0x*row0x+row0y*row0y);var scalingY=Math.sqrt(row1x*row1x+row1y*row1y);// If determinant is negative, one axis was flipped.
  7061. var determinant=row0x*row1y-row0y*row1x;if(determinant<0){// Flip axis with minimum unit vector dot product.
  7062. if(row0x<row1y){scalingX=-scalingX;}else {scalingY=-scalingY;}}// Renormalize matrix to remove scale.
  7063. if(scalingX){row0x*=1/scalingX;row0y*=1/scalingX;}if(scalingY){row1x*=1/scalingY;row1y*=1/scalingY;}// Compute rotation and renormalize matrix.
  7064. 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();/*
  7065. Input: matrix ; a 4x4 matrix
  7066. Output: translation ; a 3 component vector
  7067. scale ; a 3 component vector
  7068. skew ; skew factors XY,XZ,YZ represented as a 3 component vector
  7069. perspective ; a 4 component vector
  7070. quaternion ; a 4 component vector
  7071. Returns false if the matrix cannot be decomposed, true if it can
  7072. References:
  7073. https://github.com/kamicane/matrix3d/blob/master/lib/Matrix3d.js
  7074. https://github.com/ChromiumWebApps/chromium/blob/master/ui/gfx/transform_util.cc
  7075. http://www.w3.org/TR/css3-transforms/#decomposing-a-3d-matrix
  7076. */function decomposeMat4(matrix,translation,scale,skew,perspective,quaternion){//normalize, if not possible then bail out early
  7077. if(!normalize$4(tmp,matrix))return false;// perspectiveMatrix is used to solve for perspective, but it also provides
  7078. // an easy way to test for singularity of the upper 3x3 component.
  7079. 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
  7080. // decompose, so we'll bail early. Constant taken from SkMatrix44::invert.
  7081. 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.
  7082. 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
  7083. // rightHandSide by the inverse.
  7084. // resuing the perspectiveMatrix here since it's no longer needed
  7085. var ret=invert(perspectiveMatrix,perspectiveMatrix);if(!ret)return false;transpose(perspectiveMatrix,perspectiveMatrix);//multiply by transposed inverse perspective matrix, into perspective vec4
  7086. transformMat4$1(perspective,tmpVec4,perspectiveMatrix);}else {//no perspective
  7087. perspective[0]=perspective[1]=perspective[2]=0;perspective[3]=1;}// Next take care of translation
  7088. translation[0]=a30;translation[1]=a31;translation[2]=a32;// Now get scale and shear. 'row' is a 3 element array of 3 component vectors
  7089. mat3from4(row,tmp);// Compute X scale factor and normalize first row.
  7090. scale[0]=length(row[0]);normalize(row[0],row[0]);// Compute XY shear factor and make 2nd row orthogonal to 1st.
  7091. 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.
  7092. scale[1]=length(row[1]);normalize(row[1],row[1]);skew[0]/=scale[1];// Compute XZ and YZ shears, orthogonalize 3rd row
  7093. 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.
  7094. 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.
  7095. // Check for a coordinate system flip. If the determinant
  7096. // is -1, then negate the matrix and the scaling factors.
  7097. 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
  7098. 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.
  7099. 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
  7100. 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
  7101. 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)
  7102. 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
  7103. set.apply(mat4,[tmpMat4].concat(d.map(function(s){return s.value;})));tmpMat4[12]+=defX;tmpMat4[13]+=defY;object.setLocalTransform(tmpMat4);}});}return object.getLocalTransform();}/**
  7104. * borrow from gradient-parser, but we delete some browser compatible prefix such as `-webkit-`
  7105. * @see https://github.com/rafaelcaricio/gradient-parser
  7106. */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,/**
  7107. * @see https://projects.verou.me/conic-gradient/
  7108. */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
  7109. radialType.at=matchAtPosition();}else {var extent=matchExtentKeyword();if(extent){radialType=extent;var positionAt=matchAtPosition();if(positionAt){// @ts-ignore
  7110. radialType.at=positionAt;}}else {var defaultPosition=matchPositioning();if(defaultPosition){radialType={type:'default-radial',// @ts-ignore
  7111. at:defaultPosition};}}}return radialType;}function matchCircle(){var circle=match('shape',/^(circle)/i,0);if(circle){// @ts-ignore
  7112. circle.style=matchLength()||matchExtentKeyword();}return circle;}function matchEllipse(){var ellipse=match('shape',/^(ellipse)/i,0);if(ellipse){// @ts-ignore
  7113. 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
  7114. // @see https://observablehq.com/@danburzo/css-gradient-line
  7115. 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'
  7116. var x=cx.value;var y=cy.value;// TODO: 'em'
  7117. // '%'
  7118. 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
  7119. 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
  7120. 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};}(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'
  7121. for(var i=0;i<pathArray.length;i++){var params=pathArray[i];var cmd=params[0];if(cmd==='M'){// 遇到 'M' 判定是否是新数组,新数组中没有点
  7122. if(points.length){// 如果存在点,则说明没有遇到 'Z',开始了一个新的多边形
  7123. polylines.push(points);points=[];// 创建新的点
  7124. }points.push([params[1],params[2]]);}else if(cmd==='Z'){if(points.length){// 存在点
  7125. polygons.push(points);points=[];// 开始新的点集合
  7126. }// 如果不存在点,同时 'Z',则说明是错误,不处理
  7127. }else {points.push([params[1],params[2]]);}}// 说明 points 未放入 polygons 或者 polyline
  7128. // 仅当只有一个 M,没有 Z 时会发生这种情况
  7129. 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
  7130. // ref: https://github.com/antvis/g/issues/210
  7131. // ref: https://github.com/antvis/G2/issues/3109
  7132. 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 为顶点的夹角
  7133. var currentAngle=Math.acos((currentAndPre+currentAndNext-preAndNext)/(2*Math.sqrt(currentAndPre)*Math.sqrt(currentAndNext)));// 夹角为空、 0 或 PI 时,不需要计算夹角处的额外宽度
  7134. // 注意: 由于计算精度问题,夹角为 0 的情况计算出来的角度可能是一个很小的值,还需要判断其与 0 是否近似相等
  7135. 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]));// 将夹角转为锐角
  7136. xAngle=xAngle>Math.PI/2?Math.PI-xAngle:xAngle;yAngle=yAngle>Math.PI/2?Math.PI-yAngle:yAngle;// 这里不考虑在水平和垂直方向的投影,直接使用最大差值
  7137. // 由于上层统一加减了二分之一线宽,这里需要进行弥补
  7138. var extra={// 水平方向投影
  7139. xExtra:Math.cos(currentAngle/2-xAngle)*(lineWidth/2*(1/Math.sin(currentAngle/2)))-lineWidth/2||0,// 垂直方向投影
  7140. yExtra:Math.cos(yAngle-currentAngle/2)*(lineWidth/2*(1/Math.sin(currentAngle/2)))-lineWidth/2||0};return extra;}// 点对称
  7141. 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;};/**
  7142. * @see https://github.com/rveciana/svg-path-properties/blob/b6bd9a322966f6ef7a311872d80c56e3718de861/src/arc.ts#L121
  7143. */var pointOnEllipticalArc=function pointOnEllipticalArc(p0,rx,ry,xAxisRotation,largeArcFlag,sweepFlag,p1,t){// In accordance to: http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters
  7144. 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.
  7145. if(p0.x===p1.x&&p0.y===p1.y){return {x:p0.x,y:p0.y,ellipticalArcAngle:0};// Check if angle is correct
  7146. }// If rx = 0 or ry = 0 then this arc is treated as a straight line segment joining the endpoints.
  7147. if(rx===0||ry===0){//return this.pointOnLine(p0, p1, t);
  7148. return {x:0,y:0,ellipticalArcAngle:0};// Check if angle is correct
  7149. }// Following "Conversion from endpoint to center parameterization"
  7150. // http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
  7151. // Step #1: Compute transformedPoint
  7152. 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
  7153. 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
  7154. 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
  7155. 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
  7156. 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
  7157. // Start angle of the elliptical arc prior to the stretch and rotate operations.
  7158. // Difference between the start and end angles
  7159. 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)
  7160. sweepAngle%=2*Math.PI;// From http://www.w3.org/TR/SVG/implnote.html#ArcParameterizationAlternatives
  7161. 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;// 当前图形
  7162. var nextParams=null;// 下一节点的 path 参数
  7163. var startMovePoint=null;// 开始 M 的点,可能会有多个
  7164. var lastStartMovePointIndex=0;// 最近一个开始点 M 的索引
  7165. var count=path.length;for(var i=0;i<count;i++){var params=path[i];nextParams=path[i+1];var command=params[0];// 数学定义上的参数,便于后面的计算
  7166. 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 的点开始
  7167. currentPoint=startMovePoint;// 如果当前点的命令为 Z,相当于当前点为最近一个 M 点,则下一个点直接指向最近一个 M 点的下一个点
  7168. nextParams=path[lastStartMovePointIndex+1];}else {var len=params.length;currentPoint=[params[len-2],params[len-1]];}if(nextParams&&nextParams[0]==='Z'){// 如果下一个点的命令为 Z,则下一个点直接指向最近一个 M 点
  7169. nextParams=path[lastStartMovePointIndex];if(segments[lastStartMovePointIndex]){// 如果下一个点的命令为 Z,则最近一个 M 点的前一个点为当前点
  7170. segments[lastStartMovePointIndex].prePoint=currentPoint;}}segment.currentPoint=currentPoint;// 如果当前点与最近一个 M 点相同,则最近一个 M 点的前一个点为当前点的前一个点
  7171. 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
  7172. 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'){// 二次贝塞尔曲线只有一个控制点
  7173. var cp=[params[1],params[2]];// 二次贝塞尔曲线的终点为 currentPoint
  7174. 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
  7175. 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'){// 三次贝塞尔曲线有两个控制点
  7176. 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]
  7177. 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 命令
  7178. segment.startTangent=[prePoint[0]-_cp2[0],prePoint[1]-_cp2[1]];segment.endTangent=[currentPoint[0]-_cp3[0],currentPoint[1]-_cp3[1]];}else {// @ts-ignore
  7179. segment.command='SQ';// 将 S 命令变换为 SQ 命令
  7180. 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;}/**
  7181. * Use length instead of ratio
  7182. */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};}// 向量长度
  7183. function vMag(v){return Math.sqrt(v[0]*v[0]+v[1]*v[1]);}// u.v/|u||v|,计算夹角的余弦值
  7184. function vRatio(u,v){// 当存在一个向量的长度为 0 时,夹角也为 0,即夹角的余弦值为 1
  7185. return vMag(u)*vMag(v)?(u[0]*v[0]+u[1]*v[1])/(vMag(u)*vMag(v)):1;}// 向量角度
  7186. 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];// 弧形起点坐标
  7187. var x1=startPoint[0];var y1=startPoint[1];// 弧形终点坐标
  7188. 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) 处理
  7189. var cxp=ry?f*rx*yp/ry:0;var cyp=rx?f*-ry*xp/rx:0;// 椭圆圆心坐标
  7190. 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;// 起始点的单位向量
  7191. var u=[(xp-cxp)/rx,(yp-cyp)/ry];// 终止点的单位向量
  7192. var v=[(-1*xp-cxp)/rx,(-1*yp-cyp)/ry];// 计算起始点和圆心的连线,与 x 轴正方向的夹角
  7193. var theta=vAngle([1,0],u);// 计算圆弧起始点和终止点与椭圆圆心连线的夹角
  7194. 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 处理
  7195. 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
  7196. 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
  7197. 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']];}/**
  7198. * convert object to path, should account for:
  7199. * * transform & origin
  7200. * * anchor
  7201. * * lineWidth
  7202. */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
  7203. 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
  7204. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
  7205. 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.
  7206. 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
  7207. _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
  7208. 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
  7209. // const fontSizeString: string = isNumber(fontSize) ? `${fontSize}px` : fontSize.toString();
  7210. var fontSizeString=isNumber(fontSize)&&fontSize+"px"||'16px';// Clean-up fontFamily property by quoting each font name
  7211. // this will support font names with spaces
  7212. var fontFamilies=fontFamily.split(',');for(var i=fontFamilies.length-1;i>=0;i--){// Trim any extra white-space
  7213. var _fontFamily=fontFamilies[i].trim();// Check if font already contains strings
  7214. if(!stringRegExp.test(_fontFamily)&&genericFontFamilies.indexOf(_fontFamily)<0){_fontFamily="\""+_fontFamily+"\"";}fontFamilies[i]=_fontFamily;}return fontStyle+" "+fontVariant+" "+fontWeight+" "+fontSizeString+" "+fontFamilies.join(',');}/**
  7215. * Thanks for following contributor of codes
  7216. * https://gist.github.com/1866474
  7217. * http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  7218. * http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  7219. * https://github.com/Financial-Times/polyfill-library/blob/master/polyfills/requestAnimationFrame/polyfill.js
  7220. **/var uId=1;var uniqueId=function uniqueId(){return uId++;};// We use `self` instead of `window` for `WebWorker` support.
  7221. var root=typeof self==='object'&&self.self==self?self:// @ts-ignore
  7222. typeof global==='object'&&global.global==global?// @ts-ignore
  7223. global:{};var nowOffset=Date.now();// use performance api if exist, otherwise use Date.now.
  7224. // Date.now polyfill required.
  7225. var pnow=function pnow(){if(root.performance&&typeof root.performance.now==='function'){return root.performance.now();}// fallback
  7226. 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 이 걸려있는 경우.
  7227. // 함께 callback 이 실행될 수 있게 reservedCBs 에만 추가해주고 return
  7228. 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'
  7229. 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.
  7230. // different from CSS side(to top) @see https://developer.mozilla.org/en-US/docs/Web/CSS/gradient/linear-gradient#values
  7231. 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
  7232. 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
  7233. // TODO: repeating-linear-gradient & repeating-radial-gradient
  7234. // } else if (type === 'repeating-linear-gradient') {
  7235. // } else if (type === 'repeating-radial-gradient') {
  7236. }});}// legacy format, should be deprecated later
  7237. 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
  7238. 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);}/**
  7239. * @see https://github.com/WebKit/WebKit/blob/main/Source/WebCore/css/parser/CSSParser.cpp#L97
  7240. */var parseColor=memoize(function(colorStr){if(isPattern(colorStr)){return _extends({repetition:'repeat'},colorStr);}if(isNil(colorStr)){colorStr='';}if(colorStr==='transparent'){// transparent black
  7241. return transparentColor;}else if(colorStr==='currentColor'){// @see https://github.com/adobe-webplatform/Snap.svg/issues/526
  7242. colorStr='black';}// support CSS gradient syntax
  7243. var g=parseGradient$1(colorStr);if(g){return g;}// constants
  7244. 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);
  7245. return getOrCreateRGBA.apply(void 0,rgba);});function mergeColors(left,right){// only support constant value, exclude gradient & pattern
  7246. 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];}/**
  7247. * <length>
  7248. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length
  7249. * length with only absolute unit, eg. 1px
  7250. */var parseLength=memoize(function(css){return parseDimension(new RegExp('px','g'),css);});/**
  7251. * <percentage>
  7252. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/percentage
  7253. */var parserPercentage=memoize(function(css){return parseDimension(new RegExp('%','g'),css);});/**
  7254. * length with absolute or relative unit,
  7255. * eg. 1px, 0.7em, 50%, calc(100% - 200px);
  7256. *
  7257. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/length-percentage
  7258. */ // export const parseLengthOrPercentage = memoize((css: string): CSSUnitValue => {
  7259. // if (isNumber(css) || isFinite(Number(css))) {
  7260. // return getOrCreateUnitValue(Number(css), 'px');
  7261. // }
  7262. // return parseDimension(new RegExp('px|%|em|rem', 'g'), css) as CSSUnitValue;
  7263. // });
  7264. var parseLengthOrPercentage=function parseLengthOrPercentage(css){if(isNumber(css)||isFinite(Number(css))){// Number(css) is NaN
  7265. return getOrCreateUnitValue(Number(css)||0,'px');// return Number(css);
  7266. }return parseDimension(new RegExp('px|%|em|rem','g'),css);};var parseAngle=memoize(function(css){return parseDimension(new RegExp('deg|rad|grad|turn','g'),css);});/**
  7267. * merge CSSUnitValue
  7268. *
  7269. * @example
  7270. * 10px + 20px = 30px
  7271. * 10deg + 10rad
  7272. * 10% + 20% = 30%
  7273. */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'
  7274. 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'
  7275. // if (CSSUnitValue.isAngle(left.unit) || CSSUnitValue.isAngle(right.unit)) {
  7276. // leftValue = convertAngleUnit(left);
  7277. // rightValue = convertAngleUnit(right);
  7278. // unit = 'deg';
  7279. // }
  7280. 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]
  7281. 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"
  7282. return string.split(' ').map(function(segment){return parseLengthOrPercentage(segment);});}else {// [1, '2px', 3]
  7283. return string.map(function(segment){return parseLengthOrPercentage(segment.toString());});}}// export function mergeDimensionList(
  7284. // left: CSSUnitValue[],
  7285. // right: CSSUnitValue[],
  7286. // target: IElement | null,
  7287. // ): [number[], number[], (list: number[]) => string] | undefined {
  7288. // if (left.length !== right.length) {
  7289. // return;
  7290. // }
  7291. // const unit = left[0].unit;
  7292. // return [
  7293. // left.map((l) => l.value),
  7294. // right.map((l) => l.value),
  7295. // (values: number[]) => {
  7296. // return values.map((n) => new CSSUnitValue(n, unit)).join(' ');
  7297. // },
  7298. // ];
  7299. // }
  7300. 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();
  7301. 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)
  7302. // return x.toFixed(6).replace(/0+$/, '').replace(/\.$/, '');
  7303. return x.toString();}/**
  7304. * parse string or number to CSSUnitValue(numeric)
  7305. *
  7306. * eg.
  7307. * * 0 -> CSSUnitValue(0)
  7308. * * '2' -> CSSUnitValue(2)
  7309. */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);}});/**
  7310. * separate string to array
  7311. * eg.
  7312. * * [0.5, 0.5] -> [CSSUnitValue, CSSUnitValue]
  7313. */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
  7314. 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
  7315. var segments=path2Segments(absolutePath);// Only calculate bbox here since we don't need length now.
  7316. 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,
  7317. // Delay the calculation of length.
  7318. 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
  7319. // @see http://thednp.github.io/kute.js/svgCubicMorph.html
  7320. 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?
  7321. return pathArray;}];}/**
  7322. * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Attribute/points
  7323. *
  7324. * @example
  7325. * points="100,10 250,150 200,110"
  7326. */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]
  7327. // In the argument types string, lowercase characters represent optional arguments
  7328. var transformFunctions={// @ts-ignore
  7329. 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]};/**
  7330. * none
  7331. * scale(1) scale(1, 2)
  7332. * scaleX(1)
  7333. */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
  7334. var functionData=transformFunctions[functionName];// scale(1, 2)
  7335. if(!functionData){// invalid, eg. scale()
  7336. return [];}var args=match[2].split(',');// 1,2
  7337. var argTypes=functionData[0];// Nn
  7338. if(argTypes.length<args.length){// scale(N, n)
  7339. 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
  7340. parsedArg={a:Odeg,n:parsedArgs[0],t:Opx}[type];}else {// @ts-ignore
  7341. 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] }
  7342. 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
  7343. 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
  7344. 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
  7345. if(left.decompositionPair!==right){// @ts-ignore
  7346. left.decompositionPair=right;// @ts-ignore
  7347. leftArgs=makeMatrixDecomposition(left);}// @ts-ignore
  7348. if(right.decompositionPair!==left){// @ts-ignore
  7349. right.decompositionPair=left;// @ts-ignore
  7350. rightArgs=makeMatrixDecomposition(right);}if(leftArgs[0]===null||rightArgs[0]===null)return [// @ts-ignore
  7351. [false],// @ts-ignore
  7352. [true],// @ts-ignore
  7353. function(x){return x?right[0].d:left[0].d;}];leftArgs[0].push(0);rightArgs[0].push(1);return [leftArgs,rightArgs,// @ts-ignore
  7354. function(list){// @ts-ignore
  7355. 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
  7356. function typeTo2D(type){return type.replace(/[xy]/,'');}// scalex/y/z -> scale3d
  7357. 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)
  7358. 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)
  7359. 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);// {
  7360. // unit: arg.unit,
  7361. // value: defaultValue,
  7362. // };
  7363. })});};for(var i=0;i<left.length;i++){_loop();}}var leftResult=[];var rightResult=[];var types=[];// merge matrix() with matrix3d()
  7364. if(left.length!==right.length){var merged=mergeMatrices(left,right);// @ts-ignore
  7365. leftResult=[merged[0]];// @ts-ignore
  7366. 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
  7367. leftResult.push(_merged[0]);// @ts-ignore
  7368. 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
  7369. leftArgs=leftFunctionData[2](leftArgs);// @ts-ignore
  7370. rightArgs=rightFunctionData[2](rightArgs);}else if(leftFunctionData[1]&&rightFunctionData[1]&&typeTo3D(leftType)===typeTo3D(rightType)){type=typeTo3D(leftType);// @ts-ignore
  7371. leftArgs=leftFunctionData[1](leftArgs);// @ts-ignore
  7372. rightArgs=rightFunctionData[1](rightArgs);}else {var _merged2=mergeMatrices(left,right);// @ts-ignore
  7373. leftResult=[_merged2[0]];// @ts-ignore
  7374. 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;
  7375. 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(' ');}];}/**
  7376. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
  7377. * eg. 'center' 'top left' '50px 50px'
  7378. */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'
  7379. values[1]=values[0];values[0]='center';}else {// '50px' -> '50px center'
  7380. values[1]='center';}}if(values.length!==2){return null;}// eg. center bottom
  7381. 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;}();/**
  7382. * clipPath / textPath / offsetPath
  7383. */var CSSPropertyClipPath=/*#__PURE__*/function(){function CSSPropertyClipPath(){}var _proto=CSSPropertyClipPath.prototype;_proto.calculator=function calculator(name,oldPath,newPath,object){// unset
  7384. if(newPath instanceof CSSKeywordValue){newPath=null;}runtime.sceneGraphService.updateDisplayObjectDependency(name,oldPath,newPath,object);if(name==='clipPath'){// should affect children
  7385. 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'
  7386. 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
  7387. if(parsed instanceof CSSKeywordValue){return [];}return parsed;};return CSSPropertyFilter;}();function getFontSize(object){var fontSize=object.parsedStyle.fontSize;return isNil(fontSize)?null:fontSize;}/**
  7388. * <length> & <percentage>
  7389. */var CSSPropertyLengthOrPercentage=/*#__PURE__*/function(){function CSSPropertyLengthOrPercentage(){this.parser=parseLengthOrPercentage;this.parserWithCSSDisabled=null;this.mixer=mergeNumbers;}var _proto=CSSPropertyLengthOrPercentage.prototype;/**
  7390. * according to parent's bounds
  7391. *
  7392. * @example
  7393. * CSS.percent(50) -> CSS.px(0.5 * parent.width)
  7394. */_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
  7395. 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
  7396. // registry.unregisterParentGeometryBoundsChangedHandler(object, name);
  7397. // return absolute value
  7398. return computed.value;}};return CSSPropertyLengthOrPercentage;}();/**
  7399. * format to Tuple2<CSSUnitValue>
  7400. *
  7401. * @example
  7402. * rect.style.lineDash = 10;
  7403. * rect.style.lineDash = [10, 10];
  7404. * rect.style.lineDash = '10 10';
  7405. */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;}();/**
  7406. * used in rounded rect
  7407. *
  7408. * @example
  7409. * rect.style.radius = 10;
  7410. * rect.style.radius = '10 10';
  7411. * rect.style.radius = '10 10 10 10';
  7412. */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>
  7413. 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;}();/**
  7414. * local position
  7415. */var CSSPropertyLocalPosition=/*#__PURE__*/function(_CSSPropertyLengthOrP){_inheritsLoose(CSSPropertyLocalPosition,_CSSPropertyLengthOrP);function CSSPropertyLocalPosition(){return _CSSPropertyLengthOrP.apply(this,arguments)||this;}var _proto=CSSPropertyLocalPosition.prototype;/**
  7416. * update local position
  7417. */_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
  7418. if(needResetLocalPosition&&attributes.indexOf('transform')===-1){// account for current transform if needed
  7419. 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
  7420. 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
  7421. 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
  7422. 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;}();/**
  7423. * opacity
  7424. */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;}();/**
  7425. * Axis-Aligned Bounding Box
  7426. * 为了便于后续 Frustum Culling,通过查找表定义 p-vertex 和 n-vertex
  7427. * @see https://github.com/antvis/GWebGPUEngine/issues/3
  7428. */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();
  7429. // halfExtents: vec3 = vec3.create();
  7430. // min: vec3 = vec3.create();
  7431. // max: vec3 = vec3.create();
  7432. _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);
  7433. // vec3.copy(this.halfExtents, halfExtents);
  7434. // vec3.sub(this.min, this.center, this.halfExtents);
  7435. // vec3.add(this.max, this.center, this.halfExtents);
  7436. };_proto.setMinMax=function setMinMax(min,max){// vec3.add(this.center, max, min);
  7437. // vec3.scale(this.center, this.center, 0.5);
  7438. // vec3.sub(this.halfExtents, max, min);
  7439. // vec3.scale(this.halfExtents, this.halfExtents, 0.5);
  7440. // vec3.copy(this.min, min);
  7441. // vec3.copy(this.max, max);
  7442. 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(
  7443. // bc,
  7444. // m[12] + mx0 * ac[0] + mx1 * ac[1] + mx2 * ac[2],
  7445. // m[13] + my0 * ac[0] + my1 * ac[1] + my2 * ac[2],
  7446. // m[14] + mz0 * ac[0] + mz1 * ac[1] + mz2 * ac[2],
  7447. // );
  7448. 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(
  7449. // br,
  7450. // mx0a * ar[0] + mx1a * ar[1] + mx2a * ar[2],
  7451. // my0a * ar[0] + my1a * ar[1] + my2a * ar[2],
  7452. // mz0a * ar[0] + mz1a * ar[1] + mz2a * ar[2],
  7453. // );
  7454. // this.min = vec3.sub(this.min, bc, br);
  7455. // this.max = vec3.add(this.max, bc, br);
  7456. 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());
  7457. // const max = vec3.min(vec3.create(), this.getMax(), aabb.getMax());
  7458. 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) {
  7459. // const min = this.getMin();
  7460. // const max = this.getMax();
  7461. // return !(
  7462. // point[0] < min[0] ||
  7463. // point[0] > max[0] ||
  7464. // point[1] < min[1] ||
  7465. // point[1] > max[1] ||
  7466. // point[2] < min[2] ||
  7467. // point[2] > max[2]
  7468. // );
  7469. // }
  7470. /**
  7471. * get n-vertex
  7472. * @param plane plane of CullingVolume
  7473. */;_proto.getNegativeFarPoint=function getNegativeFarPoint(plane){if(plane.pnVertexFlag===0x111){return copyVec3([0,0,0],this.min);// return vec3.copy(vec3.create(), this.min);
  7474. }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]);
  7475. }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]);
  7476. }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]);
  7477. }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]);
  7478. }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]);
  7479. }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]);
  7480. }else {return [this.max[0],this.max[1],this.max[2]];// return vec3.fromValues(this.max[0], this.max[1], this.max[2]);
  7481. }}/**
  7482. * get p-vertex
  7483. * @param plane plane of CullingVolume
  7484. */;_proto.getPositiveFarPoint=function getPositiveFarPoint(plane){if(plane.pnVertexFlag===0x111){return copyVec3([0,0,0],this.max);// return vec3.copy(vec3.create(), this.max);
  7485. }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]);
  7486. }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]);
  7487. }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]);
  7488. }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]);
  7489. }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]);
  7490. }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]);
  7491. }else {return [this.min[0],this.min[1],this.min[2]];// return vec3.fromValues(this.min[0], this.min[1], this.min[2]);
  7492. }};return AABB;}();var Plane=/*#__PURE__*/function(){function Plane(distance,normal){this.distance=void 0;this.normal=void 0;/**
  7493. * lookup table for p-vertex & n-vertex when doing frustum culling
  7494. */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());}}}/**
  7495. * extract 6 planes from projectionMatrix
  7496. * @see http://www8.cs.umu.se/kurser/5DV051/HT12/lab/plane_extraction.pdf
  7497. */var _proto=Frustum.prototype;_proto.extractFromVPMatrix=function extractFromVPMatrix(projectionMatrix){// @ts-ignore
  7498. 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
  7499. set$1(this.planes[0].normal,m3-m0,m7-m4,m11-m8);this.planes[0].distance=m15-m12;// left
  7500. set$1(this.planes[1].normal,m3+m0,m7+m4,m11+m8);this.planes[1].distance=m15+m12;// bottom
  7501. set$1(this.planes[2].normal,m3+m1,m7+m5,m11+m9);this.planes[2].distance=m15+m13;// top
  7502. set$1(this.planes[3].normal,m3-m1,m7-m5,m11-m9);this.planes[3].distance=m15-m13;// far
  7503. set$1(this.planes[4].normal,m3-m2,m7-m6,m11-m10);this.planes[4].distance=m15-m14;// near
  7504. 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(){/**
  7505. * path2Curve
  7506. */this.parser=parsePath;this.parserWithCSSDisabled=parsePath;this.mixer=mergePaths;}var _proto=CSSPropertyPath.prototype;_proto.calculator=function calculator(name,oldParsed,parsed){// unset
  7507. 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;};/**
  7508. * update local position
  7509. */_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;/**
  7510. * update local position
  7511. */_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
  7512. return ""+parsed;};_proto.postProcessor=function postProcessor(object){object.nodeValue=""+object.parsedStyle.text||'';};return CSSPropertyText;}();/**
  7513. * it must transform after text get parsed
  7514. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/text-transform
  7515. */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;}();/**
  7516. * @see /zh/docs/api/animation#支持变换的属性
  7517. *
  7518. * support the following formats like CSS Transform:
  7519. *
  7520. * scale
  7521. * * scale(x, y)
  7522. * * scaleX(x)
  7523. * * scaleY(x)
  7524. * * scaleZ(z)
  7525. * * scale3d(x, y, z)
  7526. *
  7527. * translate (unit: none, px, %(relative to its bounds))
  7528. * * translate(x, y) eg. translate(0, 0) translate(0, 30px) translate(100%, 100%)
  7529. * * translateX(0)
  7530. * * translateY(0)
  7531. * * translateZ(0)
  7532. * * translate3d(0, 0, 0)
  7533. *
  7534. * rotate (unit: deg rad turn)
  7535. * * rotate(0.5turn) rotate(30deg) rotate(1rad)
  7536. *
  7537. * none
  7538. *
  7539. * unsupported for now:
  7540. * * calc() eg. translate(calc(100% + 10px))
  7541. * * matrix/matrix3d()
  7542. * * skew/skewX/skewY
  7543. * * perspective
  7544. */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'
  7545. if(parsed instanceof CSSKeywordValue){return [];}return parsed;};_proto.postProcessor=function postProcessor(object){var transform=object.parsedStyle.transform;parsedTransformToMat4(transform,object);};return CSSPropertyTransform;}();/**
  7546. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/transform-origin
  7547. * @example
  7548. * [10px, 10px] [10%, 10%]
  7549. */var CSSPropertyTransformOrigin=function CSSPropertyTransformOrigin(){this.parser=parseTransformOrigin;};/**
  7550. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
  7551. */(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
  7552. if(parentSortable){parentSortable.dirty=true;parentSortable.dirtyReason=exports.SortReason.Z_INDEX_CHANGED;}}};return CSSPropertyZIndex;}();/**
  7553. * canvas.customElements
  7554. *
  7555. * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
  7556. */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;}/**
  7557. * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry/get
  7558. */;_proto.get=function get(name){return this.registry[name];};return CustomElementRegistry;}();function isFederatedEvent(value){return !!value.type;}/**
  7559. * An DOM-compatible synthetic event implementation that is "forwarded" on behalf of an original
  7560. * FederatedEvent or native {@link https://dom.spec.whatwg.org/#event Event}.
  7561. */var FederatedEvent=/*#__PURE__*/function(){/**
  7562. * The event boundary which manages this event. Propagation can only occur
  7563. * within the boundary's jurisdiction.
  7564. */function FederatedEvent(manager){/**
  7565. * The type of event, supports the following:
  7566. * * pointerdown
  7567. * * touchstart
  7568. * * mousedown
  7569. * * rightdown
  7570. * * ...
  7571. */this.type=void 0;/**
  7572. * The propagation phase.
  7573. * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/eventPhase
  7574. */this.eventPhase=FederatedEvent.prototype.NONE;/**
  7575. * can be used to implement event delegation
  7576. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
  7577. */this.target=void 0;/**
  7578. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/bubbles
  7579. */this.bubbles=true;/**
  7580. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/cancelBubble
  7581. */this.cancelBubble=true;/**
  7582. * @see https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable
  7583. */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;/**
  7584. * timestamp when the event created
  7585. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/timeStamp
  7586. */this.timeStamp=void 0;/**
  7587. * the original event.
  7588. */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;/**
  7589. * The coordinates of the evnet relative to the nearest DOM layer.
  7590. * This is a non-standard property.
  7591. */this.layer=new Point();/**
  7592. * The coordinates of the event relative to the DOM document.
  7593. * This is a non-standard property.
  7594. * relative to the DOM document.
  7595. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/pageX
  7596. */this.page=new Point();/**
  7597. * relative to Canvas, origin is left-top
  7598. */this.canvas=new Point();/**
  7599. * relative to Viewport, account for Camera
  7600. */this.viewport=new Point();this.path=void 0;/**
  7601. * @see https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/view
  7602. */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;/**
  7603. * The propagation path for this event
  7604. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/composedPath
  7605. *
  7606. * So composedPath()[0] represents the original target.
  7607. * @see https://polymer-library.polymer-project.org/3.0/docs/devguide/events#retargeting
  7608. */_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;}/**
  7609. * @deprecated
  7610. */;/**
  7611. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/preventDefault
  7612. */_proto.preventDefault=function preventDefault(){if(this.nativeEvent instanceof Event&&this.nativeEvent.cancelable){this.nativeEvent.preventDefault();}this.defaultPrevented=true;}/**
  7613. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopImmediatePropagation
  7614. */;_proto.stopImmediatePropagation=function stopImmediatePropagation(){this.propagationImmediatelyStopped=true;}/**
  7615. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Event/stopPropagation
  7616. */;_proto.stopPropagation=function stopPropagation(){this.propagationStopped=true;};/**
  7617. * added for compatibility with DOM Event,
  7618. * deprecated props and methods
  7619. */_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:/**
  7620. * @deprecated
  7621. */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;}();/**
  7622. * @see https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
  7623. *
  7624. * @example
  7625. const event = new CustomEvent('build', { detail: { prop1: 'xx' } });
  7626. circle.addEventListener('build', (e) => {
  7627. e.target; // circle
  7628. e.detail; // { prop1: 'xx' }
  7629. });
  7630. circle.dispatchEvent(event);
  7631. */var CustomEvent=/*#__PURE__*/function(_FederatedEvent){_inheritsLoose(CustomEvent,_FederatedEvent);// eslint-disable-next-line @typescript-eslint/ban-types
  7632. function CustomEvent(eventName,object){var _this;_this=_FederatedEvent.call(this,null)||this;_this.type=eventName;_this.detail=object;// compatible with G 3.0
  7633. Object.assign(_assertThisInitialized(_this),object);return _this;}return CustomEvent;}(FederatedEvent);var DELEGATION_SPLITTER=':';/**
  7634. * Objects that can receive events and may have listeners for them.
  7635. * eg. Element, Canvas, DisplayObject
  7636. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
  7637. */var EventTarget=/*#__PURE__*/function(){function EventTarget(){/**
  7638. * event emitter
  7639. */this.emitter=new eventemitter3();}var _proto=EventTarget.prototype;/**
  7640. * @deprecated
  7641. * @alias addEventListener
  7642. */_proto.on=function on(type,listener,options){this.addEventListener(type,listener,options);return this;}/**
  7643. * support `capture` & `once` in options
  7644. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/EventTarget/addEventListener
  7645. */;_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
  7646. // support using delegate name in event type, eg. 'node:click'
  7647. 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
  7648. 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
  7649. originListener.apply(void 0,args);};}if(once){this.emitter.once(type,listener,context);}else {this.emitter.on(type,listener,context);}return this;}/**
  7650. * @deprecated
  7651. * @alias removeEventListener
  7652. */;_proto.off=function off(type,listener,options){if(type){this.removeEventListener(type,listener,options);}else {// remove all listeners
  7653. 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;}/**
  7654. * @deprecated
  7655. * @alias dispatchEvent
  7656. */ // eslint-disable-next-line @typescript-eslint/ban-types
  7657. ;_proto.emit=function emit(eventName,object){this.dispatchEvent(new CustomEvent(eventName,object));}/**
  7658. * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent
  7659. */;_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
  7660. var canvas;// @ts-ignore
  7661. if(this.document){canvas=this;// @ts-ignore
  7662. }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
  7663. 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;}();/**
  7664. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node
  7665. */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;/**
  7666. * points to canvas.document
  7667. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/ownerDocument
  7668. */_this.ownerDocument=null;/**
  7669. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isConnected
  7670. * @example
  7671. circle.isConnected; // false
  7672. canvas.appendChild(circle);
  7673. circle.isConnected; // true
  7674. */_this.isConnected=false;/**
  7675. * Returns node's node document's document base URL.
  7676. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node
  7677. */_this.baseURI='';/**
  7678. * Returns the children.
  7679. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/childNodes
  7680. */_this.childNodes=[];/**
  7681. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeType
  7682. */_this.nodeType=0;/**
  7683. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeName
  7684. */_this.nodeName='';/**
  7685. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/nodeValue
  7686. */_this.nodeValue=null;/**
  7687. * @see https://developer.mozilla.org/en-US/docs/Web/API/ParentNode
  7688. */_this.parentNode=null;return _this;}Node.isNode=function isNode(target){return !!target.childNodes;};var _proto=Node.prototype;/**
  7689. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/getRootNode
  7690. */_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);}/**
  7691. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/isEqualNode
  7692. */;_proto.isEqualNode=function isEqualNode(otherNode){// TODO: compare 2 nodes, not sameness
  7693. return this===otherNode;};_proto.isSameNode=function isSameNode(otherNode){return this.isEqualNode(otherNode);};/**
  7694. * @see https://developer.mozilla.org/en-US/docs/Web/API/Node/compareDocumentPosition
  7695. * @see https://github.com/b-fuze/deno-dom/blob/master/src/dom/node.ts#L338
  7696. */_proto.compareDocumentPosition=function compareDocumentPosition(other){if(other===this){// same node
  7697. return 0;}// if (!(other instanceof Node)) {
  7698. // throw new TypeError(
  7699. // 'Node.compareDocumentPosition: Argument 1 does not implement interface Node.',
  7700. // );
  7701. // }
  7702. var node1Root=other;// eslint-disable-next-line @typescript-eslint/no-this-alias
  7703. 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
  7704. 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
  7705. if(longerHierarchy[longerHierarchy.length-shorterHierarchy.length]===shorterHierarchy[0]){return longerHierarchy===node1Hierarchy?// other is a child of this
  7706. Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING:// this is a child of other
  7707. Node.DOCUMENT_POSITION_CONTAINS|Node.DOCUMENT_POSITION_PRECEDING;}// Find their first common ancestor and see whether they
  7708. // are preceding or following
  7709. 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
  7710. if(longerHierarchyNode!==shorterHierarchyNode){var siblings=shorterHierarchyNode.parentNode.childNodes;if(siblings.indexOf(shorterHierarchyNode)<siblings.indexOf(longerHierarchyNode)){// Shorter is before longer
  7711. if(shorterHierarchy===node1Hierarchy){// Other is before this
  7712. return Node.DOCUMENT_POSITION_PRECEDING;}else {// This is before other
  7713. return Node.DOCUMENT_POSITION_FOLLOWING;}}else {// Longer is before shorter
  7714. if(longerHierarchy===node1Hierarchy){// Other is before this
  7715. return Node.DOCUMENT_POSITION_PRECEDING;}else {// Other is after this
  7716. return Node.DOCUMENT_POSITION_FOLLOWING;}}}}return Node.DOCUMENT_POSITION_FOLLOWING;}/**
  7717. * @deprecated
  7718. * @alias contains
  7719. */;_proto.contain=function contain(other){return this.contains(other);};_proto.contains=function contains(other){// the node itself, one of its direct children
  7720. var tmp=other;// @see https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
  7721. while(tmp&&this!==tmp){tmp=tmp.parentNode;}return !!tmp;};_proto.getAncestor=function getAncestor(n){// eslint-disable-next-line @typescript-eslint/no-this-alias
  7722. 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:/**
  7723. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Node/textContent
  7724. */function get(){var out='';if(this.nodeName===exports.Shape.TEXT){// @ts-ignore
  7725. 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
  7726. this.childNodes.slice().forEach(function(child){_this2.removeChild(child);});if(this.nodeName===exports.Shape.TEXT){// @ts-ignore
  7727. this.style.text=""+content;}}},{key:"parent",get:/**
  7728. * @deprecated
  7729. * @alias parentNode
  7730. */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);/**
  7731. * Both nodes are in different documents or different trees in the same document.
  7732. */Node.DOCUMENT_POSITION_DISCONNECTED=1;/**
  7733. * otherNode precedes the node in either a pre-order depth-first traversal
  7734. * 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.
  7735. */Node.DOCUMENT_POSITION_PRECEDING=2;/**
  7736. * 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.
  7737. */Node.DOCUMENT_POSITION_FOLLOWING=4;/**
  7738. * otherNode is an ancestor of the node.
  7739. */Node.DOCUMENT_POSITION_CONTAINS=8;/**
  7740. * otherNode is a descendant of the node.
  7741. */Node.DOCUMENT_POSITION_CONTAINED_BY=16;/**
  7742. * The result relies upon arbitrary and/or implementation-specific behavior and is not guaranteed to be portable.
  7743. */Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC=32;/**
  7744. * the entry of DOM tree
  7745. * Document -> Node -> EventTarget
  7746. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document
  7747. */var Document=/*#__PURE__*/function(_Node){_inheritsLoose(Document,_Node);function Document(){var _this;_this=_Node.call(this)||this;/**
  7748. * only document has defaultView, points to canvas,
  7749. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView
  7750. */_this.defaultView=null;/**
  7751. * the root element of document, eg. <html>
  7752. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement
  7753. */_this.documentElement=void 0;/**
  7754. * document.timeline in WAAPI
  7755. */_this.timeline=void 0;_this.ownerDocument=null;_this.nodeName='document';// create timeline
  7756. try{_this.timeline=new runtime.AnimationTimeline(_assertThisInitialized(_this));}catch(e){}/**
  7757. * for inherited properties, the initial value is used on the root element only,
  7758. * as long as no specified value is supplied.
  7759. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/initial_value
  7760. */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
  7761. _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;/**
  7762. * @example const circle = document.createElement('circle', { style: { r: 10 } });
  7763. */_proto.createElement=function createElement(tagName,options){// @observablehq/plot will create <svg>
  7764. if(tagName==='svg'){return this.documentElement;}// d3 will use <tspan>
  7765. 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){}}/**
  7766. * Picking 2D graphics with RBush based on BBox, fast but inaccurate.
  7767. */;_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`
  7768. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
  7769. 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
  7770. 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
  7771. 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;}/**
  7772. * Do picking with API instead of triggering interactive events.
  7773. *
  7774. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementFromPoint
  7775. */;_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
  7776. 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
  7777. 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;}/**
  7778. * Do picking with API instead of triggering interactive events.
  7779. *
  7780. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Document/elementsFromPoint
  7781. */;_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
  7782. 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;}()/**
  7783. * eg. Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.
  7784. */;_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);}/**
  7785. * Execute query on documentElement.
  7786. */;_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);/**
  7787. * built-in events for element
  7788. * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationEvent
  7789. *
  7790. * TODO: use MutationObserver instead
  7791. * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
  7792. */(function(ElementEvent){ElementEvent["REPARENT"]="reparent";ElementEvent["DESTROY"]="destroy";/**
  7793. * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMAttrModified
  7794. */ElementEvent["ATTR_MODIFIED"]="DOMAttrModified";/**
  7795. * it has been inserted
  7796. * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted
  7797. */ElementEvent["INSERTED"]="DOMNodeInserted";/**
  7798. * it is being removed
  7799. * @see https://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeRemoved
  7800. */ElementEvent["REMOVED"]="removed";/**
  7801. * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnodeinsertedintodocument
  7802. */ElementEvent["MOUNTED"]="DOMNodeInsertedIntoDocument";/**
  7803. * @see https://www.w3.org/TR/DOM-Level-3-Events/#domnoderemovedfromdocument
  7804. */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);/**
  7805. * Has following capabilities:
  7806. * * Node insert/remove, eg. appendChild, removeChild, remove...
  7807. * * Query eg. querySelector getElementById...
  7808. * * Animation
  7809. */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;/**
  7810. * Unique id.
  7811. */_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};/**
  7812. * used with `getElementById()`
  7813. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/id
  7814. */_this.id=void 0;/**
  7815. * used in `getElementsByName`
  7816. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
  7817. */_this.name=void 0;/**
  7818. * https://developer.mozilla.org/zh-CN/docs/Web/API/Element/namespaceURI
  7819. */_this.namespaceURI='g';_this.scrollLeft=0;_this.scrollTop=0;/**
  7820. * We don't support border now
  7821. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop
  7822. */_this.clientTop=0;_this.clientLeft=0;/**
  7823. * is destroyed or not
  7824. */_this.destroyed=false;/**
  7825. * compatible with `style`
  7826. * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
  7827. */_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;/**
  7828. * Renderers will use these used values.
  7829. */_this.parsedStyle={// opacity: '',
  7830. // fillOpacity: '',
  7831. // strokeOpacity: '',
  7832. // transformOrigin: '',
  7833. // visibility: '',
  7834. // pointerEvents: '',
  7835. // lineWidth: '',
  7836. // lineCap: '',
  7837. // lineJoin: '',
  7838. // increasedLineWidthForHitTesting: '',
  7839. // fontSize: '',
  7840. // fontFamily: '',
  7841. // fontStyle: '',
  7842. // fontWeight: '',
  7843. // fontVariant: '',
  7844. // textAlign: '',
  7845. // textBaseline: '',
  7846. // textTransform: '',
  7847. };/**
  7848. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes
  7849. */_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
  7850. 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
  7851. runtime.sceneGraphService.detach(child);return child;}/**
  7852. * Remove all children which can be appended to its original parent later again.
  7853. */;_proto.removeChildren=function removeChildren(){for(var i=this.childNodes.length-1;i>=0;i--){var child=this.childNodes[i];this.removeChild(child);}}/**
  7854. * Recursively destroy all children which can not be appended to its original parent later again.
  7855. */;_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();}}/**
  7856. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
  7857. */;_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);}/**
  7858. * should traverses the element and its parents (heading toward the document root)
  7859. * until it finds a node that matches the specified CSS selector.
  7860. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/closest
  7861. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#polyfill
  7862. */;_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;}/**
  7863. * search in scene group, but should not include itself
  7864. */;_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;}/**
  7865. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/after
  7866. */;_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);});}}/**
  7867. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/before
  7868. */;_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);}}/**
  7869. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceWith
  7870. */;_proto.replaceWith=function replaceWith(){this.after.apply(this,arguments);this.remove();}/**
  7871. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/append
  7872. */;_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);});}/**
  7873. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/prepend
  7874. */;_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);});}/**
  7875. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/replaceChildren
  7876. */;_proto.replaceChildren=function replaceChildren(){while(this.childNodes.length&&this.firstChild){this.removeChild(this.firstChild);}this.append.apply(this,arguments);}/**
  7877. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/remove
  7878. */;_proto.remove=function remove(){if(this.parentNode){return this.parentNode.removeChild(this);}return this;};_proto.destroy=function destroy(){// destroy itself before remove
  7879. this.dispatchEvent(destroyEvent);// remove from scenegraph first
  7880. this.remove();// remove event listeners
  7881. 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);}/**
  7882. * get bounds in world space, account for children
  7883. */;_proto.getBounds=function getBounds(){return runtime.sceneGraphService.getBounds(this);}/**
  7884. * get bounds in local space, account for children
  7885. */;_proto.getLocalBounds=function getLocalBounds(){return runtime.sceneGraphService.getLocalBounds(this);}/**
  7886. * account for context's bounds in client space,
  7887. * but not accounting for children
  7888. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
  7889. */;_proto.getBoundingClientRect=function getBoundingClientRect(){return runtime.sceneGraphService.getBoundingClientRect(this);}/**
  7890. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getClientRects
  7891. */;_proto.getClientRects=function getClientRects(){return [this.getBoundingClientRect()];};/**
  7892. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/computedStyleMap
  7893. * eg. circle.computedStyleMap().get('fill');
  7894. */_proto.computedStyleMap=function computedStyleMap(){return new Map(Object.entries(this.computedStyle));};/**
  7895. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNames
  7896. */_proto.getAttributeNames=function getAttributeNames(){return Object.keys(this.attributes);}/**
  7897. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
  7898. */;_proto.getAttribute=function getAttribute(name){// @see https://github.com/antvis/G/issues/1267
  7899. 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 ""
  7900. return runtime.enableCSSParsing?isNil(value)?null:value:value;}else {return value;}}/**
  7901. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttribute
  7902. */;_proto.hasAttribute=function hasAttribute(qualifiedName){return this.getAttributeNames().includes(qualifiedName);}/**
  7903. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/hasAttributes
  7904. */;_proto.hasAttributes=function hasAttributes(){return !!this.getAttributeNames().length;}/**
  7905. * 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.
  7906. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute
  7907. */;_proto.removeAttribute=function removeAttribute(attributeName){this.setAttribute(attributeName,null);delete this.attributes[attributeName];}/**
  7908. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute
  7909. */;_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:/**
  7910. * used in `getElementsByClassName`
  7911. * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
  7912. */function get(){// @ts-ignore
  7913. return this.getAttribute('class')||'';},set:function set(className){this.setAttribute('class',className);}},{key:"classList",get:/**
  7914. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
  7915. */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;/**
  7916. * The coordinates of the mouse event relative to the canvas.
  7917. */_this.client=new Point();/**
  7918. * The movement in this pointer relative to the last `mousemove` event.
  7919. */_this.movement=new Point();/**
  7920. * The offset of the pointer coordinates w.r.t. target DisplayObject in world space. This is
  7921. * not supported at the moment.
  7922. */_this.offset=new Point();/**
  7923. * The pointer coordinates in world space.
  7924. */_this.global=new Point();/**
  7925. * The pointer coordinates in sceen space.
  7926. */_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;/**
  7927. * The unique identifier of the pointer.
  7928. *
  7929. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
  7930. */_this.pointerId=void 0;/**
  7931. * The width of the pointer's contact along the x-axis, measured in CSS pixels.
  7932. * radiusX of TouchEvents will be represented by this value.
  7933. *
  7934. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width
  7935. */_this.width=0;/**
  7936. * The height of the pointer's contact along the y-axis, measured in CSS pixels.
  7937. * radiusY of TouchEvents will be represented by this value.
  7938. *
  7939. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height
  7940. */_this.height=0;/**
  7941. * Indicates whether or not the pointer device that created the event is the primary pointer.
  7942. *
  7943. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary
  7944. */_this.isPrimary=false;/**
  7945. * The type of pointer that triggered the event.
  7946. *
  7947. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType
  7948. */_this.pointerType=void 0;/**
  7949. * Pressure applied by the pointing device during the event.
  7950. *s
  7951. * A Touch's force property will be represented by this value.
  7952. *
  7953. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
  7954. */_this.pressure=void 0;/**
  7955. * Barrel pressure on a stylus pointer.
  7956. *
  7957. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  7958. */_this.tangentialPressure=void 0;/**
  7959. * The angle, in degrees, between the pointer device and the screen.
  7960. *
  7961. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX
  7962. */_this.tiltX=void 0;/**
  7963. * The angle, in degrees, between the pointer device and the screen.
  7964. *
  7965. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY
  7966. */_this.tiltY=void 0;/**
  7967. * Twist of a stylus pointer.
  7968. *
  7969. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  7970. */_this.twist=void 0;return _this;}var _proto=FederatedPointerEvent.prototype;/**
  7971. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/getCoalescedEvents
  7972. */_proto.getCoalescedEvents=function getCoalescedEvents(){if(this.type==='pointermove'||this.type==='mousemove'||this.type==='touchmove'){return [this];}return [];}/**
  7973. * @see https://chromestatus.com/feature/5765569655603200
  7974. */;_proto.getPredictedEvents=function getPredictedEvents(){throw new Error('getPredictedEvents is not supported!');}/**
  7975. * @see https://github.com/antvis/G/issues/1115
  7976. * We currently reuses event objects in the event system,
  7977. * avoiding the creation of a large number of event objects.
  7978. * Reused objects are only used to carry different data,
  7979. * such as coordinate information, native event objects,
  7980. * and therefore the lifecycle is limited to the event handler,
  7981. * which can lead to unintended consequences if an attempt is made to cache the entire event object.
  7982. *
  7983. * 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.
  7984. */;_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;/**
  7985. * The units of `deltaX`, `deltaY`, and `deltaZ`. This is one of `DOM_DELTA_LINE`,
  7986. * `DOM_DELTA_PAGE`, `DOM_DELTA_PIXEL`.
  7987. */_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
  7988. });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-';/**
  7989. * prototype chains: DisplayObject -> Element -> Node -> EventTarget
  7990. *
  7991. * mixins: Animatable, Transformable, Visible
  7992. * @see https://github.com/tannerntannern/ts-mixer/blob/master/README.md#mixing-generic-classes
  7993. *
  7994. * Provide abilities in scene graph, such as:
  7995. * * transform `translate/rotate/scale`
  7996. * * add/remove child
  7997. * * visibility and z-index
  7998. *
  7999. * Those abilities are implemented with those components: `Transform/Sortable/Visible`.
  8000. *
  8001. * Emit following events:
  8002. * * init
  8003. * * destroy
  8004. * * attributeChanged
  8005. */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
  8006. // eg. group.get('name')
  8007. /**
  8008. * contains style props in constructor's params, eg. fill, stroke...
  8009. */_this.config=void 0;_this.isCustomElement=false;_this.isMutationObserved=false;/**
  8010. * push to active animations after calling `animate()`
  8011. */_this.activeAnimations=[];/**
  8012. * Use data-* attribute.
  8013. * @see https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
  8014. * @example
  8015. * group.dataset.prop1 = 1;
  8016. * group.getAttribute('data-prop1'); // 1
  8017. */_this.dataset=void 0;/**
  8018. * Use `this.style.clipPath` instead.
  8019. * @deprecated
  8020. */_this.getClip=function(){return this.style.clipPath||null;};_this.config=config;// compatible with G 3.0
  8021. _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
  8022. _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
  8023. _this.config.style=_this.config.style||_this.config.attrs||{};Object.assign(_this.config.style,_this.config.attrs);// this.config.style = {
  8024. // // ...DEFAULT_STYLE_PROPS,
  8025. // ...this.config.style,
  8026. // ...this.config.attrs,
  8027. // };
  8028. 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
  8029. 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
  8030. _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
  8031. {// ...this.attributes,
  8032. 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) {
  8033. 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
  8034. this.getAnimations().forEach(function(animation){animation.cancel();});// FIXME
  8035. // this.renderable = null;
  8036. // this.cullable = null;
  8037. // this.transformable = null;
  8038. // this.rBushNode = null;
  8039. // this.geometry = null;
  8040. // this.sortable = null;
  8041. };_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
  8042. if(isDisplayObject(attribute)&&// share the same clipPath if possible
  8043. attributeName!=='clipPath'&&attributeName!=='offsetPath'&&attributeName!=='textPath'){clonedStyle[attributeName]=attribute.cloneNode(deep);}// TODO: clone other type
  8044. if(customCloneFunc){clonedStyle[attributeName]=customCloneFunc(attributeName,attribute);}}var cloned=new this.constructor({// copy id & name
  8045. // @see https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode#notes
  8046. id:this.id,name:this.name,className:this.name,interactive:this.interactive,style:clonedStyle});// apply transform
  8047. cloned.setLocalTransform(this.getLocalTransform());if(deep){this.children.forEach(function(child){// skip marker
  8048. 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:
  8049. // // only Group / Text should account for text relative props
  8050. // this.tagName === Shape.GROUP || this.tagName === Shape.TEXT
  8051. // ? INHERITABLE_STYLE_PROPS
  8052. // : INHERITABLE_BASE_STYLE_PROPS,
  8053. };if(runtime.enableCSSParsing){// @ts-ignore
  8054. options.usedAttributes=INHERITABLE_STYLE_PROPS;}// account for FCP, process properties as less as possible
  8055. 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
  8056. renderable.dirty=true;};_proto.setAttribute=function setAttribute(name,value,force){if(force===void 0){force=false;}var attributeName=formatAttributeName(name);// ignore undefined value
  8057. if(isUndefined(value)){return;}if(force||value!==this.attributes[attributeName]){this.internalSetAttribute(attributeName,value);_Element.prototype.setAttribute.call(this,attributeName,value);}}/**
  8058. * called when attributes get changed or initialized
  8059. */;_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
  8060. 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
  8061. /**
  8062. * returns different values than getBoundingClientRect(), as the latter returns value relative to the viewport
  8063. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGraphicsElement/getBBox
  8064. *
  8065. * FIXME: It is worth noting that getBBox responds to original untransformed values of a drawn object.
  8066. * @see https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#getBBox
  8067. */;_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);}/**
  8068. * set position in world space
  8069. */;_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;}/**
  8070. * set position in local space
  8071. */;_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;}/**
  8072. * translate in world space
  8073. */;_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;}/**
  8074. * translate in local space
  8075. */;_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);}/**
  8076. * compatible with G 3.0
  8077. *
  8078. * scaling in local space
  8079. * scale(10) = scale(10, 10, 10)
  8080. *
  8081. * we can't set scale in world space
  8082. */;_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;}/**
  8083. * set scaling in local space
  8084. */;_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;}/**
  8085. * get scaling in local space
  8086. */;_proto.getLocalScale=function getLocalScale(){return runtime.sceneGraphService.getLocalScale(this);}/**
  8087. * get scaling in world space
  8088. */;_proto.getScale=function getScale(){return runtime.sceneGraphService.getScale(this);}/**
  8089. * only return degrees of Z axis in world space
  8090. */;_proto.getEulerAngles=function getEulerAngles(){var _getEuler=getEuler(create$2(),runtime.sceneGraphService.getWorldTransform(this)),ez=_getEuler[2];return rad2deg(ez);}/**
  8091. * only return degrees of Z axis in local space
  8092. */;_proto.getLocalEulerAngles=function getLocalEulerAngles(){var _getEuler2=getEuler(create$2(),runtime.sceneGraphService.getLocalRotation(this)),ez=_getEuler2[2];return rad2deg(ez);}/**
  8093. * set euler angles(degrees) in world space
  8094. */;_proto.setEulerAngles=function setEulerAngles(z){runtime.sceneGraphService.setEulerAngles(this,0,0,z);return this;}/**
  8095. * set euler angles(degrees) in local space
  8096. */;_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
  8097. // #region animatable
  8098. /**
  8099. * returns an array of all Animation objects affecting this element
  8100. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getAnimations
  8101. */;_proto.getAnimations=function getAnimations(){return this.activeAnimations;}/**
  8102. * create an animation with WAAPI
  8103. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/animate
  8104. */;_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
  8105. // #region visible
  8106. /**
  8107. * shortcut for Used value of `visibility`
  8108. */;_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);}/**
  8109. * bring to front in current group
  8110. */;_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;}/**
  8111. * send to back in current group
  8112. */;_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
  8113. // #region deprecated
  8114. /**
  8115. * compatible with G 3.0
  8116. * @alias object.config
  8117. * @deprecated
  8118. */;_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];}/**
  8119. * return 3x3 matrix in world space
  8120. * @deprecated
  8121. */;_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
  8122. return fromRotationTranslationScale$1(eux||euz,tx,ty,sx,sy);}/**
  8123. * return 3x3 matrix in local space
  8124. * @deprecated
  8125. */;_proto.getLocalMatrix=function getLocalMatrix(){return this.getMatrix(this.getLocalTransform());}/**
  8126. * set 3x3 matrix in world space
  8127. * @deprecated
  8128. */;_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);}/**
  8129. * set 3x3 matrix in local space
  8130. * @deprecated
  8131. */;_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);}/**
  8132. * Use `visibility: visible` instead.
  8133. * @deprecated
  8134. */;_proto.show=function show(){if(runtime.enableCSSParsing){this.style.visibility='visible';}else {this.forEach(function(object){object.style.visibility='visible';});}}/**
  8135. * Use `visibility: hidden` instead.
  8136. * @deprecated
  8137. */;_proto.hide=function hide(){if(runtime.enableCSSParsing){this.style.visibility='hidden';}else {this.forEach(function(object){object.style.visibility='hidden';});}}/**
  8138. * Use `childElementCount` instead.
  8139. * @deprecated
  8140. */;_proto.getCount=function getCount(){return this.childElementCount;}/**
  8141. * Use `parentElement` instead.
  8142. * @deprecated
  8143. */;_proto.getParent=function getParent(){return this.parentElement;}/**
  8144. * Use `children` instead.
  8145. * @deprecated
  8146. */;_proto.getChildren=function getChildren(){return this.children;}/**
  8147. * Use `firstElementChild` instead.
  8148. * @deprecated
  8149. */;_proto.getFirst=function getFirst(){return this.firstElementChild;}/**
  8150. * Use `lastElementChild` instead.
  8151. * @deprecated
  8152. */;_proto.getLast=function getLast(){return this.lastElementChild;}/**
  8153. * Use `this.children[index]` instead.
  8154. * @deprecated
  8155. */;_proto.getChildByIndex=function getChildByIndex(index){return this.children[index]||null;}/**
  8156. * Use `appendChild` instead.
  8157. * @deprecated
  8158. */;_proto.add=function add(child,index){return this.appendChild(child,index);}/**
  8159. * Use `this.style.clipPath` instead.
  8160. * @deprecated
  8161. */;_proto.setClip=function setClip(clipPath){this.style.clipPath=clipPath;};/**
  8162. * @deprecated
  8163. */_proto.set=function set(name,value){// @ts-ignore
  8164. this.config[name]=value;}/**
  8165. * @deprecated
  8166. */;_proto.get=function get(name){return this.config[name];}/**
  8167. * Use `setPosition` instead.
  8168. * @deprecated
  8169. */;_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;}/**
  8170. * Use `setPosition` instead.
  8171. * @deprecated
  8172. */;_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;}/**
  8173. * Use `this.style.zIndex` instead.
  8174. * @deprecated
  8175. */;_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"];/**
  8176. * shadow root
  8177. * @see https://yuque.antfin-inc.com/antv/czqvg5/pgqipg
  8178. */var CustomElement=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(CustomElement,_DisplayObject);// private shadowNodes: DisplayObject[] = [];
  8179. 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[] {
  8180. // return [];
  8181. // }
  8182. _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"];/**
  8183. * its attributes are inherited by its children.
  8184. * @see https://developer.mozilla.org/zh-CN/docs/Web/SVG/Element/g
  8185. *
  8186. * @example
  8187. * <g fill="white" stroke="green" stroke-width="5">
  8188. <circle cx="40" cy="40" r="25" />
  8189. <circle cx="60" cy="60" r="25" />
  8190. </g>
  8191. */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"];/**
  8192. * HTML container
  8193. * @see https://github.com/pmndrs/drei#html
  8194. */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;}/**
  8195. * return wrapper HTMLElement
  8196. * * <div> in g-webgl/canvas
  8197. * * <foreignObject> in g-svg
  8198. */var _proto=HTML.prototype;_proto.getDomElement=function getDomElement(){return this.parsedStyle.$el;}/**
  8199. * override with $el.getBoundingClientRect
  8200. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
  8201. */;_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
  8202. // @ts-ignore
  8203. 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(
  8204. // vec3.fromValues(minX, minY, 0),
  8205. // vec3.fromValues(minX + clientRect.width, minY + clientRect.height, 0),
  8206. // );
  8207. 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"];/**
  8208. * Create a line connecting two points.
  8209. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/line
  8210. *
  8211. * Also support for using marker.
  8212. */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'
  8213. 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
  8214. 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
  8215. 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
  8216. 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
  8217. 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;/**
  8218. * markers placed at the mid
  8219. */_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
  8220. 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'
  8221. 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
  8222. 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
  8223. 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
  8224. }}}/**
  8225. * Returns the total length of the path.
  8226. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getTotalLength
  8227. */;_proto.getTotalLength=function getTotalLength(){return getOrCalculatePathTotalLength(this);}/**
  8228. * Returns the point at a given distance along the path.
  8229. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGGeometryElement/getPointAtLength
  8230. */;_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
  8231. return new Point(transformed[0],transformed[1]);}/**
  8232. * Returns the point at a given ratio of the total length in path.
  8233. */;_proto.getPoint=function getPoint(ratio,inWorldSpace){if(inWorldSpace===void 0){inWorldSpace=false;}return this.getPointAtLength(ratio*getOrCalculatePathTotalLength(this),inWorldSpace);}/**
  8234. * Get start tangent vector
  8235. */;_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;}/**
  8236. * Get end tangent vector
  8237. */;_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;/**
  8238. * markers placed at the mid
  8239. */_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
  8240. 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'
  8241. 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
  8242. 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
  8243. 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
  8244. }}};return Polygon;}(DisplayObject);var _excluded$9=["style"];/**
  8245. * Polyline inherits the marker-related capabilities of Polygon.
  8246. */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
  8247. 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"];/**
  8248. * <text> @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextElement
  8249. */var Text=/*#__PURE__*/function(_DisplayObject){_inheritsLoose(Text,_DisplayObject);/**
  8250. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement#constants
  8251. */ // LENGTHADJUST_SPACING: number = 1;
  8252. // LENGTHADJUST_SPACINGANDGLYPHS: number = 2;
  8253. // LENGTHADJUST_UNKNOWN: number = 0;
  8254. 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',
  8255. 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;
  8256. // textLength: SVGAnimatedLength;
  8257. // getCharNumAtPosition(point?: DOMPointInit): number {
  8258. // throw new Error('Method not implemented.');
  8259. // }
  8260. /**
  8261. * @see https://developer.mozilla.org/en-US/docs/Web/API/SVGTextContentElement
  8262. */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 {
  8263. // throw new Error('Method not implemented.');
  8264. // }
  8265. // getExtentOfChar(charnum: number): DOMRect {
  8266. // throw new Error('Method not implemented.');
  8267. // }
  8268. // getNumberOfChars(): number {
  8269. // throw new Error('Method not implemented.');
  8270. // }
  8271. // getRotationOfChar(charnum: number): number {
  8272. // throw new Error('Method not implemented.');
  8273. // }
  8274. // getStartPositionOfChar(charnum: number): DOMPoint {
  8275. // throw new Error('Method not implemented.');
  8276. // }
  8277. // getSubStringLength(charnum: number, nchars: number): number {
  8278. // throw new Error('Method not implemented.');
  8279. // }
  8280. // selectSubString(charnum: number, nchars: number): void {
  8281. // throw new Error('Method not implemented.');
  8282. // }
  8283. ;_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);/**
  8284. * Blink used them in code generation(css_properties.json5)
  8285. */var BUILT_IN_PROPERTIES=[{/**
  8286. * used in CSS Layout API
  8287. * eg. `display: 'flex'`
  8288. */n:'display',k:['none']},{/**
  8289. * range [0.0, 1.0]
  8290. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/opacity
  8291. */n:'opacity',int:true,inh:true,d:'1',syntax:exports.PropertySyntax.OPACITY_VALUE},{/**
  8292. * inheritable, range [0.0, 1.0]
  8293. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-opacity
  8294. * @see https://svgwg.org/svg2-draft/painting.html#FillOpacity
  8295. */n:'fillOpacity',int:true,inh:true,d:'1',syntax:exports.PropertySyntax.OPACITY_VALUE},{/**
  8296. * inheritable, range [0.0, 1.0]
  8297. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-opacity
  8298. * @see https://svgwg.org/svg2-draft/painting.html#StrokeOpacity
  8299. */n:'strokeOpacity',int:true,inh:true,d:'1',syntax:exports.PropertySyntax.OPACITY_VALUE},{/**
  8300. * background-color is not inheritable
  8301. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Fills_and_Strokes
  8302. */n:'fill',int:true,k:['none'],d:'none',syntax:exports.PropertySyntax.PAINT},{n:'fillRule',k:['nonzero','evenodd'],d:'nonzero'},/**
  8303. * default to none
  8304. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke#usage_notes
  8305. */{n:'stroke',int:true,k:['none'],d:'none',syntax:exports.PropertySyntax.PAINT,/**
  8306. * Stroke 'none' won't affect geometry but others will.
  8307. */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},{/**
  8308. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-width
  8309. */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,/**
  8310. * support interpolation
  8311. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#interpolation
  8312. */int:true,d:'visible'},{n:'pointerEvents',inh:true,k:['none','auto','stroke','fill','painted','visible','visiblestroke','visiblefill','visiblepainted',// 'bounding-box',
  8313. '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,
  8314. 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>
  8315. {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
  8316. {// x in local space
  8317. n:'x',int:true,d:'0',syntax:exports.PropertySyntax.COORDINATE},{// y in local space
  8318. n:'y',int:true,d:'0',syntax:exports.PropertySyntax.COORDINATE},{// z in local space
  8319. n:'z',int:true,d:'0',syntax:exports.PropertySyntax.COORDINATE},{n:'width',int:true,l:true,/**
  8320. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/width
  8321. */k:['auto','fit-content','min-content','max-content'],d:'0',syntax:exports.PropertySyntax.LENGTH_PERCENTAGE},{n:'height',int:true,l:true,/**
  8322. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/height
  8323. */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
  8324. {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
  8325. {n:'path',int:true,l:true,d:'',a:['d'],syntax:exports.PropertySyntax.PATH,p:50},// Polyline & Polygon
  8326. {n:'points',/**
  8327. * support interpolation
  8328. */int:true,l:true,syntax:exports.PropertySyntax.LIST_OF_POINTS,p:50},// Text
  8329. {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
  8330. },{n:'font',l:true},{n:'fontSize',int:true,inh:true,/**
  8331. * @see https://www.w3schools.com/css/css_font_size.asp
  8332. */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'},// {
  8333. // n: 'whiteSpace',
  8334. // l: true,
  8335. // },
  8336. {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>();
  8337. // const tmpVec3a = vec3.create();
  8338. // const tmpVec3b = vec3.create();
  8339. // const tmpVec3c = vec3.create();
  8340. 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(){/**
  8341. * need recalc later
  8342. */ // dirty = false;
  8343. 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];}/**
  8344. * * parse value, eg.
  8345. * fill: 'red' => CSSRGB
  8346. * translateX: '10px' => CSSUnitValue { unit: 'px', value: 10 }
  8347. * fontSize: '2em' => { unit: 'px', value: 32 }
  8348. *
  8349. * * calculate used value
  8350. * * post process
  8351. */;_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
  8352. 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
  8353. // @ts-ignore
  8354. if(!isNil(attributes.radius)){// @ts-ignore
  8355. object.parsedStyle.radius=parseDimensionArrayFormat(// @ts-ignore
  8356. attributes.radius,4);}// Polyline
  8357. if(!isNil(attributes.lineDash)){object.parsedStyle.lineDash=parseDimensionArrayFormat(attributes.lineDash,2);}// @ts-ignore
  8358. if(attributes.points){// @ts-ignore
  8359. object.parsedStyle.points=parsePoints(attributes.points,object);}// Path
  8360. // @ts-ignore
  8361. if(attributes.path===''){object.parsedStyle.path=_extends({},EMPTY_PARSED_PATH);}// @ts-ignore
  8362. if(attributes.path){object.parsedStyle.path=parsePath(// @ts-ignore
  8363. attributes.path,object);}// Text
  8364. 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
  8365. attributes.anchor,2);}if(attributes.transform){object.parsedStyle.transform=parseTransform(attributes.transform);}if(attributes.transformOrigin){object.parsedStyle.transformOrigin=parseTransformOrigin(attributes.transformOrigin);}// Marker
  8366. // @ts-ignore
  8367. if(attributes.markerStart){// @ts-ignore
  8368. object.parsedStyle.markerStart=runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,// @ts-ignore
  8369. attributes.markerStart,// @ts-ignore
  8370. attributes.markerStart,null,null);}// @ts-ignore
  8371. if(attributes.markerEnd){// @ts-ignore
  8372. object.parsedStyle.markerEnd=runtime.CSSPropertySyntaxFactory['<marker>'].calculator(null,// @ts-ignore
  8373. attributes.markerEnd,// @ts-ignore
  8374. attributes.markerEnd,null,null);}// @ts-ignore
  8375. if(attributes.markerMid){// @ts-ignore
  8376. object.parsedStyle.markerMid=runtime.CSSPropertySyntaxFactory['<marker>'].calculator('',// @ts-ignore
  8377. attributes.markerMid,// @ts-ignore
  8378. attributes.markerMid,null,null);}if(// Circle & Ellipse
  8379. (object.nodeName===exports.Shape.CIRCLE||object.nodeName===exports.Shape.ELLIPSE)&&(// @ts-ignore
  8380. !isNil(attributes.cx)||// @ts-ignore
  8381. !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
  8382. !isNil(attributes.x)||// @ts-ignore
  8383. !isNil(attributes.y)||// @ts-ignore
  8384. !isNil(attributes.z))||// Line
  8385. object.nodeName===exports.Shape.LINE&&(// @ts-ignore
  8386. !isNil(attributes.x1)||// @ts-ignore
  8387. !isNil(attributes.y1)||// @ts-ignore
  8388. !isNil(attributes.z1)||// @ts-ignore
  8389. !isNil(attributes.x2)||// @ts-ignore
  8390. !isNil(attributes.y2)||// @ts-ignore
  8391. !isNil(attributes.z2))){runtime.CSSPropertySyntaxFactory['<coordinate>'].postProcessor(object,_attributeNames);}if(!isNil(attributes.zIndex)){runtime.CSSPropertySyntaxFactory['<z-index>'].postProcessor(object,_attributeNames);}// @ts-ignore
  8392. if(attributes.path){runtime.CSSPropertySyntaxFactory['<path>'].postProcessor(object,_attributeNames);}// @ts-ignore
  8393. 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;
  8394. // parse according to priority
  8395. // path 50
  8396. // points 50
  8397. // text 50
  8398. // textTransform 51
  8399. // anchor 99
  8400. // transform 100
  8401. // transformOrigin 100
  8402. if(usedAttributes===null||usedAttributes===void 0?void 0:usedAttributes.length){// uniqueAttributeSet.clear();
  8403. attributeNames=Array.from(new Set(attributeNames.concat(usedAttributes)));}// [
  8404. // 'path',
  8405. // 'points',
  8406. // 'text',
  8407. // 'textTransform',
  8408. // 'anchor',
  8409. // 'transform',
  8410. // 'transformOrigin',
  8411. // ].forEach((name) => {
  8412. // const index = attributeNames.indexOf(name);
  8413. // if (index > -1) {
  8414. // attributeNames.splice(index, 1);
  8415. // attributeNames.push(name);
  8416. // }
  8417. // });
  8418. attributeNames.forEach(function(name){// some style props maybe deleted after parsing such as `anchor` in Text
  8419. if(name in object.computedStyle){object.parsedStyle[name]=_this2.computeProperty(name,object.computedStyle[name],object);}});// if (hasUnresolvedProperties) {
  8420. // this.dirty = true;
  8421. // return;
  8422. // }
  8423. // update geometry
  8424. if(needUpdateGeometry){// object.geometry.dirty = true;
  8425. // runtime.sceneGraphService.dirtifyToRoot(object);
  8426. 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
  8427. object.children.forEach(function(child){child.internalSetAttribute(name,null,{skipUpdateAttribute:true,skipParse:true});});}});}}/**
  8428. * string -> parsed value
  8429. */;_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);
  8430. computed=getOrCreateKeyword(value);}else {if(metadata){var keywords=metadata.k,syntax=metadata.syntax;var handler=syntax&&this.getPropertySyntax(syntax);// use keywords
  8431. if(keywords&&keywords.indexOf(value)>-1){// computed = new CSSKeywordValue(value);
  8432. computed=getOrCreateKeyword(value);}else if(handler&&handler.parser){// try to parse it to CSSStyleValue, eg. '10px' -> CSS.px(10)
  8433. computed=handler.parser(value,object);}}}return computed;}/**
  8434. * computed value -> used value
  8435. */;_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;
  8436. var used=computed;if(metadata){var syntax=metadata.syntax,inherited=metadata.inh,defaultValue=metadata.d;if(computed instanceof CSSKeywordValue){var value=computed.value;/**
  8437. * @see https://developer.mozilla.org/zh-CN/docs/Web/CSS/unset
  8438. */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
  8439. 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
  8440. // behave like `inherit`
  8441. var resolved=this.tryToResolveProperty(object,name,{inherited:true});if(!isNil(resolved)){// object.parsedStyle[name] = resolved;
  8442. // return false;
  8443. return resolved;}else {this.addUnresolveProperty(object,name);return;}}}var handler=syntax&&this.getPropertySyntax(syntax);if(handler&&handler.calculator){// convert computed value to used value
  8444. 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;
  8445. // return false;
  8446. 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);}}}/**
  8447. * resolve later
  8448. */;_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];
  8449. var usedValue=object.parentElement.parsedStyle[name];if(// usedValue instanceof CSSKeywordValue &&
  8450. usedValue==='unset'||usedValue==='initial'||usedValue==='inherit'){return;}// else if (
  8451. // usedValue instanceof CSSUnitValue &&
  8452. // CSSUnitValue.isRelativeUnit(usedValue.unit)
  8453. // ) {
  8454. // return false;
  8455. // }
  8456. 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);}}/**
  8457. * update geometry when relative props changed,
  8458. * eg. r of Circle, width/height of Rect
  8459. */;_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
  8460. var halfExtents=[Math.abs(width)/2,Math.abs(height)/2,depth/2];// const halfExtents = vec3.set(
  8461. // tmpVec3a,
  8462. // Math.abs(width) / 2,
  8463. // Math.abs(height) / 2,
  8464. // depth / 2,
  8465. // );
  8466. // anchor is center by default, don't account for lineWidth here
  8467. 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
  8468. 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(
  8469. // tmpVec3b,
  8470. // ((1 - ((anchor && anchor[0]) || 0) * 2) * width) / 2 + offsetX,
  8471. // ((1 - ((anchor && anchor[1]) || 0) * 2) * height) / 2 + offsetY,
  8472. // (1 - ((anchor && anchor[2]) || 0) * 2) * halfExtents[2] + offsetZ,
  8473. // );
  8474. // update geometry's AABB
  8475. geometry.contentBounds.update(center,halfExtents);// @see https://github.molgen.mpg.de/git-mirror/cairo/blob/master/src/cairo-stroke-style.c#L97..L128
  8476. var expansion=nodeName===exports.Shape.POLYLINE||nodeName===exports.Shape.POLYGON||nodeName===exports.Shape.PATH?Math.SQRT2:0.5;// if (lineCap?.value === 'square') {
  8477. // expansion = Math.SQRT1_2;
  8478. // }
  8479. // if (lineJoin?.value === 'miter' && expansion < Math.SQRT2 * miterLimit) {
  8480. // expansion = Math.SQRT1_2 * miterLimit;
  8481. // }
  8482. // append border only if stroke existed
  8483. var hasStroke=stroke&&!stroke.isNone;if(hasStroke){var halfLineWidth=((lineWidth||0)+(increasedLineWidthForHitTesting||0))*expansion;// halfExtents[0] += halfLineWidth[0];
  8484. // halfExtents[1] += halfLineWidth[1];
  8485. halfExtents[0]+=halfLineWidth;halfExtents[1]+=halfLineWidth;// vec3.add(
  8486. // halfExtents,
  8487. // halfExtents,
  8488. // vec3.set(tmpVec3c, halfLineWidth, halfLineWidth, 0),
  8489. // );
  8490. }geometry.renderBounds.update(center,halfExtents);// account for shadow, only support constant value now
  8491. 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()
  8492. 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) {
  8493. // account for negative width / height of Rect
  8494. // @see https://github.com/antvis/g/issues/957
  8495. var flipY=width<0;var flipX=height<0;// } else {
  8496. // }
  8497. // set transform origin
  8498. 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.
  8499. runtime.sceneGraphService.dirtifyToRoot(object);}};_proto.isPropertyInheritable=function isPropertyInheritable(name){var metadata=propertyMetadataCache[name];if(!metadata){return false;}return metadata.inh;};return DefaultStyleValueRegistry;}();/**
  8500. * Different type of cameras, eg. simple camera used in 2D scene or
  8501. * advanced camera which can do actions & switch between landmarks.
  8502. */(function(CameraType){/**
  8503. * Performs all the rotational operations with the focal point instead of the camera position.
  8504. * This type of camera is useful in applications(like CAD) where 3D objects are being designed or explored.
  8505. * Camera cannot orbits over the north & south poles.
  8506. * @see http://voxelent.com/tutorial-cameras/
  8507. *
  8508. * In Three.js it's used in OrbitControls.
  8509. * @see https://threejs.org/docs/#examples/zh/controls/OrbitControls
  8510. */CameraType[CameraType["ORBITING"]=0]="ORBITING";/**
  8511. * It's similar to the ORBITING camera, but it allows the camera to orbit over the north or south poles.
  8512. *
  8513. * In Three.js it's used in OrbitControls.
  8514. * @see https://threejs.org/docs/#examples/en/controls/TrackballControls
  8515. */CameraType[CameraType["EXPLORING"]=1]="EXPLORING";/**
  8516. * Performs all the rotational operations with the camera position.
  8517. * It's useful in first person shooting games.
  8518. * Camera cannot orbits over the north & south poles.
  8519. *
  8520. * In Three.js it's used in FirstPersonControls.
  8521. * @see https://threejs.org/docs/#examples/en/controls/FirstPersonControls
  8522. */CameraType[CameraType["TRACKING"]=2]="TRACKING";})(exports.CameraType||(exports.CameraType={}));/**
  8523. * CameraType must be TRACKING
  8524. */(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;/**
  8525. * 参考「WebGL Insights - 23.Designing Cameras for WebGL Applications」,基于 Responsible Camera 思路设计
  8526. * @see https://github.com/d13g0/nucleo.js/blob/master/source/camera/Camera.js
  8527. *
  8528. * 保存相机参数,定义相机动作:
  8529. * 1. dolly 沿 n 轴移动
  8530. * 2. pan 沿 u v 轴移动
  8531. * 3. rotate 以方位角旋转
  8532. * 4. 移动到 Landmark,具有平滑的动画效果,其间禁止其他用户交互
  8533. */var Camera=/*#__PURE__*/function(){function Camera(){this.canvas=void 0;this.eventEmitter=new eventemitter3();/**
  8534. * 相机矩阵
  8535. */this.matrix=create$1();/**
  8536. * u 轴
  8537. * @see http://learnwebgl.brown37.net/07_cameras/camera_introduction.html#a-camera-definition
  8538. */this.right=fromValues$2(1,0,0);/**
  8539. * v 轴 +Y is down
  8540. */this.up=fromValues$2(0,1,0);/**
  8541. * n 轴 +Z is inside
  8542. */this.forward=fromValues$2(0,0,1);/**
  8543. * 相机位置
  8544. */this.position=fromValues$2(0,0,1);/**
  8545. * 视点位置
  8546. */this.focalPoint=fromValues$2(0,0,0);/**
  8547. * 视点到相机位置的向量
  8548. * focalPoint - position
  8549. */this.distanceVector=fromValues$2(0,0,-1);/**
  8550. * 相机位置到视点距离
  8551. * length(focalPoint - position)
  8552. */this.distance=1;/**
  8553. * @see https://en.wikipedia.org/wiki/Azimuth
  8554. */this.azimuth=0;this.elevation=0;this.roll=0;this.relAzimuth=0;this.relElevation=0;this.relRoll=0;/**
  8555. * 沿 n 轴移动时,保证移动速度从快到慢
  8556. */this.dollyingStep=0;this.maxDistance=Infinity;this.minDistance=-Infinity;/**
  8557. * zoom factor of the camera, default is 1
  8558. * eg. https://threejs.org/docs/#api/en/cameras/OrthographicCamera.zoom
  8559. */this.zoom=1;/**
  8560. * invert the horizontal coordinate system HCS
  8561. */this.rotateWorld=false;/**
  8562. * 投影矩阵参数
  8563. */ /**
  8564. * field of view [0-360]
  8565. * @see http://en.wikipedia.org/wiki/Angle_of_view
  8566. */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;
  8567. this.type=exports.CameraType.EXPLORING;this.trackingMode=exports.CameraTrackingMode.DEFAULT;this.projectionMode=exports.CameraProjectionMode.PERSPECTIVE;/**
  8568. * for culling use
  8569. */this.frustum=new Frustum();/**
  8570. * ortho matrix for Canvas2D & SVG
  8571. */this.orthoMatrix=create$1();}var _proto=Camera.prototype;// constructor(type = CameraType.EXPLORING, trackingMode = CameraTrackingMode.DEFAULT) {
  8572. // this.setType(type, trackingMode);
  8573. // }
  8574. _proto.isOrtho=function isOrtho(){return this.projectionMode===exports.CameraProjectionMode.ORTHOGRAPHIC;};_proto.getProjectionMode=function getProjectionMode(){return this.projectionMode;};_proto.getPerspective=function getPerspective(){// account for TAA
  8575. 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;}/**
  8576. * If flag is true, it reverses the azimuth and elevation angles.
  8577. * Subsequent calls to rotate, setAzimuth, setElevation,
  8578. * changeAzimuth or changeElevation will cause the inverted effect.
  8579. * setRoll or changeRoll is not affected by this method.
  8580. *
  8581. * This inversion is useful when one wants to simulate that the world
  8582. * is moving, instead of the camera.
  8583. *
  8584. * By default the camera angles are not reversed.
  8585. * @param {Boolean} flag the boolean flag to reverse the angles.
  8586. */;_proto.setWorldRotation=function setWorldRotation(flag){this.rotateWorld=flag;this._getAngles();return this;}/**
  8587. * 计算 MV 矩阵,为相机矩阵的逆矩阵
  8588. */;_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;}/**
  8589. * 设置相机矩阵
  8590. */;_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;}/**
  8591. * Sets an offset in a larger frustum, used in PixelPicking
  8592. */;_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;}/**
  8593. * Zoom by specified point in viewport coordinates.
  8594. */;_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
  8595. 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
  8596. 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
  8597. scale(this.projectionMatrix,this.projectionMatrix,fromValues$2(1,-1,1));invert(this.projectionMatrixInverse,this.projectionMatrix);this._getOrthoMatrix();this.triggerUpdate();return this;}/**
  8598. * Move the camera in world coordinates.
  8599. * It will keep looking at the current focal point.
  8600. *
  8601. * support scalars or vectors.
  8602. * @example
  8603. * setPosition(1, 2, 3);
  8604. * setPosition([1, 2, 3]);
  8605. */;_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;}/**
  8606. * Sets the focal point of this camera in world coordinates.
  8607. *
  8608. * support scalars or vectors.
  8609. * @example
  8610. * setFocalPoint(1, 2, 3);
  8611. * setFocalPoint([1, 2, 3]);
  8612. */;_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;}/**
  8613. * Moves the camera towards/from the focal point.
  8614. */;_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;}/**
  8615. * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
  8616. * the azimuth in degrees
  8617. */;_proto.setAzimuth=function setAzimuth(az){this.azimuth=getAngle$1(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;}/**
  8618. * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
  8619. */;_proto.setElevation=function setElevation(el){this.elevation=getAngle$1(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;}/**
  8620. * 设置相机方位角,不同相机模式下需要重新计算相机位置或者是视点位置
  8621. */;_proto.setRoll=function setRoll(angle){this.roll=getAngle$1(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;}/**
  8622. * 根据相机矩阵重新计算各种相机参数
  8623. */;_proto._update=function _update(){this._getAxes();this._getPosition();this._getDistance();this._getAngles();this._getOrthoMatrix();this.triggerUpdate();}/**
  8624. * 计算相机矩阵
  8625. */;_proto.computeMatrix=function computeMatrix(){// 使用四元数描述 3D 旋转
  8626. // @see https://xiaoiver.github.io/coding/2018/12/28/Camera-%E8%AE%BE%E8%AE%A1-%E4%B8%80.html
  8627. var rotZ=setAxisAngle(create$4(),[0,0,1],deg2rad(this.roll));identity(this.matrix);// only consider HCS for EXPLORING and ORBITING cameras
  8628. 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);}}/**
  8629. * Sets the camera position in the camera matrix
  8630. */;_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();}/**
  8631. * Recalculates axes based on the current matrix
  8632. */;_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);}/**
  8633. * Recalculates euler angles based on the current state
  8634. */;_proto._getAngles=function _getAngles(){// Recalculates angles
  8635. 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
  8636. 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));}}}/**
  8637. * 重新计算相机位置,只有 ORBITING 模式相机位置才会发生变化
  8638. */;_proto._getPosition=function _getPosition(){copy$1(this.position,createVec3(transformMat4$1(create$3(),[0,0,0,1],this.matrix)));// 相机位置变化,需要重新计算视距
  8639. this._getDistance();}/**
  8640. * 重新计算视点,只有 TRACKING 模式视点才会发生变化
  8641. */;_proto._getFocalPoint=function _getFocalPoint(){transformMat3(this.distanceVector,[0,0,-this.distance],fromMat4(create(),this.matrix));add$1(this.focalPoint,this.position,this.distanceVector);// 视点变化,需要重新计算视距
  8642. this._getDistance();}/**
  8643. * 重新计算视距
  8644. */;_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
  8645. 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
  8646. 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
  8647. 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
  8648. var halfExtents=[width/2,height/2,0];// default 'left'
  8649. 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
  8650. lineYOffset=halfExtents[1];}else if(textBaseline==='top'||textBaseline==='hanging'){lineYOffset=halfExtents[1]*2;}else if(textBaseline==='alphabetic'){// prevent calling getImageData for ascent metrics
  8651. lineYOffset=runtime.enableCSSParsing?lineHeight-fontProperties.ascent:0;}else if(textBaseline==='bottom'||textBaseline==='ideographic'){lineYOffset=0;}// TODO: ideographic & bottom
  8652. if(dx){lineXOffset+=dx;}if(dy){lineYOffset+=dy;}// update anchor
  8653. 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)) {
  8654. // return;
  8655. // }
  8656. 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)) {
  8657. // return;
  8658. // }
  8659. 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
  8660. // the pointerup location.
  8661. 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
  8662. // targets. That is - it's our click target!
  8663. 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
  8664. 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)) {
  8665. // return;
  8666. // }
  8667. 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
  8668. if(trackingData.overTargets&&outTarget!==e.target){// pointerout always occurs on the overTarget when the pointer hovers over another element.
  8669. 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
  8670. // is dispatched to all ancestors that no longer capture the pointer.
  8671. 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
  8672. if(outTarget!==e.target){// pointerover always occurs on the new overTarget
  8673. var overType=from.type==='mousemove'?'mouseover':'pointerover';var overEvent=_this.clonePointerEvent(e,overType);// clone faster
  8674. _this.dispatchEvent(overEvent,'pointerover');if(isMouse)_this.dispatchEvent(overEvent,'mouseover');// Probe whether the newly hovered Node is an ancestor of the original overTarget.
  8675. 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
  8676. // event.
  8677. 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
  8678. _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)) {
  8679. // return;
  8680. // }
  8681. 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
  8682. 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
  8683. // get an upstream pointerout event (upstream events do not know rootTarget has descendants).
  8684. 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)) {
  8685. // return;
  8686. // }
  8687. 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.
  8688. 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
  8689. // @see https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseenter_event#usage_notes
  8690. _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)) {
  8691. // return;
  8692. // }
  8693. 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)) {
  8694. // return;
  8695. // }
  8696. 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
  8697. 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
  8698. 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
  8699. 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
  8700. if(!skipPropagate){e.propagationStopped=false;e.propagationImmediatelyStopped=false;this.propagate(e,type);}else {// target phase
  8701. 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]
  8702. var composedPath=e.composedPath();// event flow: capture -> target -> bubbling
  8703. // capture phase
  8704. 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
  8705. 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
  8706. var index=composedPath.indexOf(e.currentTarget);// bubbling phase
  8707. 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) {
  8708. // throw new Error('Cannot find propagation path to disconnected target');
  8709. // }
  8710. if(Node.isNode(target)&&target.parentNode){// [target, parent, parent, root]
  8711. propagationPath.push(target.parentNode);target=target.parentNode;}}if(canvas){// @ts-ignore
  8712. 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
  8713. if(viewportX<0||viewportY<0||viewportX>width||viewportY>height){return null;}return this.pickHandler(position)||this.rootTarget||// return Document
  8714. null;}/**
  8715. * whether the native event trigger came from Canvas,
  8716. * should account for HTML shape
  8717. */;_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>
  8718. if(target===$el){return true;}// from <svg>
  8719. if($el&&$el.contains){return $el.contains(target);}}if(event.nativeEvent.composedPath){return event.nativeEvent.composedPath().indexOf($el)>-1;}// account for Touch
  8720. return false;}/**
  8721. * Find HTML from composed path in native UI event.
  8722. */;_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 (
  8723. // !(
  8724. // from instanceof FederatedPointerEvent &&
  8725. // to instanceof FederatedPointerEvent
  8726. // )
  8727. // )
  8728. // return;
  8729. 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 (
  8730. // !(
  8731. // from instanceof FederatedMouseEvent && to instanceof FederatedMouseEvent
  8732. // )
  8733. // )
  8734. // return;
  8735. 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
  8736. 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
  8737. 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
  8738. // @ts-ignore
  8739. var emitter=e.currentTarget.emitter;// @ts-ignore
  8740. 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);
  8741. }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);
  8742. }}}/**
  8743. * some detached nodes may exist in propagation path, need to skip them
  8744. */;_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;}();/**
  8745. * used in following scenes:
  8746. * - g `ctx.measureText`
  8747. * - g-plugin-canvas-picker `ctx.isPointInPath`
  8748. * - g-plugin-device-renderer `ctx.createLinearGradient` and generate texture
  8749. *
  8750. * @see https://blog.scottlogic.com/2020/03/19/offscreen-canvas.html
  8751. */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
  8752. if(offscreenCanvas){this.canvas=offscreenCanvas;this.context=this.canvas.getContext('2d',contextAttributes);}else {try{// OffscreenCanvas2D measureText can be up to 40% faster.
  8753. 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;}();/**
  8754. * why we need re-render
  8755. */(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={}));/**
  8756. * Use frame renderer implemented by `g-canvas/svg/webgl`, in every frame we do followings:
  8757. * * update & merge dirty rectangles
  8758. * * begin frame
  8759. * * filter by visible
  8760. * * sort by z-index in scene graph
  8761. * * culling with strategies registered in `g-canvas/webgl`
  8762. * * end frame
  8763. */var RenderingService=/*#__PURE__*/function(){function RenderingService(globalRuntime,context){this.globalRuntime=void 0;this.context=void 0;this.inited=false;this.stats={/**
  8764. * total display objects in scenegraph
  8765. */total:0,/**
  8766. * number of display objects need to render in current frame
  8767. */rendered:0};this.zIndexCounter=0;this.hooks={/**
  8768. * called before any frame rendered
  8769. */init:new SyncHook(),initAsync:new AsyncParallelHook(),/**
  8770. * only dirty object which has sth changed will be rendered
  8771. */dirtycheck:new SyncWaterfallHook(),/**
  8772. * do culling
  8773. */cull:new SyncWaterfallHook(),/**
  8774. * called at beginning of each frame, won't get called if nothing to re-render
  8775. */beginFrame:new SyncHook(),/**
  8776. * called before every dirty object get rendered
  8777. */beforeRender:new SyncHook(),/**
  8778. * called when every dirty object rendering even it's culled
  8779. */render:new SyncHook(),/**
  8780. * called after every dirty object get rendered
  8781. */afterRender:new SyncHook(),endFrame:new SyncHook(),destroy:new SyncHook(),/**
  8782. * use async but faster method such as GPU-based picking in `g-plugin-device-renderer`
  8783. */pick:new AsyncSeriesWaterfallHook(),/**
  8784. * Unsafe but sync version of pick.
  8785. */pickSync:new SyncWaterfallHook(),/**
  8786. * used in event system
  8787. */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
  8788. 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;}/**
  8789. * Meet the following conditions:
  8790. * * disable DirtyRectangleRendering
  8791. * * camera changed
  8792. */;_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);
  8793. };_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
  8794. if(this.globalRuntime.enableCSSParsing){this.globalRuntime.styleValueRegistry.recalc(displayObject);}// TODO: relayout
  8795. // dirtycheck first
  8796. 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
  8797. var sortable=displayObject.sortable;if(sortable.dirty){this.sort(displayObject,sortable);sortable.dirty=false;sortable.dirtyChildren=[];sortable.dirtyReason=undefined;}// recursive rendering its children
  8798. (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
  8799. sortable.dirtyChildren.forEach(function(child){var index=displayObject.childNodes.indexOf(child);if(index===-1){// remove from sorted list
  8800. 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
  8801. this.context.renderingContext.renderReasons.add(exports.RenderReason.DISPLAY_OBJECT_CHANGED);};return RenderingService;}();var ATTRIBUTE_REGEXP=/\[\s*(.*)=(.*)\s*\]/;/**
  8802. * support the following DOM API:
  8803. * * getElementById
  8804. * * getElementsByClassName
  8805. * * getElementsByName
  8806. * * getElementsByTag
  8807. * * querySelector
  8808. * * querySelectorAll
  8809. */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);
  8810. return ((node===null||node===void 0?void 0:node.classList)||[]).indexOf(_this.getIdOrClassname(query))>-1;});}else if(query.startsWith('#')){// getElementById('id')
  8811. return root.find(function(node){// return !node.shadow && node.id === query.substring(1);
  8812. 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();
  8813. return root.find(function(node){return root!==node&&(name==='name'?node.name===value:_this.attributeToString(node,name)===value);});}else {return null;}}else {// getElementsByTag('circle');
  8814. 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`
  8815. if(query.startsWith('.')){// getElementsByClassName('className');
  8816. // should not include itself
  8817. 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();
  8818. return root.findAll(function(node){return root!==node&&(name==='name'?node.name===value:_this2.attributeToString(node,name)===value);});}else {return [];}}else {// getElementsByTag('circle');
  8819. return root.findAll(function(node){return root!==node&&node.nodeName===query;});}};_proto.is=function is(query,node){// a simple `matches` implementation
  8820. 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,'','');/**
  8821. * update transform in scene graph
  8822. *
  8823. * @see https://community.khronos.org/t/scene-graphs/50542/7
  8824. */var DefaultSceneGraphService=/*#__PURE__*/function(){function DefaultSceneGraphService(runtime){var _this=this;this.runtime=void 0;this.pendingEvents=[];this.boundsChangedEvent=new CustomEvent(exports.ElementEvent.BOUNDS_CHANGED);/**
  8825. * rotate in world space
  8826. */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);}};}();/**
  8827. * rotate in local space
  8828. * @see @see https://docs.microsoft.com/en-us/windows/win32/api/directxmath/nf-directxmath-xmquaternionrotationrollpitchyaw
  8829. */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);};}();/**
  8830. * set euler angles(degrees) in world space
  8831. */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);}};}();/**
  8832. * translate in local space
  8833. *
  8834. * @example
  8835. * ```
  8836. * translateLocal(x, y, z)
  8837. * translateLocal(vec3(x, y, z))
  8838. * ```
  8839. */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);};}();/**
  8840. * move to position in world space
  8841. *
  8842. * 对应 g 原版的 move/moveTo
  8843. * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L684-L689
  8844. */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);};}();/**
  8845. * move to position in local space
  8846. */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);};}();/**
  8847. * translate in world space
  8848. *
  8849. * @example
  8850. * ```
  8851. * translate(x, y, z)
  8852. * translate(vec3(x, y, z))
  8853. * ```
  8854. *
  8855. * 对应 g 原版的 translate 2D
  8856. * @see https://github.com/antvis/g/blob/master/packages/g-base/src/abstract/element.ts#L665-L676
  8857. */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
  8858. 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
  8859. 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);
  8860. };_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
  8861. 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) {
  8862. // only child has z-Index
  8863. sortable.dirty=true;sortable.dirtyReason=exports.SortReason.ADDED;}// this.updateGraphDepth(child);
  8864. 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) {
  8865. // const worldTransform = this.getWorldTransform(child, transform);
  8866. // mat4.getScaling(transform.localScale, worldTransform);
  8867. // mat4.getTranslation(transform.localPosition, worldTransform);
  8868. // mat4.getRotation(transform.localRotation, worldTransform);
  8869. // transform.localDirtyFlag = true;
  8870. // }
  8871. // parent needs re-sort
  8872. var sortable=child.parentNode.sortable;// if (sortable) {
  8873. 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;}/**
  8874. * same as pivot in Pixi.js
  8875. *
  8876. * @see https://stackoverflow.com/questions/40748452/how-to-change-css-transform-origin-but-preserve-transformation
  8877. */;_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);
  8878. // vec3.add(transform.localPosition, transform.localPosition, delta);
  8879. // update origin
  8880. originVec[0]=origin[0];originVec[1]=origin[1];originVec[2]=origin[2]||0;this.dirtifyLocal(element,transform);};/**
  8881. * set euler angles(degrees) in local space
  8882. */_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);};/**
  8883. * scale in local space
  8884. */_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
  8885. if(p.renderable){p.renderable.dirty=true;}while(p){markRenderableDirty(p);p=p.parentNode;}if(affectChildren){element.forEach(function(e){markRenderableDirty(e);});}// inform dependencies
  8886. this.informDependentDisplayObjects(element);// reuse the same custom event
  8887. this.pendingEvents.push([element,{affectChildren:affectChildren}]);};_proto.updateDisplayObjectDependency=function updateDisplayObjectDependency(name,oldPath,newPath,object){// clear ref to old clip path
  8888. 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;}}/**
  8889. * won't account for children
  8890. */;_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();
  8891. return bounds||new AABB();}/**
  8892. * account for children in world space
  8893. */;_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
  8894. var existedAABB=render?renderable.renderBounds:renderable.bounds;// reset with geometry's aabb
  8895. var aabb=this.getTransformedGeometryBounds(element,render,existedAABB);// merge children's aabbs
  8896. 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
  8897. var clipped=findClosestClipPathTarget(element);if(clipped){// use bounds under world space
  8898. 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;}/**
  8899. * account for children in local space
  8900. */;_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
  8901. aabb.setFromTransformedAABB(bounds,this.getWorldTransform(element));}// calc context's offset
  8902. 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?
  8903. // @see https://github.com/playcanvas/engine/issues/1077#issuecomment-359765557
  8904. 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
  8905. ],BreakingSpaces:[0x0009,0x0020,0x2000,0x2001,0x2002,0x2003,0x2004,0x2005,0x2006,0x2008,0x2009,0x200a,0x205f,0x3000// ideographic space
  8906. ]};var LATIN_REGEX=/[a-zA-Z0-9\u00C0-\u00D6\u00D8-\u00f6\u00f8-\u00ff!"#$%&'()*+,-./:;]/;// Line breaking rules in CJK (Kinsoku Shori)
  8907. // Refer from https://en.wikipedia.org/wiki/Line_breaking_rules_in_East_Asian_languages
  8908. 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);/**
  8909. * Borrow from pixi/packages/text/src/TextMetrics.ts
  8910. */var TextService=/*#__PURE__*/function(){function TextService(runtime){var _this=this;this.runtime=void 0;/**
  8911. * font metrics cache
  8912. */this.fontMetricsCache={};this.shouldBreakByKinsokuShorui=function(char,nextChar){if(_this.isBreakingSpace(nextChar))return false;if(char){// Line breaking rules in CJK (Kinsoku Shori)
  8913. 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;/**
  8914. * Calculates the ascent, descent and fontSize of a given font-style.
  8915. */_proto.measureFont=function measureFont(font,offscreenCanvas){// as this method is used for preparing assets, don't recalculate things if we don't need to
  8916. 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
  8917. canvas.width=width;// @ts-ignore
  8918. 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
  8919. 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
  8920. 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) {
  8921. var fontProperties=this.measureFont(font,offscreenCanvas);// fallback in case UA disallow canvas data extraction
  8922. // (toDataURI, getImageData functions)
  8923. if(fontProperties.fontSize===0){fontProperties.fontSize=fontSize;fontProperties.ascent=fontSize;}// } else {
  8924. // fontProperties = {
  8925. // fontSize,
  8926. // };
  8927. // }
  8928. var context=this.runtime.offscreenCanvas.getOrCreateContext(offscreenCanvas);context.font=font;// no overflowing by default
  8929. 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
  8930. if(textPath){var totalPathLength=textPath.getTotalLength();// const startingPoint = textPath.getPoint(0);
  8931. for(var i=0;i<lines.length;i++){var width=context.measureText(lines[i]).width+(lines[i].length-1)*letterSpacing;// for (
  8932. // let i = reverse ? lines[0].length - 1 : 0;
  8933. // reverse ? i >= 0 : i < lines[0].length;
  8934. // reverse ? i-- : i++
  8935. // ) {
  8936. // graphemeInfo = lineBounds[i];
  8937. // if (positionInPath > totalPathLength) {
  8938. // positionInPath %= totalPathLength;
  8939. // } else if (positionInPath < 0) {
  8940. // positionInPath += totalPathLength;
  8941. // }
  8942. // // it would probably much faster to send all the grapheme position for a line
  8943. // // and calculate path position/angle at once.
  8944. // this.setGraphemeOnPath(
  8945. // positionInPath,
  8946. // graphemeInfo,
  8947. // startingPoint
  8948. // );
  8949. // positionInPath += graphemeInfo.kernedWidth;
  8950. // }
  8951. }}else {for(var _i=0;_i<lines.length;_i++){// char width + letterSpacing
  8952. 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) {
  8953. // width += dropShadowDistance;
  8954. // }
  8955. var lineHeight=strokeHeight||fontProperties.fontSize+lineWidth;var height=Math.max(lineHeight,fontProperties.fontSize+lineWidth)+(lines.length-1)*(lineHeight+leading);// if (dropShadow) {
  8956. // height += dropShadowDistance;
  8957. // }
  8958. lineHeight+=leading;// handle vertical text baseline
  8959. 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
  8960. 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
  8961. 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.
  8962. // @see https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow#values
  8963. if(ellipsisWidth>0&&ellipsisWidth<=maxWidth){// Backspace from line's end.
  8964. 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 runtime={};/**
  8965. * Replace with IoC container
  8966. */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
  8967. if(typeof global!=='undefined')return global;throw new Error('Unable to locate global `this`');};/**
  8968. * Camera
  8969. * `g-camera-api` will provide an advanced implementation
  8970. */runtime.CameraContribution=Camera;/**
  8971. * `g-web-animations-api` will provide an AnimationTimeline
  8972. */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({/**
  8973. * only dirty object will cause re-render
  8974. */enableDirtyCheck:true,enableCulling:false,/**
  8975. * enable auto rendering by default
  8976. */enableAutoRendering:true,/**
  8977. * enable dirty rectangle rendering by default
  8978. */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;}();/**
  8979. * apply following rules:
  8980. * 1. `visibility` in scenegraph node
  8981. * 2. other custom culling strategies, eg. frustum culling
  8982. */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;
  8983. // const renderBounds = object.getRenderBounds();
  8984. // if (AABB.isEmpty(renderBounds)) {
  8985. // cullable.visible = false;
  8986. // } else {
  8987. // const isShape2D = shape2D.indexOf(object.nodeName as Shape) > -1;
  8988. // const [p0, p1, p2, p3] = camera.getFrustum().planes;
  8989. // tmpAABB.setMinMax([-p1.distance, -p3.distance, 0], [p0.distance, p2.distance, 0]);
  8990. // cullable.visible = isShape2D ? renderBounds.intersects(tmpAABB) : true;
  8991. // }
  8992. if(strategies.length===0){cullable.visible=renderingContext.unculledEntities.indexOf(object.entity)>-1;}else {// eg. implemented by g-webgl(frustum culling)
  8993. 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) {
  8994. object.dispatchEvent(new CustomEvent(exports.ElementEvent.CULLED));// }
  8995. }return null;}return object;});renderingService.hooks.afterRender.tap(CullingPlugin.tag,function(object){object.cullable.visibilityPlaneMask=-1;});};return CullingPlugin;}();CullingPlugin.tag='Culling';/**
  8996. * Filter dirty renderables and calculate the "dirty rectangle" which will be clear when frame began
  8997. */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';/**
  8998. * support mouse & touch events
  8999. * @see https://github.com/pixijs/pixi.js/blob/dev/packages/interaction/README.md
  9000. *
  9001. * also provide some extra events such as `drag`
  9002. */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
  9003. }),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
  9004. 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
  9005. // @see https://github.com/antvis/G/issues/1235
  9006. }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;/**
  9007. * Should account for CSS Transform applied on container.
  9008. * @see https://github.com/antvis/G/issues/1161
  9009. * @see https://developer.mozilla.org/zh-CN/docs/Web/API/MouseEvent/offsetX
  9010. */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;}/**
  9011. * Transfers base & mouse event data from the nativeEvent to the federated event.
  9012. */;_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
  9013. // @see https://stackoverflow.com/a/10079076
  9014. 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
  9015. 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
  9016. 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;
  9017. var cullable=object.cullable;if(!cullable.enable){return true;}var renderBounds=object.getRenderBounds();if(AABB.isEmpty(renderBounds)){return false;}// get VP matrix from camera
  9018. 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;}/**
  9019. *
  9020. * @see「Optimized View Frustum Culling Algorithms for Bounding Boxes」
  9021. * @see https://github.com/antvis/GWebGPUEngine/issues/3
  9022. *
  9023. * * 基础相交测试 the basic intersection test
  9024. * * 标记 masking @see https://cesium.com/blog/2015/08/04/fast-hierarchical-culling/
  9025. * * TODO: 平面一致性测试 the plane-coherency test
  9026. * * TODO: 支持 mesh 指定自身的剔除策略,参考 Babylon.js @see https://doc.babylonjs.com/how_to/optimizing_your_scene#changing-mesh-culling-strategy
  9027. *
  9028. * @param aabb aabb
  9029. * @param parentPlaneMask mask of parent
  9030. * @param planes planes of frustum
  9031. */;_proto.computeVisibilityWithPlaneMask=function computeVisibilityWithPlaneMask(object,aabb,parentPlaneMask,planes){if(parentPlaneMask===exports.Mask.OUTSIDE||parentPlaneMask===exports.Mask.INSIDE){// 父节点完全位于视锥内或者外部,直接返回
  9032. return parentPlaneMask;}// Start with MASK_INSIDE (all zeros) so that after the loop, the return value can be compared with MASK_INSIDE.
  9033. // (Because if there are fewer than 31 planes, the upper bits wont be changed.)
  9034. var mask=exports.Mask.INSIDE;var isShape2D=shape2D.indexOf(object.nodeName)>-1;// Use viewport culling for 2D shapes
  9035. // @see https://github.com/antvis/g/issues/914
  9036. 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.
  9037. var flag=1<<k;if((parentPlaneMask&flag)===0){// 父节点处于当前面内部,可以跳过
  9038. continue;}// skip near & far planes when testing 2D shapes
  9039. if(isShape2D&&(k===4||k===5)){continue;}// p-vertex n-vertex <-|plane p-vertex n-vertex
  9040. // 使用 p-vertex 和 n-vertex 加速,避免进行平面和 aabb 全部顶点的相交检测
  9041. 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,继续检测下一个面
  9042. mask|=flag;}}return mask;};return FrustumCullingStrategy;}();var PrepareRendererPlugin=/*#__PURE__*/function(){function PrepareRendererPlugin(){this.rBush=void 0;/**
  9043. * sync to RBush later
  9044. */this.toSync=new Set();}var _proto=PrepareRendererPlugin.prototype;// private isFirstTimeRendering = true;
  9045. // private syncing = false;
  9046. _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[]);
  9047. renderingService.dirtify();};var handleMounted=function handleMounted(e){var object=e.target;if(runtime.enableCSSParsing){// recalc style values
  9048. 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) {
  9049. // this.isFirstTimeRendering = false;
  9050. // this.syncing = true;
  9051. // // @see https://github.com/antvis/G/issues/1117
  9052. // setTimeout(() => {
  9053. // this.syncRTree();
  9054. // console.log('fcp...');
  9055. // });
  9056. // } else {
  9057. // console.log('next...');
  9058. _this.syncRTree();// }
  9059. });};_proto.syncRTree=function syncRTree(){var _this2=this;// if (this.syncing) {
  9060. // return;
  9061. // }
  9062. // bounds changed, need re-inserting its children
  9063. var bulk=[];Array.from(this.toSync)// some objects may be removed since last frame
  9064. .filter(function(object){return object.isConnected;}).forEach(function(node){var rBushNode=node.rBushNode;// clear dirty node
  9065. 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
  9066. 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
  9067. // @see https://github.com/mourner/rbush#bulk-inserting-data
  9068. this.rBush.load(bulk);bulk.length=0;this.toSync.clear();// this.syncing = false;
  9069. };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;/**
  9070. * reuse custom event preventing from re-create them in every frame
  9071. */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);/**
  9072. * can be treated like Window in DOM
  9073. * provide some extra methods like `window`, such as:
  9074. * * `window.requestAnimationFrame`
  9075. * * `window.devicePixelRatio`
  9076. *
  9077. * prototype chains: Canvas(Window) -> EventTarget
  9078. */var Canvas=/*#__PURE__*/function(_EventTarget){_inheritsLoose(Canvas,_EventTarget);function Canvas(config){var _this;_this=_EventTarget.call(this)||this;// create document
  9079. /**
  9080. * window.document
  9081. */_this.document=void 0;/**
  9082. * @see https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry
  9083. */_this.customElements=void 0;/**
  9084. * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
  9085. */_this.requestAnimationFrame=void 0;/**
  9086. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
  9087. */_this.cancelAnimationFrame=void 0;/**
  9088. * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/devicePixelRatio
  9089. */_this.devicePixelRatio=void 0;/**
  9090. * whether the runtime supports PointerEvent?
  9091. * if not, the event system won't trigger pointer events like `pointerdown`
  9092. */_this.supportsPointerEvents=void 0;/**
  9093. * whether the runtime supports TouchEvent?
  9094. * if not, the event system won't trigger touch events like `touchstart`
  9095. */_this.supportsTouchEvents=void 0;/**
  9096. * is this native event a TouchEvent?
  9097. */_this.isTouchEvent=void 0;/**
  9098. * is this native event a MouseEvent?
  9099. */_this.isMouseEvent=void 0;/**
  9100. * @see https://developer.mozilla.org/en-US/docs/Web/API/Element
  9101. */_this.Element=DisplayObject;/**
  9102. * rAF in auto rendering
  9103. */_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
  9104. _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
  9105. if(canvas){// infer width & height with dpr
  9106. 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;}/**
  9107. * implements `Window` interface
  9108. */_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);/**
  9109. * limits query
  9110. */ // the following feature-detect from hammer.js
  9111. // @see https://github.com/hammerjs/hammer.js/blob/master/src/inputjs/input-consts.js#L5
  9112. _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
  9113. this.context.renderingContext={/**
  9114. * the root node in scene graph
  9115. */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
  9116. 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
  9117. camera.canvas=this;// redraw when camera changed
  9118. camera.eventEmitter.on(CameraEvent.UPDATED,function(){_this2.context.renderingContext.renderReasons.add(exports.RenderReason.CAMERA_CHANGED);});// bind camera
  9119. this.context.camera=camera;};_proto.getConfig=function getConfig(){return this.context.config;}/**
  9120. * get the root displayObject in scenegraph
  9121. * @alias this.document.documentElement
  9122. */;_proto.getRoot=function getRoot(){return this.document.documentElement;}/**
  9123. * get the camera of canvas
  9124. */;_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();}// /**
  9125. // * @see https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle
  9126. // */
  9127. // getComputedStyle(node: DisplayObject) {
  9128. // return node.computedStyle;
  9129. // }
  9130. ;/**
  9131. * `cleanUp` means clean all the internal services of Canvas which happens when calling `canvas.destroy()`.
  9132. */_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
  9133. var root=this.getRoot();this.unmountChildren(root);if(cleanUp){// destroy Document
  9134. this.document.destroy();this.getEventService().destroy();}// destroy services
  9135. this.getRenderingService().destroy();this.getContextService().destroy();// clear root after renderservice destroyed
  9136. if(cleanUp&&this.context.rBushRoot){// clear rbush
  9137. this.context.rBushRoot.clear();this.context.rBushRoot=null;this.context.renderingContext.root=null;}if(!skipTriggerEvent){this.dispatchEvent(new CustomEvent(exports.CanvasEvent.AFTER_DESTROY));}}/**
  9138. * compatible with G 3.0
  9139. * @deprecated
  9140. * @alias resize
  9141. */;_proto.changeSize=function changeSize(width,height){this.resize(width,height);};_proto.resize=function resize(width,height){// update canvas' config
  9142. var canvasConfig=this.context.config;canvasConfig.width=width;canvasConfig.height=height;// resize context
  9143. this.getContextService().resize(width,height);// resize camera
  9144. 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
  9145. ;_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);}/**
  9146. * Remove all children which can be appended to its original parent later again.
  9147. */;_proto.removeChildren=function removeChildren(){this.document.documentElement.removeChildren();}/**
  9148. * Recursively destroy all children which can not be appended to its original parent later again.
  9149. * But the canvas remains running which means display objects can be appended later.
  9150. */;_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
  9151. // @see https://github.com/antvis/G/issues/1268
  9152. _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
  9153. this.inited=false;this.readyPromise=undefined;// FIXME: should re-create here?
  9154. this.context.rBushRoot=new rbush();// reset rendering plugins
  9155. this.context.renderingPlugins=[];this.context.renderingPlugins.push(new EventPlugin(),new PrepareRendererPlugin(),new DirtyCheckPlugin(),new CullingPlugin([new FrustumCullingStrategy()]));//
  9156. this.loadRendererContainerModule(renderer);// init context service
  9157. this.context.contextService=new this.context.ContextService(_extends({},runtime,this.context));// init rendering service
  9158. this.context.renderingService=new RenderingService(runtime,this.context);// init event service
  9159. 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
  9160. _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
  9161. var plugins=renderer.getPlugins();plugins.forEach(function(plugin){plugin.context=_this7.context;plugin.init(runtime);});};_proto.setRenderer=function setRenderer(renderer){// update canvas' config
  9162. var canvasConfig=this.getConfig();if(canvasConfig.renderer===renderer){return;}var oldRenderer=canvasConfig.renderer;canvasConfig.renderer=renderer;// keep all children undestroyed
  9163. this.destroy(false,true);// destroy all plugins, reverse will mutate origin array
  9164. [].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
  9165. 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
  9166. if(parent!==this.document.documentElement){parent.ownerDocument=null;}parent.isConnected=false;}// trigger after unmounted
  9167. 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
  9168. parent.childNodes.forEach(function(child){_this9.mountChildren(child);});// trigger after mounted
  9169. 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);}/**
  9170. * @deprecated
  9171. * @alias client2Viewport
  9172. */;_proto.getPointByClient=function getPointByClient(clientX,clientY){return this.client2Viewport({x:clientX,y:clientY});}/**
  9173. * @deprecated
  9174. * @alias viewport2Client
  9175. */;_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);
  9176. function _inheritsLoose$1(subClass, superClass) {
  9177. subClass.prototype = Object.create(superClass.prototype);
  9178. subClass.prototype.constructor = subClass;
  9179. _setPrototypeOf$1(subClass, superClass);
  9180. }
  9181. function _setPrototypeOf$1(o, p) {
  9182. _setPrototypeOf$1 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  9183. o.__proto__ = p;
  9184. return o;
  9185. };
  9186. return _setPrototypeOf$1(o, p);
  9187. }
  9188. /**
  9189. * Provides camera action & animation.
  9190. */
  9191. var AdvancedCamera = /*#__PURE__*/function (_Camera) {
  9192. _inheritsLoose$1(AdvancedCamera, _Camera);
  9193. function AdvancedCamera() {
  9194. var _this;
  9195. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  9196. args[_key] = arguments[_key];
  9197. }
  9198. _this = _Camera.call.apply(_Camera, [this].concat(args)) || this;
  9199. /**
  9200. * switch between multiple landmarks
  9201. */
  9202. _this.landmarks = [];
  9203. _this.landmarkAnimationID = void 0;
  9204. return _this;
  9205. }
  9206. var _proto = AdvancedCamera.prototype;
  9207. /**
  9208. * Changes the azimuth and elevation with respect to the current camera axes
  9209. * @param {Number} azimuth the relative azimuth
  9210. * @param {Number} elevation the relative elevation
  9211. * @param {Number} roll the relative roll
  9212. */
  9213. _proto.rotate = function rotate(azimuth, elevation, roll) {
  9214. this.relElevation = getAngle$1(elevation);
  9215. this.relAzimuth = getAngle$1(azimuth);
  9216. this.relRoll = getAngle$1(roll);
  9217. this.elevation += this.relElevation;
  9218. this.azimuth += this.relAzimuth;
  9219. this.roll += this.relRoll;
  9220. if (this.type === exports.CameraType.EXPLORING) {
  9221. var rotX = setAxisAngle(create$4(), [1, 0, 0], deg2rad((this.rotateWorld ? 1 : -1) * this.relElevation));
  9222. var rotY = setAxisAngle(create$4(), [0, 1, 0], deg2rad((this.rotateWorld ? 1 : -1) * this.relAzimuth));
  9223. var rotZ = setAxisAngle(create$4(), [0, 0, 1], deg2rad(this.relRoll));
  9224. var rotQ = multiply$2(create$4(), rotY, rotX);
  9225. rotQ = multiply$2(create$4(), rotQ, rotZ);
  9226. var rotMatrix = fromQuat(create$1(), rotQ);
  9227. translate(this.matrix, this.matrix, [0, 0, -this.distance]);
  9228. multiply(this.matrix, this.matrix, rotMatrix);
  9229. translate(this.matrix, this.matrix, [0, 0, this.distance]);
  9230. } else {
  9231. if (Math.abs(this.elevation) > 90) {
  9232. return this;
  9233. }
  9234. this.computeMatrix();
  9235. }
  9236. this._getAxes();
  9237. if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
  9238. this._getPosition();
  9239. } else if (this.type === exports.CameraType.TRACKING) {
  9240. this._getFocalPoint();
  9241. }
  9242. this._update();
  9243. return this;
  9244. }
  9245. /**
  9246. * 沿水平(right) & 垂直(up)平移相机
  9247. */;
  9248. _proto.pan = function pan(tx, ty) {
  9249. var coords = createVec3(tx, ty, 0);
  9250. var pos = clone$1(this.position);
  9251. add$1(pos, pos, scale$1(create$2(), this.right, coords[0]));
  9252. add$1(pos, pos, scale$1(create$2(), this.up, coords[1]));
  9253. this._setPosition(pos);
  9254. this.triggerUpdate();
  9255. return this;
  9256. }
  9257. /**
  9258. * 沿 n 轴移动,当距离视点远时移动速度较快,离视点越近速度越慢
  9259. */;
  9260. _proto.dolly = function dolly(value) {
  9261. var n = this.forward;
  9262. var pos = clone$1(this.position);
  9263. var step = value * this.dollyingStep;
  9264. var updatedDistance = this.distance + value * this.dollyingStep;
  9265. // 限制视点距离范围
  9266. step = Math.max(Math.min(updatedDistance, this.maxDistance), this.minDistance) - this.distance;
  9267. pos[0] += step * n[0];
  9268. pos[1] += step * n[1];
  9269. pos[2] += step * n[2];
  9270. this._setPosition(pos);
  9271. if (this.type === exports.CameraType.ORBITING || this.type === exports.CameraType.EXPLORING) {
  9272. // 重新计算视点距离
  9273. this._getDistance();
  9274. } else if (this.type === exports.CameraType.TRACKING) {
  9275. // 保持视距,移动视点位置
  9276. add$1(this.focalPoint, pos, this.distanceVector);
  9277. }
  9278. this.triggerUpdate();
  9279. return this;
  9280. };
  9281. _proto.cancelLandmarkAnimation = function cancelLandmarkAnimation() {
  9282. if (this.landmarkAnimationID !== undefined) {
  9283. this.canvas.cancelAnimationFrame(this.landmarkAnimationID);
  9284. }
  9285. };
  9286. _proto.createLandmark = function createLandmark(name, params) {
  9287. var _position$, _position$2, _focalPoint$, _focalPoint$2;
  9288. if (params === void 0) {
  9289. params = {};
  9290. }
  9291. var _params = params,
  9292. _params$position = _params.position,
  9293. position = _params$position === void 0 ? this.position : _params$position,
  9294. _params$focalPoint = _params.focalPoint,
  9295. focalPoint = _params$focalPoint === void 0 ? this.focalPoint : _params$focalPoint,
  9296. roll = _params.roll,
  9297. zoom = _params.zoom;
  9298. var camera = new runtime.CameraContribution();
  9299. camera.setType(this.type, undefined);
  9300. camera.setPosition(position[0], (_position$ = position[1]) !== null && _position$ !== void 0 ? _position$ : this.position[1], (_position$2 = position[2]) !== null && _position$2 !== void 0 ? _position$2 : this.position[2]);
  9301. camera.setFocalPoint(focalPoint[0], (_focalPoint$ = focalPoint[1]) !== null && _focalPoint$ !== void 0 ? _focalPoint$ : this.focalPoint[1], (_focalPoint$2 = focalPoint[2]) !== null && _focalPoint$2 !== void 0 ? _focalPoint$2 : this.focalPoint[2]);
  9302. camera.setRoll(roll !== null && roll !== void 0 ? roll : this.roll);
  9303. camera.setZoom(zoom !== null && zoom !== void 0 ? zoom : this.zoom);
  9304. var landmark = {
  9305. name: name,
  9306. matrix: clone(camera.getWorldTransform()),
  9307. right: clone$1(camera.right),
  9308. up: clone$1(camera.up),
  9309. forward: clone$1(camera.forward),
  9310. position: clone$1(camera.getPosition()),
  9311. focalPoint: clone$1(camera.getFocalPoint()),
  9312. distanceVector: clone$1(camera.getDistanceVector()),
  9313. distance: camera.getDistance(),
  9314. dollyingStep: camera.getDollyingStep(),
  9315. azimuth: camera.getAzimuth(),
  9316. elevation: camera.getElevation(),
  9317. roll: camera.getRoll(),
  9318. relAzimuth: camera.relAzimuth,
  9319. relElevation: camera.relElevation,
  9320. relRoll: camera.relRoll,
  9321. zoom: camera.getZoom()
  9322. };
  9323. this.landmarks.push(landmark);
  9324. return landmark;
  9325. };
  9326. _proto.gotoLandmark = function gotoLandmark(name, options) {
  9327. var _this2 = this;
  9328. if (options === void 0) {
  9329. options = {};
  9330. }
  9331. var landmark = isString(name) ? this.landmarks.find(function (l) {
  9332. return l.name === name;
  9333. }) : name;
  9334. if (landmark) {
  9335. var _ref = isNumber(options) ? {
  9336. duration: options
  9337. } : options,
  9338. _ref$easing = _ref.easing,
  9339. easing = _ref$easing === void 0 ? 'linear' : _ref$easing,
  9340. _ref$duration = _ref.duration,
  9341. duration = _ref$duration === void 0 ? 100 : _ref$duration,
  9342. _ref$easingFunction = _ref.easingFunction,
  9343. easingFunction = _ref$easingFunction === void 0 ? undefined : _ref$easingFunction,
  9344. _ref$onfinish = _ref.onfinish,
  9345. onfinish = _ref$onfinish === void 0 ? undefined : _ref$onfinish;
  9346. var epsilon = 0.01;
  9347. if (duration === 0) {
  9348. this.syncFromLandmark(landmark);
  9349. if (onfinish) {
  9350. onfinish();
  9351. }
  9352. return;
  9353. }
  9354. // cancel ongoing animation
  9355. this.cancelLandmarkAnimation();
  9356. var destPosition = landmark.position;
  9357. var destFocalPoint = landmark.focalPoint;
  9358. var destZoom = landmark.zoom;
  9359. var destRoll = landmark.roll;
  9360. var easingFunc = easingFunction || runtime.EasingFunction(easing);
  9361. var timeStart;
  9362. var endAnimation = function endAnimation() {
  9363. _this2.setFocalPoint(destFocalPoint);
  9364. _this2.setPosition(destPosition);
  9365. _this2.setRoll(destRoll);
  9366. _this2.setZoom(destZoom);
  9367. _this2.computeMatrix();
  9368. _this2.triggerUpdate();
  9369. if (onfinish) {
  9370. onfinish();
  9371. }
  9372. };
  9373. var animate = function animate(timestamp) {
  9374. if (timeStart === undefined) {
  9375. timeStart = timestamp;
  9376. }
  9377. var elapsed = timestamp - timeStart;
  9378. if (elapsed > duration) {
  9379. endAnimation();
  9380. return;
  9381. }
  9382. // use the same ease function in animation system
  9383. var t = easingFunc(elapsed / duration);
  9384. var interFocalPoint = create$2();
  9385. var interPosition = create$2();
  9386. var interZoom = 1;
  9387. var interRoll = 0;
  9388. lerp(interFocalPoint, _this2.focalPoint, destFocalPoint, t);
  9389. lerp(interPosition, _this2.position, destPosition, t);
  9390. interRoll = _this2.roll * (1 - t) + destRoll * t;
  9391. interZoom = _this2.zoom * (1 - t) + destZoom * t;
  9392. _this2.setFocalPoint(interFocalPoint);
  9393. _this2.setPosition(interPosition);
  9394. _this2.setRoll(interRoll);
  9395. _this2.setZoom(interZoom);
  9396. var dist$1 = dist(interFocalPoint, destFocalPoint) + dist(interPosition, destPosition);
  9397. if (dist$1 <= epsilon && destZoom == undefined && destRoll == undefined) {
  9398. endAnimation();
  9399. return;
  9400. }
  9401. _this2.computeMatrix();
  9402. _this2.triggerUpdate();
  9403. if (elapsed < duration) {
  9404. _this2.landmarkAnimationID = _this2.canvas.requestAnimationFrame(animate);
  9405. }
  9406. };
  9407. this.canvas.requestAnimationFrame(animate);
  9408. }
  9409. };
  9410. _proto.syncFromLandmark = function syncFromLandmark(landmark) {
  9411. this.matrix = copy(this.matrix, landmark.matrix);
  9412. this.right = copy$1(this.right, landmark.right);
  9413. this.up = copy$1(this.up, landmark.up);
  9414. this.forward = copy$1(this.forward, landmark.forward);
  9415. this.position = copy$1(this.position, landmark.position);
  9416. this.focalPoint = copy$1(this.focalPoint, landmark.focalPoint);
  9417. this.distanceVector = copy$1(this.distanceVector, landmark.distanceVector);
  9418. this.azimuth = landmark.azimuth;
  9419. this.elevation = landmark.elevation;
  9420. this.roll = landmark.roll;
  9421. this.relAzimuth = landmark.relAzimuth;
  9422. this.relElevation = landmark.relElevation;
  9423. this.relRoll = landmark.relRoll;
  9424. this.dollyingStep = landmark.dollyingStep;
  9425. this.distance = landmark.distance;
  9426. this.zoom = landmark.zoom;
  9427. };
  9428. return AdvancedCamera;
  9429. }(Camera);
  9430. runtime.CameraContribution = AdvancedCamera;
  9431. var MutationRecord = /*#__PURE__*/function () {
  9432. MutationRecord.copy = function copy(original) {
  9433. var record = new MutationRecord(original.type, original.target);
  9434. record.addedNodes = original.addedNodes.slice();
  9435. record.removedNodes = original.removedNodes.slice();
  9436. record.previousSibling = original.previousSibling;
  9437. record.nextSibling = original.nextSibling;
  9438. record.attributeName = original.attributeName;
  9439. record.attributeNamespace = original.attributeNamespace;
  9440. record.oldValue = original.oldValue;
  9441. return record;
  9442. };
  9443. function MutationRecord(type, target) {
  9444. this.type = void 0;
  9445. this.target = void 0;
  9446. this.addedNodes = [];
  9447. this.attributeName = null;
  9448. this.attributeNamespace = null;
  9449. this.nextSibling = null;
  9450. this.oldValue = null;
  9451. this.previousSibling = null;
  9452. this.removedNodes = [];
  9453. this.type = type;
  9454. this.target = target;
  9455. }
  9456. return MutationRecord;
  9457. }();
  9458. var uidCounter = 0;
  9459. var registrationsTable = new WeakMap();
  9460. var Registration = /*#__PURE__*/function () {
  9461. function Registration(observer, target, options) {
  9462. this.observer = void 0;
  9463. this.target = void 0;
  9464. this.options = void 0;
  9465. this.transientObservedNodes = [];
  9466. this.observer = observer;
  9467. this.target = target;
  9468. this.options = options;
  9469. }
  9470. var _proto = Registration.prototype;
  9471. _proto.enqueue = function enqueue(record) {
  9472. var records = this.observer.records;
  9473. var length = records.length;
  9474. // There are cases where we replace the last record with the new record.
  9475. // For example if the record represents the same mutation we need to use
  9476. // the one with the oldValue. If we get same record (this can happen as we
  9477. // walk up the tree) we ignore the new record.
  9478. if (records.length > 0) {
  9479. var lastRecord = records[length - 1];
  9480. var recordToReplaceLast = selectRecord(lastRecord, record);
  9481. if (recordToReplaceLast) {
  9482. records[length - 1] = recordToReplaceLast;
  9483. return;
  9484. }
  9485. } else {
  9486. scheduleCallback(this.observer);
  9487. }
  9488. records[length] = record;
  9489. };
  9490. _proto.addListeners = function addListeners() {
  9491. this.addListeners_(this.target);
  9492. };
  9493. _proto.addListeners_ = function addListeners_(node) {
  9494. var options = this.options;
  9495. if (options.attributes) node.addEventListener(exports.ElementEvent.ATTR_MODIFIED, this, true);
  9496. // if (options.characterData) node.addEventListener('DOMCharacterDataModified', this, true);
  9497. if (options.childList) node.addEventListener(exports.ElementEvent.INSERTED, this, true);
  9498. if (options.childList || options.subtree) node.addEventListener(exports.ElementEvent.REMOVED, this, true);
  9499. };
  9500. _proto.removeListeners = function removeListeners() {
  9501. this.removeListeners_(this.target);
  9502. };
  9503. _proto.removeListeners_ = function removeListeners_(node) {
  9504. var options = this.options;
  9505. if (options.attributes) node.removeEventListener(exports.ElementEvent.ATTR_MODIFIED, this, true);
  9506. // if (options.characterData) node.removeEventListener('DOMCharacterDataModified', this, true);
  9507. if (options.childList) node.removeEventListener(exports.ElementEvent.INSERTED, this, true);
  9508. if (options.childList || options.subtree) node.removeEventListener(exports.ElementEvent.REMOVED, this, true);
  9509. }
  9510. /**
  9511. * Adds a transient observer on node. The transient observer gets removed
  9512. * next time we deliver the change records.
  9513. */
  9514. // addTransientObserver(node: IElement) {
  9515. // // Don't add transient observers on the target itself. We already have all
  9516. // // the required listeners set up on the target.
  9517. // if (node === this.target) return;
  9518. // this.addListeners_(node);
  9519. // this.transientObservedNodes.push(node);
  9520. // let registrations = registrationsTable.get(node);
  9521. // if (!registrations) registrationsTable.set(node, (registrations = []));
  9522. // // We know that registrations does not contain this because we already
  9523. // // checked if node === this.target.
  9524. // registrations.push(this);
  9525. // }
  9526. ;
  9527. _proto.removeTransientObservers = function removeTransientObservers() {
  9528. var transientObservedNodes = this.transientObservedNodes;
  9529. this.transientObservedNodes = [];
  9530. transientObservedNodes.forEach(function (node) {
  9531. // Transient observers are never added to the target.
  9532. this.removeListeners_(node);
  9533. var registrations = registrationsTable.get(node);
  9534. for (var i = 0; i < registrations.length; i++) {
  9535. if (registrations[i] === this) {
  9536. registrations.splice(i, 1);
  9537. // Each node can only have one registered observer associated with
  9538. // this observer.
  9539. break;
  9540. }
  9541. }
  9542. }, this);
  9543. };
  9544. _proto.handleEvent = function handleEvent(e) {
  9545. // Stop propagation since we are managing the propagation manually.
  9546. // This means that other mutation events on the page will not work
  9547. // correctly but that is by design.
  9548. e.stopImmediatePropagation();
  9549. var record;
  9550. var target;
  9551. switch (e.type) {
  9552. case exports.ElementEvent.ATTR_MODIFIED:
  9553. // http://dom.spec.whatwg.org/#concept-mo-queue-attributes
  9554. var name = e.attrName;
  9555. // @ts-ignore
  9556. var namespace = e.relatedNode.namespaceURI;
  9557. target = e.target;
  9558. // 1.
  9559. record = getRecord('attributes', target);
  9560. record.attributeName = name;
  9561. record.attributeNamespace = namespace;
  9562. // 2.
  9563. var oldValue = e.attrChange === MutationEvent.ADDITION ? null : e.prevValue;
  9564. forEachAncestorAndObserverEnqueueRecord(target, function (options) {
  9565. // 3.1, 4.2
  9566. if (!options.attributes) return;
  9567. // 3.2, 4.3
  9568. if (options.attributeFilter && options.attributeFilter.length && options.attributeFilter.indexOf(name) === -1 && options.attributeFilter.indexOf(namespace) === -1) {
  9569. return;
  9570. }
  9571. // 3.3, 4.4
  9572. if (options.attributeOldValue) return getRecordWithOldValue(oldValue);
  9573. // 3.4, 4.5
  9574. return record;
  9575. });
  9576. break;
  9577. // case 'DOMCharacterDataModified':
  9578. // // http://dom.spec.whatwg.org/#concept-mo-queue-characterdata
  9579. // var target = e.target;
  9580. // // 1.
  9581. // var record = getRecord('characterData', target);
  9582. // // 2.
  9583. // var oldValue = e.prevValue;
  9584. // forEachAncestorAndObserverEnqueueRecord(target, function(options) {
  9585. // // 3.1, 4.2
  9586. // if (!options.characterData)
  9587. // return;
  9588. // // 3.2, 4.3
  9589. // if (options.characterDataOldValue)
  9590. // return getRecordWithOldValue(oldValue);
  9591. // // 3.3, 4.4
  9592. // return record;
  9593. // });
  9594. // break;
  9595. case exports.ElementEvent.REMOVED:
  9596. // this.addTransientObserver(e.target as IElement);
  9597. // Fall through.
  9598. case exports.ElementEvent.INSERTED:
  9599. // http://dom.spec.whatwg.org/#concept-mo-queue-childlist
  9600. target = e.relatedNode;
  9601. var changedNode = e.target;
  9602. var addedNodes;
  9603. var removedNodes;
  9604. if (e.type === exports.ElementEvent.INSERTED) {
  9605. addedNodes = [changedNode];
  9606. removedNodes = [];
  9607. } else {
  9608. addedNodes = [];
  9609. removedNodes = [changedNode];
  9610. }
  9611. var previousSibling = changedNode.previousSibling;
  9612. var nextSibling = changedNode.nextSibling;
  9613. // 1.
  9614. record = getRecord('childList', target);
  9615. record.addedNodes = addedNodes;
  9616. record.removedNodes = removedNodes;
  9617. record.previousSibling = previousSibling;
  9618. record.nextSibling = nextSibling;
  9619. forEachAncestorAndObserverEnqueueRecord(target, function (options) {
  9620. // 2.1, 3.2
  9621. if (!options.childList) return;
  9622. // 2.2, 3.3
  9623. return record;
  9624. });
  9625. }
  9626. clearRecords();
  9627. };
  9628. return Registration;
  9629. }();
  9630. /**
  9631. * @see https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
  9632. * @see https://github.com/googlearchive/MutationObservers/blob/master/MutationObserver.js
  9633. */
  9634. var MutationObserver = /*#__PURE__*/function () {
  9635. function MutationObserver(callback) {
  9636. this.callback = void 0;
  9637. this.nodes = [];
  9638. this.records = [];
  9639. this.uid = uidCounter++;
  9640. this.callback = callback;
  9641. }
  9642. var _proto2 = MutationObserver.prototype;
  9643. _proto2.observe = function observe(target, options) {
  9644. // 1.1
  9645. if (!options.childList && !options.attributes && !options.characterData ||
  9646. // 1.2
  9647. options.attributeOldValue && !options.attributes ||
  9648. // 1.3
  9649. options.attributeFilter && options.attributeFilter.length && !options.attributes ||
  9650. // 1.4
  9651. options.characterDataOldValue && !options.characterData) {
  9652. throw new SyntaxError();
  9653. }
  9654. var registrations = registrationsTable.get(target);
  9655. if (!registrations) registrationsTable.set(target, registrations = []);
  9656. // 2
  9657. // If target's list of registered observers already includes a registered
  9658. // observer associated with the context object, replace that registered
  9659. // observer's options with options.
  9660. var registration;
  9661. for (var i = 0; i < registrations.length; i++) {
  9662. if (registrations[i].observer === this) {
  9663. registration = registrations[i];
  9664. registration.removeListeners();
  9665. registration.options = options;
  9666. break;
  9667. }
  9668. }
  9669. // 3.
  9670. // Otherwise, add a new registered observer to target's list of registered
  9671. // observers with the context object as the observer and options as the
  9672. // options, and add target to context object's list of nodes on which it
  9673. // is registered.
  9674. if (!registration) {
  9675. registration = new Registration(this, target, options);
  9676. registrations.push(registration);
  9677. this.nodes.push(target);
  9678. }
  9679. registration.addListeners();
  9680. };
  9681. _proto2.disconnect = function disconnect() {
  9682. var _this = this;
  9683. this.nodes.forEach(function (node) {
  9684. var registrations = registrationsTable.get(node);
  9685. for (var i = 0; i < registrations.length; i++) {
  9686. var registration = registrations[i];
  9687. if (registration.observer === _this) {
  9688. registration.removeListeners();
  9689. registrations.splice(i, 1);
  9690. // Each node can only have one registered observer associated with
  9691. // this observer.
  9692. break;
  9693. }
  9694. }
  9695. }, this);
  9696. this.records = [];
  9697. };
  9698. _proto2.takeRecords = function takeRecords() {
  9699. var copyOfRecords = this.records;
  9700. this.records = [];
  9701. return copyOfRecords;
  9702. };
  9703. return MutationObserver;
  9704. }();
  9705. // We keep track of the two (possibly one) records used in a single mutation.
  9706. var currentRecord;
  9707. var recordWithOldValue;
  9708. /**
  9709. * Creates a record without |oldValue| and caches it as |currentRecord| for
  9710. * later use.
  9711. */
  9712. function getRecord(type, target) {
  9713. return currentRecord = new MutationRecord(type, target);
  9714. }
  9715. /**
  9716. * Gets or creates a record with |oldValue| based in the |currentRecord|
  9717. */
  9718. function getRecordWithOldValue(oldValue) {
  9719. if (recordWithOldValue) return recordWithOldValue;
  9720. recordWithOldValue = MutationRecord.copy(currentRecord);
  9721. recordWithOldValue.oldValue = oldValue;
  9722. return recordWithOldValue;
  9723. }
  9724. function clearRecords() {
  9725. currentRecord = recordWithOldValue = undefined;
  9726. }
  9727. /**
  9728. * Whether the record represents a record from the current
  9729. * mutation event.
  9730. */
  9731. function recordRepresentsCurrentMutation(record) {
  9732. return record === recordWithOldValue || record === currentRecord;
  9733. }
  9734. /**
  9735. * Selects which record, if any, to replace the last record in the queue.
  9736. * This returns |null| if no record should be replaced.
  9737. */
  9738. function selectRecord(lastRecord, newRecord) {
  9739. if (lastRecord === newRecord) return lastRecord;
  9740. // Check if the the record we are adding represents the same record. If
  9741. // so, we keep the one with the oldValue in it.
  9742. if (recordWithOldValue && recordRepresentsCurrentMutation(lastRecord)) return recordWithOldValue;
  9743. return null;
  9744. }
  9745. function removeTransientObserversFor(observer) {
  9746. observer.nodes.forEach(function (node) {
  9747. var registrations = registrationsTable.get(node);
  9748. if (!registrations) return;
  9749. registrations.forEach(function (registration) {
  9750. if (registration.observer === observer) registration.removeTransientObservers();
  9751. });
  9752. });
  9753. }
  9754. /**
  9755. * This function is used for the "For each registered observer observer (with
  9756. * observer's options as options) in target's list of registered observers,
  9757. * run these substeps:" and the "For each ancestor ancestor of target, and for
  9758. * each registered observer observer (with options options) in ancestor's list
  9759. * of registered observers, run these substeps:" part of the algorithms. The
  9760. * |options.subtree| is checked to ensure that the callback is called
  9761. * correctly.
  9762. *
  9763. * @param {Node} target
  9764. * @param {function(MutationObserverInit):MutationRecord} callback
  9765. */
  9766. function forEachAncestorAndObserverEnqueueRecord(target, callback) {
  9767. for (var node = target; node; node = node.parentNode) {
  9768. var registrations = registrationsTable.get(node);
  9769. if (registrations) {
  9770. for (var j = 0; j < registrations.length; j++) {
  9771. var registration = registrations[j];
  9772. var options = registration.options;
  9773. // Only target ignores subtree.
  9774. if (node !== target && !options.subtree) continue;
  9775. var record = callback(options);
  9776. if (record) registration.enqueue(record);
  9777. }
  9778. }
  9779. }
  9780. }
  9781. // This is used to ensure that we never schedule 2 callas to setImmediate
  9782. var isScheduled = false;
  9783. // Keep track of observers that needs to be notified next time.
  9784. var scheduledObservers = [];
  9785. /**
  9786. * Schedules |dispatchCallback| to be called in the future.
  9787. */
  9788. function scheduleCallback(observer) {
  9789. scheduledObservers.push(observer);
  9790. if (!isScheduled) {
  9791. isScheduled = true;
  9792. // setImmediate(dispatchCallbacks);
  9793. if (typeof runtime.globalThis !== 'undefined') {
  9794. runtime.globalThis.setTimeout(dispatchCallbacks);
  9795. } else {
  9796. dispatchCallbacks();
  9797. }
  9798. }
  9799. }
  9800. function dispatchCallbacks() {
  9801. // http://dom.spec.whatwg.org/#mutation-observers
  9802. isScheduled = false; // Used to allow a new setImmediate call above.
  9803. var observers = scheduledObservers;
  9804. scheduledObservers = [];
  9805. // Sort observers based on their creation UID (incremental).
  9806. observers.sort(function (o1, o2) {
  9807. return o1.uid - o2.uid;
  9808. });
  9809. var anyNonEmpty = false;
  9810. observers.forEach(function (observer) {
  9811. // 2.1, 2.2
  9812. var queue = observer.takeRecords();
  9813. // 2.3. Remove all transient registered observers whose observer is mo.
  9814. removeTransientObserversFor(observer);
  9815. // 2.4
  9816. if (queue.length) {
  9817. // @ts-ignore
  9818. observer.callback(queue, observer);
  9819. anyNonEmpty = true;
  9820. }
  9821. });
  9822. // 3.
  9823. if (anyNonEmpty) dispatchCallbacks();
  9824. }
  9825. function _defineProperties$1(target, props) {
  9826. for (var i = 0; i < props.length; i++) {
  9827. var descriptor = props[i];
  9828. descriptor.enumerable = descriptor.enumerable || false;
  9829. descriptor.configurable = true;
  9830. if ("value" in descriptor) descriptor.writable = true;
  9831. Object.defineProperty(target, _toPropertyKey$1(descriptor.key), descriptor);
  9832. }
  9833. }
  9834. function _createClass$1(Constructor, protoProps, staticProps) {
  9835. if (protoProps) _defineProperties$1(Constructor.prototype, protoProps);
  9836. if (staticProps) _defineProperties$1(Constructor, staticProps);
  9837. Object.defineProperty(Constructor, "prototype", {
  9838. writable: false
  9839. });
  9840. return Constructor;
  9841. }
  9842. function _inheritsLoose$2(subClass, superClass) {
  9843. subClass.prototype = Object.create(superClass.prototype);
  9844. subClass.prototype.constructor = subClass;
  9845. _setPrototypeOf$2(subClass, superClass);
  9846. }
  9847. function _setPrototypeOf$2(o, p) {
  9848. _setPrototypeOf$2 = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
  9849. o.__proto__ = p;
  9850. return o;
  9851. };
  9852. return _setPrototypeOf$2(o, p);
  9853. }
  9854. function _toPrimitive$1(input, hint) {
  9855. if (typeof input !== "object" || input === null) return input;
  9856. var prim = input[Symbol.toPrimitive];
  9857. if (prim !== undefined) {
  9858. var res = prim.call(input, hint || "default");
  9859. if (typeof res !== "object") return res;
  9860. throw new TypeError("@@toPrimitive must return a primitive value.");
  9861. }
  9862. return (hint === "string" ? String : Number)(input);
  9863. }
  9864. function _toPropertyKey$1(arg) {
  9865. var key = _toPrimitive$1(arg, "string");
  9866. return typeof key === "symbol" ? key : String(key);
  9867. }
  9868. /**
  9869. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationPlaybackEvent
  9870. */
  9871. var AnimationEvent = /*#__PURE__*/function (_FederatedEvent) {
  9872. _inheritsLoose$2(AnimationEvent, _FederatedEvent);
  9873. function AnimationEvent(manager, target, currentTime, timelineTime) {
  9874. var _this;
  9875. _this = _FederatedEvent.call(this, manager) || this;
  9876. _this.currentTime = void 0;
  9877. _this.timelineTime = void 0;
  9878. _this.currentTime = currentTime;
  9879. _this.timelineTime = timelineTime;
  9880. // @ts-ignore
  9881. _this.target = target;
  9882. _this.type = 'finish';
  9883. _this.bubbles = false;
  9884. // @ts-ignore
  9885. _this.currentTarget = target;
  9886. _this.defaultPrevented = false;
  9887. _this.eventPhase = _this.AT_TARGET;
  9888. _this.timeStamp = Date.now();
  9889. _this.currentTime = currentTime;
  9890. _this.timelineTime = timelineTime;
  9891. return _this;
  9892. }
  9893. return AnimationEvent;
  9894. }(FederatedEvent);
  9895. var sequenceNumber = 0;
  9896. /**
  9897. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/Animation
  9898. */
  9899. var Animation = /*#__PURE__*/function () {
  9900. function Animation(effect, timeline) {
  9901. var _this$effect;
  9902. /**
  9903. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/effect
  9904. */
  9905. this.effect = void 0;
  9906. /**
  9907. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/timeline
  9908. */
  9909. this.timeline = void 0;
  9910. /**
  9911. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/id
  9912. */
  9913. this.id = void 0;
  9914. this.currentTimePending = false;
  9915. /**
  9916. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/playState
  9917. */
  9918. // playState: AnimationPlayState;
  9919. this._idle = true;
  9920. this._paused = false;
  9921. this._finishedFlag = true;
  9922. /**
  9923. * record previos state
  9924. */
  9925. this.oldPlayState = void 0;
  9926. this._holdTime = void 0;
  9927. this.readyPromise = void 0;
  9928. this.finishedPromise = void 0;
  9929. // eslint-disable-next-line @typescript-eslint/ban-types
  9930. this.resolveReadyPromise = void 0;
  9931. // eslint-disable-next-line @typescript-eslint/ban-types
  9932. this.rejectReadyPromise = void 0;
  9933. // eslint-disable-next-line @typescript-eslint/ban-types
  9934. this.resolveFinishedPromise = void 0;
  9935. // eslint-disable-next-line @typescript-eslint/ban-types
  9936. this.rejectFinishedPromise = void 0;
  9937. /**
  9938. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/onfinish
  9939. */
  9940. this.onfinish = void 0;
  9941. /**
  9942. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/oncancel
  9943. */
  9944. this.oncancel = void 0;
  9945. /**
  9946. * get called after each frame when running
  9947. */
  9948. this.onframe = void 0;
  9949. /**
  9950. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/currentTime
  9951. */
  9952. this._currentTime = 0;
  9953. /**
  9954. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/startTime
  9955. */
  9956. this._startTime = void 0;
  9957. this._playbackRate = 1;
  9958. this._totalDuration = void 0;
  9959. this._inEffect = void 0;
  9960. this._inTimeline = true;
  9961. this.onremove = void 0;
  9962. this.effect = effect;
  9963. effect.animation = this;
  9964. this.timeline = timeline;
  9965. this.id = "" + sequenceNumber++;
  9966. this._inEffect = !!this.effect.update(0);
  9967. this._totalDuration = Number((_this$effect = this.effect) === null || _this$effect === void 0 ? void 0 : _this$effect.getComputedTiming().endTime);
  9968. this._holdTime = 0;
  9969. this._paused = false;
  9970. this.oldPlayState = 'idle';
  9971. this.updatePromises();
  9972. }
  9973. /**
  9974. * state machine,
  9975. * resolve/reject ready/finished Promise according to current state
  9976. */
  9977. var _proto = Animation.prototype;
  9978. _proto.updatePromises = function updatePromises() {
  9979. var oldPlayState = this.oldPlayState;
  9980. var newPlayState = this.pending ? 'pending' : this.playState;
  9981. if (this.readyPromise && newPlayState !== oldPlayState) {
  9982. if (newPlayState === 'idle') {
  9983. this.rejectReadyPromise();
  9984. this.readyPromise = undefined;
  9985. } else if (oldPlayState === 'pending') {
  9986. this.resolveReadyPromise();
  9987. } else if (newPlayState === 'pending') {
  9988. this.readyPromise = undefined;
  9989. }
  9990. }
  9991. if (this.finishedPromise && newPlayState !== oldPlayState) {
  9992. if (newPlayState === 'idle') {
  9993. this.rejectFinishedPromise();
  9994. this.finishedPromise = undefined;
  9995. } else if (newPlayState === 'finished') {
  9996. this.resolveFinishedPromise();
  9997. } else if (oldPlayState === 'finished') {
  9998. this.finishedPromise = undefined;
  9999. }
  10000. }
  10001. this.oldPlayState = newPlayState;
  10002. return this.readyPromise || this.finishedPromise;
  10003. };
  10004. _proto.play = function play() {
  10005. this.updatePromises();
  10006. this._paused = false;
  10007. if (this._isFinished || this._idle) {
  10008. this.rewind();
  10009. this._startTime = null;
  10010. }
  10011. this._finishedFlag = false;
  10012. this._idle = false;
  10013. this.ensureAlive();
  10014. this.timeline.applyDirtiedAnimation(this);
  10015. if (this.timeline.animations.indexOf(this) === -1) {
  10016. this.timeline.animations.push(this);
  10017. }
  10018. this.updatePromises();
  10019. };
  10020. _proto.pause = function pause() {
  10021. this.updatePromises();
  10022. if (this.currentTime) {
  10023. this._holdTime = this.currentTime;
  10024. }
  10025. if (!this._isFinished && !this._paused && !this._idle) {
  10026. this.currentTimePending = true;
  10027. } else if (this._idle) {
  10028. this.rewind();
  10029. this._idle = false;
  10030. }
  10031. this._startTime = null;
  10032. this._paused = true;
  10033. this.updatePromises();
  10034. };
  10035. _proto.finish = function finish() {
  10036. this.updatePromises();
  10037. if (this._idle) return;
  10038. this.currentTime = this._playbackRate > 0 ? this._totalDuration : 0;
  10039. this._startTime = this._totalDuration - this.currentTime;
  10040. this.currentTimePending = false;
  10041. this.timeline.applyDirtiedAnimation(this);
  10042. this.updatePromises();
  10043. };
  10044. _proto.cancel = function cancel() {
  10045. var _this = this;
  10046. this.updatePromises();
  10047. if (!this._inEffect) return;
  10048. this._inEffect = false;
  10049. this._idle = true;
  10050. this._paused = false;
  10051. this._finishedFlag = true;
  10052. this._currentTime = 0;
  10053. this._startTime = null;
  10054. this.effect.update(null);
  10055. // effects are invalid after cancellation as the animation state
  10056. // needs to un-apply.
  10057. this.timeline.applyDirtiedAnimation(this);
  10058. this.updatePromises();
  10059. /**
  10060. * 1. Reject the current finished promise with a DOMException named "AbortError".
  10061. * 2. Let current finished promise be a new promise
  10062. * @see https://w3c.github.io/csswg-drafts/web-animations-1/#canceling-an-animation-section
  10063. */
  10064. // if (this.finishedPromise) {
  10065. // this.rejectFinishedPromise();
  10066. // this.finishedPromise = undefined;
  10067. // }
  10068. if (this.oncancel) {
  10069. var event = new AnimationEvent(null, this, this.currentTime, null);
  10070. setTimeout(function () {
  10071. _this.oncancel(event);
  10072. });
  10073. }
  10074. };
  10075. _proto.reverse = function reverse() {
  10076. this.updatePromises();
  10077. var oldCurrentTime = this.currentTime;
  10078. this.playbackRate *= -1;
  10079. this.play();
  10080. if (oldCurrentTime !== null) {
  10081. this.currentTime = oldCurrentTime;
  10082. }
  10083. this.updatePromises();
  10084. }
  10085. /**
  10086. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/updatePlaybackRate
  10087. */;
  10088. _proto.updatePlaybackRate = function updatePlaybackRate(playbackRate) {
  10089. this.playbackRate = playbackRate;
  10090. };
  10091. _proto.targetAnimations = function targetAnimations() {
  10092. var _this$effect2;
  10093. var target = (_this$effect2 = this.effect) === null || _this$effect2 === void 0 ? void 0 : _this$effect2.target;
  10094. return target.getAnimations();
  10095. };
  10096. _proto.markTarget = function markTarget() {
  10097. var animations = this.targetAnimations();
  10098. if (animations.indexOf(this) === -1) {
  10099. animations.push(this);
  10100. }
  10101. };
  10102. _proto.unmarkTarget = function unmarkTarget() {
  10103. var animations = this.targetAnimations();
  10104. var index = animations.indexOf(this);
  10105. if (index !== -1) {
  10106. animations.splice(index, 1);
  10107. }
  10108. };
  10109. _proto.tick = function tick(timelineTime, isAnimationFrame) {
  10110. if (!this._idle && !this._paused) {
  10111. if (this._startTime === null) {
  10112. if (isAnimationFrame) {
  10113. this.startTime = timelineTime - this._currentTime / this.playbackRate;
  10114. }
  10115. } else if (!this._isFinished) {
  10116. this.tickCurrentTime((timelineTime - this._startTime) * this.playbackRate);
  10117. }
  10118. }
  10119. if (isAnimationFrame) {
  10120. this.currentTimePending = false;
  10121. this.fireEvents(timelineTime);
  10122. }
  10123. };
  10124. _proto.rewind = function rewind() {
  10125. if (this.playbackRate >= 0) {
  10126. this.currentTime = 0;
  10127. } else if (this._totalDuration < Infinity) {
  10128. this.currentTime = this._totalDuration;
  10129. } else {
  10130. throw new Error('Unable to rewind negative playback rate animation with infinite duration');
  10131. }
  10132. };
  10133. _proto.persist = function persist() {
  10134. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  10135. };
  10136. _proto.addEventListener = function addEventListener(type, listener, options) {
  10137. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  10138. };
  10139. _proto.removeEventListener = function removeEventListener(type, listener, options) {
  10140. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  10141. };
  10142. _proto.dispatchEvent = function dispatchEvent(event) {
  10143. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  10144. };
  10145. // replaceState: AnimationReplaceState;
  10146. _proto.commitStyles = function commitStyles() {
  10147. throw new Error(ERROR_MSG_METHOD_NOT_IMPLEMENTED);
  10148. };
  10149. _proto.ensureAlive = function ensureAlive() {
  10150. // If an animation is playing backwards and is not fill backwards/both
  10151. // then it should go out of effect when it reaches the start of its
  10152. // active interval (currentTime === 0).
  10153. if (this.playbackRate < 0 && this.currentTime === 0) {
  10154. var _this$effect3;
  10155. this._inEffect = !!((_this$effect3 = this.effect) === null || _this$effect3 === void 0 ? void 0 : _this$effect3.update(-1));
  10156. } else {
  10157. var _this$effect4;
  10158. this._inEffect = !!((_this$effect4 = this.effect) === null || _this$effect4 === void 0 ? void 0 : _this$effect4.update(this.currentTime));
  10159. }
  10160. if (!this._inTimeline && (this._inEffect || !this._finishedFlag)) {
  10161. this._inTimeline = true;
  10162. this.timeline.animations.push(this);
  10163. }
  10164. };
  10165. _proto.tickCurrentTime = function tickCurrentTime(newTime, ignoreLimit) {
  10166. if (newTime !== this._currentTime) {
  10167. this._currentTime = newTime;
  10168. if (this._isFinished && !ignoreLimit) {
  10169. this._currentTime = this._playbackRate > 0 ? this._totalDuration : 0;
  10170. }
  10171. this.ensureAlive();
  10172. }
  10173. };
  10174. _proto.fireEvents = function fireEvents(baseTime) {
  10175. var _this2 = this;
  10176. if (this._isFinished) {
  10177. if (!this._finishedFlag) {
  10178. if (this.onfinish) {
  10179. var event = new AnimationEvent(null, this, this.currentTime, baseTime);
  10180. setTimeout(function () {
  10181. if (_this2.onfinish) {
  10182. _this2.onfinish(event);
  10183. }
  10184. });
  10185. }
  10186. this._finishedFlag = true;
  10187. }
  10188. } else {
  10189. if (this.onframe && this.playState === 'running') {
  10190. var _event = new AnimationEvent(null, this, this.currentTime, baseTime);
  10191. this.onframe(_event);
  10192. }
  10193. this._finishedFlag = false;
  10194. }
  10195. };
  10196. _createClass$1(Animation, [{
  10197. key: "pending",
  10198. get:
  10199. // animation: InternalAnimation | null;
  10200. /**
  10201. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/pending
  10202. */
  10203. function get() {
  10204. return this._startTime === null && !this._paused && this.playbackRate !== 0 || this.currentTimePending;
  10205. }
  10206. }, {
  10207. key: "playState",
  10208. get: function get() {
  10209. if (this._idle) return 'idle';
  10210. if (this._isFinished) return 'finished';
  10211. if (this._paused) return 'paused';
  10212. return 'running';
  10213. }
  10214. }, {
  10215. key: "ready",
  10216. get:
  10217. /**
  10218. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/ready
  10219. * @example
  10220. animation.pause();
  10221. animation.ready.then(function() {
  10222. // Displays 'running'
  10223. alert(animation.playState);
  10224. });
  10225. animation.play();
  10226. */
  10227. function get() {
  10228. var _this3 = this;
  10229. if (!this.readyPromise) {
  10230. if (this.timeline.animationsWithPromises.indexOf(this) === -1) {
  10231. this.timeline.animationsWithPromises.push(this);
  10232. }
  10233. this.readyPromise = new Promise(function (resolve, reject) {
  10234. _this3.resolveReadyPromise = function () {
  10235. resolve(_this3);
  10236. };
  10237. _this3.rejectReadyPromise = function () {
  10238. reject(new Error());
  10239. };
  10240. });
  10241. if (!this.pending) {
  10242. this.resolveReadyPromise();
  10243. }
  10244. }
  10245. return this.readyPromise;
  10246. }
  10247. /**
  10248. * @see https://developer.mozilla.org/en-US/docs/Web/API/Animation/finished
  10249. * @example
  10250. Promise.all(
  10251. elem.getAnimations().map(
  10252. function(animation) {
  10253. return animation.finished
  10254. }
  10255. )
  10256. ).then(
  10257. function() {
  10258. return elem.remove();
  10259. }
  10260. );
  10261. */
  10262. }, {
  10263. key: "finished",
  10264. get: function get() {
  10265. var _this4 = this;
  10266. if (!this.finishedPromise) {
  10267. if (this.timeline.animationsWithPromises.indexOf(this) === -1) {
  10268. this.timeline.animationsWithPromises.push(this);
  10269. }
  10270. this.finishedPromise = new Promise(function (resolve, reject) {
  10271. _this4.resolveFinishedPromise = function () {
  10272. resolve(_this4);
  10273. };
  10274. _this4.rejectFinishedPromise = function () {
  10275. reject(new Error());
  10276. };
  10277. });
  10278. if (this.playState === 'finished') {
  10279. this.resolveFinishedPromise();
  10280. }
  10281. }
  10282. return this.finishedPromise;
  10283. }
  10284. }, {
  10285. key: "currentTime",
  10286. get: function get() {
  10287. this.updatePromises();
  10288. return this._idle || this.currentTimePending ? null : this._currentTime;
  10289. },
  10290. set: function set(newTime) {
  10291. newTime = Number(newTime);
  10292. if (isNaN(newTime)) return;
  10293. this.timeline.restart();
  10294. if (!this._paused && this._startTime !== null) {
  10295. var _this$timeline;
  10296. this._startTime = Number((_this$timeline = this.timeline) === null || _this$timeline === void 0 ? void 0 : _this$timeline.currentTime) - newTime / this.playbackRate;
  10297. }
  10298. this.currentTimePending = false;
  10299. if (this._currentTime === newTime) {
  10300. return;
  10301. }
  10302. if (this._idle) {
  10303. this._idle = false;
  10304. this._paused = true;
  10305. }
  10306. this.tickCurrentTime(newTime, true);
  10307. this.timeline.applyDirtiedAnimation(this);
  10308. }
  10309. }, {
  10310. key: "startTime",
  10311. get: function get() {
  10312. return this._startTime;
  10313. },
  10314. set: function set(newTime) {
  10315. if (newTime !== null) {
  10316. this.updatePromises();
  10317. newTime = Number(newTime);
  10318. if (isNaN(newTime)) return;
  10319. if (this._paused || this._idle) return;
  10320. this._startTime = newTime;
  10321. this.tickCurrentTime((Number(this.timeline.currentTime) - this._startTime) * this.playbackRate);
  10322. this.timeline.applyDirtiedAnimation(this);
  10323. this.updatePromises();
  10324. }
  10325. }
  10326. }, {
  10327. key: "playbackRate",
  10328. get: function get() {
  10329. return this._playbackRate;
  10330. },
  10331. set: function set(value) {
  10332. if (value === this._playbackRate) {
  10333. return;
  10334. }
  10335. this.updatePromises();
  10336. var oldCurrentTime = this.currentTime;
  10337. this._playbackRate = value;
  10338. this.startTime = null;
  10339. if (this.playState !== 'paused' && this.playState !== 'idle') {
  10340. this._finishedFlag = false;
  10341. this._idle = false;
  10342. this.ensureAlive();
  10343. this.timeline.applyDirtiedAnimation(this);
  10344. }
  10345. if (oldCurrentTime !== null) {
  10346. this.currentTime = oldCurrentTime;
  10347. }
  10348. this.updatePromises();
  10349. }
  10350. }, {
  10351. key: "_isFinished",
  10352. get: function get() {
  10353. return !this._idle && (this._playbackRate > 0 && Number(this._currentTime) >= this._totalDuration || this._playbackRate < 0 && Number(this._currentTime) <= 0);
  10354. }
  10355. }, {
  10356. key: "totalDuration",
  10357. get: function get() {
  10358. return this._totalDuration;
  10359. }
  10360. }, {
  10361. key: "_needsTick",
  10362. get: function get() {
  10363. return this.pending || this.playState === 'running' || !this._finishedFlag;
  10364. }
  10365. }]);
  10366. return Animation;
  10367. }();
  10368. /**
  10369. * https://github.com/gre/bezier-easing
  10370. * BezierEasing - use bezier curve for transition easing function
  10371. * by Gaëtan Renaudeau 2014 - 2015 – MIT License
  10372. */
  10373. // These values are established by empiricism with tests (tradeoff: performance VS precision)
  10374. var NEWTON_ITERATIONS = 4;
  10375. var NEWTON_MIN_SLOPE = 0.001;
  10376. var SUBDIVISION_PRECISION = 0.0000001;
  10377. var SUBDIVISION_MAX_ITERATIONS = 10;
  10378. var kSplineTableSize = 11;
  10379. var kSampleStepSize = 1.0 / (kSplineTableSize - 1.0);
  10380. var float32ArraySupported = typeof Float32Array === 'function';
  10381. var A = function A(aA1, aA2) {
  10382. return 1.0 - 3.0 * aA2 + 3.0 * aA1;
  10383. };
  10384. var B = function B(aA1, aA2) {
  10385. return 3.0 * aA2 - 6.0 * aA1;
  10386. };
  10387. var C = function C(aA1) {
  10388. return 3.0 * aA1;
  10389. };
  10390. // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2.
  10391. var calcBezier = function calcBezier(aT, aA1, aA2) {
  10392. return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
  10393. };
  10394. // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2.
  10395. var getSlope = function getSlope(aT, aA1, aA2) {
  10396. return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1);
  10397. };
  10398. var binarySubdivide = function binarySubdivide(aX, aA, aB, mX1, mX2) {
  10399. var currentX,
  10400. currentT,
  10401. i = 0;
  10402. do {
  10403. currentT = aA + (aB - aA) / 2.0;
  10404. currentX = calcBezier(currentT, mX1, mX2) - aX;
  10405. if (currentX > 0.0) aB = currentT;else aA = currentT;
  10406. } while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
  10407. return currentT;
  10408. };
  10409. var newtonRaphsonIterate = function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
  10410. for (var i = 0; i < NEWTON_ITERATIONS; ++i) {
  10411. var currentSlope = getSlope(aGuessT, mX1, mX2);
  10412. if (currentSlope === 0.0) return aGuessT;
  10413. var currentX = calcBezier(aGuessT, mX1, mX2) - aX;
  10414. aGuessT -= currentX / currentSlope;
  10415. }
  10416. return aGuessT;
  10417. };
  10418. var bezier = function bezier(mX1, mY1, mX2, mY2) {
  10419. if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) throw new Error('bezier x values must be in [0, 1] range');
  10420. if (mX1 === mY1 && mX2 === mY2) return function (t) {
  10421. return t;
  10422. };
  10423. // Precompute samples table
  10424. var sampleValues = float32ArraySupported ? new Float32Array(kSplineTableSize) : new Array(kSplineTableSize);
  10425. for (var i = 0; i < kSplineTableSize; ++i) {
  10426. sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
  10427. }
  10428. var getTForX = function getTForX(aX) {
  10429. var intervalStart = 0.0;
  10430. var currentSample = 1;
  10431. var lastSample = kSplineTableSize - 1;
  10432. for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; ++currentSample) intervalStart += kSampleStepSize;
  10433. --currentSample;
  10434. // Interpolate to provide an initial guess for t
  10435. var dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
  10436. var guessForT = intervalStart + dist * kSampleStepSize;
  10437. var initialSlope = getSlope(guessForT, mX1, mX2);
  10438. if (initialSlope >= NEWTON_MIN_SLOPE) return newtonRaphsonIterate(aX, guessForT, mX1, mX2);else if (initialSlope === 0.0) return guessForT;else {
  10439. return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
  10440. }
  10441. };
  10442. return function (t) {
  10443. // Because JavaScript number are imprecise, we should guarantee the extremes are right.
  10444. if (t === 0 || t === 1) return t;
  10445. return calcBezier(getTForX(t), mY1, mY2);
  10446. };
  10447. };
  10448. var convertToDash = function convertToDash(str) {
  10449. str = str.replace(/([A-Z])/g, function (letter) {
  10450. return "-" + letter.toLowerCase();
  10451. });
  10452. // Remove first dash
  10453. return str.charAt(0) === '-' ? str.substring(1) : str;
  10454. };
  10455. /**
  10456. Easing Functions from anime.js, they are tried and true, so, its better to use them instead of other alternatives
  10457. */
  10458. var Quad = function Quad(t) {
  10459. return Math.pow(t, 2);
  10460. };
  10461. var Cubic = function Cubic(t) {
  10462. return Math.pow(t, 3);
  10463. };
  10464. var Quart = function Quart(t) {
  10465. return Math.pow(t, 4);
  10466. };
  10467. var Quint = function Quint(t) {
  10468. return Math.pow(t, 5);
  10469. };
  10470. var Expo = function Expo(t) {
  10471. return Math.pow(t, 6);
  10472. };
  10473. var Sine = function Sine(t) {
  10474. return 1 - Math.cos(t * Math.PI / 2);
  10475. };
  10476. var Circ = function Circ(t) {
  10477. return 1 - Math.sqrt(1 - t * t);
  10478. };
  10479. var Back = function Back(t) {
  10480. return t * t * (3 * t - 2);
  10481. };
  10482. var Bounce = function Bounce(t) {
  10483. var pow2,
  10484. b = 4;
  10485. while (t < ((pow2 = Math.pow(2, --b)) - 1) / 11) {}
  10486. return 1 / Math.pow(4, 3 - b) - 7.5625 * Math.pow((pow2 * 3 - 2) / 22 - t, 2);
  10487. };
  10488. var Elastic = function Elastic(t, params) {
  10489. if (params === void 0) {
  10490. params = [];
  10491. }
  10492. var _params = params,
  10493. _params$ = _params[0],
  10494. amplitude = _params$ === void 0 ? 1 : _params$,
  10495. _params$2 = _params[1],
  10496. period = _params$2 === void 0 ? 0.5 : _params$2;
  10497. var a = clamp(Number(amplitude), 1, 10);
  10498. var p = clamp(Number(period), 0.1, 2);
  10499. if (t === 0 || t === 1) return t;
  10500. return -a * Math.pow(2, 10 * (t - 1)) * Math.sin((t - 1 - p / (Math.PI * 2) * Math.asin(1 / a)) * (Math.PI * 2) / p);
  10501. };
  10502. var Spring = function Spring(t, params, duration) {
  10503. if (params === void 0) {
  10504. params = [];
  10505. }
  10506. var _params2 = params,
  10507. _params2$ = _params2[0],
  10508. mass = _params2$ === void 0 ? 1 : _params2$,
  10509. _params2$2 = _params2[1],
  10510. stiffness = _params2$2 === void 0 ? 100 : _params2$2,
  10511. _params2$3 = _params2[2],
  10512. damping = _params2$3 === void 0 ? 10 : _params2$3,
  10513. _params2$4 = _params2[3],
  10514. velocity = _params2$4 === void 0 ? 0 : _params2$4;
  10515. mass = clamp(mass, 0.1, 1000);
  10516. stiffness = clamp(stiffness, 0.1, 1000);
  10517. damping = clamp(damping, 0.1, 1000);
  10518. velocity = clamp(velocity, 0.1, 1000);
  10519. var w0 = Math.sqrt(stiffness / mass);
  10520. var zeta = damping / (2 * Math.sqrt(stiffness * mass));
  10521. var wd = zeta < 1 ? w0 * Math.sqrt(1 - zeta * zeta) : 0;
  10522. var a = 1;
  10523. var b = zeta < 1 ? (zeta * w0 + -velocity) / wd : -velocity + w0;
  10524. var progress = duration ? duration * t / 1000 : t;
  10525. if (zeta < 1) {
  10526. progress = Math.exp(-progress * zeta * w0) * (a * Math.cos(wd * progress) + b * Math.sin(wd * progress));
  10527. } else {
  10528. progress = (a + b * progress) * Math.exp(-progress * w0);
  10529. }
  10530. if (t === 0 || t === 1) return t;
  10531. return 1 - progress;
  10532. };
  10533. /**
  10534. * Cache the durations at set easing parameters
  10535. */
  10536. // export const EasingDurationCache: Map<string | TypeEasingFunction, number> = new Map();
  10537. /**
  10538. * The threshold for an infinite loop
  10539. */
  10540. // const INTINITE_LOOP_LIMIT = 10000;
  10541. /** Convert easing parameters to Array of numbers, e.g. "spring(2, 500)" to [2, 500] */
  10542. // export const parseEasingParameters = (str: string) => {
  10543. // const match = /(\(|\s)([^)]+)\)?/.exec(str);
  10544. // return match
  10545. // ? match[2].split(',').map((value) => {
  10546. // const num = parseFloat(value);
  10547. // return !Number.isNaN(num) ? num : value.trim();
  10548. // })
  10549. // : [];
  10550. // };
  10551. /**
  10552. * The spring easing function will only look smooth at certain durations, with certain parameters.
  10553. * This functions returns the optimal duration to create a smooth springy animation based on physics
  10554. *
  10555. * Note: it can also be used to determine the optimal duration of other types of easing function, but be careful of 'in-'
  10556. * easing functions, because of the nature of the function it can sometimes create an infinite loop, I suggest only using
  10557. * `getEasingDuration` for `spring`, specifically 'out-spring' and 'spring'
  10558. */
  10559. // export const getEasingDuration = (easing: string | TypeEasingFunction = 'spring') => {
  10560. // if (EasingDurationCache.has(easing)) return EasingDurationCache.get(easing);
  10561. // // eslint-disable-next-line @typescript-eslint/no-use-before-define
  10562. // const easingFunction = typeof easing == 'function' ? easing : getEasingFunction(easing as string);
  10563. // const params = typeof easing == 'function' ? [] : parseEasingParameters(easing);
  10564. // const frame = 1 / 6;
  10565. // let elapsed = 0;
  10566. // let rest = 0;
  10567. // let count = 0;
  10568. // while (++count < INTINITE_LOOP_LIMIT) {
  10569. // elapsed += frame;
  10570. // if (easingFunction(elapsed, params, undefined) === 1) {
  10571. // rest++;
  10572. // if (rest >= 16) break;
  10573. // } else {
  10574. // rest = 0;
  10575. // }
  10576. // }
  10577. // const duration = elapsed * frame * 1000;
  10578. // EasingDurationCache.set(easing, duration);
  10579. // return duration;
  10580. // };
  10581. /**
  10582. These Easing Functions are based off of the Sozi Project's easing functions
  10583. https://github.com/sozi-projects/Sozi/blob/d72e44ebd580dc7579d1e177406ad41e632f961d/src/js/player/Timing.js
  10584. */
  10585. var Steps = function Steps(t, params) {
  10586. if (params === void 0) {
  10587. params = [];
  10588. }
  10589. var _params3 = params,
  10590. _params3$ = _params3[0],
  10591. steps = _params3$ === void 0 ? 10 : _params3$,
  10592. type = _params3[1];
  10593. var trunc = type == 'start' ? Math.ceil : Math.floor;
  10594. return trunc(clamp(t, 0, 1) * steps) / steps;
  10595. };
  10596. // @ts-ignore
  10597. var Bezier = function Bezier(t, params) {
  10598. if (params === void 0) {
  10599. params = [];
  10600. }
  10601. var _params4 = params,
  10602. mX1 = _params4[0],
  10603. mY1 = _params4[1],
  10604. mX2 = _params4[2],
  10605. mY2 = _params4[3];
  10606. return bezier(mX1, mY1, mX2, mY2)(t);
  10607. };
  10608. /** The default `ease-in` easing function */
  10609. var easein = bezier(0.42, 0.0, 1.0, 1.0);
  10610. /** Converts easing functions to their `out`counter parts */
  10611. var EaseOut = function EaseOut(ease) {
  10612. return function (t, params, duration) {
  10613. if (params === void 0) {
  10614. params = [];
  10615. }
  10616. return 1 - ease(1 - t, params, duration);
  10617. };
  10618. };
  10619. /** Converts easing functions to their `in-out` counter parts */
  10620. var EaseInOut = function EaseInOut(ease) {
  10621. return function (t, params, duration) {
  10622. if (params === void 0) {
  10623. params = [];
  10624. }
  10625. return t < 0.5 ? ease(t * 2, params, duration) / 2 : 1 - ease(t * -2 + 2, params, duration) / 2;
  10626. };
  10627. };
  10628. /** Converts easing functions to their `out-in` counter parts */
  10629. var EaseOutIn = function EaseOutIn(ease) {
  10630. return function (t, params, duration) {
  10631. if (params === void 0) {
  10632. params = [];
  10633. }
  10634. return t < 0.5 ? (1 - ease(1 - t * 2, params, duration)) / 2 : (ease(t * 2 - 1, params, duration) + 1) / 2;
  10635. };
  10636. };
  10637. var EasingFunctions = {
  10638. steps: Steps,
  10639. 'step-start': function stepStart(t) {
  10640. return Steps(t, [1, 'start']);
  10641. },
  10642. 'step-end': function stepEnd(t) {
  10643. return Steps(t, [1, 'end']);
  10644. },
  10645. linear: function linear(t) {
  10646. return t;
  10647. },
  10648. 'cubic-bezier': Bezier,
  10649. ease: function ease(t) {
  10650. return Bezier(t, [0.25, 0.1, 0.25, 1.0]);
  10651. },
  10652. in: easein,
  10653. out: EaseOut(easein),
  10654. 'in-out': EaseInOut(easein),
  10655. 'out-in': EaseOutIn(easein),
  10656. 'in-quad': Quad,
  10657. 'out-quad': EaseOut(Quad),
  10658. 'in-out-quad': EaseInOut(Quad),
  10659. 'out-in-quad': EaseOutIn(Quad),
  10660. 'in-cubic': Cubic,
  10661. 'out-cubic': EaseOut(Cubic),
  10662. 'in-out-cubic': EaseInOut(Cubic),
  10663. 'out-in-cubic': EaseOutIn(Cubic),
  10664. 'in-quart': Quart,
  10665. 'out-quart': EaseOut(Quart),
  10666. 'in-out-quart': EaseInOut(Quart),
  10667. 'out-in-quart': EaseOutIn(Quart),
  10668. 'in-quint': Quint,
  10669. 'out-quint': EaseOut(Quint),
  10670. 'in-out-quint': EaseInOut(Quint),
  10671. 'out-in-quint': EaseOutIn(Quint),
  10672. 'in-expo': Expo,
  10673. 'out-expo': EaseOut(Expo),
  10674. 'in-out-expo': EaseInOut(Expo),
  10675. 'out-in-expo': EaseOutIn(Expo),
  10676. 'in-sine': Sine,
  10677. 'out-sine': EaseOut(Sine),
  10678. 'in-out-sine': EaseInOut(Sine),
  10679. 'out-in-sine': EaseOutIn(Sine),
  10680. 'in-circ': Circ,
  10681. 'out-circ': EaseOut(Circ),
  10682. 'in-out-circ': EaseInOut(Circ),
  10683. 'out-in-circ': EaseOutIn(Circ),
  10684. 'in-back': Back,
  10685. 'out-back': EaseOut(Back),
  10686. 'in-out-back': EaseInOut(Back),
  10687. 'out-in-back': EaseOutIn(Back),
  10688. 'in-bounce': Bounce,
  10689. 'out-bounce': EaseOut(Bounce),
  10690. 'in-out-bounce': EaseInOut(Bounce),
  10691. 'out-in-bounce': EaseOutIn(Bounce),
  10692. 'in-elastic': Elastic,
  10693. 'out-elastic': EaseOut(Elastic),
  10694. 'in-out-elastic': EaseInOut(Elastic),
  10695. 'out-in-elastic': EaseOutIn(Elastic),
  10696. spring: Spring,
  10697. 'spring-in': Spring,
  10698. 'spring-out': EaseOut(Spring),
  10699. 'spring-in-out': EaseInOut(Spring),
  10700. 'spring-out-in': EaseOutIn(Spring)
  10701. };
  10702. /**
  10703. * Convert string easing to their proper form
  10704. */
  10705. var complexEasingSyntax = function complexEasingSyntax(ease) {
  10706. return convertToDash(ease).replace(/^ease-/, '') // Remove the "ease-" keyword
  10707. .replace(/(\(|\s).+/, '') // Remove the function brackets and parameters
  10708. .toLowerCase().trim();
  10709. };
  10710. /** Re-maps a number from one range to another. Numbers outside the range are not clamped to 0 and 1, because out-of-range values are often intentional and useful. */
  10711. var getEasingFunction = function getEasingFunction(ease) {
  10712. return EasingFunctions[complexEasingSyntax(ease)] || EasingFunctions.linear;
  10713. };
  10714. // /**
  10715. // * Allows you to register new easing functions
  10716. // */
  10717. // export const registerEasingFunction = (key: string, fn: TypeEasingFunction) => {
  10718. // Object.assign(EasingFunctions, {
  10719. // [key]: fn,
  10720. // });
  10721. // };
  10722. // /**
  10723. // * Allows you to register multiple new easing functions
  10724. // */
  10725. // export const registerEasingFunctions = (...obj: typeof EasingFunctions[]) => {
  10726. // Object.assign(EasingFunctions, ...obj);
  10727. // };
  10728. var linear = function linear(x) {
  10729. return x;
  10730. };
  10731. var Start = 1;
  10732. var Middle = 0.5;
  10733. var End = 0;
  10734. function step(count, pos) {
  10735. return function (x) {
  10736. if (x >= 1) {
  10737. return 1;
  10738. }
  10739. var stepSize = 1 / count;
  10740. x += pos * stepSize;
  10741. return x - x % stepSize;
  10742. };
  10743. }
  10744. var numberString = '\\s*(-?\\d+\\.?\\d*|-?\\.\\d+)\\s*';
  10745. var cubicBezierRe = new RegExp('cubic-bezier\\(' + numberString + ',' + numberString + ',' + numberString + ',' + numberString + '\\)');
  10746. var step1Re = /steps\(\s*(\d+)\s*\)/;
  10747. var step2Re = /steps\(\s*(\d+)\s*,\s*(start|middle|end)\s*\)/;
  10748. function parseEasingFunction(normalizedEasing) {
  10749. var cubicData = cubicBezierRe.exec(normalizedEasing);
  10750. if (cubicData) {
  10751. // @ts-ignore
  10752. return bezier.apply(void 0, cubicData.slice(1).map(Number));
  10753. }
  10754. var step1Data = step1Re.exec(normalizedEasing);
  10755. if (step1Data) {
  10756. return step(Number(step1Data[1]), End);
  10757. }
  10758. var step2Data = step2Re.exec(normalizedEasing);
  10759. if (step2Data) {
  10760. // @ts-ignore
  10761. return step(Number(step2Data[1]), {
  10762. start: Start,
  10763. middle: Middle,
  10764. end: End
  10765. }[step2Data[2]]);
  10766. }
  10767. return getEasingFunction(normalizedEasing);
  10768. }
  10769. function calculateActiveDuration(timing) {
  10770. // @ts-ignore
  10771. return Math.abs(repeatedDuration(timing) / (timing.playbackRate || 1));
  10772. }
  10773. function repeatedDuration(timing) {
  10774. var _timing$iterations;
  10775. // https://drafts.csswg.org/web-animations/#calculating-the-active-duration
  10776. if (timing.duration === 0 || timing.iterations === 0) {
  10777. return 0;
  10778. }
  10779. // @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/duration#value
  10780. // if (timing.duration === 'auto') {
  10781. // timing.duration = 0;
  10782. // }
  10783. return (timing.duration === 'auto' ? 0 : Number(timing.duration)) * ((_timing$iterations = timing.iterations) !== null && _timing$iterations !== void 0 ? _timing$iterations : 1);
  10784. }
  10785. var PhaseNone = 0;
  10786. var PhaseBefore = 1;
  10787. var PhaseAfter = 2;
  10788. var PhaseActive = 3;
  10789. function calculatePhase(activeDuration, localTime, timing) {
  10790. // https://drafts.csswg.org/web-animations/#animation-effect-phases-and-states
  10791. if (localTime === null) {
  10792. return PhaseNone;
  10793. }
  10794. var endTime = timing.endTime;
  10795. if (localTime < Math.min(timing.delay, endTime)) {
  10796. return PhaseBefore;
  10797. }
  10798. if (localTime >= Math.min(timing.delay + activeDuration + timing.endDelay, endTime)) {
  10799. return PhaseAfter;
  10800. }
  10801. return PhaseActive;
  10802. }
  10803. function calculateActiveTime(activeDuration, fillMode, localTime, phase, delay) {
  10804. // https://drafts.csswg.org/web-animations/#calculating-the-active-time
  10805. switch (phase) {
  10806. case PhaseBefore:
  10807. if (fillMode === 'backwards' || fillMode === 'both') return 0;
  10808. return null;
  10809. case PhaseActive:
  10810. return localTime - delay;
  10811. case PhaseAfter:
  10812. if (fillMode === 'forwards' || fillMode === 'both') return activeDuration;
  10813. return null;
  10814. case PhaseNone:
  10815. return null;
  10816. }
  10817. }
  10818. function calculateOverallProgress(iterationDuration, phase, iterations, activeTime, iterationStart) {
  10819. // https://drafts.csswg.org/web-animations/#calculating-the-overall-progress
  10820. var overallProgress = iterationStart;
  10821. if (iterationDuration === 0) {
  10822. if (phase !== PhaseBefore) {
  10823. overallProgress += iterations;
  10824. }
  10825. } else {
  10826. overallProgress += activeTime / iterationDuration;
  10827. }
  10828. return overallProgress;
  10829. }
  10830. function calculateSimpleIterationProgress(overallProgress, iterationStart, phase, iterations, activeTime, iterationDuration) {
  10831. // https://drafts.csswg.org/web-animations/#calculating-the-simple-iteration-progress
  10832. var simpleIterationProgress = overallProgress === Infinity ? iterationStart % 1 : overallProgress % 1;
  10833. if (simpleIterationProgress === 0 && phase === PhaseAfter && iterations !== 0 && (activeTime !== 0 || iterationDuration === 0)) {
  10834. simpleIterationProgress = 1;
  10835. }
  10836. return simpleIterationProgress;
  10837. }
  10838. function calculateCurrentIteration(phase, iterations, simpleIterationProgress, overallProgress) {
  10839. // https://drafts.csswg.org/web-animations/#calculating-the-current-iteration
  10840. if (phase === PhaseAfter && iterations === Infinity) {
  10841. return Infinity;
  10842. }
  10843. if (simpleIterationProgress === 1) {
  10844. return Math.floor(overallProgress) - 1;
  10845. }
  10846. return Math.floor(overallProgress);
  10847. }
  10848. function calculateDirectedProgress(playbackDirection, currentIteration, simpleIterationProgress) {
  10849. // https://drafts.csswg.org/web-animations/#calculating-the-directed-progress
  10850. var currentDirection = playbackDirection;
  10851. if (playbackDirection !== 'normal' && playbackDirection !== 'reverse') {
  10852. var d = currentIteration;
  10853. if (playbackDirection === 'alternate-reverse') {
  10854. d += 1;
  10855. }
  10856. currentDirection = 'normal';
  10857. if (d !== Infinity && d % 2 !== 0) {
  10858. currentDirection = 'reverse';
  10859. }
  10860. }
  10861. if (currentDirection === 'normal') {
  10862. return simpleIterationProgress;
  10863. }
  10864. return 1 - simpleIterationProgress;
  10865. }
  10866. function calculateIterationProgress(activeDuration, localTime, timing) {
  10867. var phase = calculatePhase(activeDuration, localTime, timing);
  10868. var activeTime = calculateActiveTime(activeDuration, timing.fill, localTime, phase, timing.delay);
  10869. if (activeTime === null) return null;
  10870. var duration = timing.duration === 'auto' ? 0 : timing.duration;
  10871. var overallProgress = calculateOverallProgress(duration, phase, timing.iterations, activeTime, timing.iterationStart);
  10872. var simpleIterationProgress = calculateSimpleIterationProgress(overallProgress, timing.iterationStart, phase, timing.iterations, activeTime, duration);
  10873. var currentIteration = calculateCurrentIteration(phase, timing.iterations, simpleIterationProgress, overallProgress);
  10874. var directedProgress = calculateDirectedProgress(timing.direction, currentIteration, simpleIterationProgress);
  10875. timing.currentIteration = currentIteration;
  10876. timing.progress = directedProgress;
  10877. // https://drafts.csswg.org/web-animations/#calculating-the-transformed-progress
  10878. // https://drafts.csswg.org/web-animations/#calculating-the-iteration-progress
  10879. return timing.easingFunction(directedProgress);
  10880. }
  10881. function convertEffectInput(keyframes, timing, target) {
  10882. var propertySpecificKeyframeGroups = makePropertySpecificKeyframeGroups(keyframes, timing);
  10883. var interpolations = makeInterpolations(propertySpecificKeyframeGroups, target);
  10884. return function (target, fraction) {
  10885. if (fraction !== null) {
  10886. interpolations.filter(function (interpolation) {
  10887. return fraction >= interpolation.applyFrom && fraction < interpolation.applyTo;
  10888. }).forEach(function (interpolation) {
  10889. var offsetFraction = fraction - interpolation.startOffset;
  10890. var localDuration = interpolation.endOffset - interpolation.startOffset;
  10891. var scaledLocalTime = localDuration === 0 ? 0 : interpolation.easingFunction(offsetFraction / localDuration);
  10892. // apply updated attribute
  10893. target.setAttribute(interpolation.property, interpolation.interpolation(scaledLocalTime));
  10894. // if (interpolation.property === 'visibility') {
  10895. // console.log(
  10896. // scaledLocalTime,
  10897. // interpolation.interpolation(scaledLocalTime),
  10898. // );
  10899. // }
  10900. });
  10901. } else {
  10902. for (var property in propertySpecificKeyframeGroups) if (isNotReservedWord(property)) {
  10903. // clear attribute
  10904. target.setAttribute(property, null);
  10905. }
  10906. }
  10907. };
  10908. }
  10909. function isNotReservedWord(member) {
  10910. return member !== 'offset' && member !== 'easing' && member !== 'composite' && member !== 'computedOffset';
  10911. }
  10912. function makePropertySpecificKeyframeGroups(keyframes, timing) {
  10913. var propertySpecificKeyframeGroups = {};
  10914. for (var i = 0; i < keyframes.length; i++) {
  10915. for (var member in keyframes[i]) {
  10916. if (isNotReservedWord(member)) {
  10917. var propertySpecificKeyframe = {
  10918. offset: keyframes[i].offset,
  10919. computedOffset: keyframes[i].computedOffset,
  10920. easing: keyframes[i].easing,
  10921. easingFunction: parseEasingFunction(keyframes[i].easing) || timing.easingFunction,
  10922. value: keyframes[i][member]
  10923. };
  10924. propertySpecificKeyframeGroups[member] = propertySpecificKeyframeGroups[member] || [];
  10925. propertySpecificKeyframeGroups[member].push(propertySpecificKeyframe);
  10926. }
  10927. }
  10928. }
  10929. return propertySpecificKeyframeGroups;
  10930. }
  10931. function makeInterpolations(propertySpecificKeyframeGroups, target) {
  10932. var interpolations = [];
  10933. for (var groupName in propertySpecificKeyframeGroups) {
  10934. var keyframes = propertySpecificKeyframeGroups[groupName];
  10935. for (var i = 0; i < keyframes.length - 1; i++) {
  10936. var startIndex = i;
  10937. var endIndex = i + 1;
  10938. var startOffset = keyframes[startIndex].computedOffset;
  10939. var endOffset = keyframes[endIndex].computedOffset;
  10940. var applyFrom = startOffset;
  10941. var applyTo = endOffset;
  10942. if (i === 0) {
  10943. applyFrom = -Infinity;
  10944. if (endOffset === 0) {
  10945. endIndex = startIndex;
  10946. }
  10947. }
  10948. if (i === keyframes.length - 2) {
  10949. applyTo = Infinity;
  10950. if (startOffset === 1) {
  10951. startIndex = endIndex;
  10952. }
  10953. }
  10954. interpolations.push({
  10955. applyFrom: applyFrom,
  10956. applyTo: applyTo,
  10957. startOffset: keyframes[startIndex].computedOffset,
  10958. endOffset: keyframes[endIndex].computedOffset,
  10959. easingFunction: keyframes[startIndex].easingFunction,
  10960. property: groupName,
  10961. interpolation: propertyInterpolation(groupName, keyframes[startIndex].value, keyframes[endIndex].value, target)
  10962. });
  10963. }
  10964. }
  10965. interpolations.sort(function (leftInterpolation, rightInterpolation) {
  10966. return leftInterpolation.startOffset - rightInterpolation.startOffset;
  10967. });
  10968. return interpolations;
  10969. }
  10970. var InterpolationFactory = function InterpolationFactory(from, to,
  10971. // eslint-disable-next-line @typescript-eslint/ban-types
  10972. convertToString) {
  10973. return function (f) {
  10974. var interpolated = interpolate(from, to, f);
  10975. return !runtime.enableCSSParsing && isNumber(interpolated) ? interpolated : convertToString(interpolated);
  10976. };
  10977. };
  10978. function propertyInterpolation(property, left, right, target) {
  10979. var metadata = propertyMetadataCache[property];
  10980. // discrete step
  10981. // if (property === 'visibility') {
  10982. // return function (t: number) {
  10983. // if (t === 0) return left;
  10984. // if (t === 1) return right;
  10985. // debugger;
  10986. // return t < 0.5 ? left : right;
  10987. // };
  10988. // }
  10989. if (metadata && metadata.syntax && metadata.int) {
  10990. var propertyHandler = runtime.styleValueRegistry.getPropertySyntax(metadata.syntax);
  10991. if (propertyHandler) {
  10992. var usedLeft;
  10993. var usedRight;
  10994. if (runtime.enableCSSParsing) {
  10995. var computedLeft = runtime.styleValueRegistry.parseProperty(property, left, target);
  10996. var computedRight = runtime.styleValueRegistry.parseProperty(property, right, target);
  10997. usedLeft = runtime.styleValueRegistry.computeProperty(property, computedLeft, target);
  10998. usedRight = runtime.styleValueRegistry.computeProperty(property, computedRight, target);
  10999. } else {
  11000. var parser = propertyHandler.parserWithCSSDisabled;
  11001. usedLeft = parser ? parser(left, target) : left;
  11002. usedRight = parser ? parser(right, target) : right;
  11003. }
  11004. // merger [left, right, n2string()]
  11005. var interpolationArgs = propertyHandler.mixer(usedLeft, usedRight, target);
  11006. if (interpolationArgs) {
  11007. var interp = InterpolationFactory.apply(void 0, interpolationArgs);
  11008. return function (t) {
  11009. if (t === 0) return left;
  11010. if (t === 1) return right;
  11011. return interp(t);
  11012. };
  11013. }
  11014. }
  11015. }
  11016. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  11017. return InterpolationFactory(false, true, function (bool) {
  11018. return bool ? right : left;
  11019. });
  11020. }
  11021. /**
  11022. * interpolate with number, boolean, number[], boolean[]
  11023. */
  11024. function interpolate(from, to, f) {
  11025. if (typeof from === 'number' && typeof to === 'number') {
  11026. return from * (1 - f) + to * f;
  11027. }
  11028. if (typeof from === 'boolean' && typeof to === 'boolean' || typeof from === 'string' && typeof to === 'string' // skip string, eg. path ['M', 10, 10]
  11029. ) {
  11030. return f < 0.5 ? from : to;
  11031. }
  11032. if (Array.isArray(from) && Array.isArray(to)) {
  11033. // interpolate arrays/matrix
  11034. var fromLength = from.length;
  11035. var toLength = to.length;
  11036. var length = Math.max(fromLength, toLength);
  11037. var r = [];
  11038. for (var i = 0; i < length; i++) {
  11039. r.push(interpolate(from[i < fromLength ? i : fromLength - 1], to[i < toLength ? i : toLength - 1], f));
  11040. }
  11041. return r;
  11042. }
  11043. throw new Error('Mismatched interpolation arguments ' + from + ':' + to);
  11044. }
  11045. /**
  11046. * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming
  11047. */
  11048. var AnimationEffectTiming = /*#__PURE__*/function () {
  11049. function AnimationEffectTiming() {
  11050. /**
  11051. * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/delay
  11052. */
  11053. this.delay = 0;
  11054. /**
  11055. * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/direction
  11056. */
  11057. this.direction = 'normal';
  11058. /**
  11059. * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/duration
  11060. */
  11061. this.duration = 'auto';
  11062. /**
  11063. * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/easing
  11064. */
  11065. this._easing = 'linear';
  11066. this.easingFunction = linear;
  11067. /**
  11068. * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/endDelay
  11069. */
  11070. this.endDelay = 0;
  11071. /**
  11072. * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/fill
  11073. */
  11074. this.fill = 'auto';
  11075. /**
  11076. * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/iterationStart
  11077. */
  11078. this.iterationStart = 0;
  11079. /**
  11080. * @see https://developer.mozilla.org/en-US/docs/Web/API/EffectTiming/iterations
  11081. */
  11082. this.iterations = 1;
  11083. /**
  11084. * @deprecated
  11085. */
  11086. this.playbackRate = void 0;
  11087. /**
  11088. * ref to effect
  11089. */
  11090. this.effect = void 0;
  11091. this.composite = void 0;
  11092. /**
  11093. * ComputedEffectTiming
  11094. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEffect/getComputedTiming
  11095. */
  11096. this.activeDuration = void 0;
  11097. this.endTime = void 0;
  11098. this.currentIteration = null;
  11099. this.progress = null;
  11100. }
  11101. _createClass$1(AnimationEffectTiming, [{
  11102. key: "easing",
  11103. get: function get() {
  11104. return this._easing;
  11105. },
  11106. set: function set(value) {
  11107. this.easingFunction = parseEasingFunction(value);
  11108. this._easing = value;
  11109. }
  11110. }]);
  11111. return AnimationEffectTiming;
  11112. }();
  11113. /**
  11114. * @example
  11115. {
  11116. translateY: [200, 300],
  11117. scale: [1, 10],
  11118. }
  11119. * groups' length can be different, the following config should generate 3 frames:
  11120. @example
  11121. {
  11122. translateY: [200, 300, 400],
  11123. scale: [1, 10],
  11124. }
  11125. */
  11126. function convertToArrayForm(effectInput) {
  11127. var normalizedEffectInput = [];
  11128. for (var property in effectInput) {
  11129. // skip reserved props
  11130. if (property in ['easing', 'offset', 'composite']) {
  11131. continue;
  11132. }
  11133. // @ts-ignore
  11134. var values = effectInput[property];
  11135. if (!Array.isArray(values)) {
  11136. values = [values];
  11137. }
  11138. var numKeyframes = values.length;
  11139. for (var i = 0; i < numKeyframes; i++) {
  11140. if (!normalizedEffectInput[i]) {
  11141. var keyframe = {};
  11142. if ('offset' in effectInput) {
  11143. keyframe.offset = Number(effectInput.offset);
  11144. }
  11145. if ('easing' in effectInput) {
  11146. // @ts-ignore
  11147. keyframe.easing = effectInput.easing;
  11148. }
  11149. if ('composite' in effectInput) {
  11150. // @ts-ignore
  11151. keyframe.composite = effectInput.composite;
  11152. }
  11153. normalizedEffectInput[i] = keyframe;
  11154. }
  11155. if (values[i] !== undefined && values[i] !== null) {
  11156. normalizedEffectInput[i][property] = values[i];
  11157. }
  11158. }
  11159. }
  11160. normalizedEffectInput.sort(function (a, b) {
  11161. return (a.computedOffset || 0) - (b.computedOffset || 0);
  11162. });
  11163. return normalizedEffectInput;
  11164. }
  11165. function normalizeKeyframes(effectInput, timing) {
  11166. if (effectInput === null) {
  11167. return [];
  11168. }
  11169. if (!Array.isArray(effectInput)) {
  11170. effectInput = convertToArrayForm(effectInput);
  11171. }
  11172. var keyframes = effectInput.map(function (originalKeyframe) {
  11173. var keyframe = {};
  11174. if (timing === null || timing === void 0 ? void 0 : timing.composite) {
  11175. // This will be auto if the composite operation specified on the effect is being used.
  11176. // @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API/Keyframe_Formats
  11177. keyframe.composite = 'auto';
  11178. }
  11179. for (var member in originalKeyframe) {
  11180. var memberValue = originalKeyframe[member];
  11181. if (member === 'offset') {
  11182. if (memberValue !== null) {
  11183. memberValue = Number(memberValue);
  11184. if (!isFinite(memberValue)) throw new Error('Keyframe offsets must be numbers.');
  11185. if (memberValue < 0 || memberValue > 1) throw new Error('Keyframe offsets must be between 0 and 1.');
  11186. keyframe.computedOffset = memberValue;
  11187. }
  11188. } else if (member === 'composite') {
  11189. // TODO: Support add & accumulate in KeyframeEffect.composite
  11190. // @see https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/composite
  11191. if (['replace', 'add', 'accumulate', 'auto'].indexOf(memberValue) === -1) {
  11192. throw new Error(memberValue + " compositing is not supported");
  11193. }
  11194. } else ;
  11195. // assign to keyframe, no need to parse shorthand value
  11196. keyframe[member] = memberValue;
  11197. }
  11198. if (keyframe.offset === undefined) {
  11199. keyframe.offset = null;
  11200. }
  11201. if (keyframe.easing === undefined) {
  11202. // override with timing.easing
  11203. keyframe.easing = (timing === null || timing === void 0 ? void 0 : timing.easing) || 'linear';
  11204. }
  11205. if (keyframe.composite === undefined) {
  11206. keyframe.composite = 'auto';
  11207. }
  11208. return keyframe;
  11209. });
  11210. var everyFrameHasOffset = true;
  11211. var previousOffset = -Infinity;
  11212. for (var i = 0; i < keyframes.length; i++) {
  11213. var offset = keyframes[i].offset;
  11214. if (!isNil(offset)) {
  11215. if (offset < previousOffset) {
  11216. throw new TypeError('Keyframes are not loosely sorted by offset. Sort or specify offsets.');
  11217. }
  11218. previousOffset = offset;
  11219. } else {
  11220. everyFrameHasOffset = false;
  11221. }
  11222. }
  11223. keyframes = keyframes.filter(function (keyframe) {
  11224. return Number(keyframe.offset) >= 0 && Number(keyframe.offset) <= 1;
  11225. });
  11226. function spaceKeyframes() {
  11227. var _keyframes$offset;
  11228. var length = keyframes.length;
  11229. keyframes[length - 1].computedOffset = Number((_keyframes$offset = keyframes[length - 1].offset) !== null && _keyframes$offset !== void 0 ? _keyframes$offset : 1);
  11230. if (length > 1) {
  11231. var _keyframes$0$offset;
  11232. keyframes[0].computedOffset = Number((_keyframes$0$offset = keyframes[0].offset) !== null && _keyframes$0$offset !== void 0 ? _keyframes$0$offset : 0);
  11233. }
  11234. var previousIndex = 0;
  11235. var previousOffset = Number(keyframes[0].computedOffset);
  11236. for (var _i = 1; _i < length; _i++) {
  11237. var _offset = keyframes[_i].computedOffset;
  11238. if (!isNil(_offset) && !isNil(previousOffset)) {
  11239. for (var j = 1; j < _i - previousIndex; j++) keyframes[previousIndex + j].computedOffset = previousOffset + (Number(_offset) - previousOffset) * j / (_i - previousIndex);
  11240. previousIndex = _i;
  11241. previousOffset = Number(_offset);
  11242. }
  11243. }
  11244. }
  11245. if (!everyFrameHasOffset) spaceKeyframes();
  11246. return keyframes;
  11247. }
  11248. var fills = 'backwards|forwards|both|none'.split('|');
  11249. var directions = 'reverse|alternate|alternate-reverse'.split('|');
  11250. function makeTiming(timingInput, forGroup) {
  11251. var timing = new AnimationEffectTiming();
  11252. if (forGroup) {
  11253. timing.fill = 'both';
  11254. timing.duration = 'auto';
  11255. }
  11256. if (typeof timingInput === 'number' && !isNaN(timingInput)) {
  11257. timing.duration = timingInput;
  11258. } else if (timingInput !== undefined) {
  11259. Object.keys(timingInput).forEach(function (property) {
  11260. if (timingInput[property] !== undefined && timingInput[property] !== null && timingInput[property] !== 'auto') {
  11261. if (typeof timing[property] === 'number' || property === 'duration') {
  11262. if (typeof timingInput[property] !== 'number' || isNaN(timingInput[property])) {
  11263. return;
  11264. }
  11265. }
  11266. if (property === 'fill' && fills.indexOf(timingInput[property]) === -1) {
  11267. return;
  11268. }
  11269. if (property === 'direction' && directions.indexOf(timingInput[property]) === -1) {
  11270. return;
  11271. }
  11272. // @ts-ignore
  11273. timing[property] = timingInput[property];
  11274. }
  11275. });
  11276. }
  11277. return timing;
  11278. }
  11279. function normalizeTimingInput(timingInput, forGroup) {
  11280. var _timingInput;
  11281. timingInput = numericTimingToObject((_timingInput = timingInput) !== null && _timingInput !== void 0 ? _timingInput : {
  11282. duration: 'auto'
  11283. });
  11284. return makeTiming(timingInput, forGroup);
  11285. }
  11286. function numericTimingToObject(timingInput) {
  11287. if (typeof timingInput === 'number') {
  11288. if (isNaN(timingInput)) {
  11289. timingInput = {
  11290. duration: 'auto'
  11291. };
  11292. } else {
  11293. timingInput = {
  11294. duration: timingInput
  11295. };
  11296. }
  11297. }
  11298. return timingInput;
  11299. }
  11300. /**
  11301. * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect
  11302. * @example
  11303. const circleDownKeyframes = new KeyframeEffect(
  11304. circle, // element to animate
  11305. [
  11306. { transform: 'translateY(0)' }, // keyframe
  11307. { transform: 'translateY(100)' } // keyframe
  11308. ],
  11309. { duration: 3000, fill: 'forwards' } // keyframe options
  11310. );
  11311. *
  11312. */
  11313. var KeyframeEffect = /*#__PURE__*/function () {
  11314. function KeyframeEffect(target, effectInput, timingInput) {
  11315. var _this = this;
  11316. this.composite = 'replace';
  11317. this.iterationComposite = 'replace';
  11318. // pseudoElement: string | null;
  11319. this.target = void 0;
  11320. this.animation = void 0;
  11321. this.timing = void 0;
  11322. this.computedTiming = void 0;
  11323. this.normalizedKeyframes = void 0;
  11324. this.timeFraction = void 0;
  11325. this.interpolations = void 0;
  11326. this.target = target;
  11327. this.timing = normalizeTimingInput(timingInput, false);
  11328. this.timing.effect = this;
  11329. this.timing.activeDuration = calculateActiveDuration(this.timing);
  11330. this.timing.endTime = Math.max(0, this.timing.delay + this.timing.activeDuration + this.timing.endDelay);
  11331. this.normalizedKeyframes = normalizeKeyframes(effectInput, this.timing);
  11332. this.interpolations = convertEffectInput(this.normalizedKeyframes, this.timing, this.target);
  11333. // 不支持 proxy 时降级成 this.timing
  11334. var Proxy = runtime.globalThis.Proxy;
  11335. this.computedTiming = Proxy ? new Proxy(this.timing, {
  11336. get: function get(target, prop) {
  11337. if (prop === 'duration') {
  11338. return target.duration === 'auto' ? 0 : target.duration;
  11339. } else if (prop === 'fill') {
  11340. return target.fill === 'auto' ? 'none' : target.fill;
  11341. } else if (prop === 'localTime') {
  11342. return _this.animation && _this.animation.currentTime || null;
  11343. } else if (prop === 'currentIteration') {
  11344. if (!_this.animation || _this.animation.playState !== 'running') {
  11345. return null;
  11346. }
  11347. return target.currentIteration || 0;
  11348. } else if (prop === 'progress') {
  11349. if (!_this.animation || _this.animation.playState !== 'running') {
  11350. return null;
  11351. }
  11352. return target.progress || 0;
  11353. }
  11354. return target[prop];
  11355. },
  11356. set: function set() {
  11357. return true;
  11358. }
  11359. }) : this.timing;
  11360. }
  11361. var _proto = KeyframeEffect.prototype;
  11362. _proto.applyInterpolations = function applyInterpolations() {
  11363. this.interpolations(this.target, Number(this.timeFraction));
  11364. };
  11365. _proto.update = function update(localTime) {
  11366. if (localTime === null) {
  11367. return false;
  11368. }
  11369. this.timeFraction = calculateIterationProgress(this.timing.activeDuration, localTime, this.timing);
  11370. return this.timeFraction !== null;
  11371. };
  11372. _proto.getKeyframes = function getKeyframes() {
  11373. return this.normalizedKeyframes;
  11374. };
  11375. _proto.setKeyframes = function setKeyframes(keyframes) {
  11376. this.normalizedKeyframes = normalizeKeyframes(keyframes);
  11377. }
  11378. /**
  11379. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEffect/getComputedTiming
  11380. */;
  11381. _proto.getComputedTiming = function getComputedTiming() {
  11382. return this.computedTiming;
  11383. }
  11384. /**
  11385. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEffect/getTiming
  11386. */;
  11387. _proto.getTiming = function getTiming() {
  11388. return this.timing;
  11389. }
  11390. /**
  11391. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEffect/updateTiming
  11392. */;
  11393. _proto.updateTiming = function updateTiming(timing) {
  11394. var _this2 = this;
  11395. Object.keys(timing || {}).forEach(function (name) {
  11396. _this2.timing[name] = timing[name];
  11397. });
  11398. };
  11399. return KeyframeEffect;
  11400. }();
  11401. function compareAnimations(leftAnimation, rightAnimation) {
  11402. return Number(leftAnimation.id) - Number(rightAnimation.id);
  11403. }
  11404. /**
  11405. * @see https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/web-animations-js/index.d.ts
  11406. */
  11407. var AnimationTimeline = /*#__PURE__*/function () {
  11408. function AnimationTimeline(document) {
  11409. var _this = this;
  11410. this.document = void 0;
  11411. /**
  11412. * all active animations
  11413. */
  11414. this.animations = [];
  11415. this.ticking = false;
  11416. this.timelineTicking = false;
  11417. this.hasRestartedThisFrame = false;
  11418. this.animationsWithPromises = [];
  11419. this.inTick = false;
  11420. this.pendingEffects = [];
  11421. this.currentTime = null;
  11422. this.rafId = 0;
  11423. this.rafCallbacks = [];
  11424. this.frameId = void 0;
  11425. this.webAnimationsNextTick = function (t) {
  11426. _this.currentTime = t;
  11427. _this.discardAnimations();
  11428. if (_this.animations.length === 0) {
  11429. _this.timelineTicking = false;
  11430. } else {
  11431. _this.requestAnimationFrame(_this.webAnimationsNextTick);
  11432. }
  11433. };
  11434. this.processRafCallbacks = function (t) {
  11435. var processing = _this.rafCallbacks;
  11436. _this.rafCallbacks = [];
  11437. if (t < Number(_this.currentTime)) t = Number(_this.currentTime);
  11438. _this.animations.sort(compareAnimations);
  11439. _this.animations = _this.tick(t, true, _this.animations)[0];
  11440. processing.forEach(function (entry) {
  11441. entry[1](t);
  11442. });
  11443. _this.applyPendingEffects();
  11444. };
  11445. this.document = document;
  11446. }
  11447. var _proto = AnimationTimeline.prototype;
  11448. _proto.getAnimations = function getAnimations() {
  11449. this.discardAnimations();
  11450. return this.animations.slice();
  11451. };
  11452. _proto.isTicking = function isTicking() {
  11453. return this.inTick;
  11454. };
  11455. _proto.play = function play(target, keyframes, options) {
  11456. var effect = new KeyframeEffect(target, keyframes, options);
  11457. var animation = new Animation(effect, this);
  11458. this.animations.push(animation);
  11459. this.restartWebAnimationsNextTick();
  11460. animation.updatePromises();
  11461. animation.play();
  11462. animation.updatePromises();
  11463. return animation;
  11464. }
  11465. // RAF is supposed to be the last script to occur before frame rendering but not
  11466. // all browsers behave like this. This function is for synchonously updating an
  11467. // animation's effects whenever its state is mutated by script to work around
  11468. // incorrect script execution ordering by the browser.
  11469. ;
  11470. _proto.applyDirtiedAnimation = function applyDirtiedAnimation(animation) {
  11471. var _this2 = this;
  11472. if (this.inTick) {
  11473. return;
  11474. }
  11475. // update active animations in displayobject
  11476. animation.markTarget();
  11477. var animations = animation.targetAnimations();
  11478. animations.sort(compareAnimations);
  11479. // clear inactive animations
  11480. var inactiveAnimations = this.tick(Number(this.currentTime), false, animations.slice())[1];
  11481. inactiveAnimations.forEach(function (animation) {
  11482. var index = _this2.animations.indexOf(animation);
  11483. if (index !== -1) {
  11484. _this2.animations.splice(index, 1);
  11485. }
  11486. });
  11487. this.applyPendingEffects();
  11488. };
  11489. _proto.restart = function restart() {
  11490. if (!this.ticking) {
  11491. this.ticking = true;
  11492. this.requestAnimationFrame(function () {});
  11493. this.hasRestartedThisFrame = true;
  11494. }
  11495. return this.hasRestartedThisFrame;
  11496. };
  11497. _proto.destroy = function destroy() {
  11498. this.document.defaultView.cancelAnimationFrame(this.frameId);
  11499. };
  11500. _proto.applyPendingEffects = function applyPendingEffects() {
  11501. this.pendingEffects.forEach(function (effect) {
  11502. effect === null || effect === void 0 ? void 0 : effect.applyInterpolations();
  11503. });
  11504. this.pendingEffects = [];
  11505. };
  11506. _proto.updateAnimationsPromises = function updateAnimationsPromises() {
  11507. this.animationsWithPromises = this.animationsWithPromises.filter(function (animation) {
  11508. return animation.updatePromises();
  11509. });
  11510. };
  11511. _proto.discardAnimations = function discardAnimations() {
  11512. this.updateAnimationsPromises();
  11513. this.animations = this.animations.filter(function (animation) {
  11514. return animation.playState !== 'finished' && animation.playState !== 'idle';
  11515. });
  11516. };
  11517. _proto.restartWebAnimationsNextTick = function restartWebAnimationsNextTick() {
  11518. if (!this.timelineTicking) {
  11519. this.timelineTicking = true;
  11520. this.requestAnimationFrame(this.webAnimationsNextTick);
  11521. }
  11522. };
  11523. _proto.rAF = function rAF(f) {
  11524. var id = this.rafId++;
  11525. if (this.rafCallbacks.length === 0) {
  11526. this.frameId = this.document.defaultView.requestAnimationFrame(this.processRafCallbacks);
  11527. }
  11528. this.rafCallbacks.push([id, f]);
  11529. return id;
  11530. };
  11531. _proto.requestAnimationFrame = function requestAnimationFrame(f) {
  11532. var _this3 = this;
  11533. return this.rAF(function (x) {
  11534. _this3.updateAnimationsPromises();
  11535. f(x);
  11536. _this3.updateAnimationsPromises();
  11537. });
  11538. };
  11539. _proto.tick = function tick(t, isAnimationFrame, updatingAnimations) {
  11540. var _this4 = this,
  11541. _this$pendingEffects,
  11542. _this$pendingEffects2;
  11543. this.inTick = true;
  11544. this.hasRestartedThisFrame = false;
  11545. this.currentTime = t;
  11546. this.ticking = false;
  11547. var newPendingClears = [];
  11548. var newPendingEffects = [];
  11549. var activeAnimations = [];
  11550. var inactiveAnimations = [];
  11551. updatingAnimations.forEach(function (animation) {
  11552. animation.tick(t, isAnimationFrame);
  11553. if (!animation._inEffect) {
  11554. newPendingClears.push(animation.effect);
  11555. animation.unmarkTarget();
  11556. } else {
  11557. newPendingEffects.push(animation.effect);
  11558. animation.markTarget();
  11559. }
  11560. if (animation._needsTick) _this4.ticking = true;
  11561. var alive = animation._inEffect || animation._needsTick;
  11562. animation._inTimeline = alive;
  11563. if (alive) {
  11564. activeAnimations.push(animation);
  11565. } else {
  11566. inactiveAnimations.push(animation);
  11567. }
  11568. });
  11569. (_this$pendingEffects = this.pendingEffects).push.apply(_this$pendingEffects, newPendingClears);
  11570. (_this$pendingEffects2 = this.pendingEffects).push.apply(_this$pendingEffects2, newPendingEffects);
  11571. if (this.ticking) this.requestAnimationFrame(function () {});
  11572. this.inTick = false;
  11573. return [activeAnimations, inactiveAnimations];
  11574. };
  11575. return AnimationTimeline;
  11576. }();
  11577. runtime.EasingFunction = parseEasingFunction;
  11578. runtime.AnimationTimeline = AnimationTimeline;
  11579. exports.AABB = AABB;
  11580. exports.AbstractRenderer = AbstractRenderer;
  11581. exports.AbstractRendererPlugin = AbstractRendererPlugin;
  11582. exports.AdvancedCamera = AdvancedCamera;
  11583. exports.Animation = Animation;
  11584. exports.AnimationEvent = AnimationEvent;
  11585. exports.AnimationTimeline = AnimationTimeline;
  11586. exports.BUILT_IN_PROPERTIES = BUILT_IN_PROPERTIES;
  11587. exports.CSS = CSS;
  11588. exports.CSSGradientValue = CSSGradientValue;
  11589. exports.CSSKeywordValue = CSSKeywordValue;
  11590. exports.CSSRGB = CSSRGB;
  11591. exports.CSSStyleValue = CSSStyleValue;
  11592. exports.CSSUnitValue = CSSUnitValue;
  11593. exports.Camera = Camera;
  11594. exports.CameraEvent = CameraEvent;
  11595. exports.Canvas = Canvas;
  11596. exports.Circle = Circle;
  11597. exports.CircleUpdater = CircleUpdater;
  11598. exports.CustomElement = CustomElement;
  11599. exports.CustomElementRegistry = CustomElementRegistry;
  11600. exports.CustomEvent = CustomEvent;
  11601. exports.DefaultSceneGraphSelector = DefaultSceneGraphSelector;
  11602. exports.DefaultSceneGraphService = DefaultSceneGraphService;
  11603. exports.DisplayObject = DisplayObject;
  11604. exports.Document = Document;
  11605. exports.EMPTY_PARSED_PATH = EMPTY_PARSED_PATH;
  11606. exports.ERROR_MSG_METHOD_NOT_IMPLEMENTED = ERROR_MSG_METHOD_NOT_IMPLEMENTED;
  11607. exports.Element = Element;
  11608. exports.Ellipse = Ellipse;
  11609. exports.EllipseUpdater = EllipseUpdater;
  11610. exports.EventService = EventService;
  11611. exports.EventTarget = EventTarget;
  11612. exports.FederatedEvent = FederatedEvent;
  11613. exports.FederatedMouseEvent = FederatedMouseEvent;
  11614. exports.FederatedPointerEvent = FederatedPointerEvent;
  11615. exports.FederatedWheelEvent = FederatedWheelEvent;
  11616. exports.Frustum = Frustum;
  11617. exports.Group = Group;
  11618. exports.HTML = HTML;
  11619. exports.Image = Image;
  11620. exports.KeyframeEffect = KeyframeEffect;
  11621. exports.Line = Line;
  11622. exports.LineUpdater = LineUpdater;
  11623. exports.MutationEvent = MutationEvent;
  11624. exports.MutationObserver = MutationObserver;
  11625. exports.MutationRecord = MutationRecord;
  11626. exports.Node = Node;
  11627. exports.OffscreenCanvasCreator = OffscreenCanvasCreator;
  11628. exports.Path = Path;
  11629. exports.PathUpdater = PathUpdater;
  11630. exports.Plane = Plane;
  11631. exports.Point = Point;
  11632. exports.Polygon = Polygon;
  11633. exports.Polyline = Polyline;
  11634. exports.PolylineUpdater = PolylineUpdater;
  11635. exports.RBush = rbush;
  11636. exports.Rect = Rect;
  11637. exports.RectUpdater = RectUpdater;
  11638. exports.Rectangle = Rectangle;
  11639. exports.Registration = Registration;
  11640. exports.RenderingService = RenderingService;
  11641. exports.Text = Text;
  11642. exports.TextService = TextService;
  11643. exports.TextUpdater = TextUpdater;
  11644. exports.compareAnimations = compareAnimations;
  11645. exports.computeLinearGradient = computeLinearGradient;
  11646. exports.computeRadialGradient = computeRadialGradient;
  11647. exports.convertToPath = convertToPath;
  11648. exports.createVec3 = createVec3;
  11649. exports.decompose = decompose;
  11650. exports.definedProps = definedProps;
  11651. exports.deg2rad = deg2rad;
  11652. exports.deg2turn = deg2turn;
  11653. exports.findClosestClipPathTarget = findClosestClipPathTarget;
  11654. exports.fromRotationTranslationScale = fromRotationTranslationScale$1;
  11655. exports.getAngle = getAngle$1;
  11656. exports.getEuler = getEuler;
  11657. exports.getOrCalculatePathTotalLength = getOrCalculatePathTotalLength;
  11658. exports.grad2deg = grad2deg;
  11659. exports.isBrowser = isBrowser;
  11660. exports.isCSSGradientValue = isCSSGradientValue;
  11661. exports.isCSSRGB = isCSSRGB;
  11662. exports.isCanvas = isCanvas;
  11663. exports.isDisplayObject = isDisplayObject;
  11664. exports.isFederatedEvent = isFederatedEvent;
  11665. exports.isFillOrStrokeAffected = isFillOrStrokeAffected;
  11666. exports.isPattern = isPattern;
  11667. exports.makeTiming = makeTiming;
  11668. exports.mergeColors = mergeColors;
  11669. exports.normalizeKeyframes = normalizeKeyframes;
  11670. exports.normalizeTimingInput = normalizeTimingInput;
  11671. exports.numericTimingToObject = numericTimingToObject;
  11672. exports.parseColor = parseColor;
  11673. exports.parseLength = parseLength;
  11674. exports.parsePath = parsePath;
  11675. exports.parseTransform = parseTransform;
  11676. exports.parsedTransformToMat4 = parsedTransformToMat4;
  11677. exports.propertyMetadataCache = propertyMetadataCache;
  11678. exports.rad2deg = rad2deg;
  11679. exports.resetEntityCounter = resetEntityCounter;
  11680. exports.runtime = runtime;
  11681. exports.setDOMSize = setDOMSize;
  11682. exports.translatePathToString = translatePathToString;
  11683. exports.turn2deg = turn2deg;
  11684. Object.defineProperty(exports, '__esModule', { value: true });
  11685. })));