Submit
Path:
~
/
/
usr
/
share
/
grafana
/
public
/
build
/
File Content:
6378.27b1e6d863a0a3b85962.js
(()=>{var Th={64106:fe=>{"use strict";function Et(O,C){function f(){this.constructor=O}f.prototype=C.prototype,O.prototype=new f}function Tt(O,C,f,W){this.message=O,this.expected=C,this.found=f,this.location=W,this.name="SyntaxError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Tt)}Et(Tt,Error),Tt.buildMessage=function(O,C){var f={literal:function(_){return'"'+Dt(_.text)+'"'},class:function(_){var k="",tt;for(tt=0;tt<_.parts.length;tt++)k+=_.parts[tt]instanceof Array?xt(_.parts[tt][0])+"-"+xt(_.parts[tt][1]):xt(_.parts[tt]);return"["+(_.inverted?"^":"")+k+"]"},any:function(_){return"any character"},end:function(_){return"end of input"},other:function(_){return _.description}};function W(_){return _.charCodeAt(0).toString(16).toUpperCase()}function Dt(_){return _.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(k){return"\\x0"+W(k)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(k){return"\\x"+W(k)})}function xt(_){return _.replace(/\\/g,"\\\\").replace(/\]/g,"\\]").replace(/\^/g,"\\^").replace(/-/g,"\\-").replace(/\0/g,"\\0").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/[\x00-\x0F]/g,function(k){return"\\x0"+W(k)}).replace(/[\x10-\x1F\x7F-\x9F]/g,function(k){return"\\x"+W(k)})}function N(_){return f[_.type](_)}function z(_){var k=new Array(_.length),tt,d;for(tt=0;tt<_.length;tt++)k[tt]=N(_[tt]);if(k.sort(),k.length>0){for(tt=1,d=1;tt<k.length;tt++)k[tt-1]!==k[tt]&&(k[d]=k[tt],d++);k.length=d}switch(k.length){case 1:return k[0];case 2:return k[0]+" or "+k[1];default:return k.slice(0,-1).join(", ")+", or "+k[k.length-1]}}function et(_){return _?'"'+Dt(_)+'"':"end of input"}return"Expected "+z(O)+" but "+et(C)+" found."};function gt(O,C){C=C!==void 0?C:{};var f={},W={start:an},Dt=an,xt="strict",N=yt("strict",!0),z="graph",et=yt("graph",!0),_="digraph",k=yt("digraph",!0),tt="{",d=yt("{",!1),qt="}",Re=yt("}",!1),At=function(p,y,x,T){T===null&&(T=[]);var M={type:y.toLowerCase(),children:T};return p&&(M.strict=!0),x&&(M.id=x),M},ps=";",D=yt(";",!1),Ri=function(p,y){return y},On=function(p,y){return[p].concat(y)},Di="=",jt=yt("=",!1),Ei=function(p,y){return{type:"attr_stmt",target:"graph",attr_list:[{type:"attr",id:p,eq:y}]}},ms="node",vt=yt("node",!0),Ln="edge",Nt=yt("edge",!0),hr=function(p,y){return{type:"attr_stmt",target:p,attr_list:y}},Xs="[",Qs=yt("[",!1),Bn="]",ft=yt("]",!1),ur=function(p,y){return(p||[]).concat(y||[])},w=function(p,y){return y},Ni=",",Ys=yt(",",!1),_r=function(p,y,x){return[{type:"attr",id:p,eq:y}].concat(x||[])},to=function(p,y,x){var T=[p];return T=T.concat(y.map(function(M){return M.id})),{type:"edge_stmt",edge_list:T,attr_list:x||[]}},cr="->",Fn=yt("->",!1),at="--",De=yt("--",!1),Z=function(p,y,x){return[{type:"edgeRHS",edgeop:p,id:y}].concat(x||[])},Ut=function(p,y){return{type:"node_stmt",node_id:p,attr_list:y||[]}},G=function(p,y){return y?{type:"node_id",id:p,port:y}:{type:"node_id",id:p}},st=oe("port"),H=":",K=yt(":",!1),nt=function(p,y){return y},Y=function(p,y){return{type:"port",id:p,compass_pt:y||null}},ot=function(p){return{type:"port",compass_pt:p||null}},v="subgraph",L=yt("subgraph",!0),j=function(p){return p?{type:"subgraph",id:p}:{type:"subgraph"}},Ks=function(p,y){return p=p||{type:"subgraph"},p.children=y||[],p},Ne="n",ta=yt("n",!1),Yt="ne",$t=yt("ne",!1),ea="e",re=yt("e",!1),dr="se",ia=yt("se",!1),Rn="s",eo=yt("s",!1),pe="sw",gr=yt("sw",!1),fr="w",ve=yt("w",!1),ie="nw",Ps=yt("nw",!1),sa=oe("UNICODE_STRING"),Ss=function(p,y){return p+y.join("")},Ki=function(p,y){return p+y},Ji="$",na=yt("$",!1),Js="_",Dn=yt("_",!1),Zs=oe("NUMBER"),Nn="-",ys=yt("-",!1),pr=".",io=yt(".",!1),Cs=/^[0-9]/,ns=Ye([["0","9"]],!1,!1),Ka=function(p){return parseFloat(rn())},hi=function(p){return{type:"id",value:p.slice(1,p.length-1),html:!0}},Ht="<",_s=yt("<",!1),ki=">",rs=yt(">",!1),mr=function(p){return"<"+p.join("")+">"},bi=Me(),Gt=function(p){return p},ra=function(p){return p.join("")},Pr='"',so=yt('"',!1),kn=function(p){return p.join("")},Pe=function(){return rn()},zt="\\",Zi=yt("\\",!1),Gi=function(p){return p[1]==='"'?'"':p[0]+p[1]},no=function(){return""},Gn=/^[\n\r\u2028\u2029]/,ro=Ye([` `,"\r","\u2028","\u2029"],!1,!1),tn=oe("end of line"),oa=` `,oo=yt(` `,!1),ao=`\r `,aa=yt(`\r `,!1),lo="\r",Sr=yt("\r",!1),Mn="\u2028",la=yt("\u2028",!1),ha="\u2029",Xt=yt("\u2029",!1),yr=/^[^"\\\0-\x1F\x7F]/,Ja=Ye(['"',"\\",["\0",""],"\x7F"],!0,!1),ua='\\"',Za=yt('\\"',!1),_a=function(){return'"'},tl=function(){return"\\"},el=oe("COMMENT"),Es=oe("BLOCK_COMMENT"),Vn="/*",ii=yt("/*",!1),Xe="*/",en=yt("*/",!1),Ct=function(p){return p},Qe=function(p){return p.join("")},Cr=oe("C_COMMENT"),Ai="//",bs=yt("//",!1),As=/^[\n]/,ws=Ye([` `],!1,!1),ho=function(p){return p.join("")},uo=oe("MACRO_COMMENT"),Se="#",ke=yt("#",!1),wi=oe("WHITESPACE"),si=/^[\n\r]/,sn=Ye([` `,"\r"],!1,!1),os=/^[ \t]/,se=Ye([" "," "],!1,!1),Er=/^[a-z\xB5\xDF-\xF6\xF8-\xFF\u0101\u0103\u0105\u0107\u0109\u010B\u010D\u010F\u0111\u0113\u0115\u0117\u0119\u011B\u011D\u011F\u0121\u0123\u0125\u0127\u0129\u012B\u012D\u012F\u0131\u0133\u0135\u0137-\u0138\u013A\u013C\u013E\u0140\u0142\u0144\u0146\u0148-\u0149\u014B\u014D\u014F\u0151\u0153\u0155\u0157\u0159\u015B\u015D\u015F\u0161\u0163\u0165\u0167\u0169\u016B\u016D\u016F\u0171\u0173\u0175\u0177\u017A\u017C\u017E-\u0180\u0183\u0185\u0188\u018C-\u018D\u0192\u0195\u0199-\u019B\u019E\u01A1\u01A3\u01A5\u01A8\u01AA-\u01AB\u01AD\u01B0\u01B4\u01B6\u01B9-\u01BA\u01BD-\u01BF\u01C6\u01C9\u01CC\u01CE\u01D0\u01D2\u01D4\u01D6\u01D8\u01DA\u01DC-\u01DD\u01DF\u01E1\u01E3\u01E5\u01E7\u01E9\u01EB\u01ED\u01EF-\u01F0\u01F3\u01F5\u01F9\u01FB\u01FD\u01FF\u0201\u0203\u0205\u0207\u0209\u020B\u020D\u020F\u0211\u0213\u0215\u0217\u0219\u021B\u021D\u021F\u0221\u0223\u0225\u0227\u0229\u022B\u022D\u022F\u0231\u0233-\u0239\u023C\u023F-\u0240\u0242\u0247\u0249\u024B\u024D\u024F-\u0293\u0295-\u02AF\u0371\u0373\u0377\u037B-\u037D\u0390\u03AC-\u03CE\u03D0-\u03D1\u03D5-\u03D7\u03D9\u03DB\u03DD\u03DF\u03E1\u03E3\u03E5\u03E7\u03E9\u03EB\u03ED\u03EF-\u03F3\u03F5\u03F8\u03FB-\u03FC\u0430-\u045F\u0461\u0463\u0465\u0467\u0469\u046B\u046D\u046F\u0471\u0473\u0475\u0477\u0479\u047B\u047D\u047F\u0481\u048B\u048D\u048F\u0491\u0493\u0495\u0497\u0499\u049B\u049D\u049F\u04A1\u04A3\u04A5\u04A7\u04A9\u04AB\u04AD\u04AF\u04B1\u04B3\u04B5\u04B7\u04B9\u04BB\u04BD\u04BF\u04C2\u04C4\u04C6\u04C8\u04CA\u04CC\u04CE-\u04CF\u04D1\u04D3\u04D5\u04D7\u04D9\u04DB\u04DD\u04DF\u04E1\u04E3\u04E5\u04E7\u04E9\u04EB\u04ED\u04EF\u04F1\u04F3\u04F5\u04F7\u04F9\u04FB\u04FD\u04FF\u0501\u0503\u0505\u0507\u0509\u050B\u050D\u050F\u0511\u0513\u0515\u0517\u0519\u051B\u051D\u051F\u0521\u0523\u0525\u0527\u0561-\u0587\u1D00-\u1D2B\u1D6B-\u1D77\u1D79-\u1D9A\u1E01\u1E03\u1E05\u1E07\u1E09\u1E0B\u1E0D\u1E0F\u1E11\u1E13\u1E15\u1E17\u1E19\u1E1B\u1E1D\u1E1F\u1E21\u1E23\u1E25\u1E27\u1E29\u1E2B\u1E2D\u1E2F\u1E31\u1E33\u1E35\u1E37\u1E39\u1E3B\u1E3D\u1E3F\u1E41\u1E43\u1E45\u1E47\u1E49\u1E4B\u1E4D\u1E4F\u1E51\u1E53\u1E55\u1E57\u1E59\u1E5B\u1E5D\u1E5F\u1E61\u1E63\u1E65\u1E67\u1E69\u1E6B\u1E6D\u1E6F\u1E71\u1E73\u1E75\u1E77\u1E79\u1E7B\u1E7D\u1E7F\u1E81\u1E83\u1E85\u1E87\u1E89\u1E8B\u1E8D\u1E8F\u1E91\u1E93\u1E95-\u1E9D\u1E9F\u1EA1\u1EA3\u1EA5\u1EA7\u1EA9\u1EAB\u1EAD\u1EAF\u1EB1\u1EB3\u1EB5\u1EB7\u1EB9\u1EBB\u1EBD\u1EBF\u1EC1\u1EC3\u1EC5\u1EC7\u1EC9\u1ECB\u1ECD\u1ECF\u1ED1\u1ED3\u1ED5\u1ED7\u1ED9\u1EDB\u1EDD\u1EDF\u1EE1\u1EE3\u1EE5\u1EE7\u1EE9\u1EEB\u1EED\u1EEF\u1EF1\u1EF3\u1EF5\u1EF7\u1EF9\u1EFB\u1EFD\u1EFF-\u1F07\u1F10-\u1F15\u1F20-\u1F27\u1F30-\u1F37\u1F40-\u1F45\u1F50-\u1F57\u1F60-\u1F67\u1F70-\u1F7D\u1F80-\u1F87\u1F90-\u1F97\u1FA0-\u1FA7\u1FB0-\u1FB4\u1FB6-\u1FB7\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FC7\u1FD0-\u1FD3\u1FD6-\u1FD7\u1FE0-\u1FE7\u1FF2-\u1FF4\u1FF6-\u1FF7\u210A\u210E-\u210F\u2113\u212F\u2134\u2139\u213C-\u213D\u2146-\u2149\u214E\u2184\u2C30-\u2C5E\u2C61\u2C65-\u2C66\u2C68\u2C6A\u2C6C\u2C71\u2C73-\u2C74\u2C76-\u2C7B\u2C81\u2C83\u2C85\u2C87\u2C89\u2C8B\u2C8D\u2C8F\u2C91\u2C93\u2C95\u2C97\u2C99\u2C9B\u2C9D\u2C9F\u2CA1\u2CA3\u2CA5\u2CA7\u2CA9\u2CAB\u2CAD\u2CAF\u2CB1\u2CB3\u2CB5\u2CB7\u2CB9\u2CBB\u2CBD\u2CBF\u2CC1\u2CC3\u2CC5\u2CC7\u2CC9\u2CCB\u2CCD\u2CCF\u2CD1\u2CD3\u2CD5\u2CD7\u2CD9\u2CDB\u2CDD\u2CDF\u2CE1\u2CE3-\u2CE4\u2CEC\u2CEE\u2CF3\u2D00-\u2D25\u2D27\u2D2D\uA641\uA643\uA645\uA647\uA649\uA64B\uA64D\uA64F\uA651\uA653\uA655\uA657\uA659\uA65B\uA65D\uA65F\uA661\uA663\uA665\uA667\uA669\uA66B\uA66D\uA681\uA683\uA685\uA687\uA689\uA68B\uA68D\uA68F\uA691\uA693\uA695\uA697\uA723\uA725\uA727\uA729\uA72B\uA72D\uA72F-\uA731\uA733\uA735\uA737\uA739\uA73B\uA73D\uA73F\uA741\uA743\uA745\uA747\uA749\uA74B\uA74D\uA74F\uA751\uA753\uA755\uA757\uA759\uA75B\uA75D\uA75F\uA761\uA763\uA765\uA767\uA769\uA76B\uA76D\uA76F\uA771-\uA778\uA77A\uA77C\uA77F\uA781\uA783\uA785\uA787\uA78C\uA78E\uA791\uA793\uA7A1\uA7A3\uA7A5\uA7A7\uA7A9\uA7FA\uFB00-\uFB06\uFB13-\uFB17\uFF41-\uFF5A]/,vs=Ye([["a","z"],"\xB5",["\xDF","\xF6"],["\xF8","\xFF"],"\u0101","\u0103","\u0105","\u0107","\u0109","\u010B","\u010D","\u010F","\u0111","\u0113","\u0115","\u0117","\u0119","\u011B","\u011D","\u011F","\u0121","\u0123","\u0125","\u0127","\u0129","\u012B","\u012D","\u012F","\u0131","\u0133","\u0135",["\u0137","\u0138"],"\u013A","\u013C","\u013E","\u0140","\u0142","\u0144","\u0146",["\u0148","\u0149"],"\u014B","\u014D","\u014F","\u0151","\u0153","\u0155","\u0157","\u0159","\u015B","\u015D","\u015F","\u0161","\u0163","\u0165","\u0167","\u0169","\u016B","\u016D","\u016F","\u0171","\u0173","\u0175","\u0177","\u017A","\u017C",["\u017E","\u0180"],"\u0183","\u0185","\u0188",["\u018C","\u018D"],"\u0192","\u0195",["\u0199","\u019B"],"\u019E","\u01A1","\u01A3","\u01A5","\u01A8",["\u01AA","\u01AB"],"\u01AD","\u01B0","\u01B4","\u01B6",["\u01B9","\u01BA"],["\u01BD","\u01BF"],"\u01C6","\u01C9","\u01CC","\u01CE","\u01D0","\u01D2","\u01D4","\u01D6","\u01D8","\u01DA",["\u01DC","\u01DD"],"\u01DF","\u01E1","\u01E3","\u01E5","\u01E7","\u01E9","\u01EB","\u01ED",["\u01EF","\u01F0"],"\u01F3","\u01F5","\u01F9","\u01FB","\u01FD","\u01FF","\u0201","\u0203","\u0205","\u0207","\u0209","\u020B","\u020D","\u020F","\u0211","\u0213","\u0215","\u0217","\u0219","\u021B","\u021D","\u021F","\u0221","\u0223","\u0225","\u0227","\u0229","\u022B","\u022D","\u022F","\u0231",["\u0233","\u0239"],"\u023C",["\u023F","\u0240"],"\u0242","\u0247","\u0249","\u024B","\u024D",["\u024F","\u0293"],["\u0295","\u02AF"],"\u0371","\u0373","\u0377",["\u037B","\u037D"],"\u0390",["\u03AC","\u03CE"],["\u03D0","\u03D1"],["\u03D5","\u03D7"],"\u03D9","\u03DB","\u03DD","\u03DF","\u03E1","\u03E3","\u03E5","\u03E7","\u03E9","\u03EB","\u03ED",["\u03EF","\u03F3"],"\u03F5","\u03F8",["\u03FB","\u03FC"],["\u0430","\u045F"],"\u0461","\u0463","\u0465","\u0467","\u0469","\u046B","\u046D","\u046F","\u0471","\u0473","\u0475","\u0477","\u0479","\u047B","\u047D","\u047F","\u0481","\u048B","\u048D","\u048F","\u0491","\u0493","\u0495","\u0497","\u0499","\u049B","\u049D","\u049F","\u04A1","\u04A3","\u04A5","\u04A7","\u04A9","\u04AB","\u04AD","\u04AF","\u04B1","\u04B3","\u04B5","\u04B7","\u04B9","\u04BB","\u04BD","\u04BF","\u04C2","\u04C4","\u04C6","\u04C8","\u04CA","\u04CC",["\u04CE","\u04CF"],"\u04D1","\u04D3","\u04D5","\u04D7","\u04D9","\u04DB","\u04DD","\u04DF","\u04E1","\u04E3","\u04E5","\u04E7","\u04E9","\u04EB","\u04ED","\u04EF","\u04F1","\u04F3","\u04F5","\u04F7","\u04F9","\u04FB","\u04FD","\u04FF","\u0501","\u0503","\u0505","\u0507","\u0509","\u050B","\u050D","\u050F","\u0511","\u0513","\u0515","\u0517","\u0519","\u051B","\u051D","\u051F","\u0521","\u0523","\u0525","\u0527",["\u0561","\u0587"],["\u1D00","\u1D2B"],["\u1D6B","\u1D77"],["\u1D79","\u1D9A"],"\u1E01","\u1E03","\u1E05","\u1E07","\u1E09","\u1E0B","\u1E0D","\u1E0F","\u1E11","\u1E13","\u1E15","\u1E17","\u1E19","\u1E1B","\u1E1D","\u1E1F","\u1E21","\u1E23","\u1E25","\u1E27","\u1E29","\u1E2B","\u1E2D","\u1E2F","\u1E31","\u1E33","\u1E35","\u1E37","\u1E39","\u1E3B","\u1E3D","\u1E3F","\u1E41","\u1E43","\u1E45","\u1E47","\u1E49","\u1E4B","\u1E4D","\u1E4F","\u1E51","\u1E53","\u1E55","\u1E57","\u1E59","\u1E5B","\u1E5D","\u1E5F","\u1E61","\u1E63","\u1E65","\u1E67","\u1E69","\u1E6B","\u1E6D","\u1E6F","\u1E71","\u1E73","\u1E75","\u1E77","\u1E79","\u1E7B","\u1E7D","\u1E7F","\u1E81","\u1E83","\u1E85","\u1E87","\u1E89","\u1E8B","\u1E8D","\u1E8F","\u1E91","\u1E93",["\u1E95","\u1E9D"],"\u1E9F","\u1EA1","\u1EA3","\u1EA5","\u1EA7","\u1EA9","\u1EAB","\u1EAD","\u1EAF","\u1EB1","\u1EB3","\u1EB5","\u1EB7","\u1EB9","\u1EBB","\u1EBD","\u1EBF","\u1EC1","\u1EC3","\u1EC5","\u1EC7","\u1EC9","\u1ECB","\u1ECD","\u1ECF","\u1ED1","\u1ED3","\u1ED5","\u1ED7","\u1ED9","\u1EDB","\u1EDD","\u1EDF","\u1EE1","\u1EE3","\u1EE5","\u1EE7","\u1EE9","\u1EEB","\u1EED","\u1EEF","\u1EF1","\u1EF3","\u1EF5","\u1EF7","\u1EF9","\u1EFB","\u1EFD",["\u1EFF","\u1F07"],["\u1F10","\u1F15"],["\u1F20","\u1F27"],["\u1F30","\u1F37"],["\u1F40","\u1F45"],["\u1F50","\u1F57"],["\u1F60","\u1F67"],["\u1F70","\u1F7D"],["\u1F80","\u1F87"],["\u1F90","\u1F97"],["\u1FA0","\u1FA7"],["\u1FB0","\u1FB4"],["\u1FB6","\u1FB7"],"\u1FBE",["\u1FC2","\u1FC4"],["\u1FC6","\u1FC7"],["\u1FD0","\u1FD3"],["\u1FD6","\u1FD7"],["\u1FE0","\u1FE7"],["\u1FF2","\u1FF4"],["\u1FF6","\u1FF7"],"\u210A",["\u210E","\u210F"],"\u2113","\u212F","\u2134","\u2139",["\u213C","\u213D"],["\u2146","\u2149"],"\u214E","\u2184",["\u2C30","\u2C5E"],"\u2C61",["\u2C65","\u2C66"],"\u2C68","\u2C6A","\u2C6C","\u2C71",["\u2C73","\u2C74"],["\u2C76","\u2C7B"],"\u2C81","\u2C83","\u2C85","\u2C87","\u2C89","\u2C8B","\u2C8D","\u2C8F","\u2C91","\u2C93","\u2C95","\u2C97","\u2C99","\u2C9B","\u2C9D","\u2C9F","\u2CA1","\u2CA3","\u2CA5","\u2CA7","\u2CA9","\u2CAB","\u2CAD","\u2CAF","\u2CB1","\u2CB3","\u2CB5","\u2CB7","\u2CB9","\u2CBB","\u2CBD","\u2CBF","\u2CC1","\u2CC3","\u2CC5","\u2CC7","\u2CC9","\u2CCB","\u2CCD","\u2CCF","\u2CD1","\u2CD3","\u2CD5","\u2CD7","\u2CD9","\u2CDB","\u2CDD","\u2CDF","\u2CE1",["\u2CE3","\u2CE4"],"\u2CEC","\u2CEE","\u2CF3",["\u2D00","\u2D25"],"\u2D27","\u2D2D","\uA641","\uA643","\uA645","\uA647","\uA649","\uA64B","\uA64D","\uA64F","\uA651","\uA653","\uA655","\uA657","\uA659","\uA65B","\uA65D","\uA65F","\uA661","\uA663","\uA665","\uA667","\uA669","\uA66B","\uA66D","\uA681","\uA683","\uA685","\uA687","\uA689","\uA68B","\uA68D","\uA68F","\uA691","\uA693","\uA695","\uA697","\uA723","\uA725","\uA727","\uA729","\uA72B","\uA72D",["\uA72F","\uA731"],"\uA733","\uA735","\uA737","\uA739","\uA73B","\uA73D","\uA73F","\uA741","\uA743","\uA745","\uA747","\uA749","\uA74B","\uA74D","\uA74F","\uA751","\uA753","\uA755","\uA757","\uA759","\uA75B","\uA75D","\uA75F","\uA761","\uA763","\uA765","\uA767","\uA769","\uA76B","\uA76D","\uA76F",["\uA771","\uA778"],"\uA77A","\uA77C","\uA77F","\uA781","\uA783","\uA785","\uA787","\uA78C","\uA78E","\uA791","\uA793","\uA7A1","\uA7A3","\uA7A5","\uA7A7","\uA7A9","\uA7FA",["\uFB00","\uFB06"],["\uFB13","\uFB17"],["\uFF41","\uFF5A"]],!1,!1),br=/^[\u02B0-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0374\u037A\u0559\u0640\u06E5-\u06E6\u07F4-\u07F5\u07FA\u081A\u0824\u0828\u0971\u0E46\u0EC6\u10FC\u17D7\u1843\u1AA7\u1C78-\u1C7D\u1D2C-\u1D6A\u1D78\u1D9B-\u1DBF\u2071\u207F\u2090-\u209C\u2C7C-\u2C7D\u2D6F\u2E2F\u3005\u3031-\u3035\u303B\u309D-\u309E\u30FC-\u30FE\uA015\uA4F8-\uA4FD\uA60C\uA67F\uA717-\uA71F\uA770\uA788\uA7F8-\uA7F9\uA9CF\uAA70\uAADD\uAAF3-\uAAF4\uFF70\uFF9E-\uFF9F]/,co=Ye([["\u02B0","\u02C1"],["\u02C6","\u02D1"],["\u02E0","\u02E4"],"\u02EC","\u02EE","\u0374","\u037A","\u0559","\u0640",["\u06E5","\u06E6"],["\u07F4","\u07F5"],"\u07FA","\u081A","\u0824","\u0828","\u0971","\u0E46","\u0EC6","\u10FC","\u17D7","\u1843","\u1AA7",["\u1C78","\u1C7D"],["\u1D2C","\u1D6A"],"\u1D78",["\u1D9B","\u1DBF"],"\u2071","\u207F",["\u2090","\u209C"],["\u2C7C","\u2C7D"],"\u2D6F","\u2E2F","\u3005",["\u3031","\u3035"],"\u303B",["\u309D","\u309E"],["\u30FC","\u30FE"],"\uA015",["\uA4F8","\uA4FD"],"\uA60C","\uA67F",["\uA717","\uA71F"],"\uA770","\uA788",["\uA7F8","\uA7F9"],"\uA9CF","\uAA70","\uAADD",["\uAAF3","\uAAF4"],"\uFF70",["\uFF9E","\uFF9F"]],!1,!1),vi=/^[\xAA\xBA\u01BB\u01C0-\u01C3\u0294\u05D0-\u05EA\u05F0-\u05F2\u0620-\u063F\u0641-\u064A\u066E-\u066F\u0671-\u06D3\u06D5\u06EE-\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u0800-\u0815\u0840-\u0858\u08A0\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0972-\u0977\u0979-\u097F\u0985-\u098C\u098F-\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC-\u09DD\u09DF-\u09E1\u09F0-\u09F1\u0A05-\u0A0A\u0A0F-\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32-\u0A33\u0A35-\u0A36\u0A38-\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2-\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0-\u0AE1\u0B05-\u0B0C\u0B0F-\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32-\u0B33\u0B35-\u0B39\u0B3D\u0B5C-\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99-\u0B9A\u0B9C\u0B9E-\u0B9F\u0BA3-\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D\u0C58-\u0C59\u0C60-\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0-\u0CE1\u0CF1-\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32-\u0E33\u0E40-\u0E45\u0E81-\u0E82\u0E84\u0E87-\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA-\u0EAB\u0EAD-\u0EB0\u0EB2-\u0EB3\u0EBD\u0EC0-\u0EC4\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065-\u1066\u106E-\u1070\u1075-\u1081\u108E\u10D0-\u10FA\u10FD-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17DC\u1820-\u1842\u1844-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE-\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C77\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5-\u1CF6\u2135-\u2138\u2D30-\u2D67\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3006\u303C\u3041-\u3096\u309F\u30A1-\u30FA\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA014\uA016-\uA48C\uA4D0-\uA4F7\uA500-\uA60B\uA610-\uA61F\uA62A-\uA62B\uA66E\uA6A0-\uA6E5\uA7FB-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA6F\uAA71-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5-\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADC\uAAE0-\uAAEA\uAAF2\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40-\uFB41\uFB43-\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF66-\uFF6F\uFF71-\uFF9D\uFFA0-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,_i=Ye(["\xAA","\xBA","\u01BB",["\u01C0","\u01C3"],"\u0294",["\u05D0","\u05EA"],["\u05F0","\u05F2"],["\u0620","\u063F"],["\u0641","\u064A"],["\u066E","\u066F"],["\u0671","\u06D3"],"\u06D5",["\u06EE","\u06EF"],["\u06FA","\u06FC"],"\u06FF","\u0710",["\u0712","\u072F"],["\u074D","\u07A5"],"\u07B1",["\u07CA","\u07EA"],["\u0800","\u0815"],["\u0840","\u0858"],"\u08A0",["\u08A2","\u08AC"],["\u0904","\u0939"],"\u093D","\u0950",["\u0958","\u0961"],["\u0972","\u0977"],["\u0979","\u097F"],["\u0985","\u098C"],["\u098F","\u0990"],["\u0993","\u09A8"],["\u09AA","\u09B0"],"\u09B2",["\u09B6","\u09B9"],"\u09BD","\u09CE",["\u09DC","\u09DD"],["\u09DF","\u09E1"],["\u09F0","\u09F1"],["\u0A05","\u0A0A"],["\u0A0F","\u0A10"],["\u0A13","\u0A28"],["\u0A2A","\u0A30"],["\u0A32","\u0A33"],["\u0A35","\u0A36"],["\u0A38","\u0A39"],["\u0A59","\u0A5C"],"\u0A5E",["\u0A72","\u0A74"],["\u0A85","\u0A8D"],["\u0A8F","\u0A91"],["\u0A93","\u0AA8"],["\u0AAA","\u0AB0"],["\u0AB2","\u0AB3"],["\u0AB5","\u0AB9"],"\u0ABD","\u0AD0",["\u0AE0","\u0AE1"],["\u0B05","\u0B0C"],["\u0B0F","\u0B10"],["\u0B13","\u0B28"],["\u0B2A","\u0B30"],["\u0B32","\u0B33"],["\u0B35","\u0B39"],"\u0B3D",["\u0B5C","\u0B5D"],["\u0B5F","\u0B61"],"\u0B71","\u0B83",["\u0B85","\u0B8A"],["\u0B8E","\u0B90"],["\u0B92","\u0B95"],["\u0B99","\u0B9A"],"\u0B9C",["\u0B9E","\u0B9F"],["\u0BA3","\u0BA4"],["\u0BA8","\u0BAA"],["\u0BAE","\u0BB9"],"\u0BD0",["\u0C05","\u0C0C"],["\u0C0E","\u0C10"],["\u0C12","\u0C28"],["\u0C2A","\u0C33"],["\u0C35","\u0C39"],"\u0C3D",["\u0C58","\u0C59"],["\u0C60","\u0C61"],["\u0C85","\u0C8C"],["\u0C8E","\u0C90"],["\u0C92","\u0CA8"],["\u0CAA","\u0CB3"],["\u0CB5","\u0CB9"],"\u0CBD","\u0CDE",["\u0CE0","\u0CE1"],["\u0CF1","\u0CF2"],["\u0D05","\u0D0C"],["\u0D0E","\u0D10"],["\u0D12","\u0D3A"],"\u0D3D","\u0D4E",["\u0D60","\u0D61"],["\u0D7A","\u0D7F"],["\u0D85","\u0D96"],["\u0D9A","\u0DB1"],["\u0DB3","\u0DBB"],"\u0DBD",["\u0DC0","\u0DC6"],["\u0E01","\u0E30"],["\u0E32","\u0E33"],["\u0E40","\u0E45"],["\u0E81","\u0E82"],"\u0E84",["\u0E87","\u0E88"],"\u0E8A","\u0E8D",["\u0E94","\u0E97"],["\u0E99","\u0E9F"],["\u0EA1","\u0EA3"],"\u0EA5","\u0EA7",["\u0EAA","\u0EAB"],["\u0EAD","\u0EB0"],["\u0EB2","\u0EB3"],"\u0EBD",["\u0EC0","\u0EC4"],["\u0EDC","\u0EDF"],"\u0F00",["\u0F40","\u0F47"],["\u0F49","\u0F6C"],["\u0F88","\u0F8C"],["\u1000","\u102A"],"\u103F",["\u1050","\u1055"],["\u105A","\u105D"],"\u1061",["\u1065","\u1066"],["\u106E","\u1070"],["\u1075","\u1081"],"\u108E",["\u10D0","\u10FA"],["\u10FD","\u1248"],["\u124A","\u124D"],["\u1250","\u1256"],"\u1258",["\u125A","\u125D"],["\u1260","\u1288"],["\u128A","\u128D"],["\u1290","\u12B0"],["\u12B2","\u12B5"],["\u12B8","\u12BE"],"\u12C0",["\u12C2","\u12C5"],["\u12C8","\u12D6"],["\u12D8","\u1310"],["\u1312","\u1315"],["\u1318","\u135A"],["\u1380","\u138F"],["\u13A0","\u13F4"],["\u1401","\u166C"],["\u166F","\u167F"],["\u1681","\u169A"],["\u16A0","\u16EA"],["\u1700","\u170C"],["\u170E","\u1711"],["\u1720","\u1731"],["\u1740","\u1751"],["\u1760","\u176C"],["\u176E","\u1770"],["\u1780","\u17B3"],"\u17DC",["\u1820","\u1842"],["\u1844","\u1877"],["\u1880","\u18A8"],"\u18AA",["\u18B0","\u18F5"],["\u1900","\u191C"],["\u1950","\u196D"],["\u1970","\u1974"],["\u1980","\u19AB"],["\u19C1","\u19C7"],["\u1A00","\u1A16"],["\u1A20","\u1A54"],["\u1B05","\u1B33"],["\u1B45","\u1B4B"],["\u1B83","\u1BA0"],["\u1BAE","\u1BAF"],["\u1BBA","\u1BE5"],["\u1C00","\u1C23"],["\u1C4D","\u1C4F"],["\u1C5A","\u1C77"],["\u1CE9","\u1CEC"],["\u1CEE","\u1CF1"],["\u1CF5","\u1CF6"],["\u2135","\u2138"],["\u2D30","\u2D67"],["\u2D80","\u2D96"],["\u2DA0","\u2DA6"],["\u2DA8","\u2DAE"],["\u2DB0","\u2DB6"],["\u2DB8","\u2DBE"],["\u2DC0","\u2DC6"],["\u2DC8","\u2DCE"],["\u2DD0","\u2DD6"],["\u2DD8","\u2DDE"],"\u3006","\u303C",["\u3041","\u3096"],"\u309F",["\u30A1","\u30FA"],"\u30FF",["\u3105","\u312D"],["\u3131","\u318E"],["\u31A0","\u31BA"],["\u31F0","\u31FF"],["\u3400","\u4DB5"],["\u4E00","\u9FCC"],["\uA000","\uA014"],["\uA016","\uA48C"],["\uA4D0","\uA4F7"],["\uA500","\uA60B"],["\uA610","\uA61F"],["\uA62A","\uA62B"],"\uA66E",["\uA6A0","\uA6E5"],["\uA7FB","\uA801"],["\uA803","\uA805"],["\uA807","\uA80A"],["\uA80C","\uA822"],["\uA840","\uA873"],["\uA882","\uA8B3"],["\uA8F2","\uA8F7"],"\uA8FB",["\uA90A","\uA925"],["\uA930","\uA946"],["\uA960","\uA97C"],["\uA984","\uA9B2"],["\uAA00","\uAA28"],["\uAA40","\uAA42"],["\uAA44","\uAA4B"],["\uAA60","\uAA6F"],["\uAA71","\uAA76"],"\uAA7A",["\uAA80","\uAAAF"],"\uAAB1",["\uAAB5","\uAAB6"],["\uAAB9","\uAABD"],"\uAAC0","\uAAC2",["\uAADB","\uAADC"],["\uAAE0","\uAAEA"],"\uAAF2",["\uAB01","\uAB06"],["\uAB09","\uAB0E"],["\uAB11","\uAB16"],["\uAB20","\uAB26"],["\uAB28","\uAB2E"],["\uABC0","\uABE2"],["\uAC00","\uD7A3"],["\uD7B0","\uD7C6"],["\uD7CB","\uD7FB"],["\uF900","\uFA6D"],["\uFA70","\uFAD9"],"\uFB1D",["\uFB1F","\uFB28"],["\uFB2A","\uFB36"],["\uFB38","\uFB3C"],"\uFB3E",["\uFB40","\uFB41"],["\uFB43","\uFB44"],["\uFB46","\uFBB1"],["\uFBD3","\uFD3D"],["\uFD50","\uFD8F"],["\uFD92","\uFDC7"],["\uFDF0","\uFDFB"],["\uFE70","\uFE74"],["\uFE76","\uFEFC"],["\uFF66","\uFF6F"],["\uFF71","\uFF9D"],["\uFFA0","\uFFBE"],["\uFFC2","\uFFC7"],["\uFFCA","\uFFCF"],["\uFFD2","\uFFD7"],["\uFFDA","\uFFDC"]],!1,!1),Wn=/^[\u01C5\u01C8\u01CB\u01F2\u1F88-\u1F8F\u1F98-\u1F9F\u1FA8-\u1FAF\u1FBC\u1FCC\u1FFC]/,nn=Ye(["\u01C5","\u01C8","\u01CB","\u01F2",["\u1F88","\u1F8F"],["\u1F98","\u1F9F"],["\u1FA8","\u1FAF"],"\u1FBC","\u1FCC","\u1FFC"],!1,!1),Ar=/^[A-Z\xC0-\xD6\xD8-\xDE\u0100\u0102\u0104\u0106\u0108\u010A\u010C\u010E\u0110\u0112\u0114\u0116\u0118\u011A\u011C\u011E\u0120\u0122\u0124\u0126\u0128\u012A\u012C\u012E\u0130\u0132\u0134\u0136\u0139\u013B\u013D\u013F\u0141\u0143\u0145\u0147\u014A\u014C\u014E\u0150\u0152\u0154\u0156\u0158\u015A\u015C\u015E\u0160\u0162\u0164\u0166\u0168\u016A\u016C\u016E\u0170\u0172\u0174\u0176\u0178-\u0179\u017B\u017D\u0181-\u0182\u0184\u0186-\u0187\u0189-\u018B\u018E-\u0191\u0193-\u0194\u0196-\u0198\u019C-\u019D\u019F-\u01A0\u01A2\u01A4\u01A6-\u01A7\u01A9\u01AC\u01AE-\u01AF\u01B1-\u01B3\u01B5\u01B7-\u01B8\u01BC\u01C4\u01C7\u01CA\u01CD\u01CF\u01D1\u01D3\u01D5\u01D7\u01D9\u01DB\u01DE\u01E0\u01E2\u01E4\u01E6\u01E8\u01EA\u01EC\u01EE\u01F1\u01F4\u01F6-\u01F8\u01FA\u01FC\u01FE\u0200\u0202\u0204\u0206\u0208\u020A\u020C\u020E\u0210\u0212\u0214\u0216\u0218\u021A\u021C\u021E\u0220\u0222\u0224\u0226\u0228\u022A\u022C\u022E\u0230\u0232\u023A-\u023B\u023D-\u023E\u0241\u0243-\u0246\u0248\u024A\u024C\u024E\u0370\u0372\u0376\u0386\u0388-\u038A\u038C\u038E-\u038F\u0391-\u03A1\u03A3-\u03AB\u03CF\u03D2-\u03D4\u03D8\u03DA\u03DC\u03DE\u03E0\u03E2\u03E4\u03E6\u03E8\u03EA\u03EC\u03EE\u03F4\u03F7\u03F9-\u03FA\u03FD-\u042F\u0460\u0462\u0464\u0466\u0468\u046A\u046C\u046E\u0470\u0472\u0474\u0476\u0478\u047A\u047C\u047E\u0480\u048A\u048C\u048E\u0490\u0492\u0494\u0496\u0498\u049A\u049C\u049E\u04A0\u04A2\u04A4\u04A6\u04A8\u04AA\u04AC\u04AE\u04B0\u04B2\u04B4\u04B6\u04B8\u04BA\u04BC\u04BE\u04C0-\u04C1\u04C3\u04C5\u04C7\u04C9\u04CB\u04CD\u04D0\u04D2\u04D4\u04D6\u04D8\u04DA\u04DC\u04DE\u04E0\u04E2\u04E4\u04E6\u04E8\u04EA\u04EC\u04EE\u04F0\u04F2\u04F4\u04F6\u04F8\u04FA\u04FC\u04FE\u0500\u0502\u0504\u0506\u0508\u050A\u050C\u050E\u0510\u0512\u0514\u0516\u0518\u051A\u051C\u051E\u0520\u0522\u0524\u0526\u0531-\u0556\u10A0-\u10C5\u10C7\u10CD\u1E00\u1E02\u1E04\u1E06\u1E08\u1E0A\u1E0C\u1E0E\u1E10\u1E12\u1E14\u1E16\u1E18\u1E1A\u1E1C\u1E1E\u1E20\u1E22\u1E24\u1E26\u1E28\u1E2A\u1E2C\u1E2E\u1E30\u1E32\u1E34\u1E36\u1E38\u1E3A\u1E3C\u1E3E\u1E40\u1E42\u1E44\u1E46\u1E48\u1E4A\u1E4C\u1E4E\u1E50\u1E52\u1E54\u1E56\u1E58\u1E5A\u1E5C\u1E5E\u1E60\u1E62\u1E64\u1E66\u1E68\u1E6A\u1E6C\u1E6E\u1E70\u1E72\u1E74\u1E76\u1E78\u1E7A\u1E7C\u1E7E\u1E80\u1E82\u1E84\u1E86\u1E88\u1E8A\u1E8C\u1E8E\u1E90\u1E92\u1E94\u1E9E\u1EA0\u1EA2\u1EA4\u1EA6\u1EA8\u1EAA\u1EAC\u1EAE\u1EB0\u1EB2\u1EB4\u1EB6\u1EB8\u1EBA\u1EBC\u1EBE\u1EC0\u1EC2\u1EC4\u1EC6\u1EC8\u1ECA\u1ECC\u1ECE\u1ED0\u1ED2\u1ED4\u1ED6\u1ED8\u1EDA\u1EDC\u1EDE\u1EE0\u1EE2\u1EE4\u1EE6\u1EE8\u1EEA\u1EEC\u1EEE\u1EF0\u1EF2\u1EF4\u1EF6\u1EF8\u1EFA\u1EFC\u1EFE\u1F08-\u1F0F\u1F18-\u1F1D\u1F28-\u1F2F\u1F38-\u1F3F\u1F48-\u1F4D\u1F59\u1F5B\u1F5D\u1F5F\u1F68-\u1F6F\u1FB8-\u1FBB\u1FC8-\u1FCB\u1FD8-\u1FDB\u1FE8-\u1FEC\u1FF8-\u1FFB\u2102\u2107\u210B-\u210D\u2110-\u2112\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u2130-\u2133\u213E-\u213F\u2145\u2183\u2C00-\u2C2E\u2C60\u2C62-\u2C64\u2C67\u2C69\u2C6B\u2C6D-\u2C70\u2C72\u2C75\u2C7E-\u2C80\u2C82\u2C84\u2C86\u2C88\u2C8A\u2C8C\u2C8E\u2C90\u2C92\u2C94\u2C96\u2C98\u2C9A\u2C9C\u2C9E\u2CA0\u2CA2\u2CA4\u2CA6\u2CA8\u2CAA\u2CAC\u2CAE\u2CB0\u2CB2\u2CB4\u2CB6\u2CB8\u2CBA\u2CBC\u2CBE\u2CC0\u2CC2\u2CC4\u2CC6\u2CC8\u2CCA\u2CCC\u2CCE\u2CD0\u2CD2\u2CD4\u2CD6\u2CD8\u2CDA\u2CDC\u2CDE\u2CE0\u2CE2\u2CEB\u2CED\u2CF2\uA640\uA642\uA644\uA646\uA648\uA64A\uA64C\uA64E\uA650\uA652\uA654\uA656\uA658\uA65A\uA65C\uA65E\uA660\uA662\uA664\uA666\uA668\uA66A\uA66C\uA680\uA682\uA684\uA686\uA688\uA68A\uA68C\uA68E\uA690\uA692\uA694\uA696\uA722\uA724\uA726\uA728\uA72A\uA72C\uA72E\uA732\uA734\uA736\uA738\uA73A\uA73C\uA73E\uA740\uA742\uA744\uA746\uA748\uA74A\uA74C\uA74E\uA750\uA752\uA754\uA756\uA758\uA75A\uA75C\uA75E\uA760\uA762\uA764\uA766\uA768\uA76A\uA76C\uA76E\uA779\uA77B\uA77D-\uA77E\uA780\uA782\uA784\uA786\uA78B\uA78D\uA790\uA792\uA7A0\uA7A2\uA7A4\uA7A6\uA7A8\uA7AA\uFF21-\uFF3A]/,wr=Ye([["A","Z"],["\xC0","\xD6"],["\xD8","\xDE"],"\u0100","\u0102","\u0104","\u0106","\u0108","\u010A","\u010C","\u010E","\u0110","\u0112","\u0114","\u0116","\u0118","\u011A","\u011C","\u011E","\u0120","\u0122","\u0124","\u0126","\u0128","\u012A","\u012C","\u012E","\u0130","\u0132","\u0134","\u0136","\u0139","\u013B","\u013D","\u013F","\u0141","\u0143","\u0145","\u0147","\u014A","\u014C","\u014E","\u0150","\u0152","\u0154","\u0156","\u0158","\u015A","\u015C","\u015E","\u0160","\u0162","\u0164","\u0166","\u0168","\u016A","\u016C","\u016E","\u0170","\u0172","\u0174","\u0176",["\u0178","\u0179"],"\u017B","\u017D",["\u0181","\u0182"],"\u0184",["\u0186","\u0187"],["\u0189","\u018B"],["\u018E","\u0191"],["\u0193","\u0194"],["\u0196","\u0198"],["\u019C","\u019D"],["\u019F","\u01A0"],"\u01A2","\u01A4",["\u01A6","\u01A7"],"\u01A9","\u01AC",["\u01AE","\u01AF"],["\u01B1","\u01B3"],"\u01B5",["\u01B7","\u01B8"],"\u01BC","\u01C4","\u01C7","\u01CA","\u01CD","\u01CF","\u01D1","\u01D3","\u01D5","\u01D7","\u01D9","\u01DB","\u01DE","\u01E0","\u01E2","\u01E4","\u01E6","\u01E8","\u01EA","\u01EC","\u01EE","\u01F1","\u01F4",["\u01F6","\u01F8"],"\u01FA","\u01FC","\u01FE","\u0200","\u0202","\u0204","\u0206","\u0208","\u020A","\u020C","\u020E","\u0210","\u0212","\u0214","\u0216","\u0218","\u021A","\u021C","\u021E","\u0220","\u0222","\u0224","\u0226","\u0228","\u022A","\u022C","\u022E","\u0230","\u0232",["\u023A","\u023B"],["\u023D","\u023E"],"\u0241",["\u0243","\u0246"],"\u0248","\u024A","\u024C","\u024E","\u0370","\u0372","\u0376","\u0386",["\u0388","\u038A"],"\u038C",["\u038E","\u038F"],["\u0391","\u03A1"],["\u03A3","\u03AB"],"\u03CF",["\u03D2","\u03D4"],"\u03D8","\u03DA","\u03DC","\u03DE","\u03E0","\u03E2","\u03E4","\u03E6","\u03E8","\u03EA","\u03EC","\u03EE","\u03F4","\u03F7",["\u03F9","\u03FA"],["\u03FD","\u042F"],"\u0460","\u0462","\u0464","\u0466","\u0468","\u046A","\u046C","\u046E","\u0470","\u0472","\u0474","\u0476","\u0478","\u047A","\u047C","\u047E","\u0480","\u048A","\u048C","\u048E","\u0490","\u0492","\u0494","\u0496","\u0498","\u049A","\u049C","\u049E","\u04A0","\u04A2","\u04A4","\u04A6","\u04A8","\u04AA","\u04AC","\u04AE","\u04B0","\u04B2","\u04B4","\u04B6","\u04B8","\u04BA","\u04BC","\u04BE",["\u04C0","\u04C1"],"\u04C3","\u04C5","\u04C7","\u04C9","\u04CB","\u04CD","\u04D0","\u04D2","\u04D4","\u04D6","\u04D8","\u04DA","\u04DC","\u04DE","\u04E0","\u04E2","\u04E4","\u04E6","\u04E8","\u04EA","\u04EC","\u04EE","\u04F0","\u04F2","\u04F4","\u04F6","\u04F8","\u04FA","\u04FC","\u04FE","\u0500","\u0502","\u0504","\u0506","\u0508","\u050A","\u050C","\u050E","\u0510","\u0512","\u0514","\u0516","\u0518","\u051A","\u051C","\u051E","\u0520","\u0522","\u0524","\u0526",["\u0531","\u0556"],["\u10A0","\u10C5"],"\u10C7","\u10CD","\u1E00","\u1E02","\u1E04","\u1E06","\u1E08","\u1E0A","\u1E0C","\u1E0E","\u1E10","\u1E12","\u1E14","\u1E16","\u1E18","\u1E1A","\u1E1C","\u1E1E","\u1E20","\u1E22","\u1E24","\u1E26","\u1E28","\u1E2A","\u1E2C","\u1E2E","\u1E30","\u1E32","\u1E34","\u1E36","\u1E38","\u1E3A","\u1E3C","\u1E3E","\u1E40","\u1E42","\u1E44","\u1E46","\u1E48","\u1E4A","\u1E4C","\u1E4E","\u1E50","\u1E52","\u1E54","\u1E56","\u1E58","\u1E5A","\u1E5C","\u1E5E","\u1E60","\u1E62","\u1E64","\u1E66","\u1E68","\u1E6A","\u1E6C","\u1E6E","\u1E70","\u1E72","\u1E74","\u1E76","\u1E78","\u1E7A","\u1E7C","\u1E7E","\u1E80","\u1E82","\u1E84","\u1E86","\u1E88","\u1E8A","\u1E8C","\u1E8E","\u1E90","\u1E92","\u1E94","\u1E9E","\u1EA0","\u1EA2","\u1EA4","\u1EA6","\u1EA8","\u1EAA","\u1EAC","\u1EAE","\u1EB0","\u1EB2","\u1EB4","\u1EB6","\u1EB8","\u1EBA","\u1EBC","\u1EBE","\u1EC0","\u1EC2","\u1EC4","\u1EC6","\u1EC8","\u1ECA","\u1ECC","\u1ECE","\u1ED0","\u1ED2","\u1ED4","\u1ED6","\u1ED8","\u1EDA","\u1EDC","\u1EDE","\u1EE0","\u1EE2","\u1EE4","\u1EE6","\u1EE8","\u1EEA","\u1EEC","\u1EEE","\u1EF0","\u1EF2","\u1EF4","\u1EF6","\u1EF8","\u1EFA","\u1EFC","\u1EFE",["\u1F08","\u1F0F"],["\u1F18","\u1F1D"],["\u1F28","\u1F2F"],["\u1F38","\u1F3F"],["\u1F48","\u1F4D"],"\u1F59","\u1F5B","\u1F5D","\u1F5F",["\u1F68","\u1F6F"],["\u1FB8","\u1FBB"],["\u1FC8","\u1FCB"],["\u1FD8","\u1FDB"],["\u1FE8","\u1FEC"],["\u1FF8","\u1FFB"],"\u2102","\u2107",["\u210B","\u210D"],["\u2110","\u2112"],"\u2115",["\u2119","\u211D"],"\u2124","\u2126","\u2128",["\u212A","\u212D"],["\u2130","\u2133"],["\u213E","\u213F"],"\u2145","\u2183",["\u2C00","\u2C2E"],"\u2C60",["\u2C62","\u2C64"],"\u2C67","\u2C69","\u2C6B",["\u2C6D","\u2C70"],"\u2C72","\u2C75",["\u2C7E","\u2C80"],"\u2C82","\u2C84","\u2C86","\u2C88","\u2C8A","\u2C8C","\u2C8E","\u2C90","\u2C92","\u2C94","\u2C96","\u2C98","\u2C9A","\u2C9C","\u2C9E","\u2CA0","\u2CA2","\u2CA4","\u2CA6","\u2CA8","\u2CAA","\u2CAC","\u2CAE","\u2CB0","\u2CB2","\u2CB4","\u2CB6","\u2CB8","\u2CBA","\u2CBC","\u2CBE","\u2CC0","\u2CC2","\u2CC4","\u2CC6","\u2CC8","\u2CCA","\u2CCC","\u2CCE","\u2CD0","\u2CD2","\u2CD4","\u2CD6","\u2CD8","\u2CDA","\u2CDC","\u2CDE","\u2CE0","\u2CE2","\u2CEB","\u2CED","\u2CF2","\uA640","\uA642","\uA644","\uA646","\uA648","\uA64A","\uA64C","\uA64E","\uA650","\uA652","\uA654","\uA656","\uA658","\uA65A","\uA65C","\uA65E","\uA660","\uA662","\uA664","\uA666","\uA668","\uA66A","\uA66C","\uA680","\uA682","\uA684","\uA686","\uA688","\uA68A","\uA68C","\uA68E","\uA690","\uA692","\uA694","\uA696","\uA722","\uA724","\uA726","\uA728","\uA72A","\uA72C","\uA72E","\uA732","\uA734","\uA736","\uA738","\uA73A","\uA73C","\uA73E","\uA740","\uA742","\uA744","\uA746","\uA748","\uA74A","\uA74C","\uA74E","\uA750","\uA752","\uA754","\uA756","\uA758","\uA75A","\uA75C","\uA75E","\uA760","\uA762","\uA764","\uA766","\uA768","\uA76A","\uA76C","\uA76E","\uA779","\uA77B",["\uA77D","\uA77E"],"\uA780","\uA782","\uA784","\uA786","\uA78B","\uA78D","\uA790","\uA792","\uA7A0","\uA7A2","\uA7A4","\uA7A6","\uA7A8","\uA7AA",["\uFF21","\uFF3A"]],!1,!1),Is=/^[\u16EE-\u16F0\u2160-\u2182\u2185-\u2188\u3007\u3021-\u3029\u3038-\u303A\uA6E6-\uA6EF]/,as=Ye([["\u16EE","\u16F0"],["\u2160","\u2182"],["\u2185","\u2188"],"\u3007",["\u3021","\u3029"],["\u3038","\u303A"],["\uA6E6","\uA6EF"]],!1,!1),go=/^[0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19]/,Ts=Ye([["0","9"],["\u0660","\u0669"],["\u06F0","\u06F9"],["\u07C0","\u07C9"],["\u0966","\u096F"],["\u09E6","\u09EF"],["\u0A66","\u0A6F"],["\u0AE6","\u0AEF"],["\u0B66","\u0B6F"],["\u0BE6","\u0BEF"],["\u0C66","\u0C6F"],["\u0CE6","\u0CEF"],["\u0D66","\u0D6F"],["\u0E50","\u0E59"],["\u0ED0","\u0ED9"],["\u0F20","\u0F29"],["\u1040","\u1049"],["\u1090","\u1099"],["\u17E0","\u17E9"],["\u1810","\u1819"],["\u1946","\u194F"],["\u19D0","\u19D9"],["\u1A80","\u1A89"],["\u1A90","\u1A99"],["\u1B50","\u1B59"],["\u1BB0","\u1BB9"],["\u1C40","\u1C49"],["\u1C50","\u1C59"],["\uA620","\uA629"],["\uA8D0","\uA8D9"],["\uA900","\uA909"],["\uA9D0","\uA9D9"],["\uAA50","\uAA59"],["\uABF0","\uABF9"],["\uFF10","\uFF19"]],!1,!1),P=0,ht=0,Mi=[{line:1,column:1}],Kt=0,Ge=[],R=0,ge;if("startRule"in C){if(!(C.startRule in W))throw new Error(`Can't start parsing from rule "`+C.startRule+'".');Dt=W[C.startRule]}function rn(){return O.substring(ht,P)}function Ii(){return on(ht,P)}function vr(p,y){throw y=y!==void 0?y:on(ht,P),Ti([oe(p)],O.substring(ht,P),y)}function fo(p,y){throw y=y!==void 0?y:on(ht,P),Ir(p,y)}function yt(p,y){return{type:"literal",text:p,ignoreCase:y}}function Ye(p,y,x){return{type:"class",parts:p,inverted:y,ignoreCase:x}}function Me(){return{type:"any"}}function Ae(){return{type:"end"}}function oe(p){return{type:"other",description:p}}function po(p){var y=Mi[p],x;if(y)return y;for(x=p-1;!Mi[x];)x--;for(y=Mi[x],y={line:y.line,column:y.column};x<p;)O.charCodeAt(x)===10?(y.line++,y.column=1):y.column++,x++;return Mi[p]=y,y}function on(p,y){var x=po(p),T=po(y);return{start:{offset:p,line:x.line,column:x.column},end:{offset:y,line:T.line,column:T.column}}}function U(p){P<Kt||(P>Kt&&(Kt=P,Ge=[]),Ge.push(p))}function Ir(p,y){return new Tt(p,null,null,y)}function Ti(p,y,x){return new Tt(Tt.buildMessage(p,y),p,y,x)}function an(){var p,y;if(p=[],y=ts(),y!==f)for(;y!==f;)p.push(y),y=ts();else p=f;return p}function ts(){var p,y,x,T,M,$,lt,te,ee,ri,xe,Lr,xo;return p=P,y=Pt(),y!==f?(O.substr(P,6).toLowerCase()===xt?(x=O.substr(P,6),P+=6):(x=f,R===0&&U(N)),x===f&&(x=null),x!==f?(T=Pt(),T!==f?(O.substr(P,5).toLowerCase()===z?(M=O.substr(P,5),P+=5):(M=f,R===0&&U(et)),M===f&&(O.substr(P,7).toLowerCase()===_?(M=O.substr(P,7),P+=7):(M=f,R===0&&U(k))),M!==f?($=Pt(),$!==f?(lt=Ke(),lt===f&&(lt=null),lt!==f?(te=Pt(),te!==f?(O.charCodeAt(P)===123?(ee=tt,P++):(ee=f,R===0&&U(d)),ee!==f?(ri=xs(),ri===f&&(ri=null),ri!==f?(xe=Pt(),xe!==f?(O.charCodeAt(P)===125?(Lr=qt,P++):(Lr=f,R===0&&U(Re)),Lr!==f?(xo=Pt(),xo!==f?(ht=p,y=At(x,M,lt,ri),p=y):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function xs(){var p,y,x,T,M,$,lt,te,ee,ri,xe;if(p=P,y=Pt(),y!==f)if(x=Os(),x!==f)if(T=Pt(),T!==f)if(O.charCodeAt(P)===59?(M=ps,P++):(M=f,R===0&&U(D)),M===f&&(M=null),M!==f){for($=[],lt=P,te=Pt(),te!==f?(ee=Os(),ee!==f?(ri=Pt(),ri!==f?(O.charCodeAt(P)===59?(xe=ps,P++):(xe=f,R===0&&U(D)),xe===f&&(xe=null),xe!==f?(ht=lt,te=Ri(x,ee),lt=te):(P=lt,lt=f)):(P=lt,lt=f)):(P=lt,lt=f)):(P=lt,lt=f);lt!==f;)$.push(lt),lt=P,te=Pt(),te!==f?(ee=Os(),ee!==f?(ri=Pt(),ri!==f?(O.charCodeAt(P)===59?(xe=ps,P++):(xe=f,R===0&&U(D)),xe===f&&(xe=null),xe!==f?(ht=lt,te=Ri(x,ee),lt=te):(P=lt,lt=f)):(P=lt,lt=f)):(P=lt,lt=f)):(P=lt,lt=f);$!==f?(ht=p,y=On(x,$),p=y):(P=p,p=f)}else P=p,p=f;else P=p,p=f;else P=p,p=f;else P=p,p=f;return p}function Os(){var p,y,x,T,M,$;return p=P,y=Ke(),y!==f?(x=Pt(),x!==f?(O.charCodeAt(P)===61?(T=Di,P++):(T=f,R===0&&U(jt)),T!==f?(M=Pt(),M!==f?($=Ke(),$!==f?(ht=p,y=Ei(y,$),p=y):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p===f&&(p=ls(),p===f&&(p=Po(),p===f&&(p=Ot(),p===f&&(p=So(),p===f&&(p=P,y=Ke(),y!==f?(O.charCodeAt(P)===61?(x=Di,P++):(x=f,R===0&&U(jt)),x!==f?(T=Ke(),T!==f?(y=[y,x,T],p=y):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)))))),p}function ls(){var p,y,x;return p=P,O.substr(P,5).toLowerCase()===z?(y=O.substr(P,5),P+=5):(y=f,R===0&&U(et)),y===f&&(O.substr(P,4).toLowerCase()===ms?(y=O.substr(P,4),P+=4):(y=f,R===0&&U(vt)),y===f&&(O.substr(P,4).toLowerCase()===Ln?(y=O.substr(P,4),P+=4):(y=f,R===0&&U(Nt)))),y!==f?(x=Vi(),x!==f?(ht=p,y=hr(y,x),p=y):(P=p,p=f)):(P=p,p=f),p}function Vi(){var p,y,x,T,M,$,lt,te,ee;return p=P,y=Pt(),y!==f?(O.charCodeAt(P)===91?(x=Xs,P++):(x=f,R===0&&U(Qs)),x!==f?(T=Pt(),T!==f?(M=mo(),M===f&&(M=null),M!==f?($=Pt(),$!==f?(O.charCodeAt(P)===93?(lt=Bn,P++):(lt=f,R===0&&U(ft)),lt!==f?(te=Pt(),te!==f?(ee=Vi(),ee===f&&(ee=null),ee!==f?(ht=p,y=ur(M,ee),p=y):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function mo(){var p,y,x,T,M,$,lt,te;return p=P,y=Pt(),y!==f?(x=Ke(),x!==f?(T=P,M=Pt(),M!==f?(O.charCodeAt(P)===61?($=Di,P++):($=f,R===0&&U(jt)),$!==f?(lt=Pt(),lt!==f?(te=Ke(),te!==f?(ht=T,M=w(x,te),T=M):(P=T,T=f)):(P=T,T=f)):(P=T,T=f)):(P=T,T=f),T===f&&(T=null),T!==f?(M=Pt(),M!==f?(O.charCodeAt(P)===44?($=Ni,P++):($=f,R===0&&U(Ys)),$===f&&(O.charCodeAt(P)===59?($=ps,P++):($=f,R===0&&U(D))),$===f&&($=null),$!==f?(lt=mo(),lt===f&&(lt=null),lt!==f?(ht=p,y=_r(x,T,lt),p=y):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function Po(){var p,y,x,T;return p=P,y=Ot(),y===f&&(y=ni()),y!==f?(x=ln(),x!==f?(T=Vi(),T===f&&(T=null),T!==f?(ht=p,y=to(y,x,T),p=y):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function ln(){var p,y,x,T,M,$,lt;return p=P,y=Pt(),y!==f?(O.substr(P,2)===cr?(x=cr,P+=2):(x=f,R===0&&U(Fn)),x===f&&(O.substr(P,2)===at?(x=at,P+=2):(x=f,R===0&&U(De))),x!==f?(T=Pt(),T!==f?(M=Ot(),M===f&&(M=ni()),M!==f?($=Pt(),$!==f?(lt=ln(),lt===f&&(lt=null),lt!==f?(ht=p,y=Z(x,M,lt),p=y):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function So(){var p,y,x;return p=P,y=ni(),y!==f?(x=Vi(),x===f&&(x=null),x!==f?(ht=p,y=Ut(y,x),p=y):(P=p,p=f)):(P=p,p=f),p}function ni(){var p,y,x;return p=P,y=Ke(),y!==f?(x=Ie(),x===f&&(x=null),x!==f?(ht=p,y=G(y,x),p=y):(P=p,p=f)):(P=p,p=f),p}function Ie(){var p,y,x,T,M,$;return R++,p=P,O.charCodeAt(P)===58?(y=H,P++):(y=f,R===0&&U(K)),y!==f?(x=Ke(),x!==f?(T=P,O.charCodeAt(P)===58?(M=H,P++):(M=f,R===0&&U(K)),M!==f?($=ye(),$!==f?(ht=T,M=nt(x,$),T=M):(P=T,T=f)):(P=T,T=f),T===f&&(T=null),T!==f?(ht=p,y=Y(x,T),p=y):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p===f&&(p=P,O.charCodeAt(P)===58?(y=H,P++):(y=f,R===0&&U(K)),y!==f?(x=ye(),x!==f?(ht=p,y=ot(x),p=y):(P=p,p=f)):(P=p,p=f)),R--,p===f&&(y=f,R===0&&U(st)),p}function Ot(){var p,y,x,T,M,$;return p=P,y=P,O.substr(P,8).toLowerCase()===v?(x=O.substr(P,8),P+=8):(x=f,R===0&&U(L)),x!==f?(T=Pt(),T!==f?(M=Ke(),M===f&&(M=null),M!==f?($=Pt(),$!==f?(ht=y,x=j(M),y=x):(P=y,y=f)):(P=y,y=f)):(P=y,y=f)):(P=y,y=f),y===f&&(y=null),y!==f?(O.charCodeAt(P)===123?(x=tt,P++):(x=f,R===0&&U(d)),x!==f?(T=xs(),T===f&&(T=null),T!==f?(M=Pt(),M!==f?(O.charCodeAt(P)===125?($=qt,P++):($=f,R===0&&U(Re)),$!==f?(ht=p,y=Ks(y,T),p=y):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f)):(P=p,p=f),p}function ye(){var p;return O.charCodeAt(P)===110?(p=Ne,P++):(p=f,R===0&&U(ta)),p===f&&(O.substr(P,2)===Yt?(p=Yt,P+=2):(p=f,R===0&&U($t)),p===f&&(O.charCodeAt(P)===101?(p=ea,P++):(p=f,R===0&&U(re)),p===f&&(O.substr(P,2)===dr?(p=dr,P+=2):(p=f,R===0&&U(ia)),p===f&&(O.charCodeAt(P)===115?(p=Rn,P++):(p=f,R===0&&U(eo)),p===f&&(O.substr(P,2)===pe?(p=pe,P+=2):(p=f,R===0&&U(gr)),p===f&&(O.charCodeAt(P)===119?(p=fr,P++):(p=f,R===0&&U(ve)),p===f&&(O.substr(P,2)===ie?(p=ie,P+=2):(p=f,R===0&&U(Ps))))))))),p}function Ke(){var p;return p=yo(),p===f&&(p=Hn(),p===f&&(p=Co(),p===f&&(p=es(),p===f&&(p=Tr())))),p}function yo(){var p,y,x,T;if(R++,p=P,y=Te(),y!==f){for(x=[],T=mt();T!==f;)x.push(T),T=mt();x!==f?(ht=p,y=Ss(y,x),p=y):(P=p,p=f)}else P=p,p=f;return R--,p===f&&(y=f,R===0&&U(sa)),p}function Hn(){var p,y,x;return p=P,y=Co(),y!==f?(x=yo(),x!==f?(ht=p,y=Ki(y,x),p=y):(P=p,p=f)):(P=p,p=f),p}function Te(){var p;return p=vo(),p===f&&(O.charCodeAt(P)===36?(p=Ji,P++):(p=f,R===0&&U(na)),p===f&&(O.charCodeAt(P)===95?(p=Js,P++):(p=f,R===0&&U(Dn)))),p}function mt(){var p;return p=Te(),p===f&&(p=qi()),p}function Co(){var p,y,x,T,M,$,lt,te,ee;if(R++,p=P,y=P,O.charCodeAt(P)===45?(x=Nn,P++):(x=f,R===0&&U(ys)),x===f&&(x=null),x!==f){if(T=P,O.charCodeAt(P)===46?(M=pr,P++):(M=f,R===0&&U(io)),M!==f){if($=[],Cs.test(O.charAt(P))?(lt=O.charAt(P),P++):(lt=f,R===0&&U(ns)),lt!==f)for(;lt!==f;)$.push(lt),Cs.test(O.charAt(P))?(lt=O.charAt(P),P++):(lt=f,R===0&&U(ns));else $=f;$!==f?(M=[M,$],T=M):(P=T,T=f)}else P=T,T=f;if(T===f){if(T=P,M=[],Cs.test(O.charAt(P))?($=O.charAt(P),P++):($=f,R===0&&U(ns)),$!==f)for(;$!==f;)M.push($),Cs.test(O.charAt(P))?($=O.charAt(P),P++):($=f,R===0&&U(ns));else M=f;if(M!==f){if($=P,O.charCodeAt(P)===46?(lt=pr,P++):(lt=f,R===0&&U(io)),lt!==f){for(te=[],Cs.test(O.charAt(P))?(ee=O.charAt(P),P++):(ee=f,R===0&&U(ns));ee!==f;)te.push(ee),Cs.test(O.charAt(P))?(ee=O.charAt(P),P++):(ee=f,R===0&&U(ns));te!==f?(lt=[lt,te],$=lt):(P=$,$=f)}else P=$,$=f;$===f&&($=null),$!==f?(M=[M,$],T=M):(P=T,T=f)}else P=T,T=f}T!==f?(x=[x,T],y=x):(P=y,y=f)}else P=y,y=f;return y!==f&&(ht=p,y=Ka(y)),p=y,R--,p===f&&(y=f,R===0&&U(Zs)),p}function Tr(){var p,y;return p=P,y=hn(),y!==f&&(ht=p,y=hi(y)),p=y,p}function hn(){var p,y,x,T;if(p=P,O.charCodeAt(P)===60?(y=Ht,P++):(y=f,R===0&&U(_s)),y!==f){for(x=[],T=Eo(),T===f&&(T=hn());T!==f;)x.push(T),T=Eo(),T===f&&(T=hn());x!==f?(O.charCodeAt(P)===62?(T=ki,P++):(T=f,R===0&&U(rs)),T!==f?(ht=p,y=mr(x),p=y):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return p}function Eo(){var p,y,x,T,M;if(p=P,y=[],x=P,T=P,R++,O.charCodeAt(P)===62?(M=ki,P++):(M=f,R===0&&U(rs)),M===f&&(O.charCodeAt(P)===60?(M=Ht,P++):(M=f,R===0&&U(_s))),R--,M===f?T=void 0:(P=T,T=f),T!==f?(O.length>P?(M=O.charAt(P),P++):(M=f,R===0&&U(bi)),M!==f?(ht=x,T=Gt(M),x=T):(P=x,x=f)):(P=x,x=f),x!==f)for(;x!==f;)y.push(x),x=P,T=P,R++,O.charCodeAt(P)===62?(M=ki,P++):(M=f,R===0&&U(rs)),M===f&&(O.charCodeAt(P)===60?(M=Ht,P++):(M=f,R===0&&U(_s))),R--,M===f?T=void 0:(P=T,T=f),T!==f?(O.length>P?(M=O.charAt(P),P++):(M=f,R===0&&U(bi)),M!==f?(ht=x,T=Gt(M),x=T):(P=x,x=f)):(P=x,x=f);else y=f;return y!==f&&(ht=p,y=ra(y)),p=y,p}function es(){var p,y,x,T;if(p=P,O.charCodeAt(P)===34?(y=Pr,P++):(y=f,R===0&&U(so)),y!==f){for(x=[],T=Ls();T!==f;)x.push(T),T=Ls();x!==f?(O.charCodeAt(P)===34?(T=Pr,P++):(T=f,R===0&&U(so)),T!==f?(ht=p,y=kn(x),p=y):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return p}function Ls(){var p,y,x;return p=zn(),p===f&&(p=P,y=P,R++,O.charCodeAt(P)===34?(x=Pr,P++):(x=f,R===0&&U(so)),x===f&&(x=bo()),R--,x===f?y=void 0:(P=y,y=f),y!==f?(x=wo(),x!==f?(ht=p,y=Pe(),p=y):(P=p,p=f)):(P=p,p=f),p===f&&(p=Wi())),p}function zn(){var p,y,x,T;return p=P,y=P,O.charCodeAt(P)===92?(x=zt,P++):(x=f,R===0&&U(Zi)),x!==f?(O.length>P?(T=O.charAt(P),P++):(T=f,R===0&&U(bi)),T!==f?(x=[x,T],y=x):(P=y,y=f)):(P=y,y=f),y!==f&&(ht=p,y=Gi(y)),p=y,p}function Wi(){var p,y,x;return p=P,O.charCodeAt(P)===92?(y=zt,P++):(y=f,R===0&&U(Zi)),y!==f?(x=Ao(),x!==f?(ht=p,y=no(),p=y):(P=p,p=f)):(P=p,p=f),p}function bo(){var p;return Gn.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,R===0&&U(ro)),p}function Ao(){var p,y;return R++,O.charCodeAt(P)===10?(p=oa,P++):(p=f,R===0&&U(oo)),p===f&&(O.substr(P,2)===ao?(p=ao,P+=2):(p=f,R===0&&U(aa)),p===f&&(O.charCodeAt(P)===13?(p=lo,P++):(p=f,R===0&&U(Sr)),p===f&&(O.charCodeAt(P)===8232?(p=Mn,P++):(p=f,R===0&&U(la)),p===f&&(O.charCodeAt(P)===8233?(p=ha,P++):(p=f,R===0&&U(Xt)))))),R--,p===f&&(y=f,R===0&&U(tn)),p}function wo(){var p;return O.length>P?(p=O.charAt(P),P++):(p=f,R===0&&U(bi)),p}function un(){var p,y,x;if(p=P,y=[],x=Hi(),x!==f)for(;x!==f;)y.push(x),x=Hi();else y=f;return y!==f&&(ht=p,y=kn(y)),p=y,p}function Hi(){var p,y,x;return yr.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,R===0&&U(Ja)),p===f&&(p=P,O.substr(P,2)===ua?(y=ua,P+=2):(y=f,R===0&&U(Za)),y!==f&&(ht=p,y=_a()),p=y,p===f&&(p=P,O.charCodeAt(P)===92?(y=zt,P++):(y=f,R===0&&U(Zi)),y!==f?(x=Mt(),x!==f?(ht=p,y=no(),p=y):(P=p,p=f)):(P=p,p=f),p===f&&(p=P,O.charCodeAt(P)===92?(y=zt,P++):(y=f,R===0&&U(Zi)),y!==f&&(ht=p,y=tl()),p=y))),p}function xr(){var p,y;return R++,p=Or(),p===f&&(p=cn(),p===f&&(p=zi())),R--,p===f&&(y=f,R===0&&U(el)),p}function Or(){var p,y,x,T,M,$;if(R++,p=P,O.substr(P,2)===Vn?(y=Vn,P+=2):(y=f,R===0&&U(ii)),y!==f){for(x=[],T=P,M=P,R++,O.substr(P,2)===Xe?($=Xe,P+=2):($=f,R===0&&U(en)),R--,$===f?M=void 0:(P=M,M=f),M!==f?(O.length>P?($=O.charAt(P),P++):($=f,R===0&&U(bi)),$!==f?(ht=T,M=Ct($),T=M):(P=T,T=f)):(P=T,T=f);T!==f;)x.push(T),T=P,M=P,R++,O.substr(P,2)===Xe?($=Xe,P+=2):($=f,R===0&&U(en)),R--,$===f?M=void 0:(P=M,M=f),M!==f?(O.length>P?($=O.charAt(P),P++):($=f,R===0&&U(bi)),$!==f?(ht=T,M=Ct($),T=M):(P=T,T=f)):(P=T,T=f);x!==f?(O.substr(P,2)===Xe?(T=Xe,P+=2):(T=f,R===0&&U(en)),T!==f?(ht=p,y=Qe(x),p=y):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return R--,p===f&&(y=f,R===0&&U(Es)),p}function cn(){var p,y,x,T,M,$;if(R++,p=P,O.substr(P,2)===Ai?(y=Ai,P+=2):(y=f,R===0&&U(bs)),y!==f){for(x=[],T=P,M=P,R++,As.test(O.charAt(P))?($=O.charAt(P),P++):($=f,R===0&&U(ws)),R--,$===f?M=void 0:(P=M,M=f),M!==f?(O.length>P?($=O.charAt(P),P++):($=f,R===0&&U(bi)),$!==f?(ht=T,M=Gt($),T=M):(P=T,T=f)):(P=T,T=f);T!==f;)x.push(T),T=P,M=P,R++,As.test(O.charAt(P))?($=O.charAt(P),P++):($=f,R===0&&U(ws)),R--,$===f?M=void 0:(P=M,M=f),M!==f?(O.length>P?($=O.charAt(P),P++):($=f,R===0&&U(bi)),$!==f?(ht=T,M=Gt($),T=M):(P=T,T=f)):(P=T,T=f);x!==f?(As.test(O.charAt(P))?(T=O.charAt(P),P++):(T=f,R===0&&U(ws)),T===f&&(T=null),T!==f?(ht=p,y=ho(x),p=y):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return R--,p===f&&(y=f,R===0&&U(Cr)),p}function zi(){var p,y,x,T,M,$;if(R++,p=P,O.charCodeAt(P)===35?(y=Se,P++):(y=f,R===0&&U(ke)),y!==f){for(x=[],T=P,M=P,R++,As.test(O.charAt(P))?($=O.charAt(P),P++):($=f,R===0&&U(ws)),R--,$===f?M=void 0:(P=M,M=f),M!==f?(O.length>P?($=O.charAt(P),P++):($=f,R===0&&U(bi)),$!==f?(ht=T,M=Gt($),T=M):(P=T,T=f)):(P=T,T=f);T!==f;)x.push(T),T=P,M=P,R++,As.test(O.charAt(P))?($=O.charAt(P),P++):($=f,R===0&&U(ws)),R--,$===f?M=void 0:(P=M,M=f),M!==f?(O.length>P?($=O.charAt(P),P++):($=f,R===0&&U(bi)),$!==f?(ht=T,M=Gt($),T=M):(P=T,T=f)):(P=T,T=f);x!==f?(As.test(O.charAt(P))?(T=O.charAt(P),P++):(T=f,R===0&&U(ws)),T===f&&(T=null),T!==f?(ht=p,y=ho(x),p=y):(P=p,p=f)):(P=p,p=f)}else P=p,p=f;return R--,p===f&&(y=f,R===0&&U(uo)),p}function Pt(){var p,y;for(R++,p=[],y=Bs(),y===f&&(y=xr());y!==f;)p.push(y),y=Bs(),y===f&&(y=xr());return R--,p===f&&(y=f,R===0&&U(wi)),p}function Mt(){var p,y;if(p=[],si.test(O.charAt(P))?(y=O.charAt(P),P++):(y=f,R===0&&U(sn)),y!==f)for(;y!==f;)p.push(y),si.test(O.charAt(P))?(y=O.charAt(P),P++):(y=f,R===0&&U(sn));else p=f;return p}function Bs(){var p,y;if(p=[],os.test(O.charAt(P))?(y=O.charAt(P),P++):(y=f,R===0&&U(se)),y===f&&(y=Mt()),y!==f)for(;y!==f;)p.push(y),os.test(O.charAt(P))?(y=O.charAt(P),P++):(y=f,R===0&&U(se)),y===f&&(y=Mt());else p=f;return p}function vo(){var p;return p=To(),p===f&&(p=ca(),p===f&&(p=Ve(),p===f&&(p=qn(),p===f&&(p=Io(),p===f&&(p=Fs()))))),p}function ca(){var p;return Er.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,R===0&&U(vs)),p}function qn(){var p;return br.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,R===0&&U(co)),p}function Io(){var p;return vi.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,R===0&&U(_i)),p}function Ve(){var p;return Wn.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,R===0&&U(nn)),p}function To(){var p;return Ar.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,R===0&&U(wr)),p}function Fs(){var p;return Is.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,R===0&&U(as)),p}function qi(){var p;return go.test(O.charAt(P))?(p=O.charAt(P),P++):(p=f,R===0&&U(Ts)),p}if(ge=Dt(),ge!==f&&P===O.length)return ge;throw ge!==f&&P<O.length&&U(Ae()),Ti(Ge,Kt<O.length?O.charAt(Kt):null,Kt<O.length?on(Kt,Kt+1):on(Kt,Kt))}fe.exports={SyntaxError:Tt,parse:gt}},79275:(fe,Et,Tt)=>{var gt=Tt(64106);fe.exports=gt.parse},48436:(fe,Et)=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});class Tt{constructor(...C){this._head=this._tail=null,this._length=0,C.length>0&&C.forEach(f=>{this.append(f)})}*iterator(){let C=this._head;for(;C;)yield C.value,C=C.next}[Symbol.iterator](){return this.iterator()}get head(){return this._head?this._head.value:null}get tail(){return this._tail?this._tail.value:null}get length(){return this._length}insert(C,f,W=!1){if(W&&this.isDuplicate(C))return!1;let Dt=new gt(C),xt=this._head;if(xt)for(;;){if(xt.value===f)return Dt.next=xt.next,Dt.prev=xt,xt.next=Dt,Dt.next?Dt.next.prev=Dt:this._tail=Dt,this._length++,!0;if(xt.next)xt=xt.next;else return!1}else return!1}append(C,f=!1){if(f&&this.isDuplicate(C))return!1;let W=new gt(C);return this._tail?(this._tail.next=W,W.prev=this._tail,this._tail=W):this._head=this._tail=W,this._length++,!0}prepend(C,f=!1){if(f&&this.isDuplicate(C))return!1;let W=new gt(C);return this._head?(W.next=this._head,this._head.prev=W,this._head=W):this._head=this._tail=W,this._length++,!0}remove(C){let f=this._head;if(f){if(f.value===C)return this._head=f.next,this._head.prev=null,f.next=f.prev=null,this._length--,f.value;for(;;){if(f.value===C)return f.next?(f.prev.next=f.next,f.next.prev=f.prev,f.next=f.prev=null):(f.prev.next=null,this._tail=f.prev,f.next=f.prev=null),this._length--,f.value;if(f.next)f=f.next;else return}}}removeHead(){let C=this._head;if(C)return this._head.next?(this._head.next.prev=null,this._head=this._head.next,C.next=C.prev=null):(this._head=null,this._tail=null),this._length--,C.value}removeTail(){let C=this._tail;if(C)return this._tail.prev?(this._tail.prev.next=null,this._tail=this._tail.prev,C.next=C.prev=null):(this._head=null,this._tail=null),this._length--,C.value}first(C){let f=this.iterator(),W=[],Dt=Math.min(C,this.length);for(let xt=0;xt<Dt;xt++){let N=f.next();W.push(N.value)}return W}toArray(){return[...this]}isDuplicate(C){return new Set(this.toArray()).has(C)}}Et.LinkedList=Tt;class gt{constructor(C){this.value=C,this.next=null,this.prev=null}}Et.LinkedListItem=gt},58982:(fe,Et,Tt)=>{var gt=Tt(14699);fe.exports=function(O){var C,f,W,Dt;if(C=/^((?:rgb|hs[lv]|cmyk|xyz|lab)a?)\s*\(([^\)]*)\)/.exec(O)){var xt=C[1],N=xt.replace(/a$/,""),z=N==="cmyk"?4:3;f=gt[N],W=C[2].replace(/^\s+|\s+$/g,"").split(/\s*,\s*/).map(function(_,k){return/%$/.test(_)&&k===z?parseFloat(_)/100:(/%$/.test(_),parseFloat(_))}),xt===N&&W.push(1),Dt=W[z]===void 0?1:W[z],W=W.slice(0,z),f[N]=function(){return W}}else if(/^#[A-Fa-f0-9]+$/.test(O)){var N=O.replace(/^#/,""),z=N.length;f=gt.rgb,W=N.split(z===3?/(.)/:/(..)/),W=W.filter(Boolean).map(function(tt){return parseInt(z===3?tt+tt:tt,16)}),Dt=1,f.rgb=function(){return W},W[0]||(W[0]=0),W[1]||(W[1]=0),W[2]||(W[2]=0)}else f=gt.keyword,f.keyword=function(){return O},W=O,Dt=1;var et={rgb:void 0,hsl:void 0,hsv:void 0,cmyk:void 0,keyword:void 0,hex:void 0};try{et.rgb=f.rgb(W)}catch{}try{et.hsl=f.hsl(W)}catch{}try{et.hsv=f.hsv(W)}catch{}try{et.cmyk=f.cmyk(W)}catch{}try{et.keyword=f.keyword(W)}catch{}return et.rgb&&(et.hex="#"+et.rgb.map(function(_){var k=_.toString(16);return k.length===1?"0"+k:k}).join("")),et.rgb&&(et.rgba=et.rgb.concat(Dt)),et.hsl&&(et.hsla=et.hsl.concat(Dt)),et.hsv&&(et.hsva=et.hsv.concat(Dt)),et.cmyk&&(et.cmyka=et.cmyk.concat(Dt)),et}},79002:fe=>{fe.exports={rgb2hsl:Et,rgb2hsv:Tt,rgb2hwb:gt,rgb2cmyk:O,rgb2keyword:C,rgb2xyz:f,rgb2lab:W,rgb2lch:Dt,hsl2rgb:xt,hsl2hsv:N,hsl2hwb:z,hsl2cmyk:et,hsl2keyword:_,hsv2rgb:k,hsv2hsl:tt,hsv2hwb:d,hsv2cmyk:qt,hsv2keyword:Re,hwb2rgb:At,hwb2hsl:ps,hwb2hsv:D,hwb2cmyk:Ri,hwb2keyword:On,cmyk2rgb:Di,cmyk2hsl:jt,cmyk2hsv:Ei,cmyk2hwb:ms,cmyk2keyword:vt,keyword2rgb:Ni,keyword2hsl:Ys,keyword2hsv:_r,keyword2hwb:to,keyword2cmyk:cr,keyword2lab:Fn,keyword2xyz:at,xyz2rgb:Ln,xyz2lab:Nt,xyz2lch:hr,lab2xyz:Xs,lab2rgb:Bn,lab2lch:Qs,lch2lab:ft,lch2xyz:ur,lch2rgb:w};function Et(G){var st=G[0]/255,H=G[1]/255,K=G[2]/255,nt=Math.min(st,H,K),Y=Math.max(st,H,K),ot=Y-nt,v,L,j;return Y==nt?v=0:st==Y?v=(H-K)/ot:H==Y?v=2+(K-st)/ot:K==Y&&(v=4+(st-H)/ot),v=Math.min(v*60,360),v<0&&(v+=360),j=(nt+Y)/2,Y==nt?L=0:j<=.5?L=ot/(Y+nt):L=ot/(2-Y-nt),[v,L*100,j*100]}function Tt(G){var st=G[0],H=G[1],K=G[2],nt=Math.min(st,H,K),Y=Math.max(st,H,K),ot=Y-nt,v,L,j;return Y==0?L=0:L=ot/Y*1e3/10,Y==nt?v=0:st==Y?v=(H-K)/ot:H==Y?v=2+(K-st)/ot:K==Y&&(v=4+(st-H)/ot),v=Math.min(v*60,360),v<0&&(v+=360),j=Y/255*1e3/10,[v,L,j]}function gt(G){var st=G[0],H=G[1],Y=G[2],K=Et(G)[0],nt=1/255*Math.min(st,Math.min(H,Y)),Y=1-1/255*Math.max(st,Math.max(H,Y));return[K,nt*100,Y*100]}function O(G){var st=G[0]/255,H=G[1]/255,K=G[2]/255,nt,Y,ot,v;return v=Math.min(1-st,1-H,1-K),nt=(1-st-v)/(1-v)||0,Y=(1-H-v)/(1-v)||0,ot=(1-K-v)/(1-v)||0,[nt*100,Y*100,ot*100,v*100]}function C(G){return Z[JSON.stringify(G)]}function f(G){var st=G[0]/255,H=G[1]/255,K=G[2]/255;st=st>.04045?Math.pow((st+.055)/1.055,2.4):st/12.92,H=H>.04045?Math.pow((H+.055)/1.055,2.4):H/12.92,K=K>.04045?Math.pow((K+.055)/1.055,2.4):K/12.92;var nt=st*.4124+H*.3576+K*.1805,Y=st*.2126+H*.7152+K*.0722,ot=st*.0193+H*.1192+K*.9505;return[nt*100,Y*100,ot*100]}function W(G){var st=f(G),H=st[0],K=st[1],nt=st[2],Y,ot,v;return H/=95.047,K/=100,nt/=108.883,H=H>.008856?Math.pow(H,.3333333333333333):7.787*H+.13793103448275862,K=K>.008856?Math.pow(K,.3333333333333333):7.787*K+.13793103448275862,nt=nt>.008856?Math.pow(nt,.3333333333333333):7.787*nt+.13793103448275862,Y=116*K-16,ot=500*(H-K),v=200*(K-nt),[Y,ot,v]}function Dt(G){return Qs(W(G))}function xt(G){var st=G[0]/360,H=G[1]/100,K=G[2]/100,nt,Y,ot,v,L;if(H==0)return L=K*255,[L,L,L];K<.5?Y=K*(1+H):Y=K+H-K*H,nt=2*K-Y,v=[0,0,0];for(var j=0;j<3;j++)ot=st+.3333333333333333*-(j-1),ot<0&&ot++,ot>1&&ot--,6*ot<1?L=nt+(Y-nt)*6*ot:2*ot<1?L=Y:3*ot<2?L=nt+(Y-nt)*(.6666666666666666-ot)*6:L=nt,v[j]=L*255;return v}function N(G){var st=G[0],H=G[1]/100,K=G[2]/100,nt,Y;return K===0?[0,0,0]:(K*=2,H*=K<=1?K:2-K,Y=(K+H)/2,nt=2*H/(K+H),[st,nt*100,Y*100])}function z(G){return gt(xt(G))}function et(G){return O(xt(G))}function _(G){return C(xt(G))}function k(G){var st=G[0]/60,H=G[1]/100,L=G[2]/100,K=Math.floor(st)%6,nt=st-Math.floor(st),Y=255*L*(1-H),ot=255*L*(1-H*nt),v=255*L*(1-H*(1-nt)),L=255*L;switch(K){case 0:return[L,v,Y];case 1:return[ot,L,Y];case 2:return[Y,L,v];case 3:return[Y,ot,L];case 4:return[v,Y,L];case 5:return[L,Y,ot]}}function tt(G){var st=G[0],H=G[1]/100,K=G[2]/100,nt,Y;return Y=(2-H)*K,nt=H*K,nt/=Y<=1?Y:2-Y,nt=nt||0,Y/=2,[st,nt*100,Y*100]}function d(G){return gt(k(G))}function qt(G){return O(k(G))}function Re(G){return C(k(G))}function At(G){var st=G[0]/360,H=G[1]/100,K=G[2]/100,nt=H+K,Y,ot,v,L;switch(nt>1&&(H/=nt,K/=nt),Y=Math.floor(6*st),ot=1-K,v=6*st-Y,Y&1&&(v=1-v),L=H+v*(ot-H),Y){default:case 6:case 0:r=ot,g=L,b=H;break;case 1:r=L,g=ot,b=H;break;case 2:r=H,g=ot,b=L;break;case 3:r=H,g=L,b=ot;break;case 4:r=L,g=H,b=ot;break;case 5:r=ot,g=H,b=L;break}return[r*255,g*255,b*255]}function ps(G){return Et(At(G))}function D(G){return Tt(At(G))}function Ri(G){return O(At(G))}function On(G){return C(At(G))}function Di(G){var st=G[0]/100,H=G[1]/100,K=G[2]/100,nt=G[3]/100,Y,ot,v;return Y=1-Math.min(1,st*(1-nt)+nt),ot=1-Math.min(1,H*(1-nt)+nt),v=1-Math.min(1,K*(1-nt)+nt),[Y*255,ot*255,v*255]}function jt(G){return Et(Di(G))}function Ei(G){return Tt(Di(G))}function ms(G){return gt(Di(G))}function vt(G){return C(Di(G))}function Ln(G){var st=G[0]/100,H=G[1]/100,K=G[2]/100,nt,Y,ot;return nt=st*3.2406+H*-1.5372+K*-.4986,Y=st*-.9689+H*1.8758+K*.0415,ot=st*.0557+H*-.204+K*1.057,nt=nt>.0031308?1.055*Math.pow(nt,.4166666666666667)-.055:nt=nt*12.92,Y=Y>.0031308?1.055*Math.pow(Y,.4166666666666667)-.055:Y=Y*12.92,ot=ot>.0031308?1.055*Math.pow(ot,.4166666666666667)-.055:ot=ot*12.92,nt=Math.min(Math.max(0,nt),1),Y=Math.min(Math.max(0,Y),1),ot=Math.min(Math.max(0,ot),1),[nt*255,Y*255,ot*255]}function Nt(G){var st=G[0],H=G[1],K=G[2],nt,Y,ot;return st/=95.047,H/=100,K/=108.883,st=st>.008856?Math.pow(st,.3333333333333333):7.787*st+.13793103448275862,H=H>.008856?Math.pow(H,.3333333333333333):7.787*H+.13793103448275862,K=K>.008856?Math.pow(K,.3333333333333333):7.787*K+.13793103448275862,nt=116*H-16,Y=500*(st-H),ot=200*(H-K),[nt,Y,ot]}function hr(G){return Qs(Nt(G))}function Xs(G){var st=G[0],H=G[1],K=G[2],nt,Y,ot,v;return st<=8?(Y=st*100/903.3,v=7.787*(Y/100)+.13793103448275862):(Y=100*Math.pow((st+16)/116,3),v=Math.pow(Y/100,.3333333333333333)),nt=nt/95.047<=.008856?nt=95.047*(H/500+v-.13793103448275862)/7.787:95.047*Math.pow(H/500+v,3),ot=ot/108.883<=.008859?ot=108.883*(v-K/200-.13793103448275862)/7.787:108.883*Math.pow(v-K/200,3),[nt,Y,ot]}function Qs(G){var st=G[0],H=G[1],K=G[2],nt,Y,ot;return nt=Math.atan2(K,H),Y=nt*360/2/Math.PI,Y<0&&(Y+=360),ot=Math.sqrt(H*H+K*K),[st,ot,Y]}function Bn(G){return Ln(Xs(G))}function ft(G){var st=G[0],H=G[1],K=G[2],nt,Y,ot;return ot=K/360*2*Math.PI,nt=H*Math.cos(ot),Y=H*Math.sin(ot),[st,nt,Y]}function ur(G){return Xs(ft(G))}function w(G){return Bn(ft(G))}function Ni(G){return De[G]}function Ys(G){return Et(Ni(G))}function _r(G){return Tt(Ni(G))}function to(G){return gt(Ni(G))}function cr(G){return O(Ni(G))}function Fn(G){return W(Ni(G))}function at(G){return f(Ni(G))}var De={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},Z={};for(var Ut in De)Z[JSON.stringify(De[Ut])]=Ut},14699:(fe,Et,Tt)=>{var gt=Tt(79002),O=function(){return new xt};for(var C in gt){O[C+"Raw"]=function(N){return function(z){return typeof z=="number"&&(z=Array.prototype.slice.call(arguments)),gt[N](z)}}(C);var f=/(\w+)2(\w+)/.exec(C),W=f[1],Dt=f[2];O[W]=O[W]||{},O[W][Dt]=O[C]=function(N){return function(z){typeof z=="number"&&(z=Array.prototype.slice.call(arguments));var et=gt[N](z);if(typeof et=="string"||et===void 0)return et;for(var _=0;_<et.length;_++)et[_]=Math.round(et[_]);return et}}(C)}var xt=function(){this.convs={}};xt.prototype.routeSpace=function(N,z){var et=z[0];return et===void 0?this.getValues(N):(typeof et=="number"&&(et=Array.prototype.slice.call(z)),this.setValues(N,et))},xt.prototype.setValues=function(N,z){return this.space=N,this.convs={},this.convs[N]=z,this},xt.prototype.getValues=function(N){var z=this.convs[N];if(!z){var et=this.space,_=this.convs[et];z=O[et][N](_),this.convs[N]=z}return z},["rgb","hsl","hsv","cmyk","keyword"].forEach(function(N){xt.prototype[N]=function(z){return this.routeSpace(N,arguments)}}),fe.exports=O},38941:(fe,Et,Tt)=>{"use strict";var gt;gt={value:!0};const O=Tt(48436);class C extends O.LinkedList{constructor(...W){super(...W)}get front(){return this.head}enqueue(W){this.append(W)}dequeue(){return this.removeHead()}}Et.o=C},89796:(fe,Et,Tt)=>{"use strict";var gt;gt={value:!0};const O=Tt(48436);class C extends O.LinkedList{constructor(...W){super(...W)}get top(){return this.head}get size(){return this.length}push(W){this.prepend(W)}pop(){return this.removeHead()}}Et.B=C},38846:(fe,Et)=>{"use strict";var Tt;Tt={value:!0},Et.fe=Et.Qf=Tt=Tt=Tt=Tt=void 0;const gt=`\r `;function O(xt){return W.isNullOrWhiteSpace(xt)}function C(xt,...N){return W.join(xt,...N)}function f(xt,...N){return W.format(xt,...N)}Tt="",Tt=O,Tt=C,Tt=f;class W{static regexNumber=/{(\d+(:\w*)?)}/g;static regexObject=/{(\w+(:\w*)?)}/g;static empty="";static Empty="";static IsNullOrWhiteSpace(N){return W.isNullOrWhiteSpace(N)}static Join(N,...z){return W.join(N,...z)}static Format(N,...z){return W.format(N,...z)}static isNullOrWhiteSpace(N){try{return N==null||N=="undefined"?!0:N.toString().replace(/\s/g,"").length<1}catch(z){return console.log(z),!1}}static join(N,...z){try{var et=z[0];if(Array.isArray(et)||et instanceof Array){let tt=W.empty;for(let d=0;d<et.length;d++){var _=et[d];d<et.length-1?tt+=_+N:tt+=_}return tt}if(typeof et=="object"){let tt=W.empty;const d=et;return Object.keys(et).forEach(Re=>{tt+=d[Re]+N}),tt=tt.slice(0,tt.length-N.length)}var k=z;return W.joinString(N,...k)}catch(tt){return console.log(tt),W.empty}}static format(N,...z){try{return N.match(W.regexNumber)?W.formatString(W.regexNumber,N,z):N.match(W.regexObject)?W.formatString(W.regexObject,N,z,!0):N}catch(et){return console.log(et),W.empty}}static formatString(N,z,et,_=!1){return z.replace(N,function(k,tt){const d=k.split(":");1<d.length&&(tt=d[0].replace("{",""),k=d[1].replace("}",""));let qt;return(qt=(_?et[0]:et)[tt])==null||qt==null||k.match(/{\d+}/)||(qt=W.parsePattern(k,qt))!==void 0&&qt!=null?qt:W.empty})}static parsePattern(N,z){switch(N){case"L":return z=z.toLocaleLowerCase();case"U":return z=z.toLocaleUpperCase();case"d":if(typeof z=="string")return W.getDisplayDateFromString(z);if(z instanceof Date)return W.format("{0:00}.{1:00}.{2:0000}",z.getDate(),z.getMonth(),z.getFullYear());break;case"s":if(typeof z=="string")return W.getSortableDateFromString(z);if(z instanceof Date)return W.format("{0:0000}-{1:00}-{2:00}",z.getFullYear(),z.getMonth(),z.getDate());break;case"n":{const k=(z=typeof z!="string"?z.toString():z).replace(/,/g,".");if(isNaN(parseFloat(k))||k.length<=3)break;const tt=k.split(/\D+/g);let d=tt;const qt=(d=1<tt.length?[W.joinString("",...tt.splice(0,tt.length-1)),tt[tt.length-1]]:d)[0];var _=qt.length%3,et=0<_?qt.substring(0,_):W.empty,_=qt.substring(_).match(/.{3}/g);return z=et+"."+W.join(".",_)+(1<d.length?","+d[1]:"")}case"x":return this.decimalToHexString(z);case"X":return this.decimalToHexString(z,!0)}return typeof z!="number"&&isNaN(z)||isNaN(+N)||W.isNullOrWhiteSpace(z)?z:W.formatNumber(z,N)}static decimalToHexString(N,z=!1){const et=parseFloat(N),_=et.toString(16);return z?_.toLocaleUpperCase():_}static getDisplayDateFromString(N){var z=N.split("-");if(z.length<=1)return N;let et=z[z.length-1];return N=z[z.length-2],z=z[z.length-3],(et=(et=et.split("T")[0]).split(" ")[0])+`.${N}.`+z}static getSortableDateFromString(N){const z=N.replace(",","").split(".");if(z.length<=1)return N;N=z[z.length-1].split(" ");let et=W.empty,_=(1<N.length&&(et=N[N.length-1]),z[z.length-1].split(" ")[0]+`-${z[z.length-2]}-`+z[z.length-3]);return!W.isNullOrWhiteSpace(et)&&1<et.length?_+="T"+et:_+="T00:00:00",_}static formatNumber(_,et){var et=et.length,_=_.toString();return et<=_.length?_:(et=et-_.length,++et,new Array(et).join("0")+_)}static joinString(N,...z){let et=W.empty;for(let k=0;k<z.length;k++)if(!(typeof z[k]=="string"&&W.isNullOrWhiteSpace(z[k])||typeof z[k]!="number"&&typeof z[k]!="string")){var _=""+z[k];et+=_;for(let tt=k+1;tt<z.length;tt++)if(!W.isNullOrWhiteSpace(z[tt])){et+=N,k=tt-1;break}}return et}}Et.Qf=W;class Dt{Values;constructor(N=""){this.Values=[],W.isNullOrWhiteSpace(N)||(this.Values=new Array(N))}toString(){return this.Values.join(W.empty)}ToString(){return this.toString()}append(N){this.Values.push(N)}Append(N){this.append(N)}appendLine(N){this.Values.push(gt+N)}AppendLine(N){this.appendLine(N)}appendFormat(N,...z){this.Values.push(W.format(N,...z))}AppendFormat(N,...z){this.appendFormat(N,...z)}appendLineFormat(N,...z){this.Values.push(gt+W.format(N,...z))}AppendLineFormat(N,...z){return this.appendLineFormat(N,...z)}clear(){this.Values=[]}Clear(){this.clear()}}Et.fe=Dt}},Ya={};function xn(fe){var Et=Ya[fe];if(Et!==void 0)return Et.exports;var Tt=Ya[fe]={exports:{}};return Th[fe](Tt,Tt.exports,xn),Tt.exports}var Dd={};(()=>{"use strict";class fe{constructor(t,e){this.entity=t,this.bind(e)}bind(t){this.entity&&this.entity.setAttr(t,this)}}class Et{}Et.GeomObjectIndex=0,Et.DrawingObjectIndex=1,Et.AlgorithmDataIndex=2,Et.ViewerIndex=3;class Tt{constructor(){this.actions=new Set}forEach(t){this.actions.forEach(e=>e(t,null))}subscribe(t){this.actions.add(t)}unsubscribe(t){this.actions.delete(t)}raise(t,e){this.actions.forEach(i=>i(t,e))}}class gt extends fe{constructor(t){super(t,Et.GeomObjectIndex)}static getGeom(t){return t.getAttr(Et.GeomObjectIndex)}get parent(){const t=this.entity.parent;return t?gt.getGeom(t):null}rebind(t){this.entity=t,this.bind(Et.GeomObjectIndex)}*getAncestors(){let t=this.parent;for(;t!=null;)yield t,t=t.parent}}class O{static solve(t,e,i,s,n,o){const a=t*n-s*e;if(!(Math.abs(a)<O.eps))return{x:(i*n-o*e)/a,y:(t*o-s*i)/a}}}O.eps=1e-8;class C{}C.distanceEpsilonPrecision=6,C.mult=Math.pow(10,6),C.defaultLeafBoxesOffset=.5,C.lineSegmentThreshold=.05,C.intersectionEpsilon=1e-4,C.distanceEpsilon=Math.pow(10,-C.distanceEpsilonPrecision),C.squareOfDistanceEpsilon=Math.pow(10,-C.distanceEpsilonPrecision*2),C.tolerance=1e-8;function f(l,t){return(l?1:0)-(t?1:0)}function W(l,t){const e=l-t;return e<0?-1:e===0?0:1}function Dt(l,t){const e=W(l.y,t.y);return e||W(l.x,t.x)}function xt(l,t){const e=W(l.x,t.x);return e||W(l.y,t.y)}function N(l,t){const e=l-t;return-C.distanceEpsilon<=e&&e<=C.distanceEpsilon}function z(l,t){return _(l,t)>0}function et(l,t){return _(l,t)<0}function _(l,t){const e=l-t;return e<=-C.distanceEpsilon?-1:e>=C.distanceEpsilon?1:0}var k;(function(l){l[l.Clockwise=0]="Clockwise",l[l.Counterclockwise=1]="Counterclockwise",l[l.Collinear=2]="Collinear"})(k||(k={}));function tt(l,t){return l.sub(t).length}class d{constructor(t,e){this.x_=t,this.y_=e}static RoundPoint(t){return new d(d.RoundDouble(t.x),d.RoundDouble(t.y))}static RoundDouble(t){return Math.round(t*C.mult)/C.mult}toJSON(){return{x:this.x,y:this.y}}static fromJSON(t){return new d(t.x,t.y)}static ProjectionToLine(t,e,i){let s=e.sub(t);const n=s.length;if(n<C.distanceEpsilon)return t;s=s.div(n);const o=i.sub(t).dot(s);return t.add(s.mul(o))}static RayIntersectsRayInteriors(t,e,i,s){const n=d.lineLineIntersection(t,t.add(e),i,i.add(s));if(n&&n.sub(t).dot(e.div(e.l1))>C.distanceEpsilon&&n.sub(i).dot(s.div(s.l1))>C.distanceEpsilon)return n}static IntervalIntersectsRay(t,e,i,s){const n=d.lineLineIntersection(t,e,i,i.add(s));if(!n)return;const o=t.sub(n),a=n.sub(e);if(!(o.dot(a)<=0)&&!(n.sub(i).dot(s)<0)&&o.dot(o)>C.squareOfDistanceEpsilon&&a.dot(a)>=C.squareOfDistanceEpsilon)return n}static PointToTheLeftOfLineOrOnLine(t,e,i){return d.signedDoubledTriangleArea(t,e,i)>=0}static PointToTheLeftOfLine(t,e,i){return d.signedDoubledTriangleArea(t,e,i)>0}static PointIsInsideCone(t,e,i,s){return d.PointToTheRightOfLineOrOnLine(t,e,i)&&d.PointToTheLeftOfLineOrOnLine(t,e,s)}static PointToTheRightOfLineOrOnLine(t,e,i){return d.signedDoubledTriangleArea(e,i,t)<=0}static PointToTheRightOfLine(t,e,i){return d.signedDoubledTriangleArea(e,i,t)<0}static closeIntersections(t,e){return d.close(t,e,C.intersectionEpsilon)}get l1(){return Math.abs(this.x_)+Math.abs(this.y_)}dot(t){return this.x*t.x+this.y*t.y}get x(){return this.x_}get y(){return this.y_}compareTo(t){const e=W(this.x,t.x);return e!==0?e:W(this.y,t.y)}toString(){return"("+this.x+","+this.y+")"}static close(t,e,i){return t.sub(e).length<=i}static closeSquare(t,e,i){const s=e.sub(t);return s.dot(s)<=i}static closeDistEps(t,e,i=C.distanceEpsilon){return t.sub(e).length<=i}normalize(){const t=this.length;return new d(this.x/t,this.y/t)}get length(){return Math.sqrt(this.x*this.x+this.y*this.y)}get lengthSquared(){return this.x*this.x+this.y*this.y}static middle(t,e){return t.add(e).div(2)}scale(t,e){return new d(this.x*t,this.y*e)}add(t){return new d(this.x+t.x,this.y+t.y)}sub(t){return new d(this.x-t.x,this.y-t.y)}mul(t){return new d(this.x*t,this.y*t)}div(t){return new d(this.x/t,this.y/t)}equal(t){return t.x===this.x&&t.y===this.y}neg(){return new d(-this.x,-this.y)}static lineLineIntersection(t,e,i,s){const n=e.sub(t),o=i.sub(s),a=i.sub(t),h=O.solve(n.x,o.x,a.x,n.y,o.y,a.y);if(h!==void 0)return t.add(n.mul(h.x))}static segSegIntersection(t,e,i,s){const n=e.sub(t),o=i.sub(s),a=i.sub(t),h=C.tolerance,u=O.solve(n.x,o.x,a.x,n.y,o.y,a.y);if(u!==void 0&&u.x>-h&&u.x<1+h&&u.y>-h&&u.y<1+h)return t.add(n.mul(u.x))}static parallelWithinEpsilon(t,e,i){const s=t.length,n=e.length;return s<i||n<i?!0:(t=t.div(s),e=e.div(n),Math.abs(-t.x*e.y+t.y*e.x)<i)}static crossProduct(t,e){return t.x*e.y-t.y*e.x}static dot(t,e){return t.x*e.x+t.y*e.y}static add(t,e){return t.add(e)}rotate90Ccw(){return new d(-this.y,this.x)}rotate90Cw(){return new d(this.y,-this.x)}clone(){return new d(this.x,this.y)}rotate(t){const e=Math.cos(t),i=Math.sin(t);return new d(e*this.x-i*this.y,i*this.x+e*this.y)}static mkPoint(t,e,i,s){return e.mul(t).add(s.mul(i))}static convSum(t,e,i){return e.add(i.sub(e).mul(t))}static anglePCP(t,e,i){return d.angle(t.sub(e),i.sub(e))}static angle(t,e){const i=t.x,s=t.y,n=e.x,o=e.y,a=i*o-s*n,h=i*n+s*o;if(Math.abs(h)<C.tolerance)return Math.abs(a)<C.tolerance?0:a<-C.tolerance?3*Math.PI/2:Math.PI/2;if(Math.abs(a)<C.tolerance)return h<-C.tolerance?Math.PI:0;const u=Math.atan2(a,h);return a>=-C.tolerance?u:Math.PI*2+u}static signedDoubledTriangleArea(t,e,i){return(e.x-t.x)*(i.y-t.y)-(i.x-t.x)*(e.y-t.y)}static getTriangleOrientation(t,e,i){const s=d.signedDoubledTriangleArea(t,e,i);return s>C.distanceEpsilon?k.Counterclockwise:s<-C.distanceEpsilon?k.Clockwise:k.Collinear}static getTriangleOrientationWithIntersectionEpsilon(t,e,i){const s=d.signedDoubledTriangleArea(t,e,i);return s>C.intersectionEpsilon?k.Counterclockwise:s<-C.intersectionEpsilon?k.Clockwise:k.Collinear}static ClosestPointAtLineSegment(t,e,i){const s=i.sub(e),n=t.sub(e),o=s.dot(n),a=s.dot(s);return o<=0+C.tolerance?e:a<=o+C.tolerance?i:e.add(s.mul(o/a))}static pointToTheLeftOfLineOrOnLine(t,e,i){return d.signedDoubledTriangleArea(t,e,i)>=0}static pointToTheLeftOfLine(t,e,i){return d.signedDoubledTriangleArea(t,e,i)>0}static pointToTheRightOfLineOrOnLine(t,e,i){return d.signedDoubledTriangleArea(e,i,t)<=0}static pointToTheRightOfLine(t,e,i){return d.signedDoubledTriangleArea(e,i,t)<0}static canProject(t,e,i){const s=i.sub(e);return!(t.sub(e).dot(s)<0||t.sub(i).dot(s)>0)}static distToLineSegment(t,e,i){const s=i.sub(e),n=t.sub(e);let o,a;if((o=s.dot(n))<=C.tolerance)return{par:0,dist:n.length};if((a=s.dot(s))<=o+C.tolerance)return{par:1,dist:t.sub(i).length};const h=o/a;return{par:h,dist:e.add(s.mul(h)).length}}}class qt{constructor(){this._next=null,this.prev=null}get point(){return this._point}set point(t){this._point=t}get next(){return this._next}set next(t){this._next=t}get nextOnPolyline(){return this.polyline.next(this)}get prevOnPolyline(){return this.polyline.prev(this)}getNext(){return this.next}setNext(t){this.next=t,this.polyline!=null&&this.polyline.setInitIsRequired()}getPrev(){return this.prev}setPrev(t){this.prev=t,this.polyline!=null&&this.polyline.setInitIsRequired()}static mkFromPoint(t){const e=new qt;return e.point=t,e}}var Re;(function(l){l[l.Corner=0]="Corner",l[l.VertexA=1]="VertexA",l[l.otherCorner=2]="otherCorner",l[l.VertexB=3]="VertexB"})(Re||(Re={}));class At{contains(t){const e=t.sub(this.corner),i=C.distanceEpsilon,s=e.dot(this.bRot);if(s>this.abRot+i||s<-i)return!1;const n=e.dot(this.aRot);return n<=this.baRot+i&&n>=-i}get area(){return Math.abs(this.a.x*this.b.y-this.a.y*this.b.x)}vertex(t){switch(t){case Re.Corner:return this.corner;case Re.VertexA:return this.aPlusCorner;case Re.otherCorner:return this.otherCorner;case Re.VertexB:return this.bPlusCorner;default:return}}static parallelogramOfTwo(t,e){const i=new At,s=t.corner,n={minx:s.x,maxx:s.x,miny:s.y,maxy:s.y};return At.pumpMinMax(n,t.aPlusCorner),At.pumpMinMax(n,t.otherCorner),At.pumpMinMax(n,t.bPlusCorner),At.pumpMinMax(n,e.corner),At.pumpMinMax(n,e.aPlusCorner),At.pumpMinMax(n,e.otherCorner),At.pumpMinMax(n,e.bPlusCorner),i.corner=new d(n.minx,n.miny),i.a=new d(0,n.maxy-n.miny),i.b=new d(n.maxx-n.minx,0),i.aPlusCorner=i.a.add(i.corner),i.otherCorner=i.b.add(i.aPlusCorner),i.bPlusCorner=i.b.add(i.corner),i.aRot=new d(-i.a.y,i.a.x),i.aRot.length>.5&&(i.aRot=i.aRot.normalize()),i.bRot=new d(-i.b.y,i.b.x),i.bRot.length>.5&&(i.bRot=i.bRot.normalize()),i.abRot=i.a.dot(i.bRot),i.baRot=i.b.dot(i.aRot),i.abRot<0&&(i.abRot=-i.abRot,i.bRot=i.bRot.neg()),i.baRot<0&&(i.baRot=-i.baRot,i.aRot=i.aRot.neg()),i.isSeg=i.a.sub(i.b).length<C.distanceEpsilon,i}static pumpMinMax(t,e){e.x<t.minx?t.minx=e.x:e.x>t.maxx&&(t.maxx=e.x),e.y<t.miny?t.miny=e.y:e.y>t.maxy&&(t.maxy=e.y)}static intersect(t,e){return!(At.separByA(t,e)||At.separByA(e,t)||At.separByB(t,e)||At.separByB(e,t))===!1?!1:!(t.isSeg&&e.isSeg)||!d.parallelWithinEpsilon(t.otherCorner.sub(t.corner),e.otherCorner.sub(e.corner),1e-5)?!0:At.ParallelSegsIntersect(e,t)}static ParallelSegsIntersect(t,e){const i=t.corner,s=t.otherCorner,n=e.corner,o=e.otherCorner,a=s.sub(i),h=0,u=a.dot(a);let c=n.sub(i).dot(a),m=o.sub(i).dot(a);if(c>m){const S=c;c=m,m=S}return!(m<h-C.distanceEpsilon||c>u+C.distanceEpsilon)}static separByB(t,e){const i=C.distanceEpsilon,s=e.vertex(0).sub(t.corner).dot(t.bRot),n=[Re.VertexA,Re.otherCorner,Re.VertexB];if(s>t.abRot+i){for(const o of n)if(e.vertex(o).sub(t.corner).dot(t.bRot)<=t.abRot+i)return!1;return!0}else if(s<-i){for(const o of n)if(e.vertex(o).sub(t.corner).dot(t.bRot)>=-i)return!1;return!0}return!1}static separByA(t,e){const i=C.distanceEpsilon;let s=e.corner.sub(t.corner);const n=d.dot(s,t.aRot);return n>t.baRot+i?(s=e.aPlusCorner.sub(t.corner),!(d.dot(s,t.aRot)<=t.baRot+i||(s=e.bPlusCorner.sub(t.corner),d.dot(s,t.aRot)<=t.baRot+i)||(s=e.otherCorner.sub(t.corner),d.dot(s,t.aRot)<=t.baRot+i))):n<-i?(s=e.aPlusCorner.sub(t.corner),!(d.dot(s,t.aRot)>=-i||(s=e.bPlusCorner.sub(t.corner),d.dot(s,t.aRot)>=-i)||(s=e.otherCorner.sub(t.corner),d.dot(s,t.aRot)>=-i))):!1}static parallelogramByCornerSideSide(t,e,i){const s=new At;return s.corner=t,s.a=e,s.b=i,s.aRot=new d(-e.y,e.x),s.aRot.length>.5&&(s.aRot=s.aRot.normalize()),s.bRot=new d(-i.y,i.x),s.bRot.length>.5&&(s.bRot=s.bRot.normalize()),s.abRot=s.bRot.dot(e),s.baRot=i.dot(s.aRot),s.abRot<0&&(s.abRot=-s.abRot,s.bRot=s.bRot.neg()),s.baRot<0&&(s.baRot=-s.baRot,s.aRot=s.aRot.neg()),s.isSeg=e.sub(i).length<C.distanceEpsilon,s.aPlusCorner=e.add(t),s.otherCorner=i.add(s.aPlusCorner),s.bPlusCorner=i.add(t),s}static getParallelogramOfAGroup(t){let e=0,i=0,s=0,n=0,o=!0;for(const a of t){const h=ps(a);for(const u of h){const c=u.x,m=u.y;o?(o=!1,e=i=c,s=n=m):(c<e?e=c:c>i&&(i=c),m<s?s=m:m>n&&(n=m))}}return At.parallelogramByCornerSideSide(new d(e,s),new d(0,n-s),new d(i-e,0))}}function*ps(l){yield l.corner,yield l.aPlusCorner,yield l.otherCorner,yield l.bPlusCorner}class D{constructor(t,e,i,s){this.parStart=0,this.parEnd=1,this.start=new d(t,e),this.end=new d(i,s)}static fromJSON(t){return D.mkPP(d.fromJSON(t.start),d.fromJSON(t.end))}toJSON(){return{start:this.start.toJSON(),end:this.end.toJSON()}}offsetCurve(t,e){return null}trim(t,e){if(t=Math.max(this.parStart,t),e=Math.min(this.parEnd,e),t>e)throw"wrong params in trimming";const i=this.value(t),s=this.value(e);return d.close(i,s,C.distanceEpsilon)?null:D.mkPP(i,s)}value(t){return this.start.add(this.end.sub(this.start).mul(t))}trimWithWrap(t,e){return null}pNodeOverICurve(){const t=this.end.sub(this.start).mul(.5);return{parallelogram:At.parallelogramByCornerSideSide(this.start,t,t),seg:this,leafBoxesOffset:0,node:{low:0,high:1,chord:this}}}normal(){let t=this.start.sub(this.end);return t=t.div(t.length),new d(-t.y,t.x)}static mkPP(t,e){return new D(t.x,t.y,e.x,e.y)}static mkLinePXY(t,e,i){return new D(t.x,t.y,e,i)}derivative(t){return this.end.sub(this.start)}secondDerivative(t){return new d(0,0)}thirdDerivative(t){return new d(0,0)}reverse(){return D.mkPP(this.end,this.start)}translate(t){this.start=this.start.add(t),this.end=this.end.add(t)}scaleFromOrigin(t,e){return D.mkPP(this.start.scale(t,e),this.end.scale(t,e))}getParameterAtLength(t){const e=this.end.sub(this.start).length;if(e<C.tolerance)return 0;const i=t/e;return i>1?1:i<0?0:i}transform(t){return D.mkPP(t.multiplyPoint(this.start),t.multiplyPoint(this.end))}closestParameterWithinBounds(t,e,i){let s=this.closestParameter(t);return s<e&&(s=e),s>i&&(s=i),s}lengthPartial(t,e){return this.value(e).sub(this.value(t)).length}get length(){return this.start.sub(this.end).length}get boundingBox(){return Z.mkPP(this.start,this.end)}clone(){return D.mkPP(this.start.clone(),this.end.clone())}static closestParameterOnLineSegment(t,e,i){const s=i.sub(e),n=t.sub(e),o=s.dot(n);if(o<=0+C.tolerance)return 0;const a=s.dot(s);return a<=o+C.tolerance?1:o/a}closestParameter(t){return D.closestParameterOnLineSegment(t,this.start,this.end)}leftDerivative(t){return this.derivative(t)}rightDerivative(t){return this.derivative(t)}static IntersectPPPP(t,e,i,s){const n=d.lineLineIntersection(t,e,i,s);if(n!=null&&Ri(n,t,e)&&Ri(n,i,s))return n}curvature(t){return 0}curvatureDerivative(t){return 0}curvatureSecondDerivative(t){return 0}static minDistBetweenLineSegments(t,e,i,s){const n=e.sub(t),o=s.sub(i),a=t.sub(i),h=d.crossProduct(n,o),u=n.dot(n),c=n.dot(o),m=o.dot(o),S=n.dot(a),A=o.dot(a);let I,B;const q=Math.abs(h);let rt=q,ct=q;q<C.tolerance?(I=0,rt=1,B=A,ct=m):(I=d.crossProduct(o,a),B=d.crossProduct(n,a),h<0&&(I=-I,B=-B),I<0?(I=0,B=A,ct=m):I>rt&&(I=rt=1,B=A+c,ct=m)),B<0?(B=0,-S<0?I=0:-S>u?I=rt:(I=-S,rt=u)):B>ct&&(B=ct=1,-S+c<0?I=0:-S+c>u?I=rt:(I=-S+c,rt=u));const Q=Math.abs(I)<C.tolerance?0:I/rt,pt=Math.abs(B)<C.tolerance?0:B/ct;return{parab:Q,parcd:pt,dist:a.add(n.mul(Q).sub(o.mul(pt))).length}}}function Ri(l,t,e){return l.x>=Math.min(t.x,e.x)-C.distanceEpsilon&&l.y>=Math.min(t.y,e.y)-C.distanceEpsilon&&l.x<=Math.max(t.x,e.x)+C.distanceEpsilon&&l.y<=Math.max(t.y,e.y)+C.distanceEpsilon}function On(l,t,e,i){const s=d.getTriangleOrientation(l,t,e),n=d.getTriangleOrientation(l,t,i),o=d.getTriangleOrientation(e,i,l),a=d.getTriangleOrientation(e,i,t);return!!(s!=n&&o!=a||s==k.Collinear&&Ri(e,l,t)||n==k.Collinear&&Ri(i,l,t)||o==k.Collinear&&Ri(l,e,i)||a==k.Collinear&&Ri(t,e,i))}function Di(l,t,e,i,s){return{parallelogram:e,seg:i,leafBoxesOffset:s,node:{low:l,high:t,chord:null}}}class jt{static distToSegm(t,e,i){const s=i.sub(e);if(s.length<C.intersectionEpsilon)return t.sub(e.add(i).div(2)).length;let n=new d(-s.y,s.x);return n=n.mul(1/n.length),Math.abs(t.sub(e).dot(n))}static createParallelogramOnSubSeg(t,e,i){let s=i.derivative(t);const n=i.derivative(e),o=new d(-n.y,n.x),a=i.value(t),h=i.value(e),c=h.sub(a).dot(o),m=s.dot(o),S=Math.abs(c)<C.distanceEpsilon;if(!S&&Math.abs(m)<C.distanceEpsilon)return;const A=S?0:c/m;return s=s.mul(A),At.parallelogramByCornerSideSide(a,s,h.sub(a).sub(s))}static createParallelogramNodeForCurveSeg(t,e,i,s){if(t===i.parStart&&e===i.parEnd&&d.close(i.start,i.end,C.distanceEpsilon))return jt.createNodeWithSegmentSplit(t,e,i,s);const o=i.value(t),a=i.value(e),h=a.sub(o),u=i.value((t+e)/2);if(jt.distToSegm(u,o,a)<=C.intersectionEpsilon&&h.dot(h)<C.lineSegmentThreshold*C.lineSegmentThreshold&&e-t<C.lineSegmentThreshold){const c=D.mkPP(o,a),m=c.pNodeOverICurve();m.seg=i;const S=m.node;return S.low=t,S.high=e,S.chord=c,m}if(jt.WithinEpsilon(i,t,e,s)){const c=jt.createParallelogramOnSubSeg(t,e,i);if(c!==void 0)return Di(t,e,c,i,s)}return jt.createNodeWithSegmentSplit(t,e,i,s)}static WithinEpsilon(t,e,i,s){const o=(i-e)/3,a=t.value(e),h=t.value(i);return jt.distToSegm(t.value(e+o),a,h)>s?!1:jt.distToSegm(t.value(e+o*(3-1)),a,h)<=s}static createParallelogramNodeForCurveSegDefaultOffset(t){return jt.createParallelogramNodeForCurveSeg(t.parStart,t.parEnd,t,C.defaultLeafBoxesOffset)}static createNodeWithSegmentSplit(t,e,i,s){const n={parallelogram:null,seg:i,leafBoxesOffset:1,node:{children:[]}},o=n.node;return o.children.push(jt.createParallelogramNodeForCurveSeg(t,.5*(t+e),i,s)),o.children.push(jt.createParallelogramNodeForCurveSeg(.5*(t+e),e,i,s)),n.parallelogram=At.parallelogramOfTwo(o.children[0].parallelogram,o.children[1].parallelogram),n}}class Ei{constructor(t,e,i,s,n){this.par0=t,this.par1=e,this.x=i,this.seg0=s,this.seg1=n}}class ms{static closestPoint(t,e,i,s,n){let h=i,u=0,c=0,m,S=!1;do{const A=t.value(h),I=t.derivative(h),B=t.secondDerivative(h),q=I.dot(I)+A.sub(e).dot(B);if(Math.abs(q)<C.tolerance)return h;m=A.sub(e).dot(I.div(q)),h-=m,h>n+C.tolerance?(h=n,c++):h<s-C.tolerance&&(h=s,c++),u++}while(Math.abs(m)>C.tolerance&&!(S=u>=5||c>=5));return S&&t.value(i).sub(e).length<C.distanceEpsilon&&(h=i),h}}class vt{constructor(t,e,i,s,n){for(this.parStart=t,this.parEnd=e,this.aAxis=i,this.bAxis=s,this.center=n,this.pNode=null,this.setBoundingBox();this.parStart<0;)this.parStart+=Math.PI*2,this.parEnd+=Math.PI*2}isFullEllipse(){return this.parEnd===Math.PI*2&&this.parStart===0}static fromJSON(t){return new vt(t.parStart,t.parEnd,d.fromJSON(t.axis0),d.fromJSON(t.axis1),d.fromJSON(t.center))}toJSON(){return{parStart:this.parStart,parEnd:this.parEnd,axis0:this.aAxis.toJSON(),axis1:this.bAxis.toJSON(),center:this.center.toJSON()}}offsetCurve(t,e){const i=e.sub(this.center),s=d.angle(this.aAxis,i);if(this.aAxis.mul(Math.cos(s)).add(this.bAxis.mul(Math.sin(s))).length<i.length){const o=this.aAxis.length,a=this.bAxis.length;return vt.mkEllipsePPP(this.aAxis.normalize().mul(o+t),this.bAxis.normalize().mul(a+t),this.center)}{const o=this.aAxis.length,a=this.bAxis.length;return vt.mkEllipsePPP(this.aAxis.normalize().mul(o-t),this.bAxis.normalize().mul(a-t),this.center)}}reverse(){return null}static mkEllipsePPP(t,e,i){return new vt(0,Math.PI*2,t,e,i)}get start(){return this.value(this.parStart)}get end(){return this.value(this.parEnd)}trim(t,e){return new vt(Math.max(t,this.parStart),Math.min(e,this.parEnd),this.aAxis,this.bAxis,this.center)}trimWithWrap(t,e){return null}get boundingBox(){return this.box}value(t){return this.center.add(d.mkPoint(Math.cos(t),this.aAxis,Math.sin(t),this.bAxis))}derivative(t){return d.mkPoint(-Math.sin(t),this.aAxis,Math.cos(t),this.bAxis)}secondDerivative(t){return d.mkPoint(-Math.cos(t),this.aAxis,-Math.sin(t),this.bAxis)}thirdDerivative(t){return d.mkPoint(Math.sin(t),this.aAxis,-Math.cos(t),this.bAxis)}pNodeOverICurve(){return this.pNode!=null?this.pNode:this.pNode=jt.createParallelogramNodeForCurveSegDefaultOffset(this)}setBoundingBox(){if(N(this.parStart,0)&&N(this.parEnd,Math.PI*2))this.box=this.fullBox();else{this.box=Z.mkPP(this.start,this.end);let t;for(let e=Math.ceil(this.parStart/(Math.PI/2));(t=e*Math.PI/2)<this.parEnd;e++)t>this.parStart&&this.box.add(this.value(t))}}static mkEllipse(t,e,i,s,n,o){return new vt(t,e,i,s,new d(n,o))}static mkFullEllipsePPP(t,e,i){return new vt(0,Math.PI*2,t,e,i)}static mkFullEllipseNNP(t,e,i){return new vt(0,Math.PI*2,new d(t,0),new d(0,e),i)}static mkCircle(t,e){return vt.mkFullEllipseNNP(t,t,e)}translate(t){this.center=this.center.add(t),this.box.center=this.box.center.add(t),this.pNode=null}scaleFromOrigin(t,e){return new vt(this.parStart,this.parEnd,this.aAxis.mul(t),this.bAxis.mul(e),this.center.scale(t,e))}getParameterAtLength(t){let i=this.parStart,s=this.parEnd;const n=t+.001,o=t-.001;for(;s-i>C.distanceEpsilon;){const a=.5*(s+i),h=this.lengthPartial(this.parStart,a);if(h>n)s=a;else if(h<o)i=a;else return a}return(s+i)/2}transform(t){if(t!=null){const e=t.multiplyPoint(this.aAxis).sub(t.offset()),i=t.multiplyPoint(this.bAxis).sub(t.offset());return new vt(this.parStart,this.parEnd,e,i,t.multiplyPoint(this.center))}return this.clone()}closestParameterWithinBounds(t,e,i){const n=(i-e)/9;let o=e,a=Number.MAX_VALUE;for(let u=0;u<=8;u++){const c=e+u*n,m=t.sub(this.value(c)),S=m.dot(m);S<a&&(a=S,o=c)}o===0&&i===Math.PI*2&&(e=-Math.PI);let h=ms.closestPoint(this,t,o,e,i);return h<0&&(h+=2*Math.PI),h}lengthPartial(t,e){return w.lengthWithInterpolationAndThreshold(this.trim(t,e),C.lineSegmentThreshold/100)}get length(){return(this.aAxis.length+this.bAxis.length)*Math.abs(this.parEnd-this.parStart)/2}clone(){return new vt(this.parStart,this.parEnd,this.aAxis.clone(),this.bAxis.clone(),this.center.clone())}closestParameter(t){let e=0;const i=8,s=(this.parEnd-this.parStart)/(i+1);let n=this.parStart,o=Number.MAX_VALUE;for(let u=0;u<=i;u++){const c=this.parStart+u*s,m=t.sub(this.value(c)),S=m.dot(m);S<o&&(o=S,n=c)}let a=!1;n===0&&this.parEnd===Math.PI*2&&(a=!0,e=this.parStart,this.parStart=-Math.PI);let h=ms.closestPoint(this,t,n,this.parStart,this.parEnd);return h<0&&(h+=2*Math.PI),a&&(this.parStart=e),h}leftDerivative(t){return this.derivative(t)}rightDerivative(t){return this.derivative(t)}curvature(t){throw"NotImplementedException()"}curvatureDerivative(t){throw"NotImplementedException();"}curvatureSecondDerivative(t){throw"NotImplementedException()"}orientedCounterclockwise(){return d.crossProduct(this.aAxis,this.bAxis)>0}fullBox(){const t=this.aAxis.add(this.bAxis);return Z.mkPP(this.center.add(t),this.center.sub(t))}isArc(){return Math.abs(this.aAxis.dot(this.bAxis))<C.tolerance&&Math.abs(this.aAxis.length-this.bAxis.length)<C.tolerance&&d.closeDistEps(this.aAxis.rotate90Ccw(),this.bAxis)}}class Ln{constructor(t,e,i,s,n,o,a,h){this.curveA=t,this.curveB=e,this.aMin=i,this.bMin=n,this.aMax=s,this.bMax=o,this.aGuess=a,this.bGuess=h,this.si=a,this.ti=h}initValues(){this.a=this.curveA.value(this.si),this.b=this.curveB.value(this.ti),this.a_b=this.a.sub(this.b),this.ad=this.curveA.derivative(this.si),this.add=this.curveA.secondDerivative(this.si),this.bd=this.curveB.derivative(this.ti),this.bdd=this.curveB.secondDerivative(this.ti)}Fs(){return this.a_b.dot(this.ad)}Fss(){return this.a_b.dot(this.add)+this.ad.dot(this.ad)}Fst(){return-this.bd.dot(this.ad)}Ftt(){return-this.a_b.dot(this.bdd)+this.bd.dot(this.bd)}Ft(){return-this.a_b.dot(this.bd)}delta(t,e,i,s){return t*s-i*e}solve(){let t=0;const e=10;let i=0;const s=100;let n=!1;if(this.initValues(),this.curveA instanceof D&&this.curveB instanceof D){let a=this.curveB.derivative(0);a=a.div(a.length);const h=this.curveA.normal(),u=Math.abs(h.dot(a));if(Math.abs(u)<C.distanceEpsilon||this.delta(this.Fss(),this.Fst(),this.Fst(),this.Ftt())<C.tolerance){this.success=!0,this.parallelLineSegLineSegMinDist();return}}let o;do{const a=this.delta(this.Fss(),this.Fst(),this.Fst(),this.Ftt());if(Math.abs(a)<C.tolerance){this.success=!1,n=!0;break}o={s:this.delta(-this.Fs(),this.Fst(),-this.Ft(),this.Ftt())/a,t:this.delta(this.Fss(),-this.Fs(),this.Fst(),-this.Ft())/a};const h=this.si+o.s,u=this.ti+o.t;let c;h>this.aMax+C.distanceEpsilon||h<this.aMin-C.distanceEpsilon||u>this.bMax+C.distanceEpsilon||u<this.bMin-C.distanceEpsilon?(t++,this.chopDsDt(o),this.si+=o.s,this.ti+=o.t,c=!0):(c=!1,this.si=h,this.ti=u,this.si>this.aMax?this.si=this.aMax:this.si<this.aMin&&(this.si=this.aMin),this.ti>this.bMax?this.ti=this.bMax:this.ti<this.bMin&&(this.ti=this.bMin)),this.initValues(),i++,n=t>=e||i>=s||o.s===0&&o.t===0&&c}while((Math.abs(o.s)>=C.tolerance||Math.abs(o.t)>=C.tolerance)&&!n);if(n){const a=this.curveA.value(this.aGuess).sub(this.curveB.value(this.bGuess));if(a.dot(a)<C.distanceEpsilon*C.distanceEpsilon){this.aSolution=this.aGuess,this.bSolution=this.bGuess,this.aPoint=this.curveA.value(this.aGuess),this.bPoint=this.curveB.value(this.bGuess),this.success=!0;return}}this.aSolution=this.si,this.bSolution=this.ti,this.aPoint=this.a,this.bPoint=this.b,this.success=!n}chopDsDt(t){if(t.s!==0&&t.t!==0){let e=1;this.si+t.s>this.aMax?e=(this.aMax-this.si)/t.s:this.si+t.s<this.aMin&&(e=(this.aMin-this.si)/t.s);let i=1;this.ti+t.t>this.bMax?i=(this.bMax-this.ti)/t.t:this.ti+t.t<this.bMin&&(i=(this.bMin-this.ti)/t.t);const s=Math.min(e,i);t.s*=s,t.t*=s}else t.s===0?this.ti+t.t>this.bMax?t.t=this.bMax-this.ti:this.ti+t.t<this.bMin&&(t.t=this.bMin-this.ti):this.si+t.s>this.aMax?t.s=this.aMax-this.si:this.si+t.s<this.aMin&&(t.s=this.aMin-this.si)}parallelLineSegLineSegMinDist(){const t=this.curveA,e=this.curveB,i=t.start,s=t.end,n=e.start,o=e.end;let a=s.sub(i);const h=a.length;let u=0,c,m,S;if(h>C.distanceEpsilon){a=a.div(h),c=a.dot(s.sub(i)),m=a.dot(n.sub(i)),S=a.dot(o.sub(i));let A=!1;if(m>S){A=!0;const I=m;m=S,S=I}if(S<u)this.aSolution=0,this.bSolution=A?0:1;else if(m>c)this.aSolution=1,this.bSolution=A?1:0;else{const I=Math.min(c,S);this.aSolution=I/(c-u),this.bSolution=(I-m)/(S-m),A&&(this.bSolution=1-this.bSolution)}}else{let A=o.sub(n);const I=A.length;if(I>C.distanceEpsilon)if(A=A.div(I),u=0,c=A.dot(o.sub(n)),m=A.dot(i.sub(n)),m<u)this.bSolution=0,this.aSolution=1;else if(m>c)this.bSolution=1,this.aSolution=0;else{const B=Math.min(c,m);this.bSolution=B/(c-u),this.aSolution=0}else this.aSolution=0,this.bSolution=0}this.aPoint=this.curveA.value(this.aSolution),this.bPoint=this.curveB.value(this.bSolution)}}class Nt{constructor(t,e,i,s){this.b=new Array(4),this.parStart=0,this.parEnd=1,this.b[0]=t,this.b[1]=e,this.b[2]=i,this.b[3]=s,this.c=this.b[1].sub(this.b[0]).mul(3),this.e=this.b[2].sub(this.b[1]).mul(3).sub(this.c),this.l=this.b[3].sub(this.b[0]).sub(this.c).sub(this.e)}toJSON(){return{b:this.b.map(t=>t.toJSON())}}static fromJSON(t){return Nt.mkBezier(t.b.map(d.fromJSON))}leftDerivative(t){return this.derivative(t)}rightDerivative(t){return this.derivative(t)}B(t){return this.b[t]}pNodeOverICurve(){return this.pBoxNode!=null?this.pBoxNode:this.pBoxNode=jt.createParallelogramNodeForCurveSegDefaultOffset(this)}value(t){const e=t*t,i=e*t;return this.l.mul(i).add(this.e.mul(e).add(this.c.mul(t)).add(this.b[0]))}static adjustParamTo01(t){return t>1?1:t<0?0:t}trim(t,e){if(t=Nt.adjustParamTo01(t),e=Nt.adjustParamTo01(e),t>e)return this.trim(e,t);if(t>1-C.tolerance)return new Nt(this.b[3],this.b[3],this.b[3],this.b[3]);const i=new Array(3),s=new Array(2),n=this.casteljau(t,i,s),o=new Nt(n,s[1],i[2],this.b[3]),a=o.casteljau((e-t)/(1-t),i,s);return new Nt(o.b[0],i[0],s[0],a)}trimWithWrap(t,e){throw"NotImplementedException()"}casteljau(t,e,i){const s=1-t;for(let n=0;n<3;n++)e[n]=d.mkPoint(s,this.b[n],t,this.b[n+1]);for(let n=0;n<2;n++)i[n]=d.mkPoint(s,e[n],t,e[n+1]);return d.mkPoint(s,i[0],t,i[1])}derivative(t){return this.l.mul(3*t*t).add(this.e.mul(2*t)).add(this.c)}secondDerivative(t){return d.mkPoint(6*t,this.l,2,this.e)}thirdDerivative(t){return this.l.mul(6)}get start(){return this.b[0]}get end(){return this.b[3]}reverse(){return new Nt(this.b[3],this.b[2],this.b[1],this.b[0])}translate(t){this.b[0]=this.b[0].add(t),this.b[1]=this.b[1].add(t),this.b[2]=this.b[2].add(t),this.b[3]=this.b[3].add(t),this.c=this.b[1].sub(this.b[0]).mul(3),this.e=this.b[2].sub(this.b[1]).mul(3).sub(this.c),this.l=this.b[3].sub(this.b[0]).sub(this.c).sub(this.e),this.bbox&&(this.bbox=Z.translate(this.bbox,t)),this.pBoxNode=null}scaleFromOrigin(t,e){return new Nt(this.b[0].scale(t,e),this.b[1].scale(t,e),this.b[2].scale(t,e),this.b[3].scale(t,e))}offsetCurve(t,e){return null}lengthPartial(t,e){return this.trim(t,e).length}get length(){return Nt.lengthOnControlPolygon(this.b[0],this.b[1],this.b[2],this.b[3])}static lengthOnControlPolygon(t,e,i,s){const n=s.sub(t).length,o=e.sub(t).length+i.sub(e).length+s.sub(i).length;if(o-n>C.lineSegmentThreshold){const a=d.middle(t,e),h=d.middle(e,i),u=d.middle(i,s),c=d.middle(a,h),m=d.middle(u,h),S=d.middle(c,m);return Nt.lengthOnControlPolygon(t,a,c,S)+Nt.lengthOnControlPolygon(S,m,u,s)}return(o+n)/2}get boundingBox(){return this.bbox?this.bbox:this.bbox=Z.mkOnPoints(this.b)}transform(t){return new Nt(t.multiplyPoint(this.b[0]),t.multiplyPoint(this.b[1]),t.multiplyPoint(this.b[2]),t.multiplyPoint(this.b[3]))}closestParameterWithinBounds(t,e,i){const s=(i-e)/8;let n=0,o=Number.MAX_VALUE;for(let a=0;a<9;a++){const h=t.sub(this.value(a*s+e)),u=h.dot(h);u<o&&(o=u,n=a*s+e)}return ms.closestPoint(this,t,n,e,i)}clone(){return new Nt(this.b[0],this.b[1],this.b[2],this.b[3])}static mkBezier(t){return new Nt(t[0],t[1],t[2],t[3])}curvature(t){const e=this.G(t);return this.F(t)/e}F(t){return this.Xp(t)*this.Ypp(t)-this.Yp(t)*this.Xpp(t)}G(t){const e=this.Xp(t),i=this.Yp(t),s=e*e+i*i;return Math.sqrt(s*s*s)}Xp(t){return 3*this.l.x*t*t+2*this.e.x*t+this.c.x}Ypp(t){return 6*this.l.y*t+2*this.e.y}Yp(t){return 3*this.l.y*t*t+2*this.e.y*t+this.c.y}Xpp(t){return 6*this.l.x*t+2*this.e.x}Xppp(t){return 6*this.l.x}Yppp(t){return 6*this.l.y}curvatureDerivative(t){const e=this.G(t);return(this.Fp(t)*e-this.Gp(t)*this.F(t))/(e*e)}Fp(t){return this.Xp(t)*this.Yppp(t)-this.Yp(t)*this.Xppp(t)}Fpp(t){return this.Xpp(t)*this.Yppp(t)-this.Ypp(t)*this.Xppp(t)}closestParameter(t){let i=0,s=Number.MAX_VALUE;for(let n=0;n<9;n++){const o=t.sub(this.value(n*.125)),a=o.dot(o);a<s&&(s=a,i=n*.125)}return ms.closestPoint(this,t,i,0,1)}curvatureSecondDerivative(t){const e=this.G(t);return(this.Qp(t)*e-2*this.Q(t)*this.Gp(t))/(e*e*e)}Q(t){return this.Fp(t)*this.G(t)-this.Gp(t)*this.F(t)}Qp(t){return this.Fpp(t)*this.G(t)-this.Gpp(t)*this.F(t)}Gpp(t){const e=this.Xp(t),i=this.Yp(t),s=this.Xpp(t),n=this.Ypp(t),o=this.Xppp(t),a=this.Yppp(t),h=Math.sqrt(e*e+i*i),u=e*s+i*n;return 3*(u*u/h+h*(s*s+e*o+n*n+i*a))}Gp(t){const e=this.Xp(t),i=this.Yp(t),s=this.Xpp(t),n=this.Ypp(t);return 3*Math.sqrt(e*e+i*i)*(e*s+i*n)}getParameterAtLength(t){let e=0,i=1;for(;i-e>C.tolerance;){const s=(i+e)/2,n=this.evaluateError(t,s);if(n>0)i=s;else if(n<0)e=s;else return s}return(e+i)/2}evaluateError(t,e){const i=1-e,s=d.mkPoint(i,this.b[0],e,this.b[1]),n=d.mkPoint(i,this.b[1],e,this.b[2]),o=d.mkPoint(i,this.b[2],e,this.b[3]),a=d.mkPoint(i,s,e,n),h=d.mkPoint(i,n,e,o),u=d.mkPoint(i,a,e,h),c=Nt.lengthOnControlPolygon(this.b[0],s,a,u);return c>t+C.distanceEpsilon?1:c<t-C.distanceEpsilon?-1:0}}function hr(l){return l.seg.value(l.par)}function Xs(l){return l.seg.derivative(l.par)}function Qs(l){return l.seg.secondDerivative(l.par)}function Bn(l){return l.seg.thirdDerivative(l.par)}var ft;(function(l){l[l.Outside=0]="Outside",l[l.Boundary=1]="Boundary",l[l.Inside=2]="Inside"})(ft||(ft={}));function ur(l){if(l instanceof vt)return{tag:"ellipse",segData:l.toJSON()};if(l instanceof D)return{tag:"lineSegment",segData:l.toJSON()};if(l instanceof Nt)return{tag:"bezier",segData:l.toJSON()};throw new Error("not implemented")}class w{constructor(){this.segs=[],this.parEnd_=0}static fromJSON(t){const e=new w;for(const i of t.segs)switch(i.tag){case"bezier":e.addSegment(Nt.fromJSON(i.segData));break;case"ellipse":e.addSegment(vt.fromJSON(i.segData));break;case"lineSegment":e.addSegment(D.fromJSON(i.segData));break;default:throw new Error("not implemented")}return e}toJSON(){return{segs:this.segs.map(t=>ur(t))}}static CurvesIntersect(t,e){return t===e||w.intersectionOne(t,e,!1)!=null}static lengthWithInterpolationAndThreshold(t,e){throw new Error("not implemented")}static lengthWithInterpolation(t){throw"not implemented"}get parStart(){return 0}get parEnd(){return this.parEnd_}lengthPartial(t,e){const i={start:t,end:e};this.adjustStartEndEndParametersToDomain(i);const s=this.getSegIndexParam(t),n=this.getSegIndexParam(e);if(s.segIndex<n.segIndex){let o=this.segs[s.segIndex],a=o.lengthPartial(s.par,o.parEnd);for(let h=s.segIndex+1;h<n.segIndex;h++)a+=this.segs[h].length;return o=this.segs[n.segIndex],a+o.lengthPartial(o.parStart,n.par)}else throw new Error("not implemented.")}reverse(){const t=new w;for(let e=this.segs.length-1;e>=0;e--)t.addSegment(this.segs[e].reverse());return t}mkCurveWithSegs(t){this.segs=t;for(const e of t)this.parEnd_+=w.paramSpan(e)}get start(){return this.segs[0].start}get end(){return this.segs[this.segs.length-1].end}scaleFromOrigin(t,e){const i=new w;for(const s of this.segs)i.addSegment(s.scaleFromOrigin(t,e));return i}trim(t,e){const i={start:t,end:e};this.adjustStartEndEndParametersToDomain(i);const s=this.getSegIndexParam(i.start),n=this.getSegIndexParam(i.end);if(s.segIndex===n.segIndex)return this.segs[s.segIndex].trim(s.par,n.par);let o=new w;s.par<this.segs[s.segIndex].parEnd&&(o=o.addSegment(this.segs[s.segIndex].trim(s.par,this.segs[s.segIndex].parEnd)));for(let a=s.segIndex+1;a<n.segIndex;a++)o=o.addSegment(this.segs[a]);return this.segs[n.segIndex].parStart<n.par&&(o=o.addSegment(this.segs[n.segIndex].trim(this.segs[n.segIndex].parStart,n.par))),o}translate(t){for(const e of this.segs)e.translate(t);this.boundingBox_&&(this.boundingBox_=Z.translate(this.boundingBox_,t)),this.pBNode=null}adjustStartEndEndParametersToDomain(t){if(t.start>t.end){const e=t.start;t.start=t.end,t.end=e}t.start<this.parStart&&(t.start=this.parStart),t.end>this.parEnd&&(t.end=this.parEnd)}trimWithWrap(t,e){if(t<e)return this.trim(t,e);const i=new w;return i.addSegment(this.trim(t,this.parEnd)),i.addSegment(this.trim(this.parStart,e)),i}addSegs(t){for(const e of t)this.addSegment(e);return this}addSegment(t){if(t==null)return this;if(this.boundingBox_=null,!(t instanceof w))this.segs.push(t),this.parEnd_+=w.paramSpan(t);else for(const e of t.segs)this.segs.push(e),this.parEnd_+=w.paramSpan(e);return this}pNodeOverICurve(){if(this.pBNode!=null)return this.pBNode;const t=[],e=[];for(const i of this.segs){const s=i.pNodeOverICurve();t.push(s.parallelogram),e.push(s)}return this.pBNode={parallelogram:At.getParallelogramOfAGroup(t),seg:this,leafBoxesOffset:C.defaultLeafBoxesOffset,node:{children:e}},this.pBNode}static intersectionOne(t,e,i){let s=w.curveCurveXWithParallelogramNodesOne(t.pNodeOverICurve(),e.pNodeOverICurve());return i&&s!=null&&(s=w.liftIntersectionToCurves(t,e,s)),s}static getAllIntersections(t,e,i){return t instanceof D?w.getAllIntersectionsOfLineAndICurve(t,e,i):w.getAllIntersectionsInternal(t,e,i)}static getAllIntersectionsInternal(t,e,i){const s=[];if(w.curveCurveXWithParallelogramNodes(t.pNodeOverICurve(),e.pNodeOverICurve(),s),i)for(let n=0;n<s.length;n++)s[n]=w.liftIntersectionToCurves(t,e,s[n]);return s}static getAllIntersectionsOfLineAndICurve(t,e,i){return e instanceof at?w.getAllIntersectionsOfLineAndPolyline(t,e):e instanceof w?w.getAllIntersectionsOfLineAndCurve(t,e,i):e instanceof vt&&e.isArc()?w.getAllIntersectionsOfLineAndArc(t,e):w.getAllIntersectionsInternal(t,e,i)}static getAllIntersectionsOfLineAndCurve(t,e,i){const s=[],n=t.pNodeOverICurve(),o=e.pNodeOverICurve();if(At.intersect(n.parallelogram,o.parallelogram)===!1)return s;let a=0;for(const h of e.segs){const u=w.getAllIntersections(t,h,!1);if(i){for(const c of u)c.par1+=a-h.parStart,c.seg1=e;a+=h.parEnd-h.parStart}for(const c of u)w.alreadyInside(s,c)||s.push(c)}return s}static closeIntersections(t,e){return d.close(t.x,e.x,C.intersectionEpsilon)}static closeIntersectionPoints(t,e){return d.close(t,e,C.intersectionEpsilon)}static alreadyInside(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(w.closeIntersections(s,e))return!0}return!1}static getAllIntersectionsOfLineAndArc(t,e){let i=t.end.sub(t.start);const s=[],n=i.length;if(n<C.distanceEpsilon){const m=t.start.sub(e.center);if(N(m.length,e.aAxis.length)){let S=d.angle(e.aAxis,m);e.parStart-C.tolerance<=S&&(S=Math.max(S,e.parStart),S<=e.parEnd+C.tolerance&&(S=Math.min(e.parEnd,S),s.push(new Ei(0,S,t.start,t,e))))}return s}const o=i.rotate90Ccw().div(n),a=t.start.sub(e.center).dot(o),h=e.center.add(o.mul(a)),u=e.aAxis.length,c=Math.abs(a);if(u<c-C.distanceEpsilon)return s;if(i=o.rotate90Cw(),N(u,c))w.tryToAddPointToLineCircleCrossing(t,e,s,h,n,i);else{const m=Math.sqrt(u*u-a*a),S=i.mul(m);w.tryToAddPointToLineCircleCrossing(t,e,s,h.add(S),n,i),w.tryToAddPointToLineCircleCrossing(t,e,s,h.sub(S),n,i)}return s}static tryToAddPointToLineCircleCrossing(t,e,i,s,n,o){let h=s.sub(t.start).dot(o);if(h<-C.distanceEpsilon||(h=Math.max(h,0),h>n+C.distanceEpsilon))return;h=Math.min(h,n),h/=n;let u=d.angle(e.aAxis,s.sub(e.center));e.parStart-C.tolerance<=u&&(u=Math.max(u,e.parStart),u<=e.parEnd+C.tolerance&&(u=Math.min(e.parEnd,u),i.push(new Ei(h,u,s,t,e))))}static getAllIntersectionsOfLineAndPolyline(t,e){const i=[];let s=0,n=e.startPoint;for(;n!=null&&n.getNext()!=null;n=n.getNext()){const o=w.crossTwoLineSegs(t.start,t.end,n.point,n.getNext().point,0,1,0,1);o&&(w.adjustSolution(t.start,t.end,n.point,n.getNext().point,o),w.oldIntersection(i,o.x)||i.push(new Ei(o.aSol,s+o.bSol,o.x,t,e))),s++}if(e.closed){const o=w.crossTwoLineSegs(t.start,t.end,n.point,e.start,0,1,0,1);o&&(w.adjustSolution(t.start,t.end,n.point,e.start,o),w.oldIntersection(i,o.x)||i.push(new Ei(o.aSol,s+o.bSol,o.x,t,e)))}return i}static adjustSolution(t,e,i,s,n){w.closeIntersectionPoints(n.x,t)?(n.x=t,n.aSol=0):w.closeIntersectionPoints(n.x,e)&&(n.x=e,n.aSol=1),w.closeIntersectionPoints(n.x,i)?(n.x=i,n.bSol=Math.floor(n.bSol)):w.closeIntersectionPoints(n.x,s)&&(n.x=s,n.bSol=Math.ceil(n.bSol))}static curveCurveXWithParallelogramNodesOne(t,e){if(!At.intersect(t.parallelogram,e.parallelogram))return null;const i=t.node,s=e.node,n=i.hasOwnProperty("children"),o=s.hasOwnProperty("children");if(n&&o)for(const a of i.children)for(const h of s.children){const u=w.curveCurveXWithParallelogramNodesOne(a,h);if(u!=null)return u}else if(o)for(const a of s.children){const h=w.curveCurveXWithParallelogramNodesOne(t,a);if(h!=null)return h}else if(n)for(const a of i.children){const h=w.curveCurveXWithParallelogramNodesOne(a,e);if(h!=null)return h}else return w.crossOverIntervalsOne(t,e);return null}static curveCurveXWithParallelogramNodes(t,e,i){if(!At.intersect(t.parallelogram,e.parallelogram))return;const s=t.node.hasOwnProperty("children"),n=e.node.hasOwnProperty("children");if(s&&n)for(const o of t.node.children)for(const a of e.node.children)w.curveCurveXWithParallelogramNodes(o,a,i);else if(n)for(const o of e.node.children)w.curveCurveXWithParallelogramNodes(t,o,i);else if(s)for(const o of t.node.children)w.curveCurveXWithParallelogramNodes(o,e,i);else i=w.crossOverLeaves(t,e,i)}static crossOverIntervalsOne(t,e){const i=t.node,s=e.node,n=(i.high-i.low)/2,o=(s.high-s.low)/2;for(let a=1;a<2;a++){const h=a*n+i.low;for(let u=1;u<2;u++){const c=u*o+s.low;let m;if(i.chord==null&&s.chord==null?m=w.crossWithinIntervalsWithGuess(t.seg,e.seg,i.low,i.high,s.low,s.high,h,c):i.chord!=null&&s.chord==null?m=w.crossWithinIntervalsWithGuess(i.chord,e.seg,0,1,s.low,s.high,.5*a,c):i.chord==null?(m=w.crossWithinIntervalsWithGuess(t.seg,s.chord,i.low,i.high,0,1,h,.5*u),m&&(m.bSol=s.low+m.bSol*(s.high-s.low))):(m=w.crossWithinIntervalsWithGuess(i.chord,s.chord,0,1,0,1,.5*a,.5*u),m&&(m.aSol=i.low+m.aSol*(i.high-i.low),m.bSol=s.low+m.bSol*(s.high-s.low))),m)return w.createIntersectionOne(t,e,m.aSol,m.bSol,m.x)}}return w.goDeeperOne(t,e)}static crossOverLeaves(t,e,i){const s=t.node,n=e.node;let o=!1;const a=(s.high-s.low)/2+s.low,h=(n.high-n.low)/2+n.low;let u;return s.chord==null&&n.chord==null?u=w.crossWithinIntervalsWithGuess(t.seg,e.seg,s.low,s.high,n.low,n.high,a,h):s.chord!=null&&n.chord==null?(u=w.crossWithinIntervalsWithGuess(s.chord,e.seg,0,1,n.low,n.high,.5,h),u&&(u.aSol=s.low+u.aSol*(s.high-s.low))):s.chord==null?(u=w.crossWithinIntervalsWithGuess(t.seg,n.chord,s.low,s.high,0,1,a,.5),u&&(u.bSol=n.low+u.bSol*(n.high-n.low))):(u=w.crossWithinIntervalsWithGuess(s.chord,n.chord,0,1,0,1,.5,.5),u&&(u.bSol=n.low+u.bSol*(n.high-n.low),u.aSol=s.low+u.aSol*(s.high-s.low))),u&&(w.addIntersection(t,e,i,u),o=!0),o||w.goDeeper(i,t,e),i}static addIntersection(t,e,i,s){const n=t.node;w.closeIntersectionPoints(s.x,t.seg.value(n.low))?(s.x=t.seg.value(n.low),s.aSol=n.low):w.closeIntersectionPoints(s.x,t.seg.value(n.high))&&(s.x=t.seg.value(n.high),s.aSol=n.high);const o=e.node;if(w.closeIntersectionPoints(s.x,e.seg.value(o.low))?(s.x=e.seg.value(o.low),s.bSol=o.low):w.closeIntersectionPoints(s.x,e.seg.value(o.high))&&(s.x=e.seg.value(o.high),s.bSol=o.high),!w.oldIntersection(i,s.x)){const h=new Ei(s.aSol,s.bSol,s.x,t.seg,e.seg);i.push(h)}}static oldIntersection(t,e){for(const i of t)if(e.sub(i.x).length<C.distanceEpsilon*100)return!0;return!1}static createIntersectionOne(t,e,i,s,n){const o=t.node,a=e.node;return w.closeIntersectionPoints(n,t.seg.value(o.low))?(n=t.seg.value(o.low),i=o.low):w.closeIntersectionPoints(n,t.seg.value(o.high))&&(n=t.seg.value(o.high),i=o.high),w.closeIntersectionPoints(n,e.seg.value(a.low))?(n=e.seg.value(a.low),s=a.low):w.closeIntersectionPoints(n,e.seg.value(a.high))&&(n=e.seg.value(a.high),s=a.high),new Ei(i,s,n,t.seg,e.seg)}static liftIntersectionToCurves_(t,e,i,s,n,o,a){const h=t instanceof w?w.liftParameterToCurve(t,i-o.parStart,o):i,u=e instanceof w?w.liftParameterToCurve(e,s-a.parStart,a):s;return new Ei(h,u,n,t,e)}static DropIntersectionToSegs(t){let e,i;if(t.seg0 instanceof w){const o=t.seg0.getSegParam(t.par0);e=o.seg,i=o.par}else i=t.par0,e=t.seg0;let s,n;if(t.seg1 instanceof w){const o=t.seg1.getSegParam(t.par1);n=o.par,s=o.seg}else n=t.par1,s=t.seg1;return new Ei(i,n,t.x,e,s)}static liftIntersectionToCurves(t,e,i){return w.liftIntersectionToCurves_(t,e,i.par0,i.par1,i.x,i.seg0,i.seg1)}static liftParameterToCurve(t,e,i){if(t===i)return e;if(!t.hasOwnProperty("segs"))return;const s=t;let n=0;for(const o of s.segs){if(o===i)return e+n;n+=w.paramSpan(o)}throw"bug in liftParameterToCurve"}static paramSpan(t){return t.parEnd-t.parStart}static goDeeperOne(t,e){const i=t.node,s=e.node;if(t.leafBoxesOffset>C.distanceEpsilon&&e.leafBoxesOffset>C.distanceEpsilon){const a=jt.createParallelogramNodeForCurveSeg(i.low,i.high,t.seg,t.leafBoxesOffset/2),h=jt.createParallelogramNodeForCurveSeg(s.low,s.high,e.seg,e.leafBoxesOffset/2);return w.curveCurveXWithParallelogramNodesOne(a,h)}if(t.leafBoxesOffset>C.distanceEpsilon){const a=jt.createParallelogramNodeForCurveSeg(i.low,i.high,t.seg,t.leafBoxesOffset/2);return w.curveCurveXWithParallelogramNodesOne(a,e)}if(e.leafBoxesOffset>C.distanceEpsilon){const a=jt.createParallelogramNodeForCurveSeg(s.low,s.high,e.seg,e.leafBoxesOffset/2);return w.curveCurveXWithParallelogramNodesOne(t,a)}const n=t.seg.value(i.low),o=t.seg.value(i.high);if(!d.closeDistEps(n,o)){const a=e.seg.value(s.low),h=e.seg.value(s.high);if(!d.closeDistEps(a,h)){const u=t.seg instanceof D?t.seg:D.mkPP(n,o),c=e.seg instanceof D?e.seg:D.mkPP(a,h),m=w.crossWithinIntervalsWithGuess(u,c,0,1,0,1,.5,.5);if(m)return w.adjustParameters(t,u,e,c,m),w.createIntersectionOne(t,e,m.aSol,m.bSol,m.x)}}return null}static goDeeper(t,e,i){const s=e.node,n=i.node,o=e.leafBoxesOffset>C.distanceEpsilon,a=i.leafBoxesOffset>C.distanceEpsilon;if(o&&a){const h=jt.createParallelogramNodeForCurveSeg(s.low,s.high,e.seg,e.leafBoxesOffset/2),u=jt.createParallelogramNodeForCurveSeg(n.low,n.high,i.seg,i.leafBoxesOffset/2);w.curveCurveXWithParallelogramNodes(h,u,t)}else if(o){const h=jt.createParallelogramNodeForCurveSeg(s.low,s.high,e.seg,e.leafBoxesOffset/2);w.curveCurveXWithParallelogramNodes(h,i,t)}else if(a){const h=jt.createParallelogramNodeForCurveSeg(n.low,n.high,i.seg,i.leafBoxesOffset/2);w.curveCurveXWithParallelogramNodes(e,h,t)}else{const h=e.seg.value(s.low),u=e.seg.value(s.high);if(!d.closeDistEps(h,u)){const c=i.seg.value(n.low),m=i.seg.value(n.high);if(!d.closeDistEps(c,m)){const S=e.seg instanceof D?e.seg:D.mkPP(h,u),A=i.seg instanceof D?i.seg:D.mkPP(c,m),I=w.crossWithinIntervalsWithGuess(S,A,0,1,0,1,.5,.5);I&&(w.adjustParameters(e,S,i,A,I),w.addIntersection(e,i,t,I))}}}}static adjustParameters(t,e,i,s,n){if(e!==t.seg&&!(t.seg instanceof at))n.aSol=t.seg.closestParameter(n.x);else{const o=t.node;n.aSol=o.low+n.aSol*(o.high-o.low)}if(s!==i.seg&&!(i.seg instanceof at))n.bSol=i.seg.closestParameter(n.x);else{const o=i.node;n.bSol=o.low+n.bSol*(o.high-o.low)}}getSegParam(t){let e=this.parStart;for(const s of this.segs){const n=e+s.parEnd-s.parStart;if(t>=e&&t<=n)return{par:t-e+s.parStart,seg:s};e=n}const i=this.segs[this.segs.length-1];return{seg:i,par:i.parEnd}}getSegIndexParam(t){let e=0;const i=this.segs.length;for(let n=0;n<i;n++){const o=this.segs[n],a=e+o.parEnd-o.parStart;if(t>=e&&t<=a)return{segIndex:n,par:t-e+o.parStart};e=a}const s=this.segs[i-1];return{segIndex:i-1,par:s.parEnd}}value(t){return hr(this.getSegParam(t))}derivative(t){return Xs(this.getSegParam(t))}secondDerivative(t){return Qs(this.getSegParam(t))}thirdDerivative(t){return Bn(this.getSegParam(t))}static crossWithinIntervalsWithGuess(t,e,i,s,n,o,a,h){if(t instanceof D&&e instanceof D){const m=w.crossTwoLineSegs(t.start,t.end,e.start,e.end,i,s,n,o);if(m!==void 0)return m}const u=w.minDistWithinIntervals(t,e,i,s,n,o,a,h);if(u==null)return;const c=u.aX.sub(u.bX);return c.dot(c)>=C.distanceEpsilon?void 0:{aSol:u.aSol,bSol:u.bSol,x:d.middle(u.aX,u.bX)}}static crossTwoLineSegs(t,e,i,s,n,o,a,h){const u=e.sub(t),c=i.sub(s),m=i.sub(t),S=O.solve(u.x,c.x,m.x,u.y,c.y,m.y);if(S==null)return;let A=S.x,I=S.y;const B=t.add(u.mul(A));if(!(A<n-C.tolerance)&&(A=Math.max(A,n),!(A>o+C.tolerance)&&(A=Math.min(A,o),!(I<a-C.tolerance)&&(I=Math.max(I,a),!(I>h+C.tolerance)))))return I=Math.min(I,h),{aSol:A,bSol:I,x:B}}static PointRelativeToCurveLocation(t,e){if(!e.boundingBox.contains(t))return ft.Outside;const i=2*e.boundingBox.diagonal,s=Math.PI/180;let n=0;for(let o=13;o<360;o+=13){const a=new d(Math.cos(o*s),Math.sin(o*s)),h=D.mkPP(t,t.add(a.mul(i))),u=this.getAllIntersectionsOfLineAndICurve(h,e,!0);if(w.AllIntersectionsAreGood(u,e)){for(const m of u)if(d.closeDistEps(m.x,t))return ft.Boundary;if(u.length%2===1?n++:n--,n>=2)return ft.Inside;if(n<=-2)return ft.Outside}}return ft.Boundary}static AllIntersectionsAreGood(t,e){const i=e.hasOwnProperty("segs");let s=null;if(i||e instanceof at&&(s=e.toCurve()),s){for(const n of t)if(!w.RealCut(w.DropIntersectionToSegs(n),s,!1))return!1}return!0}static RealCut(t,e,i){const s=t.seg0,n=t.seg1,o=t.par0,a=t.par1,h=t.x,u=s.derivative(o).normalize(),c=n.derivative(a).normalize().rotate(Math.PI/2);if(d.closeDistEps(h,n.end)){let S=null;for(let B=0;B<e.segs.length-1;B++)if(e.segs[B]===n){S=e.segs[B+1];break}if(S==null)return!1;const A=u.rotate(Math.PI/2);return!(A.dot(n.derivative(n.parEnd))*A.dot(S.derivative(S.parStart))<C.tolerance)}if(d.closeDistEps(h,n.start)){let S=null;for(let B=e.segs.length-1;B>0;B--)if(e.segs[B]===n){S=e.segs[B-1];break}if(S==null)return!1;const A=u.rotate(Math.PI/2);return!(A.dot(n.derivative(n.parStart))*A.dot(S.derivative(S.parEnd))<C.tolerance)}const m=u.dot(c);return i?m>C.distanceEpsilon:Math.abs(m)>C.distanceEpsilon}static realCutWithClosedCurve(t,e,i){const s=t.seg0,n=t.seg1,o=t.par0,a=t.par1,h=t.x,u=s.derivative(o).normalize(),c=n.derivative(a).normalize().rotate(Math.PI/2);if(d.closeDistEps(h,n.end)){let S=null;for(let B=0;B<e.segs.length;B++)if(e.segs[B]===n){S=e.segs[(B+1)%e.segs.length];break}if(S==null)throw new Error;const A=u.rotate(Math.PI/2);return!(A.dot(n.derivative(n.parEnd))*A.dot(S.derivative(S.parStart))<C.tolerance)}if(d.closeDistEps(h,n.start)){let S=null;for(let B=0;B<e.segs.length;B++)if(e.segs[B]===n){S=e.segs[B>0?B-1:e.segs.length-1];break}const A=u.rotate(Math.PI/2);return!(A.dot(n.derivative(n.parStart))*A.dot(S.derivative(S.parEnd))<C.tolerance)}const m=u.dot(c);return i?m>C.distanceEpsilon:Math.abs(m)>C.distanceEpsilon}static minDistWithinIntervals(t,e,i,s,n,o,a,h){const u=new Ln(t,e,i,s,n,o,a,h);return u.solve(),u.success?{aSol:u.aSolution,bSol:u.bSolution,aX:u.aPoint,bX:u.bPoint}:void 0}offsetCurve(t,e){throw new Error("Method not implemented.")}get boundingBox(){if(this.boundingBox_)return this.boundingBox_;if(this.segs.length===0)this.boundingBox_=Z.mkEmpty();else{const t=this.segs[0].boundingBox.clone();for(let e=1;e<this.segs.length;e++)t.addRecSelf(this.segs[e].boundingBox);return this.boundingBox_=t}}clone(){const t=new w;for(const e of this.segs)t.addSegment(e.clone());return this.boundingBox_!=null&&(t.boundingBox_=this.boundingBox_.clone()),t}getParameterAtLength(t){let e=0;for(const i of this.segs){const s=i.length;if(s>=t)return e+i.getParameterAtLength(t);t-=s,e+=i.parEnd-i.parStart}return this.parEnd}get length(){let t=0;for(const e of this.segs)t+=e.length;return t}transform(t){const e=new w;for(const i of this.segs)e.addSegment(i.transform(t));return this.boundingBox_&&(e.boundingBox_=this.boundingBox_.transform(t)),e}closestParameterWithinBounds(t,e,i){let s=0,n=Number.MAX_VALUE,o=0;for(const a of this.segs){if(o>i)break;const h=w.paramSpan(a);if(o+h>=e){const c=Math.max(a.parStart,a.parStart+(e-o)),m=Math.min(a.parEnd,a.parStart+(i-o)),S=a.closestParameterWithinBounds(t,c,m),A=t.sub(a.value(S)),I=A.dot(A);I<n&&(s=o+S-a.parStart,n=I)}o+=h}return s}closestParameter(t){let e=0,i=Number.MAX_VALUE,s=0;for(const n of this.segs){const o=n.closestParameter(t),a=t.sub(n.value(o)),h=a.dot(a);if(h<i){if(e=s+o-n.parStart,h===0)break;i=h}s+=w.paramSpan(n)}return e}static addLineSegment(t,e,i){return t.addSegment(D.mkPP(e,i))}static addLineSegmentCNNP(t,e,i,s){return w.addLineSegment(t,new d(e,i),s)}static addLineSegmentCNNNN(t,e,i,s,n){w.addLineSegment(t,new d(e,i),new d(s,n))}static continueWithLineSegmentNN(t,e,i){w.addLineSegment(t,t.end,new d(e,i))}static continueWithLineSegmentP(t,e){w.addLineSegment(t,t.end,e)}static closeCurve(t){return w.continueWithLineSegmentP(t,t.start),t}leftDerivative(t){const e=this.tryToGetLeftSegment(t);return e!=null?e.derivative(e.parEnd):this.derivative(t)}rightDerivative(t){const e=this.tryToGetRightSegment(t);return e!=null?e.derivative(e.parStart):this.derivative(t)}tryToGetLeftSegment(t){if(Math.abs(t-this.parStart)<C.tolerance)return this.start.equal(this.end)?this.segs[this.segs.length-1]:null;for(const e of this.segs)if(t-=w.paramSpan(e),Math.abs(t)<C.tolerance)return e;return null}tryToGetRightSegment(t){if(Math.abs(t-this.parEnd)<C.tolerance)return this.start===this.end?this.segs[0]:null;for(const e of this.segs){if(Math.abs(t)<C.tolerance)return e;t-=w.paramSpan(e)}return null}static ClosestPoint(t,e){return t.value(t.closestParameter(e))}static CurveIsInsideOther(t,e){if(!e.boundingBox.containsRect(t.boundingBox))return!1;const i=w.getAllIntersections(t,e,!0);if(i.length===0)return w.NonIntersectingCurveIsInsideOther(t,e);if(i.length===1)return t.start.equal(i[0].x)?w.PointRelativeToCurveLocation(t.value((t.parStart+t.parEnd)/2),e)==ft.Inside:w.PointRelativeToCurveLocation(t.start,e)===ft.Inside;for(const s of w.PointsBetweenIntersections(t,i))if(w.PointRelativeToCurveLocation(s,e)===ft.Outside)return!1;return!0}static*PointsBetweenIntersections(t,e){e.sort((a,h)=>a.par0-h.par0);for(let a=0;a<e.length-1;a++)yield t.value((e[a].par0+e[a+1].par0)/2);const i=e[e.length-1].par0,s=e[0].par0,n=t.parEnd-i+(s-t.parStart);let o=i+n/2;o>t.parEnd&&(o=t.parStart+(o-t.parEnd)),yield t.value(o)}static NonIntersectingCurveIsInsideOther(t,e){for(let i=t.parStart;i<t.parEnd;i+=.5){const s=w.PointRelativeToCurveLocation(t.value(i),e);if(ft.Boundary!==s)return ft.Inside===s}return ft.Outside!==w.PointRelativeToCurveLocation(t.end,e)}static ClosedCurveInteriorsIntersect(t,e){if(!e.boundingBox.intersects(t.boundingBox))return!1;const i=w.getAllIntersections(t,e,!0);if(i.length===0)return w.NonIntersectingCurveIsInsideOther(t,e)||w.NonIntersectingCurveIsInsideOther(e,t);if(i.length===1)return t.start.equal(i[0].x)?w.PointRelativeToCurveLocation(t.value((t.parStart+t.parEnd)/2),e)===ft.Inside||!e.start.equal(i[0].x)?w.PointRelativeToCurveLocation(e.start,t)===ft.Inside:w.PointRelativeToCurveLocation(e.value((e.parStart+e.parEnd)/2),t)===ft.Inside:w.PointRelativeToCurveLocation(t.start,e)===ft.Inside;for(const s of w.PointsBetweenIntersections(t,i))if(w.PointRelativeToCurveLocation(s,e)===ft.Inside)return!0;return!0}curvature(t){const e=this.getSegParam(t);return e.seg.curvature(e.par)}curvatureDerivative(t){throw new Error("Not implemente")}curvatureSecondDerivative(t){throw new Error("Not implemented")}static createBezierSeg(t,e,i,s,n){const o=d.mkPoint(t,i.point,1-t,s.point),a=d.mkPoint(e,n.point,1-e,s.point),h=s.point.mul(2/3);return new Nt(o,o.div(3).add(h),h.add(a.div(3)),a)}static createBezierSegN(t,e,i,s){const n=i.mul(s);return new Nt(t,t.add(n),e.add(n),e)}static findCorner(t){const e=t.next;if(e.next==null)return;const i=e.next;if(i!=null)return{b:e,c:i}}static trimEdgeSplineWithNodeBoundaries(t,e,i,s){let n=i.parStart,o=i.parEnd;t!=null&&(n=w.findNewStart(i,n,t,s)),e!=null&&(o=w.findNewEnd(i,e,s,o));const a=Math.min(n,o),h=Math.max(n,o);return a<h?i.trim(a,h):i}static findNewEnd(t,e,i,s){const n=w.getAllIntersections(t,e,!0);if(n.length===0)return s=t.parEnd,s;if(i){s=t.parEnd;for(const o of n)o.par0<s&&(s=o.par0)}else{s=t.parStart;for(const o of n)o.par0>s&&(s=o.par0)}return s}static findNewStart(t,e,i,s){const n=w.getAllIntersections(t,i,!0);if(n.length===0){e=t.parStart;return}if(s){e=t.parStart;for(const o of n)o.par0>e&&(e=o.par0)}else{e=t.parEnd;for(const o of n)o.par0<e&&(e=o.par0)}return e}static polylineAroundClosedCurve(t){if(t instanceof vt)return w.refineEllipse(t);if(t instanceof at)return t;if(t instanceof w&&w.allSegsAreLines(t)){const e=new at;for(const i of t.segs)e.addPoint(i.start);if(e.closed=!0,!e.isClockwise())return e.reverse()}return t.boundingBox.perimeter()}static allSegsAreLines(t){for(const e of t.segs)if(!(e instanceof D))return!1;return!0}static refineEllipse(t){const e=t.boundingBox.perimeter(),i=Math.PI/4,s=t.boundingBox.width,n=t.boundingBox.height,o=Math.sqrt(s*s+n*n),a=[];for(let u=0;u<4;u++){const c=i+u*Math.PI/2,m=t.value(c),S=t.derivative(c).normalize().mul(o),A=D.mkPP(m.sub(S),m.add(S));for(const I of w.getAllIntersections(e,A,!0))a.push(I)}a.sort((u,c)=>u.par0<c.par0?-1:u.par0>c.par0?1:0);const h=new at;return a.forEach(u=>h.addPoint(u.x)),h.closed=!0,h}static polyFromBox(t){const e=new at;return e.addPoint(t.leftTop),e.addPoint(t.rightTop),e.addPoint(t.rightBottom),e.addPoint(t.leftBottom),e.closed=!0,e}}function Ni(l,t,e,i,s,n){if(s instanceof LineSegment)return!0;for(const o of[1/3,.5,2/3]){const a=l*o+e*(1-o);if(Point.closeSquare(s.value(a),Point.mkPoint(o,t,1-o,i),n*n)===!1)return!1}return!0}function Ys(l,t,e,i,s,n){let o=[];if(Ni(l,t,e,i,s,n))o.push(t),o.push(i);else{const a=.5*(l+e),h=s.value(a);o=Ys(l,t,a,h,s,n);const u=Ys(a,h,e,i,s,n).slice(1);o=o.concat(u)}return o}function _r(l,t){return Ys(l.parStart,l.start,l.parEnd,l.end,l,t)}function*to(l,t){if(t.containsRectWithPadding(l.boundingBox,1)){yield l;return}const e=t.perimeter(),i=w.getAllIntersections(l,e,!0);if(i.length==0){t.contains(l.start)&&(yield l);return}i.sort((o,a)=>o.par0-a.par0);const s=[l.parStart];let n=0;for(;n<i.length;n++){const o=i[n];o.par0>s[s.length-1]+GeomConstants.distanceEpsilon&&s.push(o.par0)}for(l.parEnd>s[s.length-1]+GeomConstants.distanceEpsilon&&s.push(l.parEnd),n=0;n<s.length-1;n++)Fn(l,s[n],s[n+1],t)&&(yield l.trim(s[n],s[n+1]))}function*cr(l,t){if(l==null)return;if(t.containsRect(l.boundingBox)){yield l;return}const e=w.getAllIntersections(l,t.perimeter(),!0);if(e.length==0){t.contains(l.start)&&(yield l);return}e.sort((n,o)=>n.par0-o.par0);const i=[l.parStart];let s=0;for(;s<e.length;s++){const n=e[s];n.par0>i[i.length-1]+GeomConstants.distanceEpsilon&&i.push(n.par0)}for(l.parEnd>i[i.length-1]+GeomConstants.distanceEpsilon&&i.push(l.parEnd),s=0;s<i.length-1;s++)if(Fn(l,i[s],i[s+1],t)){const n=l.trim(i[s],i[s+1]);n&&(yield n)}}function Fn(l,t,e,i){const s=(e-t)/5;for(let n=1;n<5;n++){const o=t+s*n;if(i.contains(l.value(o)))return!0}return!1}class at{constructor(){this.initIsRequired=!0,this.isClosed_=!1}toJSON(){return{points:Array.from(this).map(t=>t.toJSON())}}static fromJSON(t){return at.mkFromPoints(t.points.map(e=>d.fromJSON(e)))}RemoveStartPoint(){const t=this.startPoint.next;t.prev=null,this.startPoint=t,this.setInitIsRequired()}RemoveEndPoint(){const t=this.endPoint.prev;t.next=null,this.endPoint=t,this.setInitIsRequired()}setInitIsRequired(){this.initIsRequired=!0}addPointXY(t,e){this.addPoint(new d(t,e))}isClockwise(){return d.getTriangleOrientation(this.startPoint.point,this.startPoint.next.point,this.startPoint.next.next.point)==k.Clockwise}addPoint(t){const e=new qt;e.polyline=this,e.point=t.clone(),this.endPoint!=null?(this.endPoint.next=e,e.prev=this.endPoint,this.endPoint=e):this.startPoint=this.endPoint=e,this.setInitIsRequired()}PrependPoint(t){const e=qt.mkFromPoint(t);e.polyline=this,this.startPoint!=null?d.closeDistEps(t,this.startPoint.point)||(this.startPoint.prev=e,e.next=this.startPoint,this.startPoint=e):(this.endPoint=e,this.startPoint=e),this.setInitIsRequired()}*[Symbol.iterator](){for(let t=this.startPoint;t!=null;t=t.next)yield t.point}*polylinePoints(){for(let t=this.startPoint;t!=null;t=t.next)yield t}*skip(t){for(let e=this.startPoint;e!=null;e=e.next)t>0?t--:yield e}static parallelogramOfLineSeg(t,e){const i=e.sub(t).div(2);return At.parallelogramByCornerSideSide(t,i,i)}static mkFromPoints(t){const e=new at;for(const i of t)e.addPoint(i);return e}static mkClosedFromPoints(t){const e=at.mkFromPoints(t);return e.closed=!0,e}calculatePbNode(){const t=[],e=[];let i=this.startPoint,s=0;for(;i.next!=null;){const n=at.parallelogramOfLineSeg(i.point,i.next.point);t.push(n),e.push({parallelogram:n,seg:this,leafBoxesOffset:0,node:{low:s,high:s+1,chord:D.mkPP(i.point,i.next.point)}}),i=i.next,s++}if(this.isClosed_){const n=at.parallelogramOfLineSeg(this.endPoint.point,this.startPoint.point);t.push(n),e.push({parallelogram:n,seg:this,leafBoxesOffset:0,node:{low:s,high:s+1,chord:D.mkPP(this.endPoint.point,this.startPoint.point)}})}this.pBNode={parallelogram:At.getParallelogramOfAGroup(t),seg:this,leafBoxesOffset:0,node:{children:e}}}init(){this.bBox=Z.rectangleOnPoint(this.startPoint.point);for(const t of this.skip(1))this.bBox.add(t.point);this.updateCount(),this.calculatePbNode(),this.initIsRequired=!1}updateCount(){this.count_=0;for(let t=this.startPoint;t!=null;t=t.next)this.count_++}get count(){return this.initIsRequired&&this.init(),this.count_}get closed(){return this.isClosed_}set closed(t){this.isClosed_=t}value(t){this.initIsRequired&&this.init();const e=this.getAdjustedParamAndStartEndPoints(t);return d.convSum(e.t,e.a,e.b)}getAdjustedParamAndStartEndPoints(t){let e=this.startPoint;for(;e.next!=null;){if(t<=1)return{a:e.point,b:e.next.point,t};e=e.next,t-=1}if(this.closed&&t<=1)return{a:this.endPoint.point,b:this.startPoint.point,t};throw new Error("out of the parameter domain")}derivative(t){const e=this.getAdjustedParamAndStartEndPoints(t);return e.b.sub(e.a)}secondDerivative(t){return new d(0,0)}thirdDerivative(t){return new d(0,0)}pNodeOverICurve(){return this.initIsRequired&&this.init(),this.pBNode}get boundingBox(){return this.initIsRequired&&this.init(),this.bBox}get parStart(){return 0}get parEnd(){return this.initIsRequired&&this.init(),this.closed?this.count_:this.count_-1}static polylineFromCurve(t){const e=new at;e.addPoint(t.start);for(const i of t.segs)e.addPoint(i.end);return e.closed=t.start===t.end,e}trim(t,e){let i=this.toCurve();return i=i.trim(t,e),i instanceof w?at.polylineFromCurve(i):at.mkFromPoints([i.start,i.end])}trimWithWrap(t,e){throw new Error("Method not implemented.")}translate(t){let e=this.startPoint;do{if(e.point=e.point.add(t),e===this.endPoint)break;e=e.getNext()}while(!0);this.setInitIsRequired()}scaleFromOrigin(t,e){throw new Error("Method not implemented.")}get start(){return this.startPoint.point}get end(){return this.endPoint.point}reverse(){const t=new at;t.closed=this.closed;let e=this.endPoint;do{if(t.addPoint(e.point),e===this.startPoint)break;e=e.getPrev()}while(!0);return t}offsetCurve(t,e){throw new Error("Method not implemented.")}lengthPartial(t,e){throw new Error("Method not implemented.")}get length(){throw new Error("Method not implemented.")}getParameterAtLength(t){throw new Error("Method not implemented.")}transform(t){const e=new at;for(const i of this.polylinePoints())e.addPoint(t.multiplyPoint(i.point));return e.closed=this.closed,e}closestParameterWithinBounds(t,e,i){throw new Error("Method not implemented.")}closestParameter(t){let e=0,i=Number.MAX_VALUE,s=0,n=this.startPoint;for(;n.next!=null;){const o=D.mkPP(n.point,n.next.point),a=o.closestParameter(t),h=o.value(a).sub(t),u=h.dot(h);u<i&&(i=u,e=a+s),n=n.next,s++}if(this.closed){const o=D.mkPP(this.endPoint.point,this.startPoint.point),a=o.closestParameter(t),h=o.value(a).sub(t);h.dot(h)<i&&(e=a+s)}return e}clone(){const t=new at;t.closed=this.closed;let e=this.startPoint;do{if(t.addPoint(e.point),e===this.endPoint)break;e=e.getNext()}while(!0);return t}leftDerivative(t){throw new Error("Method not implemented.")}rightDerivative(t){throw new Error("Method not implemented.")}curvature(t){throw new Error("Method not implemented.")}curvatureDerivative(t){throw new Error("Method not implemented.")}curvatureSecondDerivative(t){throw new Error("Method not implemented.")}next(t){var e;return(e=t.next)!==null&&e!==void 0?e:this.closed?this.startPoint:null}prev(t){var e;return(e=t.prev)!==null&&e!==void 0?e:this.closed?this.endPoint:null}toCurve(){const t=new w;w.addLineSegment(t,this.startPoint.point,this.startPoint.next.point);let e=this.startPoint.next;for(;(e=e.next)!=null;)w.continueWithLineSegmentP(t,e.point);return this.closed&&w.continueWithLineSegmentP(t,this.startPoint.point),t}RemoveCollinearVertices(){for(let t=this.startPoint.next;t.next!=null;t=t.next)d.getTriangleOrientation(t.prev.point,t.point,t.next.point)===k.Collinear&&(t.prev.next=t.next,t.next.prev=t.prev);return this.setInitIsRequired(),this}}class De{constructor(t,e=t){this.width=t,this.height=e}pad(t){this.width+=t*2}}class Z{constructor(t){this.left_=t.left,this.right_=t.right,this.top_=t.top,this.bottom=t.bottom}transform(t){return Z.mkPP(t.multiplyPoint(this.leftTop),t.multiplyPoint(this.rightBottom))}translate(t){return Z.mkSizeCenter(this.size,this.center.add(t))}equal(t){return this.left_===t.left&&this.right_===t.right&&this.top_===t.top&&this.bottom_===t.bottom}equalEps(t){return N(this.left_,t.left)&&N(this.right_,t.right)&&N(this.top_,t.top)&&N(this.bottom_,t.bottom)}static mkSizeCenter(t,e){const i=t.width/2,s=t.height/2;return new Z({left:e.x-i,right:e.x+i,bottom:e.y-s,top:e.y+s})}add_rect(t){return this.addRec(t)}contains_point(t){return this.contains(t)}contains_rect(t){return this.containsRect(t)}intersection_rect(t){return this.intersection(t)}intersects_rect(t){return this.intersects(t)}unite(t){return Z.rectangleOfTwo(this,t)}contains_point_radius(t,e){return this.containsWithPadding(t,e)}intersects(t){return this.intersectsOnX(t)&&this.intersectsOnY(t)}intersection(t){if(!this.intersects(t)){const o=Z.mkEmpty();return o.setToEmpty(),o}const e=Math.max(this.left,t.left),i=Math.min(this.right,t.right),s=Math.max(this.bottom,t.bottom),n=Math.min(this.top,t.top);return new Z({left:e,bottom:s,right:i,top:n})}get center(){return this.leftTop.add(this.rightBottom).mul(.5)}set center(t){const e=this.leftTop.add(this.rightBottom).mul(.5),i=t.sub(e);this.leftTop=this.leftTop.add(i),this.rightBottom=this.rightBottom.add(i)}intersectsOnY(t){return!(t.bottom_>this.top_+C.distanceEpsilon||t.top_<this.bottom_-C.distanceEpsilon)}intersectsOnX(t){return!(t.left>this.right_+C.distanceEpsilon||t.right<this.left_-C.distanceEpsilon)}static mkEmpty(){return new Z({left:0,right:-1,bottom:0,top:-1})}get left(){return this.left_}set left(t){this.left_=t,this.onUpdated()}get right(){return this.right_}set right(t){this.right_=t,this.onUpdated()}get top(){return this.top_}set top(t){this.top_=t,this.onUpdated()}get bottom(){return this.bottom_}set bottom(t){this.bottom_=t,this.onUpdated()}get leftBottom(){return new d(this.left_,this.bottom_)}set leftBottom(t){this.left_=t.x,this.bottom=t.y}get rightTop(){return new d(this.right_,this.top_)}set rightTop(t){this.right_=t.x,this.top_=t.y}get leftTop(){return new d(this.left_,this.top_)}set leftTop(t){this.left_=t.x,this.top_=t.y}get rightBottom(){return new d(this.right_,this.bottom_)}set rightBottom(t){this.right_=t.x,this.bottom=t.y}onUpdated(){}static mkPP(t,e){const i=new Z({left:t.x,right:t.x,top:t.y,bottom:t.y});return i.add(e),i}static rectangleOnPoint(t){return new Z({left:t.x,right:t.x,top:t.y,bottom:t.y})}static mkLeftBottomSize(t,e,i){const s=t+i.width,n=e+i.height;return new Z({left:t,right:s,top:n,bottom:e})}static getRectangleOnCoords(t,e,i,s){const n=new Z({left:t,bottom:e,right:t,top:e});return n.add(new d(i,s)),n}static mkOnPoints(t){const e=Z.mkEmpty();for(const i of t)e.add(i);return e}static mkOnRectangles(t){const e=Z.mkEmpty();for(const i of t)e.addRecSelf(i);return e}get width(){return this.right_-this.left_}set width(t){const e=t/2,i=(this.left_+this.right_)/2;this.left_=i-e,this.right_=i+e}isEmpty(){return this.right<this.left}setToEmpty(){this.left=0,this.right=-1}get height(){return this.top_-this.bottom_}set height(t){const e=t/2,i=(this.top_+this.bottom_)/2;this.top_=i+e,this.bottom=i-e}static rectangleOfTwo(t,e){const i=new Z({left:t.left_,right:t.right_,top:t.top_,bottom:t.bottom_});return i.addRecSelf(e),i}containsWithPadding(t,e){return this.left_-e-C.distanceEpsilon<=t.x&&t.x<=this.right_+e+C.distanceEpsilon&&this.bottom_-e-C.distanceEpsilon<=t.y&&t.y<=this.top_+e+C.distanceEpsilon}get area(){return(this.right_-this.left_)*(this.top_-this.bottom_)}add(t){this.isEmpty()?(this.left_=this.right_=t.x,this.top_=this.bottom=t.y):(this.left_>t.x&&(this.left_=t.x),this.top_<t.y&&(this.top_=t.y),this.right_<t.x&&(this.right_=t.x),this.bottom_>t.y&&(this.bottom=t.y))}addRecSelf(t){this.add(t.leftTop),this.add(t.rightBottom)}addRec(t){const e=this.clone();return e.add(t.leftTop),e.add(t.rightBottom),e}static translate(t,e){const i=t.clone();return i.center=t.center.add(e),i}static transform(t,e){return Z.mkPP(e.multiplyPoint(t.leftTop),e.multiplyPoint(t.rightBottom))}contains(t){return this.containsWithPadding(t,0)}containsRect(t){return this.contains(t.leftTop)&&this.contains(t.rightBottom)}containsRectWithPadding(t,e){return this.containsWithPadding(t.leftTop,e)&&this.containsWithPadding(t.rightBottom,e)}get diagonal(){return Math.sqrt(this.width*this.width+this.height*this.height)}padWidth(t){this.left-=t,this.right+=t}padHeight(t){this.top+=t,this.bottom-=t}pad(t){t<-this.width/2&&(t=-this.width/2),t<-this.height/2&&(t=-this.height/2),this.padWidth(t),this.padHeight(t)}padEverywhere(t){this.left-=t.left,this.right+=t.right,this.bottom-=t.bottom,this.top+=t.top}static intersect(t,e){return t.intersects(e)?Z.mkPP(new d(Math.max(t.left,e.left),Math.max(t.bottom,e.bottom)),new d(Math.min(t.right,e.right),Math.min(t.top,e.top))):Z.mkEmpty()}perimeter(){const t=new at;return t.addPoint(this.leftTop),t.addPoint(this.rightTop),t.addPoint(this.rightBottom),t.addPoint(this.leftBottom),t.closed=!0,t}scaleAroundCenter(t){this.width=this.width*t,this.height=this.height*t}clone(){return new Z({left:this.left,right:this.right,top:this.top,bottom:this.bottom})}get size(){return new De(this.width,this.height)}set size(t){this.width=t.width,this.height=t.height}static creatRectangleWithSize(t,e){const i=t.width/2,s=e.x-i,n=e.x+i,o=t.height/2,a=e.y-o,h=e.y+o;return new Z({left:s,right:n,top:h,bottom:a})}addPointWithSize(t,e){const i=t.width/2,s=t.height/2;this.add(new d(e.x-i,e.y-s)),this.add(new d(e.x+i,e.y-s)),this.add(new d(e.x-i,e.y+s)),this.add(new d(e.x+i,e.y+s))}}class Ut{constructor(){this.previouisBezierCoefficient=.5,this.nextBezierCoefficient=.5,this.previousTangentCoefficient=1/3,this.nextTangentCoefficient=1/3}static mkSiteP(t){const e=new Ut;return e.point=t,e}static mkSiteSP(t,e){const i=new Ut;return i.point=e,i.prev=t,t.next=i,i}static mkSiteSPS(t,e,i){const s=new Ut;return s.prev=t,s.point=e,s.next=i,t.next=s,i.prev=s,s}get turn(){return this.next==null||this.prev==null?0:d.getTriangleOrientation(this.prev.point,this.point,this.next.point)}clone(){const t=new Ut;return t.previouisBezierCoefficient=this.previouisBezierCoefficient,t.point=this.point,t}}class G{constructor(t){this.headSite=t}static mkFromPoints(t){let e=null,i=null;for(const s of t)if(i==null)i=Ut.mkSiteP(s),e=new G(i);else{const n=Ut.mkSiteP(s);n.prev=i,i.next=n,i=n}return e}clone(){let t=this.headSite,e=null,i,s=null;for(;t!=null;)i=t.clone(),i.prev=e,e!=null?e.next=i:s=i,t=t.next,e=i;return new G(s)}get lastSite(){let t=this.headSite;for(;t.next!=null;)t=t.next;return t}*[Symbol.iterator](){let t=this.headSite;for(;t!=null;)yield t.point,t=t.next}createCurve(){const t=new w;let e=this.headSite,i;do{const s=w.findCorner(e);if(s==null)break;const n=G.createBezierSegOnSite(s.b);t.segs.length===0?d.closeDistEps(e.point,n.start)||w.addLineSegment(t,e.point,n.start):d.closeDistEps(t.end,n.start)||w.continueWithLineSegmentP(t,n.start),t.addSegment(n),e=s.b}while(!0);return t.segs.length===0?d.closeDistEps(e.point,e.next.point)?t.segs.push(new Nt(e.point,e.point.add(new d(5,5)),e.point.add(new d(-5,5)),i.point)):w.addLineSegment(t,e.point,e.next.point):d.closeDistEps(t.end,e.next.point)||w.continueWithLineSegmentP(t,e.next.point),t}static createBezierSegOnSite(t){const e=t.previouisBezierCoefficient,i=t.nextBezierCoefficient,s=t.prev,n=t.next,o=s.point.mul(e).add(t.point.mul(1-e)),a=n.point.mul(i).add(t.point.mul(1-i)),h=o.mul(t.previousTangentCoefficient).add(t.point.mul(1-t.previousTangentCoefficient)),u=a.mul(t.nextTangentCoefficient).add(t.point.mul(1-t.nextTangentCoefficient));return Nt.mkBezier([o,h,u,a])}}class st{constructor(t,e,i,s,n,o){this.elements=[[t,e,i],[s,n,o]]}get Elements(){return this.elements}getElem(t,e){return this.elements[t][e]}setElem(t,e,i){this.elements[t][e]=i}static Divide(t,e){return t.multiply(e.inverse())}isIdentity(){return N(this.elements[0][0],1)&&N(this.elements[0][1],0)&&N(this.elements[0][2],0)&&N(this.elements[1][0],0)&&N(this.elements[1][1],1)&&N(this.elements[1][2],0)}offset(){return new d(this.getElem(0,2),this.getElem(1,2))}static getIdentity(){return new st(1,0,0,0,1,0)}static rotation(t){const e=Math.cos(t),i=Math.sin(t);return new st(e,-i,0,i,e,0)}static scaleAroundCenterTransformation(t,e,i){const s=1-t,n=1-e;return new st(t,0,s*i.x,0,e,n*i.y)}multiplyPoint(t){return new d(this.getElem(0,0)*t.x+this.getElem(0,1)*t.y+this.getElem(0,2),this.getElem(1,0)*t.x+this.getElem(1,1)*t.y+this.getElem(1,2))}multiply(t){return t!=null?new st(this.getElem(0,0)*t.getElem(0,0)+this.getElem(0,1)*t.getElem(1,0),this.getElem(0,0)*t.getElem(0,1)+this.getElem(0,1)*t.getElem(1,1),this.getElem(0,0)*t.getElem(0,2)+this.getElem(0,1)*t.getElem(1,2)+this.getElem(0,2),this.getElem(1,0)*t.getElem(0,0)+this.getElem(1,1)*t.getElem(1,0),this.getElem(1,0)*t.getElem(0,1)+this.getElem(1,1)*t.getElem(1,1),this.getElem(1,0)*t.getElem(0,2)+this.getElem(1,1)*t.getElem(1,2)+this.getElem(1,2)):null}inverse(){const t=this.getElem(0,0)*this.getElem(1,1)-this.getElem(1,0)*this.getElem(0,1),e=this.getElem(1,1)/t,i=-this.getElem(0,1)/t,s=-this.getElem(1,0)/t,n=this.getElem(0,0)/t,o=-e*this.getElem(0,2)-i*this.getElem(1,2),a=-s*this.getElem(0,2)-n*this.getElem(1,2);return new st(e,i,o,s,n,a)}}class H{static mkEllipse(t,e,i){return vt.mkFullEllipseNNP(t,e,i)}static createParallelogram(t,e,i){const s=e/2,n=t/2,o=i.x,a=i.y,h=80*Math.PI/180,u=s/Math.tan(h);return at.mkClosedFromPoints([new d(-n-u+o,-s+a),new d(n+o,-s+a),new d(n+o+u,s+a),new d(-n+o,s+a)])}static createHexagon(t,e,i){const s=e/2,n=t/2,o=i.x,a=i.y;return at.mkClosedFromPoints([new d(-n+o,-s+a),new d(n+o,-s+a),new d(n+(s+o),0+a),new d(n+o,s+a),new d(-n+o,s+a),new d(-(n-s)+o,0+a)])}static createOctagon(t,e,i){const s=t/2,n=e/2,o=new Array(8);o[0]=new d(s+H.octagonPad*s,n-n*H.octagonPad),o[3]=new d(o[0].x*-1,o[0].y),o[4]=new d(o[3].x,o[3].y*-1),o[7]=new d(o[0].x,o[0].y*-1),o[1]=new d(s-s*H.octagonPad,n+n*H.octagonPad),o[2]=new d(o[1].x*-1,o[1].y),o[6]=new d(o[1].x,o[1].y*-1),o[5]=new d(o[2].x,o[2].y*-1);for(let a=0;a<8;a++)o[a]=o[a].add(i);return at.mkClosedFromPoints(o)}static createInvertedHouse(t,e,i){const s=H.createHouse(t,e,i);return H.rotateCurveAroundCenterByDegree(s,i,180)}static createHouse(t,e,i){const s=t/2,n=e/2,o=i.x,a=i.y,h=new w;return w.addLineSegmentCNNNN(h,o-s,a-n,o+s,a-n),w.continueWithLineSegmentNN(h,o+s,a+n),w.continueWithLineSegmentNN(h,o,a+2*n),w.continueWithLineSegmentNN(h,o-s,a+n),w.closeCurve(h)}static mkDiamond(t,e,i){const s=t,n=e,o=i.x,a=i.y,h=new w,u=[new d(o,a-n),new d(o+s,a),new d(o,a+n),new d(o-s,a)];return h.addSegs([D.mkPP(u[0],u[1]),D.mkPP(u[1],u[2]),D.mkPP(u[2],u[3]),D.mkPP(u[3],u[0])]),h}static rotateCurveAroundCenterByDegree(t,e,i){return H.rotateCurveAroundCenterByRadian(t,e,i*Math.PI/180)}static rotateCurveAroundCenterByRadian(t,e,i){const s=Math.cos(i),n=Math.sin(i),o=new st(1,0,e.x,0,1,e.y).multiply(new st(s,-n,0,n,s,0)).multiply(new st(1,0,-e.x,0,1,-e.y));return t.transform(o)}static mkCircle(t,e){return vt.mkCircle(t,e)}static createRectangle(t,e,i){const s=t/2,n=e/2,o=i.x,a=i.y,h=new w,u=[new d(o-s,a-n),new d(o+s,a-n),new d(o+s,a+n),new d(o-s,a+n)];return h.addSegs([D.mkPP(u[0],u[1]),D.mkPP(u[1],u[2]),D.mkPP(u[2],u[3]),D.mkPP(u[3],u[0])]),h}static isRoundedRect(t){if(!(t instanceof w))return;const e=t.segs;if(e.length!==8&&e.length!==4)return;const i=e.length===8;let s,n;for(let o=0;o<4;o++){const a=i?2*o+1:o;if(o===0){if(!(e[a]instanceof vt))return;const h=e[a];s=h.aAxis.length,n=h.bAxis.length}else{if(!(e[a]instanceof vt))return;const h=e[a];if(s!==h.aAxis.length||n!==h.bAxis.length)return}}return{radX:s,radY:n}}static mkRectangleWithRoundedCorners(t,e,i,s,n=new d(0,0)){if(i===0||s===0)return H.createRectangle(t,e,n);const o=new w,a=t/2;i>a/2&&(i=a/2);const h=e/2;s>h/2&&(s=h/2);const u=n.x,c=n.y,m=a-i,S=h-s,A=c+h,I=c-h,B=u-a,q=u+a,rt=new d(i,0),ct=new d(0,s);return m>0&&o.addSegment(D.mkPP(new d(u-m,I),new d(u+m,I))),o.addSegment(vt.mkEllipse(1.5*Math.PI,2*Math.PI,rt,ct,u+m,c-S)),S>0&&o.addSegment(D.mkPP(new d(q,c-S),new d(q,c+S))),o.addSegment(vt.mkEllipse(0,.5*Math.PI,rt,ct,u+m,c+S)),m>0&&o.addSegment(D.mkPP(new d(u+m,A),new d(u-m,A))),o.addSegment(vt.mkEllipse(.5*Math.PI,Math.PI,rt,ct,u-m,c+S)),S>0&&o.addSegment(D.mkPP(new d(B,c+S),new d(B,c-S))),o.addSegment(vt.mkEllipse(Math.PI,1.5*Math.PI,rt,ct,u-m,c-S)),o}}H.octagonPad=1/4;function K(l){return l.parEnd-l.parStart}function nt(l){switch(l.type){case"ellipse":return vt.fromJSON(l.data);case"curve":return w.fromJSON(l.data);case"lineSegment":return D.fromJSON(l.data);case"bezier":return Nt.fromJSON(l.data);case"polyline":return at.fromJSON(l.data)}}function Y(l){if(l instanceof Ellipse)return"ellipse";if(l instanceof Curve)return"curve";if(l instanceof LineSegment)return"lineSegment";if(l instanceof BezierSeg)return"bezier";if(l instanceof Polyline)return"polyline";throw new Error("not implemented")}function ot(l){return{type:Y(l),data:l.toJSON()}}var v;(function(l){l[l.None=0]="None",l[l.North=1]="North",l[l.East=2]="East",l[l.South=4]="South",l[l.West=8]="West"})(v||(v={}));class L{static get DifferenceEpsilon(){return L.differenceEpsilon}static EqualPP(t,e){return L.Equal(t.x,e.x)&&L.Equal(t.y,e.y)}static Equal(t,e){return L.Compare(t,e)===0}static Compare(t,e){let i=0;return t+L.DifferenceEpsilon<e?i=-1:e+L.DifferenceEpsilon<t&&(i=1),i}static ComparePP(t,e){let i=L.Compare(t.x,e.x);return i===0&&(i=L.Compare(t.y,e.y)),i}static LessOrEqual(t,e){const i=L.Compare(t,e);return i<0||i===0}static Less(t,e){return L.Compare(t,e)<0}static GetDirections(t,e){return j.DirectionFromPointToPoint(t,e)}static IsPureDirection(t,e){return j.IsPureDirection(L.GetDirections(t,e))}static IsPureDirectionD(t){return j.IsPureDirection(t)}static IsPureLower(t,e){const i=L.GetDirections(t,e);return v.East===i||v.North===i}static GetPureDirectionVV(t,e){return L.GetDirections(t.point,e.point)}}L.differenceEpsilon=C.distanceEpsilon/2;class j{constructor(t){this.Dir=t}get Right(){return new j(j.RotateRight(this.Dir))}static RotateRight(t){switch(t){case v.North:return v.East;case v.East:return v.South;case v.South:return v.West;case v.West:return v.North;default:throw new Error}}static RotateLeft(t){switch(t){case v.North:return v.West;case v.West:return v.South;case v.South:return v.East;case v.East:return v.North;default:throw new Error}}static ToIndex(t){switch(t){case v.North:return 0;case v.East:return 1;case v.South:return 2;case v.West:return 3;default:throw new Error}}static VectorDirection(t){let e=v.None;return t.x>L.DifferenceEpsilon?e=v.East:t.x<-L.DifferenceEpsilon&&(e=v.West),t.y>L.DifferenceEpsilon?e=e|v.North:t.y<-L.DifferenceEpsilon&&(e=e|v.South),e}static VectorDirectionPP(t,e){let i=v.None;const s=e.x-t.x,n=e.y-t.y;return s>L.DifferenceEpsilon?i=v.East:-s>L.DifferenceEpsilon&&(i=v.West),n>L.DifferenceEpsilon?i|=v.North:-n>L.DifferenceEpsilon&&(i|=v.South),i}static DirectionFromPointToPoint(t,e){return j.VectorDirectionPP(t,e)}static OppositeDir(t){switch(t){case v.North:return v.South;case v.West:return v.East;case v.South:return v.North;case v.East:return v.West;default:return v.None}}static IsPureDirection(t){switch(t){case v.North:return!0;case v.East:return!0;case v.South:return!0;case v.West:return!0;default:return!1}}static IsPureDirectionPP(t,e){return j.IsPureDirection(j.DirectionFromPointToPoint(t,e))}static DirectionsAreParallel(t,e){return t===e||t===j.OppositeDir(e)}ToPoint(){let t=0,e=0;return(this.Dir&v.East)===v.East&&t++,(this.Dir&v.North)===v.North&&e++,(this.Dir&v.West)===v.West&&t--,(this.Dir&v.South)===v.South&&e--,new d(t,e)}static toPoint(t){return new j(t).ToPoint()}static negate(t){return new j(j.OppositeDir(t.Dir))}}class Ks extends gt{constructor(t,e){super(t),this._isPositioned=!1,e&&(this.boundingBox=Z.mkPP(new d(0,0),new d(e.width,e.height)))}clone(){const t=new Ks(null,null);return t.isPositioned=this.isPositioned,t._boundingBox=this._boundingBox.clone(),t.attachmentSegmentEnd=this.attachmentSegmentEnd,t.attachmentSegmentStart=this.attachmentSegmentStart,t}get isPositioned(){return this._isPositioned}set isPositioned(t){this._isPositioned=t}get boundingBox(){return this._boundingBox}set boundingBox(t){this._boundingBox=t}setBoundingBox(t){this.isPositioned=!0,this._boundingBox=t}get width(){return this.boundingBox.width}set width(t){this.boundingBox.width=t}get height(){return this.boundingBox.height}set height(t){this.boundingBox.height=t}get center(){return this.boundingBox.center}set center(t){this.boundingBox.center=t}translate(t){this.isPositioned&&(this.center=this.center.add(t))}transform(t){this.isPositioned&&(this.center=t.multiplyPoint(this.center))}positionCenter(t){this.boundingBox.center=t,this.isPositioned=!0}}class Ne extends gt{constructor(t){super(t),this.lineWidth=1}*getSmoothPolyPoints(){yield this.source.center,this.curve instanceof w?yield*this.getCurvePoints(this.curve):this.curve instanceof D?(yield this.curve.start,yield this.curve.end):this.curve instanceof vt?(yield this.curve.start,yield this.curve.value((this.curve.parStart+this.curve.parEnd)/.5),yield this.curve.end):this.curve instanceof Nt&&(yield this.curve.start,yield this.curve.value(.25),yield this.curve.value(.75),yield this.curve.end),yield this.target.center}*getCurvePoints(t){for(const e of t.segs)if(yield e.start,e instanceof Nt){const i=ta(e);i&&(yield i)}yield t.end}static getGeom(t){return gt.getGeom(t)}clone(){const t=new Ne(null);return this.smoothedPolyline&&(t.smoothedPolyline=this.smoothedPolyline.clone()),t.curve=this.curve.clone(),this.sourceArrowhead!=null&&(t.sourceArrowhead=this.sourceArrowhead.clone()),this.targetArrowhead!=null&&(t.targetArrowhead=this.targetArrowhead.clone()),t}get label(){return this.edge!=null&&this.edge.label!=null?gt.getGeom(this.edge.label):null}set label(t){this.edge.label.setAttr(Et.GeomObjectIndex,t)}RaiseLayoutChangeEvent(t){this.edge.raiseEvents(t)}requireRouting(){this.curve=null,this.smoothedPolyline=null}translate(t){if(!(t.x===0&&t.y===0)){if(this.curve!=null&&this.curve.translate(t),this.smoothedPolyline!=null)for(let e=this.smoothedPolyline.headSite,i=this.smoothedPolyline.headSite;e!=null;e=e.next,i=i.next)e.point=i.point.add(t);if(this.sourceArrowhead!=null&&this.sourceArrowhead.tipPosition&&(this.sourceArrowhead.tipPosition=this.sourceArrowhead.tipPosition.add(t)),this.targetArrowhead!=null&&this.targetArrowhead.tipPosition&&(this.targetArrowhead.tipPosition=this.targetArrowhead.tipPosition.add(t)),this.edge.label){const e=Ks.getGeom(this.edge.label);e&&e.translate(t)}}}GetMaxArrowheadLength(){let t=0;return this.sourceArrowhead!=null&&(t=this.sourceArrowhead.length),this.targetArrowhead!=null&&this.targetArrowhead.length>t?this.targetArrowhead.length:t}transform(t){if(this.curve!=null){if(this.curve=this.curve.transform(t),this.smoothedPolyline!=null)for(let e=this.smoothedPolyline.headSite,i=this.smoothedPolyline.headSite;e!=null;e=e.next,i=i.next)e.point=t.multiplyPoint(e.point);this.sourceArrowhead!=null&&(this.sourceArrowhead.tipPosition=t.multiplyPoint(this.sourceArrowhead.tipPosition)),this.targetArrowhead!=null&&(this.targetArrowhead.tipPosition=t.multiplyPoint(this.targetArrowhead.tipPosition))}}get edge(){return this.entity}get source(){return gt.getGeom(this.edge.source)}*sourceArrowheadPoints(t){if(this.sourceArrowhead==null)return;yield this.sourceArrowhead.tipPosition;let e=this.sourceArrowhead.tipPosition.sub(this.curve.start);e=e.rotate90Cw().mul(Math.tan(t*.5*(Math.PI/180))),yield e.add(this.curve.start),yield this.curve.start.sub(e)}*targetArrowheadPoints(t){if(this.targetArrowhead==null)return;yield this.targetArrowhead.tipPosition;let e=this.targetArrowhead.tipPosition.sub(this.curve.end);e=e.rotate90Cw().mul(Math.tan(t*.5*(Math.PI/180))),yield e.add(this.curve.end),yield this.curve.end.sub(e)}get boundingBox(){const t=Z.mkEmpty();if(this.smoothedPolyline!=null)for(const i of this.smoothedPolyline)t.add(i);this.curve!=null&&t.addRecSelf(this.curve.boundingBox);for(const i of this.sourceArrowheadPoints(25))t.add(i);for(const i of this.targetArrowheadPoints(25))t.add(i);this.label&&t.addRecSelf(this.label.boundingBox);const e=this.lineWidth;return t.left-=e,t.top+=e,t.right+=e,t.bottom-=e,t}isInterGraphEdge(){return this.edge.isInterGraphEdge()}get target(){return gt.getGeom(this.edge.target)}toString(){return this.source.toString()+"->"+this.target}static RouteSelfEdge(t,e,i){const s=t.boundingBox.width,n=t.boundingBox.height,o=t.boundingBox.center,a=new d(o.x-s/4,o.y),h=new d(o.x-s/4,o.y-n/2-e),u=new d(o.x+s/4,o.y-n/2-e),c=new d(o.x+s/4,o.y);return i.smoothedPolyline=G.mkFromPoints([a,h,u,c]),i.smoothedPolyline.createCurve()}underCollapsedGraph(){return this.source.underCollapsedGraph()||this.target.underCollapsedGraph()}EdgeToAncestor(){return this.edge.EdgeToAncestor()}}function ta(l){return d.lineLineIntersection(l.b[0],l.b[1],l.b[2],l.b[3])}var Yt=xn(89796),$t;(function(l){l[l.Continue=0]="Continue",l[l.Stop=1]="Stop"})($t||($t={}));function ea(l,t,e,i,s,n){for(let a=0;a<l.length;a++){if(a===t||a===e)continue;const h=n.box0.add_rect(l[a].irect),u=h.area-n.box0.area,c=n.box1.add_rect(l[a].irect),m=c.area-n.box1.area;i.length*2<s.length?(i.push(l[a]),n.box0=h):s.length*2<i.length?(s.push(l[a]),n.box1=c):u<m?(i.push(l[a]),n.box0=h):m<u?(s.push(l[a]),n.box1=c):n.box0.area<n.box1.area?(i.push(l[a]),n.box0=h):(s.push(l[a]),n.box1=c)}}function re(l){if(l.length===0)return null;if(l.length===1)return l[0];const t={b0:l[0].irect,seed0:1},e=ia(l,t),i=[],s=[];i.push(l[t.seed0]),s.push(l[e]);const n={box0:l[t.seed0].irect,box1:l[e].irect};ea(l,t.seed0,e,i,s,n);const o=eo(l.length);return o.irect=n.box0.add_rect(n.box1),o.Left=re(i),o.Right=re(s),o}function dr(l,t){return l.add_rect(t).area}function ia(l,t){let e=dr(t.b0,l[t.seed0].irect);for(let s=2;s<l.length;s++){const n=dr(t.b0,l[s].irect);n>e&&(t.seed0=s,e=n)}let i;for(let s=0;s<l.length;s++)if(s!==t.seed0){i=s;break}e=l[t.seed0].irect.add_rect(l[i].irect).area;for(let s=0;s<l.length;s++){if(s===t.seed0)continue;const n=l[t.seed0].irect.add_rect(l[s].irect).area;n>e&&(i=s,e=n)}return i}function Rn(l,t){if(l==null||t==null)return null;const e=Array.from(l).map(i=>pe(i,t(i)));return re(e)}function eo(l){const t=new fr;return t.Count=l,t}function pe(l,t){const e=new fr;return e.UserData=l,e.irect=t,e.Count=1,e}function gr(l,t,e){return l.irect.intersects_rect(e)?t(l.UserData)===$t.Continue?l.Left!=null?gr(l.Left,t,e)===$t.Continue&&gr(l.Right,t,e)===$t.Continue?$t.Continue:$t.Stop:$t.Continue:$t.Stop:$t.Continue}class fr{toString(){return this.IsLeaf?this.Count.toString()+" "+this.UserData:this.Count.toString()}get IsLeaf(){return this.left==null}get Left(){return this.left}set Left(t){this.left!=null&&this.left.Parent===this&&(this.left.Parent=null),this.left=t,this.left!=null&&(this.left.Parent=this)}get Right(){return this.right}set Right(t){this.right!=null&&this.right.Parent===this&&(this.right.Parent=null),this.right=t,this.right!=null&&(this.right.Parent=this)}get IsLeftChild(){return this===this.Parent.Left}FirstIntersectedNode(t){var e;return t.intersects_rect(this.irect)?this.IsLeaf?this:(e=this.Left.FirstIntersectedNode(t))!==null&&e!==void 0?e:this.Right.FirstIntersectedNode(t):null}FirstHitNodeWithPredicate(t,e){var i;return this.irect.contains_point(t)?this.IsLeaf?e(t,this.UserData)===$t.Stop?this:null:(i=this.Left.FirstHitNodeWithPredicate(t,e))!==null&&i!==void 0?i:this.Right.FirstHitNodeWithPredicate(t,e):null}FirstHitByRectWithPredicate(t,e){var i;return this.irect.intersects_rect(t)?this.IsLeaf?e(this.UserData)===$t.Stop?this:null:(i=this.Left.FirstHitByRectWithPredicate(t,e))!==null&&i!==void 0?i:this.Right.FirstHitByRectWithPredicate(t,e):null}FirstHitNode(t){var e;return this.irect.contains_point(t)?this.IsLeaf?this:(e=this.Left.FirstHitNode(t))!==null&&e!==void 0?e:this.Right.FirstHitNode(t):null}*AllHitItems(t,e=null){const i=new Yt.B;for(i.push(this);i.size>0;){const s=i.pop();s.irect.intersects_rect(t)&&(s.IsLeaf?(e==null||e(s.UserData))&&(yield s.UserData):(i.push(s.left),i.push(s.right)))}}*AllHitItems_(t){const e=new Yt.B;for(e.push(this);e.size>0;){const i=e.pop();i.irect.contains_point(t)&&(i.IsLeaf?yield i.UserData:(e.push(i.left),e.push(i.right)))}}VisitTree(t,e){gr(this,t,e)}Clone(){const t=eo(this.Count);return t.UserData=this.UserData,t.irect=this.irect,this.Left!=null&&(t.Left=this.Left.Clone()),this.Right!=null&&(t.Right=this.Right.Clone()),t}*GetNodeItemsIntersectingRectangle(t){for(const e of this.GetLeafRectangleNodesIntersectingRectangle(t))yield e.UserData}*GetLeafRectangleNodesIntersectingRectangle(t){const e=new Yt.B;for(e.push(this);e.size>0;){const i=e.pop();i.irect.intersects_rect(t)&&(i.IsLeaf?yield i:(e.push(i.left),e.push(i.right)))}}*GetAllLeaves(){for(const t of this.GetAllLeafNodes())yield t.UserData}*GetAllLeafNodes(){for(const t of this.EnumRectangleNodes(!0))yield t}*EnumRectangleNodes(t){const e=new Yt.B;for(e.push(this);e.size>0;){const i=e.pop();(i.IsLeaf||!t)&&(yield i),i.IsLeaf||(e.push(i.left),e.push(i.right))}}TraverseHierarchy(t,e){e(t),t.Left!=null&&this.TraverseHierarchy(t.Left,e),t.Right!=null&&this.TraverseHierarchy(t.Right,e)}}class ve{constructor(t,e){Dt(t,e)<0?(this._first=t,this._second=e):(this._first=e,this._second=t)}get first(){return this._first}get second(){return this._second}get Length(){return tt(this._first,this._second)}CompareTo(t){const e=Dt(this._first,t._first);return e!==0?e:Dt(this._second,t._second)}static equal(t,e){return t._first.equal(e._first)&&t._second.equal(e._second)}toString(){return this._first+(" "+this._second)}}class ie{constructor(){this.size_=0,this.mapOfSets=new Map}delete(t){return this.deletexy(t.x,t.y)}clear(){this.mapOfSets.clear(),this.size_=0}get size(){return this.size_}static mk(t){const e=new ie;for(const i of t)e.add(i);return e}addxy(t,e){let i=this.mapOfSets.get(t);i==null&&this.mapOfSets.set(t,i=new Set),i.has(e)||this.size_++,i.add(e)}add(t){return this.addxy(t.x,t.y),this}deletexy(t,e){const i=this.mapOfSets.get(t);return i!=null&&i.delete(e)?(this.size_--,!0):!1}hasxy(t,e){return this.mapOfSets.has(t)&&this.mapOfSets.get(t).has(e)}has(t){return this.hasxy(t.x,t.y)}forEach(t,e){for(const i of this)t(i,i,e)}*entries(){for(const t of this)yield[t,t]}keys(){return this.values()}*values(){for(const t of this.mapOfSets)for(const e of t[1])yield new d(t[0],e)}[Symbol.iterator](){return this.values()}}function Ps(l,t){const e=new Set;for(const i of l)t.has(i)||e.add(i);return e}function sa(l,t){const e=new ie;for(const i of l)t.has(i)||e.add(i);return e}function Ss(l,t){const e=new Set(l);for(const i of t)e.add(i);return e}function Ki(l,t){for(const e of t)l.push(e)}function Ji(l,t){const e=new Set;if(l.size<t.size)for(const i of l)t.has(i)&&e.add(i);else for(const i of t)l.has(i)&&e.add(i);return e}function na(l){if(l.length===0)return new Set;let t=l[0];for(let e=1;e<l.length;e++)t=Ji(t,l[e]);return t}function Js(l,t){for(const e of t)l.add(e)}function Dn(l,t){if(l.size!==t.size)return!1;for(const e of l)if(!t.has(e))return!1;return!0}function Zs(l,t){const e=[];for(const i of l)for(const s of t(i))e.push(s);return e}function Nn(l,t,e){let i=l.get(t);i||(i=new Set,l.set(t,i)),i.add(e)}function ys(l,t,e){let i=l.get(t);i||(i=new Array,l.set(t,i)),i.push(e)}function pr(l,t,e){let i=l.get(t);i||(i=new Set,l.set(t,i)),i.add(e)}function io(l,t,e){pr(l,new ve(t[0],t[1]),e)}function Cs(l,t,e){const i=l.get(t);i&&i.delete(e)}function ns(l,t,e){Cs(l,new ve(t[0],t[1]),e)}function Ka(l,t){const e=l.findIndex(i=>i===t);e>=0&&l.splice(e,1)}var hi=xn(38941);class Ht{static assert(t,e=null){if(!t)throw e!=null?(console.log(e),new Error(e)):new Error("condition does not hold")}}class _s{constructor(){this.attrs=[],this._parent=null}addEvent(t){this.events.push(t)}removeEvent(t){const e=this.events.indexOf(t);e>=0&&(this.events=this.events.splice(e,1))}raiseEvents(t){this.events.forEach(e=>e(t))}clearAttr(){this.attrs=[]}setAttr(t,e){this.attrs[t]=e}getAttr(t){return this.attrs[t]}get parent(){return this._parent}set parent(t){this._parent=t}*getAncestors(){let t=this.parent;for(;t!=null;)yield t,t=t.parent}isDescendantOf(t){for(const e of this.getAncestors())if(e===t)return!0;return!1}}var ki;(function(l){l[l.None=0]="None",l[l.FromAncestor=1]="FromAncestor",l[l.ToAncestor=2]="ToAncestor"})(ki||(ki={}));class rs extends _s{constructor(t,e){super(),this.source=t,this.target=e,t!==e?(t.outEdges.add(this),e.inEdges.add(this)):t.selfEdges.add(this)}add(){this.source!==this.target?(this.source.outEdges.add(this),this.target.inEdges.add(this)):this.source.selfEdges.add(this)}remove(){this.source!==this.target?(this.source.outEdges.delete(this),this.target.inEdges.delete(this)):this.source.selfEdges.delete(this)}toString(){return"("+this.source.toString()+"->"+this.target.toString()+")"}isInterGraphEdge(){return this.source.parent!==this.target.parent}EdgeToAncestor(){return this.source instanceof Gt&&this.target.isDescendantOf(this.source)?ki.FromAncestor:this.target instanceof Gt&&this.source.isDescendantOf(this.target)?ki.ToAncestor:ki.None}}class mr extends _s{constructor(t){super(),this.inEdges=new Set,this.outEdges=new Set,this.selfEdges=new Set,this.id=t}removeOutEdge(t){this.outEdges.delete(t)}removeInEdge(t){this.inEdges.delete(t)}get id(){return this._id}set id(t){this._id=t}toString(){return this.id}*_edges(){for(const t of this.inEdges)yield t;for(const t of this.outEdges)yield t;for(const t of this.selfEdges)yield t}get edges(){return this._edges()}get outDegree(){return this.outEdges.size}get inDegree(){return this.inEdges.size}get selfDegree(){return this.selfEdges.size}get degree(){return this.outDegree+this.inDegree+this.selfDegree}}class bi{constructor(){this.nodeMap=new Map}remove(t){this.nodeMap.delete(t.id)}get size(){return this.nodeMap.size}*nodes_(){for(const t of this.nodeMap.values())yield t}*graphs_(){for(const t of this.nodes_())t instanceof Gt&&(yield t)}findShallow(t){return this.nodeMap.get(t)}get nodesShallow(){return this.nodes_()}get graphs(){return this.graphs_()}*_edges(){for(const t of this.nodeMap.values()){for(const e of t.outEdges)yield e;for(const e of t.selfEdges)yield e}}interGraphEdges(){throw new Error("not implemented")}get nodeShallowCount(){return this.nodeMap.size}get edgeCount(){let t=0;for(const e of this.nodeMap.values())t+=e.outDegree+e.selfDegree;return t}get edges(){return this._edges()}addNode(t){this.nodeMap.set(t.id,t)}nodeIsConsistent(t){for(const e of t.outEdges)if(e.source!==t||e.source===e.target)return!1;for(const e of t.inEdges)if(e.target!==t||e.source===e.target)return!1;for(const e of t.selfEdges)if(e.target!==e.source||e.source!==t)return!1;return!0}isConsistent(){for(const t of this.nodeMap.values())if(!this.nodeIsConsistent(t))return!1;return!0}}class Gt extends mr{constructor(t="__graph__"){super(t),this.nodeCollection=new bi}remove(t){this.nodeCollection.remove(t)}removeSubgraph(){const t=this.parent;t&&t.removeNode(this);for(const e of this.outGoingEdges())e.attachedAtSource?e.node.removeOutEdge(e.edge):e.node.removeInEdge(e.edge)}*outGoingEdges(){for(const t of this.outEdges){const e=t.target;this.isAncestor(e)||(yield{edge:t,node:e,attachedAtSource:!1})}for(const t of this.inEdges){const e=t.source;this.isAncestor(e)||(yield{edge:t,node:e,attachedAtSource:!0})}for(const t of this.nodesBreadthFirst){for(const e of t.outEdges){const i=e.target;i!==this&&(this.isAncestor(i)||(yield{edge:e,node:i,attachedAtSource:!1}))}for(const e of t.inEdges){const i=e.source;i!==this&&(this.isAncestor(i)||(yield{edge:e,node:i,attachedAtSource:!0}))}}}isAncestor(t){for(const e of t.getAncestors())if(e===this)return!0;return!1}*getClusteredConnectedComponents(){const t=new Set,e=new hi.o;for(const i of this.nodesBreadthFirst){if(t.has(i))continue;t.add(i),e.enqueue(i);const s=new Set;do{const n=e.dequeue();n.parent===this&&s.add(n);for(const o of this.reachableFrom(n))t.has(o)||(t.add(o),e.enqueue(o))}while(e.length>0);yield Array.from(s)}}*reachableFrom(t){for(const e of t.outEdges)yield e.target;for(const e of t.inEdges)yield e.source;t instanceof Gt&&(yield*t.shallowNodes),t.parent!=this&&(yield t.parent)}hasSomeAttrOnIndex(t){for(const e of this.nodesBreadthFirst)if(e.getAttr(t))return!0;for(const e of this.deepEdges)if(e.getAttr(t))return!0;return!1}*graphs(){for(const t of this.nodeCollection.graphs)yield t}noEmptySubgraphs(){for(const t of this.subgraphsBreadthFirst())if(t.shallowNodeCount===0)return!1;return!0}hasSubgraphs(){for(const t of this.shallowNodes)if(t instanceof Gt)return!0;return!1}*subgraphsBreadthFirst(){for(const t of this.nodesBreadthFirst)t instanceof Gt&&(yield t)}isEmpty(){return this.shallowNodeCount===0}setEdge(t,e){const i=this.nodeCollection.findShallow(t);if(i==null)return;const s=this.nodeCollection.findShallow(e);if(s!=null)return new rs(i,s)}get shallowNodes(){return this.nodeCollection.nodesShallow}get nodesBreadthFirst(){return this.nodesBreadthFirst_()}*nodesBreadthFirst_(){for(const t of this.nodeCollection.nodesShallow)yield t,t instanceof Gt&&(yield*t.nodesBreadthFirst)}findNodeRecursive(t){const e=this.nodeCollection.findShallow(t);if(e)return e;for(const i of this.shallowNodes)if(i instanceof Gt){const s=i.findNodeRecursive(t);if(s)return s}return null}findNode(t){return this.nodeCollection.findShallow(t)}get shallowEdges(){return this.nodeCollection.edges}get deepEdges(){return this.deepEdgesIt()}*deepEdgesIt(){for(const t of this.nodesBreadthFirst){for(const e of t.outEdges)yield e;for(const e of t.selfEdges)yield e;for(const e of t.inEdges)this.isAncestor(e.source)||(yield e)}}isConsistent(){return this.parent?this.parent.isConsistent():this.eachNodeIdIsUnique()&&this.nodeCollection.isConsistent()}nodeIsConsistent(t){return this.nodeCollection.nodeIsConsistent(t)}removeNode(t){for(const e of t.outEdges)e.target.inEdges.delete(e);for(const e of t.inEdges)e.source.outEdges.delete(e);this.nodeCollection.remove(t);for(const e of this.subgraphsBreadthFirst())e.removeNode(t)}addNode(t){return Ht.assert(this.findNodeRecursive(t.id)==null),t.parent=this,this.nodeCollection.addNode(t),t}get shallowNodeCount(){return this.nodeCollection.nodeShallowCount}get nodeCountDeep(){let t=this.nodeCollection.size;for(const e of this.shallowNodes)e instanceof Gt&&(t+=e.nodeCountDeep);return t}get edgeCount(){return this.nodeCollection.edgeCount}liftNode(t){for(;t!=null&&t.parent!==this;)t=t.parent;return t}get deepEdgesCount(){let t=0;for(const e of this.nodesBreadthFirst)t+=e.outDegree+e.selfDegree;return t}eachNodeIdIsUnique(){const t=new Set;for(const e of this.nodesBreadthFirst){if(t.has(e.id))return!1;t.add(e.id)}return!0}*allElements(){for(const t of this.allSuccessorsWidthFirst()){yield t;for(const e of t.selfEdges)yield e;for(const e of t.outEdges)yield e;for(const e of t.inEdges)this.isAncestor(e.source)||(yield e)}yield*this.edges}*allSuccessorsWidthFirst(){for(const t of this.shallowNodes)yield t;for(const t of this.shallowNodes)t instanceof Gt&&(yield*t.allSuccessorsWidthFirst())}*allSuccessorsDepthFirst(){for(const t of this.shallowNodes)t instanceof Gt&&(yield*t.allSuccessorsDepthFirst()),yield t}}function*ra(l){const t=new Set,e=new hi.o;for(const n of l.shallowNodes){if(t.has(n))continue;const o=new Array;for(s(n,e,t);e.length>0;){const a=e.dequeue();o.push(a);for(const h of i(a))s(h,e,t)}yield o}function*i(n){for(const o of n.outEdges)yield o.target;for(const o of n.inEdges)yield o.source}function s(n,o,a){a.has(n)||(o.enqueue(n),a.add(n))}}function Pr(l,t){t.parent&&t.parent.remove(t),l.addNode(t)}function so(l,t){let e=new Map;const i=l.nodeCountDeep;let s=1/i;for(const n of l.nodesBreadthFirst)e.set(n,s);for(let n=0;n<50;n++){s=(1-t)/i;const o=new Map;for(const a of l.nodesBreadthFirst)o.set(a,s);for(const a of l.nodesBreadthFirst){let h=o.get(a);for(const u of a.inEdges){const c=u.source;h+=t*(e.get(c)/c.outDegree)}o.set(a,h)}e=o}return e}function kn(l,t){return t.has(l.source)&&t.has(l.target)}class Pe extends gt{constructor(){super(...arguments),this.padding=1}clone(){const t=new Pe(null);return this.boundaryCurve&&(t.boundaryCurve=this.boundaryCurve.clone()),t}translate(t){t.x===0&&t.y===0||this.boundaryCurve.translate(t)}toJSON(){return{boundaryCurve:this.boundaryCurve,padding:this.padding}}get node(){return this.entity}get boundaryCurve(){return this._boundaryCurve}set boundaryCurve(t){t!=null&&t.boundingBox&&(t.boundingBox.height<Pe.minHeight||t.boundingBox.width<Pe.minWidth)&&(t=H.mkCircle(Pe.minWidth,t.boundingBox.center)),this._boundaryCurve=t}get id(){return this.node.id}toString(){return this.id}static mkNode(t,e){const i=new Pe(e);return i.boundaryCurve=t,i}get center(){return this.boundaryCurve.boundingBox.center}set center(t){const e=t.sub(this.center);this.boundaryCurve.translate(e)}fitBoundaryCurveToTarget(t){if(this.boundaryCurve!=null){const e=H.isRoundedRect(this.boundaryCurve);if(e==null){const i=t.width/this.boundaryCurve.boundingBox.width,s=t.height/this.boundaryCurve.boundingBox.height;this.boundaryCurve=this.boundaryCurve.scaleFromOrigin(i,s),this.boundaryCurve.translate(t.center.sub(this.boundaryCurve.boundingBox.center))}else this.boundaryCurve=H.mkRectangleWithRoundedCorners(t.width,t.height,e.radX,e.radY,t.center)}}static getGeom(t){return t.getAttr(Et.GeomObjectIndex)}*inEdges(){for(const t of this.node.inEdges)yield gt.getGeom(t)}*outEdges(){for(const t of this.node.outEdges)yield gt.getGeom(t)}*selfEdges(){for(const t of this.node.selfEdges)yield gt.getGeom(t)}get boundingBoxWithPadding(){const t=this.boundingBox.clone();return t.pad(this.padding),t}get boundingBox(){return this.boundaryCurve?this.boundaryCurve.boundingBox:null}set boundingBox(t){this.boundaryCurve&&(Math.abs(t.width-this.width)<1e-4&&Math.abs(t.height-this.height)<1e-4?this.center=t.center:this.fitBoundaryCurveToTarget(t))}get width(){return this.boundaryCurve.boundingBox.width}get height(){return this.boundaryCurve.boundingBox.height}transform(t){this.boundaryCurve!=null&&(this.boundaryCurve=this.boundaryCurve.transform(t))}underCollapsedGraph(){const t=this.node.parent;if(t==null)return!1;const e=gt.getGeom(t);return e==null?!1:e.isCollapsed?!0:e.underCollapsedGraph()}*getAncestors(){for(const t of this.node.getAncestors())yield gt.getGeom(t)}}Pe.minHeight=2,Pe.minWidth=3;class zt{constructor(t){this.cancelToken=t}ProgressStep(){}}class Zi{}Zi.GoldenRatio=(1+Math.sqrt(5))/2,Zi.GoldenRatioRemainder=2-Zi.GoldenRatio;class Gi extends zt{constructor(t,e){super(null),this.desiredAspectRatio=1.2,this.bestPacking=null,this.cachedCosts=new Map,this.rectangles=t,this.desiredAspectRatio=e}get PackedWidth(){return this.bestPacking!=null?this.bestPacking.PackedWidth:0}get PackedHeight(){return this.bestPacking!=null?this.bestPacking.PackedHeight:0}Pack(t,e,i){const s=Gi.GetGoldenSectionStep(t,e),n=Math.max(i/10,(e-t)/Gi.MaxSteps);e+=n,this.bestPackingCost=Number.MAX_VALUE,this.rectangles.length===1?this.PackLimit(t):this.rectangles.length===2?(this.PackLimit(t),this.PackLimit(e)):this.rectangles.length>2&&Gi.GoldenSectionSearch(a=>this.PackLimit(a),t,s,e,n);const o=this.bestPacking.getRects();for(let a=0;a<this.rectangles.length;a++)this.rectangles[a]=o[a]}PackLimit(t){let e=this.cachedCosts.get(t);if(e==null){const i=this.createPacking(this.rectangles,t);i.run(),this.cachedCosts.set(t,e=Math.abs(i.PackedAspectRatio-this.desiredAspectRatio)),e<this.bestPackingCost&&(this.bestPackingCost=e,this.bestPacking=i)}return e}static GoldenSectionSearch(t,e,i,s,n){if(Math.abs(e-s)<n)return t(e)<t(s)?e:s;const o=Gi.GetGoldenSectionStep(i,s),a=t(i),h=t(o),u=()=>Gi.GoldenSectionSearch(t,o,i,e,n),c=()=>Gi.GoldenSectionSearch(t,i,o,s,n);if(h<a)return c();if(h>a)return u();const m=c(),S=u();return t(S)<t(m)?S:m}static GetGoldenSectionStep(t,e){return t<e?t+Zi.GoldenRatioRemainder*(e-t):t-Zi.GoldenRatioRemainder*(t-e)}}Gi.MaxSteps=1e3;class no extends zt{get PackedWidth(){return this.packedWidth}set PackedWidth(t){this.packedWidth=t}get PackedHeight(){return this.packedHeight}set PackedHeight(t){this.packedHeight=t}get PackedAspectRatio(){return this.PackedWidth/this.PackedHeight}getRects(){const t=[];for(const[e,i]of this.rectsToCenters)e.center=i,t.push(e);return t}}class Gn extends no{constructor(t,e,i=!1){super(null),this.rectsToCenters=new Map,this.rectanglesByDescendingHeight=i?t:Gn.SortRectangles(t),this.wrapWidth=e}static SortRectangles(t){return t.sort((e,i)=>i.height-e.height),t}run(){this.Pack()}Pack(){this.PackedWidth=0,this.PackedHeight=0;const t=new Yt.B;let e=!1,i=0,s=0,n=0;const o=this.rectanglesByDescendingHeight;for(let a=0;e||a<o.length;){const h=o[a],u=t.length>0?t.top:null;if(u==null||u.right+h.width<=this.wrapWidth&&i+h.height<=u.top){const m=new d(u?u.right:0,i).add(new d(h.width/2,h.height/2));h.center=m,this.rectsToCenters.set(h,m),s=Math.max(s,h.right),n=Math.max(n,h.top),t.push(h),e=!1}else i=u.top,t.pop(),e=!0;e||a++}this.PackedWidth=s,this.PackedHeight=n}}class ro extends Gi{constructor(t,e){super(Gn.SortRectangles(t),e),this.createPacking=(i,s)=>new Gn(i,s,!0)}run(){let t=Number.MAX_VALUE,e=0,i=0;for(const s of this.rectangles){const n=s.width;i+=n,t=Math.min(t,n),e=Math.max(e,n)}this.Pack(e,i,t)}}function tn(l){return new Mn(re(l.map(([t,e])=>pe(e,t))))}function oa(l,t){l.UserData=t.UserData,l.Left=t.Left,l.Right=t.Right,l.Count--,l.irect=t.irect}function oo(l){for(let t=l.Parent;t!=null;t=t.Parent)t.Count--,t.irect=t.Left.irect.add_rect(t.Right.irect)}function ao(l,t){const e=new Array;for(const s of l.GetAllLeafNodes())s!==t&&e.push(s);const i=re(e);l.Count=i.Count,l.Left=i.Left,l.Right=i.Right,l.irect=i.Left.irect.add_rect(i.Right.irect)}function aa(l){for(let t=l.Parent;t!=null;t=t.Parent)if(!lo(t))return t;return null}function lo(l){return 2*l.Left.Count>=l.Right.Count&&2*l.Right.Count>=l.Left.Count}function Sr(l,t,e,i){return l.irect.intersects_rect(t)?l.IsLeaf?i(l.UserData)?--e.bound!==0:!0:Sr(l.Left,t,e,i)&&Sr(l.Right,t,e,i):!0}class Mn{constructor(t){this._rootNode=t}clear(){this.RootNode=null}NumberOfIntersectedIsLessThanBound(t,e,i){return Sr(this._rootNode,t,{bound:e},i)}get RootNode(){return this._rootNode}set RootNode(t){this._rootNode=t}*GetAllLeaves(){if(this._rootNode!=null&&this.Count>0)for(const t of this._rootNode.GetAllLeaves())yield t}get Count(){return this._rootNode==null?0:this._rootNode.Count}Add(t,e){this.AddNode(pe(e,t))}AddNode(t){this._rootNode==null?this._rootNode=t:this.Count<=2?this._rootNode=re(Array.from(this._rootNode.GetAllLeafNodes()).concat([t])):this.AddNodeToTreeRecursive(t,this._rootNode)}Rebuild(){this._rootNode=re(Array.from(this._rootNode.GetAllLeafNodes()))}AddNodeToTreeRecursive(t,e){if(e.IsLeaf)e.Left=pe(e.UserData,e.irect),e.Right=t,e.Count=2;else{e.Count++;let i,s;if(2*e.Left.Count<e.Right.Count)this.AddNodeToTreeRecursive(t,e.Left),e.Left.irect=e.Left.irect.add_rect(t.irect);else if(2*e.Right.Count<e.Left.Count)this.AddNodeToTreeRecursive(t,e.Right),e.Right.irect=e.Right.irect.add_rect(t.irect);else{i=e.Left.irect.add_rect(t.irect);const n=i.area-e.Left.irect.area;s=e.Right.irect.add_rect(t.irect);const o=s.area-e.Right.irect.area;n<o?(this.AddNodeToTreeRecursive(t,e.Left),e.Left.irect=i):n>o?(this.AddNodeToTreeRecursive(t,e.Right),e.Right.irect=s):i.area<s.area?(this.AddNodeToTreeRecursive(t,e.Left),e.Left.irect=i):(this.AddNodeToTreeRecursive(t,e.Right),e.Right.irect=s)}}e.irect=e.Left.irect.add_rect(e.Right.irect)}GetAllIntersecting(t){return this._rootNode==null||this.Count===0?[]:Array.from(this._rootNode.GetNodeItemsIntersectingRectangle(t))}OneIntersecting(t){if(this._rootNode==null||this.Count===0)return;const e=this._rootNode.FirstIntersectedNode(t);if(e!=null)return{intersectedLeaf:e.UserData}}GetAllLeavesIntersectingRectangle(t){return this._rootNode==null||this.Count===0?[]:this._rootNode.GetLeafRectangleNodesIntersectingRectangle(t)}IsIntersecting(t){if(this._rootNode==null||this.Count===0)return!1;for(const e of this._rootNode.GetNodeItemsIntersectingRectangle(t))return!0;return!1}Contains(t,e){if(this._rootNode==null)return!1;for(const i of this._rootNode.GetLeafRectangleNodesIntersectingRectangle(t))if(i.UserData===e)return!0;return!1}Remove(t,e){if(this._rootNode==null)return;let i;for(const s of this._rootNode.GetLeafRectangleNodesIntersectingRectangle(t))s.UserData===e&&(i=s);if(i!=null)return this.RootNode.Count===1?this.RootNode=null:this.RemoveLeaf(i),i.UserData}RemoveLeaf(t){const e=aa(t);if(e!=null)ao(e,t),oo(e);else{const i=t.Parent;i==null?this._rootNode=new fr:(oa(i,t.IsLeftChild?i.Right:i.Left),oo(i))}}UnbalancedNode(t){for(let e=t.Parent;e!=null;e=e.Parent)if(!lo(e))return e;return null}}class la extends Z{constructor(t){super(t),this.radX=t.radX,this.radY=t.radY,this.roundedRect_=H.mkRectangleWithRoundedCorners(this.width,this.height,t.radX,t.radY,this.center)}onUpdated(){this.isEmpty||(this.roundedRect_=H.mkRectangleWithRoundedCorners(this.width,this.height,this.radX,this.radY,this.center))}isOk(){return this.isEmpty()?!0:this.roundedRect_.boundingBox.equalEps(this)}setRect(t){this.left=t.left,this.right=t.right,this.top=t.top,this.bottom=t.bottom,this.isEmpty()||(this.roundedRect_=H.mkRectangleWithRoundedCorners(t.width,t.height,this.radX,this.radY,this.center))}}function ha(l,t){const e=t.map(n=>[n,n.boundingBox]),i=e.map(n=>n[1]),s=new ro(i,1.5);s.run();for(const[n,o]of e){const a=o.leftBottom.sub(n.boundingBox.leftBottom);n.translate(a)}l.boundingBox=new Z({left:0,bottom:0,right:s.PackedWidth,top:s.PackedHeight})}class Xt extends Pe{constructor(t){super(t),this.margins={left:10,top:10,bottom:10,right:10},this.radX=10,this.radY=10,this.rrect=new la({left:0,right:-1,top:20,bottom:0,radX:this.radX,radY:this.radY})}isAncestor(t){return this.graph.isAncestor(t.node)}deepTranslate(t){for(const e of this.nodesBreadthFirst){e instanceof Xt?e.boundingBox=e.boundingBox.translate(t):e.translate(t);for(const i of e.selfEdges())i.translate(t);for(const i of e.outEdges())this.graph.isAncestor(i.target.node)&&i.translate(t)}this.boundingBox=this.boundingBox.translate(t)}clone(){const t=new Xt(null);return t.boundingBox=this.boundingBox.clone(),t.layoutSettings=this.layoutSettings,t.margins=this.margins,t.radX=this.radX,t.radY=this.radY,t}calculateBoundsFromChildren(){const t=Z.mkEmpty();for(const e of this.shallowNodes)t.addRecSelf(e.boundingBoxWithPadding);return t.padEverywhere(this.margins),t}*allSuccessorsWidthFirst(){for(const t of this.graph.allSuccessorsWidthFirst())yield Pe.getGeom(t)}static getGeom(t){return gt.getGeom(t)}edgeCurveOrArrowheadsIntersectRect(t,e){for(const n of t.sourceArrowheadPoints(25))if(e.contains(n))return!0;for(const n of t.targetArrowheadPoints(25))if(e.contains(n))return!0;const i=t.curve,s=e.perimeter();return w.intersectionOne(i,s,!1)!=null||w.PointRelativeToCurveLocation(i.start,s)===ft.Inside}isEmpty(){return this.graph.isEmpty()}setSettingsRecursively(t){this.layoutSettings=t;for(const e of this.nodesBreadthFirst){const i=e;i.layoutSettings=t}}get layoutSettings(){return this._layoutSettings}set layoutSettings(t){this._layoutSettings=t}get labelSize(){return this._labelSize}set labelSize(t){this._labelSize=t}get boundingBox(){return this.rrect?this.rrect.clone():null}set boundingBox(t){t?this.rrect.setRect(t):this.rrect.roundedRect_=null}transform(t){if(!t.isIdentity()){for(const e of this.shallowNodes)e.transform(t);for(const e of this.shallowEdges)e.transform(t),e.label&&e.label.transform(t);this.boundingBox=this.rrect==null||this.rrect.isEmpty()?this.pumpTheBoxToTheGraphWithMargins():this.boundingBox.transform(t)}}translate(t){t.x===0&&t.y===0||this.deepTranslate(t)}get nodesBreadthFirst(){return this.nodesBreadthFirstIter()}*nodesBreadthFirstIter(){for(const t of this.graph.nodesBreadthFirst)yield gt.getGeom(t)}setEdge(t,e){const i=this.graph.setEdge(t,e);return new Ne(i)}getPumpedGraphWithMarginsBox(){const t={b:Z.mkEmpty()};return yr(this,t),t.b.padEverywhere(this.margins),t.b}pumpTheBoxToTheGraphWithMargins(){return this.boundingBox=this.getPumpedGraphWithMarginsBox()}get center(){return this.boundingBox||this.boundingBox.isEmpty?this.boundingBox.center:new d(0,0)}set center(t){const e=t.sub(this.center),i=new st(1,0,e.x,0,1,e.y);this.transform(i)}get left(){return this.boundingBox.left}get right(){return this.boundingBox.right}get top(){return this.boundingBox.top}get bottom(){return this.boundingBox.bottom}CheckClusterConsistency(){throw new Error("Method not implemented.")}get edgeCount(){return this.graph.edgeCount}get boundaryCurve(){return this.rrect.roundedRect_}set boundaryCurve(t){throw new Error}get shallowNodes(){return this.shallowNodes_()}*shallowNodes_(){for(const t of this.graph.shallowNodes)yield gt.getGeom(t)}get deepEdges(){return this.deepEdgesIt()}*deepEdgesIt(){for(const t of this.graph.deepEdges)yield gt.getGeom(t)}get shallowEdges(){return this.shallowEdgesIt()}*shallowEdgesIt(){for(const t of this.graph.shallowEdges)yield gt.getGeom(t)}static mk(t,e=new De(0,0)){const i=new Xt(new Gt(t));return i.labelSize=e,i}get Clusters(){return this.subgraphs()}*subgraphs(){for(const t of this.graph.subgraphsBreadthFirst())yield gt.getGeom(t)}static mkWithGraphAndLabel(t,e){const i=new Xt(t);return i.labelSize=e,i}get deepNodeCount(){let t=0;for(const e of this.graph.nodesBreadthFirst)t++;return t}get subgraphsDepthFirst(){return this.getSubgraphsDepthFirst()}*getSubgraphsDepthFirst(){for(const t of this.graph.allSuccessorsDepthFirst())t instanceof Gt&&(yield Xt.getGeom(t))}get uniformMargins(){return Math.max(this.margins.left,this.margins.right,this.margins.right,this.margins.bottom)}set uniformMargins(t){this.margins.left=this.margins.right=this.margins.right=this.margins.bottom=t}get height(){return this.boundingBox.height}get width(){return this.boundingBox.width}get shallowNodeCount(){return this.graph.shallowNodeCount}get graph(){return this.entity}liftNode(t){const e=this.graph.liftNode(t.node);return e?gt.getGeom(e):null}findNode(t){const e=this.graph.findNode(t);return e?gt.getGeom(e):null}addNode(t){return this.graph.addNode(t.node),t}addLabelToGraphBB(t){this.labelSize&&(t.top+=this.labelSize.height+2,t.width<this.labelSize.width&&(t.width=this.labelSize.width))}}function yr(l,t){for(const i of l.shallowEdges){if(!e(i))continue;const s=i.curve.boundingBox;if(t.b.addRecSelf(s),i.edge.label!=null){const n=gt.getGeom(i.edge.label);n&&t.b.addRecSelf(n.boundingBox)}}for(const i of l.shallowNodes)"shallowEdges"in i&&yr(i,t),!(i.underCollapsedGraph()||!i.boundingBox)&&t.b.addRecSelf(i.boundingBox);l instanceof Xt&&l.addLabelToGraphBB(t.b);function e(i){if(i==null||i.curve==null||i.underCollapsedGraph())return!1;if(l instanceof Xt){const s=l.entity;return s.isAncestor(i.source.entity)&&s.isAncestor(i.target.entity)}else return!0}}function*Ja(l,t,e=!0){const i=l.GetAllIntersecting(t);if(e)for(const s of i)s instanceof Node&&(yield s);else for(const s of i)(s instanceof Node||s instanceof Edge)&&(yield s)}function ua(l){const t=Array.from(l.nodesBreadthFirst).concat(Array.from(l.deepEdges)).map(e=>[GeomObject.getGeom(e).boundingBox,e]);return mkRTree(t)}function*Za(l,t,e){if(!l)return;const i=Rectangle.mkSizeCenter(new Size(t*2),e);for(const n of l.RootNode.AllHitItems(i,null))"edge"in n?s(e,n.pp._first,n.pp._second)<t&&(yield GeomObject.getGeom(n.edge)):yield GeomObject.getGeom(n);function s(n,o,a){const h=a.sub(o),u=h.length;if(u<1/10)return n.sub(Point.middle(o,a)).length;const c=h.rotate90Cw();return Math.abs(n.sub(o).dot(c))/u}}function _a(l,t){if(l==null)return null;const e=Array.from(l.nodesBreadthFirst).map(n=>[GeomNode.getGeom(n).boundingBox,n]),i=[];for(const n of l.deepEdges){const o=n.getAttr(AttributeRegistry.GeomObjectIndex);if(!o||(o.label&&i.push([o.label.boundingBox,n.label]),!o.curve))continue;const a=interpolateICurve(o.curve,t/2);o.sourceArrowhead&&i.push([Rectangle.mkPP(o.sourceArrowhead.tipPosition,o.curve.start),{edge:n,pp:new PointPair(o.sourceArrowhead.tipPosition,o.curve.start)}]);for(let h=0;h<a.length-1;h++)i.push([Rectangle.mkPP(a[h],a[h+1]),{edge:n,pp:new PointPair(a[h],a[h+1])}]);o.targetArrowhead&&i.push([Rectangle.mkPP(o.curve.end,o.targetArrowhead.tipPosition),{edge:n,pp:new PointPair(o.curve.end,o.targetArrowhead.tipPosition)}])}const s=e.concat(i);return mkRTree(s)}class tl{constructor(t){this._curveClips=[],this.arrowheads=[],this.nodes=[],this.labels=[],this.rect=t,this._curveClips=[]}get curveClips(){return this._curveClips}set curveClips(t){this._curveClips=t}addCurveClip(t){Assert.assert(!(t.curve instanceof Curve),"CurveClip.curve should not be a Curve!"),this._curveClips.push(t)}isEmpty(){return this._curveClips.length==0&&this.arrowheads.length==0&&this.nodes.length==0&&this.labels.length==0}initCurveClips(){this._curveClips=[]}clear(){this.arrowheads=[],this.nodes=[],this.labels=[],this._curveClips=[]}get entityCount(){return this._curveClips.length+this.arrowheads.length+this.labels.length+this.nodes.length}addElement(t){if(t instanceof GeomNode)this.nodes.push(t);else if(t instanceof GeomLabel)this.labels.push(t);else if("curve"in t)if(t.curve instanceof Curve)for(const e of t.curve.segs)this.addCurveClip({edge:t.edge,curve:e,startPar:e.parStart,endPar:e.parEnd});else this.addCurveClip(t);else this.arrowheads.push(t)}}let el=0;class Es{constructor(t=null){this.parents=new Set,this.children=new Set,this.ports=new Set,this.BoundaryCurve=t}get Parents(){return Array.from(this.parents.values())}get Children(){return Array.from(this.children.values())}get BoundaryCurve(){return this.boundaryCurve}set BoundaryCurve(t){this.boundaryCurve=t}get BoundingBox(){return this.BoundaryCurve.boundingBox}get Ports(){return this.ports}static mkShape(){return new Es(null)}get IsGroup(){return this.children.size>0}*Descendants(){const t=new hi.o;for(const e of this.Children)t.enqueue(e);for(;t.length>0;){const e=t.dequeue();yield e;for(const i of e.Children)t.enqueue(i)}}*Ancestors(){const t=new hi.o;for(const e of this.Parents)t.enqueue(e);for(;t.length>0;){const e=t.dequeue();yield e;for(const i of e.Parents)t.enqueue(i)}}AddParent(t){this.parents.add(t),t.children.add(this)}AddChild(t){t.parents.add(this),this.children.add(t)}RemoveChild(t){this.children.delete(t),t.parents.delete(this)}RemoveParent(t){this.parents.delete(t),t.children.delete(this)}ToString(){return this.UserData?this.UserData.toString():"null"}}class Vn{}class ii extends Vn{constructor(t,e){super(),this.curve=this.curve,this.location=e.clone()}get Location(){return this.location}set Location(t){this.location=t}Translate(t){this.location=this.location.add(t)}get Curve(){return this.curve}set Curve(t){this.curve=t}}class Xe extends ii{constructor(t,e,i){super(null,e().add(i)),this.LocationOffset=i,this.CurveDelegate=t,this.CenterDelegate=e}static mk(t,e){return new Xe(t,e,new d(0,0))}get CenterDelegate(){return this.centerDelegate}set CenterDelegate(t){this.centerDelegate=t}get CurveDelegate(){return this.curveDelegate}set CurveDelegate(t){this.curveDelegate=t}get LocationOffset(){return this.locationOffset}set LocationOffset(t){this.locationOffset=t}get Location(){return this.CenterDelegate().add(this.LocationOffset)}get Curve(){return this.CurveDelegate()}}class en{constructor(t,e,i,s,n){this.color=t,e!==void 0&&(this.item=e),i!==void 0&&(this.parent=i),s!==void 0&&(this.left=s),n!==void 0&&(this.right=n)}toString(){return this.item.toString()}}var Ct;(function(l){l[l.Red=0]="Red",l[l.Black=1]="Black"})(Ct||(Ct={}));class Qe{constructor(t){this.comparer=t,this.count=0,this.root=this.nil=new en(Ct.Black)}[Symbol.iterator](){return this.allNodes()}clear(){this.root=this.nil=new en(Ct.Black)}toNull(t){return t!==this.nil?t:null}isEmpty(){return this.root===this.nil}getComparer(){return this.comparer}getRoot(){return this.root}find(t,e=this.root){let i;for(;e!==this.nil&&(i=this.comparer(t,e.item))!==0;)e=i<0?e.left:e.right;return this.toNull(e)}findFirst(t,e=this.root){if(e===this.nil)return null;let i=null;for(;e!==this.nil;)e=t(e.item)?(i=e).left:e.right;return i}findLast(t,e=this.root){if(e===this.nil)return null;let i=null;for(;e!==this.nil;)e=t(e.item)?(i=e).right:e.left;return i}treeMinimum(t=this.root){for(;t.left!==this.nil;)t=t.left;return this.toNull(t)}treeMaximum(t=this.root){for(;t.right!==this.nil;)t=t.right;return this.toNull(t)}next(t){if(t.right!==this.nil)return this.treeMinimum(t.right);let e=t.parent;for(;e!==this.nil&&t===e.right;)t=e,e=e.parent;return this.toNull(e)}previous(t){if(t.left!==this.nil)return this.treeMaximum(t.left);let e=t.parent;for(;e!==this.nil&&t===e.left;)t=e,e=e.parent;return this.toNull(e)}leftRotate(t){const e=t.right;t.right=e.left,e.left!==this.nil&&(e.left.parent=t),e.parent=t.parent,t.parent===this.nil?this.root=e:t===t.parent.left?t.parent.left=e:t.parent.right=e,e.left=t,t.parent=e}rightRotate(t){const e=t.left;t.left=e.right,e.right!==this.nil&&(e.right.parent=t),e.parent=t.parent,t.parent===this.nil?this.root=e:t===t.parent.right?t.parent.right=e:t.parent.left=e,e.right=t,t.parent=e}deleteFixup(t){for(;t!==this.root&&t.color===Ct.Black;)if(t===t.parent.left){let e=t.parent.right;e.color===Ct.Red&&(e.color=Ct.Black,t.parent.color=Ct.Red,this.leftRotate(t.parent),e=t.parent.right),e.left.color===Ct.Black&&e.right.color===Ct.Black?(e.color=Ct.Red,t=t.parent):(e.right.color===Ct.Black&&(e.left.color=Ct.Black,e.color=Ct.Red,this.rightRotate(e),e=t.parent.right),e.color=t.parent.color,t.parent.color=Ct.Black,e.right.color=Ct.Black,this.leftRotate(t.parent),t=this.root)}else{let e=t.parent.left;e.color===Ct.Red&&(e.color=Ct.Black,t.parent.color=Ct.Red,this.rightRotate(t.parent),e=t.parent.left),e.right.color===Ct.Black&&e.left.color===Ct.Black?(e.color=Ct.Red,t=t.parent):(e.left.color===Ct.Black&&(e.right.color=Ct.Black,e.color=Ct.Red,this.leftRotate(e),e=t.parent.left),e.color=t.parent.color,t.parent.color=Ct.Black,e.left.color=Ct.Black,this.rightRotate(t.parent),t=this.root)}t.color=Ct.Black}deleteSubTree(t){let e;if(t.left===this.nil||t.right===this.nil)e=t;else for(e=t.right;e.left!==this.nil;)e=e.left;const i=e.left!==this.nil?e.left:e.right;return i.parent=e.parent,e.parent===this.nil?this.root=i:e===e.parent.left?e.parent.left=i:e.parent.right=i,e!==t&&(t.item=e.item),e.color===Ct.Black&&this.deleteFixup(i),this.toNull(t)}deleteNodeInternal(t){this.count--,this.deleteSubTree(t)}remove(t){const e=this.find(t);return e!=null?(this.count--,this.deleteSubTree(e)):null}insert(t){const e=this.treeInsert(t);return this.insertPrivate(e),this.toNull(e)}treeInsert(t){let e=this.nil,i=this.root,s=0;for(;i!==this.nil;)e=i,s=this.comparer(t,i.item),i=s<0?i.left:i.right;const n=new en(Ct.Black,t,e,this.nil,this.nil);return e===this.nil?this.root=n:s<0?e.left=n:e.right=n,this.toNull(n)}insertPrivate(t){for(this.count++,t.color=Ct.Red;t!==this.root&&t.parent.color===Ct.Red;)if(t.parent===t.parent.parent.left){const e=t.parent.parent.right;e.color===Ct.Red?(t.parent.color=Ct.Black,e.color=Ct.Black,t.parent.parent.color=Ct.Red,t=t.parent.parent):(t===t.parent.right&&(t=t.parent,this.leftRotate(t)),t.parent.color=Ct.Black,t.parent.parent.color=Ct.Red,this.rightRotate(t.parent.parent))}else{const e=t.parent.parent.left;e.color===Ct.Red?(t.parent.color=Ct.Black,e.color=Ct.Black,t.parent.parent.color=Ct.Red,t=t.parent.parent):(t===t.parent.left&&(t=t.parent,this.rightRotate(t)),t.parent.color=Ct.Black,t.parent.parent.color=Ct.Red,this.leftRotate(t.parent.parent))}this.root.color=Ct.Black}*allNodes(){if(this.isEmpty())return;let t=this.treeMinimum();for(;t!=null;)yield t.item,t=this.next(t)}toString(){let t="{",e=0;for(const i of this.allNodes())t+=i.toString(),e!==this.count-1&&(t+=` `),e++;return t+"}"}}class Cr{constructor(t){this.heapSize=0,this.A=[],this.compare=t}*[Symbol.iterator](){for(let t=1;t<=this.heapSize;t++)yield this.A[t]}Enqueue(t){let e=this.heapSize+1;this.A[e]=t,this.heapSize++;let i=e>>1,s,n;for(;e>1&&this.Less(s=this.A[e],n=this.A[i]);)this.A[i]=s,this.A[e]=n,e=i,i=e>>1}Dequeue(){if(this.heapSize<1)throw new Error;const t=this.A[1],e=this.A[this.heapSize];return this.heapSize--,this.ChangeMinimum(e),t}ChangeMinimum(t){this.A[1]=t;let e=1,i=2,s=!1;for(;i<this.heapSize&&!s;){s=!0;const n=this.A[i],o=this.A[i+1];this.compare(n,o)<0?this.compare(n,t)<0&&(this.A[e]=n,this.A[i]=t,s=!1,e=i,i=e<<1):this.compare(o,t)<0&&(this.A[e]=o,this.A[i+1]=t,s=!1,e=i+1,i=e<<1)}if(i===this.heapSize){const n=this.A[i];this.compare(n,t)<0&&(this.A[e]=n,this.A[i]=t)}}get Count(){return this.heapSize}Less(t,e){return this.compare(t,e)<0}GetMinimum(){return this.A[1]}}class Ai{}class bs extends Ai{constructor(t){super(),this.Vertex=t}get Site(){return this.Vertex.point}get Polyline(){return this.Vertex.polyline}}class As extends bs{constructor(t){super(t)}}class ws{constructor(t){this.lineSweeper=t}Compare(t,e){switch(d.getTriangleOrientation(e.Start,e.End,this.x)){case k.Collinear:return 0;case k.Clockwise:return 1;default:return-1}}SetOperand(t){this.x=this.IntersectionOfSideAndSweepLine(t)}IntersectionOfSideAndSweepLine(t){const e=t.Direction.dot(this.lineSweeper.SweepDirection),i=(this.lineSweeper.Z-t.Start.dot(this.lineSweeper.SweepDirection))/e;return t.Start.add(t.Direction.mul(i))}}class ho extends Ai{constructor(t){super(),this.site=t}get Site(){return this.site}}class uo{constructor(t,e){this.PreviousZ=Number.NEGATIVE_INFINITY,this.z=Number.NEGATIVE_INFINITY,this.Obstacles=t??[],this.SweepDirection=e,this.DirectionPerp=e.rotate(-Math.PI/2),this.EventQueue=new Cr((i,s)=>this.Compare(i,s)),this.ObstacleSideComparer=new ws(this),this.LeftObstacleSideTree=new Qe((i,s)=>this.ObstacleSideComparer.Compare(i,s)),this.RightObstacleSideTree=new Qe((i,s)=>this.ObstacleSideComparer.Compare(i,s))}get EventQueue(){return this.eventQueue}set EventQueue(t){this.eventQueue=t}get DirectionPerp(){return this.directionPerp}set DirectionPerp(t){this.directionPerp=t}get Z(){return this.z}set Z(t){t>this.z+C.tolerance&&(this.PreviousZ=this.z),this.z=t}GetZS(t){return this.SweepDirection.dot(t.Site)}GetZP(t){return this.SweepDirection.dot(t)}SegmentIsNotHorizontal(t,e){return Math.abs(t.sub(e).dot(this.SweepDirection))>C.distanceEpsilon}RemoveLeftSide(t){this.ObstacleSideComparer.SetOperand(t),this.LeftObstacleSideTree.remove(t)}RemoveRightSide(t){this.ObstacleSideComparer.SetOperand(t),this.RightObstacleSideTree.remove(t)}InsertLeftSide(t){this.ObstacleSideComparer.SetOperand(t),this.LeftObstacleSideTree.insert(t)}InsertRightSide(t){this.ObstacleSideComparer.SetOperand(t),this.RightObstacleSideTree.insert(t)}FindFirstObstacleSideToTheLeftOfPoint(t){const e=this.RightObstacleSideTree.findLast(i=>d.pointToTheRightOfLineOrOnLine(t,i.Start,i.End));return e==null?null:e.item}FindFirstObstacleSideToToTheRightOfPoint(t){const e=this.LeftObstacleSideTree.findFirst(i=>!d.pointToTheRightOfLineOrOnLine(t,i.Start,i.End));return e==null?null:e.item}EnqueueEvent(t){this.eventQueue.Enqueue(t)}InitQueueOfEvents(){for(const t of this.Obstacles)this.EnqueueLowestPointsOnObstacles(t);if(this.Ports!=null)for(const t of this.Ports.values())this.EnqueueEvent(new ho(t))}EnqueueLowestPointsOnObstacles(t){const e=this.GetLowestPoint(t);this.EnqueueEvent(new As(e))}GetLowestPoint(t){let e=t.startPoint,i=t.startPoint.next;for(;i!=null;i=i.next)this.Less(i.point,e.point)&&(e=i);return e}Compare(t,e){const i=t.Site,s=e.Site;return this.ComparePoints(i,s)}Less(t,e){return this.ComparePoints(t,e)<0}ComparePoints(t,e){let i=this.SweepDirection.dot(t),s=this.SweepDirection.dot(e);return i<s?-1:i>s?1:(i=this.directionPerp.dot(t),s=this.directionPerp.dot(e),i<s?-1:i>s?1:0)}}var Se=xn(38846);class ke{constructor(t,e,i=1){this.LengthMultiplier=1,this.Source=t,this.Target=e,this.Weight=i}static closeuv(t,e){return d.closeDistEps(t.point,ke.u,.1)&&d.closeDistEps(e.point,ke.v,.1)}get SourcePoint(){return this.Source.point}get TargetPoint(){return this.Target.point}get Length(){return this.SourcePoint.sub(this.TargetPoint).length*this.LengthMultiplier}toString(){return Se.Qf.Format("{0}->{1} ({2})",this.Source,this.Target,this.Weight)}ReversedClone(){return new ke(this.Target,this.Source)}Clone(){return new ke(this.Source,this.Target)}}ke.u=new d(545.833,840.458),ke.v=new d(606.1667261889578,786.2917261889578),ke.DefaultWeight=1;class wi extends ke{static constructorVV(t,e){return new wi(t,e,0)}constructor(t,e,i=0){super(t,e,i)}}class si{constructor(){this.m=new Map}deleteP(t){return this.delete(t.x,t.y)}clear(){this.m.clear()}get size(){return this.m.size}setxy(t,e,i){this.m.set(sn(t,e),i)}set(t,e){this.setxy(t.x,t.y,e)}delete(t,e){return this.m.delete(sn(t,e))}hasxy(t,e){return this.m.has(sn(t,e))}has(t){return this.hasxy(t.x,t.y)}getxy(t,e){return this.m.get(sn(t,e))}get(t){return this.getxy(t.x,t.y)}*keys(){for(const t of this.m.keys()){const e=t.split(",");yield new d(Number(e[0]),Number(e[1]))}}*[Symbol.iterator](){for(const[t,e]of this.m){const i=t.split(",");yield[new d(Number(i[0]),Number(i[1])),e]}}*values(){yield*this.m.values()}}function sn(l,t){return l.toString()+","+t.toString()}class os{constructor(t){this._inEdges=new Array,this._outEdges=new Qe((e,i)=>this.Compare(e,i)),this.point=t}get InEdges(){return this._inEdges}get OutEdges(){return this._outEdges}get Degree(){return this._inEdges.length+this.OutEdges.count}InEdgesLength(){return this._inEdges.length}addInEdge(t){this._inEdges.push(t)}get IsTerminal(){return this._isTerminal}set IsTerminal(t){this._isTerminal=t}get IsShortestPathTerminal(){return this._isShortestPathTerminal}set IsShortestPathTerminal(t){this._isShortestPathTerminal=t}toString(){return this.point.toString()}RemoveOutEdge(t){this.OutEdges.remove(t)}RemoveInEdge(t){const e=this._inEdges.indexOf(t);if(e===-1)return;const i=this._inEdges.length-1;e!==i&&(this._inEdges[e]=this._inEdges[i]),this._inEdges.pop()}static FindFirst(t,e){return os.FindFirst_t(t.root,t,e)}static FindFirst_t(t,e,i){if(t===e.nil)return null;let s=null;for(;t!==e.nil;)t=t.item.TargetPoint.compareTo(i)>=0?(s=t).left:t.right;return s}get(t){let e=os.FindFirst(this.OutEdges,t.point);return e!=null&&e.item.Target===t||(e=os.FindFirst(t.OutEdges,this.point),e!=null&&e.item.Target===this)?e.item:null}Compare(t,e){return t.TargetPoint.compareTo(e.TargetPoint)}ClearEdges(){this._outEdges.clear(),this._inEdges=[]}}class se{constructor(){this.activeVertices=new Set,this.VertexFactory=t=>new os(t),this.pointToVertexMap=new si}*edges_(){for(const t of this.pointToVertexMap.values())for(const e of t.OutEdges)yield e}get Edges(){return this.edges_()}ClearPrevEdgesTable(){for(const t of this.activeVertices)t.prevEdge=null;this.activeVertices.clear()}ShrinkLengthOfPrevEdge(t,e){t.prevEdge.LengthMultiplier=e}PreviosVertex(t){const e=t.prevEdge;return e?e.Source===t?e.Target:e.Source:null}SetPreviousEdge(t,e){this.activeVertices.add(t),t.prevEdge=e}AddHole(t){let e=t.startPoint;for(;e!==t.endPoint;)this.AddEdgePlPl(e,e.next),e=e.next;this.AddEdgePlPl(t.endPoint,t.startPoint)}static*OrientHolesClockwise(t){for(const e of t)for(let i=e.startPoint;;i=i.next){const s=d.getTriangleOrientation(i.point,i.next.point,i.next.next.point);if(s!==k.Collinear){yield s===k.Clockwise?e:e.reverse();break}}}AddVertexP(t){const e=this.pointToVertexMap.get(t);if(e)return e;const i=this.VertexFactory(t);return this.pointToVertexMap.set(t,i),i}AddVertexV(t){this.pointToVertexMap.set(t.point,t)}ContainsVertex(t){return this.pointToVertexMap.has(t)}static AddEdgeVV(t,e){let i;if(i=t.get(e))return i;if(t===e)throw new Error("Self-edges are not allowed");const s=new ke(t,e);return t.OutEdges.insert(s),e.InEdges.push(s),s}AddEdgePlPl(t,e){this.AddEdgePP(t.point,e.point)}static AddEdge(t){t.Source.OutEdges.insert(t),t.Target.addInEdge(t)}AddEdgeF(t,e,i){let s=this.FindVertex(t),n=null;if(s!=null&&(n=this.FindVertex(e),n!=null)){const a=s.get(n);if(a)return a}s==null?(s=this.AddVertexP(t),n=this.AddVertexP(e)):n==null&&(n=this.AddVertexP(e));const o=i(s,n);return s.OutEdges.insert(o),n.addInEdge(o),o}AddEdgePP(t,e){return this.AddEdgeF(t,e,(i,s)=>new ke(i,s))}FindVertex(t){return this.pointToVertexMap.get(t)}Vertices(){return this.pointToVertexMap.values()}RemoveVertex(t){for(const e of t.OutEdges)e.Target.RemoveInEdge(e);for(const e of t.InEdges)e.Source.RemoveOutEdge(e);this.pointToVertexMap.deleteP(t.point)}FindEdgePP(t,e){const i=this.FindVertex(t);if(i==null)return null;const s=this.FindVertex(e);return s==null?null:i.get(s)}static RemoveEdge(t){t.Source.RemoveOutEdge(t),t.Target.RemoveInEdge(t)}ClearEdges(){for(const t of this.Vertices())t.ClearEdges()}}class Er{constructor(){this.Removed=!1}}class vs extends Er{constructor(t,e,i){super(),this.start=t,this.EndVertex=e,this.ConeSide=i}get Start(){return this.start}get End(){return this.EndVertex.point}get Direction(){return this.End.sub(this.Start)}toString(){return"BrokenConeSide: "+(this.Start+(","+this.End))}}class br{constructor(t,e){this.apex=t,this.coneSweeper=e}get Removed(){return this.removed}set Removed(t){this.removed=t}get Apex(){return this.apex}set Apex(t){this.apex=t}get RightSideDirection(){return this.coneSweeper.ConeRightSideDirection}get LeftSideDirection(){return this.coneSweeper.ConeLeftSideDirection}get RightSide(){return this.rightSide}set RightSide(t){this.rightSide=t,this.rightSide.Cone=this}get LeftSide(){return this.leftSide}set LeftSide(t){this.leftSide=t,this.leftSide.Cone=this}}class co extends Ai{constructor(t,e){super(),this.site=t,this.coneToClose=e}get ConeToClose(){return this.coneToClose}get Site(){return this.site}toString(){return"ConeClosureEvent "+this.site}}class vi extends Er{constructor(t){super(),this.Cone=t}get Start(){return this.Cone.Apex}get Direction(){return this.Cone.LeftSideDirection}toString(){return"ConeLeftSide "+this.Start+(" "+this.Direction)}}class _i extends Er{constructor(t){super(),this.Cone=t}get Start(){return this.Cone.Apex}get Direction(){return this.Cone.RightSideDirection}toString(){return"ConeRightSide "+this.Start+" "+this.Direction}}class Wn{constructor(t){this.coneSweeper=t}SetOperand(t){this.x=this.IntersectionOfSegmentAndSweepLine(t)}Compare(t,e){const i=t instanceof vs,s=e instanceof vs;return i?s?this.CompareBrokenSides(t,e):this.CompareObstacleSideAndConeSide(e):s?this.CompareConeSideAndObstacleSide(t,e):Wn.CompareNotIntersectingSegs(t,e)}static CompareNotIntersectingSegs(t,e){switch(d.getTriangleOrientation(t.Start,e.Start,e.Start.add(e.Direction))){case k.Counterclockwise:return-1;case k.Clockwise:return 1;default:return 0}}CompareObstacleSideAndConeSide(t){const e=d.getTriangleOrientation(this.x,t.Start,t.Start.add(t.Direction));return e===k.Counterclockwise?-1:e===k.Clockwise?1:t instanceof vi?-1:1}CompareConeSideAndObstacleSide(t,e){const i=d.getTriangleOrientation(this.x,e.start,e.End);return i===k.Counterclockwise?-1:i===k.Clockwise||t instanceof vi?1:-1}IntersectionOfSegmentAndSweepLine(t){const e=t.Direction.dot(this.coneSweeper.SweepDirection),i=(this.coneSweeper.Z-t.Start.dot(this.coneSweeper.SweepDirection))/e;return t.Start.add(t.Direction.mul(i))}CompareBrokenSides(t,e){return t.EndVertex===e.EndVertex?Wn.CompareNotIntersectingSegs(t.ConeSide,e.ConeSide):d.getTriangleOrientation(this.x,e.start,e.EndVertex.point)===k.Counterclockwise?-1:1}}class nn extends Ai{constructor(t,e,i){super(),this.coneLeftSide=t,this.intersectionPoint=e,this.endVertex=i}get EndVertex(){return this.endVertex}get Site(){return this.intersectionPoint}toString(){return"LeftIntersectionEvent "+this.intersectionPoint}}class Ar{get Direction(){return this.End.sub(this.Start)}toString(){return this.Start+" "+this.End}}class wr extends Ar{constructor(t){super(),this.Init(t)}Init(t){this.StartVertex=t}get Polyline(){return this.StartVertex.polyline}get Start(){return this.StartVertex.point}get End(){return this.EndVertex.point}}class Is extends wr{constructor(t){super(t),this.end=t.nextOnPolyline.point}get End(){return this.end}get EndVertex(){return this.StartVertex.nextOnPolyline}}class as extends bs{constructor(t){super(t)}}class go extends Ai{constructor(t,e,i){super(),this.coneRightSide=t,this.intersectionPoint=e,this.endVertex=i}get EndVertex(){return this.endVertex}set EndVertex(t){this.endVertex=t}get Site(){return this.intersectionPoint}toString(){return"RightIntersectionEvent "+this.intersectionPoint}}class Ts extends wr{constructor(t){super(t),this.end=t.prevOnPolyline.point}get End(){return this.end}get EndVertex(){return this.StartVertex.prevOnPolyline}}class P extends bs{constructor(t){super(t)}}class ht extends uo{constructor(t,e,i,s,n,o,a){super(t,e),this.visibilityGraph=n,this.ConeRightSideDirection=i,this.ConeLeftSideDirection=s,this.coneSideComparer=new Wn(this),this.leftConeSides=new Qe((h,u)=>this.coneSideComparer.Compare(h,u)),this.rightConeSides=new Qe((h,u)=>this.coneSideComparer.Compare(h,u)),this.Ports=o,this.BorderPolyline=a,this.PortEdgesCreator=(h,u)=>new wi(h,u,0)}static Sweep(t,e,i,s,n,o){new ht(t,e,e.rotate(-i/2),e.rotate(i/2),s,n,o).Calculate()}Calculate(){for(this.InitQueueOfEvents();this.EventQueue.Count>0;)this.ProcessEvent(this.EventQueue.Dequeue());this.BorderPolyline!=null&&this.CloseRemainingCones(),this.CreatePortEdges()}CreatePortEdges(){if(this.portEdgesGraph!=null)for(const t of this.portEdgesGraph.Edges)this.visibilityGraph.AddEdgeF(t.SourcePoint,t.TargetPoint,this.PortEdgesCreator)}CloseRemainingCones(){if(this.leftConeSides.count===0)return;let t=this.BorderPolyline.startPoint,e=this.leftConeSides.count;do{const i=this.leftConeSides.treeMinimum().item.Cone;t=this.FindPolylineSideIntersectingConeRightSide(t,i),t=this.GetPolylinePointInsideOfConeAndRemoveCones(t,i),e--}while(this.leftConeSides.count>0&&e>0)}GetPolylinePointInsideOfConeAndRemoveCones(t,e){const i=t.nextOnPolyline,s=ht.FindInsidePoint(t.point,i.point,e);return d.closeDistEps(s,t.point)?(this.AddEdgeAndRemoveCone(e,t.point),this.AddEdgesAndRemoveRemainingConesByPoint(t.point)):d.closeDistEps(s,i.point)?(this.AddEdgeAndRemoveCone(e,i.point),this.AddEdgesAndRemoveRemainingConesByPoint(i.point),t=i):(t=ht.InsertPointIntoPolylineAfter(this.BorderPolyline,t,s),this.AddEdgeAndRemoveCone(e,t.point),this.AddEdgesAndRemoveRemainingConesByPoint(t.point)),t}static FindInsidePoint(t,e,i){return ht.FindInsidePointBool(t,e,i.Apex,i.Apex.add(i.LeftSideDirection),i.Apex.add(i.RightSideDirection))}static FindInsidePointBool(t,e,i,s,n){if(d.closeDistEps(t,e)||d.PointIsInsideCone(t,i,s,n))return t;if(d.PointIsInsideCone(e,i,s,n))return e;const o=d.middle(t,e);return d.pointToTheLeftOfLine(o,i,s)?ht.FindInsidePointBool(o,e,i,s,n):ht.FindInsidePointBool(t,o,i,s,n)}AddEdgesAndRemoveRemainingConesByPoint(t){const e=new Array;for(const i of this.leftConeSides)if(d.PointToTheRightOfLineOrOnLine(t,i.Start,i.Start.add(i.Direction)))e.push(i.Cone);else break;for(const i of e)this.AddEdgeAndRemoveCone(i,t)}FindPolylineSideIntersectingConeRightSide(t,e){const i=t,s=e.Apex,n=e.Apex.add(this.ConeRightSideDirection);let o=ht.GetSign(t,s,n);for(;;){const a=t.nextOnPolyline,h=ht.GetSign(a,s,n);if(h-o>0)return t;if(t=a,o=h,t===i)throw new Error("cannod decide if the polyline intersects the cone!")}}static GetSign(t,e,i){const s=d.signedDoubledTriangleArea(e,i,t.point);return s<0?1:s>0?-1:0}AddEdgeAndRemoveCone(t,e){this.Ports!=null&&this.Ports.has(t.Apex)?this.CreatePortEdge(t,e):this.visibilityGraph.AddEdgePP(t.Apex,e),this.RemoveCone(t)}CreatePortEdge(t,e){this.portEdgesGraph==null&&(this.portEdgesGraph=new se);const i=this.portEdgesGraph.FindVertex(t.Apex),s=i!=null?Array.from(i.InEdges).concat(Array.from(i.OutEdges.allNodes())):null;if(s)for(const n of s){const o=(n.Target===i?n.Source:n.Target).point;se.RemoveEdge(n),this.portEdgesGraph.AddEdgePP(o,e)}this.portEdgesGraph.AddEdgePP(t.Apex,e)}static InsertPointIntoPolylineAfter(t,e,i){let s;return e.next!=null?(s=qt.mkFromPoint(i),s.prev=e,s.next=e.next,e.next.prev=s,e.next=s):(s=qt.mkFromPoint(i),s.prev=e,e.next=s,t.endPoint=s),s.polyline=t,t.setInitIsRequired(),s}ProcessEvent(t){t instanceof bs?this.ProcessVertexEvent(t):t instanceof go?this.ProcessRightIntersectionEvent(t):t instanceof nn?this.ProcessLeftIntersectionEvent(t):(t instanceof co?t.ConeToClose.Removed||this.RemoveCone(t.ConeToClose):this.ProcessPortObstacleEvent(t),this.Z=this.GetZS(t))}ProcessPortObstacleEvent(t){this.Z=this.GetZS(t),this.GoOverConesSeeingVertexEvent(t),this.CreateConeOnVertex(t)}ProcessLeftIntersectionEvent(t){if(t.coneLeftSide.Removed===!1)if(Math.abs(t.EndVertex.point.sub(t.Site).dot(this.SweepDirection))<C.distanceEpsilon)this.RemoveCone(t.coneLeftSide.Cone);else{this.RemoveSegFromLeftTree(t.coneLeftSide),this.Z=this.GetZP(t.Site);const e=new vs(t.Site,t.EndVertex,t.coneLeftSide);this.InsertToTree(this.leftConeSides,e),t.coneLeftSide.Cone.LeftSide=e,this.LookForIntersectionOfObstacleSideAndLeftConeSide(t.Site,t.EndVertex),this.TryCreateConeClosureForLeftSide(e)}else this.Z=this.GetZP(t.Site)}TryCreateConeClosureForLeftSide(t){if(t.Cone.RightSide instanceof _i){const e=t.Cone.RightSide;d.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.EndVertex.point)==k.Clockwise&&this.CreateConeClosureEvent(t,e)}}CreateConeClosureEvent(t,e){const i=d.RayIntersectsRayInteriors(t.start,t.Direction,e.Start,e.Direction);if(i){const s=new co(i,t.Cone);this.EnqueueEvent(s)}}ProcessRightIntersectionEvent(t){if(t.coneRightSide.Removed)this.Z=this.GetZP(t.Site);else{this.RemoveSegFromRightTree(t.coneRightSide),this.Z=this.GetZP(t.Site);const e=new vs(t.Site,t.EndVertex,t.coneRightSide);this.InsertToTree(this.rightConeSides,e),t.coneRightSide.Cone.RightSide=e,this.LookForIntersectionOfObstacleSideAndRightConeSide(t.Site,t.EndVertex),this.TryCreateConeClosureForRightSide(e)}}TryCreateConeClosureForRightSide(t){if(t.Cone.LeftSide instanceof vi){const e=t.Cone.LeftSide;d.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.EndVertex.point)==k.Counterclockwise&&this.CreateConeClosureEvent(t,e)}}RemoveConesClosedBySegment(t,e){this.CloseConesCoveredBySegment(t,e,this.GetZP(t)>this.GetZP(e)?this.leftConeSides:this.rightConeSides)}CloseConesCoveredBySegment(t,e,i){let s=i.findFirst(a=>d.getTriangleOrientation(a.Start,a.Start.add(a.Direction),t)===k.Counterclockwise);if(s==null||!d.IntervalIntersectsRay(t,e,s.item.Start,s.item.Direction))return;const o=new Array;do o.push(s.item.Cone),s=i.next(s);while(s!=null&&d.IntervalIntersectsRay(t,e,s.item.Start,s.item.Direction)!==void 0);for(const a of o)this.RemoveCone(a)}ProcessVertexEvent(t){this.Z=this.GetZS(t),this.GoOverConesSeeingVertexEvent(t),this.AddConeAndEnqueueEvents(t)}static Diamond(t){return H.mkDiamond(2,2,t)}AddConeAndEnqueueEvents(t){if(t instanceof as){const e=t.Vertex.nextOnPolyline;this.CloseConesAddConeAtLeftVertex(t,e)}else if(t instanceof P){const e=t.Vertex.prevOnPolyline;this.CloseConesAddConeAtRightVertex(t,e)}else this.CloseConesAddConeAtLeftVertex(t,t.Vertex.nextOnPolyline),this.CloseConesAddConeAtRightVertex(t,t.Vertex.prevOnPolyline)}CloseConesAddConeAtRightVertex(t,e){const i=t.Vertex.nextOnPolyline.point;this.directionPerp.dot(t.Site.sub(i))>C.distanceEpsilon&&this.RemoveConesClosedBySegment(i,t.Vertex.point),this.directionPerp.dot(e.point.sub(t.Site))>C.distanceEpsilon&&this.RemoveConesClosedBySegment(t.Site,e.point);const s=t.Site,n=s.add(this.ConeLeftSideDirection),o=s.add(this.ConeRightSideDirection),a=e.point;this.GetZP(s.sub(i))>C.distanceEpsilon&&this.RemoveRightSide(new Ts(t.Vertex.nextOnPolyline)),this.GetZP(s.sub(e.point))>C.distanceEpsilon&&this.RemoveLeftSide(new Is(e)),this.GetZP(a)+C.distanceEpsilon<this.GetZS(t)&&this.CreateConeOnVertex(t),d.PointToTheRightOfLineOrOnLine(a,s,n)?d.PointToTheLeftOfLineOrOnLine(a,s,o)?this.CaseToTheLeftOfLineOrOnLineConeRp(t,e):(this.GetZP(a.sub(s))>C.distanceEpsilon&&(this.LookForIntersectionOfObstacleSideAndLeftConeSide(t.Site,e),this.InsertRightSide(new Ts(t.Vertex))),this.EnqueueRightVertexEvent(new P(e))):(this.CreateConeOnVertex(t),d.PointToTheLeftOfLineOrOnLine(a.add(this.DirectionPerp),a,s)&&this.EnqueueRightVertexEvent(new P(e)))}CaseToTheLeftOfLineOrOnLineConeRp(t,e){this.EnqueueRightVertexEvent(new P(e));const i=new br(t.Vertex.point,this),s=new vs(i.Apex,e,new vi(i));i.LeftSide=s,i.RightSide=new _i(i);const n=this.InsertToTree(this.rightConeSides,i.RightSide);this.LookForIntersectionWithConeRightSide(n);const o=this.InsertToTree(this.leftConeSides,i.LeftSide);this.FixConeLeftSideIntersections(s,o),this.GetZP(e.point.sub(t.Site))>C.distanceEpsilon&&this.InsertRightSide(new Ts(t.Vertex))}LookForIntersectionOfObstacleSideAndRightConeSide(t,e){const i=this.GetLastNodeToTheLeftOfPointInRightSegmentTree(t);if(i!=null&&i.item instanceof _i){const s=d.IntervalIntersectsRay(t,e.point,i.item.Start,this.ConeRightSideDirection);s&&this.SegmentIsNotHorizontal(s,e.point)&&this.EnqueueEvent(this.CreateRightIntersectionEvent(i.item,s,e))}}CreateRightIntersectionEvent(t,e,i){return new go(t,e,i)}GetLastNodeToTheLeftOfPointInRightSegmentTree(t){return this.rightConeSides.findLast(e=>ht.PointIsToTheRightOfSegment(t,e))}LookForIntersectionOfObstacleSideAndLeftConeSide(t,e){const i=this.GetFirstNodeToTheRightOfPoint(t);if(i==null||!(i.item instanceof vi))return;const s=i.item,n=d.IntervalIntersectsRay(t,e.point,s.Start,this.ConeLeftSideDirection);n&&this.EnqueueEvent(new nn(s,n,e))}GetFirstNodeToTheRightOfPoint(t){return this.leftConeSides.findFirst(e=>ht.PointIsToTheLeftOfSegment(t,e))}static PointIsToTheLeftOfSegment(t,e){return d.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t)===k.Counterclockwise}static PointIsToTheRightOfSegment(t,e){return d.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t)===k.Clockwise}FixConeLeftSideIntersections(t,e){do e=this.leftConeSides.next(e);while(e!=null&&d.PointToTheRightOfLineOrOnLine(t.Start,e.item.Start,e.item.Start.add(e.item.Direction)));if(e!=null&&e.item instanceof vi){const i=e.item,s=d.IntervalIntersectsRay(t.start,t.End,i.Start,i.Direction);s&&this.EnqueueEvent(new nn(i,s,t.EndVertex))}}InsertToTree(t,e){return this.coneSideComparer.SetOperand(e),t.insert(e)}CloseConesAddConeAtLeftVertex(t,e){const i=t.Vertex.prevOnPolyline.point;t.Site.sub(i).dot(this.directionPerp)<-C.distanceEpsilon&&this.RemoveConesClosedBySegment(t.Site,i),e.point.sub(t.Site).dot(this.directionPerp)<-C.distanceEpsilon&&this.RemoveConesClosedBySegment(e.point,t.Site);const s=t.Site,n=s.add(this.ConeLeftSideDirection),o=s.add(this.ConeRightSideDirection),a=e.point;this.GetZP(s.sub(i))>C.distanceEpsilon&&this.RemoveLeftSide(new Is(t.Vertex.prevOnPolyline));const h=this.GetZP(a)-this.Z;h<-C.distanceEpsilon&&this.RemoveRightSide(new Ts(e));const u=a.sub(t.Site);if(h<-C.distanceEpsilon||N(h,0)&&this.GetZP(u)>0&&u.dot(this.directionPerp)>-C.distanceEpsilon)this.CreateConeOnVertex(t);else if(!d.PointToTheLeftOfLineOrOnLine(a,s,o))this.CreateConeOnVertex(t),this.EnqueueEvent(new as(e));else if(d.PointToTheLeftOfLineOrOnLine(a,s,n))this.EnqueueEvent(new as(e)),this.GetZP(u)>C.distanceEpsilon&&(this.LookForIntersectionOfObstacleSideAndRightConeSide(t.Site,e),this.InsertLeftSide(new Is(t.Vertex)));else{this.EnqueueEvent(new as(e));const c=new br(t.Vertex.point,this),m=new vs(t.Vertex.point,e,new _i(c));c.RightSide=m,c.LeftSide=new vi(c),this.LookForIntersectionWithConeLeftSide(this.InsertToTree(this.leftConeSides,c.LeftSide));const S=this.InsertToTree(this.rightConeSides,m);this.FixConeRightSideIntersections(m,S),this.GetZP(u)>C.distanceEpsilon&&this.InsertLeftSide(new Is(t.Vertex))}}RemoveCone(t){t.Removed=!0,this.RemoveSegFromLeftTree(t.LeftSide),this.RemoveSegFromRightTree(t.RightSide)}RemoveSegFromRightTree(t){this.coneSideComparer.SetOperand(t);let e=this.rightConeSides.remove(t);if(t.Removed=!0,e==null){const i=this.Z;this.Z=Math.max(this.GetZP(t.Start),this.Z-.01),this.coneSideComparer.SetOperand(t),e=this.rightConeSides.remove(t),this.Z=i}}RemoveSegFromLeftTree(t){if(t.Removed=!0,this.coneSideComparer.SetOperand(t),this.leftConeSides.remove(t)==null){const i=this.Z;this.Z=Math.max(this.GetZP(t.Start),this.Z-.01),this.coneSideComparer.SetOperand(t),this.leftConeSides.remove(t),this.Z=i}}FixConeRightSideIntersections(t,e){do e=this.rightConeSides.previous(e);while(e!=null&&d.PointToTheLeftOfLineOrOnLine(t.start,e.item.Start,e.item.Start.add(e.item.Direction)));if(e!=null){let i;if(e.item instanceof _i){const s=e.item;(i=d.IntervalIntersectsRay(t.start,t.End,s.Start,s.Direction))&&this.EnqueueEvent(this.CreateRightIntersectionEvent(s,i,t.EndVertex))}}}CreateConeOnVertex(t){const e=new br(t.Site,this);e.LeftSide=new vi(e),e.RightSide=new _i(e);const i=this.InsertToTree(this.leftConeSides,e.LeftSide),s=this.InsertToTree(this.rightConeSides,e.RightSide);this.LookForIntersectionWithConeRightSide(s),this.LookForIntersectionWithConeLeftSide(i)}LookForIntersectionWithConeLeftSide(t){if(t.item instanceof vi){const e=t.item,i=this.FindFirstObstacleSideToTheLeftOfPoint(e.Start);i!=null&&this.TryIntersectionOfConeLeftSideAndObstacleSide(e,i)}else{const e=t.item;t=this.leftConeSides.next(t),t!=null&&t.item instanceof vi&&this.TryIntersectionOfConeLeftSideAndObstacleConeSide(t.item,e)}}LookForIntersectionWithConeRightSide(t){if(t.item instanceof _i){const e=t.item,i=this.FindFirstObstacleSideToToTheRightOfPoint(e.Start);i!=null&&this.TryIntersectionOfConeRightSideAndObstacleSide(e,i)}else{const e=t.item;t=this.rightConeSides.previous(t),t!=null&&t.item instanceof _i&&this.TryIntersectionOfConeRightSideAndObstacleConeSide(t.item,e)}}TryIntersectionOfConeRightSideAndObstacleConeSide(t,e){const i=d.IntervalIntersectsRay(e.start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(this.CreateRightIntersectionEvent(t,i,e.EndVertex))}TryIntersectionOfConeRightSideAndObstacleSide(t,e){const i=d.IntervalIntersectsRay(e.Start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(this.CreateRightIntersectionEvent(t,i,e.EndVertex))}TryIntersectionOfConeLeftSideAndObstacleConeSide(t,e){const i=d.IntervalIntersectsRay(e.start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(new nn(t,i,e.EndVertex))}TryIntersectionOfConeLeftSideAndObstacleSide(t,e){const i=d.IntervalIntersectsRay(e.Start,e.End,t.Start,t.Direction);i&&this.EnqueueEvent(new nn(t,i,e.EndVertex))}ExtendSegmentToZ(t){const e=t.Direction.dot(this.SweepDirection),i=(this.Z+40-t.Start.dot(this.SweepDirection))/e;return D.mkPP(t.Start,t.Start.add(t.Direction.mul(i)))}GoOverConesSeeingVertexEvent(t){let e=this.FindFirstSegmentInTheRightTreeNotToTheLeftOfVertex(t);if(e==null)return;const s=e.item.Cone,n=s.LeftSide;if(ht.VertexIsToTheLeftOfSegment(t,n))return;const o=[s];if(this.coneSideComparer.SetOperand(n),e=this.leftConeSides.find(n),e==null){const a=this.Z;this.Z=Math.max(this.GetZP(n.Start),this.PreviousZ),this.coneSideComparer.SetOperand(n),e=this.leftConeSides.find(n),this.Z=a}if(!(e==null&&(e=this.GetRbNodeEmergency(n),e==null))){for(e=this.leftConeSides.next(e);e!=null&&!ht.VertexIsToTheLeftOfSegment(t,e.item);)o.push(e.item.Cone),e=this.leftConeSides.next(e);for(const a of o)this.AddEdgeAndRemoveCone(a,t.Site)}}GetRbNodeEmergency(t){if(this.leftConeSides.count===0)return null;for(let e=this.leftConeSides.treeMinimum();e!=null;e=this.leftConeSides.next(e))if(e.item===t)return e;return null}static VertexIsToTheLeftOfSegment(t,e){return d.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.Site)===k.Counterclockwise}static VertexIsToTheRightOfSegment(t,e){return d.getTriangleOrientation(e.Start,e.Start.add(e.Direction),t.Site)===k.Clockwise}FindFirstSegmentInTheRightTreeNotToTheLeftOfVertex(t){return this.rightConeSides.findFirst(e=>!ht.VertexIsToTheRightOfSegment(t,e))}EnqueueRightVertexEvent(t){this.GetZP(t.Site.sub(t.Vertex.prevOnPolyline.point))>C.tolerance||this.EnqueueEvent(t)}invariant(){for(const t of this.leftConeSides)if(t.Removed)return!1;for(const t of this.rightConeSides)if(t.Removed)return!1;return!0}}class Mi extends zt{constructor(t,e){super(null),this.coneAngle=Math.PI/6,this.ports=new ie,this._obstacles=Array.from(se.OrientHolesClockwise(t)),this._visibilityGraph=e}static mk(t,e,i,s,n){const o=new Mi(t,e);return o.Ports=s,o.BorderPolyline=n,o.ConeAngle=i,o}get ConeAngle(){return this.coneAngle}set ConeAngle(t){this.coneAngle=t}get Ports(){return this.ports}set Ports(t){this.ports=t}get BorderPolyline(){return this.borderPolyline}set BorderPolyline(t){this.borderPolyline=t}get Bidirectional(){return this._bidirectional}set Bidirectional(t){this._bidirectional=t}static GetTotalSteps(t){return Math.floor((2*Math.PI-t/2)/t)+1}run(){const t=2*Math.PI-this.coneAngle/2;if(this.Bidirectional)this.HandleBideractionalCase();else{let e;for(let i=0;(e=this.coneAngle*i)<=t;i++)super.ProgressStep(),this.AddDirection(new d(Math.cos(e),Math.sin(e)),this.BorderPolyline,this._visibilityGraph)}}HandleBideractionalCase(){const t=Math.PI/this.coneAngle;for(let e=0;e<t;e++){const i=e*this.coneAngle,s=new se;this.AddDirection(new d(Math.cos(i),Math.sin(i)),this.BorderPolyline,s);const n=new se;this.AddDirection(new d(Math.cos(i)*-1,Math.sin(i)*-1),this.BorderPolyline,n),this.AddIntersectionOfBothDirectionSweepsToTheResult(s,n)}}AddIntersectionOfBothDirectionSweepsToTheResult(t,e){for(const i of t.Edges)e.FindEdgePP(i.SourcePoint,i.TargetPoint)!=null&&this._visibilityGraph.AddEdgePP(i.SourcePoint,i.TargetPoint)}AddDirection(t,e,i){ht.Sweep(this._obstacles,t,this.coneAngle,i,this.Ports,e)}}class Kt extends Vn{constructor(t){super(),this.adjustmentAngle=Math.PI/10,this.hookSize=9,this.curve=t,this.location=this.curve().start}mk(t,e){const i=new Kt(t);return i.HookSize=e,i}get Location(){return this.location}get Curve(){return this.curve()}SetLocation(t){this.location=t}get AdjustmentAngle(){return this.adjustmentAngle}set AdjustmentAngle(t){this.adjustmentAngle=t}get HookSize(){return this.hookSize}set HookSize(t){this.hookSize=t}}class Ge extends Xe{constructor(t,e,i=new d(0,0)){super(t,e,i)}get LoosePolyline(){return this.loosePolyline}set LoosePolyline(t){this.loosePolyline=t}static mk(t,e){return new Ge(t,e)}}class R extends Vn{get Location(){return this.curve.value(this.parameter)}set Location(t){throw new Error("Method should not be called.")}static mk(t,e){const i=new R;return i.curve=t,i.parameter=e,i}get Parameter(){return this.parameter}set Parameter(t){this.parameter=t}get Curve(){return this.curve}set Curve(t){this.curve=t}}class ge{constructor(){this.capacityOverflowCoefficient=ge.DefaultCapacityOverflowCoefficientMultiplier,this.RotateBundles=!1,this.MaxHubRadius=50,this.MinHubRadius=.1,this.CreateUnderlyingPolyline=!1,this.pathLengthImportance=ge.DefaultPathLengthImportance,this.inkImportance=ge.DefaultInkImportance,this.edgeSeparation=ge.DefaultEdgeSeparation,this._edgeWidthShrinkCoeff=1,this.useCubicBezierSegmentsInsideOfHubs=!1,this.angleThreshold=Math.PI/180*45,this.hubRepulsionImportance=100,this.bundleRepulsionImportance=100,this.minimalRatioOfGoodCdtEdges=.9,this.highestQuality=!0,this.KeepOverlaps=!1,this.StopAfterShortestPaths=!1}toJSON(){const t={};return this.capacityOverflowCoefficient!=ge.DefaultCapacityOverflowCoefficientMultiplier&&(t.capacityOverflowCoefficient=this.capacityOverflowCoefficient),this.RotateBundles&&(t.RotateBundles=this.RotateBundles),this.MaxHubRadius!=50&&(t.MaxHubRadius=this.MaxHubRadius),this.MinHubRadius!=.1&&(t.MinHubRadius=this.MinHubRadius),this.CreateUnderlyingPolyline&&(t.CreateUnderlyingPolyline=this.CreateUnderlyingPolyline),this.pathLengthImportance!=ge.DefaultPathLengthImportance&&(t.pathLengthImportance=this.pathLengthImportance),this.inkImportance!=ge.DefaultInkImportance&&(t.inkImportance=this.inkImportance),this.edgeSeparation!=ge.DefaultEdgeSeparation&&(t.edgeSeparation=this.edgeSeparation),this._edgeWidthShrinkCoeff!=1&&(t._edgeWidthShrinkCoeff=this._edgeWidthShrinkCoeff),this.useCubicBezierSegmentsInsideOfHubs&&(t.useCubicBezierSegmentsInsideOfHubs=this.useCubicBezierSegmentsInsideOfHubs),this.angleThreshold!=Math.PI/180*45&&(t.angleThreshold=this.angleThreshold),this.hubRepulsionImportance!=100&&(t.hubRepulsionImportance=this.hubRepulsionImportance),this.bundleRepulsionImportance!=100&&(t.bundleRepulsionImportance=this.bundleRepulsionImportance),this.minimalRatioOfGoodCdtEdges!=.9&&(t.minimalRatioOfGoodCdtEdges=this.minimalRatioOfGoodCdtEdges),this.highestQuality||(t.highestQuality=this.highestQuality),this.KeepOverlaps&&(t.KeepOverlaps=this.KeepOverlaps),this.StopAfterShortestPaths&&(t.StopAfterShortestPaths=this.StopAfterShortestPaths),t}static createFromJSON(t){const e=new ge;return t.capacityOverflowCoefficient&&(e.capacityOverflowCoefficient=t.capacityOverflowCoefficient),t.RotateBundles&&(e.RotateBundles=t.RotateBundles),t.MaxHubRadius&&(e.MaxHubRadius=t.MaxHubRadius),t.MinHubRadius&&(e.MinHubRadius=t.MinHubRadius),t.CreateUnderlyingPolyline&&(e.CreateUnderlyingPolyline=t.CreateUnderlyingPolyline),t.pathLengthImportance&&(e.pathLengthImportance=t.pathLengthImportance),t.inkImportance&&(e.inkImportance=t.inkImportance),t.edgeSeparation&&(e.edgeSeparation=t.edgeSeparation),t._edgeWidthShrinkCoeff&&(e._edgeWidthShrinkCoeff=t._edgeWidthShrinkCoeff),t.useCubicBezierSegmentsInsideOfHubs&&(e.useCubicBezierSegmentsInsideOfHubs=t.useCubicBezierSegmentsInsideOfHubs),t.angleThreshold&&(e.angleThreshold=t.angleThreshold),t.hubRepulsionImportance&&(e.hubRepulsionImportance=t.hubRepulsionImportance),t.bundleRepulsionImportance&&(e.bundleRepulsionImportance=t.bundleRepulsionImportance),t.minimalRatioOfGoodCdtEdges&&(e.minimalRatioOfGoodCdtEdges=t.minimalRatioOfGoodCdtEdges),t.highestQuality&&(e.HighestQuality=t.highestQuality),t.KeepOverlaps&&(e.KeepOverlaps=t.KeepOverlaps),t.StopAfterShortestPaths&&(e.StopAfterShortestPaths=t.StopAfterShortestPaths),e}get CapacityOverflowCoefficient(){return this.capacityOverflowCoefficient}set CapacityOverflowCoefficient(t){this.capacityOverflowCoefficient=t}get PathLengthImportance(){return this.pathLengthImportance}set PathLengthImportance(t){this.pathLengthImportance=t}get InkImportance(){return this.inkImportance}set InkImportance(t){this.inkImportance=t}get EdgeSeparation(){return this.edgeSeparation}set EdgeSeparation(t){this.edgeSeparation=t}get edgeWidthShrinkCoeff(){return this._edgeWidthShrinkCoeff}set edgeWidthShrinkCoeff(t){this._edgeWidthShrinkCoeff=t}ActualEdgeWidth(t,e=this.edgeWidthShrinkCoeff){return e*(this.edgeSeparation+t.lineWidth)}get UseCubicBezierSegmentsInsideOfHubs(){return this.useCubicBezierSegmentsInsideOfHubs}set UseCubicBezierSegmentsInsideOfHubs(t){this.useCubicBezierSegmentsInsideOfHubs=t}get AngleThreshold(){return this.angleThreshold}set AngleThreshold(t){this.angleThreshold=t}get HubRepulsionImportance(){return this.hubRepulsionImportance}set HubRepulsionImportance(t){this.hubRepulsionImportance=t}get BundleRepulsionImportance(){return this.bundleRepulsionImportance}set BundleRepulsionImportance(t){this.bundleRepulsionImportance=t}get MinimalRatioOfGoodCdtEdges(){return this.minimalRatioOfGoodCdtEdges}set MinimalRatioOfGoodCdtEdges(t){this.minimalRatioOfGoodCdtEdges=t}get HighestQuality(){return this.highestQuality}set HighestQuality(t){this.highestQuality=t}}ge.DefaultCapacityOverflowCoefficientMultiplier=1e3,ge.DefaultPathLengthImportance=500,ge.DefaultInkImportance=.01,ge.DefaultEdgeSeparation=.5;class rn extends Es{constructor(t){super(null),this.node=t}get BoundaryCurve(){return this.node.boundaryCurve}set BoundaryCurve(t){if(t)throw new Error("Cannot set BoundaryCurve directly for RelativeShape")}}class Ii{static GetShapes(t,e){const i=new Map;for(const s of t)Ii.ProcessAncestorDescendantCouple(s.target,s.source,i),Ii.InsertEdgePortsToShapes(i,s);for(const s of e)Ii.ProcessAncestorDescendantCouple(s.source,s.target,i),Ii.InsertEdgePortsToShapes(i,s);return Ii.BindShapes(i),Array.from(i.values())}static InsertEdgePortsToShapes(t,e){t.get(e.target).Ports.add(e.targetPort),t.get(e.source).Ports.add(e.sourcePort)}static BindShapes(t){for(const[e,i]of t){if(!(e instanceof Xt))continue;const s=e;for(const n of fo(s)){const o=t.get(n);o&&i.AddChild(o)}}}static ProcessAncestorDescendantCouple(t,e,i){let s=vr(e);do{for(const n of fo(s))Ii.CreateShapeIfNeeeded(n,i);if(s===t)break;s=vr(s)}while(!0);Ii.CreateShapeIfNeeeded(s,i)}static CreateShapeIfNeeeded(t,e){e.has(t)||e.set(t,new rn(t))}static NumberOfActiveNodesIsUnderThreshold(t,e,i){const s=new Set;for(const n of t)if(Ii.SetOfActiveNodesIsLargerThanThreshold(n.target,n.source,s,i))return!1;for(const n of e)if(Ii.SetOfActiveNodesIsLargerThanThreshold(n.source,n.target,s,i))return!1;return!0}static SetOfActiveNodesIsLargerThanThreshold(t,e,i,s){let n=vr(e);for(;;){for(const o of fo(n))if(i.add(o),i.size>s)return!0;if(n===t)break;n=vr(n)}return i.add(n),i.size>s}}function vr(l){const t=l.node.parent;return gt.getGeom(t)}function*fo(l){for(const t of l.graph.shallowNodes)yield gt.getGeom(t)}class yt{constructor(t){this.stamp=0,this.SetPivotAndAllocateHullPointsArray(t)}SetPivotAndAllocateHullPointsArray(t){this.pivot=new d(0,Number.MAX_SAFE_INTEGER);let e=-1,i=0;for(const s of t)s.y<this.pivot.y?(this.pivot=s,e=i):s.y===this.pivot.y&&s.x>this.pivot.x&&(this.pivot=s,e=i),i++;if(i>=1){this.hullPoints=new Array(i-1),i=0;for(const s of t)i!==e?this.hullPoints[i++]={point:s,deleted:!1,stamp:this.stamp++}:e=-1}}get StackTopPoint(){return this.stack.point}get StackSecondPoint(){return this.stack.next.point}static*CalculateConvexHull(t){const e=new yt(t);for(const i of e.Calculate())yield i}*Calculate(){if(this.pivot.y!==Number.MAX_SAFE_INTEGER){if(this.hullPoints.length===0){yield this.pivot;return}this.SortAllPointsWithoutPivot(),this.Scan();for(const t of this.EnumerateStack())yield t}}*EnumerateStack(){let t=this.stack;for(;t!=null;)yield t.point,t=t.next}Scan(){let t=0;for(;this.hullPoints[t].deleted;)t++;for(this.stack={point:this.pivot,next:null},this.Push(t++),t<this.hullPoints.length&&(this.hullPoints[t].deleted?t++:this.Push(t++));t<this.hullPoints.length;)this.hullPoints[t].deleted?t++:this.LeftTurn(t)?this.Push(t++):this.Pop();for(;this.StackHasMoreThanTwoPoints()&&!this.LeftTurnToPivot();)this.Pop()}LeftTurnToPivot(){return d.getTriangleOrientation(this.StackSecondPoint,this.StackTopPoint,this.pivot)===k.Counterclockwise}StackHasMoreThanTwoPoints(){return this.stack.next!=null&&this.stack.next.next!=null}Pop(){this.stack=this.stack.next}LeftTurn(t){if(this.stack.next==null)return!0;const e=d.getTriangleOrientationWithIntersectionEpsilon(this.StackSecondPoint,this.StackTopPoint,this.hullPoints[t].point);return e===k.Counterclockwise?!0:e===k.Clockwise?!1:this.BackSwitchOverPivot(this.hullPoints[t].point)}BackSwitchOverPivot(t){return this.stack.next.next!=null?!1:this.StackTopPoint.x>this.pivot.x+C.distanceEpsilon&&t.x<this.pivot.x-C.distanceEpsilon}Push(t){this.stack={point:this.hullPoints[t].point,next:this.stack}}SortAllPointsWithoutPivot(){this.hullPoints.sort(Ye(this.pivot))}static createConvexHullAsClosedPolyline(t){return at.mkClosedFromPoints(Array.from(yt.CalculateConvexHull(t)))}}function Ye(l){return(t,e)=>{if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;switch(d.getTriangleOrientationWithIntersectionEpsilon(l,t.point,e.point)){case k.Counterclockwise:return-1;case k.Clockwise:return 1;case k.Collinear:const i=t.point.x-l.x,s=e.point.x-l.x;if(i>C.distanceEpsilon&&s<-C.distanceEpsilon)return-1;if(i<-C.distanceEpsilon&&s>C.distanceEpsilon)return 1;const n=t.point.sub(l),o=e.point.sub(l),a=n.l1-o.l1;return a<0?(t.deleted=!0,-1):a>0?(e.deleted=!0,1):(t.stamp>e.stamp?t.deleted=!0:e.deleted=!0,0)}throw new Error}}function Me(l,t,e){l.irect.intersects_rect(t.irect)&&(l.Left==null?t.Left==null?e(l.UserData,t.UserData):(Me(l,t.Left,e),Me(l,t.Right,e)):t.Left!=null?(Me(l.Left,t.Left,e),Me(l.Left,t.Right,e),Me(l.Right,t.Left,e),Me(l.Right,t.Right,e)):(Me(l.Left,t,e),Me(l.Right,t,e)))}function Ae(l,t,e){l.irect.intersects_rect(t.irect)&&(l===t?on(l,e):l.Left==null?t.Left==null?e(l.UserData,t.UserData):(Ae(l,t.Left,e),Ae(l,t.Right,e)):t.Left!=null?(Ae(l.Left,t.Left,e),Ae(l.Left,t.Right,e),Ae(l.Right,t.Left,e),Ae(l.Right,t.Right,e)):(Ae(l.Left,t,e),Ae(l.Right,t,e)))}function oe(l,t,e){if(!l.irect.intersects_rect(t.irect))return!1;if(l===t)return po(l,e);if(l.Left==null){if(t.Left==null)return e(l.UserData,t.UserData);if(oe(l,t.Left,e)||oe(l,t.Right,e))return!0}else if(t.Left!=null){if(oe(l.Left,t.Left,e)||oe(l.Left,t.Right,e)||oe(l.Right,t.Left,e)||oe(l.Right,t.Right,e))return!0}else if(oe(l.Left,t,e)||oe(l.Right,t,e))return!0;return!1}function po(l,t){return l.Left==null?!1:oe(l.Left,l.Left,t)||oe(l.Left,l.Right,t)||oe(l.Right,l.Right,t)}function on(l,t){l.Left!=null&&(Ae(l.Left,l.Left,t),Ae(l.Left,l.Right,t),Ae(l.Right,l.Right,t))}const U=BigInt("6364136223846793005"),Ir=(BigInt(1)<<BigInt(32))-BigInt(1),Ti=(BigInt(1)<<BigInt(64))-BigInt(1);class an{constructor(t,e){this._state=BigInt(0),this._inc=(BigInt(e)<<BigInt(1)|BigInt(1))&Ti,this._random_b(),this._state=this._state+BigInt(t)&Ti,this._random_b()}_random_b(){const t=this._state;this._state=t*U+this._inc&Ti;const e=(t>>BigInt(18)^t)>>BigInt(27),i=t>>BigInt(59),s=i^BigInt(31);return(e>>i|e<<s)&Ir}_advance(t){t&=Ti;let e=BigInt(1),i=U,s=BigInt(0),n=this._inc;for(;t>0;)t&BigInt(1)&&(e=e*i&Ti,s=s*i+n&Ti),n=(i+BigInt(1))*n&Ti,i=i*i&Ti,t>>=BigInt(1);this._state=e*this._state+s&Ti}randint(t){if(t>Ir)throw new TypeError(`Bound too large: ${t}`);if(t<=0)throw new TypeError(`Empty sample space for r: 0 \u2264 r < ${t}`);const e=BigInt(t),i=(Ir^e)%e;for(;;){const s=this._random_b();if(s>=i)return Number(s%e)}}random(){return Number(this._random_b())/Math.pow(2,32)}}let ts;function xs(l){return ts==null&&(ts=new an(0,0)),ts.randint(l)}function Os(l){ts=new an(l,0)}function ls(){return ts==null&&(ts=new an(0,0)),ts.random()}function*Vi(l){const t=new Array(l.nodeCount).fill(!1),e=new hi.o;for(let i=0;i<l.nodeCount;i++)if(!t[i]){const s=new Array;for(Po(i,e,t);e.length>0;){const n=e.dequeue();s.push(n);for(const o of mo(l,n))Po(o,e,t)}yield s}}function*mo(l,t){for(const e of l.outEdges[t])yield e.target;for(const e of l.inEdges[t])yield e.source}function Po(l,t,e){e[l]===!1&&(t.enqueue(l),e[l]=!0)}function ln(l){const t=new Ie;return t.SetEdges(l,Ie.vertexCount(l)),t}function So(l){const t=new Ie;return t.SetEdges(l,Ie.vertexCount(l)),t}function ni(l,t){const e=new Ie;return e.SetEdges(l,t),e}class Ie{constructor(){this.nodeCount=0}*incidentEdges(t){for(const e of this.outEdges[t])yield e;for(const e of this.inEdges[t])yield e}static deleteFromArray(t,e){const i=t.indexOf(e,0);i>-1&&t.splice(i,1)}removeEdge(t){Ie.deleteFromArray(this.edges,t),t.source!==t.target?(Ie.deleteFromArray(this.outEdges[t.source],t),Ie.deleteFromArray(this.inEdges[t.target],t)):Ie.deleteFromArray(this.selfEdges[t.source],t)}static vertexCount(t){let e=0;for(const i of t)i.source>=e&&(e=i.source),i.target>=e&&(e=i.target);return++e}SetEdges(t,e){this.edges=t,this.nodeCount=e;const i=new Array(this.nodeCount).fill(0),s=new Array(this.nodeCount).fill(0),n=new Array(this.nodeCount).fill(0);this.outEdges=new Array(this.nodeCount),this.inEdges=new Array(this.nodeCount),this.selfEdges=new Array(this.nodeCount);for(const o of this.edges)o.source!==o.target?(i[o.source]++,s[o.target]++):n[o.source]++;for(let o=0;o<this.nodeCount;o++)this.outEdges[o]=new Array(i[o]),i[o]=0,this.inEdges[o]=new Array(s[o]),s[o]=0,this.selfEdges[o]=new Array(n[o]),n[o]=0;for(const o of this.edges){const a=o.source,h=o.target;a!==h?(this.outEdges[a][i[a]++]=o,this.inEdges[h][s[h]++]=o):this.selfEdges[a][n[a]++]=o}}inEdgesCount(t){return this.inEdges[t].length}outEdgesCount(t){return this.outEdges[t].length}selfEdgesCount(t){return this.selfEdges[t].length}addEdge(t){this.edges.push(t),t.source!==t.target?(this.outEdges[t.source].push(t),this.inEdges[t.target].push(t)):this.selfEdges[t.source].push(t)}*nodesOfConnectedGraph(){if(this.edges.length===0)return;const t=new Set,e=new hi.o;let i=this.edges[0].source;for(Ie.enqueue(t,e,i),yield i;e.length>0;){i=e.dequeue();for(const s of this.outEdges[i]){const n=s.target;t.has(n)||(Ie.enqueue(t,e,n),yield n)}for(const s of this.inEdges[i]){const n=s.source;t.has(n)||(Ie.enqueue(t,e,n),yield n)}}}*pred(t){for(const e of this.inEdges[t])yield e.source}*succ(t){for(const e of this.outEdges[t])yield e.target}static enqueue(t,e,i){e.enqueue(i),t.add(i)}}class Ot{constructor(t,e){this.x=t,this.y=e}get source(){return this.x}get target(){return this.y}isDiagonal(){return this.x===this.y}}var ye;(function(l){l[l.Increasing=0]="Increasing",l[l.Decreasing=1]="Decreasing",l[l.Extremum=2]="Extremum"})(ye||(ye={}));class Ke{constructor(t,e){this.f=t,this.length=e}get Sequence(){return this.f}set Sequence(t){this.f=t}get Length(){return this.length}set Length(t){this.length=t}FindMinimum(){let t=0,e=this.length-1,i=t+Math.floor((e-t)/2);const s=this.f(i);if(s>=this.f(0)&&s>=this.f(this.length-1))return this.f(0)<this.f(this.length-1)?0:this.length-1;for(;e-t>1;)switch(i=t+Math.floor((e-t)/2),this.BehaviourAtIndex(i)){case ye.Decreasing:t=i;break;case ye.Increasing:e=i;break;case ye.Extremum:return i}return t===e||this.f(t)<=this.f(e)?t:e}BehaviourAtIndex(t){const e=this.f(t);if(t===0){const n=this.f(1);return n===e?ye.Extremum:n>e?ye.Increasing:ye.Decreasing}if(t===this.length-1){const n=this.f(this.length-2);return n===e?ye.Extremum:n>e?ye.Decreasing:ye.Increasing}const i=e-this.f(t-1),s=this.f(t+1)-e;return i*s<=0?ye.Extremum:i>0?ye.Increasing:ye.Decreasing}FindMaximum(){let t=0,e=this.length-1,i=t+Math.floor((e-t)/2);const s=this.f(i);if(s<=this.f(0)&&s<=this.f(this.length-1))return this.f(0)>this.f(this.length-1)?0:this.length-1;for(;e-t>1;)switch(i=t+Math.floor((e-t)/2),this.BehaviourAtIndex(i)){case ye.Decreasing:e=i;break;case ye.Increasing:t=i;break;case ye.Extremum:return i}return t===e||this.f(t)>=this.f(e)?t:e}}class yo{constructor(t,e){this.f=t,this.length=e}toArray(){const t=[];for(let e=0;e<this.length;e++)t.push(this.f(e));return t}GetAdjustedSequenceForMinimum(){const t=this.f(0),i=(this.f(this.length-1)-t)/(this.length-1);return s=>Math.min(this.f(s),t+i*s)}GetAdjustedSequenceForMaximum(){const t=this.f(0),i=(this.f(this.length-1)-t)/(this.length-1);return s=>Math.max(this.f(s),t+i*s)}FindMinimum(){return this.f(0)===this.f(this.length-1)?new Ke(this.f,this.length).FindMinimum():new Ke(this.GetAdjustedSequenceForMinimum(),this.length).FindMinimum()}FindMaximum(){return this.f(0)===this.f(this.length-1)?new Ke(this.f,this.length).FindMaximum():new Ke(this.GetAdjustedSequenceForMaximum(),this.length).FindMaximum()}}class Hn{constructor(t,e){this.P=t,this.Q=e}LeftFromLineOnP(t,e,i){const s=this.P.pnt(t);return this.upperBranchOnP?d.pointToTheLeftOfLineOrOnLine(i,s,e):d.pointToTheRightOfLineOrOnLine(i,s,e)}LeftFromLineOnQ(t,e,i){const s=this.Q.pnt(t);return this.lowerBranchOnQ?d.pointToTheLeftOfLineOrOnLine(i,s,e):d.pointToTheRightOfLineOrOnLine(i,s,e)}PrevOnP(t){return this.upperBranchOnP?this.P.Prev(t):this.P.Next(t)}PrevOnQ(t){return this.lowerBranchOnQ?this.Q.Prev(t):this.Q.Next(t)}NextOnP(t){return this.upperBranchOnP?this.P.Next(t):this.P.Prev(t)}NextOnQ(t){return this.lowerBranchOnQ?this.Q.Next(t):this.Q.Prev(t)}MedianOnP(t,e){return this.upperBranchOnP?this.P.Median(t,e):this.P.Median(e,t)}MedianOnQ(t,e){return this.lowerBranchOnQ?this.Q.Median(t,e):this.Q.Median(e,t)}ModuleP(t,e){return this.upperBranchOnP?this.P.Module(e-t):this.P.Module(t-e)}ModuleQ(t,e){return this.lowerBranchOnQ?this.Q.Module(e-t):this.Q.Module(t-e)}TangentBetweenBranches(t,e,i,s){for(;e!==t||s!==i;){const n=e!==t?this.MedianOnP(t,e):t,o=s!==i?this.MedianOnQ(i,s):i,a=this.P.pnt(n),h=this.Q.pnt(o);let u=!0;this.ModuleP(t,e)>1?this.LeftFromLineOnP(this.NextOnP(n),a,h)?t=n:this.LeftFromLineOnP(this.PrevOnP(n),a,h)?e=n:u=!1:e!==t?this.LeftFromLineOnP(e,this.P.pnt(t),h)?t=e:this.LeftFromLineOnP(t,this.P.pnt(e),h)?e=t:u=!1:u=!1;let c=!0;this.ModuleQ(i,s)>1?this.LeftFromLineOnQ(this.NextOnQ(o),h,a)?i=o:this.LeftFromLineOnQ(this.PrevOnQ(o),h,a)?s=o:c=!1:s!==i?this.LeftFromLineOnQ(s,this.Q.pnt(i),a)?i=s:this.LeftFromLineOnQ(i,this.Q.pnt(s),a)?s=i:c=!1:c=!1,!u&&!c&&(t=n,e=n,i=o,s=o)}return[t,s]}FindDividingBisector(t){const e={pClosest:void 0,qClosest:void 0,p1:void 0,p2:void 0,q1:void 0,q2:void 0};this.FindClosestFeatures(e),t.bisectorPivot=d.middle(e.pClosest,e.qClosest),t.bisectorRay=e.pClosest.sub(e.qClosest).rotate(Math.PI/2),t.p1=e.p1,t.p2=e.p2,t.q1=e.q1,t.q2=e.q2}FindClosestPoints(){const t={q2:void 0,p1:void 0,p2:void 0,q1:void 0,pClosest:void 0,qClosest:void 0};return this.FindClosestFeatures(t),{pClosest:t.pClosest,qClosest:t.qClosest}}FindClosestFeatures(t){const e={leftTangentPoint:void 0,rightTangentPoint:void 0};this.P.GetTangentPoints(e,this.Q.pp(0).point),t.p2=e.leftTangentPoint,t.p1=e.rightTangentPoint,t.p2===t.p1&&(t.p2+=this.P.count),this.Q.GetTangentPoints(e,this.P.pp(0).point),t.q1=e.leftTangentPoint,t.q2=e.rightTangentPoint,t.q2===t.q1&&(t.q2+=this.Q.count),this.FindClosestPoints_(t)}FindClosestPoints_(t){for(;this.ChunksAreLong(t.p2,t.p1,t.q2,t.q1);)this.ShrinkChunks(t);t.p1===t.p2?(t.pClosest=this.P.pp(t.p2).point,t.q1===t.q2?t.qClosest=this.Q.pp(t.q1).point:(t.qClosest=d.ClosestPointAtLineSegment(t.pClosest,this.Q.pp(t.q1).point,this.Q.pp(t.q2).point),d.closeDistEps(t.qClosest,this.Q.pnt(t.q1))?t.q2=t.q1:d.closeDistEps(t.qClosest,this.Q.pnt(t.q2))&&(t.q1=t.q2))):(t.qClosest=this.Q.pp(t.q1).point,t.pClosest=d.ClosestPointAtLineSegment(t.qClosest,this.P.pp(t.p1).point,this.P.pp(t.p2).point),d.closeDistEps(t.pClosest,this.P.pnt(t.p1))?t.p2=t.p1:d.closeDistEps(t.qClosest,this.P.pnt(t.p2))&&(t.p1=t.p2))}ChunksAreLong(t,e,i,s){const n=this.P.Module(t-e)+1;if(n>2)return!0;const o=this.Q.Module(s-i)+1;return o>2||n===2&&o===2}ShrinkChunks(t){const e=t.p1===t.p2?t.p1:this.P.Median(t.p1,t.p2),i=t.q1===t.q2?t.q1:this.Q.Median(t.q2,t.q1),s=this.P.pp(e).point,n=this.Q.pp(i).point,o={a1:void 0,a2:void 0,b1:void 0,b2:void 0};if(this.GetAnglesAtTheMedian(e,i,s,n,o),!this.InternalCut(t,e,i,o.a1,o.a2,o.b1,o.b2)&&!Hn.OneOfChunksContainsOnlyOneVertex(t,e,i,o.a1,o.b1)&&!this.OnlyOneChunkContainsExactlyTwoVertices(t,{mp:e,mq:i},o)){if(t.p2===this.P.Next(t.p1)&&t.q1===this.Q.Next(t.q2)){const a=D.minDistBetweenLineSegments(this.P.pnt(t.p1),this.P.pnt(t.p2),this.Q.pnt(t.q1),this.Q.pnt(t.q2));a.parab===0?t.p2=t.p1:a.parab===1?t.p1=t.p2:a.parcd===0?t.q2=t.q1:a.parcd===1&&(t.q1=t.q2);return}o.a1<=Math.PI&&o.a2<=Math.PI&&o.b1<=Math.PI&&o.b2<=Math.PI?o.a1+o.b1>Math.PI?o.a1>=Math.PI/2?t.p1=e:t.q1=i:o.a2>=Math.PI/2?t.p2=e:t.q2=i:o.a1>Math.PI?t.p1=e:o.a2>Math.PI?t.p2=e:o.b1>Math.PI?t.q1=i:t.q2=i}}InternalCut(t,e,i,s,n,o,a){let h=!1;if(s>=Math.PI&&n>=Math.PI){const u=this.P.pp(e).point,c=this.Q.pp(i).point,m=this.P.pp(this.P.Next(e)).point,S=d.getTriangleOrientation(u,c,this.Q.pp(0).point),A=d.getTriangleOrientation(u,c,m);S===A?t.p1=this.P.Next(e):t.p2=this.P.Prev(e),h=!0}if(o>=Math.PI&&a>=Math.PI){const u=this.P.pp(e).point,c=this.Q.pp(i).point,m=this.Q.pp(this.Q.Next(i)).point,S=d.getTriangleOrientation(u,c,this.P.pp(0).point),A=d.getTriangleOrientation(u,c,m);S===A?t.q2=this.Q.Next(i):t.q1=this.Q.Prev(i),h=!0}return h}GetAnglesAtTheMedian(t,e,i,s,n){n.a1=d.anglePCP(s,i,this.P.pnt(this.P.Prev(t))),n.a2=d.anglePCP(this.P.pnt(this.P.Next(t)),i,s),n.b1=d.anglePCP(this.Q.pnt(this.Q.Next(e)),s,i),n.b2=d.anglePCP(i,s,this.Q.pnt(this.Q.Prev(e)))}OnlyOneChunkContainsExactlyTwoVertices(t,e,i){const s=t.p2===this.P.Next(t.p1),n=t.q1===this.Q.Next(t.q2);return s&&!n?(this.ProcessShortSide(t,e.mp,e.mq,i.a1,i.b1,i.a2,i.b2),!0):n&&!s?(this.SwapEverything(t,e,i),this.ProcessShortSide(t,e.mp,e.mq,i.a1,i.b1,i.a2,i.b2),this.SwapEverything(t,e,i),!0):!1}SwapEverything(t,e,i){this.SwapPq();let s=t.p2;t.p2=t.q1,t.q1=s,s=t.q2,t.q2=t.p1,t.p1=s,s=e.mq,e.mq=e.mp,e.mp=s,s=i.a2,i.a2=i.b1,i.b1=s,s=i.b2,i.b2=i.a1,i.a1=s}ProcessShortSide(t,e,i,s,n,o,a){e===t.p2?this.ProcessSide(t,i,s,n,a):o<=Math.PI?o+a>=Math.PI?o>=Math.PI/2?t.p2=t.p1:t.q2=i:n>=Math.PI/2?t.q1=i:o<a&&(d.canProject(this.Q.pnt(i),this.P.pp(t.p1).point,this.P.pp(t.p2).point)?t.q1=i:t.p1=t.p2):s+n<=Math.PI?t.p1=t.p2:t.p2=t.p1}SwapPq(){const t=this.P;this.P=this.Q,this.Q=t}ProcessSide(t,e,i,s,n){const o=this.Q.pnt(e);i<=Math.PI?i+s>=Math.PI?i>=Math.PI/2?t.p1=t.p2:t.q1=e:n>=Math.PI/2?t.q2=e:i<n&&(d.canProject(o,this.P.pp(t.p1).point,this.P.pp(t.p2).point)?t.q2=e:t.p2=t.p1):(t.p2=t.p1,s>=Math.PI?t.q1=e:n>=Math.PI&&(t.q2=e))}static OneOfChunksContainsOnlyOneVertex(t,e,i,s,n){return t.p1===t.p2?(n>=Math.PI/2?t.q1=i:t.q2=i,!0):t.q1===t.q2?(s>=Math.PI/2?t.p1=e:t.p2=e,!0):!1}CalculateLeftTangents(){const t={bisectorPivot:null,bisectorRay:null,p1:0,p2:0,q1:0,q2:0};this.FindDividingBisector(t);const e=this.P.FindTheFurthestVertexFromBisector(t.p1,t.p2,t.bisectorPivot,t.bisectorRay),i=this.Q.FindTheFurthestVertexFromBisector(t.q2,t.q1,t.bisectorPivot,t.bisectorRay);this.upperBranchOnP=!1,this.lowerBranchOnQ=!0,this.leftPLeftQ=this.TangentBetweenBranches(e,t.p1,i,t.q1),this.lowerBranchOnQ=!1,this.leftPRightQ=this.TangentBetweenBranches(e,t.p1,i,t.q2)}CalculateRightTangents(){const t={bisectorPivot:null,bisectorRay:null,p1:0,p2:0,q1:0,q2:0};this.FindDividingBisector(t);const e=this.P.FindTheFurthestVertexFromBisector(t.p1,t.p2,t.bisectorPivot,t.bisectorRay),i=this.Q.FindTheFurthestVertexFromBisector(t.q2,t.q1,t.bisectorPivot,t.bisectorRay);this.upperBranchOnP=!0,this.lowerBranchOnQ=!0,this.rightPLeftQ=this.TangentBetweenBranches(e,t.p2,i,t.q1),this.lowerBranchOnQ=!1,this.rightPRightQ=this.TangentBetweenBranches(e,t.p2,i,t.q2)}}class Te{constructor(t){this.polyline=t,this.points=new Array;for(let e=this.polyline.startPoint;e;e=e.next)this.points.push(e)}static mkFromPoints(t){return new Te(at.mkClosedFromPoints(t))}get Polyline(){return this.polyline}Next(t){return this.Module(t+1)}Prev(t){return this.Module(t-1)}get count(){return this.Polyline.count}Module(t){return t<0?t+this.count:t<this.count?t:t-this.count}pp(t){return this.points[this.Module(t)]}pnt(t){return this.pp(t).point}toString(){return this.polyline.toString()}Median(t,e){return e>t?Math.floor((e+t)/2):this.Module(e+Math.floor((this.count+t)/2))}FindTheFurthestVertexFromBisector(t,e,i,s){let n=s.rotate(Math.PI/2);this.polyline.startPoint.point.sub(i).dot(n)<0&&(n=n.mul(-1)),t===e&&(e=this.Next(t));do{const o=this.Median(e,t),a=this.pnt(o);this.pnt(this.Next(o)).sub(a).dot(n)>=0?e=this.Next(o):this.pnt(this.Prev(o)).sub(a).dot(n)>=0?t=this.Prev(o):e=o,t=o}while(t!==e);return t}static TestPolygonDist(t,e){let i=Number.MAX_SAFE_INTEGER;for(let s=0;s<t.count;s++)for(let n=0;n<e.count;n++){const o=D.minDistBetweenLineSegments(t.pnt(s),t.pnt(s+1),e.pnt(n),e.pnt(n+1));i=Math.min(i,o.dist)}return i}static Distance(t,e){const s=new Hn(t,e).FindClosestPoints();return{p:s.pClosest,q:s.qClosest,dist:s.pClosest.sub(s.qClosest).length}}static DistanceOnly(t,e){return Te.Distance(t,e).dist}static PolygonIsLegalDebug(t){const e=t.Polyline;for(let i=e.startPoint;i.next!=null&&i.next.next!=null;i=i.next)if(d.getTriangleOrientation(i.point,i.next.point,i.next.next.point)===k.Collinear)return!1;return!0}static DistancePoint(t,e){let i=Number.MAX_VALUE;for(let s=0;s<t.count;s++){const n=d.distToLineSegment(e,t.points[s].point,t.points[(s+1)%t.count].point).dist;i=Math.min(i,n)}return i}GetTangentPoints(t,e){const i=new yo(this.GetSequenceDelegate(e),this.count);t.leftTangentPoint=i.FindMaximum(),t.rightTangentPoint=i.FindMinimum()}GetSequenceDelegate(t){const e=this.pnt(0);return i=>{const s=d.anglePCP(e,t,this.pnt(i));return s<Math.PI?s:s-2*Math.PI}}}class mt{constructor(t,e,i,s){this.randomizationShift=.01,this.TightObstacles=new Set,this.Obstacles=t,this.TightPadding=e,this.LoosePadding=i,this.IgnoreTightPadding=s}ObstaclesIntersectLine(t,e){return this.ObstaclesIntersectICurve(D.mkPP(t,e))}static PadCorner(t,e,i,s,n){const o=mt.GetPaddedCorner(e,i,s,n);return o.numberOfPoints===-1?!1:(t.addPoint(o.a),o.numberOfPoints===2&&t.addPoint(o.b),!0)}static CurveIsClockwise(t,e){return d.getTriangleOrientation(e,t.start,t.start.add(t.derivative(t.parStart)))==k.Clockwise}static PaddedPolylineBoundaryOfNode(t,e,i=!1){return mt.CreatePaddedPolyline(w.polylineAroundClosedCurve(t),e,i)}static LoosePolylineWithFewCorners(t,e,i){return e<C.distanceEpsilon?t:mt.CreateLoosePolylineOnBisectors(t,e,i)}static CreateLoosePolylineOnBisectors(t,e,i){const s=Array.from(mt.BisectorPoints(t,e));i&&o();const n=yt.CalculateConvexHull(s);return at.mkClosedFromPoints(n);function o(){for(let a=0;a<s.length;a++){const h=s[a];s[a]=new d(h.x+(2*ls()-1)*i,h.y+(2*ls()-1)*i)}}}static CreateRectNodeOfPolyline(t){return pe(t,t.boundingBox)}CreateLooseObstacles(){this.tightPolylinesToLooseDistances=new Map,this.LooseObstacles=new Array;for(const t of this.TightObstacles){const e=mt.FindMaxPaddingForTightPolyline(this.RootOfTightHierarchy,t,this.LoosePadding);this.tightPolylinesToLooseDistances.set(t,e),this.LooseObstacles.push(mt.LoosePolylineWithFewCorners(t,e,this.randomizationShift))}this.RootOfLooseHierarchy=mt.CalculateHierarchy(this.LooseObstacles)}CreateTightObstacles(){this.RootOfTightHierarchy=this.CreateTightObstacles_(),this.OverlapsDetected=this.TightObstacles.size<this.Obstacles.length}Calculate(){this.IgnoreTightPadding?this.CreateTightObstaclesIgnoringTightPadding():this.CreateTightObstacles(),this.IsEmpty()||this.CreateLooseObstacles()}IsEmpty(){return this.TightObstacles==null||this.TightObstacles.size===0}ObstaclesIntersectICurve(t){const e=t.boundingBox;return mt.CurveIntersectsRectangleNode(t,e,this.RootOfTightHierarchy)}static CurveIntersectsRectangleNode(t,e,i){if(!i.irect.intersects(e))return!1;if(i.UserData!=null){const s=i.UserData;return w.intersectionOne(s,t,!1)!=null||mt.PointIsInside(s.start,t)}return mt.CurveIntersectsRectangleNode(t,e,i.Left)||mt.CurveIntersectsRectangleNode(t,e,i.Right)}static PointIsInside(t,e){return w.PointRelativeToCurveLocation(t,e)===ft.Inside}CreateTightObstaclesIgnoringTightPadding(){const t=this.Obstacles.map(s=>w.polylineAroundClosedCurve(s)),e=mt.CalculateHierarchy(t),i=mt.GetOverlappedPairSet(e);if(this.TightObstacles=new Set,i.size===0){for(const s of t){const n=mt.FindMaxPaddingForTightPolyline(e,s,this.TightPadding);this.TightObstacles.add(mt.LoosePolylineWithFewCorners(s,n,this.randomizationShift))}this.RootOfTightHierarchy=mt.CalculateHierarchy(Array.from(this.TightObstacles))}else{for(const s of t)this.TightObstacles.add(mt.CreatePaddedPolyline(s,this.TightPadding));if(!this.IsEmpty())for(this.RootOfTightHierarchy=mt.CalculateHierarchy(Array.from(this.TightObstacles)),this.OverlapsDetected=!1;mt.GetOverlappedPairSet(this.RootOfTightHierarchy).size>0;)this.RootOfTightHierarchy=mt.ReplaceTightObstaclesWithConvexHulls(this.TightObstacles,Array.from(i)),this.OverlapsDetected=!0}}CreateTightObstacles_(){if(this.Obstacles.length===0)return null;for(const t of this.Obstacles)mt.CalculateTightPolyline(this.TightObstacles,this.TightPadding,t);return mt.RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(this.TightObstacles)}static CalculateTightPolyline(t,e,i){const s=mt.PaddedPolylineBoundaryOfNode(i,e);t.add(s)}static CalculateHierarchy(t){const e=t.map(i=>mt.CreateRectNodeOfPolyline(i));return re(e)}static RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(t){let e=mt.CalculateHierarchy(Array.from(t)),i;for(;(i=mt.GetOverlappedPairSet(e)).size>0;)e=mt.ReplaceTightObstaclesWithConvexHulls(t,Array.from(i));return e}static MapToInt(t){const e=new Map;for(let i=0;i<t.length;i++)e.set(t[i],i);return e}static ReplaceTightObstaclesWithConvexHulls(t,e){const i=new Set;for(const h of e)i.add(h[0]),i.add(h[1]);const s=Array.from(i),n=mt.MapToInt(s),o=So(Array.from(e).map(h=>new Ot(n.get(h[0]),n.get(h[1])))),a=Vi(o);for(const h of a){const u=h.map(S=>s[S]),c=Zs(u,S=>S),m=yt.createConvexHullAsClosedPolyline(c);for(const S of u)t.delete(S);t.add(m)}return mt.CalculateHierarchy(Array.from(t))}static OneCurveLiesInsideOfOther(t,e){return w.PointRelativeToCurveLocation(t.start,e)!==ft.Outside||w.PointRelativeToCurveLocation(e.start,t)!==ft.Outside}static PolylinesIntersect(t,e){return w.CurvesIntersect(t,e)||mt.OneCurveLiesInsideOfOther(t,e)}static GetOverlappedPairSet(t){const e=new Set;return Ae(t,t,(i,s)=>{mt.PolylinesIntersect(i,s)&&e.add([i,s])}),e}static*BisectorPoints(t,e){for(let i=t.startPoint;i!=null;i=i.next){const s={skip:!1},n=mt.GetStickingVertexOnBisector(i,e,s);s.skip||(yield n)}}static GetStickingVertexOnBisector(t,e,i){const s=t.polyline.prev(t).point,n=t.point,o=t.polyline.next(t).point;let a=n.sub(s).normalize().add(n.sub(o).normalize());const h=a.length;return h<C.tolerance?i.skip=!0:(i.skip=!1,a=a.div(h)),a.mul(e).add(n)}static FindMaxPaddingForTightPolyline(t,e,i){let s=i;const n=new Te(e),o=e.boundingBox.clone();o.pad(2*i);for(const a of Array.from(t.GetNodeItemsIntersectingRectangle(o)).filter(h=>h!==e)){const h=Te.Distance(n,new Te(a)).dist;s=Math.min(s,h/mt.LooseDistCoefficient)}return s}static GetPaddedCorner(t,e,i,s){const n=t.point,o=e.point,a=i.point;if(d.getTriangleOrientation(n,o,a)===k.Counterclockwise)return{a:void 0,b:void 0,numberOfPoints:-1};let h=o.sub(n).rotate(Math.PI/2).normalize();if(mt.CornerIsNotTooSharp(n,o,a)){h=h.mul(s);const I=a.sub(o).normalize().mul(s).rotate(Math.PI/2),B=d.lineLineIntersection(n.add(h),o.add(h),o.add(I),a.add(I));return{a:B,b:B,numberOfPoints:1}}const u=o.sub(n).normalize().add(o.sub(a).normalize());if(u.length<C.intersectionEpsilon){const I=o.add(h.mul(s));return{a:I,b:I,numberOfPoints:1}}const c=u.normalize().mul(s),m=c.rotate(Math.PI/2),S=(s-c.dot(h))/m.dot(h),A=m.mul(S);return{a:c.add(A).add(o),b:c.sub(A).add(o),numberOfPoints:2}}static CornerIsNotTooSharp(t,e,i){const s=t.sub(e).rotate(Math.PI/4).add(e);return d.getTriangleOrientation(e,s,i)===k.Counterclockwise}static CreatePaddedPolyline(t,e,i=!1){const s=new at,n=i?Co(t):t;if(!mt.PadCorner(s,n.endPoint.prev,n.endPoint,n.startPoint,e)||!mt.PadCorner(s,n.endPoint,n.startPoint,n.startPoint.next,e))return mt.CreatePaddedPolyline(at.mkClosedFromPoints(Array.from(yt.CalculateConvexHull(n))),e);for(let o=n.startPoint;o.next.next!=null;o=o.next)if(!mt.PadCorner(s,o,o.next,o.next.next,e))return mt.CreatePaddedPolyline(at.mkClosedFromPoints(Array.from(yt.CalculateConvexHull(n))),e);return s.closed=!0,s}}mt.LooseDistCoefficient=2.1;function Co(l){const t=new at,e=.01;for(let i=l.startPoint;i;i=i.next){const s=i.point.x+e*ls(),n=i.point.y+e*ls();t.addPointXY(s,n)}return t.closed=l.closed,t}class Tr{get TightPolyline(){return this.tightPoly}set TightPolyline(t){this.tightPoly=t}static mk(t,e,i){const s=new Tr;return s.TightPolyline=t,s.LooseShape=e,s.Distance=i,s}toString(){return(this.TightPolyline==null?"null":this.TightPolyline.toString().substring(0,5))+","+(this.LooseShape==null?"null":this.LooseShape.toString().substring(0,5))}}class hn{constructor(t,e,i,s){this.loosePolylinesToNodes=new Map,this.MainShape=t,this.TightPadding=e,this.LoosePadding=i,this.ShapesToTightLooseCouples=s}Calculate(t,e=Number.MAX_VALUE){Os(3),this.MainShape.Children.length!==0&&(this.CreateTightObstacles(),this.CreateTigthLooseCouples(t),this.OverlapsDetected&&this.FillTheMapOfShapeToTightLooseCouples())}FillTheMapOfShapeToTightLooseCouples(){const t=re(this.MainShape.Children.map(e=>pe(e,e.BoundingBox)));Me(t,this.coupleHierarchy,this.TryMapShapeToTightLooseCouple.bind(this))}TryMapShapeToTightLooseCouple(t,e){hn.ShapeIsInsideOfPoly(t,e.TightPolyline)&&this.ShapesToTightLooseCouples.set(t,e)}static ShapeIsInsideOfPoly(t,e){return w.PointRelativeToCurveLocation(t.BoundaryCurve.start,e)===ft.Inside}CreateTigthLooseCouples(t){const e=new Array;for(const i of this.tightHierarchy.GetAllLeaves()){const s=mt.FindMaxPaddingForTightPolyline(this.tightHierarchy,i,this.LoosePadding),n=mt.LoosePolylineWithFewCorners(i,s,t),o=new Es(n),a=Tr.mk(i,o,s);this.ShapesToTightLooseCouples.set(this.tightToShape.get(i),a),e.push(a)}this.coupleHierarchy=re(e.map(i=>pe(i,i.TightPolyline.boundingBox)))}CreateTightObstacles(){this.tightToShape=new Map;const t=new Set(this.MainShape.Children.map(this.InitialTightPolyline.bind(this))),e=t.size;this.tightHierarchy=mt.RemovePossibleOverlapsInTightPolylinesAndCalculateHierarchy(t),this.OverlapsDetected=e>t.size}InitialTightPolyline(t){let e=mt.PaddedPolylineBoundaryOfNode(t.BoundaryCurve,this.TightPadding);const i=Zs(this.LoosePolylinesUnderShape(t),n=>n).filter(n=>w.PointRelativeToCurveLocation(n,e)===ft.Outside);if(i.length==0)return this.tightToShape&&this.tightToShape.set(e,t),e;const s=Array.from(e).concat(i);return e=at.mkClosedFromPoints(yt.CalculateConvexHull(s)),this.tightToShape&&this.tightToShape.set(e,t),e}LoosePolylinesUnderShape(t){return t.Children.map(e=>this.ShapesToTightLooseCouples.get(e).LooseShape.BoundaryCurve)}}class Eo{constructor(t,e,i){this.indexToA=t,this.priority=e,this.v=i}}class es{constructor(t=W){this.heapSize=0,this.compare=t,this.cache=new Map,this.A=[]}get count(){return this.heapSize}ContainsElement(t){return this.cache.has(t)}SwapWithParent(t){const e=this.A[t>>1];this.PutAtI(t>>1,this.A[t]),this.PutAtI(t,e)}Enqueue(t,e){let i=++this.heapSize;const s=new Eo(i,e,t);for(this.cache.set(t,s),this.A[i]=s;i>1&&this.compare(this.A[i>>1].priority,e)>0;)this.SwapWithParent(i),i>>=1}IsEmpty(){return this.heapSize===0}PutAtI(t,e){this.A[t]=e,e.indexToA=t}Dequeue(){if(this.heapSize===0)throw new Error("dequeue on an empty queue");const t=this.A[1].v;return this.MoveQueueOneStepForward(t),t}DequeueAndGetPriority(t){if(this.heapSize===0)throw new Error("dequeue on an empty queue");const e=this.A[1].v;return t.priority=this.A[1].priority,this.MoveQueueOneStepForward(e),e}MoveQueueOneStepForward(t){this.cache.delete(t),this.PutAtI(1,this.A[this.heapSize]);let e=1;for(;;){let i=e;const s=e<<1;s<=this.heapSize&&this.compare(this.A[s].priority,this.A[e].priority)<0&&(i=s);const n=s+1;if(n<=this.heapSize&&this.compare(this.A[n].priority,this.A[i].priority)<0&&(i=n),i!==e)this.SwapWithParent(i);else break;e=i}this.heapSize--}DecreasePriority(t,e){const i=this.cache.get(t);if(!i)return;i.priority=e;let s=i.indexToA;for(;s>1&&this.compare(this.A[s].priority,this.A[s>>1].priority)<0;){this.SwapWithParent(s);s>>=1}}*GetEnumerator(){for(let t=1;t<=this.heapSize;t++)yield this.A[t].v}Peek(t){if(this.count===0){t.priority=0;return}return t.priority=this.A[1].priority,this.A[1].v}toString(){const t=new Se.fe;for(const e of this.A)t.Append(e+",");return t.ToString()}}class Ls{constructor(t,e,i){this.upperBound=Number.POSITIVE_INFINITY,this._visGraph=i,this._visGraph.ClearPrevEdgesTable();for(const s of i.Vertices())s.Distance=Number.POSITIVE_INFINITY;this.source=t,this.targets=new Set(e),this.source.Distance=0}GetPath(){const t=new es(W);for(this.source.Distance=0,t.Enqueue(this.source,0);!t.IsEmpty()&&(this.current=t.Dequeue(),!this.targets.has(this.current));){for(const e of this.current.OutEdges)this.PassableOutEdge(e)&&this.ProcessNeighbor(t,e,e.Target);for(const e of this.current.InEdges)this.PassableInEdge(e)&&this.ProcessNeighbor(t,e,e.Source)}return this._visGraph.PreviosVertex(this.current)==null?null:this.CalculatePath()}PassableOutEdge(t){return t.Source===this.source||this.targets.has(t.Target)||!Ls.IsForbidden(t)}PassableInEdge(t){return this.targets.has(t.Source)||t.Target===this.source||!Ls.IsForbidden(t)}static IsForbidden(t){return t.IsPassable!=null&&!t.IsPassable()||t instanceof wi}ProcessNeighbor(t,e,i){const s=e.Length,n=this.current.Distance+s;n>=this.upperBound||(this.targets.has(i)&&(this.upperBound=n,this.closestTarget=i),i!==this.source&&this._visGraph.PreviosVertex(i)==null?(i.Distance=n,this._visGraph.SetPreviousEdge(i,e),t.Enqueue(i,n)):n<i.Distance&&(i.Distance=n,this._visGraph.SetPreviousEdge(i,e),t.DecreasePriority(i,n)))}CalculatePath(){if(this.closestTarget==null)return null;const t=new Array;let e=this.closestTarget;do t.push(e),e=this._visGraph.PreviosVertex(e);while(e!==this.source);return t.push(this.source),t.reverse()}}class zn{constructor(t,e,i){this._lengthMultiplier=1,this._lengthMultiplierForAStar=1,this._visGraph=t,this._source=e,this._target=i,this._source.Distance=0}get LengthMultiplier(){return this._lengthMultiplier}set LengthMultiplier(t){this._lengthMultiplier=t}get LengthMultiplierForAStar(){return this._lengthMultiplierForAStar}set LengthMultiplierForAStar(t){this._lengthMultiplierForAStar=t}GetPath(t){const e=new es(W);for(this._source.Distance=0,this._target.Distance=Number.POSITIVE_INFINITY,e.Enqueue(this._source,this.H(this._source));!e.IsEmpty();){const i={priority:0},s=e.DequeueAndGetPriority(i);if(i.priority>=this._target.Distance)break;for(const n of s.OutEdges)if(this.PassableOutEdge(n)){const o=n.Target;this.ProcessNeighbor(e,s,n,o)}for(const n of s.InEdges)if(this.PassableInEdge(n)){const o=n.Source;this.ProcessNeighbor(e,s,n,o)}}return this._visGraph.PreviosVertex(this._target)==null?null:this.CalculatePath(t)}PassableOutEdge(t){return t.Source===this._source||t.Target===this._target||!zn.IsForbidden(t)}PassableInEdge(t){return t.Source===this._target||t.Target===this._source||!zn.IsForbidden(t)}static IsForbidden(t){return t.IsPassable!=null&&!t.IsPassable()||t instanceof wi}ProcessNeighborN(t,e,i,s,n){const o=i.Length+n,a=e.Distance+o;s!==this._source&&this._visGraph.PreviosVertex(s)==null?(s.Distance=a,this._visGraph.SetPreviousEdge(s,i),s!==this._target&&t.Enqueue(s,this.H(s))):s!==this._source&&a<s.Distance&&(s.Distance=a,this._visGraph.SetPreviousEdge(s,i),s!==this._target&&t.DecreasePriority(s,this.H(s)))}ProcessNeighbor(t,e,i,s){const n=i.Length,o=e.Distance+n;s!==this._source&&this._visGraph.PreviosVertex(s)==null?(s.Distance=o,this._visGraph.SetPreviousEdge(s,i),s!==this._target&&t.Enqueue(s,this.H(s))):s!==this._source&&o<s.Distance&&(s.Distance=o,this._visGraph.SetPreviousEdge(s,i),s!==this._target&&t.DecreasePriority(s,this.H(s)))}H(t){return t.Distance+t.point.sub(this._target.point).length*this.LengthMultiplierForAStar}CalculatePath(t){const e=new Array;let i=this._target;do e.push(i),t&&this._visGraph.ShrinkLengthOfPrevEdge(i,this.LengthMultiplier),i=this._visGraph.PreviosVertex(i);while(i!==this._source);return e.push(this._source),e.reverse()}}var Wi;(function(l){l[l.Regular=0]="Regular",l[l.Tangent=1]="Tangent"})(Wi||(Wi={}));class bo{constructor(t,e){this.LeftTangent=t,this.RightTangent=e}toString(){return Se.Qf.Format("{0},{1}",this.Start,this.End)}get Start(){return this.leftTangent.End.point}get End(){return this.rightTangent.End.point}get LeftTangent(){return this.leftTangent}set LeftTangent(t){this.leftTangent=t}get RightTangent(){return this.rightTangent}set RightTangent(t){this.rightTangent=t}get RbNode(){return this.rbNode}set RbNode(t){this.rbNode=t}}class Ao{constructor(t,e){this.start=t,this.End=e}get Comp(){return this.comp}set Comp(t){this.comp=t}get IsHigh(){return!this.IsLow}get IsLow(){return this.lowTangent}set IsLow(t){this.lowTangent=t}get SeparatingPolygons(){return this.separatingPolygons}set SeparatingPolygons(t){this.separatingPolygons=t}get Diagonal(){return this.diagonal}set Diagonal(t){this.diagonal=t}get Start(){return this.start}set Start(t){this.start=t}get End(){return this.end}set End(t){this.end=t}toString(){return Se.Qf.Format("{0},{1}",this.Start,this.End)}}class wo{get PointOnTangentAndInsertedDiagonal(){return this.pointOnTheRay}set PointOnTangentAndInsertedDiagonal(t){this.pointOnTheRay=t}Compare(t,e){if(t.Start.equal(e.Start))return 0;switch(d.getTriangleOrientation(this.PointOnTangentAndInsertedDiagonal,e.Start,e.End)){case k.Counterclockwise:return-1;default:return 1}}static BelongsToTheDiagonal(t,e,i){return d.closeDistEps(t,d.ClosestPointAtLineSegment(t,e,i))}static IntersectDiagonalWithRay(t,e,i){const s=e.sub(t),n=i.Start,o=i.End,a=O.solve(o.x-n.x,s.x*-1,t.x-n.x,o.y-n.y,s.y*-1,t.y-n.y);return t.add(s.mul(a.y))}}class un{constructor(t){this.pivot=t}IComparer(t,e){if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;const i=t.Start.point.sub(this.pivot),s=e.Start.point.sub(this.pivot);return un.CompareVectorsByAngleToXAxis(i,s)}static CompareVectorsByAngleToXAxis(t,e){return t.y>=0?e.y<0?-1:un.CompareVectorsPointingToTheSameYHalfPlane(t,e):e.y>=0?1:un.CompareVectorsPointingToTheSameYHalfPlane(t,e)}static CompareVectorsPointingToTheSameYHalfPlane(t,e){const i=t.x*e.y-t.y*e.x;if(i>C.tolerance)return-1;if(i<-C.tolerance)return 1;if(t.x>=0){if(e.x<0)return-1}else if(e.x>=0)return 1;let s=Math.abs(t.x)-Math.abs(e.x);return s<0?-1:s>0?1:(s=Math.abs(t.y)-Math.abs(e.y),s<0?-1:s>0?1:0)}}class Hi extends zt{constructor(t,e,i){super(null),this.polygons=[],this.activeDiagonalComparer=new wo,this.polygons=t,this.visibilityGraph=i,this.addedPolygons=e}run(){this.useLeftPTangents=!0,this.CalculateAndAddEdges(),this.useLeftPTangents=!1,this.CalculateAndAddEdges()}CalculateAndAddEdges(){for(const t of this.addedPolygons)this.CalculateVisibleTangentsFromPolygon(t);this.ProgressStep()}CalculateVisibleTangentsFromPolygon(t){this.currentPolygon=t,this.AllocateDataStructures(),this.OrganizeTangents(),this.InitActiveDiagonals(),this.Sweep()}AllocateDataStructures(){this.tangents=new Array,this.diagonals=new Array,this.activeDiagonalTree=new Qe(this.activeDiagonalComparer.Compare.bind(this.activeDiagonalComparer))}Sweep(){if(!(this.tangents.length<2))for(let t=1;t<this.tangents.length;t++){const e=this.tangents[t];e.Diagonal!=null?(e.Diagonal.RbNode===this.activeDiagonalTree.treeMinimum()&&this.AddVisibleEdge(e),e.IsHigh&&this.RemoveDiagonalFromActiveNodes(e.Diagonal)):e.IsLow&&(this.activeDiagonalComparer.PointOnTangentAndInsertedDiagonal=e.End.point,this.InsertActiveDiagonal(new bo(e,e.Comp)),e.Diagonal.RbNode===this.activeDiagonalTree.treeMinimum()&&this.AddVisibleEdge(e))}}AddVisibleEdge(t){se.AddEdgeVV(xr(this.visibilityGraph,t.start),xr(this.visibilityGraph,t.End))}InitActiveDiagonals(){if(this.tangents.length===0)return;const t=this.tangents[0],e=t.start.point,i=t.End.point;for(const s of this.diagonals)Hi.RayIntersectDiagonal(e,i,s)&&(this.activeDiagonalComparer.PointOnTangentAndInsertedDiagonal=wo.IntersectDiagonalWithRay(e,i,s),this.InsertActiveDiagonal(s));if(t.Diagonal.RbNode===this.activeDiagonalTree.treeMinimum()&&this.AddVisibleEdge(t),t.IsLow===!1){const s=t.Diagonal;this.RemoveDiagonalFromActiveNodes(s)}}RemoveDiagonalFromActiveNodes(t){const e=this.activeDiagonalTree.deleteSubTree(t.RbNode);e!=null&&e.item!=null&&(e.item.RbNode=e),t.LeftTangent.Diagonal=null,t.RightTangent.Diagonal=null}InsertActiveDiagonal(t){t.RbNode=this.activeDiagonalTree.insert(t),Hi.MarkDiagonalAsActiveInTangents(t)}static MarkDiagonalAsActiveInTangents(t){t.LeftTangent.Diagonal=t,t.RightTangent.Diagonal=t}static RayIntersectDiagonal(t,e,i){const s=i.Start,n=i.End;return d.getTriangleOrientation(t,s,n)===k.Counterclockwise&&d.getTriangleOrientation(t,e,s)!==k.Counterclockwise&&d.getTriangleOrientation(t,e,n)!==k.Clockwise}static TangentComparison(t,e){return un.CompareVectorsByAngleToXAxis(t.End.point.sub(t.start.point),e.End.point.sub(e.start.point))}*AllObstacles(){for(const t of this.addedPolygons)yield t;if(this.polygons)for(const t of this.polygons)yield t}OrganizeTangents(){for(const t of this.AllObstacles())t!==this.currentPolygon&&this.ProcessPolygonQ(t);this.tangents.sort(Hi.TangentComparison)}ProcessPolygonQ(t){const e=new Hn(this.currentPolygon,t);this.useLeftPTangents?e.CalculateLeftTangents():e.CalculateRightTangents();let i=this.useLeftPTangents?e.leftPLeftQ:e.rightPLeftQ;const s=new Ao(this.currentPolygon.pp(i[0]),t.pp(i[1]));s.IsLow=!0,s.SeparatingPolygons=!this.useLeftPTangents,i=this.useLeftPTangents?e.leftPRightQ:e.rightPRightQ;const n=new Ao(this.currentPolygon.pp(i[0]),t.pp(i[1]));n.IsLow=!1,n.SeparatingPolygons=this.useLeftPTangents,s.Comp=n,n.Comp=s,this.tangents.push(s),this.tangents.push(n),this.diagonals.push(new bo(s,n))}}function xr(l,t){return l.FindVertex(t.point)}class Or{get Pivot(){return this.pivot}set Pivot(t){this.pivot=t}get IntersectionOfTheRayAndInsertedEdge(){return this.pointOnTheRay}set IntersectionOfTheRayAndInsertedEdge(t){this.pointOnTheRay=t}Compare(t,e){switch(d.getTriangleOrientation(this.IntersectionOfTheRayAndInsertedEdge,e.point,e.nextOnPolyline.point)){case k.Counterclockwise:return-1;default:return 1}}IntersectionPointBelongsToTheInsertedEdge(t){const e=t.point.sub(this.IntersectionOfTheRayAndInsertedEdge),i=t.nextOnPolyline.point.sub(this.IntersectionOfTheRayAndInsertedEdge);return Math.abs(e.x*i.y-i.x*e.y)<C.distanceEpsilon}IntersectEdgeWithRayPPP(t,e,i){const s=O.solve(e.x-t.x,-i.x,this.Pivot.x-t.x,e.y-t.y,-i.y,this.Pivot.y-t.y);if(!(-C.tolerance<=s.x&&s.x<=1+C.tolerance))throw new Error;if(!s)throw new Error;return this.Pivot.add(i.mul(s.y))}IntersectEdgeWithRay(t,e){return this.IntersectEdgeWithRayPPP(t.point,t.nextOnPolyline.point,e)}static constructorPP(t,e){const i=new Or;return i.pivot=t,i.pointOnTheRay=e,i}}class cn{constructor(t,e){this.start=t,this.end=e}get Start(){return this.start}set Start(t){this.start=t}get End(){return this.end}set End(t){this.end=t}*Sides(){let t=this.start;for(;t!==this.end;){const e=t;yield e,t=e.nextOnPolyline}}MoveStartClockwise(){return this.Start!==this.End?(this.Start=this.Start.nextOnPolyline,!0):!1}toString(){return Se.Qf.Format("Stem({0},{1})",this.Start,this.End)}}class zi{constructor(t,e,i,s){this.sideNodes=new Map,this.visibleBoundaries=new Map,this.sortedListOfPolypoints=new Array,this.holes=Array.from(t),this.visibilityGraph=e,this.q=i,this.qPolylinePoint=qt.mkFromPoint(this.q),this.QVertex=this.visibilityGraph.AddVertexP(this.qPolylinePoint.point),this.visibilityKind=s;const n=new un(this.q);this.heapForSorting=new Cr(n.IComparer.bind(n))}get QVertex(){return this.qV}set QVertex(t){this.qV=t}static CalculatePointVisibilityGraph(t,e,i,s){const n=e.FindVertex(i);if(n!=null)return n;const o=new zi(t,e,i,s);return o.FillGraph(),o.QVertex}FillGraph(){this.ComputeHoleBoundariesPossiblyVisibleFromQ(),this.visibleBoundaries.size>0&&(this.SortSAndInitActiveSides(),this.Sweep())}SortSAndInitActiveSides(){this.InitHeapAndInsertActiveSides();for(let t=this.heapForSorting.GetMinimum();this.sortedListOfPolypoints.push(t.Start),t.MoveStartClockwise()?this.heapForSorting.ChangeMinimum(t):this.heapForSorting.Dequeue(),this.heapForSorting.Count!==0;t=this.heapForSorting.GetMinimum());}InitHeapAndInsertActiveSides(){for(const t of this.GetInitialVisibleBoundaryStemsAndInsertActiveSides())this.heapForSorting.Enqueue(t)}*GetInitialVisibleBoundaryStemsAndInsertActiveSides(){for(const[t,e]of this.visibleBoundaries){let i=!1;for(const s of e.Sides()){const n=s;if(n.point.y<this.q.y){if(s.nextOnPolyline.point.y>=this.q.y){const o=d.getTriangleOrientation(this.q,n.point,s.nextOnPolyline.point);if(o===k.Counterclockwise||o===k.Collinear){i=!0,yield new cn(e.Start,s),yield new cn(s.nextOnPolyline,e.End),this.RegisterActiveSide(s);break}}}else{if(n.point.y>this.q.y)break;if(s.point.x>=this.q.x){i=!0,yield new cn(s,e.End),s!==e.Start&&(yield new cn(e.Start,t.prev(n))),this.RegisterActiveSide(s);break}}}i||(yield e)}}RegisterActiveSide(t){this.activeEdgeComparer.IntersectionOfTheRayAndInsertedEdge=this.activeEdgeComparer.IntersectEdgeWithRay(t,new d(1,0)),this.sideNodes.set(t,this.activeSidesTree.insert(t))}Sweep(){for(const t of this.sortedListOfPolypoints)this.SweepPolylinePoint(t)}SweepPolylinePoint(t){const e=zi.GetIncomingSide(t),i=this.GetOutgoingSide(t);this.activeEdgeComparer.IntersectionOfTheRayAndInsertedEdge=t.point;let s;if(s=this.sideNodes.get(e)){if(s===this.activeSidesTree.treeMinimum()&&this.AddEdge(t),i!=null)s.item=i,this.sideNodes.set(i,s);else{const n=this.activeSidesTree.deleteSubTree(s);n!=null&&n.item!=null&&this.sideNodes.set(n.item,n)}this.sideNodes.delete(e)}else if(i!=null){let n;(n=this.sideNodes.get(i))||(n=this.activeSidesTree.insert(i),this.sideNodes.set(i,n),n===this.activeSidesTree.treeMinimum()&&this.AddEdge(t))}else throw new Error}AddEdge(t){(this.visibilityKind===Wi.Regular||this.visibilityKind===Wi.Tangent&&zi.LineTouchesPolygon(this.QVertex.point,t))&&this.visibilityGraph.AddEdgeF(this.QVertex.point,t.point,(e,i)=>new wi(e,i))}static LineTouchesPolygon(t,e){const i=e.polyline.prev(e).point,s=e.polyline.next(e).point,n=e.point;return d.signedDoubledTriangleArea(t,n,i)*d.signedDoubledTriangleArea(t,n,s)>=0}GetOutgoingSide(t){const e=this.visibleBoundaries.get(t.polyline);return t===e.End?null:t}static GetIncomingSide(t){return t.prevOnPolyline}ComputeHoleBoundariesPossiblyVisibleFromQ(){this.InitActiveEdgesAndActiveEdgesComparer();for(const t of this.holes)this.ComputeVisiblePartOfTheHole(t)}InitActiveEdgesAndActiveEdgesComparer(){this.activeEdgeComparer=new Or,this.activeEdgeComparer.pivot=this.q,this.activeSidesTree=new Qe(this.activeEdgeComparer.Compare.bind(this.activeEdgeComparer))}ComputeVisiblePartOfTheHole(t){let e,i=!0;for(e=t.startPoint;!this.HoleSideIsVisibleFromQ(t,e);e=t.next(e))i=!1;let s=t.next(e);if(i)for(;this.HoleSideIsVisibleFromQ(t,t.prev(e));)e=t.prev(e);for(;this.HoleSideIsVisibleFromQ(t,s);s=t.next(s));this.visibleBoundaries.set(t,new cn(e,s))}HoleSideIsVisibleFromQ(t,e){return d.signedDoubledTriangleArea(this.q,e.point,t.next(e).point)>=-C.squareOfDistanceEpsilon}}class Pt extends zt{constructor(){super(...arguments),this.IgnoreTightPadding=!0,this.activeRectangle=Z.mkEmpty(),this.activePolygons=new Array,this.alreadyAddedOrExcludedPolylines=new Set,this.UseEdgeLengthMultiplier=!1,this.UseInnerPolylingShortcutting=!0,this.UsePolylineEndShortcutting=!0,this.AllowedShootingStraightLines=!0,this.LookForRoundedVertices=!1}rerouteEdge(t){const e=t.smoothedPolyline?at.mkFromPoints(t.smoothedPolyline):at.mkFromPoints(t.getSmoothPolyPoints());this.pathOptimizer.run(e),t.curve=this.pathOptimizer.poly.toCurve()}static constructorANNN(t,e,i,s){return Pt.constructorANNNB(t,e,i,s,!1)}get Obstacles(){return this.obstacles_}set Obstacles(t){this.obstacles_=t}get EnteringAngleBound(){return this.enteringAngleBound_}set EnteringAngleBound(t){this.enteringAngleBound_=t}get SourceTightPolyline(){return this._sourceTightPolyline}set SourceTightPolyline(t){this._sourceTightPolyline=t}get TargetTightPolyline(){return this.targetTightPolyline}set TargetTightPolyline(t){this.targetTightPolyline=t}get TargetLoosePolyline(){return this.targetLoosePolyline}set TargetLoosePolyline(t){this.targetLoosePolyline=t}get VisibilityGraph(){return this.visibilityGraph}set VisibilityGraph(t){this.visibilityGraph=t}get SourcePort(){return this.sourcePort}set SourcePort(t){if(this.sourcePort=t,this.sourcePort!=null)if(this.SourceTightPolyline=Pt.GetFirstHitPolyline(this.sourcePort.Location,this.ObstacleCalculator.RootOfTightHierarchy),this.sourcePort instanceof ii)this.alreadyAddedOrExcludedPolylines.add(this.SourceLoosePolyline),this.StartPointOfEdgeRouting=this.SourcePort.Location;else{const e=this.sourcePort;this.StartPointOfEdgeRouting=this.TakeBoundaryPortOutsideOfItsLoosePolyline(e.Curve,e.Parameter,this.SourceLoosePolyline)}}get TargetPort(){return this.targetPort}set TargetPort(t){this.targetPort=t}get LoosePadding(){return this.loosePadding}set LoosePadding(t){this.loosePadding=t,this.ObstacleCalculator!=null&&(this.ObstacleCalculator.LoosePadding=t)}get OffsetForPolylineRelaxing(){return this.TightPadding*.75}get StartPointOfEdgeRouting(){return this.startPointOfRouting_}set StartPointOfEdgeRouting(t){this.startPointOfRouting_=t}ExtendVisibilityGraphToLocation(t){this.VisibilityGraph==null&&(this.VisibilityGraph=new se);let e=null;if(!this.activeRectangle.contains(t)){this.activeRectangle.isEmpty?this.activeRectangle=Z.mkPP(this.SourcePort.Location,t):this.activeRectangle.add(t),e=this.GetAddedPolygonesAndMaybeExtendActiveRectangle();for(const i of e)this.VisibilityGraph.AddHole(i.Polyline)}e==null||e.length===0?(this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.CalculateEdgeTargetVisibilityGraph(t)):(this.RemovePointVisibilityGraphs(),new Hi(e,this.activePolygons,this.VisibilityGraph).run(),Ki(this.activePolygons,e),this.CalculateEdgeTargetVisibilityGraph(t),this.CalculateSourcePortVisibilityGraph())}RemovePointVisibilityGraphs(){this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.sourceVV!=null&&this.VisibilityGraph.RemoveVertex(this.sourceVV)}CalculateEdgeTargetVisibilityGraph(t){this.targetVV=zi.CalculatePointVisibilityGraph(Array.from(this.GetActivePolylines()),this.VisibilityGraph,t,Wi.Tangent)}CalculateSourcePortVisibilityGraph(){this.sourceVV=zi.CalculatePointVisibilityGraph(Array.from(this.GetActivePolylines()),this.VisibilityGraph,this.StartPointOfEdgeRouting,Wi.Tangent)}TakeBoundaryPortOutsideOfItsLoosePolyline(t,e,i){const s=t.value(e);let n=t.leftDerivative(e).normalize().add(t.rightDerivative(e).normalize()).normalize();d.getTriangleOrientation(Pt.PointInsideOfConvexCurve(t),s,s.add(n))==k.Counterclockwise&&(n=n.mul(-1)),n=n.rotate(Math.PI/2);const o=i.boundingBox.diagonal;let a=D.mkPP(s,s.add(n.mul(o)));const h=w.intersectionOne(a,i,!1).x;let u=n.mul(h.sub(s).length/2);for(;;){a=D.mkPP(s,h.add(u));let c=!1;for(const m of Pt.IntersectionsOfLineAndRectangleNodeOverPolylineLR(a,this.ObstacleCalculator.RootOfLooseHierarchy))if(m.seg1!==i){u=u.div(1.5),c=!0;break}if(!c)break}return a.end}static PointInsideOfConvexCurve(t){return t.value(0).add(t.value(1.5)).div(2)}*GetActivePolylines(){for(const t of this.activePolygons)yield t.Polyline}GetAddedPolygonesAndMaybeExtendActiveRectangle(){const t=this.activeRectangle,e=new Array;let i;do{i=!1;for(const s of this.ObstacleCalculator.RootOfLooseHierarchy.GetNodeItemsIntersectingRectangle(this.activeRectangle))this.alreadyAddedOrExcludedPolylines.has(s)||(t.addRec(s.boundingBox),e.push(new Te(s)),this.alreadyAddedOrExcludedPolylines.add(s),i=!0);i&&(this.activeRectangle=t)}while(i);return e}PolylineSegmentIntersectsTightHierarchy(t,e){return this.PolylineIntersectsPolyRectangleNodeOfTightHierarchyPPR(t,e,this.ObstacleCalculator.RootOfTightHierarchy)}PolylineIntersectsPolyRectangleNodeOfTightHierarchyPPR(t,e,i){return this.PolylineIntersectsPolyRectangleNodeOfTightHierarchy(D.mkPP(t,e),i)}PolylineIntersectsPolyRectangleNodeOfTightHierarchy(t,e){if(!t.boundingBox.intersects(e.irect))return!1;if(e.UserData!=null){for(const i of w.getAllIntersections(t,e.UserData,!1))if(i.seg1!==this.SourceTightPolyline&&i.seg1!==this.TargetTightPolyline||(i.seg1===this.SourceTightPolyline&&this.SourcePort)instanceof R||(i.seg1===this.TargetTightPolyline&&this.TargetPort)instanceof R)return!0;return!1}return this.PolylineIntersectsPolyRectangleNodeOfTightHierarchy(t,e.Left)||this.PolylineIntersectsPolyRectangleNodeOfTightHierarchy(t,e.Right)}static IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,e){const i=new Array;return Pt.IntersectionsOfLineAndRectangleNodeOverPolyline(t,e,i),i}static IntersectionsOfLineAndRectangleNodeOverPolyline(t,e,i){if(e!=null&&t.boundingBox.intersects(e.irect)){if(e.UserData!=null){Ki(i,w.getAllIntersections(t,e.UserData,!0));return}Pt.IntersectionsOfLineAndRectangleNodeOverPolyline(t,e.Left,i),Pt.IntersectionsOfLineAndRectangleNodeOverPolyline(t,e.Right,i)}}LineCanBeAcceptedForRouting(t){const e=this.SourcePort instanceof ii,i=this.TargetPort instanceof ii;if(!e&&!this.targetIsInsideOfSourceTightPolyline&&!this.InsideOfTheAllowedConeOfBoundaryPort(t.end,this.SourcePort)||!i&&this.TargetPort!=null&&!this.sourceIsInsideOfTargetTightPolyline&&!this.InsideOfTheAllowedConeOfBoundaryPort(t.start,this.TargetPort))return!1;const s=Pt.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy);for(const n of s)if(n.seg1!==this.SourceTightPolyline&&n.seg1!==this.targetTightPolyline)return!1;return!0}InsideOfTheAllowedConeOfBoundaryPort(t,e){const i=e.Curve,s=mt.CurveIsClockwise(i,Pt.PointInsideOfConvexCurve(i)),n=e.Location,o=this.GetPointOnTheRightBoundaryPortConeSide(n,i,s,e.Parameter),a=this.GetPointOnTheLeftBoundaryPortConeSide(n,i,s,e.Parameter);return d.getTriangleOrientation(n,o,t)!==k.Clockwise&&d.getTriangleOrientation(n,t,a)!==k.Clockwise}GetPointOnTheRightBoundaryPortConeSide(t,e,i,s){const n=i?e.rightDerivative(s):e.leftDerivative(s).neg();return t.add(n.rotate(this.EnteringAngleBound))}GetPointOnTheLeftBoundaryPortConeSide(t,e,i,s){const n=i?e.leftDerivative(s).neg():e.rightDerivative(s);return t.add(n.rotate(-this.EnteringAngleBound))}SmoothenCorners(t){let e=t.headSite,i={b:null,c:null};for(;i=w.findCorner(e);)e=this.SmoothOneCorner(e,i.c,i.b)}SmoothOneCorner(t,e,i){let o=.5,a,h,u;t.prev==null?(u=2,h=1):e.next==null?(u=1,h=2):u=h=1;do a=w.createBezierSeg(o*u,o*h,t,i,e),i.previouisBezierCoefficient=o*u,i.nextBezierCoefficient=o*h,o/=1.5;while(c()>this.loosePadding&&o>.01);return o*=1.5,o<.5&&o>.01&&(o=.5*(o+o*1.5),a=w.createBezierSeg(o*u,o*h,t,i,e),c()>this.loosePadding&&(i.previouisBezierCoefficient=o*u,i.nextBezierCoefficient=o*h)),i;function c(){const m=a.closestParameter(i.point);return i.point.sub(a.value(m)).length}}TryToRemoveInflectionsAndCollinearSegments(t){let e=!0;const i={s:null};for(;e;)for(e=!1,i.s=t.headSite;i.s!=null&&i.s.next!=null;i.s=i.s.next)i.s.turn*i.s.next.turn<0&&(e=this.TryToRemoveInflectionEdge(i)||e)}TryToRemoveInflectionEdge(t){if(!this.ObstacleCalculator.ObstaclesIntersectLine(t.s.prev.point,t.s.next.point)){const e=t.s.prev,i=t.s.next;return e.next=i,i.prev=e,t.s=e,!0}if(!this.ObstacleCalculator.ObstaclesIntersectLine(t.s.prev.point,t.s.next.next.point)){const e=t.s.prev,i=t.s.next.next;return e.next=i,i.prev=e,t.s=e,!0}if(!this.ObstacleCalculator.ObstaclesIntersectLine(t.s.point,t.s.next.next.point)){const e=t.s.next.next;return t.s.next=e,e.prev=t.s,!0}return!1}GetShortestPolyline(t,e){this.CleanTheGraphForShortestPath();const s=new zn(this.visibilityGraph,t,e).GetPath(this.UseEdgeLengthMultiplier);if(s==null)return null;let n=at.mkFromPoints(Array.from(s).map(o=>o.point)).RemoveCollinearVertices();return this.pathOptimizer&&(this.pathOptimizer.run(n),n=this.pathOptimizer.poly),n}CleanTheGraphForShortestPath(){this.visibilityGraph.ClearPrevEdgesTable()}get OverlapsDetected(){return this.ObstacleCalculator.OverlapsDetected}get TightHierarchy(){return this.ObstacleCalculator.RootOfTightHierarchy}set TightHierarchy(t){this.ObstacleCalculator.RootOfTightHierarchy=t}get LooseHierarchy(){return this.ObstacleCalculator.RootOfLooseHierarchy}set LooseHierarchy(t){this.ObstacleCalculator.RootOfLooseHierarchy=t}CalculateObstacles(){this.ObstacleCalculator=new mt(this.Obstacles,this.TightPadding,this.LoosePadding,this.IgnoreTightPadding),this.ObstacleCalculator.Calculate()}static constructorANNNB(t,e,i,s,n){const o=new Pt(null);return o.IgnoreTightPadding=n,o.EnteringAngleBound=80*(Math.PI/180),o.TightPadding=e,o.LoosePadding=i,s>0?(Ht.assert(s>Math.PI/180),Ht.assert(s<=90*(Math.PI/180)),o.UseSpanner=!0,o.ExpectedProgressSteps=Mi.GetTotalSteps(s)):o.ExpectedProgressSteps=t.length,o.ConeSpannerAngle=s,o.Obstacles=t,o.CalculateObstacles(),o}RouteEdgeToLocation(t){this.TargetPort=new ii(null,t),this.TargetTightPolyline=null,this.TargetLoosePolyline=null;const e=new Ne(null);let i=D.mkPP(this.SourcePort.Location,t);if(this.LineCanBeAcceptedForRouting(i)){this._polyline=new at,this._polyline.addPoint(i.start),this._polyline.addPoint(i.end);const s=G.mkFromPoints(this._polyline);return e.curve=s.createCurve(),e}return this.SourcePort instanceof R&&(i=D.mkPP(this.StartPointOfEdgeRouting,t),Pt.IntersectionsOfLineAndRectangleNodeOverPolylineLR(i,this.ObstacleCalculator.RootOfTightHierarchy).length==0)?(this._polyline=new at,this._polyline.addPoint(this.SourcePort.Location),this._polyline.addPoint(i.start),this._polyline.addPoint(i.end),e.curve=G.mkFromPoints(this._polyline).createCurve(),e):(this.ExtendVisibilityGraphToLocation(t),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV),this.SourcePort instanceof R&&this._polyline.PrependPoint(this.SourcePort.Location),e.curve=G.mkFromPoints(this._polyline).createCurve(),e)}RouteEdgeToPort(t,e,i,s){return this.ObstacleCalculator.IsEmpty()?this.sourcePort!=null&&this.targetPort!=null?(s.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(this.sourcePort.Location,this.targetPort.Location),D.mkPP(this.sourcePort.Location,this.targetPort.Location)):null:(this.TargetPort=t,this.TargetTightPolyline=Pt.GetFirstHitPolyline(t.Location,this.ObstacleCalculator.RootOfTightHierarchy),t instanceof R?this.RouteEdgeToBoundaryPort(e,i,s):this.RouteEdgeToFloatingPortOfNode(e,i,s))}SmoothedPolylineFromTwoPoints(t,e){return this._polyline=new at,this._polyline.addPoint(t),this._polyline.addPoint(e),G.mkFromPoints(this._polyline)}RouteEdgeToFloatingPortOfNode(t,e,i){return this.sourcePort instanceof ii?this.RouteFromFloatingPortToFloatingPort(t,e,i):this.RouteFromBoundaryPortToFloatingPort(t,e,i)}RouteFromBoundaryPortToFloatingPort(t,e,i){const s=this.SourcePort.Location,n=this.targetPort.Location;let o=D.mkPP(s,n);if(this.LineCanBeAcceptedForRouting(o))return i.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(o.start,o.end),o;if(!this.targetIsInsideOfSourceTightPolyline){const h=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.SourcePort.Curve,this.SourcePort.Parameter,this.SourceLoosePolyline);if(o=D.mkPP(h,n),this.LineAvoidsTightHierarchyLP(o,t))return i.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(o.start,o.end),o}this.ExtendVisibilityGraphToLocationOfTargetFloatingPort(t),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV);const a=this.SourceTightPolyline;return this.targetIsInsideOfSourceTightPolyline||(this.SourceTightPolyline=null),this.SourceTightPolyline=a,this._polyline.PrependPoint(s),this.SmoothCornersAndReturnCurve(e,i)}SmoothCornersAndReturnCurve(t,e){return e.smoothedPolyline=G.mkFromPoints(this._polyline),t&&this.SmoothenCorners(e.smoothedPolyline),e.smoothedPolyline.createCurve()}RouteFromFloatingPortToFloatingPort(t,e,i){return this.ExtendVisibilityGraphToLocationOfTargetFloatingPort(t),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV),this._polyline==null?null:(i.smoothedPolyline=G.mkFromPoints(this._polyline),this.SmoothCornersAndReturnCurve(e,i))}TryShortcutPolyPoint(t){return this.LineAvoidsTightHierarchyLPP(D.mkPP(t.point,t.next.next.point),this.SourceTightPolyline,this.targetTightPolyline)?(t.next=t.next.next,t.next.prev=t,!0):!1}ExtendVisibilityGraphToLocationOfTargetFloatingPort(t){this.VisibilityGraph==null&&(this.VisibilityGraph=new se);let e=null;const i=this.targetPort.Location;if(!this.activeRectangle.contains(i)){this.activeRectangle.isEmpty?this.activeRectangle=Z.mkPP(this.SourcePort.Location,i):this.activeRectangle.add(i),e=this.GetAddedPolygonesAndMaybeExtendActiveRectangle();for(const s of e)this.VisibilityGraph.AddHole(s.Polyline)}e==null?(this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.CalculateEdgeTargetVisibilityGraphForFloatingPort(i,t),this.sourceVV==null&&this.CalculateSourcePortVisibilityGraph()):(this.RemovePointVisibilityGraphs(),new Hi(e,this.activePolygons,this.VisibilityGraph).run(),Ki(this.activePolygons,e),this.CalculateEdgeTargetVisibilityGraphForFloatingPort(i,t),this.CalculateSourcePortVisibilityGraph())}CalculateEdgeTargetVisibilityGraphForFloatingPort(t,e){this.UseSpanner?this.targetVV=this.AddTransientVisibilityEdgesForPort(t,e):this.targetVV=zi.CalculatePointVisibilityGraph(this.GetActivePolylinesWithException(e),this.VisibilityGraph,t,Wi.Tangent)}AddTransientVisibilityEdgesForPort(t,e){let i=this.GetVertex(t);if(i!=null)return i;if(i=this.visibilityGraph.AddVertexP(t),e!=null)for(const s of e)this.visibilityGraph.AddEdgeF(t,s,(n,o)=>new wi(n,o));else i=zi.CalculatePointVisibilityGraph(this.GetActivePolylines(),this.VisibilityGraph,t,Wi.Tangent);return i}GetVertex(t){let e=this.visibilityGraph.FindVertex(t);return e==null&&this.LookForRoundedVertices&&(e=this.visibilityGraph.FindVertex(d.RoundPoint(t))),e}*GetActivePolylinesWithException(t){for(const e of this.activePolygons)e.Polyline!==t&&(yield e.Polyline)}RouteEdgeToBoundaryPort(t,e,i){return this.TargetLoosePolyline=t,this.sourcePort instanceof ii?this.RouteFromFloatingPortToBoundaryPort(e,i):this.RouteFromBoundaryPortToBoundaryPort(e,i)}RouteFromBoundaryPortToBoundaryPort(t,e){const i=this.SourcePort.Location;let s;const n=this.targetPort.Location;let o=D.mkPP(i,n);if(this.LineCanBeAcceptedForRouting(o))this._polyline=new at,this._polyline.addPoint(o.start),this._polyline.addPoint(o.end),e.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(o.start,o.end),s=G.mkFromPoints(this._polyline).createCurve();else{const a=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.targetPort.Curve,this.targetPort.Parameter,this.TargetLoosePolyline);if(o=D.mkPP(i,a),this.InsideOfTheAllowedConeOfBoundaryPort(a,this.SourcePort)&&this.LineAvoidsTightHierarchyLP(o,this._sourceTightPolyline))this._polyline=new at,this._polyline.addPoint(o.start),this._polyline.addPoint(o.end),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e);else if(o=D.mkPP(this.StartPointOfEdgeRouting,n),this.InsideOfTheAllowedConeOfBoundaryPort(this.StartPointOfEdgeRouting,this.TargetPort)&&this.LineAvoidsTightHierarchy(o))this._polyline=new at,this._polyline.addPoint(i),this._polyline.addPoint(o.start),this._polyline.addPoint(o.end),s=this.SmoothCornersAndReturnCurve(t,e);else{let h;if(h=D.IntersectPPPP(i,this.StartPointOfEdgeRouting,n,a))this._polyline=new at,this._polyline.addPoint(i),this._polyline.addPoint(h),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e);else if(d.closeDistEps(this.StartPointOfEdgeRouting,a))this._polyline=new at,this._polyline.addPoint(i),this._polyline.addPoint(a),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e);else if(this.LineAvoidsTightHierarchy(D.mkPP(this.StartPointOfEdgeRouting,a)))this._polyline=new at,this._polyline.addPoint(i),this._polyline.addPoint(this.StartPointOfEdgeRouting),this._polyline.addPoint(a),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e);else{this.ExtendVisibilityGraphToTargetBoundaryPort(a),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV);const u={tmpTargetTight:null},c=this.HideSourceTargetTightsIfNeeded(u);this.RecoverSourceTargetTights(c,u.tmpTargetTight),this._polyline.PrependPoint(i),this._polyline.addPoint(n),s=this.SmoothCornersAndReturnCurve(t,e)}}}return s}RecoverSourceTargetTights(t,e){this.SourceTightPolyline=t,this.TargetTightPolyline=e}HideSourceTargetTightsIfNeeded(t){const e=this.SourceTightPolyline;return t.tmpTargetTight=this.TargetTightPolyline,this.TargetTightPolyline=null,this.SourceTightPolyline=null,e}LineAvoidsTightHierarchy(t){return Pt.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy).length===0}RouteFromFloatingPortToBoundaryPort(t,e){const i=this.targetPort.Location;let s;if(this.InsideOfTheAllowedConeOfBoundaryPort(this.sourcePort.Location,this.targetPort)&&(s=D.mkPP(this.SourcePort.Location,i),this.LineCanBeAcceptedForRouting(s)))return e.smoothedPolyline=this.SmoothedPolylineFromTwoPoints(s.start,s.end),s;const n=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.TargetPort.Curve,this.TargetPort.Parameter,this.TargetLoosePolyline);if(s=D.mkPP(this.SourcePort.Location,n),this.LineAvoidsTightHierarchyLP(s,this._sourceTightPolyline))return this._polyline=at.mkFromPoints([s.start,s.end,i]),e.smoothedPolyline=G.mkFromPoints(this._polyline),e.smoothedPolyline.createCurve();this.ExtendVisibilityGraphToTargetBoundaryPort(n),this._polyline=this.GetShortestPolyline(this.sourceVV,this.targetVV),this._polyline.addPoint(i);const o={smoothedPolyline:null};return this.SmoothCornersAndReturnCurve(t,o)}LineAvoidsTightHierarchyLP(t,e){let i=!0;for(const s of Pt.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy))if(s.seg1!==e){i=!1;break}return i}LineAvoidsTightHierarchyLPP(t,e,i){let s=!0;for(const n of Pt.IntersectionsOfLineAndRectangleNodeOverPolylineLR(t,this.ObstacleCalculator.RootOfTightHierarchy))if(!(n.seg1===e||n.seg1===i)){s=!1;break}return s}LineAvoidsTightHierarchyPPPP(t,e,i,s){return this.LineAvoidsTightHierarchyLPP(D.mkPP(t,e),i,s)}ExtendVisibilityGraphToTargetBoundaryPort(t){let e=null;if(this.VisibilityGraph==null&&(this.VisibilityGraph=new se),!this.activeRectangle.contains(t)||!this.activeRectangle.containsRect(this.TargetLoosePolyline.boundingBox)){this.activeRectangle.isEmpty?(this.activeRectangle=this.TargetLoosePolyline.boundingBox.clone(),this.activeRectangle.add(this.SourcePort.Location),this.activeRectangle.add(this.StartPointOfEdgeRouting),this.activeRectangle.add(t)):(this.activeRectangle.add(t),this.activeRectangle.addRec(this.TargetLoosePolyline.boundingBox)),e=this.GetAddedPolygonesAndMaybeExtendActiveRectangle();for(const i of e)this.VisibilityGraph.AddHole(i.Polyline)}e==null?(this.targetVV!=null&&this.VisibilityGraph.RemoveVertex(this.targetVV),this.CalculateEdgeTargetVisibilityGraph(t)):(this.RemovePointVisibilityGraphs(),new Hi(e,this.activePolygons,this.VisibilityGraph).run(),Ki(this.activePolygons,e),this.CalculateEdgeTargetVisibilityGraph(t),this.CalculateSourcePortVisibilityGraph())}GetHitLoosePolyline(t){return this.ObstacleCalculator.IsEmpty()||this.ObstacleCalculator.RootOfLooseHierarchy==null?null:Pt.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfLooseHierarchy)}static GetFirstHitPolyline(t,e){const i=Pt.GetFirstHitRectangleNode(t,e);return i?i.UserData:null}static GetFirstHitRectangleNode(t,e){return e==null?null:e.FirstHitNodeWithPredicate(t,(i,s)=>w.PointRelativeToCurveLocation(i,s)!==ft.Outside?$t.Stop:$t.Continue)}Clean(){this.TargetPort=null,this.SourcePort=null,this.SourceTightPolyline=null,this.SourceLoosePolyline=null,this.TargetLoosePolyline=null,this.targetTightPolyline=null,this.VisibilityGraph=null,this.targetVV=null,this.sourceVV=null,this.activePolygons=[],this.alreadyAddedOrExcludedPolylines.clear(),this.activeRectangle.setToEmpty()}SetSourcePortAndSourceLoosePolyline(t,e){this.SourceLoosePolyline=e,this.sourcePort=t,this.sourcePort!=null&&(this.SourceTightPolyline=Pt.GetFirstHitPolyline(this.sourcePort.Location,this.ObstacleCalculator.RootOfTightHierarchy),this.sourcePort instanceof ii?(this.alreadyAddedOrExcludedPolylines.add(this.SourceLoosePolyline),this.StartPointOfEdgeRouting=this.SourcePort.Location):this.StartPointOfEdgeRouting=this.TakeBoundaryPortOutsideOfItsLoosePolyline(this.SourcePort.Curve,this.sourcePort.Parameter,this.SourceLoosePolyline))}run(){this.CalculateWholeTangentVisibilityGraph()}CalculateWholeTangentVisibilityGraph(){this.VisibilityGraph=new se,this.CalculateWholeVisibilityGraphOnExistingGraph()}CalculateWholeVisibilityGraphOnExistingGraph(){this.activePolygons=Array.from(this.AllPolygons());for(const e of this.ObstacleCalculator.LooseObstacles)this.VisibilityGraph.AddHole(e);let t;this.UseSpanner?t=new Mi(this.ObstacleCalculator.LooseObstacles,this.VisibilityGraph):t=new Hi(new Array,this.activePolygons,this.visibilityGraph),t.run()}RouteSplineFromPortToPortWhenTheWholeGraphIsReady(t,e,i,s){const n=t instanceof ii&&e instanceof R||t instanceof Kt;if(n){const a=t;t=e,e=a}this.sourcePort=t,this.targetPort=e,this.FigureOutSourceTargetPolylinesAndActiveRectangle();let o=this.GetEdgeGeomByRouting(i,s);return o==null?null:(this.targetVV=null,this.sourceVV=null,n&&(o=o.reverse()),o)}GetEdgeGeomByRouting(t,e){this.sourceIsInsideOfTargetTightPolyline=this.TargetTightPolyline==null||w.PointRelativeToCurveLocation(this.sourcePort.Location,this.TargetTightPolyline)===ft.Inside;let i;if(this.sourcePort instanceof R){const s=this.sourcePort;this.StartPointOfEdgeRouting=this.targetIsInsideOfSourceTightPolyline?s.Location:this.TakeBoundaryPortOutsideOfItsLoosePolyline(s.Curve,s.Parameter,this.SourceLoosePolyline),this.CalculateSourcePortVisibilityGraph();const n={smoothedPolyline:null};this.targetPort instanceof R?i=this.RouteFromBoundaryPortToBoundaryPort(t,n):i=this.RouteFromBoundaryPortToFloatingPort(this.targetLoosePolyline,t,n)}else this.targetPort instanceof ii?(this.ExtendVisibilityGraphFromFloatingSourcePort(),i=this.RouteFromFloatingPortToFloatingPort(this.targetLoosePolyline,t,e)):i=this.RouteFromFloatingPortToAnywherePort(this.targetPort.LoosePolyline,t,e,this.targetPort);return i}RouteFromFloatingPortToAnywherePort(t,e,i,s){return s.Curve.boundingBox.contains(this.sourcePort.Location)?(this.sourceVV=this.GetVertex(this.sourcePort.Location),this._polyline=this.GetShortestPolylineToMulitpleTargets(this.sourceVV,Array.from(this.Targets(t))),this._polyline==null?null:(this.FixLastPolylinePointForAnywherePort(s),s.HookSize>0&&this.BuildHook(s),this.SmoothCornersAndReturnCurve(e,i))):(i.smoothedPolyline=null,null)}BuildHook(t){const e=t.Curve,i=vt.mkFullEllipseNNP(t.HookSize,t.HookSize,this._polyline.end),s=w.getAllIntersections(e,i,!0);d.getTriangleOrientation(s[0].x,this._polyline.end,this._polyline.endPoint.prev.point)==k.Counterclockwise&&s.reverse();const n=this._polyline.end.sub(this._polyline.endPoint.prev.point).normalize(),o=e.derivative(s[0].par0).normalize(),a=o.dot(n);if(Math.abs(a)<.2)this.ExtendPolyline(o,s[0],n,t);else{const h=e.derivative(s[1].par0).normalize();h.dot(n)<a?this.ExtendPolyline(h,s[1],n,t):this.ExtendPolyline(o,s[0],n,t)}}ExtendPolyline(t,e,i,s){let n=t.rotate(Math.PI/2);n.dot(i)<0&&(n=n.neg());const o=e.x.add(n.mul(s.HookSize));let a;(a=d.lineLineIntersection(o,o.add(t),this._polyline.end,this._polyline.end.add(i)))&&(this._polyline.addPoint(a),this._polyline.addPoint(o),this._polyline.addPoint(e.x))}FixLastPolylinePointForAnywherePort(t){for(;;){const e=this.GetLastPointInsideOfCurveOnPolyline(t.Curve);e.next.next=null,this._polyline.endPoint=e.next;let i=e.next.point.sub(e.point);i=i.normalize().mul(t.Curve.boundingBox.diagonal);const s=i.rotate(t.AdjustmentAngle*-1),n=i.rotate(t.AdjustmentAngle),o=w.intersectionOne(t.Curve,D.mkPP(e.point,e.point.add(s)),!0),a=w.intersectionOne(t.Curve,D.mkPP(e.point,e.point.add(n)),!0);if(o==null||a==null)return;const h=Pt.GetTrimmedCurveForHookingUpAnywhere(t.Curve,e,o,a),u=h.value(h.closestParameter(e.point));if(!this.LineAvoidsTightHierarchyLPP(D.mkPP(e.point,u),this.SourceTightPolyline,null)){const c=w.intersectionOne(t.Curve,D.mkPP(e.point,e.next.point),!1);if(c==null)return;this._polyline.endPoint.point=c.x;break}if(this._polyline.endPoint.point=u,e.prev==null||!this.TryShortcutPolyPoint(e.prev))break}}static GetTrimmedCurveForHookingUpAnywhere(t,e,i,s){const n=d.getTriangleOrientation(s.x,i.x,e.point)===k.Clockwise,o=i.par0,a=s.par0;let h,u,c;return n?o<a?t.trim(o,a):(u=t.trim(o,t.parEnd),h=t.trim(t.parStart,a),c=new w,c.addSegs([u,h])):a<o?t.trim(a,o):(u=t.trim(a,t.parEnd),h=t.trim(t.parStart,o),c=new w,c.addSegs([u,h]))}GetLastPointInsideOfCurveOnPolyline(t){for(let e=this._polyline.endPoint.prev;e!=null;e=e.prev)if(e.prev==null||w.PointRelativeToCurveLocation(e.point,t)===ft.Inside)return e;throw new Error}GetShortestPolylineToMulitpleTargets(t,e){this.CleanTheGraphForShortestPath();const s=new Ls(t,e,this.VisibilityGraph).GetPath();if(s==null)return null;const n=new at;for(const o of s)n.addPoint(o.point);return n.RemoveCollinearVertices()}Targets(t){return Array.from(t).map(e=>this.visibilityGraph.FindVertex(e))}ExtendVisibilityGraphFromFloatingSourcePort(){const t=this.sourcePort;this.StartPointOfEdgeRouting=t.Location,this.UseSpanner?this.sourceVV=this.AddTransientVisibilityEdgesForPort(this.sourcePort.Location,this.SourceLoosePolyline):this.sourceVV=zi.CalculatePointVisibilityGraph(Array.from(this.GetActivePolylines()).filter(e=>e!==this.SourceLoosePolyline),this.VisibilityGraph,this.StartPointOfEdgeRouting,Wi.Tangent)}FigureOutSourceTargetPolylinesAndActiveRectangle(){let t=this.sourcePort.Curve.value(this.sourcePort.Curve.parStart);this._sourceTightPolyline=Pt.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfTightHierarchy),this.SourceLoosePolyline=Pt.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfLooseHierarchy),t=this.targetPort.Curve.value(this.targetPort.Curve.parStart),this.targetTightPolyline=Pt.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfTightHierarchy),this.targetLoosePolyline=Pt.GetFirstHitPolyline(t,this.ObstacleCalculator.RootOfLooseHierarchy),this.activeRectangle=Z.mkPP(new d(Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY),new d(Number.POSITIVE_INFINITY,Number.NEGATIVE_INFINITY))}*AllPolygons(){for(const t of this.ObstacleCalculator.LooseObstacles)yield new Te(t)}GetVisibilityGraph(){return this.VisibilityGraph}AddActivePolygons(t){Ki(this.activePolygons,t)}ClearActivePolygons(){this.activePolygons=[]}}class Mt{constructor(){this.length=Mt.defaultArrowheadLength,this.width=0,this.length=Mt.defaultArrowheadLength}toJSON(){let t="{";return this.tipPosition&&(t+='"tipPosition": '+this.tipPosition.toJSON()),t+="}",t}clone(){const t=new Mt;return t.length=this.length,t.width=this.width,t.tipPosition=this.tipPosition,t}static calculateArrowheads(t){if(t.sourceArrowhead==null&&t.targetArrowhead==null)return!0;const e=Mt.findTrimStartForArrowheadAtSource(t);if(e==null)return!1;const i=Mt.findTrimEndForArrowheadAtTarget(t);if(i==null||e>i-C.intersectionEpsilon||w.closeIntersectionPoints(t.curve.value(e),t.curve.value(i)))return!1;const s=t.curve.trim(e,i);return s==null?!1:(t.sourceArrowhead!=null&&(t.sourceArrowhead.tipPosition=t.curve.start),t.targetArrowhead!=null&&(t.targetArrowhead.tipPosition=t.curve.end),t.curve=s,!0)}static getIntersectionsWithArrowheadCircle(t,e,i){const s=vt.mkFullEllipseNNP(e,e,i);return w.getAllIntersections(s,t,!0)}static findTrimEndForArrowheadAtTarget(t){const e=C.distanceEpsilon*C.distanceEpsilon;let i=t.curve.parEnd;if(t.targetArrowhead==null||t.targetArrowhead.length<=C.distanceEpsilon)return i;const s=t.curve;let n=t.targetArrowhead.length,o,a,h=10;do{if(h--,h===0)return;a=Mt.getIntersectionsWithArrowheadCircle(s,n,s.end),i=a.length!==0?Math.max(...a.map(u=>u.par1)):s.parEnd,o=t.curve.value(i),n/=2}while(o.sub(s.start).lengthSquared<e||a.length===0);return i}static findTrimStartForArrowheadAtSource(t){if(t.sourceArrowhead==null||t.sourceArrowhead.length<=C.distanceEpsilon)return t.curve.parStart;const e=C.distanceEpsilon*C.distanceEpsilon;let i=t.sourceArrowhead.length,s;const n=t.curve;let o,a=10,h;for(;--a>0;){if(o=Mt.getIntersectionsWithArrowheadCircle(n,i,n.start),o.length===0)return n.parStart;if(h=Math.min(...o.map(u=>u.par1)),s=o.filter(u=>u.par1===h)[0].x,s.sub(n.end).lengthSquared>=e)return h;i/=2}}static trimSplineAndCalculateArrowheads(t,e,i){return Mt.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,e,i)}static trimSplineAndCalculateArrowheadsII(t,e,i,s,n){if(t.curve=w.trimEdgeSplineWithNodeBoundaries(e,i,s,n),t.curve==null)return!1;if((t.sourceArrowhead==null||t.sourceArrowhead.length<C.distanceEpsilon)&&(t.targetArrowhead==null||t.targetArrowhead.length<C.distanceEpsilon))return!0;let o=!1;const a=t.sourceArrowhead!=null?t.sourceArrowhead.length:0,h=t.targetArrowhead!=null?t.targetArrowhead.length:0,u=t.curve.end.sub(t.curve.start).length;t.sourceArrowhead!=null&&(t.sourceArrowhead.length=Math.min(u,a)),t.targetArrowhead!=null&&(t.targetArrowhead.length=Math.min(u,h));let c=10;for(;(t.sourceArrowhead!=null&&t.sourceArrowhead.length>C.intersectionEpsilon||t.targetArrowhead!=null&&t.targetArrowhead.length>C.intersectionEpsilon)&&!o&&(o=Mt.calculateArrowheads(t),o||(t.sourceArrowhead!=null&&(t.sourceArrowhead.length*=.5),t.targetArrowhead!=null&&(t.targetArrowhead.length*=.5)),c--,c!==0););return o||(t.sourceArrowhead!=null&&(t.sourceArrowhead.tipPosition=s.start),t.targetArrowhead!=null&&(t.targetArrowhead.tipPosition=s.end)),t.sourceArrowhead!=null&&(t.sourceArrowhead.length=a),t.targetArrowhead!=null&&(t.targetArrowhead.length=h),o}static createBigEnoughSpline(t){const e=t.source.center;let i=t.target.center;const s=i.sub(e),n=s.length;let o;n<.001?(o=new d(1,0),i=e.add(o.rotate(Math.PI/2))):o=s.rotate(Math.PI/2);let a=1;t.sourceArrowhead!=null&&(a+=t.sourceArrowhead.length),t.targetArrowhead!=null&&(a+=t.targetArrowhead.length),o=o.normalize().mul(1.5*a);for(let h=1;h<1e4;h=h*2){const u=w.createBezierSegN(e,i,o,h);if(Mt.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,u,!1))return}Mt.createEdgeCurveWithNoTrimming(t,e,i)}static createEdgeCurveWithNoTrimming(t,e,i){const s=i.sub(e).normalize();let n=e,o=i;const a=t.targetArrowhead;a!=null&&(a.tipPosition=i,o=i.sub(s.mul(a.length)));const h=t.sourceArrowhead;h!=null&&(h.tipPosition=e,n=e.add(s.mul(h.length))),t.curve=D.mkPP(n,o)}}Mt.defaultArrowheadLength=5;class Bs{constructor(){this.m=new Map}clear(){this.m.clear()}get size(){return this.m.size}set(t,e){this.m.set(qn(t),e)}delete(t){this.m.delete(qn(t))}has(t){return this.m.has(qn(t))}getPP(t,e){return this.get(new ve(t,e))}get(t){return this.m.get(qn(t))}*keys(){for(const t of this.m.keys())yield vo(t)}*[Symbol.iterator](){for(const[t,e]of this.m)yield[vo(t),e]}*values(){yield*this.m.values()}}function vo(l){const t=l.split(" "),e=t[0],i=t[1];let s=e.split(",");const n=new d(Number(s[0]),Number(s[1]));s=i.split(",");const o=new d(Number(s[0]),Number(s[1]));return new ve(n,o)}function ca(l,t){return[Io(l),Io(t)].sort().join(" ")}function qn(l){return ca(l.first,l.second)}function Io(l){return l.x.toString()+","+l.y.toString()}class Ve{static GetShapes(t,e=Array.from(t.shallowEdges)){const i=new Map;To(t,i);for(const s of e){let n=i.get(s.source);n&&s.sourcePort!=null&&n.Ports.add(s.sourcePort),n=i.get(s.target),n&&s.targetPort!=null&&n.Ports.add(s.targetPort)}return Array.from(i.values())}static CreateShapeWithCenterPort(t){const e=new rn(t),i=Xe.mk(()=>t.boundaryCurve,()=>t.center);e.Ports.add(i);for(const s of t.inEdges())Ve.FixPortAtTarget(i,s);for(const s of t.outEdges())Ve.FixPortAtSource(i,s);for(const s of t.selfEdges())Ve.FixPortAtSource(i,s),Ve.FixPortAtTarget(i,s);return e}static CreateShapeWithClusterBoundaryPort(t){const e=new rn(t),i=Ge.mk(()=>t.boundaryCurve,()=>t.center);e.Ports.add(i);let s;for(const n of t.inEdges())n.EdgeToAncestor()===ki.ToAncestor?(s==null&&(s=new Kt(()=>t.boundaryCurve)),n.targetPort=s):Ve.FixPortAtTarget(i,n);for(const n of t.outEdges())n.EdgeToAncestor()===ki.FromAncestor?(s==null&&(s=new Kt(()=>t.boundaryCurve)),n.sourcePort=s):Ve.FixPortAtSource(i,n);for(const n of t.selfEdges())Ve.FixPortAtSource(i,n),Ve.FixPortAtTarget(i,n);return e}static FixPortAtSource(t,e){e!=null&&e.sourcePort==null&&(e.sourcePort=t)}static FixPortAtTarget(t,e){e!=null&&e.targetPort==null&&(e.targetPort=t)}}function To(l,t){for(const e of l.shallowNodes)if(e instanceof Xt){const i=Ve.CreateShapeWithClusterBoundaryPort(e);t.set(e,i);const s=e;if(!s.isCollapsed){To(s,t);for(const n of s.shallowNodes)i.AddChild(t.get(n))}}else t.set(e,Ve.CreateShapeWithCenterPort(e))}class Fs{constructor(){this.arrayOfMaps=new Array}isEmpty(){if(this.arrayOfMaps.length===0)return!0;for(const t of this.arrayOfMaps)if(t.size>0)return!1;return!0}set(t,e,i){let s=this.arrayOfMaps[t];s===void 0&&(this.arrayOfMaps[t]=s=new Map),s.set(e,i)}setPair(t,e){this.set(t.x,t.y,e)}delete(t,e){if(t<0||t>=this.arrayOfMaps.length)return;const i=this.arrayOfMaps[t];i!==void 0&&(i.delete(e),i.size===0&&(this.arrayOfMaps[t]=void 0))}has(t,e){if(t<0||t>=this.arrayOfMaps.length)return!1;const i=this.arrayOfMaps[t];return i===void 0?!1:i.has(e)}get(t,e){if(t<0||t>=this.arrayOfMaps.length)return null;const i=this.arrayOfMaps[t];return i===void 0?null:i.get(e)}getI(t){return this.get(t.x,t.y)}*keys(){for(let t=0;t<this.arrayOfMaps.length;t++){const e=this.arrayOfMaps[t];if(e!==void 0)for(const i of e)yield new Ot(t,i[0])}}*keyValues(){for(let t=0;t<this.arrayOfMaps.length;t++){const e=this.arrayOfMaps[t];if(e!==void 0)for(const i of e)yield[new Ot(t,i[0]),i[1]]}}*values(){for(let t=0;t<this.arrayOfMaps.length;t++){const e=this.arrayOfMaps[t];if(e!==void 0)for(const i of e)yield i[1]}}get size(){let t=0;for(let e=0;e<this.arrayOfMaps.length;e++){const i=this.arrayOfMaps[e];i!==void 0&&(t+=i.size)}return t}}var qi;(function(l){l[l.NotVisited=0]="NotVisited",l[l.InStack=1]="InStack",l[l.Visited=2]="Visited"})(qi||(qi={}));class p{constructor(t,e){this.v=t,this.i=e}}class y{static getFeedbackSetWithConstraints(t,e){throw new Error("Method not implemented.")}static push(t,e,i,s){e[i]=qi.InStack,t.push(new p(i,s))}static getFeedbackSet(t){const e=new Fs;if(t==null||t.nodeCount===0)return[];const i=new Array(t.nodeCount).fill(qi.NotVisited);for(let s=0;s<t.nodeCount;s++){if(i[s]===qi.Visited)continue;const n=new Yt.B;let o=0;for(y.push(n,i,s,o);n.size>0;){const a=n.pop();s=a.v,i[s]=qi.Visited,o=a.i;let h=t.outEdges[s];for(;o<h.length;o++){const u=h[o];if(u.source===u.target)continue;const c=i[u.target];c===qi.InStack?e.set(u.source,u.target,u):c===qi.NotVisited&&(y.push(n,i,s,o+1),s=u.target,i[u.target]=qi.Visited,h=t.outEdges[s],o=-1)}}}return Array.from(e.values())}}class x{constructor(){this.isEmpty=!0}AddValue(t){this.isEmpty?(this.max=t,this.min=t,this.isEmpty=!1):t<this.min?this.min=t:t>this.max&&(this.max=t)}get length(){return this.max-this.min}static sign(t){return t>C.distanceEpsilon?1:t<-C.distanceEpsilon?-1:0}}class T{constructor(t){this.Right=t,this.Left=t}SetActiveState(t,e){this.IsActive=t,this.VectorIndex=e,this.IsActive?(this.Left.ActiveConstraintCount++,this.Right.ActiveConstraintCount++):(this.Left.ActiveConstraintCount--,this.Right.ActiveConstraintCount--)}SetVectorIndex(t){this.VectorIndex=t}Reinitialize(){this.IsActive=!1,this.IsUnsatisfiable=!1,this.ClearDfDv()}UpdateGap(t){this.Gap=t}static constructorVVNB(t,e,i,s){const n=new T(t);return n.Left=t,n.Right=e,n.Gap=i,n.IsEquality=s,n.Lagrangian=0,n.IsActive=!1,n}ToString(){return Se.Qf.Format(" Cst: [{0}] [{1}] {2} {3:F5} vio {4:F5} Lm {5:F5}/{6:F5} {7}actv",this.Left,this.Right,this.IsEquality?"==":">=",this.Gap,this.Violation,this.Lagrangian,this.Lagrangian*2,this.IsActive?"+":this.IsUnsatisfiable?"!":"-")}get Violation(){return this.Left.ActualPos*this.Left.Scale+(this.Gap-this.Right.ActualPos*this.Right.Scale)}ClearDfDv(){this.Lagrangian=0}CompareTo(t){let e=this.Left.CompareTo(t.Left);return e===0&&(e=this.Right.CompareTo(t.Right)),e===0&&(e=W(this.Gap,t.Gap)),e}}class M{constructor(t){this.ConstraintToEval=t,this.Depth=-1}static constructorDCVV(t,e,i,s){const n=new M(e);return n.Set(t,e,i,s),n}Set(t,e,i,s){return this.Parent=t,this.ConstraintToEval=e,this.VariableToEval=i,this.VariableDoneEval=s,this.Depth=0,this.ChildrenHaveBeenPushed=!1,e.Lagrangian=0,this}get IsLeftToRight(){return this.VariableToEval===this.ConstraintToEval.Right}toString(){return Se.Qf.Format("{0} {1}{2} - {3}{4} ({5})","",this.IsLeftToRight?"":"*",this.ConstraintToEval.Left.Name,this.IsLeftToRight?"*":"",this.ConstraintToEval.Right.Name,this.Depth)}}class ${constructor(t,e){this.Constraint=t,this.IsForward=e}}class lt{constructor(t,e){this.Variables=new Array,t!=null&&this.AddVariable(t),this.allConstraints=e}toString(){return Se.Qf.Format("[Block: nvars = {0} refpos = {1:F5} scale = {2:F5}]",this.Variables.length,this.ReferencePos,this.Scale)}ComputeDfDv(t){this.allConstraints.DfDvStack=new Yt.B;const e=new T(t);this.dfDvDummyParentNode=new M(e);const i=this.GetDfDvNode(this.dfDvDummyParentNode,e,t,null);for(this.allConstraints.DfDvStack.push(i);;){const s=this.allConstraints.DfDvStack.top,n=this.allConstraints.DfDvStack.length;if(!s.ChildrenHaveBeenPushed){s.ChildrenHaveBeenPushed=!0;for(const o of s.VariableToEval.LeftConstraints)if(o.IsActive&&o.Right!==s.VariableDoneEval){const a=this.GetDfDvNode(s,o,o.Right,s.VariableToEval);o.Right.ActiveConstraintCount===1?this.ProcessDfDvLeafNodeDirectly(a):this.PushDfDvNode(a)}for(const o of s.VariableToEval.RightConstraints)if(o.IsActive&&o.Left!==s.VariableDoneEval){const a=this.GetDfDvNode(s,o,o.Left,s.VariableToEval);o.Left.ActiveConstraintCount===1?this.ProcessDfDvLeafNodeDirectly(a):this.PushDfDvNode(a)}if(this.allConstraints.DfDvStack.length>n)continue}if(this.allConstraints.DfDvStack.pop(),this.ProcessDfDvLeafNode(s),s===i)break}}ProcessDfDvLeafNode(t){const e=t.VariableToEval.DfDv;t.IsLeftToRight?(t.ConstraintToEval.Lagrangian=t.ConstraintToEval.Lagrangian+e,t.Parent.ConstraintToEval.Lagrangian=t.Parent.ConstraintToEval.Lagrangian+t.ConstraintToEval.Lagrangian):(t.ConstraintToEval.Lagrangian=(t.ConstraintToEval.Lagrangian+e)*-1,t.Parent.ConstraintToEval.Lagrangian=t.Parent.ConstraintToEval.Lagrangian-t.ConstraintToEval.Lagrangian),this.CheckForConstraintPathTarget(t),this.Debug_CheckForViolatedActiveConstraint(t.ConstraintToEval),this.allConstraints.RecycleDfDvNode(t)}Debug_CheckForViolatedActiveConstraint(t){t.Violation>this.allConstraints.SolverParameters.GapTolerance}ProcessDfDvLeafNodeDirectly(t){this.ProcessDfDvLeafNode(t)}GetDfDvNode(t,e,i,s){const n=this.allConstraints.DfDvRecycleStack.size>0?this.allConstraints.DfDvRecycleStack.pop().Set(t,e,i,s):M.constructorDCVV(t,e,i,s);return n.Depth=n.Parent.Depth+1,this.allConstraints.MaxConstraintTreeDepth<n.Depth&&(this.allConstraints.MaxConstraintTreeDepth=n.Depth),n}PushDfDvNode(t){this.PushOnDfDvStack(t)}AddVariableAndPushDfDvNode(t,e){t.push(e.VariableToEval),this.PushOnDfDvStack(e)}PushOnDfDvStack(t){this.allConstraints.DfDvStack.push(t)}CheckForConstraintPathTarget(t){if(this.pathTargetVariable===t.VariableToEval){for(;t.Parent!==this.dfDvDummyParentNode;)this.constraintPath.push(new $(t.ConstraintToEval,t.IsLeftToRight)),t=t.Parent;this.pathTargetVariable=null}}Expand(t){this.constraintPath==null&&(this.constraintPath=new Array),this.constraintPath=[],this.pathTargetVariable=t.Right,this.ComputeDfDv(t.Left);let e=null;if(this.constraintPath.length>0){for(const o of this.constraintPath)o.IsForward&&(e==null||o.Constraint.Lagrangian<e.Lagrangian)&&(o.Constraint.IsEquality||(e=o.Constraint));e!=null&&this.allConstraints.DeactivateConstraint(e)}if(this.constraintPath=[],this.pathTargetVariable=null,e==null){t.IsUnsatisfiable=!0,this.allConstraints.NumberOfUnsatisfiableConstraints++;return}const i=new Array;this.GetConnectedVariables(i,t.Right,t.Left);const s=t.Violation,n=i.length;for(let o=0;o<n;o++)i[o].OffsetInBlock=i[o].OffsetInBlock+s;this.allConstraints.ActivateConstraint(t),t.ClearDfDv(),this.UpdateReferencePos()}Split(t){if(t&&this.UpdateReferencePos(),this.Variables.length<2)return null;let e=null;this.ComputeDfDv(this.Variables[0]);let i=this.allConstraints.SolverParameters.Advanced.MinSplitLagrangianThreshold;const s=this.Variables.length;for(let n=0;n<s;n++)for(const o of this.Variables[n].LeftConstraints)o.IsActive&&!o.IsEquality&&o.Lagrangian<i&&(e=o,i=o.Lagrangian);return e==null?null:this.SplitOnConstraint(e)}SplitOnConstraint(t){this.allConstraints.DeactivateConstraint(t);let e=new lt(null,this.allConstraints);return this.TransferConnectedVariables(e,t.Right,t.Left),e.Variables.length>0?(this.UpdateReferencePos(),e.UpdateReferencePos()):e=null,e}AddVariable(t){this.Variables.push(t),t.Block=this,this.Variables.length===1?(this.Scale=t.Scale,this.ReferencePos=t.ActualPos,this.sumAd=t.ActualPos*t.Weight,this.sumAb=0,this.sumA2=t.Weight,t.OffsetInBlock=0):this.AddVariableToBlockSums(t)}UpdateReferencePos(){this.Scale=this.Variables[0].Scale,this.sumAd=0,this.sumAb=0,this.sumA2=0;const t=this.Variables.length;for(let e=0;e<t;e++)this.AddVariableToBlockSums(this.Variables[e]);this.UpdateReferencePosFromSums()}AddVariableToBlockSums(t){const e=this.Scale/t.Scale,i=t.OffsetInBlock/t.Scale,s=e*t.Weight;this.sumAd+=s*t.DesiredPos,this.sumAb+=s*i,this.sumA2+=s*e}UpdateReferencePosFromSums(){if(!(Number.isFinite(this.sumAd)&&Number.isFinite(this.sumAb)&&Number.isFinite(this.sumA2)))throw new Error("infinite numbers");this.ReferencePos=(this.sumAd-this.sumAb)/this.sumA2,this.UpdateVariablePositions()}UpdateVariablePositions(){const t=this.Scale*this.ReferencePos,e=this.Variables.length;for(let i=0;i<e;i++){const s=this.Variables[i];s.ActualPos=(t+s.OffsetInBlock)/s.Scale}}GetConnectedVariables(t,e,i){this.RecurseGetConnectedVariables(t,e,i)}RecurseGetConnectedVariables(t,e,i){this.allConstraints.DfDvStack=new Yt.B;const s=new T(e);for(this.dfDvDummyParentNode=new M(s),this.allConstraints.DfDvStack.push(this.GetDfDvNode(this.dfDvDummyParentNode,s,e,i)),t.push(e);this.allConstraints.DfDvStack.length>0;){const n=this.allConstraints.DfDvStack.top,o=this.allConstraints.DfDvStack.length;if(!n.ChildrenHaveBeenPushed){n.ChildrenHaveBeenPushed=!0;for(const a of n.VariableToEval.LeftConstraints)a.IsActive&&a.Right!==n.VariableDoneEval&&(a.Right.ActiveConstraintCount===1?t.push(a.Right):this.AddVariableAndPushDfDvNode(t,this.GetDfDvNode(n,a,a.Right,n.VariableToEval)));for(const a of n.VariableToEval.RightConstraints)a.IsActive&&a.Left!==n.VariableDoneEval&&(a.Left.ActiveConstraintCount===1?t.push(a.Left):this.AddVariableAndPushDfDvNode(t,this.GetDfDvNode(n,a,a.Left,n.VariableToEval)))}this.allConstraints.DfDvStack.length>o||this.allConstraints.RecycleDfDvNode(this.allConstraints.DfDvStack.pop())}}TransferConnectedVariables(t,e,i){this.GetConnectedVariables(t.Variables,e,i);const s=t.Variables.length;for(let o=0;o<s;o++)t.Variables[o].Block=t;let n=this.Variables.length-1;for(let o=this.Variables.length-1;o>=0;o--)this.Variables[o].Block===t&&(o<n&&(this.Variables[o]=this.Variables[n]),n--);if(this.Variables=this.Variables.slice(0,n+1),this.Variables.length===0){for(let o=0;o<s;o++){const a=t.Variables[o];this.Variables.push(a),a.Block=this}t.Variables=[]}}}class te{constructor(){this.Vector=new Array}get Count(){return this.Vector.length}item(t){return this.Vector[t]}Add(t){t.VectorIndex=this.Vector.length,this.Vector.push(t)}Remove(t){const e=this.Vector[this.Vector.length-1];this.Vector[t.VectorIndex]=e,e.VectorIndex=t.VectorIndex,this.Vector.pop()}toString(){return this.Vector.toString()}}class ee{constructor(){this.nextConstraintIndex=0,this.DfDvStack=new Yt.B,this.DfDvRecycleStack=new Yt.B}get IsEmpty(){return this.Vector==null}Create(t){this.Vector=new Array(t),this.firstActiveConstraintIndex=t}Add(t){t.SetVectorIndex(this.nextConstraintIndex),this.Vector[this.nextConstraintIndex++]=t}ActivateConstraint(t){this.firstActiveConstraintIndex--,this.SwapConstraint(t)}DeactivateConstraint(t){this.SwapConstraint(t),this.firstActiveConstraintIndex++}SwapConstraint(t){const e=this.Vector[this.firstActiveConstraintIndex];e.SetVectorIndex(t.VectorIndex),this.Vector[t.VectorIndex]=e,this.Vector[this.firstActiveConstraintIndex]=t,t.SetActiveState(!t.IsActive,this.firstActiveConstraintIndex)}Reinitialize(){if(this.Vector!=null){for(const t of this.Vector)t.Reinitialize();this.firstActiveConstraintIndex=this.Vector.length}}RecycleDfDvNode(t){this.DfDvRecycleStack.length<1024&&this.DfDvRecycleStack.push(t)}toString(){return this.Vector.toString()}}class ri{constructor(){this.GapTolerance=1e-4,this.QpscConvergenceEpsilon=1e-5,this.QpscConvergenceQuotient=1e-6,this.OuterProjectIterationsLimit=-1,this.InnerProjectIterationsLimit=-1,this.TimeLimit=-1,this.Advanced=new xe}Clone(){const t=this.MemberwiseClone();return t.Advanced=this.Advanced.Clone(),t}MemberwiseClone(){const t=new ri;return t.GapTolerance=this.GapTolerance,t.QpscConvergenceEpsilon=this.QpscConvergenceEpsilon,t.QpscConvergenceQuotient=this.QpscConvergenceQuotient,t.OuterProjectIterationsLimit=this.OuterProjectIterationsLimit,t.InnerProjectIterationsLimit=this.InnerProjectIterationsLimit,t.TimeLimit=this.TimeLimit,t}}class xe{constructor(){this.ForceQpsc=!1,this.ScaleInQpsc=!0,this.MinSplitLagrangianThreshold=-1e-7,this.UseViolationCache=!0,this.ViolationCacheMinBlocksDivisor=10,this.ViolationCacheMinBlocksCount=100}Clone(){const t=new xe;return t.ForceQpsc=this.ForceQpsc,t.ScaleInQpsc=this.ScaleInQpsc,t.MinSplitLagrangianThreshold=this.MinSplitLagrangianThreshold,t.UseViolationCache=this.UseViolationCache,t.ViolationCacheMinBlocksDivisor=this.ViolationCacheMinBlocksDivisor,t.ViolationCacheMinBlocksCount=this.ViolationCacheMinBlocksCount,t}}class Lr{constructor(t){this.Variable=t,this.OrigWeight=t.Weight,this.OrigScale=t.Scale,this.OrigDesiredPos=this.Variable.DesiredPos}}class xo{constructor(t,e){this.Value=t,this.Column=e}}class ui{constructor(t,e){this.newMatrixRow=new Array,this.previousFunctionValue=Number.MAX_VALUE,this.solverParameters=t,this.matrixQ=new Array(e).fill(0),this.vectorWiDi=new Array(e).fill(0),this.vectorQpscVars=new Array(e).fill(0),this.gradientVector=new Array(e).fill(0),this.vectorQg=new Array(e).fill(0),this.vectorPrevY=new Array(e).fill(0),this.vectorCurY=new Array(e).fill(0)}AddVariable(t){if(this.isFirstProjectCall=!0,this.vectorWiDi[t.Ordinal]=2*(t.Weight*t.DesiredPos)*-1,this.vectorPrevY[t.Ordinal]=t.Weight,t.Neighbors!=null)for(const e of t.Neighbors)this.vectorPrevY[t.Ordinal]=this.vectorPrevY[t.Ordinal]+e.Weight,this.vectorPrevY[e.Neighbor.Ordinal]=this.vectorPrevY[e.Neighbor.Ordinal]-e.Weight;for(let e=0;e<this.vectorPrevY.length;e++)this.vectorPrevY[e]!==0&&(this.newMatrixRow.push(new xo(this.vectorPrevY[e]*2,e)),this.vectorPrevY[e]=0);this.matrixQ[t.Ordinal]=Array.from(this.newMatrixRow),this.newMatrixRow=[],this.vectorQpscVars[t.Ordinal]=new Lr(t),t.Weight=1}VariablesComplete(){for(const t of this.vectorQpscVars){const e=t.Variable;for(const i of this.matrixQ[e.Ordinal])i.Column===e.Ordinal&&(this.solverParameters.Advanced.ScaleInQpsc&&(e.Scale=1/Math.sqrt(Math.abs(i.Value)),Number.isFinite(e.Scale)||(e.Scale=1),e.Scale,this.vectorWiDi[e.Ordinal]=this.vectorWiDi[e.Ordinal]*e.Scale),this.vectorCurY[e.Ordinal]=e.ActualPos,e.DesiredPos=e.ActualPos)}if(this.solverParameters.Advanced.ScaleInQpsc)for(let t=0;t<this.matrixQ.length;t++){const e=this.matrixQ[t];for(let i=0;i<e.length;i++)e[i].Column===t?e[i].Value=1:e[i].Value=e[i].Value*(this.vectorQpscVars[t].Variable.Scale*this.vectorQpscVars[e[i].Column].Variable.Scale)}}PreProject(){if(this.isFirstProjectCall)for(const s of this.vectorQpscVars)this.vectorCurY[s.Variable.Ordinal]=s.Variable.ActualPos;if(this.MatrixVectorMultiply(this.vectorCurY,this.gradientVector),this.HasConverged())return!1;ui.VectorVectorAdd(this.gradientVector,this.vectorWiDi,this.gradientVector);const t=ui.VectorVectorMultiply(this.gradientVector,this.gradientVector);let e=0;if(t!==0&&(this.MatrixVectorMultiply(this.gradientVector,this.vectorQg),e=ui.VectorVectorMultiply(this.vectorQg,this.gradientVector)),e===0)return!1;const i=t/e;ui.VectorCopy(this.vectorPrevY,this.vectorCurY),ui.VectorScaledVectorSubtract(this.vectorPrevY,i,this.gradientVector,this.vectorCurY);for(let s=0;s<this.vectorCurY.length;s++)this.vectorQpscVars[s].Variable.DesiredPos=this.vectorCurY[s];return!0}PostProject(){for(const i of this.vectorQpscVars)this.vectorCurY[i.Variable.Ordinal]=i.Variable.ActualPos;ui.VectorVectorSubtract(this.vectorPrevY,this.vectorCurY,this.vectorCurY);const t=ui.VectorVectorMultiply(this.gradientVector,this.vectorCurY);let e=0;if(t!==0){this.MatrixVectorMultiply(this.vectorCurY,this.vectorQg);const i=ui.VectorVectorMultiply(this.vectorQg,this.vectorCurY);e=i===0?1:t/i,e>1?e=1:e<0&&(e=0)}return ui.VectorScaledVectorSubtract(this.vectorPrevY,e,this.vectorCurY,this.vectorCurY),this.isFirstProjectCall=!1,e>0}QpscComplete(){for(const t of this.vectorQpscVars)t.Variable.Weight=t.OrigWeight,t.Variable.DesiredPos=t.OrigDesiredPos,this.solverParameters.Advanced.ScaleInQpsc&&(t.Variable.ActualPos=t.Variable.ActualPos*t.Variable.Scale,t.Variable.Scale=t.OrigScale);return this.previousFunctionValue}HasConverged(){const t=this.GetFunctionValue(this.vectorCurY);let e=!1;if(!this.isFirstProjectCall){const i=this.previousFunctionValue-t;let s=0;if(i!==0){const n=this.previousFunctionValue!==0?this.previousFunctionValue:t;s=Math.abs(i/n)}(Math.abs(i)<this.solverParameters.QpscConvergenceEpsilon||Math.abs(s)<this.solverParameters.QpscConvergenceQuotient)&&(e=!0)}return this.previousFunctionValue=t,e}GetFunctionValue(t){return ui.VectorVectorMultiply(this.gradientVector,t)/2+ui.VectorVectorMultiply(this.vectorWiDi,t)}static VectorVectorMultiply(t,e){let i=0;for(let s=0;s<t.length;s++)i=i+t[s]*e[s];return i}MatrixVectorMultiply(t,e){let i=0;for(const s of this.matrixQ){let n=0;for(const o of s)n=n+o.Value*t[o.Column];e[i++]=n}}static VectorVectorAdd(t,e,i){for(let s=0;s<t.length;s++)i[s]=t[s]+e[s]}static VectorVectorSubtract(t,e,i){for(let s=0;s<t.length;s++)i[s]=t[s]-e[s]}static VectorScaledVectorSubtract(t,e,i,s){for(let n=0;n<t.length;n++)s[n]=t[n]-e*i[n]}static VectorCopy(t,e){for(let i=0;i<e.length;i++)t[i]=e[i]}}class Oo{constructor(){this.NumberOfUnsatisfiableConstraints=0,this.OuterProjectIterations=0,this.InnerProjectIterationsTotal=0,this.MinInnerProjectIterations=0,this.MaxInnerProjectIterations=0,this.MaxConstraintTreeDepth=0,this.GoalFunctionValue=0,this.TimeLimitExceeded=!1,this.OuterProjectIterationsLimitExceeded=!1,this.InnerProjectIterationsLimitExceeded=!1}get ExecutionLimitExceeded(){return this.TimeLimitExceeded||this.OuterProjectIterationsLimitExceeded||this.InnerProjectIterationsLimitExceeded}Clone(){const t=new Oo;return t.GoalFunctionValue=this.GoalFunctionValue,t.InnerProjectIterationsLimitExceeded=this.InnerProjectIterationsLimitExceeded,t.InnerProjectIterationsTotal=this.InnerProjectIterationsTotal,t.MaxConstraintTreeDepth=this.MaxConstraintTreeDepth,t.OuterProjectIterations=this.OuterProjectIterations,t.OuterProjectIterationsLimitExceeded=this.OuterProjectIterationsLimitExceeded,t.AlgorithmUsed=this.AlgorithmUsed,t.NumberOfUnsatisfiableConstraints=this.NumberOfUnsatisfiableConstraints,t.MaxInnerProjectIterations=this.MaxInnerProjectIterations,t}}var Lo;(function(l){l[l.ProjectOnly=0]="ProjectOnly",l[l.QpscWithScaling=1]="QpscWithScaling",l[l.QpscWithoutScaling=2]="QpscWithoutScaling"})(Lo||(Lo={}));class xh{constructor(t,e){this.Neighbor=t,this.Weight=e}}class Oh{constructor(t,e,i,s,n){if(this.ActiveConstraintCount=0,s<=0)throw new Error("weight");if(n<=0)throw new Error("scale");let o=i*s;if(!Number.isFinite(o)||Number.isNaN(o))throw new Error("desiredPos");if(o=i*n,!Number.isFinite(o)||Number.isNaN(o))throw new Error("desiredPos");this.Ordinal=t,this.UserData=e,this.DesiredPos=i,this.Weight=s,this.Scale=n,this.OffsetInBlock=0,this.ActualPos=this.DesiredPos}get DfDv(){return 2*(this.Weight*(this.ActualPos-this.DesiredPos))/this.Scale}Reinitialize(){this.ActiveConstraintCount=0,this.OffsetInBlock=0,this.ActualPos=this.DesiredPos}AddNeighbor(t,e){this.Neighbors==null&&(this.Neighbors=new Array),this.Neighbors.push(new xh(t,e))}toString(){return Se.Qf.Format("{0} {1:F5} ({2:F5}) {3:F5} {4:F5}",this.Name,this.ActualPos,this.DesiredPos,this.Weight,this.Scale)}get Name(){return this.UserData==null?"-0-":this.UserData.toString()}SetConstraints(t,e){this.LeftConstraints=t,this.RightConstraints=e}CompareTo(t){return W(this.Ordinal,t.Ordinal)}}class Br{get IsFull(){return this.numConstraints===Br.MaxConstraints}Clear(){this.LowViolation=0,this.numConstraints=0,this.constraints||(this.constraints=new Array(Br.MaxConstraints))}FilterBlock(t){this.LowViolation=Number.MAX_VALUE;const e=this.numConstraints>0;for(let i=this.numConstraints-1;i>=0;i--){const s=this.constraints[i];if(s.Left.Block===t||s.Right.Block===t||s.IsActive||s.IsUnsatisfiable)i<this.numConstraints-1&&(this.constraints[i]=this.constraints[this.numConstraints-1]),this.numConstraints--;else{const n=s.Left.ActualPos*s.Left.Scale+(s.Gap-s.Right.ActualPos*s.Right.Scale);n<this.LowViolation&&(this.LowViolation=n)}}return this.numConstraints===0&&(this.LowViolation=0),e}FindIfGreater(t){let e=null;for(let i=0;i<this.numConstraints;i++){const s=this.constraints[i],n=s.Left.ActualPos*s.Left.Scale+(s.Gap-s.Right.ActualPos*s.Right.Scale);n>t&&(t=n,e=s)}return e}Insert(t,e){let i=0,s=e,n=e;for(let o=0;o<this.numConstraints;o++){const a=this.constraints[o],h=a.Left.ActualPos*a.Left.Scale+(a.Gap-a.Right.ActualPos*a.Right.Scale);h<s?(n=s,i=o,s=h):h<n&&(n=h)}this.IsFull?(this.constraints[i]=t,this.LowViolation=n):(this.constraints[this.numConstraints++]=t,this.IsFull&&(this.LowViolation=s))}}Br.MaxConstraints=20;class il{constructor(t,e){this.NumberOfLeftConstraints=0,this.Constraints=t,this.NumberOfLeftConstraints=e}}class Lh{constructor(){this.allBlocks=new te,this.allConstraints=new ee,this.numberOfConstraints=0,this.numberOfVariables=0,this.equalityConstraints=new Array,this.loadedVariablesAndConstraintLists=new Map,this.emptyConstraintList=new Array(0),this.updatedConstraints=new Array,this.violationCache=new Br,this.violationCacheMinBlockCutoff=0,this.nextVariableOrdinal=0,this.solverParams=new ri,this.solverSolution=new Oo}get IsQpsc(){return this.hasNeighbourPairs||this.solverParams.Advanced.ForceQpsc}AddVariableAN(t,e){return this.AddVariableANNN(t,e,1,1)}AddVariableANN(t,e,i){return this.AddVariableANNN(t,e,i,1)}AddVariableANNN(t,e,i,s){if(!this.allConstraints.IsEmpty)throw new Error("Cannot add Variables or Constraints once Solve() has been called");const n=new Oh(this.nextVariableOrdinal++,t,e,i,s),o=new lt(n,this.allConstraints);return n.Block=o,this.allBlocks.Add(o),this.numberOfVariables++,this.loadedVariablesAndConstraintLists.set(n,new il(new Array,0)),n}UpdateVariables(){for(const t of this.allBlocks.Vector)t.UpdateReferencePos()}get Variables(){return Zs(this.allBlocks.Vector,t=>t.Variables)}get VariableCount(){return this.numberOfVariables}*Constraints(){if(this.allConstraints.IsEmpty)for(const t of this.loadedVariablesAndConstraintLists.keys()){const e=this.loadedVariablesAndConstraintLists.get(t);if(e.Constraints!=null){const i=e.Constraints.length;for(let s=0;s<i;s++){const n=e.Constraints[s];if(t===n.Left)return yield,n}}}else for(const t of this.allConstraints.Vector)yield t}get ConstraintCount(){return this.numberOfConstraints}AddEqualityConstraint(t,e,i){return this.AddConstraintVVNB(t,e,i,!0)}AddConstraintVVNB(t,e,i,s){if(!this.allConstraints.IsEmpty)throw new Error("Cannot add Variables or Constraints once Solve() has been called");if(t===e)throw new Error("Cannot add a constraint between a variable and itself");const n=this.loadedVariablesAndConstraintLists.get(t),o=this.loadedVariablesAndConstraintLists.get(e),a=T.constructorVVNB(t,e,i,s);return this.loadedVariablesAndConstraintLists.set(t,new il(n.Constraints,n.NumberOfLeftConstraints+1)),n.Constraints.push(a),o.Constraints.push(a),this.numberOfConstraints++,s&&this.equalityConstraints.push(a),a}AddConstraint(t,e,i){return this.AddConstraintVVNB(t,e,i,!1)}SetConstraintUpdate(t,e){e!==t.Gap&&this.updatedConstraints.push([t,e])}AddNeighborPair(t,e,i){if(i<=0||Number.isNaN(i)||!Number.isFinite(i))throw new Error("relationshipWeight");if(t===e)throw new Error;t.AddNeighbor(e,i),e.AddNeighbor(t,i),this.hasNeighbourPairs=!0}Solve(){return this.SolvePar(null)}SolvePar(t){t&&(this.solverParams=t.Clone()),this.solverParams.OuterProjectIterationsLimit<0&&(this.solverParams.OuterProjectIterationsLimit=100*(Math.floor(Math.log2(this.numberOfVariables))+1)),this.solverParams.InnerProjectIterationsLimit<0&&(this.solverParams.InnerProjectIterationsLimit=this.numberOfConstraints*2+100*(Math.max(0,Math.floor(Math.log2(this.numberOfConstraints)))+1));const e=!this.allConstraints.IsEmpty;if(this.CheckForUpdatedConstraints(),this.solverSolution=new Oo,this.solverSolution.MinInnerProjectIterations=Number.MAX_VALUE,this.allConstraints.MaxConstraintTreeDepth=0,this.allConstraints.SolverParameters=this.solverParams,this.numberOfConstraints===0){if(!this.IsQpsc)return this.solverSolution.Clone()}else e||this.SetupConstraints();return this.allConstraints.NumberOfUnsatisfiableConstraints=0,this.MergeEqualityConstraints(),this.IsQpsc?this.SolveQpsc():(this.SolveByStandaloneProject(),this.CalculateStandaloneProjectGoalFunctionValue()),this.solverSolution.MinInnerProjectIterations>this.solverSolution.MaxInnerProjectIterations&&(this.solverSolution.MinInnerProjectIterations=this.solverSolution.MaxInnerProjectIterations),this.solverSolution.NumberOfUnsatisfiableConstraints=this.allConstraints.NumberOfUnsatisfiableConstraints,this.solverSolution.MaxConstraintTreeDepth=this.allConstraints.MaxConstraintTreeDepth,this.solverSolution.Clone()}CheckForUpdatedConstraints(){if(this.updatedConstraints.length===0)return;let t=this.IsQpsc;for(const[e,i]of this.updatedConstraints){const s=e;if(s.UpdateGap(i),!t&&!s.IsEquality){this.SplitOnConstraintIfActive(s);continue}t=!0}this.updatedConstraints=[],t&&this.ReinitializeBlocks()}SplitOnConstraintIfActive(t){if(t.IsActive){const e=t.Left.Block.SplitOnConstraint(t);e!=null&&this.allBlocks.Add(e)}}SetupConstraints(){this.allConstraints.Create(this.numberOfConstraints);for(const t of this.loadedVariablesAndConstraintLists.keys()){const e=this.loadedVariablesAndConstraintLists.get(t),i=e.Constraints;let s=0,n=0,o=0;i!=null&&(s=i.length,n=e.NumberOfLeftConstraints,o=s-n);let a=this.emptyConstraintList;n!==0&&(a=new Array(n));let h=this.emptyConstraintList;o!==0&&(h=new Array(o)),t.SetConstraints(a,h);let u=0,c=0;for(let m=0;m<s;m++){const S=i[m];t===S.Left?a[u++]=S:h[c++]=S}for(const m of t.LeftConstraints)this.allConstraints.Add(m)}this.loadedVariablesAndConstraintLists.clear(),this.violationCacheMinBlockCutoff=Number.MAX_VALUE,this.solverParams.Advanced.UseViolationCache&&this.solverParams.Advanced.ViolationCacheMinBlocksDivisor>0&&(this.violationCacheMinBlockCutoff=Math.min(this.allBlocks.Count/this.solverParams.Advanced.ViolationCacheMinBlocksDivisor,this.solverParams.Advanced.ViolationCacheMinBlocksCount))}SolveByStandaloneProject(){for(;;){if(!this.RunProject())return;if(!this.SplitBlocks())break}}RunProject(){return this.solverSolution.OuterProjectIterations++,this.Project(),!this.CheckForLimitsExceeded()}CheckForLimitsExceeded(){return this.solverParams.OuterProjectIterationsLimit>0&&this.solverSolution.OuterProjectIterations>=this.solverParams.OuterProjectIterationsLimit?(this.solverSolution.OuterProjectIterationsLimitExceeded=!0,!0):!!this.solverSolution.InnerProjectIterationsLimitExceeded}CalculateStandaloneProjectGoalFunctionValue(){this.solverSolution.GoalFunctionValue=0;const t=this.allBlocks.Count;for(let e=0;e<t;e++){const i=this.allBlocks.item(e),s=i.Variables.length;for(let n=0;n<s;n++){const o=i.Variables[n];this.solverSolution.GoalFunctionValue+=o.Weight*(o.ActualPos*o.ActualPos),this.solverSolution.GoalFunctionValue-=2*(o.Weight*(o.DesiredPos*o.ActualPos))}}}SolveQpsc(){if(this.solverSolution.AlgorithmUsed=this.solverParams.Advanced.ScaleInQpsc?Lo.QpscWithScaling:Lo.QpscWithoutScaling,!this.QpscMakeFeasible())return;const t=new ui(this.solverParams,this.numberOfVariables);for(const i of this.allBlocks.Vector)for(const s of i.Variables)t.AddVariable(s);t.VariablesComplete(),this.ReinitializeBlocks(),this.MergeEqualityConstraints();let e=!1;for(;!(!t.PreProject()&&!e||(e=this.SplitBlocks(),!this.RunProject())||!t.PostProject()&&!e););this.solverSolution.GoalFunctionValue=t.QpscComplete()}QpscMakeFeasible(){return this.RunProject()}ReinitializeBlocks(){const t=Array.from(this.allBlocks.Vector);this.allBlocks.Vector=[];for(const e of t)for(const i of e.Variables){i.Reinitialize();const s=new lt(i,this.allConstraints);this.allBlocks.Add(s)}this.allConstraints.Reinitialize(),this.violationCache.Clear()}MergeEqualityConstraints(){for(const t of this.equalityConstraints){if(t.Left.Block===t.Right.Block){Math.abs(t.Violation)>this.solverParams.GapTolerance&&(t.IsUnsatisfiable=!0,this.allConstraints.NumberOfUnsatisfiableConstraints++);continue}this.MergeBlocks(t)}}Project(){if(this.numberOfConstraints===0)return!1;this.violationCache.Clear(),this.lastModifiedBlock=null;let t=this.allBlocks.Count>this.violationCacheMinBlockCutoff,e=1;const i={maxViolation:0};let s=this.GetMaxViolatedConstraint(i,t);if(!s)return!1;for(;s;){if(s.Left.Block===s.Right.Block?(s.Left.Block.Expand(s),s.IsUnsatisfiable&&this.violationCache.Clear(),this.lastModifiedBlock=s.Left.Block):this.lastModifiedBlock=this.MergeBlocks(s),this.solverParams.InnerProjectIterationsLimit>0&&e>=this.solverParams.InnerProjectIterationsLimit){this.solverSolution.InnerProjectIterationsLimitExceeded=!0;break}t=this.allBlocks.Count>this.violationCacheMinBlockCutoff,t||this.violationCache.Clear(),e++;const n={maxViolation:0};s=this.GetMaxViolatedConstraint(n,t)}return this.solverSolution.InnerProjectIterationsTotal=this.solverSolution.InnerProjectIterationsTotal+e,this.solverSolution.MaxInnerProjectIterations<e&&(this.solverSolution.MaxInnerProjectIterations=e),this.solverSolution.MinInnerProjectIterations>e&&(this.solverSolution.MinInnerProjectIterations=e),!0}MergeBlocks(t){let e=t.Left.Block,i=t.Right.Block,s=t.Left.OffsetInBlock+(t.Gap-t.Right.OffsetInBlock);i.Variables.length>e.Variables.length&&(e=t.Right.Block,i=t.Left.Block,s=-s);const n=i.Variables.length;for(let o=0;o<n;o++){const a=i.Variables[o];a.OffsetInBlock+=s,e.AddVariable(a)}return e.UpdateReferencePosFromSums(),this.allConstraints.ActivateConstraint(t),this.allBlocks.Remove(i),e}SplitBlocks(){const t=new Array,e=this.allBlocks.Count;for(let s=0;s<e;s++){const o=this.allBlocks.item(s).Split(this.IsQpsc);o!=null&&t.push(o)}const i=t.length;for(let s=0;s<i;s++){const n=t[s];this.allBlocks.Add(n)}return t.length!==0}GetMaxViolatedConstraint(t,e){t.maxViolation=this.solverParams.GapTolerance;const i=this.SearchViolationCache(t.maxViolation);return i??this.SearchAllConstraints(t.maxViolation,e)}SearchViolationCache(t){let e=null;if(this.lastModifiedBlock==null)return;this.lastModifiedBlock.Variables.length<this.numberOfVariables+1&&this.violationCache.FilterBlock(this.lastModifiedBlock);const i=this.lastModifiedBlock.Variables.length;for(let n=0;n<i;n++){const o=this.lastModifiedBlock.Variables[n];for(const a of o.LeftConstraints)if(!a.IsActive&&!a.IsUnsatisfiable){const h=a.Left.ActualPos*a.Left.Scale+(a.Gap-a.Right.ActualPos*a.Right.Scale);z(h,t)&&(e!=null&&t>this.violationCache.LowViolation&&this.violationCache.Insert(e,t),t=a.Violation,e=a)}for(const a of o.RightConstraints)if(!a.IsActive&&!a.IsUnsatisfiable&&a.Left.Block!==this.lastModifiedBlock){const h=a.Left.ActualPos*a.Left.Scale+(a.Gap-a.Right.ActualPos*a.Right.Scale);z(h,t)&&(e!=null&&t>this.violationCache.LowViolation&&this.violationCache.Insert(e,t),t=h,e=a)}}const s=this.violationCache.FindIfGreater(t);return s!=null&&(e!=null&&t>this.violationCache.LowViolation&&this.violationCache.Insert(e,t),e=s),e}SearchAllConstraints(t,e){let i=null;this.violationCache.Clear();for(const s of this.allConstraints.Vector){if(s.IsActive)break;if(s.IsUnsatisfiable)continue;const n=s.Left.ActualPos*s.Left.Scale+(s.Gap-s.Right.ActualPos*s.Right.Scale);let o=null,a=0;z(n,t)&&(t>this.violationCache.LowViolation&&(o=i,a=t),t=n,i=s),e&&(o==null&&s!==i&&(!this.violationCache.IsFull||n>this.violationCache.LowViolation)&&(o=s,a=n),o!=null&&a>this.violationCache.LowViolation&&this.violationCache.Insert(o,a))}return i}}class Fr{constructor(){this.variables=new Map,this.fixedVars=new Map,this.FailToAdjustEpsilon=.001,this.InitSolver()}AddVariableWithIdealPositionNNN(t,e,i){this.variables.set(t,this.solver.AddVariableANN(t,e,i))}AddVariableWithIdealPositionNN(t,e){this.AddVariableWithIdealPositionNNN(t,e,1)}AddLeftRightSeparationConstraintNNNB(t,e,i,s){const n=this.GetVariable(t);if(n==null)return;const o=this.GetVariable(e);o!=null&&this.solver.AddConstraintVVNB(n,o,i,s)}AddLeftRightSeparationConstraintNNN(t,e,i){this.AddLeftRightSeparationConstraintNNNB(t,e,i,!1)}AddGoalTwoVariablesAreCloseNNN(t,e,i){const s=this.GetVariable(t);if(s==null)return;const n=this.GetVariable(e);n!=null&&this.solver.AddNeighborPair(s,n,i)}AddGoalTwoVariablesAreClose(t,e){this.AddGoalTwoVariablesAreCloseNNN(t,e,1)}GetVariable(t){return this.variables.get(t)}Solve(){this.SolveP(null)}SolveP(t){const e={executionLimitExceeded:!1};this.SolvePNS(t,e)}SolvePNS(t,e){let i;do{this.solution=null;let s=null;if(t!=null&&(s=t,s==null))throw new Error("parameters");this.solution=this.solver.SolvePar(s),e.executionLimitExceeded=this.solution.ExecutionLimitExceeded,i=this.AdjustConstraintsForMovedFixedVars()}while(i&&this.solution.ExecutionLimitExceeded===!1);return this.solution.ExecutionLimitExceeded===!1}AdjustConstraintsForMovedFixedVars(){const t=new Set;for(const[e,i]of this.fixedVars.entries())Fr.Close(i,this.GetVariableResolvedPosition(e))||t.add(e);return t.size===0?!1:this.AdjustConstraintsForMovedFixedVarSet(t)}static Close(t,e){return Math.abs(t-e)<5e-4}AdjustConstraintsForMovedFixedVarSet(t){for(;t.size>0;){let e;for(const i of t){e=i;break}if(!this.AdjustSubtreeOfFixedVar(e,t))return!1}return!0}AdjustSubtreeOfFixedVar(t,e){const i={successInAdjusting:!1},s=this.AdjustConstraintsOfNeighborsOfFixedVariable(t,i);if(!i.successInAdjusting||s.length===0)return!1;for(const n of s)e.delete(n);return!0}AdjustConstraintsOfNeighborsOfFixedVariable(t,e){const i=this.variables.get(t).Block.Variables,s=new x,n=new x;let o=1;for(const a of i)this.fixedVars.has(a.UserData)&&(s.AddValue(a.ActualPos),n.AddValue(a.DesiredPos),n.length>0&&(o=Math.max(o,s.length/n.length)));return o===1&&(o=2),e.successInAdjusting=this.FixActiveConstraints(i,o),i.map(a=>a.UserData)}FixActiveConstraints(t,e){let i=!1;for(const s of t)for(const n of s.LeftConstraints)n.IsActive&&(n.Gap>this.FailToAdjustEpsilon&&(i=!0),this.solver.SetConstraintUpdate(n,n.Gap/e));return i}GetVariableResolvedPosition(t){const e=this.GetVariable(t);return e==null?0:e.ActualPos}InitSolver(){this.solver=new Lh,this.variables.clear()}AddFixedVariable(t,e){this.AddVariableWithIdealPositionNNN(t,e,Fr.FixedVarWeight),this.fixedVars.set(t,e)}ContainsVariable(t){return this.variables.has(t)}GetVariableIdealPosition(t){return this.variables.get(t).DesiredPos}get Solution(){return this.solution}}Fr.FixedVarWeight=1e9;class Bh{constructor(){this.lowBound=Number.NEGATIVE_INFINITY,this.upperBound=Number.POSITIVE_INFINITY}get Position(){return this.position}set Position(t){t<this.lowBound?this.position=this.lowBound:t>this.upperBound?this.position=this.upperBound:this.position=t}get LowBound(){return this.lowBound}set LowBound(t){this.lowBound=t}get UpperBound(){return this.upperBound}set UpperBound(t){this.upperBound=t}toString(){return this.lowBound+(" "+(this.Position+(" "+this.upperBound)))}}class Fh{constructor(t){this.idealPositions=new Map,this.varList=new Array,this.constraints=new Set,this.solverShell=new Fr,this.boundsToInt=new Map,this.varSepartion=t}SetLowBound(t,e){const i=this.Var(e);i.LowBound=Math.max(t,i.LowBound)}Var(t){return this.varList[t]}SetUpperBound(t,e){const i=this.Var(t);i.UpperBound=Math.min(e,i.UpperBound)}Solve(){this.SolveByRegularSolver()}SolveByRegularSolver(){this.CreateVariablesForBounds();for(let t=0;t<this.varList.length;t++){const e=this.varList[t];e.IsFixed?this.solverShell.AddFixedVariable(t,e.Position):(this.solverShell.AddVariableWithIdealPositionNN(t,this.idealPositions.get(t)),e.LowBound!==Number.NEGATIVE_INFINITY&&this.constraints.add(new Ot(this.GetBoundId(e.LowBound),t)),e.UpperBound!==Number.POSITIVE_INFINITY&&this.constraints.add(new Ot(t,this.GetBoundId(e.UpperBound))))}this.CreateGraphAndRemoveCycles();for(const t of this.graph.edges){let e=0;t.x<this.varList.length&&(e+=this.varList[t.x].Width),t.y<this.varList.length&&(e+=this.varList[t.y].Width),e/=2,this.solverShell.AddLeftRightSeparationConstraintNNN(t.x,t.y,this.varSepartion+e)}this.solverShell.Solve();for(let t=0;t<this.varList.length;t++)this.varList[t].Position=this.solverShell.GetVariableResolvedPosition(t)}GetBoundId(t){return this.boundsToInt.get(t)}CreateVariablesForBounds(){for(const t of this.varList)t.IsFixed||(t.LowBound!==Number.NEGATIVE_INFINITY&&this.RegisterBoundVar(t.LowBound),t.UpperBound!==Number.POSITIVE_INFINITY&&this.RegisterBoundVar(t.UpperBound))}RegisterBoundVar(t){if(!this.boundsToInt.has(t)){const e=this.varList.length+this.boundsToInt.size;this.boundsToInt.set(t,e),this.solverShell.AddFixedVariable(e,t)}}CreateGraphAndRemoveCycles(){this.graph=ni(Array.from(this.constraints),this.varList.length+this.boundsToInt.size);const t=y.getFeedbackSet(this.graph);if(t!=null)for(const e of t)this.graph.removeEdge(e)}GetVariablePosition(t){return this.varList[t].Position}AddConstraint(t,e){this.constraints.add(new Ot(t,e))}AddVariableNNNN(t,e,i,s){this.idealPositions.set(t,i),this.AddVariableNNBN(t,e,!1,s)}AddFixedVariable(t,e){this.AddVariableNNBN(t,e,!0,0)}AddVariableNNBN(t,e,i,s){const n=new Bh;n.Position=e,n.IsFixed=i,n.Width=s,this.varList.push(n)}}const Nd={dumpDebugCurves:null};class It{clone(){const t=new It;return t.transparency=this.transparency,t.width=this.width,t.color=this.color,t.icurve=this.icurve.clone(),t.label=this.label,t.dashArray=this.dashArray,t.drawPN=this.drawPN,t}static mkDebugCurveTWCILD(t,e,i,s,n,o,a=!1){const h=new It;return h.transparency=t,h.width=e,h.color=i,h.icurve=s,h.label=n,h.dashArray=o,h.drawPN=a,h}static mkDebugCurveTWCI(t,e,i,s){return It.mkDebugCurveTWCILD(t,e,i,s,null,null)}static mkDebugCurveWCI(t,e,i){return It.mkDebugCurveTWCI(255,t,e,i)}static mkDebugCurveCI(t,e){return It.mkDebugCurveWCI(1,t,e)}static mkDebugCurveI(t){return It.mkDebugCurveCI("Black",t)}}It.colors=["DeepSkyBlue","IndianRed","Orange","Gold","DarkRed","Plum","Red","Violet","Indigo","Yellow","OrangeRed","Tomato","Purple","SaddleBrown","Green","Navy","Aqua","Pink","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","Lime","BurlyWood","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","CadetBlue","Chartreuse","DarkBlue","DarkCyan","DarkGoldenrod","DarkGray","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","DarkOrange","DarkOrchid","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkTurquoise","DarkViolet","DeepPink","DimGray","DodgerBlue","Firebrick","FloralWhite","ForestGreen","Fuchsia","CodeAnalysis","Gainsboro","GhostWhite","Goldenrod","Gray","GreenYellow","Honeydew","HotPink","Ivory","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGoldenrodYellow","LightGray","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSteelBlue","LightYellow","LimeGreen","Linen","Magenta","Maroon","MediumAquamarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","OldLace","Olive","OliveDrab","Orchid","PaleGoldenrod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","PowderBlue","RosyBrown","RoyalBlue","Salmon","SandyBrown","SeaGreen","CodeAnalysis","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Transparent","Turquoise","Aquamarine","Azure","Beige","Wheat","White","WhiteSmoke","YellowGreen","Khaki","AntiqueWhite"];class Rh extends ke{constructor(t,e){super(t,e),this.RightNeighbors=new Set,this.setOfLongestSegs=new Set,this.RightBound=Number.POSITIVE_INFINITY,this.LeftBound=Number.NEGATIVE_INFINITY,this.Direction=j.DirectionFromPointToPoint(t.point,e.point)}AddRightNeighbor(t){this.RightNeighbors.add(t)}get LongestNudgedSegments(){return this.setOfLongestSegs}AddLongestNudgedSegment(t){this.setOfLongestSegs.add(t)}BoundFromRight(t){t=Math.max(t,this.LeftBound),this.RightBound=Math.min(t,this.RightBound)}BoundFromLeft(t){t=Math.min(t,this.RightBound),this.LeftBound=Math.max(t,this.LeftBound)}}class hs{constructor(t){this.Point=t}*GetEnumerator(){let t;for(t=this;t!=null;t=t.Next)yield t.Point}get X(){return this.Point.x}get Y(){return this.Point.y}InsertVerts(t,e,i){for(e--;t<e;e--)this.SetNewNext(i[e])}InsertVertsInReverse(t,e,i){for(t++;t<e;t++)this.SetNewNext(i[t])}SetNewNext(t){const e=new hs(t),i=this.Next;this.Next=e,e.Next=i}}class Bo{constructor(t,e){this.IsFixed=!1,this.Reversed=!1,this.index=-1,this.AxisEdge=t,this.Width=e}toString(){return this.Source+(" "+this.Target)}get LongestNudgedSegment(){return this.longestNudgedSegment}set LongestNudgedSegment(t){this.longestNudgedSegment=t,this.longestNudgedSegment!=null&&(this.longestNudgedSegment.AddEdge(this),this.AxisEdge.AddLongestNudgedSegment(this.longestNudgedSegment))}get Source(){return this.Reversed?this.AxisEdge.TargetPoint:this.AxisEdge.SourcePoint}get Target(){return this.Reversed?this.AxisEdge.SourcePoint:this.AxisEdge.TargetPoint}static VectorsAreParallel(t,e){return N(t.x*e.y-t.y*e.x,0)}static EdgesAreParallel(t,e){return Bo.VectorsAreParallel(t.AxisEdge.TargetPoint.sub(t.AxisEdge.SourcePoint),e.AxisEdge.TargetPoint.sub(e.AxisEdge.SourcePoint))}get Direction(){return this.Reversed?j.OppositeDir(this.AxisEdge.Direction):this.AxisEdge.Direction}get Index(){return this.index}set Index(t){this.index=t}}class Oe{constructor(t){this.pathVisibilityGraph=new se,this.axisEdgesToPathOrders=new Map,this.OriginalPaths=t}get PathVisibilityGraph(){return this.pathVisibilityGraph}GetOrder(){return this.FillTheVisibilityGraphByWalkingThePaths(),this.InitPathOrder(),this.OrderPaths(),this.axisEdgesToPathOrders}FillTheVisibilityGraphByWalkingThePaths(){for(const t of this.OriginalPaths)this.FillTheVisibilityGraphByWalkingPath(t)}FillTheVisibilityGraphByWalkingPath(t){const e=this.CreatePathEdgesFromPoints(s(),t.Width);let i=e.next();for(i.done||t.SetFirstEdge(i.value);(i=e.next()).done===!1;)t.AddEdge(i.value);function*s(){if(t.PathPoints instanceof hs)for(let n=t.PathPoints;n!=null;n=n.Next)yield n.Point;else for(const n of t.PathPoints)yield n}}*CreatePathEdgesFromPoints(t,e){let i=t.next(),s=i.value;for(;!(i=t.next()).done;)yield this.CreatePathEdge(s,i.value,e),s=i.value}CreatePathEdge(t,e,i){switch(j.DirectionFromPointToPoint(t,e)){case v.East:case v.North:return new Bo(this.GetAxisEdge(t,e),i);case v.South:case v.West:{const n=new Bo(this.GetAxisEdge(e,t),i);return n.Reversed=!0,n}default:throw new Error("Not a rectilinear path")}}GetAxisEdge(t,e){return this.PathVisibilityGraph.AddEdgeF(t,e,(i,s)=>new Rh(i,s))}InitPathOrder(){for(const t of this.PathVisibilityGraph.Edges)this.axisEdgesToPathOrders.set(t,new Array);for(const t of this.OriginalPaths)for(const e of t.PathEdges())this.axisEdgesToPathOrders.get(e.AxisEdge).push(e)}OrderPaths(){for(const t of Oe.WalkGraphEdgesInTopologicalOrderIfPossible(this.PathVisibilityGraph))this.OrderPathEdgesSharingEdge(t)}OrderPathEdgesSharingEdge(t){const e=this.PathOrderOfVisEdge(t);e.sort(Oe.CompareTwoPathEdges);let i=0;for(const s of e)s.Index=i++}static CompareTwoPathEdges(t,e){if(t===e)return 0;const i=Oe.CompareInDirectionStartingFromAxisEdge(t,e,t.AxisEdge,t.AxisEdge.Direction);return i!==0?i:-Oe.CompareInDirectionStartingFromAxisEdge(t,e,t.AxisEdge,j.OppositeDir(t.AxisEdge.Direction))}static CompareInDirectionStartingFromAxisEdge(t,e,i,s){for(;;){if(t=Oe.GetNextPathEdgeInDirection(t,i,s),t==null||(e=Oe.GetNextPathEdgeInDirection(e,i,s),e==null))return 0;if(t.AxisEdge===e.AxisEdge){s=Oe.FindContinuedDirection(i,s,t.AxisEdge),i=t.AxisEdge;const u=Oe.GetExistingOrder(t,e);if(u===Oe.NotOrdered)continue;return s===i.Direction?u:-u}const n=s===i.Direction?i.Target:i.Source,o=Oe.OtherVertex(t.AxisEdge,n),a=Oe.OtherVertex(e.AxisEdge,n),h=Oe.ProjectionForCompare(i,s!==i.Direction);return W(h(o.point),h(a.point))}}static FindContinuedDirection(t,e,i){return t.Direction===e?i.Source===t.Target?i.Direction:j.OppositeDir(i.Direction):i.Source===t.Source?i.Direction:j.OppositeDir(i.Direction)}static OtherVertex(t,e){return t.Source===e?t.Target:t.Source}static ProjectionForCompare(t,e){return t.Direction===v.North?e?i=>-i.x:i=>i.x:e?i=>i.y:i=>-i.y}static GetNextPathEdgeInDirection(t,e,i){return e.Direction===i?t.Reversed?t.Prev:t.Next:t.Reversed?t.Next:t.Prev}static GetExistingOrder(t,e){const i=t.Index;if(i===-1)return Oe.NotOrdered;const s=e.Index;return W(i,s)}PathOrderOfVisEdge(t){return this.axisEdgesToPathOrders.get(t)}static InitQueueOfSources(t,e,i){for(const s of i.Vertices()){const n=s.InEdgesLength();e.set(s,n),n===0&&t.enqueue(s)}}static*WalkGraphEdgesInTopologicalOrderIfPossible(t){const e=new hi.o,i=new Map;for(Oe.InitQueueOfSources(e,i,t);e.length>0;){const s=e.dequeue();for(const n of s.OutEdges){const o=i.get(n.Target);i.set(n.Target,o-1),o===1&&e.enqueue(n.Target),yield n}}}}Oe.NotOrdered=Number.MAX_VALUE;class Dh extends Ai{constructor(t,e){super(),this.site=e,this.AxisEdge=t}get Site(){return this.site}}class sl extends Ai{constructor(t,e){super(),this.site=e,this.AxisEdge=t}get Site(){return this.site}}class Nh{constructor(t){this.edges=new Set,this.Source=t}get Edges(){return this.edges}AddEdge(t){this.UpPoint=t.TargetPoint,this.edges.add(t)}RemoveAxis(t){this.edges.delete(t)}IsEmpty(){return this.edges.size===0}}class us extends uo{constructor(t,e,i,s,n){super(e,new j(t).ToPoint()),this.DirectionPerp=new j(t).Right.ToPoint(),this.PathOrders=s,this.xProjection=t===v.North?o=>o.x:o=>-o.y,this.edgeContainersTree=new Qe((o,a)=>this.CompareAA(o,a)),this.SweepPole=j.VectorDirection(this.SweepDirection),this.AxisEdges=n,this.AxisEdgesToObstaclesTheyOriginatedFrom=i}FindFreeSpace(){this.InitTheQueueOfEvents(),this.ProcessEvents()}ProcessEvents(){for(;this.EventQueue.Count>0;)this.ProcessEvent(this.EventQueue.Dequeue())}ProcessEvent(t){t instanceof bs?this.ProcessVertexEvent(t):(this.Z=this.GetZP(t.Site),t instanceof sl?this.ProcessLowEdgeEvent(t):this.ProcessHighEdgeEvent(t))}ProcessHighEdgeEvent(t){const e=t.AxisEdge;this.RemoveEdge(e),this.ConstraintEdgeWithObstaclesAtZ(e,e.Target.point)}ProcessLowEdgeEvent(t){const e=t.AxisEdge,i=this.GetOrCreateAxisEdgesContainer(e);i.item.AddEdge(e);const s=this.edgeContainersTree.previous(i);if(s!=null)for(const o of s.item.edges)for(const a of i.item.edges)this.TryToAddRightNeighbor(o,a);const n=this.edgeContainersTree.next(i);if(n!=null)for(const o of i.item.Edges)for(const a of n.item.edges)this.TryToAddRightNeighbor(o,a);this.ConstraintEdgeWithObstaclesAtZ(e,e.Source.point)}TryToAddRightNeighbor(t,e){this.ProjectionsOfEdgesOverlap(t,e)&&t.AddRightNeighbor(e)}ProjectionsOfEdgesOverlap(t,e){return this.SweepPole===v.North?!(t.TargetPoint.y<e.SourcePoint.y-C.distanceEpsilon||e.TargetPoint.y<t.SourcePoint.y-C.distanceEpsilon):!(t.TargetPoint.x<e.SourcePoint.x-C.distanceEpsilon||e.TargetPoint.x<t.SourcePoint.x-C.distanceEpsilon)}GetObstacleBoundaries(t){return this.Obstacles.map(e=>It.mkDebugCurveWCI(1,t,e))}ConstraintEdgeWithObstaclesAtZ(t,e){this.ConstraintEdgeWithObstaclesAtZFromLeft(t,e),this.ConstraintEdgeWithObstaclesAtZFromRight(t,e)}ConstraintEdgeWithObstaclesAtZFromRight(t,e){const i=this.GetActiveSideFromRight(e);if(i==null||this.NotRestricting(t,i.item.Polyline))return;const s=this.ObstacleSideComparer.IntersectionOfSideAndSweepLine(i.item);t.BoundFromRight(s.dot(this.DirectionPerp))}GetActiveSideFromRight(t){return this.LeftObstacleSideTree.findFirst(e=>us.PointToTheLeftOfLineOrOnLineLocal(t,e.Start,e.End))}ConstraintEdgeWithObstaclesAtZFromLeft(t,e){const i=this.GetActiveSideFromLeft(e);if(i==null||this.NotRestricting(t,i.item.Polyline))return;const s=this.ObstacleSideComparer.IntersectionOfSideAndSweepLine(i.item);t.BoundFromLeft(s.dot(this.DirectionPerp))}static PointToTheLeftOfLineOrOnLineLocal(t,e,i){return d.signedDoubledTriangleArea(t,e,i)>-us.AreaComparisonEpsilon}static PointToTheRightOfLineOrOnLineLocal(t,e,i){return d.signedDoubledTriangleArea(e,i,t)<us.AreaComparisonEpsilon}GetActiveSideFromLeft(t){return this.RightObstacleSideTree.findLast(e=>us.PointToTheRightOfLineOrOnLineLocal(t,e.Start,e.End))}static EdgeMidPoint(t){return d.middle(t.SourcePoint,t.TargetPoint)}GetOrCreateAxisEdgesContainer(t){const e=t.Source.point,i=this.GetAxisEdgesContainerNode(e);return i??this.edgeContainersTree.insert(new Nh(e))}GetAxisEdgesContainerNode(t){const e=this.xProjection(t),i=this.edgeContainersTree.findFirst(s=>this.xProjection(s.Source)>=e-C.distanceEpsilon/2);return i!=null&&this.xProjection(i.item.Source)<=e+C.distanceEpsilon/2?i:null}ProcessVertexEvent(t){this.Z=this.GetZS(t),t instanceof as?this.ProcessLeftVertex(t,t.Vertex.nextOnPolyline):t instanceof P?this.ProcessRightVertex(t,t.Vertex.prevOnPolyline):(this.ProcessLeftVertex(t,t.Vertex.nextOnPolyline),this.ProcessRightVertex(t,t.Vertex.prevOnPolyline))}ProcessRightVertex(t,e){const i=t.Site;this.ProcessPrevSegmentForRightVertex(t,i);const s=e.point.sub(t.Site),n=s.dot(this.DirectionPerp),o=s.dot(this.SweepDirection);o<=C.distanceEpsilon?n>0&&o>=0?this.EnqueueEvent(new P(e)):this.RestrictEdgeContainerToTheRightOfEvent(t.Vertex):(this.InsertRightSide(new Ts(t.Vertex)),this.EnqueueEvent(new P(e)),this.RestrictEdgeContainerToTheRightOfEvent(t.Vertex))}RestrictEdgeContainerToTheRightOfEvent(t){const e=t.point,i=this.xProjection(e),s=this.edgeContainersTree.findFirst(n=>i<=this.xProjection(n.Source));if(s!=null)for(const n of s.item.Edges)this.NotRestricting(n,t.polyline)||n.BoundFromLeft(this.DirectionPerp.dot(e))}NotRestricting(t,e){return this.AxisEdgesToObstaclesTheyOriginatedFrom.get(t)===e}ProcessPrevSegmentForRightVertex(t,e){const i=t.Vertex.nextOnPolyline.point;e.sub(i).dot(this.SweepDirection)>C.distanceEpsilon&&this.RemoveRightSide(new Ts(t.Vertex.nextOnPolyline))}RemoveEdge(t){const e=this.GetAxisEdgesContainerNode(t.Source.point);e.item.RemoveAxis(t),e.item.IsEmpty()&&this.edgeContainersTree.deleteNodeInternal(e)}ProcessLeftVertex(t,e){const i=t.Site;this.ProcessPrevSegmentForLeftVertex(t,i);const s=e.point.sub(t.Site),n=s.dot(this.DirectionPerp),o=s.dot(this.SweepDirection);o<=C.distanceEpsilon?n<0&&o>=0&&this.EnqueueEvent(new as(e)):(this.InsertLeftSide(new Is(t.Vertex)),this.EnqueueEvent(new as(e))),this.RestrictEdgeFromTheLeftOfEvent(t.Vertex)}RestrictEdgeFromTheLeftOfEvent(t){const e=t.point,i=this.GetContainerNodeToTheLeftOfEvent(e);if(i!=null)for(const s of i.item.Edges)this.NotRestricting(s,t.polyline)||s.BoundFromRight(e.dot(this.DirectionPerp))}GetContainerNodeToTheLeftOfEvent(t){const e=this.xProjection(t);return this.edgeContainersTree.findLast(i=>this.xProjection(i.Source)<=e)}ProcessPrevSegmentForLeftVertex(t,e){const i=t.Vertex.prevOnPolyline.point;e.sub(i).dot(this.SweepDirection)>C.distanceEpsilon&&this.RemoveLeftSide(new Is(t.Vertex.prevOnPolyline))}InitTheQueueOfEvents(){this.InitQueueOfEvents();for(const t of this.AxisEdges)this.EnqueueEventsForEdge(t)}EnqueueEventsForEdge(t){this.EdgeIsParallelToSweepDir(t)&&(this.EnqueueEvent(us.EdgeLowPointEvent(t,t.Source.point)),this.EnqueueEvent(us.EdgeHighPointEvent(t,t.Target.point)))}EdgeIsParallelToSweepDir(t){return t.Direction===this.SweepPole||t.Direction===j.OppositeDir(this.SweepPole)}static EdgeHighPointEvent(t,e){return new Dh(t,e)}static EdgeLowPointEvent(t,e){return new sl(t,e)}CompareAA(t,e){return W(t.Source.dot(this.DirectionPerp),e.Source.dot(this.DirectionPerp))}}us.AreaComparisonEpsilon=C.intersectionEpsilon;class kh extends Ar{constructor(t){super(),this.CompassDirection=v.None,this.edges=new Array,this._isFixed=!1,this.Id=-1,this.IdealPosition=0,this.Id=t}get Start(){return this.start}get End(){return this.end}get Edges(){return this.edges}AddEdge(t){if(this.Edges.length===0){let e=j.VectorDirectionPP(t.Source,t.Target);switch(e){case v.South:e=v.North;break;case v.West:e=v.East;break}this.CompassDirection=e,this.start=t.Source,this.end=t.Source}switch(this.CompassDirection){case v.North:this.TryPointForStartAndEndNorth(t.Source),this.TryPointForStartAndEndNorth(t.Target);break;case v.East:this.TryPointForStartAndEndEast(t.Source),this.TryPointForStartAndEndEast(t.Target);break}this.Edges.push(t)}TryPointForStartAndEndNorth(t){t.y<this.start.y?this.start=t:t.y>this.end.y&&(this.end=t)}TryPointForStartAndEndEast(t){t.x<this.start.x?this.start=t:t.x>this.end.x&&(this.end=t)}get IsFixed(){return this._isFixed}set IsFixed(t){this._isFixed=t}get Width(){let t=0;for(const e of this.edges)t=Math.max(t,e.Width);return t}GetLeftBound(){if(!this.IsFixed){let t=Number.NEGATIVE_INFINITY;for(const e of this.edges)t=Math.max(t,e.AxisEdge.LeftBound);return t}return this.CompassDirection===v.North?this.Edges[0].Source.x:-this.Edges[0].Source.y}GetRightBound(){if(!this.IsFixed){let t=Number.POSITIVE_INFINITY;for(const e of this.edges)t=Math.min(t,e.AxisEdge.RightBound);return t}return this.Position()}Position(){return this.CompassDirection===v.North?this.Edges[0].Source.x:-this.Edges[0].Source.y}}class is{constructor(t,e){this.tree=new Qe((i,s)=>W(i.Point.x,s.Point.x)),this.VerticalPoints=e,this.HorizontalPoints=t}SplitPoints(){this.VerticalPoints.length===0||this.HorizontalPoints.length===0||(this.InitEventQueue(),this.ProcessEvents())}ProcessEvents(){for(;!this.Queue.IsEmpty();){const t={priority:0},e=this.Queue.DequeueAndGetPriority(t);this.ProcessEvent(e,t.priority)}}ProcessEvent(t,e){N(t.Next.Point.x,t.Point.x)?e===is.Low(t)?this.ProcessLowLinkedPointEvent(t):this.ProcessHighLinkedPointEvent(t):this.IntersectWithTree(t)}IntersectWithTree(t){let e,i,s;const n=t.Y;if(t.Point.x<t.Next.Point.x?(i=t.Point.x,e=t.Next.Point.x,s=!0):(e=t.Point.x,i=t.Next.Point.x,s=!1),s)for(let o=this.tree.findFirst(a=>i<=a.Point.x);o!=null&&o.item.Point.x<=e;o=this.tree.next(o)){const a=new d(o.item.Point.x,n);t=is.TrySplitHorizontalPoint(t,a,!0),is.TrySplitVerticalPoint(o.item,a)}else for(let o=this.tree.findLast(a=>a.Point.x<=e);o!=null&&o.item.Point.x>=i;o=this.tree.previous(o)){const a=new d(o.item.Point.x,n);t=is.TrySplitHorizontalPoint(t,a,!1),is.TrySplitVerticalPoint(o.item,a)}}static TrySplitVerticalPoint(t,e){is.Low(t)+C.distanceEpsilon<e.y&&e.y+C.distanceEpsilon<is.High(t)&&t.SetNewNext(e)}static TrySplitHorizontalPoint(t,e,i){return i&&t.X+C.distanceEpsilon<e.x&&e.x+C.distanceEpsilon<t.Next.X||!i&&t.Next.X+C.distanceEpsilon<e.x&&e.x+C.distanceEpsilon<t.X?(t.SetNewNext(e),t.Next):t}ProcessHighLinkedPointEvent(t){this.tree.remove(t)}ProcessLowLinkedPointEvent(t){this.tree.insert(t)}InitEventQueue(){this.Queue=new es(W);for(const t of this.VerticalPoints)this.Queue.Enqueue(t,is.Low(t));for(const t of this.HorizontalPoints)this.Queue.Enqueue(t,t.Point.y)}static Low(t){return Math.min(t.Point.y,t.Next.Point.y)}static High(t){return Math.max(t.Point.y,t.Next.Point.y)}}class Un{constructor(t){this.verticesToPathOffsets=new si,this.Paths=t}MergePaths(){this.InitVerticesToPathOffsetsAndRemoveSelfCycles();for(const t of this.Paths)this.ProcessPath(t)}ProcessPath(t){const e=new Map;let i=null;for(let s=t.PathPoints;s!=null;s=s.Next){const n=this.verticesToPathOffsets.get(s.Point);if(i!=null){if(e.size>0)for(const[o,a]of n){const h=e.get(o);h&&(this.CollapseLoopingPath(o,h,a,t,s),e.delete(o))}for(const[o,a]of i)n.has(o)||e.set(o,a)}i=n}}CollapseLoopingPath(t,e,i,s,n){const o=Un.FindLinkedPointInPath(s,e.Point),a=Array.from(Un.GetPointsInBetween(o,n));Un.Before(e,i)?(this.CleanDisappearedPiece(e,i,t),this.ReplacePiece(e,i,a,t)):(this.CleanDisappearedPiece(i,e,t),this.ReplacePiece(i,e,a.reverse(),t))}static*GetPointsInBetween(t,e){for(let i=t.Next;i!==e;i=i.Next)yield i.Point}ReplacePiece(t,e,i,s){let n=t;for(const o of i){const a=new hs(o);n.Next=a,n=a,this.verticesToPathOffsets.get(o).set(s,n)}n.Next=e}CleanDisappearedPiece(t,e,i){for(const s of Un.GetPointsInBetween(t,e))this.verticesToPathOffsets.get(s).delete(i)}static Before(t,e){for(t=t.Next;t!=null;t=t.Next)if(t===e)return!0;return!1}static FindLinkedPointInPath(t,e){for(let i=t.PathPoints;;i=i.Next)if(i.Point.equal(e))return i}InitVerticesToPathOffsetsAndRemoveSelfCycles(){for(const t of this.Paths)for(let e=t.PathPoints;e!=null;e=e.Next){let i=this.verticesToPathOffsets.get(e.Point);i||this.verticesToPathOffsets.set(e.Point,i=new Map);const s=i.get(t);s?(this.CleanDisappearedPiece(s,e,t),s.Next=e.Next):i.set(t,e)}}}class Gh{constructor(t){this.projection=t}compare(t,e){return W(this.projection(t),this.projection(e))}}/*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */var jn;(function(l){l.has=Symbol.for("@esfx/collection-core!ReadonlyCollection.has"),l.name="ReadonlyContainer";function t(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&l.has in e}l.hasInstance=t})(jn||(jn={}));var Rr;(function(l){l.has=jn.has,l.add=Symbol.for("@esfx/collection-core!Collection.add"),l.delete=Symbol.for("@esfx/collection-core!Collection.delete"),l.name="Container";function t(e){return jn.hasInstance(e)&&l.add in e&&l.delete in e}l.hasInstance=t})(Rr||(Rr={}));var oi;(function(l){l.has=jn.has,l.size=Symbol.for("@esfx/collection-core!ReadonlyCollection.size"),l.name="ReadonlyCollection";function t(e){return jn.hasInstance(e)&&(typeof e=="object"&&e!==null||typeof e=="function")&&Symbol.iterator in e&&l.size in e}l.hasInstance=t})(oi||(oi={}));var we;(function(l){l.size=oi.size,l.has=oi.has,l.add=Rr.add,l.delete=Rr.delete,l.clear=Symbol.for("@esfx/collection-core!Collection.clear"),l.name="Collection";function t(e){return oi.hasInstance(e)&&Rr.hasInstance(e)&&l.clear in e}l.hasInstance=t})(we||(we={}));var dn;(function(l){l.size=oi.size,l.has=oi.has,l.indexOf=Symbol.for("@esfx/collection-core!ReadonlyIndexedCollection.indexOf"),l.getAt=Symbol.for("@esfx/collection-core!ReadonlyIndexedCollection.getAt"),l.name="ReadonlyIndexedCollection";function t(e){return oi.hasInstance(e)&&l.indexOf in e&&l.getAt in e}l.hasInstance=t})(dn||(dn={}));var Fo;(function(l){l.size=oi.size,l.has=oi.has,l.indexOf=dn.indexOf,l.getAt=dn.getAt,l.setAt=Symbol.for("@esfx/collection-core!FixedSizeIndexedCollection.setAt"),l.name="FixedSizeIndexedCollection";function t(e){return dn.hasInstance(e)&&l.setAt in e}l.hasInstance=t})(Fo||(Fo={}));var nl;(function(l){l.size=oi.size,l.has=oi.has,l.indexOf=dn.indexOf,l.getAt=dn.getAt,l.setAt=Fo.setAt,l.add=we.add,l.delete=we.delete,l.clear=we.clear,l.insertAt=Symbol.for("@esfx/collection-core!IndexedCollection.insertAt"),l.removeAt=Symbol.for("@esfx/collection-core!IndexedCollection.removeAt"),l.name="IndexedCollection";function t(e){return Fo.hasInstance(e)&&l.insertAt in e&&l.removeAt in e}l.hasInstance=t})(nl||(nl={}));var Rs;(function(l){l.has=Symbol.for("@esfx/collection-core!ReadonlyKeyedContainer.has"),l.get=Symbol.for("@esfx/collection-core!ReadonlyKeyedContainer.get"),l.name="ReadonlyKeyedContainer";function t(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&l.has in e&&l.get in e}l.hasInstance=t})(Rs||(Rs={}));var Dr;(function(l){l.has=Rs.has,l.get=Rs.get,l.set=Symbol.for("@esfx/collection-core!KeyedCollection.set"),l.delete=Symbol.for("@esfx/collection-core!KeyedCollection.delete"),l.name="KeyedContainer";function t(e){return Rs.hasInstance(e)&&l.set in e&&l.delete in e}l.hasInstance=t})(Dr||(Dr={}));var ci;(function(l){l.has=Rs.has,l.get=Rs.get,l.size=Symbol.for("@esfx/collection-core!ReadonlyKeyedCollection.size"),l.keys=Symbol.for("@esfx/collection-core!ReadonlyKeyedCollection.keys"),l.values=Symbol.for("@esfx/collection-core!ReadonlyKeyedCollection.values"),l.name="ReadonlyKeyedCollection";function t(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&Symbol.iterator in e&&Rs.hasInstance(e)&&l.size in e&&l.keys in e&&l.values in e}l.hasInstance=t})(ci||(ci={}));var di;(function(l){l.size=ci.size,l.has=ci.has,l.get=ci.get,l.keys=ci.keys,l.values=ci.values,l.set=Dr.set,l.delete=Dr.delete,l.clear=Symbol.for("@esfx/collection-core!KeyedCollection.clear"),l.name="KeyedCollection";function t(e){return ci.hasInstance(e)&&Dr.hasInstance(e)&&l.clear in e}l.hasInstance=t})(di||(di={}));var Je;(function(l){l.size=Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.size"),l.has=Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.has"),l.hasValue=Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.hasValue"),l.get=Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.get"),l.keys=Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.keys"),l.values=Symbol.for("@esfx/collection-core!ReadonlyKeyedMultiCollection.values"),l.name="ReadonlyKeyedMultiCollection";function t(e){return(typeof e=="object"&&e!==null||typeof e=="function")&&Symbol.iterator in e&&l.size in e&&l.has in e&&l.hasValue in e&&l.get in e&&l.keys in e&&l.values in e}l.hasInstance=t})(Je||(Je={}));var $n;(function(l){l.size=Je.size,l.has=Je.has,l.hasValue=Je.hasValue,l.get=Je.get,l.keys=Je.keys,l.values=Je.values,l.add=Symbol.for("@esfx/collection-core!KeyedMultiCollection.add"),l.delete=Symbol.for("@esfx/collection-core!KeyedMultiCollection.delete"),l.deleteValue=Symbol.for("@esfx/collection-core!KeyedMultiCollection.deleteValue"),l.clear=Symbol.for("@esfx/collection-core!KeyedMultiCollection.clear"),l.name="KeyedMultiCollection";function t(e){return Je.hasInstance(e)&&l.add in e&&l.delete in e&&l.deleteValue in e&&l.clear in e}l.hasInstance=t})($n||($n={}));/*! Copyright 2022 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. THIRD PARTY LICENSE NOTICE: xxHash Library Copyright (c) 2012-2021 Yann Collet All rights reserved. BSD 2-Clause License (https://www.opensource.org/licenses/bsd-license.php) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */const gn=2654435761,fn=2246822519,rl=3266489917,Mh=668265263,ol=374761393;function Vh(l,t,e,i){if(t%4)throw new TypeError("Pointer not aligned");const s=new Uint32Array(l);let n,o,a,h,u,c,m;if(o=t+e,t>>=2,e>=16){a=o-16>>2,h=(i+gn|0)+fn|0,u=i+fn|0,c=i+0|0,m=i+gn|0;do h=h+s[t++]*fn|0|0,h=(h<<13|h>>>19)*gn|0,u=u+s[t++]*fn|0|0,u=(u<<13|u>>>19)*gn|0,c=c+s[t++]*fn|0|0,c=(c<<13|c>>>19)*gn|0,m=m+s[t++]*fn|0|0,m=(m<<13|m>>>19)*gn|0;while(t<=a);n=(h<<1|h>>>31)+(u<<7|u>>>25)|(c<<12|c>>>20)|(m<<18|m>>>14)}else n=i+ol|0;for(n=n+e|0,a=o-4>>2;t<=a;)n=n+s[t++]*rl|0|0,n=(n<<17|n>>>15)*Mh|0;if(t=t<<2,t<o){const S=new Uint8Array(s.buffer);do n=n+S[t++]*ol|0|0,n=(n<<11|n>>>21)*gn|0;while(t<o)}return n=(n^n>>>15)*fn|0,n=(n^n>>>13)*rl|0,n=n^n>>>16,n>>>0}const Wh=typeof WebAssembly<"u"&&typeof WebAssembly.Module=="function"&&typeof WebAssembly.Instance=="function",Hh=new Uint8Array([0,97,115,109,1,0,0,0,1,8,1,96,3,127,127,126,1,126,3,2,1,0,5,3,1,0,1,7,15,2,3,109,101,109,2,0,5,120,120,104,54,52,0,0,10,130,6,1,255,5,2,3,126,1,127,32,0,32,1,106,33,6,32,1,65,32,79,4,126,32,6,65,32,107,33,6,32,2,66,214,235,130,238,234,253,137,245,224,0,124,33,3,32,2,66,177,169,172,193,173,184,212,166,61,125,33,4,32,2,66,249,234,208,208,231,201,161,228,225,0,124,33,5,3,64,32,3,32,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,3,32,4,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,4,32,2,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,2,32,5,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,5,32,6,32,0,65,8,106,34,0,79,13,0,11,32,2,66,12,137,32,5,66,18,137,124,32,4,66,7,137,124,32,3,66,1,137,124,32,3,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,4,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,2,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,5,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,5,32,2,66,197,207,217,178,241,229,186,234,39,124,11,32,1,173,124,33,2,32,0,32,1,65,31,113,106,33,1,3,64,32,1,32,0,65,8,106,79,4,64,32,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,32,2,133,66,27,137,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,33,2,32,0,65,8,106,33,0,12,1,11,11,32,0,65,4,106,32,1,77,4,64,32,2,32,0,53,2,0,66,135,149,175,175,152,182,222,155,158,127,126,133,66,23,137,66,207,214,211,190,210,199,171,217,66,126,66,249,243,221,241,153,246,153,171,22,124,33,2,32,0,65,4,106,33,0,11,3,64,32,0,32,1,73,4,64,32,2,32,0,49,0,0,66,197,207,217,178,241,229,186,234,39,126,133,66,11,137,66,135,149,175,175,152,182,222,155,158,127,126,33,2,32,0,65,1,106,33,0,12,1,11,11,32,2,32,2,66,33,136,133,66,207,214,211,190,210,199,171,217,66,126,34,2,66,29,136,32,2,133,66,249,243,221,241,153,246,153,171,22,126,34,2,66,32,136,32,2,133,11]),Xn=Wh?new WebAssembly.Instance(new WebAssembly.Module(Hh)).exports:void 0;/*! Copyright 2022 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */var Qn=Xn?.mem,al=Xn?.xxh64;/*! Copyright 2022 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */const zh=typeof TextEncoder=="function";let ll=(l,t)=>(ll=qh())(l,t);const hl=(l,t)=>ll(l,t);function qh(){function l(){const e=new TextEncoder;function i(s,n){const{written:o=0}=e.encodeInto(s,n);return o}return i}function t(){function e(i,s){const n=i.length;let o=0;for(let a=0;a<n;a++){let h=i.charCodeAt(a);if(h&55296&&!(h&4294910976)&&a<n-1){const u=i.charCodeAt(a+1);(u&64512)===56320&&(h=((h&1023)<<10)+(u&1023)+65536,a++)}if(!(h&4294967168))s[o++]=h;else if(!(h&4294965248))s[o++]=h>>6|192,s[o++]=h&63|128;else if(!(h&268431360))s[o++]=h>>12|224,s[o++]=h>>6&63|128,s[o++]=h&63|128;else if(!(h&4292870144))s[o++]=h>>18|240,s[o++]=h>>12&63|128,s[o++]=h>>6&63|128,s[o++]=h&63|128;else throw new RangeError("Unsupported charCode.")}return o}return e}return zh?l():t()}/*! Copyright 2022 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */const da=typeof BigInt=="function"&&typeof BigInt(0)=="bigint",ul=typeof BigUint64Array=="function",Uh=typeof Qn=="object"&&typeof al=="function",ga=new ArrayBuffer(8),jh=new Float64Array(ga),cs=new Uint32Array(ga);let Yn=()=>(Yn=Kh())(),cl=l=>(cl=Jh())(l),dl=l=>(dl=Zh())(l),gl=l=>(gl=Yn())(l),fl=l=>(fl=_h())(l),pl=l=>(pl=tu())(l);const $h=l=>cl(l),Xh=l=>dl(l),Qh=l=>gl(l),Yh=l=>fl(l),ml=l=>pl(l);function Kh(){function l(){const e=new BigUint64Array(cs.buffer);let i=new Uint8Array(Qn.buffer);function s(u){Qn.buffer.byteLength<u&&(Qn.grow(Math.ceil((u-Qn.buffer.byteLength)/65536)),i=new Uint8Array(Qn.buffer))}function n(u){e[0]=u;const c=cs[0],m=cs[1];return(c<<7|c>>>25)^m}function o(){return cs[0]=Ro(),cs[1]=Ro(),e[0]}function a(u,c){s(u.length*3);const m=hl(u,i);return n(al(0,m,c))}function h(){const u=o();function c(m){return a(m,u)}return c}return h}function t(){let e=new Uint8Array(65536);function i(o){e.byteLength<o&&(e=new Uint8Array(o+(65536-o%65536)))}function s(o,a){i(o.length*3);const h=hl(o,e);return Vh(e.buffer,0,h,a)>>0}function n(){const o=Ro();function a(h){return s(h,o)}return a}return n}return da&&ul&&Uh?l():t()}function Jh(){function l(e){jh[0]=e;const i=cs[0],s=cs[1];return(i<<7|i>>>25)^s|0}function t(e){return e>>0===e?e|0:l(e)}return t}function Zh(){function l(){const i=new BigUint64Array(ga),s=BigInt(0),n=BigInt(1),o=BigInt(2),a=BigInt(2)**BigInt(31)-BigInt(1),h=~a,u=BigInt(64);function c(m){if(m===s)return 0;if(m>=h&&m<=a)return Number(m);m=m<s?~m*o+n:m*o;let S=0;for(;m;)i[0]=m,S=(S<<7|S>>>25)^cs[0],S=(S<<7|S>>>25)^cs[1],m=m>>u;return S|0}return c}function t(){const i=BigInt(0),s=BigInt(1),n=BigInt(2),o=BigInt(2)**BigInt(31)-BigInt(1),a=~o,h=BigInt(32),u=BigInt("0xFFFFFFFF");function c(m){if(m===i)return 0;if(m>=a&&m<=o)return Number(m);m=m<i?~m*n+s:m*n;let S=0;for(;m!==i;)S=(S<<7|S>>>25)^Number(m&u),m>>=h,S=(S<<7|S>>>25)^Number(m&u),m>>=h;return S|0}return c}function e(){const i=Yn();function s(n){return i(n.toString())}return s}return da&&ul?l():da?t():e()}function _h(){const l="description"in Symbol.prototype?A=>A.description:A=>{const I=A.toString();return I.length>=8&&I.slice(0,7)==="Symbol("&&I.slice(-1)===")"?I.slice(7,-1):I},t=Yn();let e,i;try{new WeakMap().set(Symbol.iterator,null),e=new WeakMap,i=new WeakMap}catch{e=new Map,i=new Map}for(const A of Object.getOwnPropertyNames(Symbol))if(typeof A=="string"){const I=Symbol[A];typeof I=="symbol"&&i.set(I,`Symbol.${A}`)}const s=Yn();let n;try{new WeakMap().set(Symbol.for("@esfx/equatable!~globalSymbolTest"),null),n=new WeakMap}catch{n=new Map}const o=Yn();let a,h=1;try{new WeakMap().set(Symbol(),null),a=new WeakMap}catch{a=new Map}function u(A,I){let B=n.get(A);return B===void 0&&(B=s(I),n.set(A,B)),B}function c(A,I){let B=e.get(A);return B===void 0&&(B=t(I),e.set(A,B)),B}function m(A){let I=a.get(A);return I===void 0&&(I=o(`${h++}#${l(A)}`),a.set(A,I)),I}function S(A){const I=i.get(A);if(I!==void 0)return c(A,I);const B=Symbol.keyFor(A);return B!==void 0?u(A,B):m(A)}return S}function tu(){const l=new WeakMap,t=Ro();let e=1;function i(n){return n=~n+(n<<15),n=n^n>>12,n=n+(n<<2),n=n^n>>4,n=n*2057,n=n^n>>16,n>>>0}function s(n){let o=l.get(n);return o===void 0&&(o=i(e++^t)^t,l.set(n,o)),o}return s}function Ro(){return Math.floor(Math.random()*4294967295)>>>0}/*! Copyright 2021 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */const Do=typeof globalThis=="object"?globalThis:typeof global=="object"?global:typeof self=="object"?self:void 0,fa=Symbol.for("@esfx/equatable!~hashUnknown");let No;Do&&typeof Do[fa]=="function"?No=Do[fa]:(No=function(t){switch(typeof t){case"boolean":return t?1:0;case"number":return $h(t);case"bigint":return Xh(t);case"string":return Qh(t);case"symbol":return Yh(t);case"function":return ml(t);case"object":return t===null?0:ml(t);case"undefined":return 0;default:throw new TypeError(`Unsupported type: ${typeof t}`)}},Object.defineProperty(Do,fa,{value:No}));function eu(l){return No(l)}/*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */var Ds;(function(l){l.equals=Symbol.for("@esfx/equatable:Equatable.equals"),l.hash=Symbol.for("@esfx/equatable:Equatable.hash"),l.name="Equatable";function t(e){let i;return e!=null&&l.equals in(i=Object(e))&&l.hash in i}l.hasInstance=t,Object.defineProperty(l,Symbol.hasInstance,{configurable:!0,writable:!0,value:t})})(Ds||(Ds={}));var Kn;(function(l){l.compareTo=Symbol.for("@esfx/equatable:Comparable.compareTo"),l.name="Comparable";function t(e){return e!=null&&l.compareTo in Object(e)}l.hasInstance=t,Object.defineProperty(l,Symbol.hasInstance,{configurable:!0,writable:!0,value:t})})(Kn||(Kn={}));var Ns;(function(l){l.structuralEquals=Symbol.for("@esfx/equatable:StructualEquatable.structuralEquals"),l.structuralHash=Symbol.for("@esfx/equatable:StructuralEquatable.structuralHash"),l.name="StructuralEquatable";function t(e){let i;return e!=null&&l.structuralEquals in(i=Object(e))&&l.structuralHash in i}l.hasInstance=t,Object.defineProperty(l,Symbol.hasInstance,{configurable:!0,writable:!0,value:t})})(Ns||(Ns={}));var Jn;(function(l){l.structuralCompareTo=Symbol.for("@esfx/equatable:StructuralComparable.structuralCompareTo"),l.name="StructuralComparable";function t(e){return e!=null&&l.structuralCompareTo in Object(e)}l.hasInstance=t,Object.defineProperty(l,Symbol.hasInstance,{configurable:!0,writable:!0,value:t})})(Jn||(Jn={}));var gi;(function(l){const t=Object.defineProperty({},Symbol.toStringTag,{configurable:!0,value:"Equaler"});l.defaultEqualer=e((n,o)=>Ds.hasInstance(n)?n[Ds.equals](o):Ds.hasInstance(o)?o[Ds.equals](n):Object.is(n,o),n=>Ds.hasInstance(n)?n[Ds.hash]():iu(n)),l.structuralEqualer=e((n,o)=>Ns.hasInstance(n)?n[Ns.structuralEquals](o,l.structuralEqualer):Ns.hasInstance(o)?o[Ns.structuralEquals](n,l.structuralEqualer):l.defaultEqualer.equals(n,o),n=>Ns.hasInstance(n)?n[Ns.structuralHash](l.structuralEqualer):l.defaultEqualer.hash(n)),l.tupleEqualer=e((n,o)=>{if(n!=null&&!Array.isArray(n)||o!=null&&!Array.isArray(o))throw new TypeError("Array expected");if(n===o)return!0;if(!n||!o||n.length!==o.length)return!1;for(let a=0;a<n.length;a++)if(!l.defaultEqualer.equals(n[a],o[a]))return!1;return!0},n=>{if(n==null)return 0;if(!Array.isArray(n))throw new TypeError("Array expected");let o=0;for(const a of n)o=i(o,l.defaultEqualer.hash(a));return o}),l.tupleStructuralEqualer=e((n,o)=>{if(n!=null&&!Array.isArray(n)||o!=null&&!Array.isArray(o))throw new TypeError("Array expected");if(n===o)return!0;if(!n||!o||n.length!==o.length)return!1;for(let a=0;a<n.length;a++)if(!l.structuralEqualer.equals(n[a],o[a]))return!1;return!0},n=>{if(n==null)return 0;if(!Array.isArray(n))throw new TypeError("Array expected");let o=0;for(const a of n)o=i(o,l.structuralEqualer.hash(a));return o});function e(n,o=l.defaultEqualer.hash){return Object.setPrototypeOf({equals:n,hash:o},t)}l.create=e;function i(n,o,a=7){if(typeof n!="number")throw new TypeError("Integer expected: x");if(typeof o!="number")throw new TypeError("Integer expected: y");if(typeof a!="number")throw new TypeError("Integer expected: rotate");if(isNaN(n)||!isFinite(n))throw new RangeError("Argument must be a finite number value: x");if(isNaN(o)||!isFinite(o))throw new RangeError("Argument must be a finite number value: y");if(isNaN(a)||!isFinite(a))throw new RangeError("Argument must be a finite number value: rotate");for(;a<0;)a+=32;for(;a>=32;)a-=32;return(n<<a|n>>>32-a)^o}l.combineHashes=i;function s(n){return typeof n=="object"&&n!==null&&typeof n.equals=="function"&&typeof n.hash=="function"}l.hasInstance=s,Object.defineProperty(l,Symbol.hasInstance,{configurable:!0,writable:!0,value:s})})(gi||(gi={}));var kd=gi.defaultEqualer,Gd=gi.structuralEqualer,Md=gi.tupleEqualer,Vd=gi.tupleEqualer,Wd=gi.combineHashes,ss;(function(l){const t=Object.defineProperty({},Symbol.toStringTag,{configurable:!0,value:"Comparer"});l.defaultComparer=e((s,n)=>Kn.hasInstance(s)?s[Kn.compareTo](n):Kn.hasInstance(n)?-n[Kn.compareTo](s):s<n?-1:s>n?1:0),l.structuralComparer=e((s,n)=>Jn.hasInstance(s)?s[Jn.structuralCompareTo](n,l.structuralComparer):Jn.hasInstance(n)?-n[Jn.structuralCompareTo](s,l.structuralComparer):l.defaultComparer.compare(s,n)),l.tupleComparer=e((s,n)=>{if(s!=null&&!Array.isArray(s)||n!=null&&!Array.isArray(n))throw new TypeError("Array expected");let o;if(o=l.defaultComparer.compare(s.length,n.length))return o;for(let a=0;a<s.length;a++)if(o=l.defaultComparer.compare(s[a],n[a]))return o;return 0}),l.tupleStructuralComparer=e((s,n)=>{if(s!=null&&!Array.isArray(s)||n!=null&&!Array.isArray(n))throw new TypeError("Array expected");let o;if(o=l.defaultComparer.compare(s.length,n.length))return o;for(let a=0;a<s.length;a++)if(o=l.structuralComparer.compare(s[a],n[a]))return o;return 0});function e(s){return Object.setPrototypeOf({compare:s},t)}l.create=e;function i(s){return typeof s=="object"&&s!==null&&typeof s.compare=="function"}l.hasInstance=i,Object.defineProperty(l,Symbol.hasInstance,{configurable:!0,writable:!0,value:i})})(ss||(ss={}));var Hd=ss.defaultComparer,zd=ss.structuralComparer,qd=ss.tupleComparer,Ud=ss.tupleStructuralComparer;function iu(l){return eu(l)}/*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */var Pl;const ko=function(){var l={exports:{}};return function(t,e,i){/*! The following comments were added due to code inlined from "@esfx/internal-binarysearch": *//*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */"use strict";Object.defineProperty(e,"__esModule",{value:!0});function s(n,o,a){if(n.length===0)return-1;let h=0,u=n.length-1;for(;h<=u;){const c=h+(u-h>>1),m=n[c];switch(Math.sign(a.compare(m,o))){case-1:h=c+1;break;case 0:return c;case 1:u=c-1;break}}return~h}e.binarySearch=s}(l,l.exports,null),l.exports}();class Go{constructor(...t){this._keys=[],this._values=[];let e,i;if(t.length>0){const s=t[0];s===void 0||s!=null&&Symbol.iterator in Object(s)?(e=s,t.length>1&&(i=t[1])):i=s}if(i??(i=ss.defaultComparer),this._comparer=typeof i=="function"?ss.create(i):i,e)for(const[s,n]of e)this.set(s,n)}get comparer(){return this._comparer}get size(){return this._keys.length}has(t){return(0,ko.binarySearch)(this._keys,t,this._comparer)>=0}get(t){const e=(0,ko.binarySearch)(this._keys,t,this._comparer);return e>=0?this._values[e]:void 0}set(t,e){const i=(0,ko.binarySearch)(this._keys,t,this._comparer);return i>=0?this._values[i]=e:(this._keys.splice(~i,0,t),this._values.splice(~i,0,e)),this}delete(t){const e=(0,ko.binarySearch)(this._keys,t,this._comparer);return e>=0?(this._keys.splice(e,1),this._values.splice(e,1),!0):!1}clear(){this._keys.length=0,this._values.length=0}keys(){return this._keys.values()}values(){return this._values.values()}*entries(){for(let t=0;t<this._keys.length;t++)yield[this._keys[t],this._values[t]]}[Symbol.iterator](){return this.entries()}forEach(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");for(const[i,s]of this)t.call(e,s,i,this)}get[di.size](){return this.size}[di.has](t){return this.has(t)}[di.get](t){return this.get(t)}[di.set](t,e){this.set(t,e)}[di.delete](t){return this.delete(t)}[di.clear](){this.clear()}[di.keys](){return this.keys()}[di.values](){return this.values()}}Pl=Go,Object.defineProperty(Pl.prototype,Symbol.toStringTag,{configurable:!0,writable:!0,value:"SortedMap"});class We{static RefinePaths(t,e){We.AdjustPaths(t);const i=We.CreatePathsToFirstLinkedVerticesMap(t);We.Refine(Array.from(i.values())),We.CrossVerticalAndHorizontalSegs(i.values()),We.ReconstructPathsFromLinkedVertices(i),e&&new Un(t).MergePaths()}static AdjustPaths(t){for(const e of t)e.PathPoints=We.AdjustPathPoints(e.PathPoints)}static AdjustPathPoints(t){if(!t||t.length===0)return;const e=[];let i=d.RoundPoint(t[0]);e.push(i);for(let s=1;s<t.length;s++){const n=d.RoundPoint(t[s]);i.equal(n)||(i=n,e.push(i))}return e}static CrossVerticalAndHorizontalSegs(t){const e=new Array,i=new Array;for(const s of t)for(let n=s;n.Next!=null;n=n.Next)N(n.Point.x,n.Next.Point.x)?i.push(n):e.push(n);new is(e,i).SplitPoints()}static ReconstructPathsFromLinkedVertices(t){for(const[e,i]of t)e.PathPoints=i}static Refine(t){We.RefineInDirection(v.North,t),We.RefineInDirection(v.East,t)}static*groupByProj(t,e){const i=new Map;for(const s of e){const n=t(s.Point);let o=i.get(n);o||(o=new Array,i.set(n,o)),o.push(s)}for(const s of i.values())yield s}static RefineInDirection(t,e){const i={projectionToPerp:void 0,projectionToDirection:void 0};We.GetProjectionsDelegates(t,i);const s=Array.from(We.GetAllLinkedVertsInDirection(i.projectionToPerp,e)),n=We.groupByProj(i.projectionToPerp,s);for(const o of n)We.RefineCollinearBucket(o,i.projectionToDirection)}static GetProjectionsDelegates(t,e){t===v.East?(e.projectionToDirection=i=>i.x,e.projectionToPerp=i=>i.y):(e.projectionToPerp=i=>i.x,e.projectionToDirection=i=>i.y)}static*GetAllLinkedVertsInDirection(t,e){for(const i of e)for(let s=i;s.Next!=null;s=s.Next)N(t(s.Point),t(s.Next.Point))&&(yield s)}static RefineCollinearBucket(t,e){const i=new Go(new Gh(e));for(const o of t)i.has(o.Point)||i.set(o.Point,0),i.has(o.Next.Point)||i.set(o.Next.Point,0);const s=new Array(i.size);let n=0;for(const o of i.keys())s[n++]=o;for(n=0;n<s.length;n++)i.set(s[n],n);for(const o of t){n=i.get(o.Point);const a=i.get(o.Next.Point);Math.abs(a-n)>1&&We.InsertPoints(o,s,n,a)}}static InsertPoints(t,e,i,s){i<s?t.InsertVerts(i,s,e):t.InsertVertsInReverse(s,i,e)}static CreatePathsToFirstLinkedVerticesMap(t){const e=new Map;for(const i of t)e.set(i,We.CreateLinkedVertexOfEdgePath(i));return e}static CreateLinkedVertexOfEdgePath(t){const e=t.PathPoints;let i=new hs(e[0]);const s=i;for(let n=1;n<e.length;n++)i.Next=new hs(e[n]),i=i.Next;return s}}class pn{constructor(t,e){this.Points=t,this.I=e}static equal(t,e){return t.I===e.I&&t.Points===e.Points}get Start(){return this.Points[this.I]}get End(){return this.Points[this.I+1]}}class mn{constructor(t,e){this.segTree=new Mn(null),this.crossedOutPaths=new Set,this.HierarchyOfObstacles=new Mn(e),this.Paths=t}static RemoveStaircases(t,e){new mn(t,e).Calculate()}Calculate(){this.InitHierarchies();let t;do{t=!1;for(const e of this.Paths.filter(i=>!this.crossedOutPaths.has(i)))this.ProcessPath(e)&&(t=!0)}while(t)}ProcessPath(t){const e={pts:t.PathPoints,canHaveStaircase:!1};return this.ProcessPoints(e)?(t.PathPoints=e.pts,!0):(e.canHaveStaircase||this.crossedOutPaths.add(t),!1)}ProcessPoints(t){const e=this.FindStaircaseStart(t);return e<0?!1:(t.pts=this.RemoveStaircasePN(t.pts,e),!0)}FindStaircaseStart(t){if(t.canHaveStaircase=!1,t.pts.length<5)return-1;const e=[new pn(t.pts,0),new pn(t.pts,1),new pn(t.pts,2),new pn(t.pts,3)];let i=0;for(let s=0;;){const n={canHaveStaircaseAtI:!1};if(this.IsStaircase(t.pts,s,e,n))return t.canHaveStaircase=!0,s;if(t.canHaveStaircase=t.canHaveStaircase||n.canHaveStaircaseAtI,s++,t.pts.length<s+5)return-1;e[i]=new pn(t.pts,s+3),i++,i%=4}}static GetFlippedPoint(t,e){return N(t[e].y,t[e+1].y)?new d(t[e+4].x,t[e].y):new d(t[e].x,t[e+4].y)}Crossing(t,e,i){return mn.IsCrossing(D.mkPP(t,e),this.segTree,i)}static IsCrossing(t,e,i){for(const s of e.GetAllIntersecting(t.boundingBox))if(i.findIndex(n=>n===s)===-1)return!0;return!1}IntersectObstacleHierarchyPPP(t,e,i){return this.IntersectObstacleHierarchyL(D.mkPP(t,e))||this.IntersectObstacleHierarchyL(D.mkPP(e,i))}IntersectObstacleHierarchyL(t){return this.HierarchyOfObstacles.GetAllIntersecting(t.boundingBox).some(e=>w.intersectionOne(t,e,!1)!=null)}IsStaircase(t,e,i,s){const n=t[e],o=t[e+1];let a=t[e+2];const h=t[e+3],u=t[e+4];return s.canHaveStaircaseAtI=!1,j.DirectionFromPointToPoint(n,o)!==j.DirectionFromPointToPoint(a,h)||j.DirectionFromPointToPoint(o,a)!==j.DirectionFromPointToPoint(h,u)||(a=mn.GetFlippedPoint(t,e),this.IntersectObstacleHierarchyPPP(o,a,h))?!1:(s.canHaveStaircaseAtI=!0,!this.Crossing(o,a,i))}RemoveStaircasePN(t,e){const i=t[e],s=t[e+1],n=Math.abs(i.y-s.y)<C.distanceEpsilon/2;return this.RemoveStaircasePNB(t,e,n)}RemoveStaircasePNB(t,e,i){this.RemoveSegs(t);const s=new Array(t.length-2);nu(t,s,e+1);const n=t[e+1],o=t[e+3];return s[e+1]=i?new d(o.x,n.y):new d(n.x,o.y),su(t,e+4,s,e+2,s.length-e-2),this.InsertNewSegs(s,e),s}RemoveSegs(t){for(let e=0;e<t.length-1;e++)this.RemoveSeg(new pn(t,e))}RemoveSeg(t){this.segTree.Remove(mn.Rect(t),t)}InsertNewSegs(t,e){this.InsSeg(t,e),this.InsSeg(t,e+1)}InitHierarchies(){for(const t of this.Paths)this.InsertPathSegs(t)}InsertPathSegs(t){this.InsertSegs(t.PathPoints)}InsertSegs(t){for(let e=0;e<t.length-1;e++)this.InsSeg(t,e)}InsSeg(t,e){const i=new pn(t,e);this.segTree.Add(mn.Rect(i),i)}static Rect(t){return Z.mkPP(t.Start,t.End)}}function su(l,t,e,i,s){for(;s-- >0;)e[i++]=l[t++]}function nu(l,t,e){let i=0;for(;e-- >0;)t[i++]=l[i++]}class Jt{constructor(t,e,i,s){this.AncestorsSets=s,this.HierarchyOfGroups=re(Array.from(s.keys()).filter(n=>n.IsGroup).map(n=>pe(n,n.BoundingBox))),this.Obstacles=i,this.EdgeSeparation=2*e,this.Paths=t,this.HierarchyOfObstacles=re(i.map(n=>pe(n,n.boundingBox))),this.MapPathsToTheirObstacles()}get HasGroups(){return this.HierarchyOfGroups!=null&&this.HierarchyOfGroups.Count>0}MapPathsToTheirObstacles(){this.PathToObstacles=new Map;for(const t of this.Paths)this.MapPathToItsObstacles(t)}MapPathToItsObstacles(t){if(!t.PathPoints||t.PathPoints.length===0)return;const e=t.PathPoints,i=this.HierarchyOfObstacles.FirstHitNodeWithPredicate(e[0],Jt.ObstacleTest),s=this.HierarchyOfObstacles.FirstHitNodeWithPredicate(e[e.length-1],Jt.ObstacleTest);i!=null&&s!=null&&this.PathToObstacles.set(t,[i.UserData,s.UserData])}static ObstacleTest(t,e){return w.PointRelativeToCurveLocation(t,e)!==ft.Outside?$t.Stop:$t.Continue}Calculate(t,e){this.NudgingDirection=t,We.RefinePaths(this.Paths,e),this.GetPathOrdersAndPathGraph(),this.MapAxisEdgesToTheirObstacles(),this.DrawPaths()}MapAxisEdgesToTheirObstacles(){this.axisEdgesToObstaclesTheyOriginatedFrom=new Map;for(const t of this.Paths)this.MapPathEndAxisEdgesToTheirObstacles(t);for(const t of this.Paths)this.UmmapPathInteriourFromStrangerObstacles(t)}UmmapPathInteriourFromStrangerObstacles(t){const e=this.FindFirstUnmappedEdge(t);if(e==null)return;const i=this.FindLastUnmappedEdge(t);for(let s=e;s!=null&&s!==i;s=s.Next)this.axisEdgesToObstaclesTheyOriginatedFrom.delete(s.AxisEdge)}FindLastUnmappedEdge(t){for(let e=t.LastEdge;e!=null;e=e.Prev)if(e.AxisEdge.Direction!==this.NudgingDirection)return e;return null}FindFirstUnmappedEdge(t){for(let e=t.FirstEdge;e!=null;e=e.Next)if(e.AxisEdge.Direction!==this.NudgingDirection)return e;return null}MapPathEndAxisEdgesToTheirObstacles(t){const e=this.PathToObstacles.get(t);e&&(this.ProcessThePathStartToMapAxisEdgesToTheirObstacles(t,e[0]),this.ProcessThePathEndToMapAxisEdgesToTheirObstacles(t,e[1]))}ProcessThePathEndToMapAxisEdgesToTheirObstacles(t,e){for(let i=t.LastEdge;i!=null&&j.DirectionsAreParallel(i.Direction,this.NudgingDirection);i=i.Prev)this.axisEdgesToObstaclesTheyOriginatedFrom.set(i.AxisEdge,e)}ProcessThePathStartToMapAxisEdgesToTheirObstacles(t,e){for(let i=t.FirstEdge;i!=null&&j.DirectionsAreParallel(i.Direction,this.NudgingDirection);i=i.Next)this.axisEdgesToObstaclesTheyOriginatedFrom.set(i.AxisEdge,e)}GetPathOrdersAndPathGraph(){const t=new Oe(this.Paths);this.PathOrders=t.GetOrder(),this.PathVisibilityGraph=t.PathVisibilityGraph}static GetCurvesForShow(t,e){const i=new Array;for(const s of t){const n=new at;for(const o of s.PathPoints)n.addPoint(o);i.push(n)}return i.concat(Array.from(e))}DrawPaths(){this.SetWidthsOfArrowheads(),this.CreateLongestNudgedSegments(),this.FindFreeSpaceInDirection(Array.from(this.PathVisibilityGraph.Edges)),this.MoveLongestSegsIdealPositionsInsideFeasibleIntervals(),this.PositionShiftedEdqges()}SetWidthsOfArrowheads(){for(const t of this.Paths)Jt.SetWidthsOfArrowheadsForEdge(t)}static SetWidthsOfArrowheadsForEdge(t){const e=t.GeomEdge;if(e.targetArrowhead!=null){const i=t.LastEdge;i.Width=Math.max(e.targetArrowhead.width,i.Width)}if(e.sourceArrowhead!=null){const i=t.FirstEdge;i.Width=Math.max(e.sourceArrowhead.width,i.Width)}}PositionShiftedEdqges(){this.Solver=new Fh(this.EdgeSeparation);for(let t=0;t<this.LongestNudgedSegs.length;t++)this.CreateVariablesOfLongestSegment(this.LongestNudgedSegs[t]);this.CreateConstraintsOfTheOrder(),this.CreateConstraintsBetweenLongestSegments(),this.Solver.SolveByRegularSolver(),this.ShiftPathEdges()}MoveLongestSegsIdealPositionsInsideFeasibleIntervals(){for(let t=0;t<this.LongestNudgedSegs.length;t++){const e=this.LongestNudgedSegs[t];Jt.MoveLongestSegIdealPositionsInsideFeasibleInterval(e)}}static MoveLongestSegIdealPositionsInsideFeasibleInterval(t){if(t.IsFixed)return;const e=t.GetLeftBound(),i=t.GetRightBound();t.IdealPosition<e?t.IdealPosition=e:t.IdealPosition>i&&(t.IdealPosition=i)}ShiftPathEdges(){for(const t of this.Paths)t.PathPoints=this.GetShiftedPoints(t)}GetShiftedPoints(t){return Jt.RemoveSwitchbacksAndMiddlePoints(this.GetShiftedPointsSimple(t))}static Rectilinearise(t,e){if(t.x===e.x||t.y===e.y)return e;const i=Math.abs(t.x-e.x),s=Math.abs(t.y-e.y);return i<s?new d(t.x,e.y):new d(e.x,t.y)}GetShiftedPointsSimple(t){const e=[],i=t.FirstEdge;e.push(this.ShiftedPoint(i.Source,i.LongestNudgedSegment));for(const s of t.PathEdges())e.push(this.ShiftedEdgePositionOfTarget(s));return e}ShiftedEdgePositionOfTarget(t){return t.LongestNudgedSegment!=null||t.Next==null?this.ShiftedPoint(t.Target,t.LongestNudgedSegment):this.ShiftedPoint(t.Next.Source,t.Next.LongestNudgedSegment)}ShiftedPoint(t,e){if(e==null)return t;const i=this.Solver.GetVariablePosition(e.Id);return this.NudgingDirection===v.North?new d(i,t.y):new d(t.x,-i)}static LineSegOfLongestSeg(t,e){const i=e===v.East?n=>n.x:n=>n.y,s={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};for(const n of t.Edges)Jt.UpdateMinMaxWithPoint(s,i,n.Source),Jt.UpdateMinMaxWithPoint(s,i,n.Target);return e===v.East?new D(s.min,-t.IdealPosition,s.max,-t.IdealPosition):new D(t.IdealPosition,s.min,t.IdealPosition,s.max)}static UpdateMinMaxWithPoint(t,e,i){const s=e(i);t.min>s&&(t.min=s),t.max<s&&(t.max=s)}CreateConstraintsBetweenLongestSegments(){for(const t of this.LongestNudgedSegs)this.CreateConstraintsBetweenLongestSegmentsForSegment(t)}CreateConstraintsBetweenLongestSegmentsForSegment(t){const e=new Set;for(const i of t.Edges){const s=i.AxisEdge;if(s!=null)for(const n of s.RightNeighbors)for(const o of n.LongestNudgedSegments)e.add(o)}for(const i of e)this.ConstraintTwoLongestSegs(t,i)}CreateConstraintsOfTheOrder(){for(const t of this.PathOrders)Jt.ParallelToDirection(t[0],this.NudgingDirection)&&this.CreateConstraintsOfThePathOrder(t[1])}static ParallelToDirection(t,e){switch(e){case v.North:case v.South:return N(t.SourcePoint.x,t.TargetPoint.x);default:return N(t.SourcePoint.y,t.TargetPoint.y)}}CreateConstraintsOfThePathOrder(t){let e=null;for(const i of t.filter(s=>s.LongestNudgedSegment!=null))e!=null&&this.ConstraintTwoLongestSegs(e.LongestNudgedSegment,i.LongestNudgedSegment),e=i}ConstraintTwoLongestSegs(t,e){(!t.IsFixed||!e.IsFixed)&&this.Solver.AddConstraint(t.Id,e.Id)}CreateVariablesOfLongestSegment(t){if(t.IsFixed)this.Solver.AddFixedVariable(t.Id,Jt.SegmentPosition(t,this.NudgingDirection));else{const e=t.GetLeftBound(),i=t.GetRightBound();e>=i?(this.Solver.AddFixedVariable(t.Id,Jt.SegmentPosition(t,this.NudgingDirection)),t.IsFixed=!0):(this.Solver.AddVariableNNNN(t.Id,Jt.SegmentPosition(t,this.NudgingDirection),t.IdealPosition,t.Width),e!==Number.NEGATIVE_INFINITY&&this.Solver.SetLowBound(e,t.Id),i!==Number.POSITIVE_INFINITY&&this.Solver.SetUpperBound(t.Id,i))}}static SegmentPosition(t,e){return e===v.North?t.Start.x:-t.Start.y}FindFreeSpaceInDirection(t){this.BoundAxisEdgesByRectsKnownInAdvance(),new us(this.NudgingDirection,this.Obstacles,this.axisEdgesToObstaclesTheyOriginatedFrom,this.PathOrders,t).FindFreeSpace()}BoundAxisEdgesByRectsKnownInAdvance(){for(const t of this.Paths)this.HasGroups&&this.BoundPathByMinCommonAncestors(t),this.BoundAxisEdgesAdjacentToSourceAndTargetOnEdge(t)}BoundPathByMinCommonAncestors(t){for(const e of this.GetMinCommonAncestors(t.GeomEdge)){const i=e.BoundingBox;for(const s of t.PathEdges()){const n=s.AxisEdge;n.Direction===this.NudgingDirection&&this.BoundAxisEdgeByRect(i,n)}}}GetMinCommonAncestors(t){this.PortToShapes==null&&(this.PortToShapes=Jt.MapPortsToShapes(this.AncestorsSets.keys()));const e=ru(this.AncestorsForPort(t.sourcePort),this.AncestorsForPort(t.targetPort));return Array.from(e).filter(i=>!i.Children.some(s=>e.has(s)))}AncestorsForPort(t){const e=this.PortToShapes.get(t);return e?this.AncestorsSets.get(e):new Set(this.HierarchyOfGroups.AllHitItems(Z.mkPP(t.Location,t.Location),null))}BoundAxisEdgeAdjacentToObstaclePort(t,e){t.Curve==null?this.BoundAxisByPoint(t.Location,e):t.Curve.boundingBox.contains(t.Location)&&this.BoundAxisEdgeByRect(t.Curve.boundingBox,e)}BoundAxisByPoint(t,e){e!=null&&e.Direction===this.NudgingDirection&&(this.NudgingDirection===v.North?(e.BoundFromLeft(t.x),e.BoundFromRight(t.x)):(e.BoundFromLeft(-t.y),e.BoundFromRight(-t.y)))}BoundAxisEdgesAdjacentToSourceAndTargetOnEdge(t){this.BoundAxisEdgeAdjacentToObstaclePort(t.GeomEdge.sourcePort,t.FirstEdge.AxisEdge),this.BoundAxisEdgeAdjacentToObstaclePort(t.GeomEdge.targetPort,t.LastEdge.AxisEdge)}BoundAxisEdgeByRect(t,e){e!=null&&e.Direction===this.NudgingDirection&&(this.NudgingDirection===v.North?(e.BoundFromLeft(t.left),e.BoundFromRight(t.right)):(e.BoundFromLeft(t.top*-1),e.BoundFromRight(t.bottom*-1)))}CreateLongestNudgedSegments(){const t=this.NudgingDirection===v.East?e=>-e.y:e=>e.x;this.LongestNudgedSegs=new Array;for(let e=0;e<this.Paths.length;e++)this.CreateLongestNudgedSegmentsForPath(this.Paths[e],t)}CreateLongestNudgedSegmentsForPath(t,e){this.GoOverPathAndCreateLongSegs(t),Jt.CalculateIdealPositionsForLongestSegs(t,e)}static CalculateIdealPositionsForLongestSegs(t,e){let i=null,s=null,n=e(t.Start);for(const o of t.PathEdges())if(o.LongestNudgedSegment!=null){if(i=o.LongestNudgedSegment,s!=null){let a;Jt.SetIdealPositionForSeg(s,a=e(s.start),n,e(i.Start)),n=a,s=null}}else i!=null&&(s=i,i=null);s!=null?Jt.SetIdealPositionForSeg(s,e(s.Start),n,e(t.End)):i!=null&&(i.IdealPosition=e(i.Start))}static SetIdealPositionForSeg(t,e,i,s){const n=Math.max(i,s),o=Math.min(i,s);o+C.distanceEpsilon<e?e<n?t.IdealPosition=.5*(n+o):t.IdealPosition=n:t.IdealPosition=o}GoOverPathAndCreateLongSegs(t){let e=null;const i=j.OppositeDir(this.NudgingDirection);for(const s of t.PathEdges()){const n=s.Direction;n===this.NudgingDirection||n===i?(e==null?(s.LongestNudgedSegment=e=new kh(this.LongestNudgedSegs.length),this.LongestNudgedSegs.push(e)):s.LongestNudgedSegment=e,s.IsFixed&&(e.IsFixed=!0)):(s.LongestNudgedSegment=null,e=null)}}static BuildPolylineForPath(t){const e={points:t.PathPoints.map(i=>i.clone())};return Jt.ExtendPolylineToPorts(e,t),e.points}static ExtendPolylineToPorts(t,e){Jt.ExtendPolylineToSourcePort(t,e.GeomEdge.sourcePort.Location),Jt.ExtendPolylineToTargetPort(t,e.GeomEdge.targetPort.Location),t.points.length<2&&(t.points=new Array(2),t.points[0]=e.GeomEdge.sourcePort.Location,t.points[1]=e.GeomEdge.targetPort.Location)}static ExtendPolylineToTargetPort(t,e){const i=t.points.length-1,s=j.VectorDirectionPP(t.points[i-1],t.points[i]);if(Jt.ProjectionsAreClose(t.points[i-1],s,e)){t.points=t.points.slice(0,i);return}const n=t.points[i];s===v.East||s===v.West?t.points[i]=new d(e.x,n.y):t.points[i]=new d(n.x,e.y)}static ProjectionsAreClose(t,e,i){return e===v.East||e===v.West?N(t.x,i.x):N(t.y,i.y)}static ExtendPolylineToSourcePort(t,e){const i=j.VectorDirectionPP(t.points[0],t.points[1]);if(Jt.ProjectionsAreClose(t.points[1],i,e)){t.points=t.points.slice(1);return}const s=t.points[0];i===v.East||i===v.West?t.points[0]=new d(e.x,s.y):t.points[0]=new d(s.x,e.y)}static RemoveSwitchbacksAndMiddlePoints(t){const e=[];let i=t[0];e.push(i);let s=t[1],n=j.VectorDirectionPP(i,s),o=1;for(;++o<t.length;){const a=j.VectorDirectionPP(s,t[o]);a===n||j.OppositeDir(a)===n||a===v.None||(d.closeDistEps(i,s)||e.push(i=Jt.Rectilinearise(i,s)),n=a),s=t[o]}return d.closeDistEps(i,s)||e.push(Jt.Rectilinearise(i,s)),e}static NudgePaths(t,e,i,s,n){if(t.length===0)return;const o=new Jt(t,e,i,s);o.Calculate(v.North,!0),o.Calculate(v.East,!1),o.Calculate(v.North,!1),n&&o.RemoveStaircases();for(const a of t)a.GeomEdge.curve=at.mkFromPoints(Jt.BuildPolylineForPath(a))}RemoveStaircases(){mn.RemoveStaircases(this.Paths,this.HierarchyOfObstacles)}static MapPortsToShapes(t){const e=new Map;for(const i of t)for(const s of i.Ports)e.set(s,i);return e}static*GetEdgePathFromPathEdgesAsDebugCurves(t,e,i,s){const n=s.ArrayOfPathPoints(),o=n.length,a=o>1?(e-t)/(o-1):1;for(let h=0;h<n.length-1;h++)yield It.mkDebugCurveTWCI(200,t+a*h,i,D.mkPP(n[h],n[h+1]))}}function ru(l,t){const e=new Set;if(l.size<t.size)for(const i of l)t.has(i)&&e.add(i);else for(const i of t)l.has(i)&&e.add(i);return e}class ou{constructor(t,e){this.Crossings=[],this.Location=t,this.Crossings=e}}class Nr{constructor(){this.ListOfPointsAndCrossings=[],this.index=0,this.ListOfPointsAndCrossings=new Array}Count(){return this.ListOfPointsAndCrossings.length}Add(t,e){this.ListOfPointsAndCrossings.push(new ou(t,e))}Pop(){return this.ListOfPointsAndCrossings[this.index++]}CurrentIsBeforeOrAt(t){return this.index>=this.ListOfPointsAndCrossings.length?!1:L.ComparePP(this.ListOfPointsAndCrossings[this.index].Location,t)<=0}get First(){return this.ListOfPointsAndCrossings[0]}get Last(){return this.ListOfPointsAndCrossings[this.ListOfPointsAndCrossings.length-1]}Reset(){this.index=0}MergeFrom(t){if(this.Reset(),t==null)return;const e=this.ListOfPointsAndCrossings.length;let i=0;const s=t.ListOfPointsAndCrossings.length;let n=0;const o=new Array(this.ListOfPointsAndCrossings.length);for(;i<e||n<s;){if(i>=e){o.push(t.ListOfPointsAndCrossings[n++]);continue}if(n>=s){o.push(this.ListOfPointsAndCrossings[i++]);continue}const a=this.ListOfPointsAndCrossings[i],h=t.ListOfPointsAndCrossings[n],u=L.ComparePP(a.Location,h.Location);u===0?(o.push(a),++i,++n):u===-1?(o.push(a),++i):(o.push(h),++n)}this.ListOfPointsAndCrossings=o}Trim(t,e){this.Reset(),!(this.ListOfPointsAndCrossings==null||this.ListOfPointsAndCrossings.length===0)&&(this.ListOfPointsAndCrossings=this.ListOfPointsAndCrossings.filter(i=>L.ComparePP(i.Location,t)>=0&&L.ComparePP(i.Location,e)<=0))}static ToCrossingArray(t,e){let i=0;const s=t.length;for(let a=0;a<s;a++)t[a].DirectionToInside===e&&i++;if(i===0)return null;const n=new Array(i);let o=0;for(let a=0;a<s;a++)t[a].DirectionToInside===e&&(n[o++]=t[a]);return n}ToString(){return Se.Qf.Format("{0} [{1}]",this.ListOfPointsAndCrossings.length,this.index)}}class it{static EdgeDirectionVE(t){return it.EdgeDirectionVV(t.Source,t.Target)}static EdgeDirectionVV(t,e){return L.GetDirections(t.point,e.point)}static GetEdgeEnd(t,e){const i=it.EdgeDirectionVE(t);return e===i?t.Target:t.Source}static FindAdjacentVertex(t,e){for(const i of t.InEdges)if(L.GetDirections(t.point,i.SourcePoint)===e)return i.Source;for(const i of t.OutEdges)if(L.GetDirections(t.point,i.TargetPoint)===e)return i.Target;return null}static FindAdjacentEdge(t,e){for(const i of t.InEdges)if(L.GetDirections(i.SourcePoint,t.point)===e)return i;for(const i of t.OutEdges)if(L.GetDirections(t.point,i.TargetPoint)===e)return i;return null}static FindBendPointBetween(t,e,i){return it.IsVerticalD(i)?new d(e.x,t.y):new d(t.x,e.y)}static SegmentIntersectionPPP(t,e,i){const s=L.GetDirections(t,e);return it.IsVerticalD(s)?new d(t.x,i.y):new d(i.x,t.y)}static SegmentIntersectionSP(t,e){return it.SegmentIntersectionPPP(t.Start,t.End,e)}static SegmentsIntersection(t,e){return it.IntervalsIntersect(t.Start,t.End,e.Start,e.End)}static SegmentsIntersectLL(t,e){return it.IntervalsIntersect(t.start,t.end,e.start,e.end)}static IntervalsOverlapSS(t,e){return it.IntervalsOverlapPPPP(t.Start,t.End,e.Start,e.End)}static IntervalsOverlapPPPP(t,e,i,s){return it.IntervalsAreCollinear(t,e,i,s)&&L.ComparePP(t,s)!==L.ComparePP(e,i)}static IntervalsAreCollinear(t,e,i,s){const n=it.IsVerticalPP(t,e);return it.IsVerticalPP(i,s)===n?n?L.Equal(t.x,i.x):L.Equal(t.y,i.y):!1}static IntervalsAreSame(t,e,i,s){return L.EqualPP(t,i)&&L.EqualPP(e,s)}static IntervalsIntersect(t,e,i,s){const n=it.SegmentIntersectionPPP(t,e,i);return it.PointIsOnSegmentPPP(t,e,n)&&it.PointIsOnSegmentPPP(i,s,n)?n:void 0}static SegmentIntersectionEP(t,e){return it.SegmentIntersectionPPP(t.SourcePoint,t.TargetPoint,e)}static PointIsOnSegmentPPP(t,e,i){return L.EqualPP(t,i)||L.EqualPP(e,i)||L.GetDirections(t,i)===L.GetDirections(i,e)}static PointIsOnSegmentSP(t,e){return it.PointIsOnSegmentPPP(t.Start,t.End,e)}static IsVerticalD(t){return(t&(v.North|v.South))!==0}static IsVerticalE(t){return it.IsVerticalD(L.GetDirections(t.SourcePoint,t.TargetPoint))}static IsVerticalPP(t,e){return it.IsVerticalD(L.GetDirections(t,e))}static IsVertical(t){return it.IsVerticalD(L.GetDirections(t.start,t.end))}static IsAscending(t){return(t&(v.North|v.East))!==0}static Slope(t,e,i){const s=e.sub(t);return s.dot(i.PerpDirectionAsPoint)/s.dot(i.DirectionAsPoint)}static SortAscending(t,e){const i=L.GetDirections(t,e);return v.None===i||it.IsAscending(i)?[t,e]:[e,t]}static RectangleBorderIntersect(t,e,i){switch(i){case v.North:case v.South:return new d(e.x,it.GetRectangleBound(t,i));case v.East:case v.West:return new d(it.GetRectangleBound(t,i),e.y);default:throw new Error}}static GetRectangleBound(t,e){switch(e){case v.North:return t.top;case v.South:return t.bottom;case v.East:return t.right;case v.West:return t.left;default:throw new Error}}static RectangleInteriorsIntersect(t,e){return L.Compare(t.bottom,e.top)<0&&L.Compare(e.bottom,t.top)<0&&L.Compare(t.left,e.right)<0&&L.Compare(e.left,t.right)<0}static PointIsInRectangleInterior(t,e){return L.Compare(t.y,e.top)<0&&L.Compare(e.bottom,t.y)<0&&L.Compare(t.x,e.right)<0&&L.Compare(e.left,t.x)<0}}class ae{constructor(t){this.Dir=t,this.DirectionAsPoint=j.toPoint(this.Dir),this.PerpDirection=v.North===t?v.East:v.North,this.PerpDirectionAsPoint=j.toPoint(this.PerpDirection),this.OppositeDirection=j.OppositeDir(t)}get Dir(){return this.dir}set Dir(t){this.dir=t}get IsHorizontal(){return v.East===this.Dir}get IsVertical(){return v.North===this.Dir}Compare(t,e){const i=this.ComparePerpCoord(t,e);return i!==0?i:this.CompareScanCoord(t,e)}CompareScanCoord(t,e){return L.Compare(t.sub(e).dot(this.DirectionAsPoint),0)}ComparePerpCoord(t,e){return L.Compare(t.sub(e).dot(this.PerpDirectionAsPoint),0)}IsFlatS(t){return this.IsFlatPP(t.Start,t.End)}IsFlatPP(t,e){return L.Equal(e.sub(t).dot(this.PerpDirectionAsPoint),0)}IsPerpendicularS(t){return this.IsPerpendicularPP(t.Start,t.End)}IsPerpendicularPP(t,e){return L.Equal(e.sub(t).dot(this.DirectionAsPoint),0)}Coord(t){return t.dot(this.DirectionAsPoint)}Min(t,e){return this.Compare(t,e)<=0?t:e}Max(t,e){return this.Compare(t,e)>=0?t:e}get PerpendicularInstance(){return this.IsHorizontal?ae.VerticalInstance:ae.HorizontalInstance}static GetInstance(t){return it.IsVerticalD(t)?ae.VerticalInstance:ae.HorizontalInstance}ToString(){return this.Dir.toString()}}ae.HorizontalInstance=new ae(v.East),ae.VerticalInstance=new ae(v.North);class bt extends Ar{constructor(t,e,i,s){super(),this.Update(t,e),this.Weight=i,this.GroupBoundaryPointAndCrossingsList=s}static mk(t,e){return new bt(t,e,bt.NormalWeight,null)}get Start(){return this.startPoint}get End(){return this.endPoint}get IsVertical(){return bt.IsVerticalSegment(this.Start,this.End)}get ScanDirection(){return this.IsVertical?ae.VerticalInstance:ae.HorizontalInstance}get IsOverlapped(){return bt.OverlappedWeight===this.Weight}get IsReflection(){return bt.ReflectionWeight===this.Weight}static IsVerticalSegment(t,e){return t.x===e.x}MergeGroupBoundaryCrossingList(t){t!=null&&(this.GroupBoundaryPointAndCrossingsList==null&&(this.GroupBoundaryPointAndCrossingsList=new Nr),this.GroupBoundaryPointAndCrossingsList.MergeFrom(t))}TrimGroupBoundaryCrossingList(){this.GroupBoundaryPointAndCrossingsList!=null&&this.GroupBoundaryPointAndCrossingsList.Trim(this.Start,this.End)}Update(t,e){this.startPoint=t,this.endPoint=e}SetInitialVisibilityVertex(t){this.LowestVisibilityVertex=t,this.HighestVisibilityVertex=t}AppendVisibilityVertex(t,e){if(this.HighestVisibilityVertex==null)this.AddGroupCrossingsBeforeHighestVisibilityVertex(t,e)||this.SetInitialVisibilityVertex(e);else{if(L.IsPureLower(e.point,this.HighestVisibilityVertex.point))return;this.AddGroupCrossingsBeforeHighestVisibilityVertex(t,e)||this.AppendHighestVisibilityVertex(e)}}AddVisibilityEdge(t,e){const i=new ke(t,e,this.Weight);return se.AddEdge(i),i}AppendHighestVisibilityVertex(t){L.EqualPP(this.HighestVisibilityVertex.point,t.point)||(this.AddVisibilityEdge(this.HighestVisibilityVertex,t),this.HighestVisibilityVertex=t)}LoadStartOverlapVertexIfNeeded(t){if(this.NeedStartOverlapVertex){const e=t.FindVertex(this.Start);this.AppendVisibilityVertex(t,e??t.AddVertexP(this.Start))}}LoadEndOverlapVertexIfNeeded(t){if(this.NeedEndOverlapVertex){const e=t.FindVertex(this.End);this.AppendVisibilityVertex(t,e??t.AddVertexP(this.End))}}OnSegmentIntersectorBegin(t){this.AppendGroupCrossingsThroughPoint(t,this.Start)||this.LoadStartOverlapVertexIfNeeded(t)}OnSegmentIntersectorEnd(t){this.AppendGroupCrossingsThroughPoint(t,this.End),this.GroupBoundaryPointAndCrossingsList=null,(this.HighestVisibilityVertex==null||L.IsPureLower(this.HighestVisibilityVertex.point,this.End))&&this.LoadEndOverlapVertexIfNeeded(t)}static Subsume(t,e,i,s,n,o,a,h){return h.extendStart=!0,h.extendEnd=!0,t.seg==null||!it.IntervalsOverlapPPPP(t.seg.Start,t.seg.End,e,i)?!1:t.seg.Weight!==s?t.seg.Start===e&&t.seg.End===i?(t.seg.Weight=Math.min(t.seg.Weight,s),!0):!1:(h.extendStart=o.CompareScanCoord(e,t.seg.Start)===-1,h.extendEnd=o.CompareScanCoord(i,t.seg.End)===1,(h.extendStart||h.extendEnd)&&(a.Remove(t.seg),t.seg.startPoint=o.Min(t.seg.Start,e),t.seg.endPoint=o.Max(t.seg.End,i),t.seg=a.InsertUnique(t.seg).item,t.seg.MergeGroupBoundaryCrossingList(n)),!0)}IntersectsSegment(t){return it.SegmentsIntersection(this,t)!==void 0}toString(){return"["+this.Start+" -> "+this.End+(this.IsOverlapped?" olap":" free")+"]"}ContainsPoint(t){return L.EqualPP(this.Start,t)||L.EqualPP(this.End,t)||L.GetDirections(this.Start,t)===L.GetDirections(t,this.End)}get HasSparsePerpendicularCoords(){return this.sparsePerpendicularCoords==null?!1:this.sparsePerpendicularCoords.size>0}CreatePointFromPerpCoord(t){return this.IsVertical?new d(this.Start.x,t):new d(t,this.Start.y)}AddSparseVertexCoord(t){this.sparsePerpendicularCoords==null&&(this.sparsePerpendicularCoords=new Set),this.sparsePerpendicularCoords.add(t)}AddSparseEndpoint(t){return this.sparsePerpendicularCoords.has(t)?!1:(this.sparsePerpendicularCoords.add(t),!0)}CreateSparseVerticesAndEdges(t){var e;if(this.sparsePerpendicularCoords!=null){this.AppendGroupCrossingsThroughPoint(t,this.Start);for(const i of Array.from(this.sparsePerpendicularCoords.values()).sort(W)){const s=this.CreatePointFromPerpCoord(i);this.AppendVisibilityVertex(t,(e=t.FindVertex(s))!==null&&e!==void 0?e:t.AddVertexP(s))}this.AppendGroupCrossingsThroughPoint(t,this.End),this.GroupBoundaryPointAndCrossingsList=null,this.sparsePerpendicularCoords.clear(),this.sparsePerpendicularCoords=null}}HasVisibility(){return this.LowestVisibilityVertex!=null}AddGroupCrossingsBeforeHighestVisibilityVertex(t,e){return this.AppendGroupCrossingsThroughPoint(t,e.point)?(L.IsPureLower(this.HighestVisibilityVertex.point,e.point)&&(this.AddVisibilityEdge(this.HighestVisibilityVertex,e),this.HighestVisibilityVertex=e),!0):!1}AppendGroupCrossingsThroughPoint(t,e){var i;if(this.GroupBoundaryPointAndCrossingsList==null)return!1;let s=!1;for(;this.GroupBoundaryPointAndCrossingsList.CurrentIsBeforeOrAt(e);){const n=this.GroupBoundaryPointAndCrossingsList.Pop();let o=null,a=null;L.ComparePP(n.Location,this.Start)>0&&(o=Nr.ToCrossingArray(n.Crossings,this.ScanDirection.OppositeDirection)),L.ComparePP(n.Location,this.End)<0&&(a=Nr.ToCrossingArray(n.Crossings,this.ScanDirection.Dir)),s=!0;const h=(i=t.FindVertex(n.Location))!==null&&i!==void 0?i:t.AddVertexP(n.Location);t.AddVertexP(n.Location),o!=null||a!=null?(this.AddLowCrossings(t,h,o),this.AddHighCrossings(t,h,a)):this.LowestVisibilityVertex==null?this.SetInitialVisibilityVertex(h):this.AppendHighestVisibilityVertex(h)}return s}static GetCrossingInteriorVertex(t,e,i){var s;const n=i.GetInteriorVertexPoint(e.point);return(s=t.FindVertex(n))!==null&&s!==void 0?s:t.AddVertexP(n)}AddCrossingEdge(t,e,i,s){let n=null;this.HighestVisibilityVertex!=null&&(L.EqualPP(this.HighestVisibilityVertex.point,i.point)?n=t.FindEdgePP(e.point,i.point):this.AppendHighestVisibilityVertex(e)),n==null&&(n=this.AddVisibilityEdge(e,i));const o=s.map(h=>h.Group.InputShape),a=n.IsPassable;a==null?n.IsPassable=()=>{for(const h of o)if(h.IsTransparent)return!0;return!1}:n.IsPassable=()=>{for(const h of o)if(h.IsTransparent||a())return!0;return!1},this.LowestVisibilityVertex==null&&this.SetInitialVisibilityVertex(e),this.HighestVisibilityVertex=i}AddLowCrossings(t,e,i){if(i!=null){const s=bt.GetCrossingInteriorVertex(t,e,i[0]);this.AddCrossingEdge(t,s,e,i)}}AddHighCrossings(t,e,i){if(i!=null){const s=bt.GetCrossingInteriorVertex(t,e,i[0]);this.AddCrossingEdge(t,e,s,i)}}}bt.NormalWeight=ke.DefaultWeight,bt.ReflectionWeight=5,bt.OverlappedWeight=500;class Sl{constructor(t,e,i,s,n){this.IsClosed=!1,this.Vertex=t,this.Direction=e!=null?j.DirectionFromPointToPoint(e.Vertex.point,t.point):v.None,this.ResetEntry(e,i,s,n)}ResetEntry(t,e,i,s){this.PreviousEntry=t,this.Length=e,this.NumberOfBends=i,this.Cost=s}get PreviousVertex(){return this.PreviousEntry==null?null:this.PreviousEntry.Vertex}toString(){return this.Vertex.point+(" "+(this.Direction+(" "+(this.IsClosed+(" "+this.Cost)))))}}class pa{constructor(){this.Clear()}Set(t,e){this.Vertex=t,this.Weight=e}Clear(){this.Vertex=null,this.Weight=Number.NaN}}class Vt{constructor(){this.nextNeighbors=[new pa,new pa,new pa],this.LengthImportance=1,this.BendsImportance=1}CombinedCost(t,e){return this.LengthImportance*t+this.BendsImportance*e}TotalCostFromSourceToVertex(t,e){return this.CombinedCost(t,e)+this.sourceCostAdjustment}InitPath(t,e,i){if(e===i||!this.InitEntryDirectionsAtTarget(i))return!1;this.Target=i,this.Source=e;const s=this.TotalCostFromSourceToVertex(0,0)+this.HeuristicDistanceFromVertexToTarget(e.point,v.None);return s>=this.upperBoundOnCost?!1:(this.queue=new es(W),this.visitedVertices=[e],t==null?this.EnqueueInitialVerticesFromSource(s):this.EnqueueInitialVerticesFromSourceEntries(t),this.queue.count>0)}InitEntryDirectionsAtTarget(t){this.EntryDirectionsToTarget=v.None;for(const e of t.OutEdges)this.EntryDirectionsToTarget=this.EntryDirectionsToTarget|j.DirectionFromPointToPoint(e.TargetPoint,t.point);for(const e of t.InEdges)this.EntryDirectionsToTarget=this.EntryDirectionsToTarget|j.DirectionFromPointToPoint(e.SourcePoint,t.point);return this.EntryDirectionsToTarget!==v.None}static IsInDirs(t,e){return t===(t&e)}MultistageAdjustedCostBound(t){return Number.isFinite(t)?t+this.BendsImportance:t}HeuristicDistanceFromVertexToTarget(t,e){const i=this.Target.point.sub(t);if(N(i.x,0)&&N(i.y,0))return this.targetCostAdjustment;const s=j.VectorDirection(i);let n;return e===v.None?(e=v.East|(v.North|(v.West|v.South)),n=this.GetNumberOfBends(e,s)):n=this.GetNumberOfBends(e,s),this.CombinedCost(Vt.ManhattanDistance(t,this.Target.point),n)+this.targetCostAdjustment}GetNumberOfBends(t,e){return j.IsPureDirection(e)?this.GetNumberOfBendsForPureDirection(t,e):Vt.GetBendsForNotPureDirection(e,t,this.EntryDirectionsToTarget)}GetNumberOfBendsForPureDirection(t,e){return(e&t)===e?Vt.IsInDirs(e,this.EntryDirectionsToTarget)?0:Vt.IsInDirs(Vt.Left(e),this.EntryDirectionsToTarget)||Vt.IsInDirs(Vt.Right(e),this.EntryDirectionsToTarget)?2:4:this.GetNumberOfBendsForPureDirection(Vt.AddOneTurn[t],e)+1}static GetBendsForNotPureDirection(t,e,i){const s=t&e;if(s===v.None)return Vt.GetBendsForNotPureDirection(t,Vt.AddOneTurn[e],i)+1;const n=t&i;return n===v.None?Vt.GetBendsForNotPureDirection(t,e,Vt.AddOneTurn[i])+1:(s|n)===t?1:2}static Left(t){switch(t){case v.None:return v.None;case v.North:return v.West;case v.East:return v.North;case v.South:return v.East;case v.West:return v.South;default:throw new Error("direction")}}static Right(t){switch(t){case v.None:return v.None;case v.North:return v.East;case v.East:return v.South;case v.South:return v.West;case v.West:return v.North;default:throw new Error("direction")}}static RestorePathV(t){return Vt.RestorePath(t,null)}static RestorePath(t,e){if(t.entry==null)return[];const i=new Array;let s=!1,n=v.None;for(;;){n===t.entry.Direction?s=!0:(s=!1,i.push(t.entry.Vertex.point),n=t.entry.Direction);const o=t.entry.PreviousEntry;if(o==null||t.entry.Vertex===e)break;t.entry=o}return s&&i.push(t.entry.Vertex.point),i.reverse(),i}QueueReversedEntryToNeighborVertexIfNeeded(t,e,i){const s={numberOfBends:0,length:0},n=e.PreviousVertex,o=Vt.GetLengthAndNumberOfBendsToNeighborVertex(t,n,i,s);if(this.CombinedCost(s.length,s.numberOfBends)<this.CombinedCost(e.Length,e.NumberOfBends)||t.Vertex.Degree===1){const a=this.TotalCostFromSourceToVertex(s.length,s.numberOfBends)+this.HeuristicDistanceFromVertexToTarget(n.point,o);this.EnqueueEntry(t,n,s.length,s.numberOfBends,a)}}UpdateEntryToNeighborVertexIfNeeded(t,e,i){const s={numberOfBends:0,length:0},n=Vt.GetLengthAndNumberOfBendsToNeighborVertex(t,e.Vertex,i,s);if(this.CombinedCost(s.length,s.numberOfBends)<this.CombinedCost(e.Length,e.NumberOfBends)){const o=this.TotalCostFromSourceToVertex(s.length,s.numberOfBends)+this.HeuristicDistanceFromVertexToTarget(e.Vertex.point,n);e.ResetEntry(t,s.length,s.numberOfBends,o),this.queue.DecreasePriority(e,o)}}CreateAndEnqueueEntryToNeighborVertex(t,e,i){const s={numberOfBends:0,length:0},n=Vt.GetLengthAndNumberOfBendsToNeighborVertex(t,e,i,s),o=this.TotalCostFromSourceToVertex(s.length,s.numberOfBends)+this.HeuristicDistanceFromVertexToTarget(e.point,n);o<this.upperBoundOnCost&&(e.VertexEntries==null&&this.visitedVertices.push(e),this.EnqueueEntry(t,e,s.length,s.numberOfBends,o))}EnqueueEntry(t,e,i,s,n){const o=new Sl(e,t,i,s,n);e.SetVertexEntry(o),this.queue.Enqueue(o,o.Cost)}static GetLengthAndNumberOfBendsToNeighborVertex(t,e,i,s){s.length=t.Length+Vt.ManhattanDistance(t.Vertex.point,e.point)*i;const n=j.DirectionFromPointToPoint(t.Vertex.point,e.point);return s.numberOfBends=t.NumberOfBends,t.Direction!==v.None&&n!==t.Direction&&s.numberOfBends++,n}static ManhattanDistance(t,e){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}GetPathWithCost(t,e,i,s,n,o,a){if(this.upperBoundOnCost=a,this.sourceCostAdjustment=i,this.targetCostAdjustment=o,!this.InitPath(t,e,n))return null;for(;this.queue.count>0;){const h=this.queue.Dequeue(),u=h.Vertex;if(u===this.Target){if(s==null)return this.Cleanup(),h;if(h.Direction,this.EntryDirectionsToTarget===v.None){let m=0;for(const S of this.Target.VertexEntries)s[m++]=S;return this.Cleanup(),null}this.upperBoundOnCost=Math.min(this.MultistageAdjustedCostBound(h.Cost),this.upperBoundOnCost);continue}h.IsClosed=!0;for(const m of this.nextNeighbors)m.Clear();const c=Vt.Right(h.Direction);this.ExtendPathAlongInEdges(h,u.InEdges,c),this.ExtendPathAlongOutEdges(h,u.OutEdges,c);for(const m of this.nextNeighbors)m.Vertex!=null&&this.ExtendPathToNeighborVertex(h,m.Vertex,m.Weight)}if(s!=null&&this.Target.VertexEntries!=null)for(let h=0;h<this.Target.VertexEntries.length;h++)s[h]=this.Target.VertexEntries[h];return this.Cleanup(),null}ExtendPathAlongInEdges(t,e,i){for(const s of e)this.ExtendPathAlongEdge(t,s,!0,i)}ExtendPathAlongOutEdges(t,e,i){let s=e.isEmpty()?null:e.treeMinimum();for(;s!=null;s=e.next(s))this.ExtendPathAlongEdge(t,s.item,!1,i)}ExtendPathAlongEdge(t,e,i,s){if(!Vt.IsPassable(e))return;const n=i?e.Source:e.Target;if(n===t.PreviousVertex){if(t.Vertex.Degree>1||t.Vertex!==this.Source)return;this.ExtendPathToNeighborVertex(t,n,e.Weight);return}const o=j.DirectionFromPointToPoint(t.Vertex.point,n.point);let a=this.nextNeighbors[2];o!==t.Direction&&(a=this.nextNeighbors[o===s?1:0]),a.Set(n,e.Weight)}EnqueueInitialVerticesFromSource(t){const e=new Sl(this.Source,null,0,0,t);e.IsClosed=!0;for(const i of this.Source.OutEdges)Vt.IsPassable(i)&&this.ExtendPathToNeighborVertex(e,i.Target,i.Weight);for(const i of this.Source.InEdges)Vt.IsPassable(i)&&this.ExtendPathToNeighborVertex(e,i.Source,i.Weight)}EnqueueInitialVerticesFromSourceEntries(t){for(const e of t)e!=null&&this.queue.Enqueue(e,e.Cost)}ExtendPathToNeighborVertex(t,e,i){const s=j.DirectionFromPointToPoint(t.Vertex.point,e.point),n=e.VertexEntries!=null?e.VertexEntries[j.ToIndex(s)]:null;n==null?this.CreateAndEnqueueReversedEntryToNeighborVertex(t,e,i)||this.CreateAndEnqueueEntryToNeighborVertex(t,e,i):n.IsClosed||this.UpdateEntryToNeighborVertexIfNeeded(t,n,i)}CreateAndEnqueueReversedEntryToNeighborVertex(t,e,i){if(t.Vertex.VertexEntries!=null){const s=j.DirectionFromPointToPoint(e.point,t.Vertex.point),n=t.Vertex.VertexEntries[j.ToIndex(s)];if(n!=null)return this.QueueReversedEntryToNeighborVertexIfNeeded(t,n,i),!0}return!1}static IsPassable(t){return t.IsPassable==null||t.IsPassable()}Cleanup(){for(const t of this.visitedVertices)t.RemoveVertexEntries();this.visitedVertices=[],this.queue=null}}Vt.DefaultBendPenaltyAsAPercentageOfDistance=4,Vt.AddOneTurn=[v.None,v.North|v.East|v.West,v.North|v.East|v.South,15,v.East|v.South|v.West,15,15,15,13,15,15,15,15,15,15,15];class kr{constructor(t){this.bendPenaltyAsAPercentageOfDistance=Vt.DefaultBendPenaltyAsAPercentageOfDistance,this.currentPassTargetEntries=new Array(4),this.bendPenaltyAsAPercentageOfDistance=t}GetPath(t,e){const i={entry:this.GetPathStage(null,t,null,e)};return Vt.RestorePathV(i)}GetPathStage(t,e,i,s){const n=new Vt,o={bestEntry:null,bestCost:Number.MAX_VALUE/bt.OverlappedWeight};let a=Number.POSITIVE_INFINITY;const h=kr.Barycenter(e),u=kr.Barycenter(s),c=Vt.ManhattanDistance(h,u);n.BendsImportance=Math.max(.001,c*(this.bendPenaltyAsAPercentageOfDistance*.01));const m=n.LengthImportance,S=i!=null?this.currentPassTargetEntries:null,A=[];for(const q of e)for(const rt of s)A.push([q,rt]);A.sort(([q,rt],[ct,Q])=>I(q,rt)-I(ct,Q));for(const[q,rt]of A){if(d.closeDistEps(q.point,rt.point))continue;const ct=B(q,h)*m,Q=B(rt,u)*m;let pt=o.bestCost;if(i!=null){for(let _t=0;_t<S.length;_t++)S[_t]=null;pt=n.MultistageAdjustedCostBound(o.bestCost)}const Lt=n.GetPathWithCost(t,q,ct,S,rt,Q,pt);if(S!=null){kr.UpdateTargetEntriesForEachDirection(i,S,o);continue}if(Lt==null)continue;const Bt=Lt.Cost/I(q,rt);(Lt.Cost<o.bestCost||N(Lt.Cost,o.bestCost)&&Bt<a)&&(o.bestCost=Lt.Cost,o.bestEntry=Lt,a=Lt.Cost/I(q,rt))}return o.bestEntry;function I(q,rt){return Vt.ManhattanDistance(q.point,rt.point)}function B(q,rt){return Vt.ManhattanDistance(q.point,rt)}}static UpdateTargetEntriesForEachDirection(t,e,i){for(let s=0;s<e.length;s++){const n=e[s];n!=null&&(t[s]==null||n.Cost<t[s].Cost)&&(t[s]=n,n.Cost<i.bestCost&&(i.bestCost=n.Cost,i.bestEntry=n))}}static Barycenter(t){let e=new d(0,0);for(const i of t)e=e.add(i.point);return e.div(t.length)}}class au{constructor(t){this.GeomEdge=t}get PathPoints(){return this._pathPoints}set PathPoints(t){this._pathPoints=t}get Width(){return this.GeomEdge.lineWidth}get End(){return this.LastEdge.Target}get Start(){return this.FirstEdge.Source}ArrayOfPathPoints(){return this._pathPoints instanceof hs?Array.from(yl(this._pathPoints)):this._pathPoints}*PathEdges(){for(let t=this.FirstEdge;t!=null;t=t.Next)yield t}AddEdge(t){t.Path=this,this.LastEdge.Next=t,t.Prev=this.LastEdge,this.LastEdge=t}SetFirstEdge(t){this.FirstEdge=t,this.LastEdge=t,t.Path=this}toString(){const t=new Se.fe;this.PathPoints instanceof hs&&t.Append("L");for(const e of yl(this.PathPoints))t.Append(e.toString());return t.ToString()}}function*yl(l){if(l instanceof hs)for(let t=l;t!=null;t=t.Next)yield t.Point;else for(const t of l)yield t}class Cl extends wr{constructor(t,e,i,s){super(e),this.Slope=0,this.SlopeInverse=0,this.Obstacle=t,this.endVertex=s?e.nextOnPolyline:e.prevOnPolyline,i.IsPerpendicularPP(e.point,this.endVertex.point)||(this.Slope=it.Slope(e.point,this.endVertex.point,i),this.SlopeInverse=1/this.Slope)}get Obstacle(){return this.obstacle}set Obstacle(t){this.obstacle=t}get EndVertex(){return this.endVertex}}class Ui extends Cl{constructor(t,e,i){super(t,e,i,i.IsHorizontal)}}class Gr extends Cl{constructor(t,e,i){super(t,e,i,i.IsVertical)}}class Ee{constructor(t,e){t!=null&&(this.PaddedPolyline=mt.PaddedPolylineBoundaryOfNode(t.BoundaryCurve,e),Ee.RoundVerticesAndSimplify(this.PaddedPolyline),this.IsRectangle=this.IsPolylineRectangle(),this.InputShape=t,this.Ports=new Set(this.InputShape.Ports))}get PaddedPolyline(){return this._PaddedPolyline}set PaddedPolyline(t){this._PaddedPolyline=t}get looseVisibilityPolyline(){return this._looseVisibilityPolyline==null&&(this._looseVisibilityPolyline=Ee.CreateLoosePolyline(this.VisibilityPolyline)),this._looseVisibilityPolyline}set looseVisibilityPolyline(t){this._looseVisibilityPolyline=t}GetPortChanges(t){return t.addedPorts=Ps(this.InputShape.Ports,this.Ports),t.removedPorts=Ps(this.Ports,this.InputShape.Ports),t.addedPorts.size===0&&t.removedPorts.size===0?!1:(this.Ports=new Set(this.InputShape.Ports),!0)}get IsInConvexHull(){return this.ConvexHull!=null}get IsGroup(){return this.InputShape!=null&&this.InputShape.IsGroup}get VisibilityBoundingBox(){return this.VisibilityPolyline.boundingBox}get VisibilityPolyline(){return this.ConvexHull!=null?this.ConvexHull.Polyline:this.PaddedPolyline}static CreateSentinel(t,e,i,s){const n=Ee.mk(t,e,s);return n.CreateInitialSides(n.PaddedPolyline.startPoint,i),n}CreateInitialSides(t,e){this.ActiveLowSide=new Ui(this,t,e),this.ActiveHighSide=new Gr(this,t,e),e.IsFlatS(this.ActiveHighSide)&&(this.ActiveHighSide=new Gr(this,this.ActiveHighSide.EndVertex,e))}static mk(t,e,i){const s=new Ee(null,0);return s.PaddedPolyline=at.mkClosedFromPoints([d.RoundPoint(t),d.RoundPoint(e)]),s.Ordinal=i,s}IsPolylineRectangle(){if(this.PaddedPolyline.count!==4)return!1;let t=this.PaddedPolyline.startPoint,e=t.nextOnPolyline,i=j.VectorDirectionPP(t.point,e.point);if(!j.IsPureDirection(i))return!1;do{t=e,e=t.nextOnPolyline;const s=j.DirectionFromPointToPoint(t.point,e.point);if(s!==j.RotateRight(i))return!1;i=s}while(t!==this.PaddedPolyline.startPoint);return!0}static RoundVerticesAndSimplify(t){let e=t.startPoint;do e.point=d.RoundPoint(e.point),e=e.nextOnPolyline;while(e!==t.startPoint);Ee.RemoveCloseAndCollinearVerticesInPlace(t),t.setInitIsRequired()}get IsPrimaryObstacle(){return this.ConvexHull==null||this===this.ConvexHull.PrimaryObstacle}static RemoveCloseAndCollinearVerticesInPlace(t){const e=C.intersectionEpsilon*10;for(let i=t.startPoint.next;i!=null;i=i.next)d.close(i.prev.point,i.point,e)&&(i.next==null?t.RemoveEndPoint():(i.prev.next=i.next,i.next.prev=i.prev));return d.close(t.start,t.end,e)&&t.RemoveStartPoint(),t=t.RemoveCollinearVertices(),t.endPoint.prev!=null&&t.endPoint.prev!==t.startPoint&&d.getTriangleOrientation(t.endPoint.prev.point,t.end,t.start)===k.Collinear&&t.RemoveEndPoint(),t.startPoint.next!=null&&t.endPoint.prev!==t.startPoint&&d.getTriangleOrientation(t.end,t.start,t.startPoint.next.point)===k.Collinear&&t.RemoveStartPoint(),t.setInitIsRequired(),t}get isOverlapped(){return this.clump!==void 0&&this.clump.length>0}get IsSentinel(){return this.InputShape==null}IsInSameClump(t){return this.isOverlapped&&this.clump===t.clump}Close(){this.ActiveLowSide=null,this.ActiveHighSide=null}SetConvexHull(t){this.clump=null,this.IsRectangle=!1,this.ConvexHull=t,this.looseVisibilityPolyline=null}static CreateLoosePolyline(t){const e=mt.CreatePaddedPolyline(t,C.intersectionEpsilon*10);return Ee.RoundVerticesAndSimplify(e),e}get IsTransparentAncestor(){return this.InputShape==null?!1:this.InputShape.IsTransparent}set IsTransparentAncestor(t){this.InputShape.IsTransparent=t}}Ee.FirstSentinelOrdinal=1,Ee.FirstNonSentinelOrdinal=10;class lu{constructor(t,e,i,s){this.IsOverlapped=!1,this.unpaddedToPaddedBorderWeight=bt.NormalWeight,this.ObstaclePort=t,this.UnpaddedBorderIntersect=e,this.OutwardDirection=i;const n=D.mkPP(this.UnpaddedBorderIntersect,it.RectangleBorderIntersect(t.Obstacle.VisibilityBoundingBox,this.UnpaddedBorderIntersect,i)),o=w.getAllIntersections(n,t.Obstacle.VisibilityPolyline,!0);this.VisibilityBorderIntersect=d.RoundPoint(o[0].x);const a={pacList:null};this.MaxVisibilitySegment=s.CreateMaxVisibilitySegment(this.VisibilityBorderIntersect,this.OutwardDirection,a),this.pointAndCrossingsList=a.pacList,(this.Obstacle.isOverlapped||this.Obstacle.IsGroup&&!this.Obstacle.IsInConvexHull)&&(this.IsOverlapped=s.IntersectionIsInsideAnotherObstacle(null,this.Obstacle,this.VisibilityBorderIntersect,ae.GetInstance(this.OutwardDirection)),(!this.Obstacle.IsGroup||this.IsOverlapped||this.InteriorEdgeCrossesObstacle(s))&&(this.unpaddedToPaddedBorderWeight=bt.OverlappedWeight)),this.Obstacle.IsInConvexHull&&this.unpaddedToPaddedBorderWeight===bt.NormalWeight&&this.SetUnpaddedToPaddedBorderWeightFromHullSiblingOverlaps(s)}get Obstacle(){return this.ObstaclePort.Obstacle}get InitialWeight(){return this.IsOverlapped?bt.OverlappedWeight:bt.NormalWeight}get IsCollinearWithPort(){return j.IsPureDirection(L.GetDirections(this.VisibilityBorderIntersect,this.ObstaclePort.Location))}get IsVertical(){return it.IsVertical(this.MaxVisibilitySegment)}get WantVisibilityIntersection(){return!this.IsOverlapped&&this.CanExtend&&(!this.ObstaclePort.HasCollinearEntrances||this.IsCollinearWithPort)}get CanExtend(){return L.GetDirections(this.MaxVisibilitySegment.start,this.MaxVisibilitySegment.end)!==v.None}SetUnpaddedToPaddedBorderWeightFromHullSiblingOverlaps(t){(this.Obstacle.IsGroup?this.InteriorEdgeCrossesObstacle(t):this.InteriorEdgeCrossesConvexHullSiblings())&&(this.unpaddedToPaddedBorderWeight=bt.OverlappedWeight)}InteriorEdgeCrossesObstacle(t){const e=Z.mkPP(this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect);return this.InteriorEdgeCrossesObstacleRFI(e,i=>i.VisibilityPolyline,Array.from(t.Root.GetLeafRectangleNodesIntersectingRectangle(e)).filter(i=>!i.UserData.IsGroup&&i.UserData!==this.Obstacle).map(i=>i.UserData))}InteriorEdgeCrossesConvexHullSiblings(){const t=Z.mkPP(this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect);return this.InteriorEdgeCrossesObstacleRFI(t,e=>e.PaddedPolyline,this.Obstacle.ConvexHull.Obstacles.filter(e=>e!==this.Obstacle))}InteriorEdgeCrossesObstacleRFI(t,e,i){let s=null;for(const n of i){const o=e(n);if(!it.RectangleInteriorsIntersect(t,o.boundingBox))continue;if(s=s??D.mkPP(this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect),w.intersectionOne(s,o,!1)!=null||ft.Outside!==w.PointRelativeToCurveLocation(this.UnpaddedBorderIntersect,o))return!0}return!1}get HasGroupCrossings(){return this.pointAndCrossingsList!=null&&this.pointAndCrossingsList.Count()>0}HasGroupCrossingBeforePoint(t){if(!this.HasGroupCrossings)return!1;const e=it.IsAscending(this.OutwardDirection)?this.pointAndCrossingsList.First:this.pointAndCrossingsList.Last;return L.GetDirections(this.MaxVisibilitySegment.start,e.Location)===L.GetDirections(e.Location,t)}AddToAdjacentVertex(t,e,i,s){let n=t.VisGraph.FindVertex(this.VisibilityBorderIntersect);if(n!=null){this.ExtendEdgeChain(t,n,n,i,s);return}this.OutwardDirection===L.GetDirections(e.point,this.VisibilityBorderIntersect)?(this.VisibilityBorderIntersect=e.point,n=e):(n=t.FindOrAddVertex(this.VisibilityBorderIntersect),t.FindOrAddEdge(n,e,this.InitialWeight)),this.ExtendEdgeChain(t,n,e,i,s)}ExtendEdgeChain(t,e,i,s,n){t.ExtendEdgeChainVRLPB(i,s,this.MaxVisibilitySegment,this.pointAndCrossingsList,this.IsOverlapped);const o=t.FindOrAddVertex(this.UnpaddedBorderIntersect);t.FindOrAddEdge(o,e,this.unpaddedToPaddedBorderWeight),n&&t.ConnectVertexToTargetVertex(this.ObstaclePort.CenterVertex,o,this.OutwardDirection,this.InitialWeight)}toString(){return Se.Qf.Format("{0} {1}~{2} {3}",this.ObstaclePort.Location,this.UnpaddedBorderIntersect,this.VisibilityBorderIntersect,this.OutwardDirection)}}class hu{constructor(t,e){this.HasCollinearEntrances=!1,this.VisibilityRectangle=Z.mkEmpty(),this.Port=t,this.Obstacle=e,this.PortEntrances=new Array,this.Location=d.RoundPoint(this.Port.Location)}CreatePortEntrance(t,e,i){const s=new lu(this,t,e,i);this.PortEntrances.push(s),this.VisibilityRectangle.add(s.MaxVisibilitySegment.end),this.HasCollinearEntrances=this.HasCollinearEntrances||s.IsCollinearWithPort}ClearVisibility(){this.PortEntrances=[]}AddToGraph(t,e){e&&(this.CenterVertex=t.FindOrAddVertex(this.Location))}RemoveFromGraph(){this.CenterVertex=null}get LocationHasChanged(){return!d.closeDistEps(this.Location,d.RoundPoint(this.Port.Location))}get PortCurve(){return this.Port.Curve}get PortLocation(){return this.Port.Location}toString(){return this.Port+this.Obstacle.toString()}}class uu{constructor(t,e){this.maxVisibilitySegmentsAndCrossings=new Array(4),this.OutOfBoundsDirectionFromGraph=v.None,this.GetVertex(t,e)}get Point(){return this.Vertex.point}get InitialWeight(){return this.IsOverlapped?bt.OverlappedWeight:bt.NormalWeight}get IsOutOfBounds(){return v.None!==this.OutOfBoundsDirectionFromGraph}GetVertex(t,e){this.Vertex=t.FindOrAddVertex(e)}AddEdgeToAdjacentEdge(t,e,i,s){const n=it.SegmentIntersectionEP(e,this.Point);let o=t.VisGraph.FindVertex(n);return o!=null?this.AddToAdjacentVertex(t,o,i,s):o=t.AddEdgeToTargetEdge(this.Vertex,e,n),this.ExtendEdgeChain(t,o,i,s),o}AddToAdjacentVertex(t,e,i,s){L.EqualPP(this.Point,e.point)||t.FindOrAddEdge(this.Vertex,e,this.InitialWeight),this.ExtendEdgeChain(t,e,i,s)}ExtendEdgeChain(t,e,i,s){let n=this.IsOverlapped;n&&(n=t.ObstacleTree.PointIsInsideAnObstaclePD(e.point,i));const o=this.GetSegmentAndCrossings(this.IsOverlapped?e:this.Vertex,i,t);t.ExtendEdgeChainVRLPB(e,s,o[0],o[1],n)}GetSegmentAndCrossings(t,e,i){const s=j.ToIndex(e);let n=this.maxVisibilitySegmentsAndCrossings[s];if(n==null){const o={pacList:null};n=[i.ObstacleTree.CreateMaxVisibilitySegment(t.point,e,o),o.pacList],this.maxVisibilitySegmentsAndCrossings[s]=n}else L.GetDirections(t.point,n[0].start)===e&&(n[0].start=t.point);return n}MaxVisibilityInDirectionForNonOverlappedFreePoint(t,e){return this.GetSegmentAndCrossings(this.Vertex,t,e)[0].end}AddOobEdgesFromGraphCorner(t,e){const i=L.GetDirections(e,this.Vertex.point),s=t.VisGraph.FindVertex(e);t.ConnectVertexToTargetVertex(s,this.Vertex,i&(v.North|v.South),bt.NormalWeight),t.ConnectVertexToTargetVertex(s,this.Vertex,i&(v.East|v.West),bt.NormalWeight)}RemoveFromGraph(){this.Vertex=null}toString(){return this.Vertex.toString()}}class ma{constructor(t,e){this.BoundaryWidth=C.distanceEpsilon,this.Group=t,this.DirectionToInside=e}GetInteriorVertexPoint(t){return d.RoundPoint(t.add(j.toPoint(this.DirectionToInside).mul(this.BoundaryWidth)))}toString(){return Se.Qf.Format("{0} {1}",this.DirectionToInside,this.Group)}}ma.BoundaryWidth=C.distanceEpsilon;class Pa extends Ai{constructor(t){super(),this.site=t}get Site(){return this.site}}class Mo extends bs{constructor(t,e){super(e),this.Obstacle=t}}class Vo extends Mo{constructor(t,e){super(t,e)}}class cu{constructor(t){this.Coord=t}AddPendingPerpendicularCoord(t){this.pendingPerpCoords==null&&(this.pendingPerpCoords=new Array),this.pendingPerpCoords.push(t)}ResetForIntersections(){this.CurrentSegment=this.FirstSegment}get IsHorizontal(){return!this.FirstSegment.IsVertical}TraverseToSegmentContainingPoint(t){if(this.CurrentSegment.ContainsPoint(t))return!0;const e=this.IsHorizontal?t.y:t.x;if(!L.Equal(this.Coord,e)){for(;this.MoveNext(););return!1}for(;;){if((this.CurrentSegment.NextSegment==null||L.GetDirections(this.CurrentSegment.End,t)==L.GetDirections(t,this.CurrentSegment.NextSegment.Start))&&d.closeIntersections(this.CurrentSegment.End,t))return this.CurrentSegment.Update(this.CurrentSegment.Start,t),!0;if(!this.MoveNext())return!1;if(this.CurrentSegment.ContainsPoint(t))return!0;if(L.IsPureLower(t,this.CurrentSegment.Start))return this.CurrentSegment.Update(t,this.CurrentSegment.End),!0}}MoveNext(){return this.CurrentSegment=this.CurrentSegment.NextSegment,this.HasCurrent}get HasCurrent(){return this.CurrentSegment!=null}PointIsCurrentEndAndNextStart(t){return t.equal(this.CurrentSegment.End)&&this.CurrentSegment.NextSegment!=null&&t.equal(this.CurrentSegment.NextSegment.Start)}AddPerpendicularCoord(t){const e=this.IsHorizontal?new d(t,this.Coord):new d(this.Coord,t);this.TraverseToSegmentContainingPoint(e),this.CurrentSegment.AddSparseVertexCoord(t)}toString(){return this.FirstSegment==null?"-0- "+this.Coord:this.IsHorizontal?"(H) Y === "+this.Coord:"(V) X === "}AppendScanSegment(t){this.FirstSegment==null?this.FirstSegment=t:this.CurrentSegment.NextSegment=t,this.CurrentSegment=t}AddPendingPerpendicularCoordsToScanSegments(){if(this.pendingPerpCoords!=null){this.ResetForIntersections();for(const t of this.pendingPerpCoords)this.AddPerpendicularCoord(t)}}}class El{constructor(t,e){this.CurrentSlotIndex=0,this.vector=[],this.IsHorizontal=e;const i=Array.from(t).sort((s,n)=>s>n?1:s<n?-1:0);for(const s of i)this.vector.push(new cu(s))}get Length(){return this.vector.length}get CurrentSlot(){return this.vector[this.CurrentSlotIndex]}Item(t){return this.vector[t]}CreateScanSegment(t,e,i,s){this.CurrentSlot.AppendScanSegment(new bt(t,e,i,s))}ScanSegmentsCompleteForCurrentSlot(){this.CurrentSlotIndex++}ScanSegmentsComplete(){for(const t of this.vector)t.AddPendingPerpendicularCoordsToScanSegments()}Items(){return this.vector}ResetForIntersections(){for(const t of this.vector)t.ResetForIntersections()}FindNearest(t,e){let i=0,s=this.vector.length-1;if(t<=this.vector[i].Coord)return i;if(t>=this.vector[s].Coord)return s;for(;s-i>2;){const n=i+(s-i>>1),o=this.vector[n];if(t<o.Coord){s=n;continue}if(t>o.Coord){i=n;continue}return n}for(i++;i<=s;i++){const n=this.vector[i];if(t<n.Coord)return e>0?i:i-1;if(t===n.Coord)break}return i}CreateSparseVerticesAndEdges(t){for(const e of this.vector){e.ResetForIntersections();for(let i=e.FirstSegment;i!=null;i=i.NextSegment)i.CreateSparseVerticesAndEdges(t)}}GetParallelCoord(t){return this.IsHorizontal?t.y:t.x}GetPerpendicularCoord(t){return this.IsHorizontal?t.x:t.y}ConnectAdjoiningSegmentEndpoints(){for(const t of this.vector){t.ResetForIntersections();let e=t.FirstSegment;for(let i=e.NextSegment;i!=null;i=i.NextSegment){if(i.HasSparsePerpendicularCoords&&e.HasSparsePerpendicularCoords&&i.Start===e.End){const s=this.GetPerpendicularCoord(i.Start);e.AddSparseEndpoint(s),i.AddSparseEndpoint(s)}e=i}}}toString(){return(this.IsHorizontal?"(H) count":"(V) count === ")+this.vector.length}}class Pn extends Ai{constructor(t,e,i){super(),this.InitialObstacle=t,this.ReflectingObstacle=e,this.site=i}static mk(t,e,i){const s=new Pn(t.ReflectingObstacle,e,i);return s.PreviousSite=t,s}IsStaircaseStep(t){return this.InitialObstacle===t}get Site(){return this.site}}class bl{constructor(){this.eventTree=new Cr((t,e)=>this.Compare(t,e))}Reset(t){this.scanDirection=t}Enqueue(t){this.eventTree.Enqueue(t)}Dequeue(){return this.eventTree.Dequeue()}get Count(){return this.eventTree.Count}Compare(t,e){if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;let i=this.scanDirection.ComparePerpCoord(t.Site,e.Site);if(i)return i;const s=t instanceof Pn?0:1,n=e instanceof Pn?0:1;return i=s-n,i||this.scanDirection.CompareScanCoord(t.Site,e.Site)}}class Al{constructor(){this.pointCrossingMap=new si,this.pointList=new Array}AddIntersection(t,e,i){let s=this.pointCrossingMap.get(t);s||(s=new Array,this.pointCrossingMap.set(t,s));const n=s.length;for(let a=0;a<n;a++){const h=s[a];if(h.Group===e)return h}const o=new ma(e,i);return s.push(o),o}Clear(){this.pointCrossingMap.clear()}GetOrderedListBetween(t,e){if(this.pointCrossingMap.size===0)return null;if(L.ComparePP(t,e)>0){const n=t;t=e,e=n}this.pointList=[];for(const n of this.pointCrossingMap.keys())L.ComparePP(n,t)>=0&&L.ComparePP(n,e)<=0&&this.pointList.push(n);this.pointList.sort((n,o)=>n.compareTo(o));const i=new Nr,s=this.pointList.length;for(let n=0;n<s;n++){const o=this.pointList[n];i.Add(o,this.pointCrossingMap.get(o))}return i}toString(){return Se.Qf.Format("{0}",this.pointCrossingMap.size)}}class wl extends Pn{constructor(t,e,i){super(t.ReflectingObstacle,e.Obstacle,i),this.Side=e}}class du{constructor(t){this.staleSites=new Array,this.scanDirection=t,this.eventTree=new Qe((e,i)=>this.CompareBB(e,i)),this.findFirstPred=e=>this.CompareToFindFirstPoint(e.Site)>=0}Add(t){this.eventTree.insert(t)}MarkStaleSite(t){this.staleSites.push(t)}RemoveStaleSites(){const t=this.staleSites.length;if(t>0){for(let e=0;e<t;e++)this.RemoveExact(this.staleSites[e]);this.staleSites=[]}}RemoveSitesForFlatBottom(t,e){for(let i=this.FindFirstInRange(t,e);i!=null;i=this.FindNextInRange(i,e))this.MarkStaleSite(i.item);this.RemoveStaleSites()}Find(t){return this.FindFirstInRange(t,t)}RemoveExact(t){const e=this.eventTree.find(t);return e!=null&&e.item.Site===t.Site?(this.eventTree.deleteNodeInternal(e),!0):!1}FindFirstInRange(t,e){this.findFirstPoint=t;const i=this.eventTree.findFirst(this.findFirstPred);return i!=null&&this.Compare(i.item.Site,e)<=0?i:null}CompareToFindFirstPoint(t){return this.Compare(t,this.findFirstPoint)}FindNextInRange(t,e){const i=this.eventTree.next(t);return i!=null&&this.Compare(i.item.Site,e)<=0?i:null}CompareBB(t,e){return this.scanDirection.CompareScanCoord(t.Site,e.Site)}Compare(t,e){return this.scanDirection.CompareScanCoord(t,e)}}class vl extends Mo{constructor(t,e){super(t,e)}}class Il extends Mo{constructor(t,e){super(t,e)}}class Tl extends Mo{constructor(t,e){super(t,e)}}class xl extends Pn{constructor(t,e,i){super(t.ReflectingObstacle,e.obstacle,i),this.Side=e}}class Ol{get LowNeighborSide(){return this.LowNeighbor==null?null:this.LowNeighbor.item}get HighNeighborSide(){return this.HighNeighbor==null?null:this.HighNeighbor.item}Clear(){this.LowNeighbor=null,this.LowOverlapEnd=null,this.GroupSideInterveningBeforeLowNeighbor=null,this.HighNeighbor=null,this.HighOverlapEnd=null,this.GroupSideInterveningBeforeHighNeighbor=null}SetSides(t,e,i,s){if(it.IsAscending(t)){this.HighNeighbor=e,this.HighOverlapEnd=i,this.GroupSideInterveningBeforeHighNeighbor=s;return}this.LowNeighbor=e,this.LowOverlapEnd=i,this.GroupSideInterveningBeforeLowNeighbor=s}}class ji{constructor(){this.arrayOfSets=new Array}has(t){return this.hasxy(t.x,t.y)}remove(t){if(!(t.x<0||t.x>=this.arrayOfSets.length))return this.arrayOfSets[t.x].delete(t.y)}hasxy(t,e){if(t<0||t>=this.arrayOfSets.length)return!1;const i=this.arrayOfSets[t];return i!==void 0&&i.has(e)}static mk(t){const e=new ji;for(const i of t)e.add(i);return e}*values(){for(let t=0;t<this.arrayOfSets.length;t++){const e=this.arrayOfSets[t];if(e)for(const i of e.values())yield new Ot(t,i)}}add(t){let e=this.arrayOfSets[t.x];e==null&&(this.arrayOfSets[t.x]=e=new Set),e.add(t.y)}addNN(t,e){let i=this.arrayOfSets[t];i==null&&(this.arrayOfSets[t]=i=new Set),i.add(e)}clear(){for(const t of this.arrayOfSets)t&&t.clear()}}class Ll{constructor(t,e){this.Polyline=t,this.Obstacles=Array.from(e),this.PrimaryObstacle=this.Obstacles[0],Ee.RoundVerticesAndSimplify(this.Polyline)}}class Zn{static MungeClosestIntersectionInfo(t,e,i){const s=e.seg1.boundingBox,n=d.RoundPoint(e.x).clone();return i?new d(Zn.MungeIntersect(t.x,n.x,s.left,s.right),n.y):new d(n.x,Zn.MungeIntersect(t.y,n.y,s.bottom,s.top))}static MungeIntersect(t,e,i,s){if(t<e){const n=Math.min(i,s);e<n&&(e=n)}else if(t>e){const n=Math.max(i,s);e>n&&(e=n)}return d.RoundDouble(e)}}class le{constructor(){this.CurrentGroupBoundaryCrossingMap=new Al,this.overlapPairs=new ji,this.hasOverlaps=!1,this.lookupIntPair=new Ot(-1,-1)}get GraphBox(){return this.Root.irect}Init(t,e,i){this.CreateObstacleListAndOrdinals(t),this.AncestorSets=e,this.CreateRoot(),this.shapeIdToObstacleMap=i}CreateObstacleListAndOrdinals(t){this.allObstacles=Array.from(t);let e=Ee.FirstNonSentinelOrdinal;for(const i of this.allObstacles)i.Ordinal=e++}OrdinalToObstacle(t){return this.allObstacles[t-Ee.FirstNonSentinelOrdinal]}CreateRoot(){this.Root=le.CalculateHierarchy(this.GetAllObstacles()),this.OverlapsExist()&&(this.AccreteClumps(),this.AccreteConvexHulls(),this.GrowGroupsToAccommodateOverlaps(),this.Root=le.CalculateHierarchy(this.GetAllObstacles().filter(t=>t.IsPrimaryObstacle)))}OverlapsExist(){return this.Root==null?!1:(Ae(this.Root,this.Root,(t,e)=>this.CheckForInitialOverlaps(t,e)),this.hasOverlaps)}OverlapPairAlreadyFound(t,e){return this.lookupIntPair.x=e.Ordinal,this.lookupIntPair.y=t.Ordinal,this.overlapPairs.has(this.lookupIntPair)}CheckForInitialOverlaps(t,e){if(this.hasOverlaps)return;const i={bIsInsideA:!1,aIsInsideB:!1};if(le.ObstaclesIntersect(t,e,i)){this.hasOverlaps=!0;return}!i.aIsInsideB&&!i.bIsInsideA||t.IsGroup&&e.IsGroup||t.IsGroup&&i.bIsInsideA||e.IsGroup&&i.aIsInsideB||(this.hasOverlaps=!0)}AccreteClumps(){this.AccumulateObstaclesForClumps(),this.CreateClumps()}AccreteConvexHulls(){for(;;)if(this.AccumulateObstaclesForConvexHulls(),!this.CreateConvexHulls())return}static CalculateHierarchy(t){const e=Array.from(t).map(i=>pe(i,i.VisibilityBoundingBox));return re(e)}AccumulateObstaclesForClumps(){this.overlapPairs.clear();const t=le.CalculateHierarchy(this.GetAllObstacles().filter(e=>!e.IsGroup&&e.IsRectangle));t!=null&&Me(t,t,(e,i)=>this.EvaluateOverlappedPairForClump(e,i))}EvaluateOverlappedPairForClump(t,e){if(t===e||this.OverlapPairAlreadyFound(t,e))return;const i={bIsInsideA:!1,aIsInsideB:!1};!le.ObstaclesIntersect(t,e,i)&&!i.aIsInsideB&&!i.bIsInsideA||this.overlapPairs.add(new Ot(t.Ordinal,e.Ordinal))}AccumulateObstaclesForConvexHulls(){this.overlapPairs.clear();const t=le.CalculateHierarchy(this.GetAllObstacles().filter(e=>e.IsPrimaryObstacle&&!e.IsGroup));t!=null&&Me(t,t,(e,i)=>this.EvaluateOverlappedPairForConvexHull(e,i))}EvaluateOverlappedPairForConvexHull(t,e){if(t===e||this.OverlapPairAlreadyFound(t,e))return;const i={bIsInsideA:!1,aIsInsideB:!1};!le.ObstaclesIntersect(t,e,i)&&!i.aIsInsideB&&!i.bIsInsideA||!t.IsInConvexHull&&!e.IsInConvexHull&&t.IsRectangle&&e.IsRectangle||(this.overlapPairs.add(new Ot(t.Ordinal,e.Ordinal)),this.AddClumpToConvexHull(t),this.AddClumpToConvexHull(e),this.AddConvexHullToConvexHull(t),this.AddConvexHullToConvexHull(e))}GrowGroupsToAccommodateOverlaps(){for(;;)if(this.AccumulateObstaclesForGroupOverlaps(),!this.GrowGroupsToResolveOverlaps())return}AccumulateObstaclesForGroupOverlaps(){const t=le.CalculateHierarchy(this.GetAllObstacles().filter(i=>i.IsGroup)),e=le.CalculateHierarchy(this.GetAllObstacles().filter(i=>i.IsPrimaryObstacle));t==null||e==null||Me(t,e,(i,s)=>this.EvaluateOverlappedPairForGroup(i,s))}EvaluateOverlappedPairForGroup(t,e){if(t===e||this.OverlapPairAlreadyFound(t,e))return;const i={bIsInsideA:!1,aIsInsideB:!1},s=le.ObstaclesIntersect(t,e,i);if(!(!s&&!i.aIsInsideB&&!i.bIsInsideA)){if(t.IsRectangle&&e.IsRectangle){e.IsGroup||(i.aIsInsideB||le.FirstRectangleContainsACornerOfTheOther(e.VisibilityBoundingBox,t.VisibilityBoundingBox))&&(e.OverlapsGroupCorner=!0);return}!s&&(e.IsGroup||i.bIsInsideA)||this.overlapPairs.add(new Ot(t.Ordinal,e.Ordinal))}}static FirstRectangleContainsACornerOfTheOther(t,e){return t.contains(e.leftBottom)||t.contains(e.leftTop)||t.contains(e.rightTop)||t.contains(e.rightBottom)}static FirstPolylineStartIsInsideSecondPolyline(t,e){return w.PointRelativeToCurveLocation(t.start,e)!==ft.Outside}AddClumpToConvexHull(t){if(t.isOverlapped){for(const e of t.clump.filter(i=>i.Ordinal!==t.Ordinal))this.overlapPairs.add(new Ot(t.Ordinal,e.Ordinal));t.clump=[]}}AddConvexHullToConvexHull(t){if(t.IsInConvexHull){for(const e of t.ConvexHull.Obstacles.filter(i=>i.Ordinal!==t.Ordinal))this.overlapPairs.add(new Ot(t.Ordinal,e.Ordinal));t.ConvexHull.Obstacles=[]}}CreateClumps(){const t=ln(Array.from(this.overlapPairs.values())),e=Vi(t);for(const i of e){if(i.length===1)continue;const s=i.map(n=>this.OrdinalToObstacle(n));for(const n of s)n.clump=s}}CreateConvexHulls(){let t=!1;const e=ln(Array.from(this.overlapPairs.values())),i=Vi(e);for(const s of i){if(s.length===1)continue;t=!0;const n=s.map(this.OrdinalToObstacle),o=Zs(n,h=>h.VisibilityPolyline),a=new Ll(yt.createConvexHullAsClosedPolyline(o),n);for(const h of n)h.SetConvexHull(a)}return t}GrowGroupsToResolveOverlaps(){let t=!1;for(const e of this.overlapPairs.values()){t=!0;const i=this.OrdinalToObstacle(e.x),s=this.OrdinalToObstacle(e.y);le.ResolveGroupAndGroupOverlap(i,s)||le.ResolveGroupAndObstacleOverlap(i,s)}return this.overlapPairs.clear(),t}static ResolveGroupAndGroupOverlap(t,e){return e.IsGroup?(t.VisibilityPolyline.boundingBox.area>e.VisibilityPolyline.boundingBox.area?le.ResolveGroupAndObstacleOverlap(t,e):le.ResolveGroupAndObstacleOverlap(e,t),!0):!1}static ResolveGroupAndObstacleOverlap(t,e){let i=e.looseVisibilityPolyline;le.GrowGroupAroundLoosePolyline(t,i);const s={bIsInsideA:!1,aIsInsideB:!1};for(;le.ObstaclesIntersect(e,t,s)||!s.aIsInsideB;)i=Ee.CreateLoosePolyline(i),le.GrowGroupAroundLoosePolyline(t,i)}static GrowGroupAroundLoosePolyline(t,e){const i=Array.from(t.VisibilityPolyline).concat(Array.from(e));t.SetConvexHull(new Ll(yt.createConvexHullAsClosedPolyline(i),[t]))}static ObstaclesIntersect(t,e,i){return w.CurvesIntersect(t.VisibilityPolyline,e.VisibilityPolyline)?(i.aIsInsideB=!1,i.bIsInsideA=!1,!0):(i.aIsInsideB=le.FirstPolylineStartIsInsideSecondPolyline(t.VisibilityPolyline,e.VisibilityPolyline),i.bIsInsideA=!i.aIsInsideB&&le.FirstPolylineStartIsInsideSecondPolyline(e.VisibilityPolyline,t.VisibilityPolyline),t.IsRectangle&&e.IsRectangle?!1:le.ObstaclesAreCloseEnoughToBeConsideredTouching(t,e,i.aIsInsideB,i.bIsInsideA)?(i.aIsInsideB=!1,i.bIsInsideA=!1,!0):!1)}static ObstaclesAreCloseEnoughToBeConsideredTouching(t,e,i,s){if(!i&&!s)return w.CurvesIntersect(t.looseVisibilityPolyline,e.VisibilityPolyline);const n=i?t.looseVisibilityPolyline:e.looseVisibilityPolyline,o=i?e.VisibilityPolyline:t.VisibilityPolyline;for(const a of n)if(w.PointRelativeToCurveLocation(a,o)===ft.Outside){const h=w.ClosestPoint(o,a);if(!d.closeIntersections(a,h))return!0}return!1}AdjustSpatialAncestors(){if(this.SpatialAncestorsAdjusted)return!1;for(const e of this.GetAllGroups()){const i=e.VisibilityBoundingBox;for(const s of this.Root.GetNodeItemsIntersectingRectangle(i))if(s!==e&&w.ClosedCurveInteriorsIntersect(s.VisibilityPolyline,e.VisibilityPolyline)){if(s.IsInConvexHull)for(const n of s.ConvexHull.Obstacles)this.AncestorSets.get(n.InputShape).add(e.InputShape);this.AncestorSets.get(s.InputShape).add(e.InputShape)}}let t=new Array;for(const e of this.Root.GetAllLeaves()){const i=e.VisibilityBoundingBox;t=t.concat(Array.from(this.AncestorSets.get(e.InputShape)).filter(s=>!i.intersects(this.shapeIdToObstacleMap.get(s).VisibilityBoundingBox)));for(const s of t)this.AncestorSets.get(e.InputShape).delete(s);t=[]}return this.SpatialAncestorsAdjusted=!0,!0}GetAllGroups(){return this.GetAllObstacles().filter(t=>t.IsGroup)}Clear(){this.Root=null,this.AncestorSets=null}CreateMaxVisibilitySegment(t,e,i){const s=it.RectangleBorderIntersect(this.GraphBox,t,e);if(L.GetDirections(t,s)===v.None)return i.pacList=null,D.mkPP(t,t);const n=this.RestrictSegmentWithObstacles(t,s);return i.pacList=this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(n.start,n.end),n}GetAllObstacles(){return this.allObstacles}GetAllPrimaryObstacles(){return this.Root.GetAllLeaves()}IntersectionIsInsideAnotherObstacle(t,e,i,s){return this.insideHitTestIgnoreObstacle1=e,this.insideHitTestIgnoreObstacle2=t,this.insideHitTestScanDirection=s,this.Root.FirstHitNodeWithPredicate(i,this.InsideObstacleHitTest.bind(this))!=null}PointIsInsideAnObstaclePD(t,e){return this.PointIsInsideAnObstacle(t,ae.GetInstance(e))}PointIsInsideAnObstacle(t,e){return this.insideHitTestIgnoreObstacle1=null,this.insideHitTestIgnoreObstacle2=null,this.insideHitTestScanDirection=e,this.Root.FirstHitNodeWithPredicate(t,this.InsideObstacleHitTest.bind(this))!=null}InsideObstacleHitTest(t,e){if(e===this.insideHitTestIgnoreObstacle1||e===this.insideHitTestIgnoreObstacle2||e.IsGroup||!it.PointIsInRectangleInterior(t,e.VisibilityBoundingBox))return $t.Continue;const i=it.RectangleBorderIntersect(e.VisibilityBoundingBox,t,this.insideHitTestScanDirection.dir).add(this.insideHitTestScanDirection.DirectionAsPoint),s=it.RectangleBorderIntersect(e.VisibilityBoundingBox,t,this.insideHitTestScanDirection.OppositeDirection).sub(this.insideHitTestScanDirection.DirectionAsPoint),n=D.mkPP(s,i),o=w.getAllIntersections(n,e.VisibilityPolyline,!0);if(o.length===2){const a=d.RoundPoint(o[0].x),h=d.RoundPoint(o[1].x);if(!L.EqualPP(t,a)&&!L.EqualPP(t,h)&&t.compareTo(a)!==t.compareTo(h)&&!N(Math.floor(o[0].par1),Math.floor(o[1].par1)))return $t.Stop}return $t.Continue}SegmentCrossesAnObstacle(t,e){this.stopAtGroups=!0,this.wantGroupCrossings=!1;const i=this.RestrictSegmentPrivate(t,e);return!L.EqualPP(i.end,e)}SegmentCrossesANonGroupObstacle(t,e){this.stopAtGroups=!1,this.wantGroupCrossings=!1;const i=this.RestrictSegmentPrivate(t,e);return!L.EqualPP(i.end,e)}RestrictSegmentWithObstacles(t,e){return this.stopAtGroups=!1,this.wantGroupCrossings=!0,this.RestrictSegmentPrivate(t,e)}RestrictSegmentPrivate(t,e){return this.GetRestrictedIntersectionTestSegment(t,e),this.currentRestrictedRay=D.mkPP(t,e),this.restrictedRayLengthSquared=t.sub(e).lengthSquared,this.CurrentGroupBoundaryCrossingMap.Clear(),this.RecurseRestrictRayWithObstacles(this.Root),this.currentRestrictedRay}GetRestrictedIntersectionTestSegment(t,e){const i=L.GetDirections(t,e),s=v.West===i?this.GraphBox.right:v.East===i?this.GraphBox.left:t.x,n=v.West===i?this.GraphBox.left:v.East===i?this.GraphBox.right:e.x,o=v.South===i?this.GraphBox.top*2:v.North===i?this.GraphBox.bottom:t.y,a=v.South===i?this.GraphBox.bottom:v.North===i?this.GraphBox.top:t.y;this.restrictedIntersectionTestSegment=D.mkPP(new d(s,o),new d(n,a))}RecurseRestrictRayWithObstacles(t){if(!it.RectangleInteriorsIntersect(this.currentRestrictedRay.boundingBox,t.irect))return;const e=t.UserData;if(e!=null){const i=w.getAllIntersections(this.restrictedIntersectionTestSegment,e.VisibilityPolyline,!0);if(!e.IsGroup||this.stopAtGroups){this.LookForCloserNonGroupIntersectionToRestrictRay(i);return}this.wantGroupCrossings&&this.AddGroupIntersectionsToRestrictedRay(e,i);return}this.RecurseRestrictRayWithObstacles(t.Left),this.RecurseRestrictRayWithObstacles(t.Right)}LookForCloserNonGroupIntersectionToRestrictRay(t){let e=0,i=null,s=this.restrictedRayLengthSquared;const n=L.GetDirections(this.restrictedIntersectionTestSegment.start,this.restrictedIntersectionTestSegment.end);for(const o of t){const a=d.RoundPoint(o.x),h=L.GetDirections(this.currentRestrictedRay.start,a);if(h===j.OppositeDir(n))continue;if(e++,v.None===h){s=0,i=o;continue}const u=a.sub(this.currentRestrictedRay.start).lengthSquared;if(u<s){if(o.x.sub(this.currentRestrictedRay.start).lengthSquared<C.squareOfDistanceEpsilon)continue;s=u,i=o}}if(i!=null){if(e===1){const o=d.RoundPoint(i.x);if(d.closeIntersections(o,this.currentRestrictedRay.start)||d.closeIntersections(o,this.currentRestrictedRay.end))return}this.restrictedRayLengthSquared=s,this.currentRestrictedRay.end=Zn.MungeClosestIntersectionInfo(this.currentRestrictedRay.start,i,!it.IsVerticalPP(this.currentRestrictedRay.start,this.currentRestrictedRay.end))}}AddGroupIntersectionsToRestrictedRay(t,e){for(const i of e){const s=d.RoundPoint(i.x);if(s.sub(this.currentRestrictedRay.start).lengthSquared>this.restrictedRayLengthSquared)continue;const o=L.GetDirections(this.currentRestrictedRay.start,this.currentRestrictedRay.end),a=i.seg1,h=j.VectorDirection(a.derivative(i.par1));let u=o;h&j.RotateRight(o)&&(u=j.OppositeDir(u)),this.CurrentGroupBoundaryCrossingMap.AddIntersection(s,t,u)}}}class gu{constructor(t,e){this.scanDirection=t,this.SideTree=new Qe((i,s)=>this.Compare(i,s)),this.linePositionAtLastInsertOrRemove=e}Insert(t,e){return this.linePositionAtLastInsertOrRemove=e,this.SideTree.insert(t)}get Count(){return this.SideTree.count}Remove(t,e){this.linePositionAtLastInsertOrRemove=e,this.SideTree.remove(t)}Find(t){return this.scanDirection.ComparePerpCoord(this.linePositionAtLastInsertOrRemove,t.Start)===-1?null:this.SideTree.find(t)}NextLowB(t){return this.NextLowR(this.Find(t))}NextLowR(t){return this.SideTree.previous(t)}NextHighB(t){return this.NextHighR(this.Find(t))}NextHighR(t){return this.SideTree.next(t)}Next(t,e){return it.IsAscending(t)?this.SideTree.next(e):this.SideTree.previous(e)}Lowest(){return this.SideTree.treeMinimum()}Compare(t,e){if(t.Obstacle===e.Obstacle)return t===e?0:t instanceof Ui?-1:1;const i=he.ScanLineIntersectSidePBS(this.linePositionAtLastInsertOrRemove,t,this.scanDirection),s=he.ScanLineIntersectSidePBS(this.linePositionAtLastInsertOrRemove,e,this.scanDirection);let n=i.compareTo(s);if(n===0){const o=t instanceof Ui,a=e instanceof Ui;n=f(o,a),n===0&&(n=W(t.Obstacle.Ordinal,e.Obstacle.Ordinal))}return n}}class Wo{constructor(t){this.lookupSegment=bt.mk(new d(0,0),new d(0,1)),this.ScanDirection=t,this.segmentTree=new Qe((e,i)=>this.Compare(e,i)),this.findIntersectorPred=e=>this.CompareIntersector(e),this.findPointPred=e=>this.CompareToPoint(e)}get Segments(){return this.segmentTree.allNodes()}InsertUnique(t){this.AssertValidSegmentForInsertion(t);const e=this.segmentTree.find(t);return e??this.segmentTree.insert(t)}AssertValidSegmentForInsertion(t){}Remove(t){this.segmentTree.remove(t)}Find(t,e){this.lookupSegment.Update(t,e);const i=this.segmentTree.find(this.lookupSegment);return i!=null&&L.EqualPP(i.item.End,e)?i.item:null}FindLowestIntersector(t,e){const i=this.FindLowestIntersectorNode(t,e);return i!=null?i.item:null}FindLowestIntersectorNode(t,e){this.lookupSegment.Update(t,t);let i=this.segmentTree.findLast(this.findIntersectorPred);if(L.EqualPP(t,e))i!=null&&this.ScanDirection.Compare(i.item.End,t)<0&&(i=null);else for(this.lookupSegment.Update(t,e);i!=null&&!i.item.IntersectsSegment(this.lookupSegment);){if(this.ScanDirection.Compare(i.item.Start,e)>0)return null;i=this.segmentTree.next(i)}return i}FindHighestIntersector(t,e){this.lookupSegment.Update(e,e);let i=this.segmentTree.findLast(this.findIntersectorPred);if(L.EqualPP(t,e))i!=null&&this.ScanDirection.Compare(i.item.End,t)<0&&(i=null);else for(this.lookupSegment.Update(t,e);i!=null&&!i.item.IntersectsSegment(this.lookupSegment);){if(this.ScanDirection.Compare(i.item.End,t)<0)return null;i=this.segmentTree.previous(i)}return i!=null?i.item:null}CompareIntersector(t){return this.ScanDirection.Compare(t.Start,this.lookupSegment.Start)<=0}FindSegmentContainingPoint(t,e){return this.FindSegmentOverlappingPoints(t,t,e)}FindSegmentOverlappingPoints(t,e,i){this.lookupSegment.Update(t,e);const s=this.segmentTree.findFirst(this.findPointPred);if(s!=null){const n=s.item;if(this.ScanDirection.Compare(n.Start,e)<=0)return n}return null}CompareToPoint(t){return this.ScanDirection.Compare(t.End,this.lookupSegment.Start)>=0}MergeAndRemoveNextNode(t,e){return this.ScanDirection.Compare(t.End,e.item.End)===-1&&t.Update(t.Start,e.item.End),t.MergeGroupBoundaryCrossingList(e.item.GroupBoundaryPointAndCrossingsList),this.segmentTree.deleteNodeInternal(e),this.segmentTree.find(t)}MergeSegments(){if(this.segmentTree.count<2)return;let t=this.segmentTree.treeMinimum(),e=this.segmentTree.next(t);for(;e!=null;e=this.segmentTree.next(t))switch(this.ScanDirection.Compare(e.item.Start,t.item.End)){case 1:t=e;break;case 0:e.item.IsOverlapped===t.item.IsOverlapped?t=this.MergeAndRemoveNextNode(t.item,e):(t.item.NeedEndOverlapVertex=!0,e.item.NeedStartOverlapVertex=!0,t=e);break;default:if(t.item.IsOverlapped!==e.item.IsOverlapped){if(t.item.IsOverlapped)t.item.Start===e.item.Start?t=this.MergeAndRemoveNextNode(e.item,t):(t.item.Update(t.item.Start,e.item.Start),t=e);else if(t.item.End===e.item.End)t=this.MergeAndRemoveNextNode(t.item,e);else{const s=e.item,n=t.item;this.segmentTree.deleteNodeInternal(e),s.Update(n.End,s.End),this.segmentTree.insert(s),s.TrimGroupBoundaryCrossingList(),t=this.segmentTree.find(n)}break}t=this.MergeAndRemoveNextNode(t.item,e);break}}Compare(t,e){if(t===e)return 0;if(t==null)return-1;if(e==null)return 1;let i=this.ScanDirection.Compare(t.Start,e.Start);return i===0&&(i=this.ScanDirection.Compare(t.End,e.End)*-1),i}}class fu extends os{constructor(t){super(t)}SetVertexEntry(t){this.VertexEntries==null&&(this.VertexEntries=new Array(4)),this.VertexEntries[j.ToIndex(t.Direction)]=t}RemoveVertexEntries(){this.VertexEntries=null}}class he{constructor(t){this.ObstacleTree=new le,this.CurrentGroupBoundaryCrossingMap=new Al,this.LowNeighborSides=new Ol,this.HighNeighborSides=new Ol,this.ScanDirection=ae.HorizontalInstance,this.eventQueue=new bl,this.HorizontalScanSegments=new Wo(ae.HorizontalInstance),this.VerticalScanSegments=new Wo(ae.VerticalInstance),this.wantReflections=t}get ParallelScanSegments(){return this.ScanDirection.IsHorizontal?this.HorizontalScanSegments:this.VerticalScanSegments}get PerpendicularScanSegments(){return this.ScanDirection.IsHorizontal?this.VerticalScanSegments:this.HorizontalScanSegments}static NewVisibilityGraph(){const t=new se;return t.VertexFactory=e=>new fu(e),t}GenerateVisibilityGraph(){if(this.ObstacleTree.Root==null)return;this.InitializeEventQueue(ae.HorizontalInstance);let t=Ee.FirstSentinelOrdinal,e=new d(this.ObstacleTree.GraphBox.left-he.SentinelOffset,this.ObstacleTree.GraphBox.bottom-he.SentinelOffset),i=new d(this.ObstacleTree.GraphBox.left-he.SentinelOffset,this.ObstacleTree.GraphBox.top+he.SentinelOffset),s=Ee.CreateSentinel(e,i,this.ScanDirection,t++);this.scanLine.Insert(s.ActiveHighSide,this.ObstacleTree.GraphBox.leftBottom),e=new d(this.ObstacleTree.GraphBox.right+he.SentinelOffset,this.ObstacleTree.GraphBox.bottom-he.SentinelOffset),i=new d(this.ObstacleTree.GraphBox.right+he.SentinelOffset,this.ObstacleTree.GraphBox.top+he.SentinelOffset),s=Ee.CreateSentinel(e,i,this.ScanDirection,t++),this.scanLine.Insert(s.ActiveLowSide,this.ObstacleTree.GraphBox.leftBottom),this.ProcessEvents(),this.InitializeEventQueue(ae.VerticalInstance),e=new d(this.ObstacleTree.GraphBox.left-he.SentinelOffset,this.ObstacleTree.GraphBox.bottom-he.SentinelOffset),i=new d(this.ObstacleTree.GraphBox.right+he.SentinelOffset,this.ObstacleTree.GraphBox.bottom-he.SentinelOffset),s=Ee.CreateSentinel(e,i,this.ScanDirection,t++),this.scanLine.Insert(s.ActiveHighSide,this.ObstacleTree.GraphBox.leftBottom),e=new d(this.ObstacleTree.GraphBox.left-he.SentinelOffset,this.ObstacleTree.GraphBox.top+he.SentinelOffset),i=new d(this.ObstacleTree.GraphBox.right+he.SentinelOffset,this.ObstacleTree.GraphBox.top+he.SentinelOffset),s=Ee.CreateSentinel(e,i,this.ScanDirection,t),this.scanLine.Insert(s.ActiveLowSide,this.ObstacleTree.GraphBox.leftBottom),this.ProcessEvents()}static ScanLineIntersectSidePBS(t,e,i){const s=e.Direction;let n=e.Start.x,o=e.Start.y;return i.IsHorizontal?(n+=s.x/s.y*(t.y-e.Start.y),n=Zn.MungeIntersect(t.x,n,e.Start.x,e.End.x),o=t.y):(n=t.x,o+=s.y/s.x*(t.x-e.Start.x),o=Zn.MungeIntersect(t.y,o,e.Start.y,e.End.y)),new d(n,o)}GetOpenVertex(t){let e=t.startPoint,i=this.TraversePolylineForEvents(e),s=this.PointCompare(i.point,e.point);for(;;i=this.TraversePolylineForEvents(i)){const n=this.PointCompare(i.point,e.point);if(n<=0)e=i;else if(n>0&&s<=0)break;s=n}return e}TraversePolylineForEvents(t){return this.ScanDirection.IsHorizontal?t.nextOnPolyline:t.prevOnPolyline}InitializeEventQueue(t){this.ScanDirection=t,this.eventQueue.Reset(this.ScanDirection),this.EnqueueBottomVertexEvents(),this.scanLine=new gu(this.ScanDirection,this.ObstacleTree.GraphBox.leftBottom),this.lookaheadScan=new du(this.ScanDirection)}EnqueueBottomVertexEvents(){for(const t of this.ObstacleTree.GetAllPrimaryObstacles()){const e=this.GetOpenVertex(t.VisibilityPolyline);this.eventQueue.Enqueue(new Vo(t,e))}}IsFlat(t){return this.ScanDirection.IsFlatS(t)}IsPerpendicular(t){return this.ScanDirection.IsPerpendicularS(t)}ScanLineIntersectSide(t,e){return he.ScanLineIntersectSidePBS(t,e,this.ScanDirection)}SideReflectsUpward(t){return t instanceof Ui?this.ScanDirection.Coord(t.End)>this.ScanDirection.Coord(t.Start):this.ScanDirection.Coord(t.End)<this.ScanDirection.Coord(t.Start)}SideReflectsDownward(t){return t instanceof Ui?this.ScanDirection.Coord(t.End)<this.ScanDirection.Coord(t.Start):this.ScanDirection.Coord(t.End)>this.ScanDirection.Coord(t.Start)}StoreLookaheadSite(t,e,i,s){if(this.wantReflections&&!this.IsPerpendicular(e)){if(!s&&!it.PointIsInRectangleInterior(i,e.Obstacle.VisibilityBoundingBox))return;this.SideReflectsUpward(e)&&this.lookaheadScan.Find(i)==null&&this.lookaheadScan.Add(new Pn(t,e.Obstacle,i))}}LoadReflectionEvents(t){this.LoadReflectionEventsBB(t,t)}LoadReflectionEventsBB(t,e){if(t==null||this.SideReflectsUpward(t)||this.IsPerpendicular(t))return;const i=Z.mkPP(t.Start,t.End),s=Z.mkPP(e.Start,e.End);if(this.ScanDirection.IsHorizontal?!i.intersectsOnX(s):!i.intersectsOnY(s))return;const n=Z.intersect(i,s),o=n.leftBottom,a=n.rightTop;let h=this.lookaheadScan.FindFirstInRange(o,a);for(;h!=null;){const u=he.ScanLineIntersectSidePBS(h.item.Site,t,this.ScanDirection.PerpendicularInstance);this.ScanDirection.ComparePerpCoord(u,h.item.Site)>0?this.AddReflectionEvent(h.item,t,u):h.item.ReflectingObstacle!==t.Obstacle&&this.lookaheadScan.MarkStaleSite(h.item),h=this.lookaheadScan.FindNextInRange(h,a)}this.lookaheadScan.RemoveStaleSites()}AddPerpendicularReflectionSegment(t,e,i){if(this.lookaheadScan.RemoveExact(t.PreviousSite)){if(e==null)return!1;if(t.PreviousSite.IsStaircaseStep(t.ReflectingObstacle)){if(!it.PointIsInRectangleInterior(t.Site,t.ReflectingObstacle.VisibilityBoundingBox)||!this.InsertPerpendicularReflectionSegment(t.PreviousSite.Site,t.Site))return!1;if(i!=null&&t.IsStaircaseStep(i.Obstacle))return this.ScanLineCrossesObstacle(t.Site,i.Obstacle)}}return!1}AddParallelReflectionSegment(t,e,i,s){{const n=this.ScanLineIntersectSide(s.Site,e??i),o=e!=null?n:s.Site,a=e!=null?s.Site:n;return e==null?e=this.scanLine.NextLowB(i).item:i=this.scanLine.NextHighB(e).item,this.InsertParallelReflectionSegment(o,a,t,e,i,s)}}AddReflectionEvent(t,e,i){const s=e;s!=null?this.eventQueue.Enqueue(new xl(t,s,i)):this.eventQueue.Enqueue(new wl(t,e,i))}AddSideToScanLine(t,e){const i=this.scanLine.Insert(t,e);return this.LoadReflectionEvents(t),i}RemoveSideFromScanLine(t,e){this.scanLine.Remove(t.item,e)}PointCompare(t,e){return this.ScanDirection.Compare(t,e)}Clear(){this.ObstacleTree.Clear(),this.eventQueue=new bl,this.HorizontalScanSegments=new Wo(ae.HorizontalInstance),this.VerticalScanSegments=new Wo(ae.VerticalInstance),this.VisibilityGraph=null}ProcessEvents(){for(;this.eventQueue.Count>0;){const t=this.eventQueue.Dequeue();t instanceof Vo?this.ProcessEventO(t):t instanceof vl?this.ProcessEventLB(t):t instanceof Il?this.ProcessEventHB(t):t instanceof Tl?this.ProcessEventCV(t):t instanceof xl?this.ProcessEventLR(t):t instanceof wl?this.ProcessEventHR(t):this.ProcessCustomEvent(t),this.LowNeighborSides.Clear(),this.HighNeighborSides.Clear()}}ProcessCustomEvent(t){}ScanLineCrossesObstacle(t,e){return this.ScanDirection.ComparePerpCoord(t,e.VisibilityBoundingBox.leftBottom)>0&&this.ScanDirection.ComparePerpCoord(t,e.VisibilityBoundingBox.rightTop)<0}FindInitialNeighborSides(t,e){e.lowNborSideNode=this.scanLine.NextLowR(t),e.highNborSideNode=this.scanLine.NextHighR(t)}FindNeighborsBRR(t,e,i){this.LowNeighborSides.Clear(),this.HighNeighborSides.Clear(),this.FindNeighbors(t,e,this.LowNeighborSides),this.FindNeighbors(t,i,this.HighNeighborSides)}FindNeighbors(t,e,i){const s=t instanceof Vo?e.item.Start:e.item.End,n={lowNborSideNode:null,highNborSideNode:null};this.FindInitialNeighborSides(e,n),this.SkipToNeighbor(this.ScanDirection.OppositeDirection,e.item,s,n.lowNborSideNode,i),this.SkipToNeighbor(this.ScanDirection.Dir,e.item,s,n.highNborSideNode,i)}SkipToNeighbor(t,e,i,s,n){let o=null,a=null;for(;;s=this.scanLine.Next(t,s))if(s.item.Obstacle!==e.Obstacle){if(s.item.Obstacle.IsGroup){this.ProcessGroupSideEncounteredOnTraversalToNeighbor(s,i,t)&&a==null&&(a=s.item);continue}if(s.item instanceof Gr===it.IsAscending(t)){this.ScanLineCrossesObstacle(i,s.item.Obstacle)&&(o=s,a=null);continue}break}n.SetSides(t,s,o,a)}ProcessGroupSideEncounteredOnTraversalToNeighbor(t,e,i){if(!this.ScanLineCrossesObstacle(e,t.item.Obstacle))return!1;const s=t.item instanceof Ui===it.IsAscending(i)?i:j.OppositeDir(i),n=this.ScanLineIntersectSide(e,t.item);return this.CurrentGroupBoundaryCrossingMap.AddIntersection(n,t.item.Obstacle,s),!0}FindNeighborsAndProcessVertexEvent(t,e,i){this.CurrentGroupBoundaryCrossingMap.Clear(),this.FindNeighborsBRR(i,t,e),this.ProcessVertexEvent(t,e,i),this.CurrentGroupBoundaryCrossingMap.Clear()}ProcessEventO(t){var e,i;const s=t.Obstacle;s.CreateInitialSides(t.Vertex,this.ScanDirection),this.AddSideToScanLine(s.ActiveLowSide,t.Site);const n=this.AddSideToScanLine(s.ActiveHighSide,t.Site),o=this.scanLine.Find(s.ActiveLowSide);this.FindNeighborsAndProcessVertexEvent(o,n,t);const a=(e=this.LowNeighborSides.GroupSideInterveningBeforeLowNeighbor)!==null&&e!==void 0?e:this.LowNeighborSides.LowNeighborSide;this.SideReflectsUpward(a)&&this.LoadReflectionEvents(s.ActiveLowSide);const h=(i=this.HighNeighborSides.GroupSideInterveningBeforeHighNeighbor)!==null&&i!==void 0?i:this.HighNeighborSides.HighNeighborSide;if(this.SideReflectsUpward(h)&&this.LoadReflectionEvents(s.ActiveHighSide),s.ActiveHighSide.Start!==s.ActiveLowSide.Start){const u=new Gr(s,t.Vertex,this.ScanDirection);this.lookaheadScan.RemoveSitesForFlatBottom(u.Start,u.End)}this.EnqueueLowBendVertexEvent(s.ActiveLowSide),this.EnqueueHighBendOrCloseVertexEvent(s.ActiveHighSide)}ProcessEventLB(t){const e=t.Obstacle,i=new Ui(e,t.Vertex,this.ScanDirection);this.ScanDirection.ComparePerpCoord(i.End,i.Start)>0&&(this.RemoveSideFromScanLine(this.scanLine.Find(e.ActiveLowSide),t.Site),this.AddSideToScanLine(i,t.Site),e.ActiveLowSide=i,this.EnqueueLowBendVertexEvent(i))}EnqueueLowBendVertexEvent(t){this.eventQueue.Enqueue(new vl(t.Obstacle,t.EndVertex))}ProcessEventHB(t){const e=t.Obstacle,i=new Gr(e,t.Vertex,this.ScanDirection);this.RemoveSideFromScanLine(this.scanLine.Find(e.ActiveHighSide),t.Site);const s=this.AddSideToScanLine(i,t.Site);if(e.ActiveHighSide=i,this.EnqueueHighBendOrCloseVertexEvent(e.ActiveHighSide),this.wantReflections&&this.ScanDirection.IsHorizontal&&i.Start.x===e.VisibilityBoundingBox.right&&this.SideReflectsUpward(i)){const n=this.scanLine.NextHighR(s);n.item instanceof Ui&&this.SideReflectsDownward(n.item)&&(!e.isOverlapped||!this.ObstacleTree.PointIsInsideAnObstacle(i.Start,this.ScanDirection))&&(this.StoreLookaheadSite(n.item.Obstacle,i,i.Start,!0),this.LoadReflectionEvents(n.item))}}EnqueueHighBendOrCloseVertexEvent(t){const e=t.Obstacle,i=this.ScanDirection.IsHorizontal?t.EndVertex.prevOnPolyline:t.EndVertex.nextOnPolyline;this.ScanDirection.ComparePerpCoord(i.point,t.End)>0?this.eventQueue.Enqueue(new Il(e,t.EndVertex)):this.eventQueue.Enqueue(new Tl(e,t.EndVertex))}CreateCloseEventSegmentsAndFindNeighbors(t){const e=t.Obstacle;let i=this.scanLine.Find(e.ActiveLowSide),s=this.scanLine.Find(e.ActiveHighSide);if(this.scanLine.Compare(e.ActiveLowSide,e.ActiveHighSide)===1){const n=i;i=s,s=n}if(this.FindNeighborsAndProcessVertexEvent(i,s,t),this.wantReflections&&e.isOverlapped)for(let n=this.scanLine.NextHighR(i);n.item!==s.item;n=this.scanLine.NextHighR(n))this.LoadReflectionEvents(n.item);this.scanLine.Remove(e.ActiveLowSide,t.Site),this.scanLine.Remove(e.ActiveHighSide,t.Site)}ProcessEventCV(t){this.CreateCloseEventSegmentsAndFindNeighbors(t);const e=this.LowNeighborSides.LowNeighbor.item,i=this.HighNeighborSides.HighNeighbor.item,s=t.Obstacle;this.LoadReflectionEvents(e),this.LoadReflectionEvents(i),s.Close()}ProcessEventLR(t){const e=t.Side.Obstacle,i=this.scanLine.NextLowB(t.Side).item;this.AddPerpendicularReflectionSegment(t,t.Side,i)&&this.AddParallelReflectionSegment(e,i,null,t)&&this.LoadReflectionEvents(e.ActiveLowSide)}ProcessEventHR(t){const e=t.Side.Obstacle,i=this.scanLine.NextHighB(t.Side).item;this.AddPerpendicularReflectionSegment(t,t.Side,i)&&this.AddParallelReflectionSegment(e,null,i,t)&&this.LoadReflectionEvents(e.ActiveHighSide)}MakeInBoundsLocation(t){const e=Math.max(t.x,this.ObstacleTree.GraphBox.left),i=Math.max(t.y,this.ObstacleTree.GraphBox.bottom);return new d(Math.min(e,this.ObstacleTree.GraphBox.right),Math.min(i,this.ObstacleTree.GraphBox.top))}IsInBoundsV(t){return this.IsInBoundsP(t.point)}IsInBoundsP(t){return L.EqualPP(t,this.MakeInBoundsLocation(t))}}he.SentinelOffset=1;class fi extends he{constructor(){super(!1),this.horizontalVertexPoints=new ie,this.verticalVertexPoints=new ie,this.boundingBoxSteinerPoints=new ie,this.xCoordAccumulator=new Set,this.yCoordAccumulator=new Set,this.horizontalCoordMap=new Map,this.verticalCoordMap=new Map}Clear(){super.Clear(),this.Cleanup()}Cleanup(){this.horizontalVertexPoints.clear(),this.verticalVertexPoints.clear(),this.boundingBoxSteinerPoints.clear(),this.xCoordAccumulator.clear(),this.yCoordAccumulator.clear(),this.horizontalCoordMap.clear(),this.verticalCoordMap.clear()}GenerateVisibilityGraph(){this.AccumulateVertexCoords(),this.CreateSegmentVectorsAndPopulateCoordinateMaps(),this.RunScanLineToCreateSegmentsAndBoundingBoxSteinerPoints(),this.GenerateSparseIntersectionsFromVertexPoints(),this.CreateScanSegmentTrees(),this.Cleanup()}AccumulateVertexCoords(){for(const t of this.ObstacleTree.GetAllObstacles())this.xCoordAccumulator.add(t.VisibilityBoundingBox.left),this.xCoordAccumulator.add(t.VisibilityBoundingBox.right),this.yCoordAccumulator.add(t.VisibilityBoundingBox.top),this.yCoordAccumulator.add(t.VisibilityBoundingBox.bottom)}CreateSegmentVectorsAndPopulateCoordinateMaps(){this.horizontalScanSegmentVector=new El(this.yCoordAccumulator,!0),this.verticalScanSegmentVector=new El(this.xCoordAccumulator,!1);for(let t=0;t<this.horizontalScanSegmentVector.Length;t++)this.horizontalCoordMap.set(this.horizontalScanSegmentVector.Item(t).Coord,t);for(let t=0;t<this.verticalScanSegmentVector.Length;t++)this.verticalCoordMap.set(this.verticalScanSegmentVector.Item(t).Coord,t)}RunScanLineToCreateSegmentsAndBoundingBoxSteinerPoints(){super.GenerateVisibilityGraph(),this.horizontalScanSegmentVector.ScanSegmentsComplete(),this.verticalScanSegmentVector.ScanSegmentsComplete(),this.xCoordAccumulator.clear(),this.yCoordAccumulator.clear()}InitializeEventQueue(t){super.InitializeEventQueue(t),this.SetVectorsAndCoordMaps(t),this.AddAxisCoordinateEvents(t)}AddAxisCoordinateEvents(t){if(t.IsHorizontal){for(const e of this.yCoordAccumulator)this.eventQueue.Enqueue(new Pa(new d(this.ObstacleTree.GraphBox.left-fi.SentinelOffset,e)));return}for(const e of this.xCoordAccumulator)this.eventQueue.Enqueue(new Pa(new d(e,this.ObstacleTree.GraphBox.bottom-fi.SentinelOffset)))}ProcessCustomEvent(t){this.ProcessAxisCoordinate(t)||this.ProcessCustomEvent(t)}ProcessAxisCoordinate(t){return t instanceof Pa?(this.CreateScanSegmentsOnAxisCoordinate(t.Site),!0):!1}InsertPerpendicularReflectionSegment(t,e){return!1}InsertParallelReflectionSegment(t,e,i,s,n,o){return!1}ProcessVertexEvent(t,e,i){const s=this.ScanDirection.IsHorizontal?this.horizontalVertexPoints:this.verticalVertexPoints;s.add(i.Site);const n=this.LowNeighborSides.LowNeighbor.item,o=this.HighNeighborSides.HighNeighbor.item,a=this.ScanDirection.Dir,h=this.ScanDirection.OppositeDirection,u=this.ScanLineIntersectSide(i.Site,n),c=this.ScanLineIntersectSide(i.Site,o);if(this.ObstacleTree.GraphBox.contains(u)){const S=it.RectangleBorderIntersect(n.Obstacle.VisibilityBoundingBox,u,a);L.IsPureLower(S,i.Site)&&this.boundingBoxSteinerPoints.add(S)}if(this.ObstacleTree.GraphBox.contains(c)){const S=it.RectangleBorderIntersect(o.Obstacle.VisibilityBoundingBox,c,h);L.IsPureLower(i.Site,S)&&this.boundingBoxSteinerPoints.add(S)}const m={lowCorner:void 0,highCorner:void 0};fi.GetBoundingCorners(t.item.Obstacle.VisibilityBoundingBox,i instanceof Vo,this.ScanDirection.IsHorizontal,m),(L.IsPureLower(u,m.lowCorner)||n.Obstacle.IsInSameClump(i.Obstacle))&&s.add(m.lowCorner),(L.IsPureLower(m.highCorner,c)||o.Obstacle.IsInSameClump(i.Obstacle))&&s.add(m.highCorner)}static GetBoundingCorners(t,e,i,s){if(e){s.lowCorner=t.leftBottom,s.highCorner=i?t.rightBottom:t.leftTop;return}s.lowCorner=i?t.leftTop:t.rightBottom,s.highCorner=t.rightTop}CreateScanSegmentsOnAxisCoordinate(t){this.CurrentGroupBoundaryCrossingMap.Clear();const e=this.scanLine.Lowest();let i=this.scanLine.NextHighR(e),s=0,n=t,o=!1;for(;i!=null;i=this.scanLine.NextHighR(i)){if(this.SkipSide(n,i.item))continue;if(i.item.Obstacle.IsGroup){(s===0||o)&&this.HandleGroupCrossing(t,i.item);continue}if(i.item instanceof Ui){if(s>0){s++;continue}n=this.CreateScanSegment(n,i.item,bt.NormalWeight),this.CurrentGroupBoundaryCrossingMap.Clear(),s=1,o=i.item.Obstacle.isOverlapped;continue}s++,!(s>0)&&(n=i.item.Obstacle.isOverlapped||i.item.Obstacle.OverlapsGroupCorner?this.CreateScanSegment(n,i.item,bt.OverlappedWeight):this.ScanLineIntersectSide(n,i.item),this.CurrentGroupBoundaryCrossingMap.Clear(),o=!1)}const a=this.ScanDirection.IsHorizontal?new d(this.ObstacleTree.GraphBox.right+fi.SentinelOffset,n.y):new d(n.x,this.ObstacleTree.GraphBox.top+fi.SentinelOffset);this.parallelSegmentVector.CreateScanSegment(n,a,bt.NormalWeight,this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(n,a)),this.parallelSegmentVector.ScanSegmentsCompleteForCurrentSlot()}HandleGroupCrossing(t,e){if(!this.ScanLineCrossesObstacle(t,e.Obstacle))return;const i=e instanceof Ui?this.ScanDirection.Dir:this.ScanDirection.OppositeDirection,s=this.ScanLineIntersectSide(t,e),n=this.CurrentGroupBoundaryCrossingMap.AddIntersection(s,e.Obstacle,i);this.AddPerpendicularCoordForGroupCrossing(s);const o=n.GetInteriorVertexPoint(s);this.AddPerpendicularCoordForGroupCrossing(o)}AddPerpendicularCoordForGroupCrossing(t){const e=this.FindPerpendicularSlot(t,0);e!==-1&&this.perpendicularSegmentVector.Item(e).AddPendingPerpendicularCoord(this.parallelSegmentVector.CurrentSlot.Coord)}SkipSide(t,e){if(e.Obstacle.IsSentinel)return!0;const i=e.Obstacle.VisibilityBoundingBox;return this.ScanDirection.IsHorizontal?t.y===i.bottom||t.y===i.top:t.x===i.left||t.x===i.right}CreateScanSegment(t,e,i){const s=this.ScanLineIntersectSide(t,e);return t!==s&&this.parallelSegmentVector.CreateScanSegment(t,s,i,this.CurrentGroupBoundaryCrossingMap.GetOrderedListBetween(t,s)),s}GenerateSparseIntersectionsFromVertexPoints(){this.VisibilityGraph=fi.NewVisibilityGraph(),this.GenerateSparseIntersectionsAlongHorizontalAxis(),this.GenerateSparseIntersectionsAlongVerticalAxis(),this.ConnectAdjoiningScanSegments(),this.horizontalScanSegmentVector.CreateSparseVerticesAndEdges(this.VisibilityGraph),this.verticalScanSegmentVector.CreateSparseVerticesAndEdges(this.VisibilityGraph)}GenerateSparseIntersectionsAlongHorizontalAxis(){this.currentAxisPointComparer=Dt;const t=Array.from(this.horizontalVertexPoints.values()).sort(this.currentAxisPointComparer),e=Array.from(this.boundingBoxSteinerPoints.values()).sort(this.currentAxisPointComparer);this.ScanDirection=ae.HorizontalInstance,this.SetVectorsAndCoordMaps(this.ScanDirection),this.GenerateSparseIntersections(t,e)}GenerateSparseIntersectionsAlongVerticalAxis(){this.currentAxisPointComparer=(i,s)=>i.compareTo(s);const t=Array.from(this.verticalVertexPoints.values()).sort(this.currentAxisPointComparer),e=Array.from(this.boundingBoxSteinerPoints.values()).sort(this.currentAxisPointComparer);this.ScanDirection=ae.VerticalInstance,this.SetVectorsAndCoordMaps(this.ScanDirection),this.GenerateSparseIntersections(t,e)}SetVectorsAndCoordMaps(t){t.IsHorizontal?(this.parallelSegmentVector=this.horizontalScanSegmentVector,this.perpendicularSegmentVector=this.verticalScanSegmentVector,this.perpendicularCoordMap=this.verticalCoordMap):(this.parallelSegmentVector=this.verticalScanSegmentVector,this.perpendicularSegmentVector=this.horizontalScanSegmentVector,this.perpendicularCoordMap=this.horizontalCoordMap)}ConnectAdjoiningScanSegments(){this.horizontalScanSegmentVector.ConnectAdjoiningSegmentEndpoints(),this.verticalScanSegmentVector.ConnectAdjoiningSegmentEndpoints()}GenerateSparseIntersections(t,e){this.perpendicularSegmentVector.ResetForIntersections(),this.parallelSegmentVector.ResetForIntersections();let i=1;const s={j:0};for(const n of this.parallelSegmentVector.Items())for(;!(!n.CurrentSegment.ContainsPoint(t[i])&&(!this.AddSteinerPointsToInterveningSegments(t[i],e,s,n)||!n.TraverseToSegmentContainingPoint(t[i])));){if(this.AddPointsToCurrentSegmentIntersections(e,s,n),this.GenerateIntersectionsFromVertexPointForCurrentSegment(t[i],n),n.PointIsCurrentEndAndNextStart(t[i])){n.MoveNext();continue}if(++i>=t.length)return}}AddSteinerPointsToInterveningSegments(t,e,i,s){for(;i.j<e.length&&this.currentAxisPointComparer(e[i.j],t)===-1;){if(!s.TraverseToSegmentContainingPoint(e[i.j]))return!1;this.AddPointsToCurrentSegmentIntersections(e,i,s)}return!0}AddPointsToCurrentSegmentIntersections(t,e,i){for(;e.j<t.length&&i.CurrentSegment.ContainsPoint(t[e.j]);e.j++){const s=this.FindPerpendicularSlot(t[e.j],0);this.AddSlotToSegmentIntersections(i,s)}}GenerateIntersectionsFromVertexPointForCurrentSegment(t,e){const i=this.FindPerpendicularSlot(e.CurrentSegment.Start,1),s=this.FindPerpendicularSlot(e.CurrentSegment.End,-1),n=this.FindPerpendicularSlot(t,0);i>=s||(this.AddSlotToSegmentIntersections(e,i),this.AddSlotToSegmentIntersections(e,s),n>i&&n<s&&(this.AddSlotToSegmentIntersections(e,n),this.AddBinaryDivisionSlotsToSegmentIntersections(e,i,n,s)))}FindPerpendicularSlot(t,e){return fi.FindIntersectingSlot(this.perpendicularSegmentVector,this.perpendicularCoordMap,t,e)}static FindIntersectingSlot(t,e,i,s){const n=t.GetParallelCoord(i),o=e.get(n);return o!==void 0?o:s===0?-1:t.FindNearest(n,s)}AddSlotToSegmentIntersections(t,e){const i=this.perpendicularSegmentVector.Item(e);t.CurrentSegment.AddSparseVertexCoord(i.Coord),i.AddPerpendicularCoord(t.Coord)}AddBinaryDivisionSlotsToSegmentIntersections(t,e,i,s){let n=0,o=this.perpendicularSegmentVector.Length-1;for(;o-n>1;){const a=n+Math.floor((o-n)/2);if(i<=a){o=a,i<o&&o<=s&&this.AddSlotToSegmentIntersections(t,o);continue}n=a,i>n&&n>=e&&this.AddSlotToSegmentIntersections(t,n)}}CreateScanSegmentTrees(){fi.CreateScanSegmentTree(this.horizontalScanSegmentVector,this.HorizontalScanSegments),fi.CreateScanSegmentTree(this.verticalScanSegmentVector,this.VerticalScanSegments)}static CreateScanSegmentTree(t,e){for(const i of t.Items())for(let s=i.FirstSegment;s!=null;s=s.NextSegment)s.HasVisibility()&&e.InsertUnique(s)}}class pi{constructor(t){this.AddedVertices=new Array,this.AddedEdges=new Array,this.edgesToRestore=new Array,this.LimitPortVisibilitySpliceToEndpointBoundingBox=!1,this.GraphGenerator=t}get ObstacleTree(){return this.GraphGenerator.ObstacleTree}get VisGraph(){return this.GraphGenerator.VisibilityGraph}get IsSparseVg(){return this.GraphGenerator instanceof fi}AddVertex(t){const e=this.VisGraph.AddVertexP(t);return this.AddedVertices.push(e),e}FindOrAddVertex(t){const e=this.VisGraph.FindVertex(t);return e??this.AddVertex(t)}FindOrAddEdgeVV(t,e){return this.FindOrAddEdge(t,e,bt.NormalWeight)}FindOrAddEdge(t,e,i){const s=L.GetPureDirectionVV(t,e),n={bracketSource:void 0,bracketTarget:void 0,splitVertex:void 0};pi.GetBrackets(t,e,s,n);let o=this.VisGraph.FindEdgePP(n.bracketSource.point,n.bracketTarget.point);return o=o!=null?this.SplitEdge(o,n.splitVertex):this.CreateEdge(n.bracketSource,n.bracketTarget,i),o}static GetBrackets(t,e,i,s){if(s.splitVertex=e,!pi.FindBracketingVertices(t,e.point,i,s)){const n={bracketSource:null,bracketTarget:null};pi.FindBracketingVertices(e,t.point,j.OppositeDir(i),n)&&(s.bracketSource=n.bracketTarget,s.splitVertex=t),s.bracketTarget=n.bracketSource}}static FindBracketingVertices(t,e,i,s){for(s.bracketSource=t;s.bracketTarget=it.FindAdjacentVertex(s.bracketSource,i),s.bracketTarget!=null;){if(d.closeDistEps(s.bracketTarget.point,e))return!0;if(i!==L.GetDirections(s.bracketTarget.point,e))break;s.bracketSource=s.bracketTarget}return s.bracketTarget!=null}CreateEdge(t,e,i){let s=t,n=e;L.IsPureLower(s.point,n.point)||(s=e,n=t);const o=new wi(s,n,i);return se.AddEdge(o),this.AddedEdges.push(o),o}RemoveFromGraph(){this.RemoveAddedVertices(),this.RemoveAddedEdges(),this.RestoreRemovedEdges()}RemoveAddedVertices(){for(const t of this.AddedVertices)this.VisGraph.FindVertex(t.point)!=null&&this.VisGraph.RemoveVertex(t);this.AddedVertices=[]}RemoveAddedEdges(){for(const t of this.AddedEdges)this.VisGraph.FindVertex(t.SourcePoint)!=null&&se.RemoveEdge(t);this.AddedEdges=[]}RestoreRemovedEdges(){for(const t of this.edgesToRestore)se.AddEdge(t);this.edgesToRestore=[]}FindNextEdge(t,e){return it.FindAdjacentEdge(t,e)}FindPerpendicularOrContainingEdge(t,e,i){for(;;){const s=it.FindAdjacentVertex(t,e);if(s==null)break;const n=L.GetDirections(s.point,i);if(j.OppositeDir(e)&n)return this.VisGraph.FindEdgePP(t.point,s.point);t=s}return null}FindNearestPerpendicularOrContainingEdge(t,e,i){let s;e&L.GetDirections(t.point,i);let n=t;const o=s;for(;v.None!==o;){const h=it.FindAdjacentVertex(n,s);if(h==null||j.OppositeDir(s)&L.GetDirections(h.point,i))break;n=h,e&L.GetDirections(n.point,i)}let a;for(;a=this.FindPerpendicularOrContainingEdge(n,e,i),!(a!=null||n===t);)n=it.FindAdjacentVertex(n,j.OppositeDir(s));return a}ConnectVertexToTargetVertex(t,e,i,s){if(d.closeDistEps(t.point,e.point))return;const n=L.GetDirections(t.point,e.point);if(L.IsPureDirectionD(n)){this.FindOrAddEdgeVV(t,e);return}const o=it.FindBendPointBetween(t.point,e.point,i),a=this.FindOrAddVertex(o);this.FindOrAddEdge(t,a,s),this.FindOrAddEdge(a,e,s)}AddEdgeToTargetEdge(t,e,i){let s=this.VisGraph.FindVertex(i);return s==null&&(s=this.AddVertex(i),this.SplitEdge(e,s)),this.FindOrAddEdgeVV(t,s),s}SplitEdge(t,e){return t==null?null:d.closeDistEps(t.Source.point,e.point)||d.closeDistEps(t.Target.point,e.point)?t:(t instanceof wi||this.edgesToRestore.push(t),se.RemoveEdge(t),(this.IsSparseVg||t.Weight===bt.OverlappedWeight)&&e.Degree>0?(this.FindOrAddEdge(e,t.Source,t.Weight),this.FindOrAddEdge(e,t.Target,t.Weight)):(this.CreateEdge(e,t.Target,t.Weight),this.CreateEdge(t.Source,e,t.Weight)))}ExtendEdgeChainVRLPB(t,e,i,s,n){const o=L.GetDirections(i.start,i.end);if(o===v.None)return;const a=it.GetRectangleBound(e,o),h=it.IsVerticalD(o)?d.RoundPoint(new d(t.point.x,a)):d.RoundPoint(new d(a,t.point.y));if(d.closeDistEps(h,t.point)||L.GetDirections(t.point,h)!==o)return;let u=i;L.GetDirections(h,u.end)===o&&(u=D.mkPP(u.start,h)),this.ExtendEdgeChain(t,o,u,i,s,n)}ExtendEdgeChain(t,e,i,s,n,o){if(L.GetDirections(t.point,i.end)!==e)return;let h=j.RotateLeft(e),u=it.FindAdjacentVertex(t,h);if(u==null&&(h=j.OppositeDir(h),u=it.FindAdjacentVertex(t,h),u==null))return;const c=j.OppositeDir(h),m={spliceTarget:null};this.ExtendSpliceWorker(u,e,c,i,s,o,m)&&this.ExtendSpliceWorker(m.spliceTarget,e,h,i,s,o,m),this.SpliceGroupBoundaryCrossings(n,t,i)}SpliceGroupBoundaryCrossings(t,e,i){if(t==null||t.Count()===0)return;t.Reset();let s=i.start,n=i.end,o=L.GetDirections(s,n);it.IsAscending(o)||(s=i.end,n=i.start,o=j.OppositeDir(o)),e=pi.TraverseToFirstVertexAtOrAbove(e,s,j.OppositeDir(o));for(let a=e;a!=null;a=it.FindAdjacentVertex(a,o)){const h=L.ComparePP(a.point,n)>=0;for(;t.CurrentIsBeforeOrAt(a.point);){const u=t.Pop();L.ComparePP(u.Location,e.point)>0&&L.ComparePP(u.Location,n)<=0&&this.SpliceGroupBoundaryCrossing(a,u,j.OppositeDir(o)),L.ComparePP(u.Location,e.point)>=0&&L.ComparePP(u.Location,n)<0&&this.SpliceGroupBoundaryCrossing(a,u,o)}if(h)break}}static TraverseToFirstVertexAtOrAbove(t,e,i){let s=t;const n=j.OppositeDir(i);for(;;){const o=it.FindAdjacentVertex(s,i);if(o==null||L.GetDirections(o.point,e)===n)break;s=o}return s}SpliceGroupBoundaryCrossing(t,e,i){var s,n;const o=Nr.ToCrossingArray(e.Crossings,i);if(o!=null){const a=(s=this.VisGraph.FindVertex(e.Location))!==null&&s!==void 0?s:this.AddVertex(e.Location);t.point.equal(a.point)||this.FindOrAddEdgeVV(t,a);const h=o[0].GetInteriorVertexPoint(e.Location),u=(n=this.VisGraph.FindVertex(h))!==null&&n!==void 0?n:this.AddVertex(h),c=this.FindOrAddEdgeVV(a,u),m=o.map(S=>S.Group.InputShape);c.IsPassable=()=>m.some(S=>S.IsTransparent)}}ExtendSpliceWorker(t,e,i,s,n,o,a){let h=it.FindAdjacentVertex(t,i);a.spliceTarget=it.FindAdjacentVertex(h,i);const u={spliceSource:t};for(;pi.GetNextSpliceSource(u,i,e);){const c=it.FindBendPointBetween(h.point,u.spliceSource.point,j.OppositeDir(i));if(pi.IsPointPastSegmentEnd(n,c))break;if(a.spliceTarget=pi.GetSpliceTarget(u,i,c),a.spliceTarget==null){if(this.IsSkippableSpliceSourceWithNullSpliceTarget(u.spliceSource,e))continue;if(this.ObstacleTree.SegmentCrossesAnObstacle(u.spliceSource.point,c))return!1}let m=this.VisGraph.FindVertex(c);if(m!=null){if(a.spliceTarget==null||this.VisGraph.FindEdgePP(h.point,c)!=null)return a.spliceTarget==null&&this.FindOrAddEdge(h,m,o?bt.OverlappedWeight:bt.NormalWeight),!1}else m=this.AddVertex(c);if(this.FindOrAddEdge(h,m,o?bt.OverlappedWeight:bt.NormalWeight),this.FindOrAddEdge(u.spliceSource,m,o?bt.OverlappedWeight:bt.NormalWeight),o&&(o=this.SeeIfSpliceIsStillOverlapped(e,m)),h=m,!(e&L.GetDirections(c,s.end))){a.spliceTarget=null;break}}return a.spliceTarget!=null}static GetNextSpliceSource(t,e,i){let s=it.FindAdjacentVertex(t.spliceSource,i);if(s==null)for(s=t.spliceSource;;){if(s=it.FindAdjacentVertex(s,j.OppositeDir(e)),s==null)return!1;const n=it.FindAdjacentVertex(s,i);if(n!=null){s=n;break}}return t.spliceSource=s,!0}static GetSpliceTarget(t,e,i){const s=L.GetDirections(t.spliceSource.point,i);let n=s,o=t.spliceSource;for(;n===s&&(t.spliceSource=o,o=it.FindAdjacentVertex(t.spliceSource,e),o!=null);){if(d.closeDistEps(o.point,i)){o=it.FindAdjacentVertex(o,e);break}n=L.GetDirections(o.point,i)}return o}SeeIfSpliceIsStillOverlapped(t,e){let i=this.FindNextEdge(e,j.RotateLeft(t)),s=i==null?!1:bt.NormalWeight===i.Weight;return s||(i=this.FindNextEdge(e,j.RotateRight(t)),s=i==null?!1:bt.NormalWeight===i.Weight),!s||this.ObstacleTree.PointIsInsideAnObstaclePD(e.point,t)}IsSkippableSpliceSourceWithNullSpliceTarget(t,e){if(pi.IsSkippableSpliceSourceEdgeWithNullTarget(it.FindAdjacentEdge(t,e)))return!0;const i=it.FindAdjacentEdge(t,j.OppositeDir(e));return pi.IsSkippableSpliceSourceEdgeWithNullTarget(i)||pi.IsReflectionEdge(i)}static IsSkippableSpliceSourceEdgeWithNullTarget(t){return t!=null&&t.IsPassable!=null&&N(t.Length,ma.BoundaryWidth)}static IsReflectionEdge(t){return t!=null&&t.Weight===bt.ReflectionWeight}static IsPointPastSegmentEnd(t,e){return L.GetDirections(t.start,t.end)===L.GetDirections(t.end,e)}toString(){return Se.Qf.Format("{0} {1}",this.AddedVertices.length,this.edgesToRestore.length)}}class Mr{constructor(t){this.obstaclePortMap=new Map,this.freePointMap=new si,this.freePointLocationsUsedByRouteEdges=new ie,this.RouteToCenterOfObstacles=!1,this.obstaclePortsInGraph=new Array,this.freePointsInGraph=new Set,this.activeAncestors=new Array,this.TransUtil=new pi(t),this.graphGenerator=t}get LimitPortVisibilitySpliceToEndpointBoundingBox(){return this.TransUtil.LimitPortVisibilitySpliceToEndpointBoundingBox}set LimitPortVisibilitySpliceToEndpointBoundingBox(t){this.TransUtil.LimitPortVisibilitySpliceToEndpointBoundingBox=t}get VisGraph(){return this.graphGenerator.VisibilityGraph}get HScanSegments(){return this.graphGenerator.HorizontalScanSegments}get VScanSegments(){return this.graphGenerator.VerticalScanSegments}get ObstacleTree(){return this.graphGenerator.ObstacleTree}get AncestorSets(){return this.ObstacleTree.AncestorSets}Clear(){this.TransUtil.RemoveFromGraph(),this.obstaclePortMap.clear()}CreateObstaclePorts(t){for(const e of t.Ports)this.CreateObstaclePort(t,e)}CreateObstaclePort(t,e){if(e.Curve==null)return null;const i=d.RoundPoint(e.Location);if(ft.Outside===w.PointRelativeToCurveLocation(i,t.InputShape.BoundaryCurve)||t.InputShape.BoundaryCurve!==e.Curve&&ft.Outside===w.PointRelativeToCurveLocation(i,e.Curve))return null;const s=new hu(e,t);return this.obstaclePortMap.set(e,s),s}FindVertices(t){const e=new Array,i=this.obstaclePortMap.get(t);if(i)if(this.RouteToCenterOfObstacles)e.push(i.CenterVertex);else for(const s of i.PortEntrances){const n=this.VisGraph.FindVertex(s.UnpaddedBorderIntersect);n!=null&&e.push(n)}else e.push(this.VisGraph.FindVertex(d.RoundPoint(t.Location)));return e}RemoveObstaclePorts(t){for(const e of t.Ports)this.RemoveObstaclePort(e)}RemoveObstaclePort(t){this.obstaclePortMap.delete(t)}AddControlPointsToGraph(t,e){this.GetPortSpliceLimitRectangle(t),this.activeAncestors=[];const i={oport:null},s={oport:null},n=this.FindAncestorsAndObstaclePort(t.sourcePort,i),o=this.FindAncestorsAndObstaclePort(t.targetPort,s);if(this.AncestorSets.size>0&&i.oport!=null&&s.oport!=null){const a=Ps(o,n),h=Ps(n,o);this.ActivateAncestors(h,a,e)}this.AddPortToGraph(t.sourcePort,i.oport),this.AddPortToGraph(t.targetPort,s.oport)}ConnectOobWaypointToEndpointVisibilityAtGraphBoundary(t,e){if(t==null||!t.IsOutOfBounds)return;const i=this.FindVertices(e);let s=t.OutOfBoundsDirectionFromGraph&(v.North|v.South);this.ConnectToGraphAtPointsCollinearWithVertices(t,s,i),s=t.OutOfBoundsDirectionFromGraph&(v.East|v.West),this.ConnectToGraphAtPointsCollinearWithVertices(t,s,i)}ConnectToGraphAtPointsCollinearWithVertices(t,e,i){if(v.None===e)return;const s=j.OppositeDir(e);for(const n of i){const o=this.InBoundsGraphBoxIntersect(n.point,e),a=this.VisGraph.FindVertex(o);a!=null&&this.TransUtil.ConnectVertexToTargetVertex(t.Vertex,a,s,bt.NormalWeight)}}SetAllAncestorsActive(t,e){if(this.AncestorSets.size===0)return!1;this.ObstacleTree.AdjustSpatialAncestors(),this.ClearActiveAncestors();const i={oport:null},s={oport:null},n=this.FindAncestorsAndObstaclePort(t.sourcePort,s),o=this.FindAncestorsAndObstaclePort(t.targetPort,i);return this.AncestorSets.size>0&&n!=null&&o!=null?(this.ActivateAncestors(n,o,e),!0):!1}SetAllGroupsActive(){this.ClearActiveAncestors();for(const t of this.ObstacleTree.GetAllGroups())t.IsTransparentAncestor=!0,this.activeAncestors.push(t)}FindAncestorsAndObstaclePort(t,e){return e.oport=this.FindObstaclePort(t),this.AncestorSets.size===0?null:e.oport!=null?this.AncestorSets.get(e.oport.Obstacle.InputShape):new Set(Array.from(this.ObstacleTree.Root.AllHitItems(Z.mkPP(t.Location,t.Location),i=>i.IsGroup)).map(i=>i.InputShape))}ActivateAncestors(t,e,i){for(const s of Ss(t,e)){const n=i.get(s);n.IsTransparentAncestor=!0,this.activeAncestors.push(n)}}ClearActiveAncestors(){for(const t of this.activeAncestors)t.IsTransparentAncestor=!1;this.activeAncestors=[]}RemoveControlPointsFromGraph(){this.ClearActiveAncestors(),this.RemoveObstaclePortsFromGraph(),this.RemoveFreePointsFromGraph(),this.TransUtil.RemoveFromGraph(),this.portSpliceLimitRectangle=Z.mkEmpty()}RemoveObstaclePortsFromGraph(){for(const t of this.obstaclePortsInGraph)t.RemoveFromGraph();this.obstaclePortsInGraph=[]}RemoveFreePointsFromGraph(){for(const t of this.freePointsInGraph)t.RemoveFromGraph();this.freePointsInGraph.clear()}RemoveStaleFreePoints(){if(this.freePointMap.size>this.freePointLocationsUsedByRouteEdges.size){const t=Array.from(this.freePointMap).filter(e=>!this.freePointLocationsUsedByRouteEdges.has(e[0]));for(const e of t)this.freePointMap.deleteP(e[0])}}ClearVisibility(){this.freePointMap.clear();for(const t of this.obstaclePortMap.values())t.ClearVisibility()}BeginRouteEdges(){this.RemoveControlPointsFromGraph(),this.freePointLocationsUsedByRouteEdges.clear()}EndRouteEdges(){this.RemoveStaleFreePoints()}FindObstaclePort(t){let e=this.obstaclePortMap.get(t);if(e){const i={removedPorts:null,addedPorts:null};if(e.Obstacle.GetPortChanges(i)){for(const s of i.addedPorts)this.CreateObstaclePort(e.Obstacle,s);for(const s of i.removedPorts)this.RemoveObstaclePort(s);e=this.obstaclePortMap.get(t)}}return e}AddPortToGraph(t,e){if(e!=null){this.AddObstaclePortToGraph(e);return}this.AddFreePointToGraph(t.Location)}AddObstaclePortToGraph(t){if(!(t.LocationHasChanged&&(this.RemoveObstaclePort(t.Port),t=this.CreateObstaclePort(t.Obstacle,t.Port),t==null))){t.AddToGraph(this.TransUtil,this.RouteToCenterOfObstacles),this.obstaclePortsInGraph.push(t),this.CreateObstaclePortEntrancesIfNeeded(t);for(const e of t.PortEntrances)this.AddObstaclePortEntranceToGraph(e)}}CreateObstaclePortEntrancesIfNeeded(t){t.PortEntrances.length>0||this.CreateObstaclePortEntrancesFromPoints(t)}GetPortVisibilityIntersection(t){const e=this.FindObstaclePort(t.sourcePort),i=this.FindObstaclePort(t.targetPort);if(e==null||i==null||e.Obstacle.IsInConvexHull||i.Obstacle.IsInConvexHull||(this.CreateObstaclePortEntrancesIfNeeded(e),this.CreateObstaclePortEntrancesIfNeeded(i),!e.VisibilityRectangle.intersects(i.VisibilityRectangle)))return null;for(const s of e.PortEntrances)if(s.WantVisibilityIntersection)for(const n of i.PortEntrances){if(!n.WantVisibilityIntersection)continue;const o=s.IsVertical===n.IsVertical?Mr.GetPathPointsFromOverlappingCollinearVisibility(s,n):Mr.GetPathPointsFromIntersectingVisibility(s,n);if(o!=null)return o}return null}static GetPathPointsFromOverlappingCollinearVisibility(t,e){return!it.IntervalsAreSame(t.MaxVisibilitySegment.start,t.MaxVisibilitySegment.end,e.MaxVisibilitySegment.end,e.MaxVisibilitySegment.start)||t.HasGroupCrossings||e.HasGroupCrossings||d.closeDistEps(t.UnpaddedBorderIntersect,e.UnpaddedBorderIntersect)?null:[t.UnpaddedBorderIntersect,e.UnpaddedBorderIntersect]}static GetPathPointsFromIntersectingVisibility(t,e){const i=it.SegmentsIntersectLL(t.MaxVisibilitySegment,e.MaxVisibilitySegment);return!i||t.HasGroupCrossingBeforePoint(i)||e.HasGroupCrossingBeforePoint(i)?null:[t.UnpaddedBorderIntersect,i,e.UnpaddedBorderIntersect]}CreateObstaclePortEntrancesFromPoints(t){const e=this.graphGenerator.ObstacleTree.GraphBox,i=Z.mkPP(d.RoundPoint(t.PortCurve.boundingBox.leftBottom),d.RoundPoint(t.PortCurve.boundingBox.rightTop)),s=d.RoundPoint(t.PortLocation);let n=!1;const o={xx0:null,xx1:null};if(!L.Equal(s.y,i.top)&&!L.Equal(s.y,i.bottom)){n=!0;const a=new D(e.left,s.y,e.right,s.y);this.GetBorderIntersections(s,a,t.PortCurve,o);let h=new d(Math.min(o.xx0.x,o.xx1.x),s.y);h.x<i.left&&(h=new d(i.left,h.y));let u=new d(Math.max(o.xx0.x,o.xx1.x),s.y);u.x>i.right&&(u=new d(i.right,u.y)),this.CreatePortEntrancesAtBorderIntersections(i,t,s,h,u)}if(!L.Equal(s.x,i.left)&&!L.Equal(s.x,i.right)){n=!0;const a=new D(s.x,e.bottom,s.x,e.top);this.GetBorderIntersections(s,a,t.PortCurve,o);let h=new d(s.x,Math.min(o.xx0.y,o.xx1.y));h.y<e.bottom&&(h=new d(h.x,e.bottom));let u=new d(s.x,Math.max(o.xx0.y,o.xx1.y));u.y>e.top&&(u=new d(u.x,e.top)),this.CreatePortEntrancesAtBorderIntersections(i,t,s,h,u)}n||this.CreateEntrancesForCornerPort(i,t,s)}GetBorderIntersections(t,e,i,s){const n=w.getAllIntersections(e,i,!0);s.xx0=d.RoundPoint(n[0].x),s.xx1=d.RoundPoint(n[1].x)}CreatePortEntrancesAtBorderIntersections(t,e,i,s,n){const o=L.GetDirections(s,n);L.EqualPP(s,i)||this.CreatePortEntrance(t,e,n,o),L.EqualPP(n,i)||this.CreatePortEntrance(t,e,s,j.OppositeDir(o))}static GetDerivative(t,e){const i=t.PortCurve.closestParameter(e);let s=t.PortCurve.derivative(i);const n=(t.PortCurve.parStart+t.PortCurve.parEnd)/2;return mt.CurveIsClockwise(t.PortCurve,t.PortCurve.value(n))||(s=s.mul(-1)),s}CreatePortEntrance(t,e,i,s){e.CreatePortEntrance(i,s,this.ObstacleTree);const n=ae.GetInstance(s);let o=it.GetRectangleBound(t,s)-n.Coord(i);if(o<0&&(o=-o),o>C.intersectionEpsilon){const a=j.VectorDirection(Mr.GetDerivative(e,i));let h;s|j.OppositeDir(s),v.None!==(s&a)&&(h=j.OppositeDir(h)),e.CreatePortEntrance(i,h,this.ObstacleTree)}}CreateEntrancesForCornerPort(t,e,i){let s=v.North;L.EqualPP(i,t.leftBottom)?s=v.South:L.EqualPP(i,t.leftTop)?s=v.West:L.EqualPP(i,t.rightTop)?s=v.North:L.EqualPP(i,t.rightBottom)&&(s=v.East),e.CreatePortEntrance(i,s,this.ObstacleTree),e.CreatePortEntrance(i,j.RotateRight(s),this.ObstacleTree)}AddObstaclePortEntranceToGraph(t){const e=this.VisGraph.FindVertex(t.VisibilityBorderIntersect);if(e){t.ExtendEdgeChain(this.TransUtil,e,e,this.portSpliceLimitRectangle,this.RouteToCenterOfObstacles);return}const i={targetVertex:null},s=t.IsOverlapped?bt.OverlappedWeight:bt.NormalWeight;this.FindorCreateNearestPerpEdgePPDNT(t.MaxVisibilitySegment.end,t.VisibilityBorderIntersect,t.OutwardDirection,s,i)!=null&&t.AddToAdjacentVertex(this.TransUtil,i.targetVertex,this.portSpliceLimitRectangle,this.RouteToCenterOfObstacles)}InBoundsGraphBoxIntersect(t,e){return it.RectangleBorderIntersect(this.graphGenerator.ObstacleTree.GraphBox,t,e)}FindorCreateNearestPerpEdgePPDN(t,e,i,s){const n={targetVertex:null};return this.FindorCreateNearestPerpEdgePPDNT(t,e,i,s,n)}FindorCreateNearestPerpEdgePPDNT(t,e,i,s,n){const o=it.SortAscending(t,e),a=o[0],h=o[1],u=it.IsVerticalD(i)?this.HScanSegments:this.VScanSegments,c=it.IsAscending(i)?u.FindLowestIntersector(a,h):u.FindHighestIntersector(a,h);if(c==null)return n.targetVertex=null,null;const m=it.SegmentIntersectionSP(c,a);return this.FindOrCreateNearestPerpEdgeFromNearestPerpSegment(it.IsAscending(i)?a:h,c,m,s,n)}FindOrCreateNearestPerpEdgeFromNearestPerpSegment(t,e,i,s,n){var o;const a={segsegVertex:this.VisGraph.FindVertex(i),targetVertex:null};if(a.segsegVertex==null){const m=this.FindOrCreateSegmentIntersectionVertexAndAssociatedEdge(t,i,e,s,a);if(m!=null)return m}else if(L.EqualPP(t,i))return n.targetVertex=a.segsegVertex,this.TransUtil.FindNextEdge(n.targetVertex,j.OppositeDir(e.ScanDirection.Dir));const h=L.GetDirections(i,t);let u=L.GetDirections(a.segsegVertex.point,t);if(h===u){const m={bracketTarget:null,bracketSource:null};return pi.FindBracketingVertices(a.segsegVertex,t,h,m),(o=this.TransUtil.FindNextEdge(m.bracketSource,j.RotateLeft(h)))!==null&&o!==void 0?o:this.TransUtil.FindNextEdge(m.bracketSource,j.RotateRight(h))}u&=~h;const c=this.TransUtil.FindNearestPerpendicularOrContainingEdge(a.segsegVertex,u,t);return c==null?(n.targetVertex=this.TransUtil.AddVertex(i),this.TransUtil.FindOrAddEdge(n.targetVertex,e.HighestVisibilityVertex,e.Weight)):(a.segsegVertex=it.GetEdgeEnd(c,j.OppositeDir(u)),i=it.SegmentIntersectionPPP(t,i,a.segsegVertex.point),L.EqualPP(a.segsegVertex.point,i)?(n.targetVertex=a.segsegVertex,this.TransUtil.FindNextEdge(a.segsegVertex,u)):(n.targetVertex=this.TransUtil.FindOrAddVertex(i),this.TransUtil.FindOrAddEdge(a.segsegVertex,n.targetVertex,s)))}FindOrCreateSegmentIntersectionVertexAndAssociatedEdge(t,e,i,s,n){const a=(i.IsVertical?this.HScanSegments:this.VScanSegments).FindHighestIntersector(i.Start,e);if(a==null)return n.segsegVertex=null,n.targetVertex=this.TransUtil.AddVertex(e),this.TransUtil.FindOrAddEdge(n.targetVertex,i.LowestVisibilityVertex,i.Weight);const h=it.SegmentsIntersection(i,a);if(n.segsegVertex=this.VisGraph.FindVertex(h),!n.segsegVertex){n.segsegVertex=this.TransUtil.AddVertex(h);const u=this.AddEdgeToClosestSegmentEnd(i,n.segsegVertex,i.Weight);if(this.AddEdgeToClosestSegmentEnd(a,n.segsegVertex,a.Weight),L.EqualPP(n.segsegVertex.point,e))return n.targetVertex=n.segsegVertex,u}return L.EqualPP(t,e)?(n.targetVertex=this.TransUtil.FindOrAddVertex(e),this.TransUtil.FindOrAddEdge(n.segsegVertex,n.targetVertex,s)):(n.targetVertex=null,null)}AddEdgeToClosestSegmentEnd(t,e,i){return L.IsPureLower(t.HighestVisibilityVertex.point,e.point)?this.TransUtil.FindOrAddEdge(t.HighestVisibilityVertex,e,i):L.IsPureLower(e.point,t.LowestVisibilityVertex.point)?this.TransUtil.FindOrAddEdge(e,t.LowestVisibilityVertex,i):this.TransUtil.FindOrAddEdgeVV(t.LowestVisibilityVertex,e)}GetPortSpliceLimitRectangle(t){if(!this.LimitPortVisibilitySpliceToEndpointBoundingBox){this.portSpliceLimitRectangle=this.graphGenerator.ObstacleTree.GraphBox;return}this.portSpliceLimitRectangle=this.GetPortRectangle(t.sourcePort),this.portSpliceLimitRectangle.addRecSelf(this.GetPortRectangle(t.targetPort))}GetPortRectangle(t){const e=this.obstaclePortMap.get(t);return e?e.Obstacle.VisibilityBoundingBox.clone():Z.mkOnPoints([d.RoundPoint(t.Location)])}AddToLimitRectangle(t){this.graphGenerator.IsInBoundsP(t)&&this.portSpliceLimitRectangle.add(t)}FindOrCreateFreePoint(t){let e=this.freePointMap.get(t);return e?e.GetVertex(this.TransUtil,t):(e=new uu(this.TransUtil,t),this.freePointMap.set(t,e)),this.freePointsInGraph.add(e),this.freePointLocationsUsedByRouteEdges.add(t),e}AddFreePointToGraph(t){t=d.RoundPoint(t);const e=this.VisGraph.FindVertex(t),i=this.FindOrCreateFreePoint(t);if(e!=null)return i;if(!this.graphGenerator.IsInBoundsP(t))return this.CreateOutOfBoundsFreePoint(i),i;let s=null;i.IsOverlapped=this.ObstacleTree.PointIsInsideAnObstacle(i.Point,this.HScanSegments.ScanDirection);let n;if(this.VScanSegments.FindSegmentContainingPoint(t,!0),n!=null){const a={targetVertex:null};s=this.FindOrCreateNearestPerpEdgeFromNearestPerpSegment(t,n,t,i.InitialWeight,a)}let o=v.South;if(s!=null)o=it.EdgeDirectionVE(s),this.ConnectFreePointToLateralEdge(i,j.RotateLeft(o)),this.ConnectFreePointToLateralEdge(i,j.RotateRight(o));else for(let a=0;a<4;a++)this.ConnectFreePointToLateralEdge(i,o),o=j.RotateLeft(o);return i}CreateOutOfBoundsFreePoint(t){const e=t.Point,i=this.graphGenerator.MakeInBoundsLocation(e),s=L.GetDirections(i,e);if(t.OutOfBoundsDirectionFromGraph=s,!L.IsPureDirectionD(s)){t.AddOobEdgesFromGraphCorner(this.TransUtil,i);return}let n=this.VisGraph.FindVertex(i);const o=j.OppositeDir(s);if(n!=null)t.AddToAdjacentVertex(this.TransUtil,n,o,this.portSpliceLimitRectangle);else{const u=this.FindorCreateNearestPerpEdgePPDN(e,i,s,bt.NormalWeight);u!=null&&(n=t.AddEdgeToAdjacentEdge(this.TransUtil,u,o,this.portSpliceLimitRectangle))}const a=it.FindAdjacentVertex(n,j.RotateLeft(o));a!=null&&this.TransUtil.ConnectVertexToTargetVertex(t.Vertex,a,o,bt.NormalWeight);const h=it.FindAdjacentVertex(n,j.RotateRight(o));h!=null&&this.TransUtil.ConnectVertexToTargetVertex(t.Vertex,h,o,bt.NormalWeight)}ConnectFreePointToLateralEdge(t,e){const i=t.IsOverlapped?this.InBoundsGraphBoxIntersect(t.Point,e):t.MaxVisibilityInDirectionForNonOverlappedFreePoint(e,this.TransUtil),s=this.FindorCreateNearestPerpEdgePPDN(i,t.Point,e,t.InitialWeight);s!=null&&t.AddEdgeToAdjacentEdge(this.TransUtil,s,e,this.portSpliceLimitRectangle)}}class me extends zt{constructor(t,e,i){super(null),this.Padding=0,this.CornerFitRadius=0,this.edgeSeparatian=3,this.BendPenaltyAsAPercentageOfDistance=0,this.ShapeToObstacleMap=new Map,this.EdgesToRoute=new Array,this.removeStaircases=!0,this.selfEdges=new Array,this.Padding=e,this.CornerFitRadius=i,this.BendPenaltyAsAPercentageOfDistance=Vt.DefaultBendPenaltyAsAPercentageOfDistance,this.GraphGenerator=new fi,this.PortManager=new Mr(this.GraphGenerator),this.AddShapes(t)}get RouteToCenterOfObstacles(){return this.PortManager.RouteToCenterOfObstacles}set RouteToCenterOfObstacles(t){this.PortManager.RouteToCenterOfObstacles=t}get LimitPortVisibilitySpliceToEndpointBoundingBox(){return this.PortManager.LimitPortVisibilitySpliceToEndpointBoundingBox}set LimitPortVisibilitySpliceToEndpointBoundingBox(t){this.PortManager.LimitPortVisibilitySpliceToEndpointBoundingBox=t}AddEdgeGeometryToRoute(t){d.closeDistEps(d.RoundPoint(t.sourcePort.Location),d.RoundPoint(t.targetPort.Location))?this.selfEdges.push(t):this.EdgesToRoute.push(t)}get EdgeGeometriesToRoute(){return this.EdgesToRoute}RemoveAllEdgeGeometriesToRoute(){this.EdgesToRoute=[]}get UseSparseVisibilityGraph(){return this.GraphGenerator instanceof fi}get Obstacles(){return Array.from(this.ShapeToObstacleMap.values()).map(t=>t.InputShape)}get PaddedObstacles(){return Array.from(this.ShapeToObstacleMap.values()).map(t=>t.PaddedPolyline)}AddObstacles(t){this.AddShapes(t),this.RebuildTreeAndGraph()}AddShapes(t){for(const e of t)this.AddObstacleWithoutRebuild(e)}AddObstacle(t){this.AddObstacleWithoutRebuild(t),this.RebuildTreeAndGraph()}UpdateObstacles(t){for(const e of t)this.UpdateObstacleWithoutRebuild(e);this.RebuildTreeAndGraph()}UpdateObstacle(t){this.UpdateObstacleWithoutRebuild(t),this.RebuildTreeAndGraph()}RemoveObstacles(t){for(const e of t)this.RemoveObstacleWithoutRebuild(e);this.RebuildTreeAndGraph()}RemoveObstacle(t){this.RemoveObstacleWithoutRebuild(t),this.RebuildTreeAndGraph()}AddObstacleWithoutRebuild(t){if(t.BoundaryCurve==null)throw new Error("Shape must have a BoundaryCurve");this.CreatePaddedObstacle(t)}UpdateObstacleWithoutRebuild(t){if(t.BoundaryCurve==null)throw new Error("Shape must have a BoundaryCurve");this.PortManager.RemoveObstaclePorts(this.ShapeToObstacleMap.get(t)),this.CreatePaddedObstacle(t)}CreatePaddedObstacle(t){const e=new Ee(t,this.Padding);this.ShapeToObstacleMap.set(t,e),this.PortManager.CreateObstaclePorts(e)}RemoveObstacleWithoutRebuild(t){const e=this.ShapeToObstacleMap.get(t);this.ShapeToObstacleMap.delete(t),this.PortManager.RemoveObstaclePorts(e)}RemoveAllObstacles(){this.InternalClear(!1)}RebuildTreeAndGraph(){const t=this.ObsTree.Root!=null,e=this.GraphGenerator.VisibilityGraph!=null;this.InternalClear(!0),t&&this.GenerateObstacleTree(),e&&this.GenerateVisibilityGraph()}get VisibilityGraph(){return this.GenerateVisibilityGraph(),this.GraphGenerator.VisibilityGraph}Clear(){this.InternalClear(!1)}static constructorEmpty(){return me.constructorC(null)}static constructorC(t){return new me([],me.DefaultPadding,me.DefaultCornerFitRadius)}static constructorI(t){return new me(t,me.DefaultPadding,me.DefaultCornerFitRadius)}static constructorINN(t,e,i){return new me(t,e,i)}static constructorGNAN(t,e,i,s){const n=new me(Ve.GetShapes(t),i,s);if(e==null)for(const o of t.deepEdges)n.AddEdgeGeometryToRoute(o);else for(const o of e)n.AddEdgeGeometryToRoute(o);return n}run(){this.GenerateVisibilityGraph(),this.GeneratePaths()}GeneratePaths(){const t=this.EdgesToRoute.map(e=>new au(e));this.FillEdgePathsWithShortestPaths(t),this.NudgePaths(t),this.RouteSelfEdges(),this.FinaliseEdgeGeometries()}RouteSelfEdges(){for(const t of this.selfEdges){const e={smoothedPolyline:null};t.curve=Ne.RouteSelfEdge(t.sourcePort.Curve,Math.max(this.Padding,2*t.GetMaxArrowheadLength()),e)}}FillEdgePathsWithShortestPaths(t){this.PortManager.BeginRouteEdges();const e=new kr(this.BendPenaltyAsAPercentageOfDistance);for(const i of t)this.AddControlPointsAndGeneratePath(e,i);this.PortManager.EndRouteEdges()}AddControlPointsAndGeneratePath(t,e){const i=this.PortManager.GetPortVisibilityIntersection(e.GeomEdge);if(i!=null){this.GeneratePathThroughVisibilityIntersection(e,i);return}this.SpliceVisibilityAndGeneratePath(t,e)}GeneratePathThroughVisibilityIntersection(t,e){t.PathPoints=e}SpliceVisibilityAndGeneratePath(t,e){this.PortManager.AddControlPointsToGraph(e.GeomEdge,this.ShapeToObstacleMap),this.GeneratePath(t,e,!1)||this.RetryPathsWithAdditionalGroupsEnabled(t,e),this.PortManager.RemoveControlPointsFromGraph()}GeneratePath(t,e,i){const s=this.PortManager.FindVertices(e.GeomEdge.sourcePort),n=this.PortManager.FindVertices(e.GeomEdge.targetPort);return me.GetSingleStagePath(e,t,s,n,i)}static GetSingleStagePath(t,e,i,s,n){return t.PathPoints=e.GetPath(i,s),n&&me.EnsureNonNullPath(t),t.PathPoints!=null&&t.PathPoints.length>0}static EnsureNonNullPath(t){t.PathPoints==null&&(L.IsPureDirection(t.GeomEdge.sourcePort.Location,t.GeomEdge.targetPort.Location)?t.PathPoints=[t.GeomEdge.sourcePort.Location,t.GeomEdge.targetPort.Location]:t.PathPoints=[t.GeomEdge.sourcePort.Location,new d(t.GeomEdge.sourcePort.Location.x,t.GeomEdge.targetPort.Location.y),t.GeomEdge.targetPort.Location])}RetryPathsWithAdditionalGroupsEnabled(t,e){(!this.PortManager.SetAllAncestorsActive(e.GeomEdge,this.ShapeToObstacleMap)||!this.GeneratePath(t,e,!1))&&(this.PortManager.SetAllGroupsActive(),this.GeneratePath(t,e,!0))}NudgePaths(t){const e=this.ObsTree.SpatialAncestorsAdjusted?Zt.GetAncestorSetsMap(this.Obstacles):this.AncestorsSets;Jt.NudgePaths(t,this.edgeSeparatian,this.PaddedObstacles,e,this.RemoveStaircases)}get RemoveStaircases(){return this.removeStaircases}set RemoveStaircases(t){this.removeStaircases=t}FinaliseEdgeGeometries(){for(const t of this.EdgesToRoute.concat(this.selfEdges)){if(t.curve==null)continue;t.curve instanceof at&&(t.curve=me.FitArcsIntoCorners(this.CornerFitRadius,Array.from(t.curve))),me.CalculateArrowheads(t)}}CreateVisibilityGraph(){this.GraphGenerator.Clear(),this.InitObstacleTree(),this.GraphGenerator.GenerateVisibilityGraph()}static CalculateArrowheads(t){Mt.trimSplineAndCalculateArrowheadsII(t,t.sourcePort.Curve,t.targetPort.Curve,t.curve,!0)}get ObsTree(){return this.GraphGenerator.ObstacleTree}GenerateObstacleTree(){if(this.Obstacles==null||this.Obstacles.length===0)throw new Error("No obstacles have been added");this.ObsTree.Root==null&&this.InitObstacleTree()}InitObstacleTree(){this.AncestorsSets=Zt.GetAncestorSetsMap(this.Obstacles),this.ObsTree.Init(this.ShapeToObstacleMap.values(),this.AncestorsSets,this.ShapeToObstacleMap)}InternalClear(t){this.GraphGenerator.Clear(),this.ClearShortestPaths(),t?this.PortManager.ClearVisibility():(this.PortManager.Clear(),this.ShapeToObstacleMap.clear(),this.EdgesToRoute=[])}ClearShortestPaths(){for(const t of this.EdgesToRoute)t.curve=null}GenerateVisibilityGraph(){if(this.Obstacles==null||this.Obstacles.length===0)throw new Error("No obstacles have been set");this.GraphGenerator.VisibilityGraph==null&&this.CreateVisibilityGraph()}static FitArcsIntoCorners(t,e){if(t==0)return at.mkFromPoints(e);const i=me.GetFittedArcSegs(t,e),s=new w;let n=null;for(const o of i){const a=me.EllipseIsAlmostLineSegment(o);n!=null?a?w.continueWithLineSegmentP(s,me.CornerPoint(o)):(w.continueWithLineSegmentP(s,o.start),s.addSegment(o)):a?w.addLineSegment(s,e[0],me.CornerPoint(o)):(w.addLineSegment(s,e[0],o.start),s.addSegment(o)),n=o}return s.segs.length>0?w.continueWithLineSegmentP(s,e[e.length-1]):w.addLineSegment(s,e[0],e[e.length-1]),s}static CornerPoint(t){return t.center.add(t.aAxis.add(t.bAxis))}static EllipseIsAlmostLineSegment(t){return t.aAxis.lengthSquared<1e-4||t.aAxis.lengthSquared<1e-4}static*GetFittedArcSegs(t,e){let i=e[1].sub(e[0]),s=i.normalize(),n=Math.min(t,i.length/2);for(let o=1;o<e.length-1;o++){i=e[o+1].sub(e[o]);const a=i.length;if(a<C.intersectionEpsilon){yield new vt(0,0,new d(0,0),new d(0,0),e[o]);continue}const h=i.div(a);Math.abs(h.dot(s))>.9&&(yield new vt(0,0,new d(0,0),new d(0,0),e[o]));const u=Math.min(t,i.length/2),c=h.mul(-u),m=s.mul(n);yield new vt(0,Math.PI/2,c,m,e[o].sub(m.add(c))),s=h,n=u}}}me.DefaultPadding=1,me.DefaultCornerFitRadius=3;class ks{constructor(t,e,i,s=1){this.Source=t,this.Target=e,this.CrossingWeight=i,this.Weight=s}toString(){return Se.Qf.Format("{0}->{1}",this.Source,this.Target)}}class _n{static FindClosestPoints(t,e){const i=w.minDistWithinIntervals(t,e,t.parStart,t.parEnd,e.parStart,e.parEnd,(t.parStart+t.parEnd)/2,(e.parStart+e.parEnd)/2);if(i)return{curveClosestPoint:i.aX,labelSideClosest:i.bX}}static GetSegmentInFrontOfLabel(t,e){if(t instanceof w){for(const i of t.segs)if((i.start.y-e)*(i.end.y-e)<=0)return i}return null}static ShiftLabel(t,e,i){const s=t.lineWidth/2,n=e.sub(i),o=n.length;o>s&&t.label.positionCenter(t.label.center.add(n.div(o*(o-s))))}static updateLabel(t,e){let i=null;e.labelIsToTheRightOfTheSpline?(t.label.positionCenter(new d(e.x+e.rightAnchor/2,e.y)),i=D.mkPP(t.label.boundingBox.leftTop,t.label.boundingBox.leftBottom)):e.labelIsToTheLeftOfTheSpline&&(t.label.positionCenter(new d(e.x-e.leftAnchor/2,e.y)),i=D.mkPP(t.label.boundingBox.rightTop,t.label.boundingBox.rightBottom));const s=_n.GetSegmentInFrontOfLabel(t.curve,t.label.center.y);if(s!=null&&w.getAllIntersections(t.curve,w.polyFromBox(t.label.boundingBox),!1).length===0){const n=_n.FindClosestPoints(s,i);if(n)_n.ShiftLabel(t,n.curveClosestPoint,n.labelSideClosest);else{let o,a;const h=s.closestParameter(i.start),u=s.closestParameter(i.end);s.value(h).sub(i.start).length<s.value(u).sub(i.end).length?(o=s.value(h),a=i.start):(o=s.value(u),a=i.end),_n.ShiftLabel(t,o,a)}}}}class $i{constructor(t,e,i,s=1,n=1){this.reversed=!1,this.source=t,this.target=e,this.edge=i,this.weight=s,this.separation=n}get CrossingWeight(){return 1}get hasLabel(){return this.edge.label!=null}get labelWidth(){return this.edge.label.width}get labelHeight(){return this.edge.label.height}reverse(){const t=this.source;this.source=this.target,this.target=t,this.reversed=!this.reversed}toString(){return"edge("+this.source+"->"+this.target+")"}get curve(){return this.edge.curve}set curve(t){this.edge.curve=t}get underlyingPolyline(){return this.edge.smoothedPolyline}get LayerSpan(){return this.LayerEdges!=null?this.LayerEdges.length:0}isSelfEdge(){return this.source===this.target}reversedClone(){const t=new $i(this.target,this.source,this.edge);if(this.LayerEdges!=null){const e=this.LayerEdges.length;t.LayerEdges=new Array(e);for(let i=0;i<e;i++){const s=this.LayerEdges[e-1-i];t.LayerEdges[i]=new ks(s.Target,s.Source,s.CrossingWeight)}t.LayerEdges[0].Source=this.target,t.LayerEdges[this.LayerEdges.length-1].Target=this.source}return t}get count(){return this.LayerEdges.length}getNode(t){if(t>=0){if(t<this.LayerEdges.length)return this.LayerEdges[t].Source;if(t===this.LayerEdges.length)return this.LayerEdges[t-1].Target}throw new Error("wrong index "+t)}updateEdgeLabelPosition(t){if(this.edge.label!=null){const e=this.LayerEdges.length/2,i=this.LayerEdges[e];_n.updateLabel(this.edge,t[i.Source])}}[Symbol.iterator](){return this.nodes()}*nodes(){yield this.LayerEdges[0].Source;for(const t of this.LayerEdges)yield t.Target}}class pu{constructor(){this.maxLayerOfGeomGraph=new Set,this.minLayerOfGeomGraph=new Set,this.sameLayerConstraints=new Array,this.upDownConstraints=new Array,this.gluedUpDownIntConstraints=new ji,this.sameLayerDictionaryOfRepresentatives=new Map,this.representativeToItsLayer=new Map,this.maxLayerInt=new Array,this.minLayerInt=new Array,this.sameLayerInts=new Array,this.upDownInts=new Array}getFeedbackSetExternal(t,e){throw new Error("Method not implemented.")}pinNodeToMaxLayer(t){this.maxLayerOfGeomGraph.add(t)}pinNodeToMinLayer(t){this.minLayerOfGeomGraph.add(t)}get isEmpty(){return this.maxLayerOfGeomGraph.size===0&&this.minLayerOfGeomGraph.size===0&&this.sameLayerConstraints.length===0&&this.upDownConstraints.length===0}clear(){this.maxLayerOfGeomGraph.clear(),this.minLayerOfGeomGraph.clear(),this.sameLayerConstraints=[],this.upDownConstraints=[]}getFeedbackSetImp(t,e){return this.nodeIdToIndex=e,this.intGraph=t,this.maxRepresentative=-1,this.minRepresentative=-1,this.createIntegerConstraints(),this.glueTogetherSameConstraintsMaxAndMin(),this.addMaxMinConstraintsToGluedConstraints(),this.removeCyclesFromGluedConstraints(),this.getFeedbackSet()}removeCyclesFromGluedConstraints(){const t=ni(Array.from(this.gluedUpDownIntConstraints.values()),this.intGraph.nodeCount),e=y.getFeedbackSetWithConstraints(t,null);for(const i of e)this.gluedUpDownIntConstraints.remove(i)}addMaxMinConstraintsToGluedConstraints(){if(this.maxRepresentative!==-1)for(let t=0;t<this.intGraph.nodeCount;t++){const e=this.nodeToRepr(t);e!==this.maxRepresentative&&this.gluedUpDownIntConstraints.add(new Ot(this.maxRepresentative,e))}if(this.minRepresentative!==-1)for(let t=0;t<this.intGraph.nodeCount;t++){const e=this.nodeToRepr(t);e!==this.minRepresentative&&this.gluedUpDownIntConstraints.add(new Ot(e,this.minRepresentative))}}glueTogetherSameConstraintsMaxAndMin(){this.createDictionaryOfSameLayerRepresentatives();const t=this.upDownInts.map(this.gluedIntPairNN);this.gluedUpDownIntConstraints=new ji}gluedIntPairNN(t){return new Ot(this.nodeToRepr(t[0]),this.nodeToRepr(t[1]))}gluedIntPairI(t){return new Ot(this.nodeToRepr(t.source),this.nodeToRepr(t.target))}gluedIntPair(t){return new Ot(this.nodeToRepr(t.source),this.nodeToRepr(t.target))}gluedIntEdge(t){const e=this.nodeToRepr(t.source),i=this.nodeToRepr(t.target),s=new $i(e,i,t.edge);return s.separation=t.separation,s.weight=0,s}nodeToRepr(t){const e=this.sameLayerDictionaryOfRepresentatives.get(t);return e||t}createDictionaryOfSameLayerRepresentatives(){const t=this.createGraphOfSameLayers();for(const e of Vi(t))this.glueSameLayerNodesOfALayer(e)}createGraphOfSameLayers(){return ni(this.createEdgesOfSameLayers(),this.intGraph.nodeCount)}createEdgesOfSameLayers(){const t=new Array;return this.maxRepresentative!==-1&&this.maxLayerInt.filter(e=>e!==this.maxRepresentative).map(e=>new Ot(this.maxRepresentative,e)).forEach(e=>t.push(e)),this.minRepresentative!==-1&&this.minLayerInt.filter(e=>e!==this.minRepresentative).map(e=>new Ot(this.minRepresentative,e)).forEach(e=>t.push(e)),this.sameLayerInts.forEach(e=>t.push(new Ot(e[0],e[1]))),t}glueSameLayerNodesOfALayer(t){if(t.length>1){let e=-1;if(this.componentsIsMaxLayer(t))for(const i of t)this.sameLayerDictionaryOfRepresentatives.set(i,e=this.maxRepresentative);else if(this.componentIsMinLayer(t))for(const i of t)this.sameLayerDictionaryOfRepresentatives.set(i,e=this.minRepresentative);else for(const i of t)e===-1&&(e=i),this.sameLayerDictionaryOfRepresentatives.set(i,e);this.representativeToItsLayer.set(e,t)}}componentIsMinLayer(t){return t.findIndex(e=>this.minRepresentative===e)>=0}componentsIsMaxLayer(t){return t.findIndex(e=>this.maxRepresentative===e)>=0}createIntegerConstraints(){this.createMaxIntConstraints(),this.createMinIntConstraints(),this.createUpDownConstraints(),this.createSameLayerConstraints()}createSameLayerConstraints(){this.sameLayerInts=this.createIntConstraintsFromStringCouples(this.sameLayerConstraints)}createUpDownConstraints(){this.upDownInts=this.createIntConstraintsFromStringCouples(this.upDownConstraints)}createIntConstraintsFromStringCouples(t){return t.map(e=>[this.nodeIndex(e[0]),this.nodeIndex(e[1])]).filter(e=>e[0]!==-1&&e[1]!==-1)}createMinIntConstraints(){this.minLayerInt=this.createIntConstraintsFromExtremeLayer(this.minLayerOfGeomGraph),this.minLayerInt.length>0&&(this.minRepresentative=this.minLayerInt[0])}createMaxIntConstraints(){this.maxLayerInt=this.createIntConstraintsFromExtremeLayer(this.maxLayerOfGeomGraph),this.maxLayerInt.length>0&&(this.maxRepresentative=this.maxLayerInt[0])}createIntConstraintsFromExtremeLayer(t){return Array.from(t).map(e=>this.nodeIndex(e)).filter(e=>e!==-1)}nodeIndex(t){const e=this.nodeIdToIndex.get(t.node.id);return e||-1}getFeedbackSet(){return this.gluedIntGraph=this.createGluedGraph(),Array.from(this.unglueIntPairs(y.getFeedbackSetWithConstraints(this.gluedIntGraph,this.gluedUpDownIntConstraints)))}*unglueIntPairs(t){for(const e of t)for(const i of this.unglueEdge(e))yield i}*unglueEdge(t){for(const e of this.unglueNode(t.source))for(const i of this.intGraph.outEdges[e])this.nodeToRepr(i.target)===t.target&&(yield i)}createGluedGraph(){const t=new ji;return this.intGraph.edges.forEach(e=>t.add(this.gluedIntPairI(e))),ni(Array.from(t.values()),this.intGraph.nodeCount)}unglueNode(t){const e=this.representativeToItsLayer.get(t);return e||[t]}getGluedNodeCounts(){const t=new Array(this.nodeIdToIndex.size).fill(0);for(let e=0;e<t.length;e++)t[this.nodeToRepr(e)]++;return t}}function mu(l,t){return[l,t]}class Pu{constructor(){this.leftRightConstraints=new Array,this.leftRightNeighbors=new Array,this.nodeToBlockRoot=new Map,this.upDownVerticalConstraints=new Array,this.BlockRootToBlock=new Map}get IsEmpty(){return this.leftRightNeighbors.length===0&&this.upDownVerticalConstraints.length===0&&this.leftRightConstraints.length===0}AddSameLayerNeighbors(t){for(let e=0;e<t.length-1;e++)this.AddSameLayerNeighborsPair(t[e],t[e+1])}AddSameLayerNeighborsPair(t,e){this.leftRightNeighbors.push([t,e])}NodeToBlockRootSoft(t){const e=this.nodeToBlockRoot.get(t);return e||t}CreateMappingOfNeibBlocks(){const t=this.BasicGraphFromLeftRightIntNeibs();for(let e=0;e<t.nodeCount;e++)if(t.inEdges[e].length===0&&!this.nodeToBlockRoot.has(e)){const i=new Array;let s=e;for(let n=t.outEdges[s];n.length>0;n=t.outEdges[s])s=n[0].y,i.push(s),this.nodeToBlockRoot.set(s,e);i.length>0&&this.BlockRootToBlock.set(e,i)}}BasicGraphFromLeftRightIntNeibs(){return ln(Array.from(this.LeftRightIntNeibs.values()).map(t=>new Ot(t.x,t.y)))}NodeIndex(t){const e=this.nodeIdToIndex.get(t.id);return e||-1}PrepareForOrdering(t,e){this.nodeIdToIndex=t,this.MapNodesToToIntegers(e),this.CreateMappingOfNeibBlocks(),this.LiftLeftRightRelationsToNeibBlocks()}LiftLeftRightRelationsToNeibBlocks(){this.LeftRighInts=ji.mk(this.leftRightConstraints.map(e=>mu(this.NodeIndex(e[0]),this.NodeIndex(e[1]))).filter(e=>e[0]!==-1&&e[1]!==-1).map(e=>new Ot(this.NodeToBlockRootSoft(e[0]),this.NodeToBlockRootSoft(e[1]))).filter(e=>e.x!==e.x));const t=y.getFeedbackSet(ln(Array.from(this.LeftRighInts.values())));for(const e of t)this.LeftRighInts.remove(new Ot(e.source,e.target))}MapNodesToToIntegers(t){this.LeftRightIntNeibs=ji.mk(Array.from(this.leftRightNeighbors.values()).map(e=>[this.NodeIndex(e[0]),this.NodeIndex(e[1])]).filter(e=>e[0]!==-1&&e[1]!==-1).map(e=>new Ot(e[0],e[1]))),this.VerticalInts=ji.mk(this.upDownVerticalConstraints.map(e=>[this.NodeIndex(e[0]),this.NodeIndex(e[1])]).filter(e=>e[0]!==-1&&e[1]!==-1&&t[e[0]]>t[e[1]]).map(e=>new Ot(e[0],e[1])))}}var xi;(function(l){l[l.TB=0]="TB",l[l.LR=1]="LR",l[l.BT=2]="BT",l[l.RL=3]="RL",l[l.None=4]="None"})(xi||(xi={}));var He;(function(l){l[l.Spline=0]="Spline",l[l.SplineBundling=1]="SplineBundling",l[l.StraightLine=2]="StraightLine",l[l.SugiyamaSplines=3]="SugiyamaSplines",l[l.Rectilinear=4]="Rectilinear",l[l.RectilinearToCenter=5]="RectilinearToCenter",l[l.None=6]="None"})(He||(He={}));class Vr{constructor(){this.coneAngle=30*(Math.PI/180),this.padding=2,this.polylinePadding=1,this.routingToParentConeAngle=Math.PI/6,this.simpleSelfLoopsForParentEdgesThreshold=200,this.incrementalRoutingThreshold=5e6,this.routeMultiEdgesAsBundles=!0,this.KeepOriginalSpline=!1,this.EdgeRoutingMode=He.Spline}toJSON(){const t={};return this.EdgeRoutingMode!=He.Spline&&(t.edgeRoutingMode=He.Spline),this.ConeAngle!=30*(Math.PI/180)&&(t.coneAngle=this.ConeAngle),this.padding!=3&&(t.padding=this.padding),this.polylinePadding!=1.5&&(t.polylinePadding=this.polylinePadding),this.bundlingSettings&&(t.bundlingSettingsJSON=this.bundlingSettings.toJSON()),t}static fromJSON(t){const e=new Vr;return t.edgeRoutingMode&&(t.edgeRoutingMode=e.edgeRoutingMode),t.coneAngle&&(e.coneAngle=t.coneAngle),t.padding&&(e.padding=t.padding),t.polylinePadding&&(e.polylinePadding=t.polylinePadding),t.bundlingSettingsJSON&&(e.bundlingSettings=ge.createFromJSON(t.bundlingSettingsJSON)),t.routingToParentConeAngle&&(e.routingToParentConeAngle=t.routingToParentConeAngle),t.simpleSelfLoopsForParentEdgesThreshold&&(e.simpleSelfLoopsForParentEdgesThreshold=t.simpleSelfLoopsForParentEdgesThreshold),t.incrementalRoutingThreshold&&(e.incrementalRoutingThreshold=t.incrementalRoutingThreshold),t.routeMultiEdgesAsBundles&&(e.routeMultiEdgesAsBundles=t.routeMultiEdgesAsBundles),t.KeepOriginalSpline&&(e.KeepOriginalSpline=t.KeepOriginalSpline),e}get EdgeRoutingMode(){return this.edgeRoutingMode}set EdgeRoutingMode(t){t===He.SplineBundling&&this.bundlingSettings==null&&this.bundlingSettings==null&&(this.bundlingSettings=new ge),this.edgeRoutingMode=t}get ConeAngle(){return this.coneAngle}set ConeAngle(t){this.coneAngle=t}get Padding(){return this.padding}set Padding(t){this.padding=t}get PolylinePadding(){return this.polylinePadding}set PolylinePadding(t){this.polylinePadding=t}get RoutingToParentConeAngle(){return this.routingToParentConeAngle}set RoutingToParentConeAngle(t){this.routingToParentConeAngle=t}get SimpleSelfLoopsForParentEdgesThreshold(){return this.simpleSelfLoopsForParentEdgesThreshold}set SimpleSelfLoopsForParentEdgesThreshold(t){this.simpleSelfLoopsForParentEdgesThreshold=t}get IncrementalRoutingThreshold(){return this.incrementalRoutingThreshold}set IncrementalRoutingThreshold(t){this.incrementalRoutingThreshold=t}get RouteMultiEdgesAsBundles(){return this.routeMultiEdgesAsBundles}set RouteMultiEdgesAsBundles(t){this.routeMultiEdgesAsBundles=t}}class tr{constructor(){this.edgeRoutingSettings=new Vr,this.nodeSeparation=10,this.packingAspectRatio=1.5}static fromJSON(t){const e=new tr;return t.nodeSeparation!=10&&(e.nodeSeparation=t.nodeSeparation),t.packingAspectRatio&&(e.packingAspectRatio=t.packingAspectRatio),t.edgeRoutingSettings&&(e.edgeRoutingSettings=Vr.fromJSON(t.edgeRoutingSettings)),e}toJSON(){let t=!1;const e={};return this.nodeSeparation!=10&&(e.nodeSeparation=this.nodeSeparation,t=!0),this.packingAspectRatio!=1.5&&(e.packingAspectRatio=this.packingAspectRatio,t=!0),(e.edgeRoutingSettings=this.edgeRoutingSettings.toJSON())&&(t=!0),t?e:void 0}get NodeSeparation(){return this.nodeSeparation}set NodeSeparation(t){this.nodeSeparation=t}get PackingAspectRatio(){return this.packingAspectRatio}set PackingAspectRatio(t){this.packingAspectRatio=t}}var er;(function(l){l[l.None=0]="None",l[l.Top=1]="Top",l[l.Bottom=2]="Bottom"})(er||(er={}));class Sn{constructor(){this.commonSettings=new tr,this.verticalConstraints=new pu,this.horizontalConstraints=new Pu,this.NoGainAdjacentSwapStepsBound=5,this.NoGainStepsForOrderingMultiplier=1,this.AspectRatio=0,this.MaxNumberOfPassesInOrdering=24,this.BrandesThreshold=600,this.LabelCornersPreserveCoefficient=.1,this.MinNodeHeight=72*.5/4,this.MinNodeWidth=72*.75/4,this.SnapToGridByY=er.None,this.yLayerSep=10*3,this.transform=st.getIdentity(),this.GridSizeByY=0,this.GridSizeByX=0,this.commonSettings.edgeRoutingSettings.EdgeRoutingMode=He.SugiyamaSplines}get NodeSeparation(){return this.commonSettings.NodeSeparation}get edgeRoutingSettings(){return this.commonSettings.edgeRoutingSettings}set edgeRoutingSettings(t){this.commonSettings.edgeRoutingSettings=t}toJSON(){const t={};return this.sameRanks&&(t.sameRanks=this.sameRanks),this.verticalConstraints&&(t.verticalConstraints=this.verticalConstraints),this.horizontalConstraints&&(t.horizontalConstraints=this.horizontalConstraints),this.NoGainAdjacentSwapStepsBound!=5&&(t.horizontalConstraints=this.horizontalConstraints),this.NoGainStepsForOrderingMultiplier!=1&&(t.RepetitionCoefficientForOrdering=this.NoGainStepsForOrderingMultiplier),this.AspectRatio&&(t.AspectRatio=this.AspectRatio),this.MaxNumberOfPassesInOrdering!=24&&(t.MaxNumberOfPassesInOrdering=this.MaxNumberOfPassesInOrdering),this.BrandesThreshold!=600&&(t.BrandesThreshold=this.BrandesThreshold),this.LabelCornersPreserveCoefficient!=.1&&(t.LabelCornersPreserveCoefficient=this.LabelCornersPreserveCoefficient),this.MinNodeHeight!=72*.5/4&&(t.MinNodeHeight=this.MinNodeHeight),this.MinNodeWidth!=72*.75/4&&(t.MinNodeWidth=this.MinNodeWidth),this.SnapToGridByY!=er.None&&(t.SnapToGridByY=this.SnapToGridByY),this.yLayerSep!=10*3&&(t.yLayerSep=this.yLayerSep),this.transform&&(t.transform=this.transform.elements),this.GridSizeByY&&(t.GridSizeByY=this.GridSizeByY),this.GridSizeByX&&(t.GridSizeByX=this.GridSizeByX),t.commonLayoutSettings=this.commonSettings.toJSON(),t}static fromJSON(t){const e=new Sn;return t.sameRanks&&(e.sameRanks=t.sameRanks),t.verticalConstraints&&(e.verticalConstraints=t.verticalConstraints),t.horizontalConstraints&&(e.horizontalConstraints=t.horizontalConstraints),t.NoGainAdjacentSwapStepsBound&&(e.horizontalConstraints=t.horizontalConstraints),t.RepetitionCoefficientForOrdering&&(e.NoGainStepsForOrderingMultiplier=t.RepetitionCoefficientForOrdering),t.AspectRatio&&(e.AspectRatio=t.AspectRatio),t.MaxNumberOfPassesInOrdering&&(e.MaxNumberOfPassesInOrdering=t.MaxNumberOfPassesInOrdering),t.BrandesThreshold&&(e.BrandesThreshold=t.BrandesThreshold),t.LabelCornersPreserveCoefficient&&(e.LabelCornersPreserveCoefficient=t.LabelCornersPreserveCoefficient),t.MinNodeHeight&&(e.MinNodeHeight=t.MinNodeHeight),t.MinNodeWidth&&(e.MinNodeWidth=e.MinNodeWidth),t.SnapToGridByY&&(e.SnapToGridByY=t.SnapToGridByY),t.yLayerSep&&(e.yLayerSep=t.yLayerSep),t.transform&&(e.transform=new st(t.transform[0][0],t.transform[0][1],t.transform[0][2],t.transform[1][0],t.transform[1][1],t.transform[1][2])),t.GridSizeByY&&(e.GridSizeByY=t.GridSizeByY),t.GridSizeByX&&(e.GridSizeByX=t.GridSizeByX),t.commonLayoutSettings&&(e.commonSettings=tr.fromJSON(t.commonLayoutSettings)),e}get LayerSeparation(){return this.yLayerSep}set LayerSeparation(t){this.yLayerSep=Math.max(10*3,t)}ActualLayerSeparation(t){return t?this.LayerSeparation/2:this.LayerSeparation}transformIsRotation(t){const e=st.rotation(t);for(let i=0;i<2;i++)for(let s=0;s<3;s++)if(!N(e.elements[i][s],this.transform.elements[i][s]))return!1;return!0}get layerDirection(){if(this.transformIsRotation(0))return xi.TB;if(this.transformIsRotation(Math.PI/2))return xi.LR;if(this.transformIsRotation(-Math.PI/2))return xi.RL;if(this.transformIsRotation(Math.PI))return xi.BT;throw new Error("unexpected layout direction")}set layerDirection(t){switch(t){case xi.TB:this.transform=st.getIdentity();break;case xi.LR:this.transform=st.rotation(Math.PI/2);break;case xi.RL:this.transform=st.rotation(-Math.PI/2);break;case xi.BT:this.transform=st.rotation(Math.PI);break;default:throw new Error("unexpected layout direction")}}}class Bl extends zt{constructor(t,e,i){super(null),this.graph=t,this.source=e,this.length=i}get Result(){return this.result}run(){const t=new es((s,n)=>s-n),e=new Map;for(const s of this.graph.shallowNodes){const n=s===this.source?0:Number.POSITIVE_INFINITY;t.Enqueue(s,n),e.set(s,n)}for(;t.count>0;){const s={priority:0},n=t.DequeueAndGetPriority(s);e.set(n,s.priority);const o=e.get(n);for(const a of n.inEdges()){const h=a.source,u=o+this.length(a);e.get(h)>u&&(e.set(h,u),t.DecreasePriority(h,u))}for(const a of n.outEdges()){const h=a.target,u=o+this.length(a);e.get(h)>u&&(e.set(h,u),t.DecreasePriority(h,u))}}this.result=new Array(this.graph.shallowNodeCount);let i=0;for(const s of this.graph.shallowNodes){const n=e.get(s);n!==void 0?this.result[i++]=n:this.result[i++]=Number.POSITIVE_INFINITY}}}class Sa extends zt{constructor(t,e){super(null),this.graph=t,this.length=e}get Result(){return this.result}set Result(t){this.result=t}run(){this.result=new Array(this.graph.shallowNodeCount);let t=0;for(const e of this.graph.shallowNodes){const i=new Bl(this.graph,e,this.length);i.run(),this.Result[t++]=i.Result}}static Stress(t,e){let i=0;if(t.edgeCount===0)return i;const s=new Sa(t,e);s.run();const n=s.Result;let o=0;for(const h of t.shallowEdges)o+=e(h);o/=t.edgeCount;let a=0;for(const h of t.shallowNodes){let u=0;for(const c of t.shallowNodes){if(a!==u){const m=h.center.sub(c.center).length,S=o*n[a][u],A=S-m;i+=A*A/(S*S)}u++}a++}return i}}class Su extends zt{constructor(t,e,i){super(null),this.graph=t,this.pivotArray=e,this.length=i}get Result(){return this.result}run(){this.result=new Array(this.pivotArray.length);const t=Array.from(this.graph.shallowNodes),e=new Array(this.graph.shallowNodeCount).fill(Number.POSITIVE_INFINITY);let i=t[0];this.pivotArray[0]=0;for(let s=0;;s++){const n=new Bl(this.graph,i,this.length);if(n.run(),this.Result[s]=n.Result,s+1<this.pivotArray.length){let o=0;for(let a=0;a<this.Result[s].length;a++)e[a]=Math.min(e[a],this.Result[s][a]),e[a]>e[o]&&(o=a);i=t[o],this.pivotArray[s+1]=o}else break}}}class yu{static Rotate(t,e,i){const s=Math.sin(i*(Math.PI/180)),n=Math.cos(i*(Math.PI/180));for(let o=0;o<t.length;o++){const a=n*t[o]+s*e[o];e[o]=n*e[o]-s*t[o],t[o]=a}}}class Qt{static DoubleCenter(t){const e=new Array(t.length).fill(0),i=new Array(t[0].length).fill(0);let s=0;for(let n=0;n<t.length;n++)for(let o=0;o<t[0].length;o++)e[n]+=t[n][o],i[o]+=t[n][o],s+=t[n][o];for(let n=0;n<t.length;n++)e[n]/=t.length;for(let n=0;n<t[0].length;n++)i[n]/=t[0].length;s/=t.length,s/=t[0].length;for(let n=0;n<t.length;n++)for(let o=0;o<t[0].length;o++)t[n][o]-=e[n]+i[o]-s}static SquareEntries(t){for(let e=0;e<t.length;e++)for(let i=0;i<t[0].length;i++)t[e][i]=Math.pow(t[e][i],2)}static Multiply(t,e){for(let i=0;i<t.length;i++)for(let s=0;s<t[0].length;s++)t[i][s]*=e}static MultiplyX(t,e){if(t[0].length!==e.length)return null;const i=new Array(e.length).fill(0);for(let s=0;s<t.length;s++)for(let n=0;n<t[0].length;n++)i[s]+=t[s][n]*e[n];return i}static Norm(t){let e=0;for(let i=0;i<t.length;i++)e+=Math.pow(t[i],2);return Math.sqrt(e)}static Normalize(t){const e=Qt.Norm(t);if(e<=0)return 0;for(let i=0;i<t.length;i++)t[i]/=e;return e}static RandomUnitLengthVector(t){const e=new Array(t);for(let i=0;i<t;i++)e[i]=ls();return Qt.Normalize(e),e}static SpectralDecomposition(t,e){Qt.SpectralDecompositionIE(t,e,30,1e-6)}static SpectralDecompositionIE(t,e,i,s){const n=t[0].length;e.u1=Qt.RandomUnitLengthVector(n),e.lambda1=0,e.u2=Qt.RandomUnitLengthVector(n),e.lambda2=0;let o=0;const a=1-s;for(let h=0;h<i&&o<a;h++){const u=Qt.MultiplyX(t,e.u1),c=Qt.MultiplyX(t,e.u2);e.lambda1=Qt.Normalize(u),e.lambda2=Qt.Normalize(c),Qt.MakeOrthogonal(c,u),Qt.Normalize(c),o=Math.min(Qt.DotProduct(e.u1,u),Qt.DotProduct(e.u2,c)),e.u1=u,e.u2=c}}static DotProduct(t,e){if(t.length!==e.length)return 0;let i=0;for(let s=0;s<t.length;s++)i+=t[s]*e[s];return i}static MakeOrthogonal(t,e){if(t.length!==e.length)return;const i=Qt.DotProduct(t,e)/Qt.DotProduct(e,e);for(let s=0;s<t.length;s++)t[s]-=i*e[s]}static ClassicalScaling(t,e){const i=new Array(t.length);for(let s=0;s<t.length;s++)i[s]=t[s].slice();Qt.SquareEntries(i),Qt.DoubleCenter(i),Qt.Multiply(i,-.5),Qt.SpectralDecomposition(i,e),e.lambda1=Math.sqrt(Math.abs(e.lambda1)),e.lambda2=Math.sqrt(Math.abs(e.lambda2));for(let s=0;s<e.u1.length;s++)e.u1[s]*=e.lambda1,e.u2[s]*=e.lambda2}static DistanceScalingSubset(t,e,i,s,n){const o=e.length,a=t.length,h=new Array(a);for(let c=0;c<a;c++)for(let m=0;m<o;m++)t[c][m]===0&&(h[c]=m);const u=new Array(a).fill(0);for(let c=0;c<a;c++)for(let m=0;m<o;m++)h[c]!==m&&(u[c]+=s[c][m]);for(let c=0;c<n;c++)for(let m=0;m<a;m++){let S=0,A=0;for(let I=0;I<o;I++)if(m!==I){let B=Math.sqrt(Math.pow(e[h[m]]-e[I],2)+Math.pow(i[h[m]]-i[I],2));B>0&&(B=1/B),S+=s[m][I]*(e[I]+t[m][I]*(e[h[m]]-e[I])*B),A+=s[m][I]*(i[I]+t[m][I]*(i[h[m]]-i[I])*B)}e[h[m]]=S/u[m],i[h[m]]=A/u[m]}}static DistanceScaling(t,e,i,s,n){const o=e.length,a=new Array(o).fill(0);for(let h=0;h<o;h++)for(let u=0;u<o;u++)h!==u&&(a[h]+=s[h][u]);for(let h=0;h<n;h++)for(let u=0;u<o;u++){let c=0,m=0;for(let S=0;S<o;S++)if(u!==S){let A=Math.sqrt(Math.pow(e[u]-e[S],2)+Math.pow(i[u]-i[S],2));A>0&&(A=1/A),c+=s[u][S]*(e[S]+t[u][S]*(e[u]-e[S])*A),m+=s[u][S]*(i[S]+t[u][S]*(i[u]-i[S])*A)}e[u]=c/a[u],i[u]=m/a[u]}}static ExponentialWeightMatrix(t,e){const i=new Array(t.length);for(let s=0;s<t.length;s++){i[s]=new Array(t[s].length).fill(0);for(let n=0;n<t[s].length;n++)t[s][n]>0&&(i[s][n]=Math.pow(t[s][n],e))}return i}static EuclideanDistanceMatrix(t,e){const i=new Array(t.length);for(let s=0;s<t.length;s++){i[s]=new Array(t.length);for(let n=0;n<t.length;n++)i[s][n]=Math.sqrt(Math.pow(t[s]-t[n],2)+Math.pow(e[s]-e[n],2))}return i}static LandmarkClassicalScaling(t,e,i){const s=new Array(t.length);for(let a=0;a<t.length;a++){s[a]=new Array(t.length);for(let h=0;h<t.length;h++)s[a][h]=t[a][i[h]]}Qt.SquareEntries(s);const n=new Array(t.length).fill(0);for(let a=0;a<t.length;a++){for(let h=0;h<t.length;h++)n[a]+=s[a][h];n[a]/=t.length}Qt.DoubleCenter(s),Qt.Multiply(s,-.5);const o={u1:new Array,u2:new Array,lambda1:0,lambda2:0};Qt.SpectralDecomposition(s,o),o.lambda1=Math.sqrt(Math.abs(o.lambda1)),o.lambda2=Math.sqrt(Math.abs(o.lambda2)),e.x=new Array(t[0].length).fill(0),e.y=new Array(t[0].length).fill(0);for(let a=0;a<e.x.length;a++)for(let h=0;h<s.length;h++){const u=(Math.pow(t[h][a],2)-n[h])/2;e.x[a]-=o.u1[h]*u,e.y[a]-=o.u2[h]*u}}}class Cu{constructor(t,e){this.constrained=!1,this.Capacity=1e6,ue.AbovePP(t.point,e.point)===1?(this.upperSite=t,this.lowerSite=e):(this.lowerSite=t,this.upperSite=e),this.upperSite.AddEdgeToSite(this)}get CcwTriangle(){return this.ccwTriangle}set CcwTriangle(t){this.ccwTriangle=t}get CwTriangle(){return this.cwTriangle}set CwTriangle(t){this.cwTriangle=t}GetOtherTriangle_c(t){return this.cwTriangle.Contains(t)?this.ccwTriangle:this.cwTriangle}IsAdjacent(t){return t===this.upperSite||t===this.lowerSite}GetOtherTriangle_T(t){return this.ccwTriangle===t?this.cwTriangle:this.ccwTriangle}toString(){return Se.Qf.Format("({0},{1})",this.upperSite,this.lowerSite)}OtherSite(t){return this.upperSite===t?this.lowerSite:this.upperSite}}class Wr{constructor(t){this.Owner=null,this.InEdges=new Array,this.point=t}cleanRemovedEdges(){for(const t of this.Edges)t.CcwTriangle===null&&t.CwTriangle===null&&this.Edges.splice(this.Edges.indexOf(t),1)}static mkSO(t,e){const i=new Wr(t);return i.Owner=e,i}AddEdgeToSite(t){this.Edges==null&&(this.Edges=new Array),this.Edges.push(t)}EdgeBetweenUpperSiteAndLowerSite(t){if(this.Edges!=null){for(const e of this.Edges)if(e.lowerSite===t)return e}return null}AddInEdge(t){this.InEdges.push(t)}*Triangles(){let t;if(this.Edges!=null&&this.Edges.length>0)t=this.Edges[0];else if(this.InEdges!=null&&this.InEdges.length>0)t=this.InEdges[0];else return;let e=t;do{const i=e.upperSite===this?e.CcwTriangle:e.CwTriangle;if(i==null){e=null;break}yield i,e=i.Edges.getItem(i.Edges.index(e)+2)}while(e!==t);if(e!==t){e=t;do{const i=e.upperSite===this?e.CwTriangle:e.CcwTriangle;if(i==null)break;yield i,e=i.Edges.getItem(i.Edges.index(e)+1)}while(!0)}}toString(){return this.point.toString()}}class ir{constructor(t,e){this.RightSite=e.upperSite===t?e.lowerSite:e.upperSite,this.LeftSite=t,this.Edge=e}get x(){return this.LeftSite.point.x}toString(){return"("+this.LeftSite.toString()+", "+this.Edge.toString()+","+this.RightSite.toString()+")"}}class ya{has(t){return t===this.item0||t===this.item1||t===this.item2}index(t){return t===this.item0?0:t===this.item1?1:t===this.item2?2:-1}getItem(t){switch(t){case 0:case 3:case-3:return this.item0;case 1:case 4:case-2:return this.item1;case 2:case 5:case-1:return this.item2;default:throw new Error}}setItem(t,e){switch(t){case 0:case 3:case-3:this.item0=e;break;case 1:case 4:case-2:this.item1=e;break;case 2:case 5:case-1:this.item2=e;break;default:throw new Error}}[Symbol.iterator](){return this.GetEnumerator()}*GetEnumerator(){yield this.item0,yield this.item1,yield this.item2}}function jd(l,t,e){const i=new ya;return i.item0=l,i.item1=t,i.item2=e,i}class Ze{constructor(){this.Edges=new ya,this.Sites=new ya}containsPoint(t){return Ze.PointLocationForTriangle(t,this)!==ft.Outside}static PointLocationForTriangle(t,e){let i=!1;for(let s=0;s<3;s++){const n=d.signedDoubledTriangleArea(t,e.Sites.getItem(s).point,e.Sites.getItem(s+1).point);if(n<-C.distanceEpsilon)return ft.Outside;n<C.distanceEpsilon&&(i=!0)}return i?ft.Boundary:ft.Inside}intersectsLine(t,e,i){if(Ze.PointLocationForTriangle(t,this)!=ft.Outside||Ze.PointLocationForTriangle(e,this)!=ft.Outside)return!0;for(const s of this.Edges)if(this.abIntersectsTrianglSide(t,e,s))return!0;return!1}abIntersectsTrianglSide(t,e,i){return On(t,e,i.lowerSite.point,i.upperSite.point)}static mkSSSD(t,e,i,s){const n=d.getTriangleOrientation(t.point,e.point,i.point),o=new Ze;switch(n){case k.Counterclockwise:o.FillCcwTriangle(t,e,i,s);break;case k.Clockwise:o.FillCcwTriangle(t,i,e,s);break;default:throw new Error}return o}static mkSED(t,e,i){const s=new Ze;switch(d.getTriangleOrientation(e.upperSite.point,e.lowerSite.point,t.point)){case k.Counterclockwise:e.CcwTriangle=s,s.Sites.setItem(0,e.upperSite),s.Sites.setItem(1,e.lowerSite);break;case k.Clockwise:e.CwTriangle=s,s.Sites.setItem(0,e.lowerSite),s.Sites.setItem(1,e.upperSite);break;default:throw new Error}return s.Edges.setItem(0,e),s.Sites.setItem(2,t),s.CreateEdge(1,i),s.CreateEdge(2,i),s}static mkSSSEE(t,e,i,s,n,o){const a=Ze.mkSSSD(t,e,i,o);return a.Edges.setItem(0,s),a.Edges.setItem(1,n),a.BindEdgeToTriangle(t,s),a.BindEdgeToTriangle(e,n),a.CreateEdge(2,o),a}BindEdgeToTriangle(t,e){t===e.upperSite?e.CcwTriangle=this:e.CwTriangle=this}FillCcwTriangle(t,e,i,s){this.Sites.setItem(0,t),this.Sites.setItem(1,e),this.Sites.setItem(2,i);for(let n=0;n<3;n++)this.CreateEdge(n,s)}CreateEdge(t,e){const i=this.Sites.getItem(t),s=this.Sites.getItem(t+1),n=e(i,s);this.Edges.setItem(t,n),this.BindEdgeToTriangle(i,n)}Contains(t){return this.Sites.has(t)}OppositeEdge(t){const e=this.Sites.index(t);return this.Edges.getItem(e+1)}OppositeSite(t){const e=this.Edges.index(t);return this.Sites.getItem(e+2)}BoundingBox(){const t=Z.mkPP(this.Sites.getItem(0).point,this.Sites.getItem(1).point);return t.add(this.Sites.getItem(2).point),t}static mkSSSEED(t,e,i,s,n,o){const a=new Ze;return a.Sites.setItem(0,t),a.Sites.setItem(1,e),a.Sites.setItem(2,i),a.Edges.setItem(0,s),a.Edges.setItem(1,n),a.BindEdgeToTriangle(t,s),a.BindEdgeToTriangle(e,n),a.CreateEdge(2,o),a}toString(){return this.Sites.getItem(0).toString()+","+this.Sites.getItem(1).toString()+","+this.Sites.getItem(2).toString()}}class Fl{constructor(t){this.Edge=t}}class Le extends zt{constructor(t,e,i,s){if(super(null),this.front=new Qe((o,a)=>o.x-a.x),this.triangles=new Set,this.listOfSites=t,this.listOfSites.length===0)return;this.p_1=e,this.p_2=i,this.createEdgeDelegate=s;const n=Ze.mkSSSD(e,i,this.listOfSites[0],s);this.triangles.add(n),this.front.insert(new ir(e,n.Edges.getItem(2))),this.front.insert(new ir(this.listOfSites[0],n.Edges.getItem(1)))}run(){if(this.listOfSites.length!==0){for(let t=1;t<this.listOfSites.length;t++)this.ProcessSite(this.listOfSites[t]);this.FinalizeTriangulation()}}FinalizeTriangulation(){this.RemoveP1AndP2Triangles(),this.triangles.size>0&&this.MakePerimeterConvex()}MakePerimeterConvex(){let t=this.CreateDoubleLinkedListOfPerimeter();do{const e=this.FindConcaveEdge(t);if(e==null)return;t=this.ShortcutTwoListElements(e)}while(!0)}FindConcaveEdge(t){let e=t,i;do{if(i=e.Next,d.getTriangleOrientation(e.Start.point,e.End.point,i.End.point)===k.Counterclockwise)return e;e=i}while(i!==t);return null}static FindPivot(t){let e=t,i=t;do i=i.Next,(i.Start.point.x<e.Start.point.x||i.Start.point.x===e.Start.point.x&&i.Start.point.y<e.Start.point.y)&&(e=i);while(i!==t);return e}FindFirsePerimeterEdge(){for(const t of this.triangles)for(const e of t.Edges)if(e.GetOtherTriangle_T(t)==null)return e;return null}CreateDoubleLinkedListOfPerimeter(){const t=this.FindFirsePerimeterEdge();let e=t,i=null,s,n=null;const o=new Array;do s=Le.CreatePerimeterElementFromEdge(e),o.push(D.mkPP(s.Start.point,s.End.point)),e=Le.FindNextEdgeOnPerimeter(e),n!=null?(s.Prev=n,n.Next=s):i=s,n=s;while(e!==t);return i.Prev=s,s.Next=i,i}static FindNextEdgeOnPerimeter(t){var e;let i=(e=t.CwTriangle)!==null&&e!==void 0?e:t.CcwTriangle;for(t=i.Edges.getItem(i.Edges.index(t)+2);t.CwTriangle!=null&&t.CcwTriangle!=null;)i=t.GetOtherTriangle_T(i),t=i.Edges.getItem(i.Edges.index(t)+2);return t}static CreatePerimeterElementFromEdge(t){const e=new Fl(t);return t.CwTriangle!=null?(e.Start=t.upperSite,e.End=t.lowerSite):(e.End=t.upperSite,e.Start=t.lowerSite),e}RemoveP1AndP2Triangles(){const t=new Set;for(const e of this.triangles)(e.Sites.has(this.p_1)||e.Sites.has(this.p_2))&&t.add(e);for(const e of t)Le.RemoveTriangleWithEdges(this.triangles,e)}static RemoveTriangleWithEdges(t,e){t.delete(e);for(const i of e.Edges)i.CwTriangle===e?i.CwTriangle=null:i.CcwTriangle=null,i.CwTriangle==null&&i.CcwTriangle==null&&Ca(i.upperSite.Edges,i)}static RemoveTriangleButLeaveEdges(t,e){t.delete(e);for(const i of e.Edges)i.CwTriangle===e?i.CwTriangle=null:i.CcwTriangle=null}ProcessSite(t){this.PointEvent(t);for(let e=0;e<t.Edges.length;e++){const i=t.Edges[e];i.constrained&&this.EdgeEvent(i)}}EdgeEvent(t){Le.EdgeIsProcessed(t)||(this.traversingEdge=t,this.runEdgeInserter())}static EdgeIsProcessed(t){return t.CwTriangle!=null||t.CcwTriangle!=null}ShowFrontWithSite(t,e=null){const i=new Array;if(t.Edges!=null)for(const s of t.Edges)i.push(It.mkDebugCurveTWCI(200,.8,s.constrained?"Pink":"Brown",D.mkPP(s.upperSite.point,s.lowerSite.point)));i.push(It.mkDebugCurveTWCI(200,1,"Brown",vt.mkFullEllipseNNP(.5,.5,t.point)));for(const s of this.triangles)for(let n=0;n<3;n++){const o=s.Edges.getItem(n);i.push(It.mkDebugCurveTWCI(o.constrained?155:100,o.constrained?.8:.4,o.constrained?"Pink":"Navy",D.mkPP(o.upperSite.point,o.lowerSite.point)))}if(e!=null)for(const s of e)i.push(It.mkDebugCurveTWCI(100,.5,"Red",s));for(const s of this.front)i.push(It.mkDebugCurveTWCI(100,5.5,"Green",D.mkPP(s.Edge.upperSite.point,s.Edge.lowerSite.point)))}Show(t){Le.ShowCdt(Array.from(this.triangles.values()),this.front,null,null,[],t)}static ShowCdt(t,e,i,s,n,o){let a=new Array;if(i!=null)for(const h of i)a.push(It.mkDebugCurveTWCI(200,.1,"Red",h));if(s!=null)for(const h of s)a.push(It.mkDebugCurveTWCI(200,.1,"Blue",h));if(e!=null)for(const h of e)a.push(It.mkDebugCurveTWCI(200,.1,"Green",D.mkPP(h.Edge.upperSite.point,h.Edge.lowerSite.point)));for(const h of t)for(let u=0;u<3;u++){const c=h.Edges.getItem(u);a.push(Le.GetDebugCurveOfCdtEdge(c))}a=a.concat(n)}static GetDebugCurveOfCdtEdge(t){return t.CcwTriangle==null||t.CwTriangle==null?It.mkDebugCurveTWCI(255,.5,t.constrained?"Brown":"Black",D.mkPP(t.upperSite.point,t.lowerSite.point)):It.mkDebugCurveTWCI(200,t.constrained?.8:.2,t.constrained?"Pink":"Navy",D.mkPP(t.upperSite.point,t.lowerSite.point))}PointEvent(t){const e=this.ProjectToFront(t),i={rightSite:null},s=e.item.x+C.distanceEpsilon<t.point.x?this.MiddleCase(t,e,i):this.LeftCase(t,e,i);let n=this.InsertSiteIntoFront(s,t,i.rightSite);this.TriangulateEmptySpaceToTheRight(n),n=Le.FindNodeInFrontBySite(this.front,s),this.TriangulateEmptySpaceToTheLeft(n)}LeftCase(t,e,i){const s=e.item;this.InsertAndLegalizeTriangle(t,s);const n=this.front.previous(e),o=n.item.LeftSite;i.rightSite=e.item.RightSite,this.InsertAndLegalizeTriangle(t,n.item),this.front.deleteNodeInternal(n);const a=this.front.remove(s);return o}MiddleCase(t,e,i){const s=e.item.LeftSite;return i.rightSite=e.item.RightSite,this.InsertAndLegalizeTriangle(t,e.item),this.front.deleteNodeInternal(e),s}TriangulateEmptySpaceToTheLeft(t){const e=t.item.RightSite;let i=this.front.previous(t);for(;i!=null;){const s=i.item,n=s.LeftSite,o=s.RightSite;if(o.point.sub(e.point).dot(n.point.sub(o.point))<0)t=this.ShortcutTwoFrontElements(i,t),i=this.front.previous(t);else{this.TryTriangulateBasinToTheLeft(t);break}}}ShortcutTwoListElements(t){var e;const i=t.Next;let s=Ze.mkSSSEE(t.Start,t.End,i.End,t.Edge,i.Edge,this.createEdgeDelegate);this.triangles.add(s);const n=s.Edges.getItem(2);this.LegalizeEdge(t.Start,s.OppositeEdge(t.Start)),s=(e=n.CcwTriangle)!==null&&e!==void 0?e:n.CwTriangle,this.LegalizeEdge(i.End,s.OppositeEdge(i.End));const o=new Fl(n);return o.Start=t.Start,o.End=i.End,t.Prev.Next=o,o.Prev=t.Prev,o.Next=i.Next,i.Next.Prev=o,o}ShortcutTwoFrontElements(t,e){var i;const s=t.item,n=e.item;let o=Ze.mkSSSEED(s.LeftSite,s.RightSite,n.RightSite,s.Edge,n.Edge,this.createEdgeDelegate);this.triangles.add(o),this.front.deleteNodeInternal(t),this.front.remove(n);const a=o.Edges.getItem(2);return this.LegalizeEdge(s.LeftSite,o.OppositeEdge(s.LeftSite)),o=(i=a.CcwTriangle)!==null&&i!==void 0?i:a.CwTriangle,this.LegalizeEdge(n.RightSite,o.OppositeEdge(n.RightSite)),this.front.insert(new ir(s.LeftSite,a))}TryTriangulateBasinToTheLeft(t){if(!Le.DropsSharpEnoughToTheLeft(t.item))return;const e=new Yt.B;for(e.push(t.item.LeftSite);;){const i=e.pop();t=Le.FindNodeInFrontBySite(this.front,i);const s=this.front.previous(t);if(s==null)return;if(d.getTriangleOrientation(s.item.LeftSite.point,t.item.LeftSite.point,t.item.RightSite.point)==k.Counterclockwise)e.push(s.item.LeftSite),this.ShortcutTwoFrontElements(s,t);else if(t.item.LeftSite.point.y>t.item.RightSite.point.y)e.push(s.item.LeftSite);else{if(s.item.LeftSite.point.y<=s.item.RightSite.point.y)return;e.push(s.item.LeftSite)}}}static DropsSharpEnoughToTheLeft(t){const e=t.Edge;if(t.RightSite!==e.upperSite)return!1;const i=e.lowerSite.point.sub(e.upperSite.point);return i.x>=.5*i.y}InsertSiteIntoFront(t,e,i){let s=null,n=null;for(const o of e.Edges)if(n==null&&o.lowerSite===t&&(n=o),s==null&&o.lowerSite===i&&(s=o),n!=null&&s!=null)break;return this.front.insert(new ir(t,n)),this.front.insert(new ir(e,s))}TriangulateEmptySpaceToTheRight(t){const i=t.item.LeftSite.point;let s=this.front.next(t);for(;s!=null;){const n=s.item,o=n.LeftSite,a=n.RightSite;if(o.point.sub(i).dot(a.point.sub(o.point))<0)t=this.ShortcutTwoFrontElements(t,s),s=this.front.next(t);else{this.TryTriangulateBasinToTheRight(t);break}}}TryTriangulateBasinToTheRight(t){if(!Le.DropsSharpEnoughToTheRight(t.item))return;const e=new Yt.B;for(e.push(t.item.LeftSite);;){const i=e.pop();t=Le.FindNodeInFrontBySite(this.front,i);const s=this.front.next(t);if(s==null)return;if(d.getTriangleOrientation(t.item.LeftSite.point,t.item.RightSite.point,s.item.RightSite.point)==k.Counterclockwise)this.ShortcutTwoFrontElements(t,s),e.push(i);else if(t.item.LeftSite.point.y>t.item.RightSite.point.y)e.push(t.item.RightSite);else{if(s.item.LeftSite.point.y>=s.item.RightSite.point.y)return;e.push(t.item.RightSite)}}}static DropsSharpEnoughToTheRight(t){const e=t.Edge;if(t.LeftSite!==e.upperSite)return!1;const i=e.lowerSite.point.sub(e.upperSite.point);return i.x<=-.5*i.y}static FindNodeInFrontBySite(t,e){return t.findLast(i=>i.LeftSite.point.x<=e.point.x)}InsertAndLegalizeTriangle(t,e){var i;if(d.getTriangleOrientation(t.point,e.LeftSite.point,e.RightSite.point)!==k.Collinear){const s=Ze.mkSED(t,e.Edge,this.createEdgeDelegate);this.triangles.add(s),this.LegalizeEdge(t,s.Edges.getItem(0))}else{const s=e.Edge;Ca(s.upperSite.Edges,s);let n=(i=s.CcwTriangle)!==null&&i!==void 0?i:s.CwTriangle;const o=n.OppositeSite(s);Le.RemoveTriangleButLeaveEdges(this.triangles,n),n=Ze.mkSSSD(e.LeftSite,o,t,this.createEdgeDelegate);const a=Ze.mkSSSD(e.RightSite,o,t,this.createEdgeDelegate);this.triangles.add(n),this.triangles.add(a),this.LegalizeEdge(t,n.OppositeEdge(t)),this.LegalizeEdge(t,a.OppositeEdge(t))}}LegalizeEdge(t,e){e.constrained||e.CcwTriangle==null||e.CwTriangle==null||(e.CcwTriangle.Contains(t)?this.LegalizeEdgeForOtherCwTriangle(t,e):this.LegalizeEdgeForOtherCcwTriangle(t,e))}LegalizeEdgeForOtherCwTriangle(t,e){const i=e.CwTriangle.Edges.index(e);if(Rl(t,e.upperSite,e.CwTriangle.Sites.getItem(i+2),e.lowerSite)){const s=Dl(t,e);this.LegalizeEdge(t,s.CwTriangle.OppositeEdge(t)),this.LegalizeEdge(t,s.CcwTriangle.OppositeEdge(t))}}LegalizeEdgeForOtherCcwTriangle(t,e){const i=e.CcwTriangle.Edges.index(e);if(Rl(t,e.lowerSite,e.CcwTriangle.Sites.getItem(i+2),e.upperSite)){const s=Dl(t,e);this.LegalizeEdge(t,s.CwTriangle.OppositeEdge(t)),this.LegalizeEdge(t,s.CcwTriangle.OppositeEdge(t))}}ProjectToFront(t){return this.front.findLast(e=>e.x<=t.point.x)}runEdgeInserter(){this.initEdgeInserter(),this.TraceEdgeThroughTriangles(),this.TriangulatePolygon0(this.rightPolygon,this.traversingEdge.upperSite,this.traversingEdge.lowerSite,!0),this.TriangulatePolygon0(this.leftPolygon,this.traversingEdge.upperSite,this.traversingEdge.lowerSite,!1),this.UpdateFront()}initEdgeInserter(){this.rightPolygon=new Array,this.leftPolygon=new Array,this.addedTriangles=new Array,this.piercedEdge=null,this.piercedTriangle=null,this.piercedToTheLeftFrontElemNode=null,this.piercedToTheRightFrontElemNode=null}UpdateFront(){const t=new Set;for(const e of this.addedTriangles)for(const i of e.Edges)if(i.CwTriangle==null||i.CcwTriangle==null){if(i.lowerSite==this.p_2&&i.upperSite==this.p_1)continue;t.add(i)}for(const e of t)this.AddEdgeToFront(e)}AddEdgeToFront(t){const e=t.upperSite.point.x<t.lowerSite.point.x?t.upperSite:t.lowerSite;this.front.insert(new ir(e,t))}TriangulatePolygon0(t,e,i,s){t.length>0&&this.TriangulatePolygon1(0,t.length-1,t,e,i,s)}TriangulatePolygon1(t,e,i,s,n,o){let a=i[t],h=t;for(let m=t+1;m<=e;m++){const S=i[m];c(S)&&(h=m,a=S)}const u=Ze.mkSSSD(s,n,a,this.createEdgeDelegate);this.triangles.add(u),this.addedTriangles.push(u),t<h&&this.TriangulatePolygon1(t,h-1,i,s,a,o),h<e&&this.TriangulatePolygon1(h+1,e,i,a,n,o);function c(m){return o?Ea(m,s,a,n):Ea(m,s,n,a)}}TraceEdgeThroughTriangles(){this.initEdgeTracer(),this.Traverse()}Traverse(){for(;!this.BIsReached();)this.piercedToTheLeftFrontElemNode!=null?this.ProcessLeftFrontPiercedElement():this.piercedToTheRightFrontElemNode!=null?this.ProcessRightFrontPiercedElement():this.ProcessPiercedEdge();this.piercedTriangle!=null&&this.removePiercedTriangle(this.piercedTriangle),this.FindMoreRemovedFromFrontElements();for(const t of this.elementsToBeRemovedFromFront)this.front.remove(t)}ProcessLeftFrontPiercedElement(){let t=this.piercedToTheLeftFrontElemNode;do this.elementsToBeRemovedFromFront.push(t.item),this.AddSiteToLeftPolygon(t.item.LeftSite),t=this.front.previous(t);while(d.pointToTheLeftOfLine(t.item.LeftSite.point,this.a.point,this.b.point));if(this.elementsToBeRemovedFromFront.push(t.item),this.AddSiteToRightPolygon(t.item.LeftSite),t.item.LeftSite===this.b){this.piercedToTheLeftFrontElemNode=t;return}this.FindPiercedTriangle(t),this.piercedToTheLeftFrontElemNode=null}FindPiercedTriangle(t){var e;const i=t.item.Edge,s=(e=i.CcwTriangle)!==null&&e!==void 0?e:i.CwTriangle,n=s.Edges.index(i);for(let o=1;o<=2;o++){const a=s.Edges.getItem(o+n),h=x.sign(d.signedDoubledTriangleArea(a.lowerSite.point,this.a.point,this.b.point));if(x.sign(d.signedDoubledTriangleArea(a.upperSite.point,this.a.point,this.b.point))*h<=0){this.piercedTriangle=s,this.piercedEdge=a;break}}}FindMoreRemovedFromFrontElements(){for(const t of this.removedTriangles)for(const e of t.Edges)if(e.CcwTriangle==null&&e.CwTriangle==null){const i=e.upperSite.point.x<e.lowerSite.point.x?e.upperSite:e.lowerSite,s=Le.FindNodeInFrontBySite(this.front,i);s.item.Edge===e&&this.elementsToBeRemovedFromFront.push(s.item)}}ProcessPiercedEdge(){this.piercedEdge.CcwTriangle===this.piercedTriangle?(this.AddSiteToLeftPolygon(this.piercedEdge.lowerSite),this.AddSiteToRightPolygon(this.piercedEdge.upperSite)):(this.AddSiteToLeftPolygon(this.piercedEdge.upperSite),this.AddSiteToRightPolygon(this.piercedEdge.lowerSite)),this.removePiercedTriangle(this.piercedTriangle),this.PrepareNextStateAfterPiercedEdge()}PrepareNextStateAfterPiercedEdge(){var t,e;const i=(t=this.piercedEdge.CwTriangle)!==null&&t!==void 0?t:this.piercedEdge.CcwTriangle,s=i.Edges.index(this.piercedEdge);for(let n=1;n<=2;n++){const o=i.Edges.getItem(n+s),a=x.sign(d.signedDoubledTriangleArea(o.lowerSite.point,this.a.point,this.b.point));if(x.sign(d.signedDoubledTriangleArea(o.upperSite.point,this.a.point,this.b.point))*a<=0){if(o.CwTriangle!=null&&o.CcwTriangle!=null){this.piercedTriangle=i,this.piercedEdge=o;break}this.piercedTriangle=null,this.piercedEdge=null;const u=o.upperSite.point.x<o.lowerSite.point.x?o.upperSite:o.lowerSite,c=Le.FindNodeInFrontBySite(this.front,u);u.point.x<this.a.point.x?this.piercedToTheLeftFrontElemNode=c:this.piercedToTheRightFrontElemNode=c,this.removePiercedTriangle((e=o.CwTriangle)!==null&&e!==void 0?e:o.CcwTriangle);break}}}removePiercedTriangle(t){this.triangles.delete(t);for(const e of t.Edges)e.CwTriangle===t?e.CwTriangle=null:e.CcwTriangle=null,this.removedTriangles.push(t)}ProcessRightFrontPiercedElement(){let t=this.piercedToTheRightFrontElemNode;do this.elementsToBeRemovedFromFront.push(t.item),this.AddSiteToRightPolygon(t.item.RightSite),t=this.front.next(t);while(d.pointToTheRightOfLine(t.item.RightSite.point,this.a.point,this.b.point));if(this.elementsToBeRemovedFromFront.push(t.item),this.AddSiteToLeftPolygon(t.item.RightSite),t.item.RightSite===this.b){this.piercedToTheRightFrontElemNode=t;return}this.FindPiercedTriangle(t),this.piercedToTheRightFrontElemNode=null}AddSiteToLeftPolygon(t){this.AddSiteToPolygonWithCheck(t,this.leftPolygon)}AddSiteToPolygonWithCheck(t,e){t!==this.b&&(e.length===0||e[e.length-1]!==t)&&e.push(t)}AddSiteToRightPolygon(t){this.AddSiteToPolygonWithCheck(t,this.rightPolygon)}BIsReached(){var t;const e=(t=this.piercedToTheLeftFrontElemNode)!==null&&t!==void 0?t:this.piercedToTheRightFrontElemNode;return e!=null?e.item.Edge.IsAdjacent(this.b):this.piercedEdge.IsAdjacent(this.b)}initEdgeTracer(){this.elementsToBeRemovedFromFront=[],this.a=this.traversingEdge.upperSite,this.b=this.traversingEdge.lowerSite,this.removedTriangles=[];const t=Le.FindNodeInFrontBySite(this.front,this.a),e=this.front.previous(t);if(d.pointToTheLeftOfLine(this.b.point,e.item.LeftSite.point,e.item.RightSite.point))this.piercedToTheLeftFrontElemNode=e;else if(d.pointToTheRightOfLine(this.b.point,t.item.RightSite.point,t.item.LeftSite.point))this.piercedToTheRightFrontElemNode=t;else for(const i of this.a.Edges){const s=i.CcwTriangle;if(s==null||d.pointToTheLeftOfLine(this.b.point,i.lowerSite.point,i.upperSite.point))continue;const n=s.Edges.index(i),o=s.Sites.getItem(n+2);if(d.pointToTheLeftOfLineOrOnLine(this.b.point,o.point,i.upperSite.point)){this.piercedEdge=s.Edges.getItem(n+1),this.piercedTriangle=s;break}}}}function Ca(l,t){if(l.length===0)return;const e=l.findIndex(i=>t===i);e>=0&&(e!==l.length-1&&(l[e]=l[l.length-1]),l.pop())}function Rl(l,t,e,i){return Eu(l,t,e,i)&&Ea(l,t,e,i)}function Eu(l,t,e,i){return d.getTriangleOrientation(t.point,l.point,e.point)===k.Clockwise&&d.getTriangleOrientation(e.point,l.point,i.point)===k.Clockwise}function Ea(l,t,e,i){const s=t.point.x-l.point.x,n=t.point.y-l.point.y,o=e.point.x-l.point.x,a=e.point.y-l.point.y,h=i.point.x-l.point.x,u=i.point.y-l.point.y,c=s*s+n*n,m=o*o+a*a,S=h*h+u*u;return s*(a*S-u*m)-o*(n*S-u*c)+h*(n*m-a*c)>C.tolerance}function $d(l){if(Point.getTriangleOrientation(l.Sites.getItem(0).point,l.Sites.getItem(1).point,l.Sites.getItem(2).point)!=TriangleOrientation.Counterclockwise)return!1;for(let t=0;t<3;t++){const e=l.Edges.getItem(t),i=l.Sites.getItem(t),s=l.Sites.getItem(t+1);if(!e.IsAdjacent(i)||!e.IsAdjacent(s))return!1;if(e.upperSite===i){if(e.CcwTriangle!==l)return!1}else if(e.CwTriangle!==l)return!1}return!0}function Dl(l,t){let e,i;t.CcwTriangle.Contains(l)?(e=t.CcwTriangle,i=t.CwTriangle):(e=t.CwTriangle,i=t.CcwTriangle);const s=e.Edges.index(t),n=i.Edges.index(t),o=i.Sites.getItem(n+2),a=e.Edges.getItem(s+1),h=i.Edges.getItem(n+1),u=ue.GetOrCreateEdge(l,o);return e.Sites.setItem(s+1,o),e.Edges.setItem(s,h),e.Edges.setItem(s+1,u),i.Sites.setItem(n+1,l),i.Edges.setItem(n,a),i.Edges.setItem(n+1,u),h.lowerSite===o?h.CcwTriangle=e:h.CwTriangle=e,a.lowerSite===l?a.CcwTriangle=i:a.CwTriangle=i,u.upperSite===l?(u.CcwTriangle=i,u.CwTriangle=e):(u.CcwTriangle=e,u.CwTriangle=i),Ca(t.upperSite.Edges,t),u}class ue extends zt{constructor(t,e,i){super(null),this.isolatedSites=[],this.obstacles=[],this.PointsToSites=new si,this.simplifyObstacles=!0,this.rectangleNodeOnTriangles=null,this.isolatedSites=t,this.obstacles=e,this.isolatedSegments=i}static constructor_(t){const e=new ue(null,null,null);return e.isolatedSitesWithObject=t,e}FillAllInputSites(){if(this.isolatedSitesWithObject!=null)for(const t of this.isolatedSitesWithObject)this.AddSite(t[0],t[1]);if(this.isolatedSites!=null)for(const t of this.isolatedSites)this.AddSite(t,null);if(this.obstacles!=null)for(const t of this.obstacles)this.AddPolylineToAllInputSites(t);if(this.isolatedSegments!=null)for(const t of this.isolatedSegments)this.AddConstrainedEdge(t.A,t.B,null);this.AddP1AndP2(),this.allInputSites=Array.from(this.PointsToSites.values())}AddSite(t,e){let i;return(i=this.PointsToSites.get(t))?i.Owner=e:(i=Wr.mkSO(t,e),this.PointsToSites.set(t,i)),i}AddP1AndP2(){const t=Z.mkEmpty();for(const s of this.PointsToSites.keys())t.add(s);const e=10,i=10;this.P1=new Wr(t.leftBottom.add(new d(-e,-i))),this.P2=new Wr(t.rightBottom.add(new d(e,-i)))}AddPolylineToAllInputSites(t){if(this.simplifyObstacles)for(let e=t.startPoint;e!=null;){const i=e.point;if(e=e.next,!e)break;for(;e.next&&d.getTriangleOrientation(i,e.point,e.next.point)===k.Collinear;)e=e.next;this.AddConstrainedEdge(i,e.point,t)}else for(let e=t.startPoint;e.next!=null;e=e.next)this.AddConstrainedEdge(e.point,e.next.point,t);t.closed&&this.AddConstrainedEdge(t.endPoint.point,t.startPoint.point,t)}AddConstrainedEdge(t,e,i){const s=ue.AbovePP(t,e);let n,o;s>0?(n=this.AddSite(t,i),o=this.AddSite(e,i)):(n=this.AddSite(e,i),o=this.AddSite(t,i));const a=ue.CreateEdgeOnOrderedCouple(n,o);a.constrained=!0}static GetOrCreateEdge(t,e){if(ue.AboveCC(t,e)===1){const i=t.EdgeBetweenUpperSiteAndLowerSite(e);return i??ue.CreateEdgeOnOrderedCouple(t,e)}else{const i=e.EdgeBetweenUpperSiteAndLowerSite(t);return i??ue.CreateEdgeOnOrderedCouple(e,t)}}static CreateEdgeOnOrderedCouple(t,e){return new Cu(t,e)}GetTriangles(){return this.sweeper.triangles}run(){this.Initialization(),this.SweepAndFinalize()}SweepAndFinalize(){this.sweeper=new Le(this.allInputSites,this.P1,this.P2,ue.GetOrCreateEdge),this.sweeper.run(),this.cleanRemovedEdges()}cleanRemovedEdges(){for(const t of this.PointsToSites.values())t.cleanRemovedEdges()}Initialization(){this.FillAllInputSites(),this.allInputSites.sort(ue.OnComparison)}static OnComparison(t,e){return ue.AboveCC(t,e)}static AbovePP(t,e){let i=t.y-e.y;return i>0?1:i<0?-1:(i=t.x-e.x,i>0?-1:i<0?1:0)}static AboveCC(t,e){return ue.AbovePP(t.point,e.point)}RestoreEdgeCapacities(){for(const t of this.allInputSites)for(const e of t.Edges)e.constrained||(e.ResidualCapacity=e.Capacity)}SetInEdges(){for(const t of this.PointsToSites.values())for(const e of t.Edges)e.lowerSite.AddInEdge(e)}FindSite(t){return this.PointsToSites.get(t)}static PointIsInsideOfTriangle(t,e){for(let i=0;i<3;i++){const s=e.Sites.getItem(i).point,n=e.Sites.getItem(i+1).point;if(d.signedDoubledTriangleArea(t,s,n)<C.distanceEpsilon*-1)return!1}return!0}getRectangleNodeOnTriangles(){return this.rectangleNodeOnTriangles==null&&(this.rectangleNodeOnTriangles=re(Array.from(this.GetTriangles().values()).map(t=>pe(t,t.BoundingBox())))),this.rectangleNodeOnTriangles}}function Nl(l){const t=Array.from(l.GetAllLeaves()),e=l.irect,i=e.diagonal/4,s=e.clone();return s.pad(i),bu(t.concat([s.perimeter()]))}function bu(l){const t=new ue(null,l,null);return t.run(),t}class Hr{constructor(t,e){this.start=t,this.end=e}add(t){this.add_d(t)}add_rect(t){const e=t,i=this.clone();return i.add_d(e.start),i.add_d(e.end),i}clone(){return new Hr(this.start,this.end)}contains_point(t){return this.contains_d(t)}contains_rect(t){const e=t;return this.contains_d(e.start)&&this.contains_d(e.end)}intersection_rect(t){const e=t;return new Hr(Math.max(this.start,e.start),Math.min(this.end,e.end))}intersects_rect(t){const e=t;return this.intersects(e)}contains_point_radius(t,e){return this.contains_d(t-e)&&this.contains_d(t+e)}static mkInterval(t,e){const i=new Hr(t.start,t.end);return i.add_d(e.start),i.add_d(e.end),i}add_d(t){this.start>t&&(this.start=t),this.end<t&&(this.end=t)}get Start(){return this.start}set Start(t){this.start=t}get Length(){return this.end-this.start}contains_d(t){return this.start<=t&&t<=this.end}GetInRange(t){return t<this.start?this.start:t>this.end?this.end:t}intersects(t){return t.start>this.end+C.distanceEpsilon?!1:!(t.end<this.start-C.distanceEpsilon)}}class kl{constructor(t){this.heapSize=0,this._priors=new Array(t),this._heap=new Array(t+1),this._reverse_heap=new Array(t)}get Count(){return this.heapSize}SwapWithParent(t){const e=this._heap[t>>1];this.PutAtI(t>>1,this._heap[t]),this.PutAtI(t,e)}Enqueue(t,e){this.heapSize++;let i=this.heapSize;for(this._priors[t]=e,this.PutAtI(i,t);i>1&&this._priors[this._heap[i>>1]]>e;)this.SwapWithParent(i),i>>=1}PutAtI(t,e){this._heap[t]=e,this._reverse_heap[e]=t}Dequeue(){if(this.heapSize===0)throw new Error;const t=this._heap[1];if(this.heapSize>1){this.PutAtI(1,this._heap[this.heapSize]);let e=1;for(;;){let i=e;const s=e<<1;s<=this.heapSize&&this._priors[this._heap[s]]<this._priors[this._heap[e]]&&(i=s);const n=s+1;if(n<=this.heapSize&&this._priors[this._heap[n]]<this._priors[this._heap[i]]&&(i=n),i!==e)this.SwapWithParent(i);else break;e=i}}return this.heapSize--,t}IsEmpty(){return this.heapSize===0}DecreasePriority(t,e){this._priors[t]=e;let i=this._reverse_heap[t];for(;i>1&&this._priors[this._heap[i]]<this._priors[this._heap[i>>1]];){this.SwapWithParent(i);i>>=1}}}class Au{constructor(t,e,i,s){this._numberOfOverlaps=0,this._proximityEdges=t,this._nodeSizes=e,this._nodePositions=i,this._forLayers=s,this._q=new kl(e.length*2)}Run(){return this.InitQueue(),this.FindOverlaps(),this._numberOfOverlaps}FindOverlaps(){for(;this._q.Count>0;){let t=this._q.Dequeue();t<this._nodePositions.length?(this.FindOverlapsWithInterval(t),this.AddIntervalToTree(t)):(t-=this._nodePositions.length,this.RemoveIntervalFromTree(t))}}RemoveIntervalFromTree(t){this._intervalTree.Remove(this.GetInterval(t),t)}AddIntervalToTree(t){const e=this.GetInterval(t);this._intervalTree==null&&(this._intervalTree=tn([])),this._intervalTree.Add(e,t)}FindOverlapsWithInterval(t){if(this._intervalTree==null)return;const e=this.GetInterval(t);for(const i of this._intervalTree.GetAllIntersecting(e)){const s=Xi.GetIdealEdge(t,i,this._nodePositions[t],this._nodePositions[i],this._nodeSizes);if(s.overlapFactor<=1)return;this._proximityEdges.push(s),this._numberOfOverlaps++}}GetInterval(t){const e=this._nodeSizes[t].width/2,i=this._nodePositions[t].x;return new Hr(i-e,i+e)}InitQueue(){for(let t=0;t<this._nodeSizes.length;t++){const e=this._nodeSizes[t].height/2,i=this._nodePositions[t].y;this._q.Enqueue(t,i-e),this._q.Enqueue(this._nodeSizes.length+t,i+e)}}}class Gl{constructor(t,e,i){this.treeNodes=new Set,this.hedgehog=new Map,this.graph=t,this.weight=e,this.root=i,this.q=new kl(this.graph.nodeCount)}NodeIsInTree(t){return this.treeNodes.has(t)}GetTreeEdges(){const t=new Array;for(this.Init();t.length<this.graph.nodeCount-1&&this.q.Count>0;)this.AddEdgeToTree(t);return t}AddEdgeToTree(t){const e=this.q.Dequeue(),i=this.hedgehog.get(e);this.treeNodes.add(e),t.push(i),this.UpdateOutEdgesOfV(e),this.UpdateInEdgesOfV(e)}UpdateOutEdgesOfV(t){for(const e of this.graph.outEdges[t]){const i=e.target;if(this.NodeIsInTree(i))continue;const s=this.hedgehog.get(i);if(s){const n=this.weight(s),o=this.weight(e);o<n&&(this.q.DecreasePriority(i,o),this.hedgehog.set(i,e))}else this.q.Enqueue(i,this.weight(e)),this.hedgehog.set(i,e)}}UpdateInEdgesOfV(t){for(const e of this.graph.inEdges[t]){const i=e.source;if(this.NodeIsInTree(i))continue;const s=this.hedgehog.get(i);if(s){const n=this.weight(s),o=this.weight(e);o<n&&(this.q.DecreasePriority(i,o),this.hedgehog.set(i,e))}else this.q.Enqueue(i,this.weight(e)),this.hedgehog.set(i,e)}}Init(){this.treeNodes.add(this.root);for(const t of this.graph.outEdges[this.root]){const e=this.weight(t);this.q.Enqueue(t.target,e),this.hedgehog.set(t.target,t)}for(const t of this.graph.inEdges[this.root]){const e=this.weight(t);this.q.Enqueue(t.source,e),this.hedgehog.set(t.source,t)}}}class ba{static GetMst(t,e){if(t.length===0)return null;const i=t.map(a=>new Ot(a.source,a.target)),s=new Fs;for(let a=0;a<t.length;a++)s.setPair(i[a],t[a]);const n=ni(i,e);return new Gl(n,a=>s.get(a.source,a.target).weight,i[0].source).GetTreeEdges().map(a=>s.get(a.source,a.target))}static GetMstOnCdt(t,e){const i=Array.from(t.PointsToSites.values()),s=new Map;for(let h=0;h<i.length;h++)s.set(i[h],h);const n=ba.GetEdges(i,s),o=So(Array.from(n.keys()));return new Gl(o,h=>e(n.get(h.source,h.target)),0).GetTreeEdges().map(h=>n.get(h.source,h.target))}static GetEdges(t,e){const i=new Fs;for(let s=0;s<t.length;s++){const n=t[s],o=e.get(n);for(const a of n.Edges)i.set(o,e.get(a.lowerSite),a)}return i}}class Aa{constructor(){this.epsilon=.01,this.iterationsMax=1e3,this.stopOnMaxIterat=!1,this.nodeSeparation=4,this.randomizationSeed=1,this.randomizationShift=.1}get StopOnMaxIterat(){return this.stopOnMaxIterat}set StopOnMaxIterat(t){this.stopOnMaxIterat=t}get Epsilon(){return this.epsilon}set Epsilon(t){this.epsilon=t}get IterationsMax(){return this.iterationsMax}set IterationsMax(t){this.iterationsMax=t}get NodeSeparation(){return this.nodeSeparation}set NodeSeparation(t){this.nodeSeparation=t}get RandomizationSeed(){return this.randomizationSeed}set RandomizationSeed(t){this.randomizationSeed=t}get RandomizationShift(){return this.randomizationShift}set RandomizationShift(t){this.randomizationShift=t}Clone(){const t=new Aa;return t.Epsilon=this.Epsilon,t.IterationsMax=this.IterationsMax,t.StopOnMaxIterat=this.StopOnMaxIterat,t.NodeSeparation=this.NodeSeparation,t.RandomizationSeed=this.RandomizationSeed,t.RandomizationShift=this.randomizationShift,t}}class Xi{constructor(t,e){this._settings=t,this._nodes=e}static RemoveOverlaps(t,e){const i=new Aa;i.RandomizationShift=1,i.NodeSeparation=e,new Xi(i,t).RemoveOverlaps()}RemoveOverlaps(){if(this._nodes.length<3){this.RemoveOverlapsOnTinyGraph();return}const t={nodePositions:new Array,nodeSizes:new Array};for(wu(this._settings,this._nodes,t,this._settings.RandomizationShift),this.lastRunNumberIterations=0;this.OneIteration(t.nodePositions,t.nodeSizes,!1);)this.lastRunNumberIterations++;for(;this.OneIteration(t.nodePositions,t.nodeSizes,!0);)this.lastRunNumberIterations++;for(let e=0;e<this._nodes.length;e++)this._nodes[e].center=t.nodePositions[e]}RemoveOverlapsOnTinyGraph(){if(this._nodes.length!==1&&this._nodes.length===2){const t=this._nodes[0],e=this._nodes[1];d.closeDistEps(t.center,e.center)&&(e.center=e.center.add(new d(.001,0)));const i=this.GetIdealDistanceBetweenTwoNodes(t,e),s=d.middle(t.center,e.center);let n=t.center.sub(e.center);const o=n.length;n=n.mul(.5*(i/o)),t.center=s.add(n),e.center=s.sub(n)}}GetIdealDistanceBetweenTwoNodes(t,e){const i=t.center.sub(e.center),s=Math.abs(i.x),n=Math.abs(i.y),o=(t.width+e.width)/2+this._settings.NodeSeparation,a=(t.height+e.height)/2+this._settings.NodeSeparation;let h=Number.POSITIVE_INFINITY,u=Number.POSITIVE_INFINITY;return s>C.tolerance&&(h=o/s),n>C.tolerance&&(u=a/n),Math.min(h,u)*i.length}static AvgEdgeLength(t){let e=0,i=0;for(const s of t)for(const n of s.outEdges())i+=s.center.sub(n.target.center).length,e++;return e>0?i/e:1}OneIteration(t,e,i){const s=new Array;for(let c=0;c<t.length;c++)s.push([t[c],c]);const n=ue.constructor_(s);n.run();const o=new Map;for(let c=0;c<t.length;c++)o.set(n.PointsToSites.get(t[c]),c);let a=0;const h=new Array;for(const c of n.PointsToSites.values())for(const m of c.Edges){const S=m.upperSite.point,A=m.lowerSite.point,I=o.get(m.upperSite),B=o.get(m.lowerSite),q=Xi.GetIdealEdge(I,B,S,A,e);h.push(q),q.overlapFactor>1&&a++}if(a===0||i){const c=this.FindProximityEdgesWithSweepLine(h,e,t);if(a===0&&c===0||a===0&&!i)return!1}const u=ba.GetMst(h,t.length);return Xi.MoveNodePositions(u,t,u[0].source),!0}FindProximityEdgesWithSweepLine(t,e,i){return new Au(t,e,i,this._overlapForLayers).Run()}static GetIdealEdge(t,e,i,s,n){const o={overlapFactor:0},a=Xi.GetIdealEdgeLength(t,e,i,s,n,o),h=i.sub(s).length,u=Z.mkSizeCenter(n[t],i),c=Z.mkSizeCenter(n[e],s),m=o.overlapFactor>1?h-a:Xi.GetDistanceRects(u,c);return{source:Math.min(t,e),target:Math.max(t,e),overlapFactor:o.overlapFactor,idealDistance:a,weight:m}}static GetIdealEdgeLength(t,e,i,s,n,o){const a=i.sub(s),h=a.length,u=Math.abs(a.x),c=Math.abs(a.y),m=(n[t].width+n[e].width)/2,S=(n[t].height+n[e].height)/2;if(u>=m||c>=S)return o.overlapFactor=1,a.length;let A;const I=1e-10;if(u>I)c>I?A=Math.min(m/u,S/c):A=m/u;else if(c>I)A=S/c;else return o.overlapFactor=2,Math.sqrt(m*m+S*S)/4;return A=Math.max(A,1.001),o.overlapFactor=A,A*h}static GetDistanceRects(t,e){if(t.intersects(e))return 0;let i=0,s=0;return(t.right<e.left||e.right<t.left)&&(s=t.left-e.right),t.top<e.bottom?i=e.bottom-t.top:e.top<t.bottom&&(i=t.bottom-e.top),Math.sqrt(s*s+i*i)}static MoveNodePositions(t,e,i){const s=e.map(o=>o.clone()),n=new Set;n.add(i);for(let o=0;o<t.length;o++){const a=t[o];n.has(a.source)?Xi.MoveNode(a.source,a.target,s,e,n,a.idealDistance):Xi.MoveNode(a.target,a.source,s,e,n,a.idealDistance)}}static MoveNode(t,e,i,s,n,o){let a=i[e].sub(i[t]);a=a.mul(o/a.length+.01),s[e]=s[t].add(a),n.add(e)}GetLastRunIterations(){return this.lastRunNumberIterations}}function wu(l,t,e,i){e.nodePositions=t.map(s=>s.center),i&&vu(e.nodePositions,new an(0,0),i),e.nodeSizes=t.map(s=>{const n=s.boundingBox.size;return n.width+=l.NodeSeparation,n.height+=l.NodeSeparation,n})}function vu(l,t,e){const i=new ie;for(let s=0;s<l.length;s++){let n=l[s];if(e||i.has(n))do{const o=n.x+(2*t.random()-1)*e,a=n.y+(2*t.random()-1)*e;n=new d(o,a)}while(i.has(n));l[s]=n,i.add(n)}}class zr extends zt{constructor(t,e,i,s){super(i),this.settings=t,this.graph=e,this.length=s}run(){this.LayoutConnectedGraphWithMds(),this.graph.pumpTheBoxToTheGraphWithMargins()}static ScaleToAverageEdgeLength(t,e,i,s){const n=new Map;let o=0;for(const u of t.shallowNodes)n.set(u,o),o++;let a=0,h=0;for(const u of t.shallowEdges){const c=n.get(u.source),m=n.get(u.target);h+=Math.sqrt(Math.pow(e[c]-e[m],2)+Math.pow(i[c]-i[m],2)),a+=s(u)}if(a>0&&(h/=a),h>0)for(let u=0;u<e.length;u++)e[u]/=h,i[u]/=h}static LayoutGraphWithMds(t,e,i,s){if(i.x=new Array(t.shallowNodeCount),i.y=new Array(t.shallowNodeCount),i.x.length===0)return;if(i.x.length===1){i.x[0]=i.y[0]=0;return}const n=Math.min(e.PivotNumber,t.shallowNodeCount),o=e.GetNumberOfIterationsWithMajorization(t.shallowNodeCount),a=e.Exponent,h=new Array(n),u=new Su(t,h,s);u.run();const c=u.Result;if(Qt.LandmarkClassicalScaling(c,i,h),zr.ScaleToAverageEdgeLength(t,i.x,i.y,s),o>0){const m=new Sa(t,s);m.run();const S=m.Result,A=Qt.ExponentialWeightMatrix(S,a);Qt.DistanceScalingSubset(S,i.x,i.y,A,o)}}LayoutConnectedGraphWithMds(){const t={x:[],y:[]};zr.LayoutGraphWithMds(this.graph,this.settings,t,this.length),this.settings.RotationAngle!==0&&yu.Rotate(t.x,t.y,this.settings.RotationAngle);let e=0;for(const i of this.graph.shallowNodes)i.boundingBox&&(i.center=new d(t.x[e]*this.settings.ScaleX,t.y[e]*this.settings.ScaleY)),e++;this.settings.removeOverlaps&&Xi.RemoveOverlaps(Array.from(this.graph.shallowNodes),this.settings.NodeSeparation),this.graph.pumpTheBoxToTheGraphWithMargins()}ScaleNodes(t,e){for(const i of t)i.center=i.center.mul(e)}static PackGraphs(t,e){if(t.length===0)return Z.mkEmpty();if(t.length===1)return t[0].boundingBox;const i=t.map(o=>o.boundingBox),s=new Array;for(const o of t)s.push({g:o,lb:o.boundingBox.leftBottom.clone()});const n=new ro(i,e.PackingAspectRatio);n.run();for(const{g:o,lb:a}of s){const h=o.boundingBox.leftBottom.sub(a);o.translate(h)}return new Z({left:0,bottom:0,right:n.PackedWidth,top:n.PackedHeight})}}class qr{constructor(){this.commonSettings=new tr,this.pivotNumber=50,this.iterationsWithMajorization=30,this.scaleX=100,this.scaleY=100,this.exponent=-2,this.rotationAngle=0,this._removeOverlaps=!0,this._callIterationsWithMajorizationThreshold=2e3,this.adjustScale=!1}static fromJSON(t){const e=new qr;return t.pivotNumber&&(e.pivotNumber=t.pivotNumber),t.iterationsWithMajorization&&(e.iterationsWithMajorization=t.iterationsWithMajorization),t.scaleX&&(e.scaleX=t.scaleX),t.scaleY&&(e.scaleY=t.scaleY),t.exponent&&(e.exponent=t.exponent),t.rotationAngle&&(e.rotationAngle=t.rotationAngle),t.removeOverlaps!=null&&(e._removeOverlaps=t.removeOverlaps),t._callIterationsWithMajorizationThreshold&&(e._callIterationsWithMajorizationThreshold=t._callIterationsWithMajorizationThreshold),e}toJSON(){const t={};return this.pivotNumber!=50&&(t.pivotNumber=this.pivotNumber),this.iterationsWithMajorization!=30&&(t.iterationsWithMajorization=this.iterationsWithMajorization),this.scaleX!=200&&(t.scaleX=this.scaleX),this.scaleY!=200&&(t.scaleY=this.scaleY),this.exponent!=-2&&(t.exponent=this.exponent),this.rotationAngle!=0&&(t.rotationAngle=this.rotationAngle),this._removeOverlaps||(t.removeOverlaps=this._removeOverlaps),this._callIterationsWithMajorizationThreshold!=3e3&&(t._callIterationsWithMajorizationThreshold=this._callIterationsWithMajorizationThreshold),t}get NodeSeparation(){return this.commonSettings.NodeSeparation}set NodeSeparation(t){this.commonSettings.NodeSeparation=t}get edgeRoutingSettings(){return this.commonSettings.edgeRoutingSettings}set edgeRoutingSettings(t){this.commonSettings.edgeRoutingSettings=t}get removeOverlaps(){return this._removeOverlaps}set removeOverlaps(t){this._removeOverlaps=t}get PivotNumber(){return this.pivotNumber}set PivotNumber(t){this.pivotNumber=t}get IterationsWithMajorization(){return this.iterationsWithMajorization}set IterationsWithMajorization(t){this.iterationsWithMajorization=t}get ScaleX(){return this.scaleX}set ScaleX(t){this.scaleX=t}get ScaleY(){return this.scaleY}set ScaleY(t){this.scaleY=t}get Exponent(){return this.exponent}set Exponent(t){this.exponent=t}get RotationAngle(){return this.rotationAngle}set RotationAngle(t){this.rotationAngle=t%360}get AdjustScale(){return this.adjustScale}set AdjustScale(t){this.adjustScale=t}GetNumberOfIterationsWithMajorization(t){return t>this.CallIterationsWithMajorizationThreshold?0:this.IterationsWithMajorization}get CallIterationsWithMajorizationThreshold(){return this._callIterationsWithMajorizationThreshold}set CallIterationsWithMajorizationThreshold(t){this._callIterationsWithMajorizationThreshold=t}}function Xd(l,t=null){const e=l.layoutSettings instanceof MdsLayoutSettings?l.layoutSettings:new MdsLayoutSettings;enforceLayoutSettings(l,e),layoutGeomGraphDetailed(l,t,Iu,routeEdges,optimalPackingRunner)}class wa extends zt{constructor(t,e,i,s){super(e),this.graph=t,this.length=i,this.settings=s,this.settings.ScaleX=this.settings.ScaleY=200}get scaleX(){return this.settings.ScaleX}set scaleX(t){this.settings.ScaleX=t}get scaleY(){return this.settings.ScaleY}set scaleY(t){this.settings.ScaleY=t}run(){new zr(this.settings,this.graph,this.cancelToken,this.length).run()}}function Iu(l,t){new wa(l,t,()=>1,l.layoutSettings).run()}function Ml(l,t,e){if(t)for(const i of t){if(e&&e.canceled)return;mi.RouteEdge(i,l.padding)}else for(const i of l.nodesBreadthFirst){if(e&&e.canceled)return;for(const s of i.outEdges())s.curve==null&&mi.RouteEdge(s,l.padding);for(const s of i.selfEdges())s.curve==null&&mi.RouteEdge(s,l.padding)}}class mi extends zt{constructor(t,e){super(null),this.edges=t,this.padding=e}run(){Zt.CreatePortsIfNeeded(this.edges);for(const t of this.edges)mi.RouteEdge(t,this.padding)}static RouteEdge(t,e){const i=t;i.sourcePort==null&&(i.sourcePort=Xe.mk(()=>t.source.boundaryCurve,()=>t.source.center)),i.targetPort==null&&(i.targetPort=Xe.mk(()=>t.target.boundaryCurve,()=>t.target.center)),mi.ContainmentLoop(i,e)||(i.curve=mi.GetEdgeLine(t)),Mt.trimSplineAndCalculateArrowheadsII(i,i.sourcePort.Curve,i.targetPort.Curve,t.curve,!1)}static ContainmentLoop(t,e){const i=t.sourcePort.Curve,s=t.targetPort.Curve;if(i==null||s==null)return!1;const n=i.boundingBox,o=s.boundingBox,a=n.containsRect(o),h=!a&&o.containsRect(n);return a||h?(t.curve=mi.CreateLoop(n,o,h,e),!0):!1}static CreateLoop(t,e,i,s){return i?mi.CreateLoop_(t,e,s,!1):mi.CreateLoop_(e,t,s,!0)}static CreateLoop_(t,e,i,s){const n=t.center,o=mi.FindClosestPointOnBoxBoundary(t.center,e);let a=o.sub(n);const u=(Math.abs(a.x)<C.distanceEpsilon?Math.min(n.y-e.bottom,e.top-n.y):Math.min(n.x-e.left,e.right-n.x))/2,c=Math.min(i,u);a.length<=C.distanceEpsilon&&(a=new d(1,0));const m=a.normalize(),S=m.rotate(Math.PI/2),A=o.add(m.mul(i)),I=A.add(S.mul(c)),B=o.add(S.mul(c)),q=n.add(S.mul(c));return(s?G.mkFromPoints([q,B,I,A,o,n]):G.mkFromPoints([n,o,A,I,B,q])).createCurve()}static FindClosestPointOnBoxBoundary(t,e){const i=t.x-e.left<e.right-t.x?e.left:e.right,s=t.y-e.bottom<e.top-t.y?e.bottom:e.top;return Math.abs(i-t.x)<Math.abs(s-t.y)?new d(i,t.y):new d(t.x,s)}static GetEdgeLine(t){let e,i;t.sourcePort==null?(e=t.source.center,i=t.source.boundaryCurve):(e=t.sourcePort.Location,i=t.sourcePort.Curve);let s,n;t.targetPort==null?(s=t.target.center,n=t.target.boundaryCurve):(s=t.targetPort.Location,n=t.targetPort.Curve);let o=D.mkPP(e,s),a=w.getAllIntersections(i,o,!1);if(a.length>0){let h=o.trim(a[0].par1,1);h instanceof D&&(o=h,a=w.getAllIntersections(n,o,!1),a.length>0&&(h=o.trim(0,a[0].par1),h instanceof D&&(o=h)))}return o}static CreateSimpleEdgeCurveWithUnderlyingPolyline(t){const e=t.sourcePort?t.sourcePort.Location:t.source.center,i=t.targetPort?t.targetPort.Location:t.target.center;if(t.source===t.target){const s=2/(3*t.source.boundaryCurve.boundingBox.width),n=t.source.boundingBox.height/4;t.smoothedPolyline=mi.CreateUnderlyingPolylineForSelfEdge(e,s,n),t.curve=t.smoothedPolyline.createCurve()}else t.smoothedPolyline=G.mkFromPoints([e,i]),t.curve=t.smoothedPolyline.createCurve();Mt.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,t.curve,!1)}static CreateUnderlyingPolylineForSelfEdge(t,e,i){const s=t.add(new d(0,i)),n=t.add(new d(e,i)),o=t.add(new d(e,i*-1)),a=t.add(new d(0,i*-1));let h=Ut.mkSiteP(t);const u=new G(h);return h=Ut.mkSiteSP(h,s),h=Ut.mkSiteSP(h,n),h=Ut.mkSiteSP(h,o),h=Ut.mkSiteSP(h,a),Ut.mkSiteSP(h,t),u}static SetStraightLineEdgesWithUnderlyingPolylines(t){Zt.CreatePortsIfNeeded(Array.from(t.deepEdges));for(const e of t.deepEdges)mi.CreateSimpleEdgeCurveWithUnderlyingPolyline(e)}}/*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */var Vl;const va=function(){var l={exports:{}};return function(t,e,i){/*! The following comments were added due to code inlined from "@esfx/internal-binarysearch": *//*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */"use strict";Object.defineProperty(e,"__esModule",{value:!0});function s(n,o,a){if(n.length===0)return-1;let h=0,u=n.length-1;for(;h<=u;){const c=h+(u-h>>1),m=n[c];switch(Math.sign(a.compare(m,o))){case-1:h=c+1;break;case 0:return c;case 1:u=c-1;break}}return~h}e.binarySearch=s}(l,l.exports,null),l.exports}();class Tu{constructor(...t){this._values=[];let e,i;if(t.length>0){const s=t[0];s===void 0||s!=null&&Symbol.iterator in Object(s)?(e=s,t.length>1&&(i=t[1])):i=s}if(i??(i=ss.defaultComparer),this._comparer=typeof i=="function"?ss.create(i):i,e)for(const s of e)this.add(s)}get comparer(){return this._comparer}get size(){return this._values.length}has(t){return(0,va.binarySearch)(this._values,t,this._comparer)>=0}add(t){const e=(0,va.binarySearch)(this._values,t,this._comparer);return e>=0?this._values[e]=t:this._values.splice(~e,0,t),this}delete(t){const e=(0,va.binarySearch)(this._values,t,this._comparer);return e>=0?(this._values.splice(e,1),!0):!1}clear(){this._values.length=0}keys(){return this._values.values()}values(){return this._values.values()}*entries(){for(let t=0;t<this._values.length;t++)yield[this._values[t],this._values[t]]}[Symbol.iterator](){return this.values()}forEach(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");for(const i of this)t.call(e,i,i,this)}get[we.size](){return this.size}[we.has](t){return this.has(t)}[we.add](t){this.add(t)}[we.delete](t){return this.delete(t)}[we.clear](){this.clear()}}Vl=Tu,Object.defineProperty(Vl.prototype,Symbol.toStringTag,{configurable:!0,writable:!0,value:"SortedSet"});/*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */var Wl;const _e=function(){var l={exports:{}};return function(t,e,i){/*! The following comments were added due to code inlined from "@esfx/internal-collections-hash": *//*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. THIRD PARTY LICENSE NOTICE: HashMap is derived from the implementation of Dictionary<T> in .NET Core. HashSet is derived from the implementation of HashSet<T> in .NET Core. "getPrime", "expandPrime", and "isPrime" are derived from the implementation of "HashHelpers" in .NET Core. .NET Core is licensed under the MIT License: The MIT License (MIT) Copyright (c) .NET Foundation and Contributors All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */"use strict";Object.defineProperty(e,"__esModule",{value:!0});const s=2**31-1,n=2146435069,o=101,a=[3,7,11,17,23,29,37,47,59,71,89,107,131,163,197,239,293,353,431,521,631,761,919,1103,1327,1597,1931,2333,2801,3371,4049,4861,5839,7013,8419,10103,12143,14591,17519,21023,25229,30293,36353,43627,52361,62851,75431,90523,108631,130363,156437,187751,225307,270371,324449,389357,467237,560689,672827,807403,968897,1162687,1395263,1674319,2009191,2411033,2893249,3471899,4166287,4999559,5999471,7199369];function h(F){if(F&1){const X=Math.sqrt(F)|0;for(let J=3;J<=X;J+=2)if(!(F%J))return!1;return!0}return F===2}function u(F){if(F<0)throw new RangeError;for(let X=0;X<a.length;X++){const J=a[X];if(J>=F)return J}for(let X=F|1;X<s;X+=2)if(h(X)&&(X-1)%o)return X;return F}function c(F){const X=2*F;return X>n&&n>F?n:u(X)}function m(){return{prevEntry:void 0,nextEntry:void 0,skipNextEntry:!1,next:0,hashCode:0,key:void 0,value:void 0}}function S(F,X){const J=m(),dt={buckets:void 0,entries:void 0,freeSize:0,freeList:0,size:0,equaler:F,head:J,tail:J};return A(dt,X),dt}e.createHashData=S;function A(F,X){const J=u(X);return F.freeList=-1,F.buckets=new Int32Array(J),F.entries=new Array(J),J}function I(F,X){const J=F.size,dt=new Int32Array(X),ut=F.entries?F.entries.slice():[];ut.length=X;for(let St=0;St<J;St++){const Rt=ut[St];if(Rt&&Rt.hashCode>=0){const Wt=Rt.hashCode%X;Rt.next=dt[Wt]-1,dt[Wt]=St+1}}F.buckets=dt,F.entries=ut}function B(F,X){let J=-1;if(F.buckets&&F.entries){let dt=F.equaler.hash(X)&s;J=F.buckets[dt%F.buckets.length]-1;const ut=F.entries.length;for(;J>>>0<ut;){const St=F.entries[J];if(St.hashCode===dt&&F.equaler.equals(St.key,X))break;J=St.next}}return J}e.findEntryIndex=B;function q(F,X){const J=B(F,X);return J>=0?F.entries[J].value:void 0}e.findEntryValue=q;function rt(F,X,J){if(F.buckets||A(F,0),!F.buckets||!F.entries)throw new Error;const dt=F.equaler.hash(X)&s;let ut=dt%F.buckets.length,St=F.buckets[ut]-1;for(;St>>>0<F.entries.length;){const $s=F.entries[St];if($s.hashCode===dt&&F.equaler.equals($s.key,X)){$s.value=J;return}St=$s.next}let Rt=!1,Wt;if(F.freeSize>0)Wt=F.freeList,Rt=!0,F.freeSize--;else{const $s=F.size;if($s===F.entries.length){if(I(F,c(F.size)),!F.buckets||!F.entries)throw new Error;ut=dt%F.buckets.length}Wt=$s,F.size=$s+1}const ei=F.entries[Wt]||(F.entries[Wt]=m());Rt&&(F.freeList=ei.next),ei.hashCode=dt,ei.next=F.buckets[ut]-1,ei.key=X,ei.value=J,ei.skipNextEntry=!1;const Yi=F.tail;Yi.nextEntry=ei,ei.prevEntry=Yi,F.tail=ei,F.buckets[ut]=Wt+1}e.insertEntry=rt;function ct(F,X){if(F.buckets&&F.entries){const J=F.equaler.hash(X)&s,dt=J%F.buckets.length;let ut=-1,St;for(let Rt=F.buckets[dt]-1;Rt>=0;Rt=St.next){if(St=F.entries[Rt],St.hashCode===J&&F.equaler.equals(St.key,X)){ut<0?F.buckets[dt]=St.next+1:F.entries[ut].next=St.next;const Wt=St.prevEntry;return Wt.nextEntry=St.nextEntry,Wt.nextEntry&&(Wt.nextEntry.prevEntry=Wt),F.tail===St&&(F.tail=Wt),St.hashCode=-1,St.next=F.freeList,St.key=void 0,St.value=void 0,St.prevEntry=void 0,St.nextEntry=Wt,St.skipNextEntry=!0,F.freeList=Rt,F.freeSize++,!0}ut=Rt}}return!1}e.deleteEntry=ct;function Q(F){if(F.size>0){F.buckets&&F.buckets.fill(0),F.entries&&F.entries.fill(void 0);let J=F.head.nextEntry;for(;J;){const dt=J.nextEntry;J.prevEntry=void 0,J.nextEntry=F.head,J.skipNextEntry=!0,J=dt}F.head.nextEntry=void 0,F.tail=F.head,F.size=0,F.freeList=-1,F.freeSize=0}}e.clearEntries=Q;function pt(F,X){if(X<0)throw new RangeError;const J=F.entries?F.entries.length:0;if(J>=X)return J;if(!F.buckets)return A(F,X);const dt=u(X);return I(F,u(X)),dt}e.ensureCapacity=pt;function Lt(F,X=F.size-F.freeSize){if(X<F.size)throw new RangeError;if(!F.buckets||!F.entries)return;const J=u(X),dt=F.entries;if(J>=(dt?dt.length:0))return;const ut=F.size;if(A(F,J),!F.buckets||!F.entries)throw new Error;let St=0;for(let Rt=0;Rt<ut;Rt++){const Wt=dt[Rt].hashCode;if(Wt>=0){const ei=Wt%J;F.entries[St]=dt[Rt],F.entries[St].next=F.buckets[ei]-1,F.buckets[ei]=St+1,St++}}F.size=St,F.freeSize=0}e.trimExcessEntries=Lt;function Bt(F){return F.key}e.selectEntryKey=Bt;function _t(F){return F.value}e.selectEntryValue=_t;function Fi(F){return[F.key,F.value]}e.selectEntryEntry=Fi;function*fs(F,X){let J=F;for(;J;){const dt=J.skipNextEntry;J=J.nextEntry,!dt&&J&&(yield X(J))}}e.iterateEntries=fs;function V(F,X,J,dt){let ut=X;for(;ut;){const St=ut.skipNextEntry;ut=ut.nextEntry,!St&&ut&&J.call(dt,ut.value,ut.key,F)}}e.forEachEntry=V}(l,l.exports,null),l.exports}();class Hl{constructor(...t){let e,i,s;if(t.length>0){const n=t[0];if(typeof n=="number"){if(!(Object.is(n,n|0)&&n>=0))throw new RangeError("Argument out of range: capacity");e=n,t.length>1&&(s=t[1])}else n===void 0||n!=null&&Symbol.iterator in Object(n)?(i=n,t.length>1&&(s=t[1])):s=n}if(e??(e=0),s??(s=gi.defaultEqualer),this._hashData=(0,_e.createHashData)(s,e),i)for(const[n,o]of i)this.set(n,o)}get equaler(){return this._hashData.equaler}get size(){return this._hashData.size-this._hashData.freeSize}has(t){return(0,_e.findEntryIndex)(this._hashData,t)>=0}get(t){return(0,_e.findEntryValue)(this._hashData,t)}set(t,e){return(0,_e.insertEntry)(this._hashData,t,e),this}delete(t){return(0,_e.deleteEntry)(this._hashData,t)}clear(){(0,_e.clearEntries)(this._hashData)}ensureCapacity(t){if(typeof t!="number")throw new TypeError("Number expected: capacity");if(!(Object.is(t,t|0)&&t>=0))throw new RangeError("Argument out of range: capacity");return(0,_e.ensureCapacity)(this._hashData,t)}trimExcess(t){if(t!==void 0){if(typeof t!="number")throw new TypeError("Number expected: capacity");if(!(Object.is(t,t|0)&&t>=0))throw new RangeError("Argument out of range: capacity")}(0,_e.trimExcessEntries)(this._hashData,t)}keys(){return(0,_e.iterateEntries)(this._hashData.head,_e.selectEntryKey)}values(){return(0,_e.iterateEntries)(this._hashData.head,_e.selectEntryValue)}entries(){return(0,_e.iterateEntries)(this._hashData.head,_e.selectEntryEntry)}[Symbol.iterator](){return this.entries()}forEach(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");(0,_e.forEachEntry)(this,this._hashData.head,t,e)}get[ci.size](){return this.size}[ci.has](t){return this.has(t)}[ci.get](t){return this.get(t)}[ci.keys](){return this.keys()}[ci.values](){return this.values()}[di.set](t,e){this.set(t,e)}[di.delete](t){return this.delete(t)}[di.clear](){this.clear()}}Wl=Hl,Object.defineProperty(Wl.prototype,Symbol.toStringTag,{configurable:!0,writable:!0,value:"HashMap"});/*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. THIRD PARTY LICENSE NOTICE: HashSet is derived from the implementation of HashSet<T> in .NET Core. .NET Core is licensed under the MIT License: The MIT License (MIT) Copyright (c) .NET Foundation and Contributors All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */var zl;const ti=function(){var l={exports:{}};return function(t,e,i){/*! The following comments were added due to code inlined from "@esfx/internal-collections-hash": *//*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. THIRD PARTY LICENSE NOTICE: HashMap is derived from the implementation of Dictionary<T> in .NET Core. HashSet is derived from the implementation of HashSet<T> in .NET Core. "getPrime", "expandPrime", and "isPrime" are derived from the implementation of "HashHelpers" in .NET Core. .NET Core is licensed under the MIT License: The MIT License (MIT) Copyright (c) .NET Foundation and Contributors All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */"use strict";Object.defineProperty(e,"__esModule",{value:!0});const s=2**31-1,n=2146435069,o=101,a=[3,7,11,17,23,29,37,47,59,71,89,107,131,163,197,239,293,353,431,521,631,761,919,1103,1327,1597,1931,2333,2801,3371,4049,4861,5839,7013,8419,10103,12143,14591,17519,21023,25229,30293,36353,43627,52361,62851,75431,90523,108631,130363,156437,187751,225307,270371,324449,389357,467237,560689,672827,807403,968897,1162687,1395263,1674319,2009191,2411033,2893249,3471899,4166287,4999559,5999471,7199369];function h(V){if(V&1){const F=Math.sqrt(V)|0;for(let X=3;X<=F;X+=2)if(!(V%X))return!1;return!0}return V===2}function u(V){if(V<0)throw new RangeError;for(let F=0;F<a.length;F++){const X=a[F];if(X>=V)return X}for(let F=V|1;F<s;F+=2)if(h(F)&&(F-1)%o)return F;return V}function c(V){const F=2*V;return F>n&&n>V?n:u(F)}function m(){return{prevEntry:void 0,nextEntry:void 0,skipNextEntry:!1,next:0,hashCode:0,key:void 0,value:void 0}}function S(V,F){const X=m(),J={buckets:void 0,entries:void 0,freeSize:0,freeList:0,size:0,equaler:V,head:X,tail:X};return A(J,F),J}e.createHashData=S;function A(V,F){const X=u(F);return V.freeList=-1,V.buckets=new Int32Array(X),V.entries=new Array(X),X}function I(V,F){const X=V.size,J=new Int32Array(F),dt=V.entries?V.entries.slice():[];dt.length=F;for(let ut=0;ut<X;ut++){const St=dt[ut];if(St&&St.hashCode>=0){const Rt=St.hashCode%F;St.next=J[Rt]-1,J[Rt]=ut+1}}V.buckets=J,V.entries=dt}function B(V,F){let X=-1;if(V.buckets&&V.entries){let J=V.equaler.hash(F)&s;X=V.buckets[J%V.buckets.length]-1;const dt=V.entries.length;for(;X>>>0<dt;){const ut=V.entries[X];if(ut.hashCode===J&&V.equaler.equals(ut.key,F))break;X=ut.next}}return X}e.findEntryIndex=B;function q(V,F,X){if(V.buckets||A(V,0),!V.buckets||!V.entries)throw new Error;const J=V.equaler.hash(F)&s;let dt=J%V.buckets.length,ut=V.buckets[dt]-1;for(;ut>>>0<V.entries.length;){const Yi=V.entries[ut];if(Yi.hashCode===J&&V.equaler.equals(Yi.key,F)){Yi.value=X;return}ut=Yi.next}let St=!1,Rt;if(V.freeSize>0)Rt=V.freeList,St=!0,V.freeSize--;else{const Yi=V.size;if(Yi===V.entries.length){if(I(V,c(V.size)),!V.buckets||!V.entries)throw new Error;dt=J%V.buckets.length}Rt=Yi,V.size=Yi+1}const Wt=V.entries[Rt]||(V.entries[Rt]=m());St&&(V.freeList=Wt.next),Wt.hashCode=J,Wt.next=V.buckets[dt]-1,Wt.key=F,Wt.value=X,Wt.skipNextEntry=!1;const ei=V.tail;ei.nextEntry=Wt,Wt.prevEntry=ei,V.tail=Wt,V.buckets[dt]=Rt+1}e.insertEntry=q;function rt(V,F){if(V.buckets&&V.entries){const X=V.equaler.hash(F)&s,J=X%V.buckets.length;let dt=-1,ut;for(let St=V.buckets[J]-1;St>=0;St=ut.next){if(ut=V.entries[St],ut.hashCode===X&&V.equaler.equals(ut.key,F)){dt<0?V.buckets[J]=ut.next+1:V.entries[dt].next=ut.next;const Rt=ut.prevEntry;return Rt.nextEntry=ut.nextEntry,Rt.nextEntry&&(Rt.nextEntry.prevEntry=Rt),V.tail===ut&&(V.tail=Rt),ut.hashCode=-1,ut.next=V.freeList,ut.key=void 0,ut.value=void 0,ut.prevEntry=void 0,ut.nextEntry=Rt,ut.skipNextEntry=!0,V.freeList=St,V.freeSize++,!0}dt=St}}return!1}e.deleteEntry=rt;function ct(V){if(V.size>0){V.buckets&&V.buckets.fill(0),V.entries&&V.entries.fill(void 0);let X=V.head.nextEntry;for(;X;){const J=X.nextEntry;X.prevEntry=void 0,X.nextEntry=V.head,X.skipNextEntry=!0,X=J}V.head.nextEntry=void 0,V.tail=V.head,V.size=0,V.freeList=-1,V.freeSize=0}}e.clearEntries=ct;function Q(V,F){if(F<0)throw new RangeError;const X=V.entries?V.entries.length:0;if(X>=F)return X;if(!V.buckets)return A(V,F);const J=u(F);return I(V,u(F)),J}e.ensureCapacity=Q;function pt(V,F=V.size-V.freeSize){if(F<V.size)throw new RangeError;if(!V.buckets||!V.entries)return;const X=u(F),J=V.entries;if(X>=(J?J.length:0))return;const dt=V.size;if(A(V,X),!V.buckets||!V.entries)throw new Error;let ut=0;for(let St=0;St<dt;St++){const Rt=J[St].hashCode;if(Rt>=0){const Wt=Rt%X;V.entries[ut]=J[St],V.entries[ut].next=V.buckets[Wt]-1,V.buckets[Wt]=ut+1,ut++}}V.size=ut,V.freeSize=0}e.trimExcessEntries=pt;function Lt(V){return V.key}e.selectEntryKey=Lt;function Bt(V){return V.value}e.selectEntryValue=Bt;function _t(V){return[V.key,V.value]}e.selectEntryEntry=_t;function*Fi(V,F){let X=V;for(;X;){const J=X.skipNextEntry;X=X.nextEntry,!J&&X&&(yield F(X))}}e.iterateEntries=Fi;function fs(V,F,X,J){let dt=F;for(;dt;){const ut=dt.skipNextEntry;dt=dt.nextEntry,!ut&&dt&&X.call(J,dt.value,dt.key,V)}}e.forEachEntry=fs}(l,l.exports,null),l.exports}();class Ho{constructor(...t){let e,i,s;if(t.length>0){const n=t[0];if(typeof n=="number"){if(!(Object.is(n,n|0)&&n>=0))throw new RangeError("Argument out of range: capacity");e=n,t.length>1&&(s=t[1])}else n===void 0||n!=null&&Symbol.iterator in Object(n)?(i=n,t.length>1&&(s=t[1])):s=n}if(e??(e=0),s??(s=gi.defaultEqualer),this._hashData=(0,ti.createHashData)(s,e),i)for(const n of i)this.add(n)}get equaler(){return this._hashData.equaler}get size(){return this._hashData.size-this._hashData.freeSize}has(t){return(0,ti.findEntryIndex)(this._hashData,t)>=0}add(t){return(0,ti.insertEntry)(this._hashData,t,t),this}tryAdd(t){const e=this.size;return(0,ti.insertEntry)(this._hashData,t,t),this.size>e}delete(t){return(0,ti.deleteEntry)(this._hashData,t)}clear(){(0,ti.clearEntries)(this._hashData)}ensureCapacity(t){if(typeof t!="number")throw new TypeError("Number expected: capacity");if(!(Object.is(t,t|0)&&t>=0))throw new RangeError("Argument out of range: capacity");return(0,ti.ensureCapacity)(this._hashData,t)}trimExcess(t){if(t!==void 0){if(typeof t!="number")throw new TypeError("Number expected: capacity");if(!(Object.is(t,t|0)&&t>=0))throw new RangeError("Argument out of range: capacity")}(0,ti.trimExcessEntries)(this._hashData,t)}keys(){return(0,ti.iterateEntries)(this._hashData.head,ti.selectEntryKey)}values(){return(0,ti.iterateEntries)(this._hashData.head,ti.selectEntryValue)}entries(){return(0,ti.iterateEntries)(this._hashData.head,ti.selectEntryEntry)}[Symbol.iterator](){return this.values()}forEach(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");(0,ti.forEachEntry)(this,this._hashData.head,t,e)}get[we.size](){return this.size}[we.has](t){return this.has(t)}[we.add](t){this.add(t)}[we.delete](t){return this.delete(t)}[we.clear](){this.clear()}}zl=Ho,Object.defineProperty(zl.prototype,Symbol.toStringTag,{configurable:!0,writable:!0,value:"HashSet"});/*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */var ql;class xu{constructor(...t){var e,i;this._size=0;let s,n,o;Lu(t)?[s,o={}]=t:(s=0,Ou(t)?[n,o={}]=t:o={});const a=(e=o?.keyEqualer)!==null&&e!==void 0?e:gi.defaultEqualer,h=(i=o?.valueEqualer)!==null&&i!==void 0?i:gi.defaultEqualer;if(this._map=new Hl(s,a),this._keyEqualer=a,this._valueEqualer=h,n)for(const[u,c]of n)this.add(u,c)}get keyEqualer(){return this._keyEqualer}get valueEqualer(){return this._valueEqualer}get size(){return this._size}has(t){return this._map.has(t)}hasValue(t,e){const i=this._map.get(t);return i?i.has(e):!1}get(t){return this._map.get(t)}add(t,e){let i=this._map.get(t);i||(i=new Ho(this._valueEqualer),this._map.set(t,i));const s=i.size;return i.add(e),this._size+=i.size-s,this}delete(t){const e=this._map.get(t);return e?(this._size-=e.size,this._map.delete(t),e.size):0}deleteValue(t,e){const i=this._map.get(t);if(i){const s=i.size;if(i.delete(e))return this._size+=i.size-s,i.size<=0&&this._map.delete(t),!0}return!1}clear(){this._map.clear(),this._size=0}ensureCapacity(t){return this._map.ensureCapacity(t)}trimExcess(t){this._map.trimExcess(t)}keys(){return this._map.keys()}*values(){for(const t of this._map.values())yield*t}*entries(){for(const[t,e]of this._map)for(const i of e)yield[t,i]}[Symbol.iterator](){return this.entries()}forEach(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");for(const[i,s]of this._map)for(const n of s)t.call(e,n,i,this)}get[Je.size](){return this.size}[Je.has](t){return this.has(t)}[Je.hasValue](t,e){return this.hasValue(t,e)}[Je.get](t){return this.get(t)}[Je.keys](){return this.keys()}[Je.values](){return this.values()}[$n.add](t,e){this.add(t,e)}[$n.delete](t){return this.delete(t)}[$n.deleteValue](t,e){return this.deleteValue(t,e)}[$n.clear](){this.clear()}}ql=xu,Object.defineProperty(ql.prototype,Symbol.toStringTag,{configurable:!0,writable:!0,value:"MultiMap"});function Ou(l){const[t,e]=l;return(t===void 0||t!=null&&Symbol.iterator in Object(t))&&(e===void 0||typeof e=="object"&&e!==null||typeof e=="function")}function Lu(l){const[t,e]=l;return typeof t=="number"&&(e===void 0||typeof e=="object"&&e!==null||typeof e=="function")}/*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. THIRD PARTY LICENSE NOTICE: LinkedList is derived from the implementation of LinkedList in Promise Extensions for Javascript: https://github.com/rbuckton/prex Promise Extensions is licensed under the Apache 2.0 License: Promise Extensions for JavaScript Copyright (c) Microsoft Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */var Ul,jl;let Ia,yn,Gs,Cn,Ms;class ze{constructor(t){this._list=void 0,this._previous=void 0,this._next=void 0,this.value=t}get list(){return this._list}get previous(){if(this._previous&&this._list&&this!==this._list.first)return this._previous}get next(){if(this._next&&this._list&&this._next!==this._list.first)return this._next}detachSelf(){return this._list?this._list.deleteNode(this):!1}}Ul=ze,Ia=(l,t)=>{l._list=t},yn=l=>l._previous,Gs=(l,t)=>{l._previous=t},Cn=l=>l._next,Ms=(l,t)=>{l._next=t},Object.defineProperty(Ul.prototype,Symbol.toStringTag,{configurable:!0,writable:!0,value:"LinkedListNode"});class sr{constructor(...t){this._size=0,this._head=void 0;let e,i;if(t.length>0){const s=t[0];s===void 0||s!=null&&Symbol.iterator in Object(s)?(e=s,t.length>1&&(i=t[1])):i=s}if(i??(i=gi.defaultEqualer),this._equaler=typeof i=="function"?gi.create(i):i,e)for(const s of e)this.push(s)}get equaler(){return this._equaler}get first(){return this._head}get last(){if(this._head)return yn(this._head)}get size(){return this._size}[Symbol.iterator](){return this.values()}*values(){for(const t of this.nodes())yield t.value}*nodes(){let t,e=this.first;for(;e!==void 0;)t=e,e=t.next,yield t}*drain(){for(const t of this.nodes())this.deleteNode(t),yield t.value}nodeOf(t,e){if(e!=null&&!(e instanceof ze))throw new TypeError("LinkedListNode expected: fromNode");if(e!=null&&e.list!==this)throw new TypeError("Wrong list.");for(let i=e??this.first;i;i=i.next)if(this._equaler.equals(i.value,t))return i}lastNodeOf(t,e){if(e!=null&&!(e instanceof ze))throw new TypeError("LinkedListNode expected: fromNode");if(e!=null&&e.list!==this)throw new TypeError("Wrong list.");for(let i=e??this.last;i;i=i.previous)if(this._equaler.equals(i.value,t))return i}find(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");let i,s=this.first;for(;s!==void 0;){i=s,s=i.next;const n=i.value;if(t.call(e,n,i,this))return n}}findLast(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");let i,s=this.last;for(;s!==void 0;){i=s,s=i.previous;const n=i.value;if(t.call(e,n,i,this))return n}}findNode(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");let i,s=this.first;for(;s!==void 0;)if(i=s,s=i.next,t.call(e,i.value,i,this))return i}findLastNode(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");let i,s=this.last;for(;s!==void 0;)if(i=s,s=i.previous,t.call(e,i.value,i,this))return i}has(t){return this.nodeOf(t)!==void 0}insertBefore(t,e){if(t!=null&&!(t instanceof ze))throw new TypeError("LinkedListNode expected: node");if(t!=null&&t.list!==this)throw new TypeError("Wrong list.");return this._insertNode(t??void 0,new ze(e),0)}insertNodeBefore(t,e){if(t!=null&&!(t instanceof ze))throw new TypeError("LinkedListNode expected: node");if(t!=null&&t.list!==this)throw new TypeError("Wrong list.");if(!(e instanceof ze))throw new TypeError("LinkedListNode expected: newNode");if(e.list)throw new Error("Node is already attached to a list.");this._insertNode(t||void 0,e,0)}insertAfter(t,e){if(t!=null&&!(t instanceof ze))throw new TypeError("LinkedListNode expected: node");if(t!=null&&t.list!==this)throw new TypeError("Wrong list.");return this._insertNode(t||void 0,new ze(e),1)}insertNodeAfter(t,e){if(t!=null&&!(t instanceof ze))throw new TypeError("LinkedListNode expected: node");if(t!=null&&t.list!==this)throw new TypeError("Wrong list.");if(!(e instanceof ze))throw new TypeError("LinkedListNode expected: newNode");if(e.list)throw new Error("Node is already attached to a list.");this._insertNode(t||void 0,e,1)}push(t){return this._insertNode(void 0,new ze(t),1)}pushNode(t){if(!(t instanceof ze))throw new TypeError("LinkedListNode expected: newNode");if(t.list)throw new Error("Node is already attached to a list.");this._insertNode(void 0,t,1)}pop(){const t=this.popNode();return t?t.value:void 0}popNode(){const t=this.last;if(this.deleteNode(t))return t}shift(){const t=this.shiftNode();return t?t.value:void 0}shiftNode(){const t=this.first;if(this.deleteNode(t))return t}unshift(t){return this._insertNode(void 0,new ze(t),0)}unshiftNode(t){if(!(t instanceof ze))throw new TypeError("LinkedListNode expected: newNode");if(t.list)throw new Error("Node is already attached to a list.");this._insertNode(void 0,t,0)}delete(t){const e=this.nodeOf(t);if(e&&this.deleteNode(e))return e}deleteNode(t){if(t!=null&&!(t instanceof ze))throw new TypeError("LinkedListNode expected: node");if(t!=null&&t.list!==this)throw new TypeError("Wrong list.");return t==null||!t.list?!1:this._deleteNode(t)}deleteAll(t,e){if(typeof t!="function")throw new TypeError("Function expected: predicate");let i=0,s=this.first;for(;s;){const n=s.next;t.call(e,s.value,s,this)&&s.list===this&&(this._deleteNode(s),++i),s=n}return i}clear(){for(;this.size>0;)this.deleteNode(this.last)}forEach(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");let i,s=this.first;for(;s!==void 0;)i=s,s=i.next,t.call(e,i.value,i,this)}map(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");const i=new sr;let s,n=this.first;for(;n!==void 0;){s=n,n=s.next;const o=t.call(e,s.value,s,this);i.push(o)}return i}filter(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");const i=new sr(this.equaler);let s,n=this.first;for(;n!==void 0;){s=n,n=s.next;const o=s.value;t.call(e,o,s,this)&&i.push(o)}return i}reduce(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");let i=arguments.length>1,s=e,n,o=this.first;for(;o!==void 0;){n=o,o=n.next;const a=n.value;i?s=t(s,a,n,this):(s=a,i=!0)}return s}reduceRight(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");let i=arguments.length>1,s=e,n,o=this.last;for(;o!==void 0;){n=o;const a=n.value;i?s=t(s,a,n,this):(s=a,i=!0),o=n.previous}return s}some(t,e){if(t!==void 0&&typeof t!="function")throw new TypeError("Function expected: callback");let i,s=this.first;for(;s!==void 0;)if(i=s,s=i.next,!t||t.call(e,i.value,i,this))return!0;return!1}every(t,e){if(typeof t!="function")throw new TypeError("Function expected: callback");let i=!1,s,n=this.first;for(;n!==void 0;){if(s=n,n=s.next,!t.call(e,s.value,s,this))return!1;i=!0}return i}_deleteNode(t){return Cn(t)===t?this._head=void 0:(Gs(Cn(t),yn(t)),Ms(yn(t),Cn(t)),this._head===t&&(this._head=Cn(t))),Ia(t,void 0),Gs(t,void 0),Ms(t,void 0),this._size--,!0}_insertNode(t,e,i){if(Ia(e,this),this._head===void 0)Ms(e,e),Gs(e,e),this._head=e;else switch(i){case 0:t===void 0?(t=this._head,this._head=e):t===this._head&&(this._head=e),Ms(e,t),Gs(e,yn(t)),Ms(yn(t),e),Gs(t,e);break;case 1:t===void 0&&(t=yn(this._head)),Gs(e,t),Ms(e,Cn(t)),Gs(Cn(t),e),Ms(t,e);break}return this._size++,e}get[oi.size](){return this.size}[oi.has](t){return this.has(t)}[we.add](t){this.push(t)}[we.delete](t){return!!this.delete(t)}[we.clear](){this.clear()}}jl=sr,Object.defineProperty(jl.prototype,Symbol.toStringTag,{configurable:!0,writable:!0,value:"LinkedList"});/*! Copyright 2019 Ron Buckton Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */var En;(function(l){l[l.OverlapsOtherLabels=0]="OverlapsOtherLabels",l[l.OverlapsNodes=1]="OverlapsNodes",l[l.OverlapsEdges=2]="OverlapsEdges",l[l.OverlapsNothing=Number.MAX_VALUE]="OverlapsNothing"})(En||(En={}));var ai;(function(l){l[l.Any=0]="Any",l[l.Port=1]="Port",l[l.Starboard=2]="Starboard",l[l.Top=3]="Top",l[l.Bottom=4]="Bottom",l[l.Left=5]="Left",l[l.Right=6]="Right"})(ai||(ai={}));class Bu{}class Fu{constructor(){this.points=new sr,this.coveredLength=0}AddFirst(t){if(this.points.size!==0){const e=this.points.first.value;this.coveredLength=this.coveredLength+t.Center.sub(e.Center).length}return this.points.insertBefore(null,t),this.coveredLength}AddLast(t){if(this.points.size!==0){const e=this.points.last.value;this.coveredLength=this.coveredLength+t.Center.sub(e.Center).length}return this.points.insertAfter(null,t),this.coveredLength}}var nr;(function(l){l[l.AlongCurve=0]="AlongCurve",l[l.Horizontal=1]="Horizontal"})(nr||(nr={}));class $l{constructor(t){this.location=t,this.boundingBox=Z.rectangleOnPoint(t)}}class Ur{constructor(t,e){this.data=e,this.boundingBox=t}}class Ru{constructor(t){this.innerPoints=[],this.outerPoints=[],this.placementSide=ai.Any,this.placementOffset=.5,this.edgePoints=t,this.placementSide}}class Ft extends zt{constructor(t,e){super(null),this.placementStrategy=[nr.Horizontal,nr.AlongCurve],this.obstacleMaps=[],this.edgeInfos=new Map,this.granularity=Ft.MinGranularity,this.ScaleCollisionGranularity=!0,this.granularity=this.ScaleCollisionGranularity?this.interpolateGranularity(e.length):Ft.MinGranularity,this.InitializeObstacles(t,e),this.edges=e}get CollisionGranularity(){return this.granularity}set CollisionGranularity(t){this.granularity=t}static constructorG(t){return new Ft(Array.from(t.nodesBreadthFirst),Array.from(t.deepEdges).filter(e=>e.label))}static constructorGA(t,e){return new Ft(Array.from(t.nodesBreadthFirst),e.filter(i=>i.label))}interpolateGranularity(t){if(t<=Ft.LowerEdgeBound)return Ft.MaxGranularity;if(t>=Ft.UpperEdgeBound)return Ft.MinGranularity;const e=(Ft.UpperEdgeBound-Ft.LowerEdgeBound)/(t-Ft.LowerEdgeBound);return Math.ceil(Ft.MinGranularity+e)}InitializeObstacles(t,e){const i=this.GetEdgeObstacles(e);this.obstacleMaps[1]=tn(t.map(s=>[s.boundingBox,new Ur(s.boundingBox,s)])),this.obstacleMaps[2]=tn(i.map(s=>[s.boundingBox,new Ur(s.boundingBox,s)]))}static CurvePoints(t,e){const i=[],s=t.end.sub(t.start).lengthSquared/(e*e);return Ft.SubdivideCurveSegment(i,t,s,t.parStart,t.parEnd),i.sort(Ft.compareByArgument),i}static compareByArgument(t,e){return t[0]<e[0]?-1:t[0]>e[0]?1:0}static SubdivideCurveSegment(t,e,i,s,n){if(t.length>64)return;const o=e.value(s),a=e.value(n);if(o.sub(a).lengthSquared>i){const h=(s+n)/2;Ft.SubdivideCurveSegment(t,e,i,s,h),Ft.SubdivideCurveSegment(t,e,i,h,n)}else t.push([s,o])}static PlaceLabelsAtDefaultPositions(t,e){for(const i of e)i.label&&new Ft([i.source,i.target],[i]).run()}GetEdgeObstacles(t){const e=[];for(const i of t){if(i.curve==null)continue;const s=Ft.CurvePoints(i.curve,this.CollisionGranularity);this.edgeInfos.set(i,new Ru(s));for(const n of s)e.push(new $l(n[1]))}return e}AddLabelObstacle(t){this.labelObstacleMap==null?(this.labelObstacleMap=tn([[t.boundingBox,t]]),this.obstacleMaps[0]=this.labelObstacleMap):this.labelObstacleMap.Add(t.boundingBox,t)}run(){this.edges.sort((t,e)=>this.edgeInfos.get(t).edgePoints.length-this.edgeInfos.get(e).edgePoints.length);for(const t of this.edges)this.PlaceLabel(t)}PlaceLabel(t){let e=!1;for(const i of this.placementStrategy){switch(i){case nr.AlongCurve:e=this.PlaceEdgeLabelOnCurve(t.label);break;case nr.Horizontal:e=this.PlaceEdgeLabelHorizontally(t);break;default:throw new Error("unexpected case")}if(e)break}e?this.CalculateCenterLabelInfoCenter(t.label):this.PlaceLabelAtFirstPosition(t.label)}getLabelInfo(t){const e=t.parent;return this.edgeInfos.get(e)}PlaceLabelAtFirstPosition(t){const e=t.parent,i=e.curve,s=this.edgeInfos.get(e).edgePoints,n=this.StartIndex(t,s.map(S=>S[1])),o=s[n][1];let a=i.derivative(s[n][0]);a.length<C.distanceEpsilon&&(a=new d(1,1)),a=a.normalize();const h=new De(t.width,t.height),u=this.getLabelInfo(t),c=Ft.GetPossibleSides(u.placementSide,a)[0],m=Ft.GetLabelBounds(o,a,h,c);this.SetLabelBounds(this.getLabelInfo(t),m)}StartIndex(t,e){const i=this.getLabelInfo(t);return Math.min(e.length-1,Math.max(0,Math.floor(e.length*i.placementOffset)))}CalculateCenterLabelInfoCenter(t){const e=this.getLabelInfo(t);let i=new d(0,0);for(const s of e.innerPoints)i=i.add(s);for(const s of e.outerPoints)i=i.add(s);t.positionCenter(i.div(e.innerPoints.length+e.outerPoints.length))}PlaceEdgeLabelHorizontally(t){const e=t.label,s=this.getLabelInfo(e).edgePoints,n=new De(e.width,e.height);let o=-1,a=Z.mkEmpty();const h=t.curve;for(const u of Ft.ExpandingSearch(this.StartIndex(e,s.map(c=>c[1])),0,s.length)){const c=s[u];let m=h.derivative(c[0]);if(!N(m.lengthSquared,0)){m=m.normalize();for(const S of Ft.GetPossibleSides(this.getLabelInfo(e).placementSide,m)){const A=Ft.GetLabelBounds(c[1],m,n,S),I=this.ConflictIndexRL(A,e);if(I>o&&(o=I,a=A,o===Number.MAX_VALUE))break}if(o===Number.MAX_VALUE)break}}if(o>=0){this.SetLabelBounds(this.getLabelInfo(e),a);const u=new Ur(a,null);this.AddLabelObstacle(u);const c=this.getLabelInfo(e);return o===0?c.placementResult=En.OverlapsOtherLabels:o===1?c.placementResult=En.OverlapsNodes:o===2?c.placementResult=En.OverlapsEdges:c.placementResult=En.OverlapsNothing,!0}return!1}static GetLabelBounds(t,e,i,s){const n=e.rotate(Math.PI/2).mul(s),o=t.add(n),a=1;let h=n.x>0?o.x:o.x-i.width,u=n.y>0?o.y:o.y-i.height;if(Math.abs(n.x)<.75){const c=Math.acos(Math.abs(n.y)/a),m=a/Math.sin(c),S=a/Math.cos(c);h+=(n.x>0?-1:1)*Math.min(m,i.width/2),u+=(n.y>0?1:-1)*S}else if(Math.abs(n.y)<.75){const c=Math.acos(Math.abs(n.x)/a),m=a/Math.sin(c),S=a/Math.cos(c);h+=(n.x>0?1:-1)*S,u+=(n.y>0?-1:1)*Math.min(m,i.height/2)}return Z.mkLeftBottomSize(h,u,i)}SetLabelBounds(t,e){t.innerPoints=[e.leftTop,e.rightTop],t.outerPoints=[e.leftBottom,e.rightBottom]}static GetPossibleSides(t,e){switch(e.length===0&&(t=ai.Any),t){case ai.Port:return[-1];case ai.Starboard:return[1];case ai.Top:return N(e.x,0)?Ft.GetPossibleSides(ai.Left,e):[1];case ai.Bottom:return N(e.x,0)?Ft.GetPossibleSides(ai.Right,e):[e.x<0?-1:1];case ai.Left:return N(e.y,0)?Ft.GetPossibleSides(ai.Top,e):[e.y<0?-1:1];case ai.Right:return N(e.y,0)?Ft.GetPossibleSides(ai.Bottom,e):[e.y<0?1:-1];default:return[-1,1]}}static*ExpandingSearch(t,e,i){let s=t+1,n=s;for(;n>e;)yield--n;for(;s<i;)yield s++}static PointSetLength(t){let e=0,i=null;for(const s of t)i!=null&&(e+=i.sub(s.Center).length),i=s.Center;return e}PlaceEdgeLabelOnCurve(t){const e=t.parent,i=this.getLabelInfo(t);i.innerPoints=null;const s=i.edgePoints,n=3,o=t.height/2,a=new De(o,o),h=t.width;for(const u of Ft.ExpandingSearch(this.StartIndex(t,s),0,s.length)){const c=this.GetSidesAndEdgeCurve(t,e,s,u);for(const m of c){const S=new Fu,A={coveredLength:0};if(this.ProcessExpandingSearchOnSide(u,s,e.curve,m,o,n,a,A,S,h),A.coveredLength>=h)return this.CaseOfCoveredLengthGreaterThanLabelLength(t,S,A.coveredLength,h,a),!0}}return!1}CaseOfCoveredLengthGreaterThanLabelLength(t,e,i,s,n){const o=new Array,a=new Array,h=Array.from(e.points),u=i-s;if(u>0){let m=h[h.length-1],S=h[h.length-2],A=m.Center.sub(S.Center),I=A.length;u>I&&(m=h[0],S=h[1],A=m.Center.sub(S.Center),I=A.length);const B=A.mul((I-u)/I);m.Center=S.Center.add(B),m.Inner=S.Inner.add(B),m.Outer=S.Outer.add(B)}this.GoOverOrderedPointsAndAddLabelObstacels(h,o,a,n);const c=this.getLabelInfo(t);c.innerPoints=o,c.outerPoints=a}GoOverOrderedPointsAndAddLabelObstacels(t,e,i,s){for(const n of t){const o=n.Center;e.push(n.Inner),i.push(n.Outer);const a=new Ur(Z.mkSizeCenter(new De(s.width*2,s.height*2),o),null);this.AddLabelObstacle(a)}}ProcessExpandingSearchOnSide(t,e,i,s,n,o,a,h,u,c){for(const m of Ft.ExpandingSearch(t,0,e.length)){const[S,A]=e[m],I=i.derivative(S);if(N(I.lengthSquared,0))continue;const B=I.rotate(Math.PI/2).normalize().mul(s),q=A.add(B.mul(n+o));if(this.Conflict(q,n,a))break;{const rt=new Bu;if(rt.Center=q,rt.Inner=A.add(B.mul(o)),rt.Outer=A.add(B.mul(2*n+o)),h.coveredLength=m<=t?u.AddFirst(rt):u.AddLast(rt),h.coveredLength>=c)break}}}GetSidesAndEdgeCurve(t,e,i,s){const n=e.curve.derivative(i[s][0]);return Ft.GetPossibleSides(this.getLabelInfo(t).placementSide,n)}Conflict(t,e,i){return this.ConflictIndex(t,e,i)!==Number.MAX_VALUE}ConflictIndexRL(t,e){const i=e.parent,s=i.source,n=i.target;for(let o=0;o<this.obstacleMaps.length;o++)if(this.obstacleMaps[o]!=null){for(const a of this.obstacleMaps[o].GetAllIntersecting(t))if(!(o===En.OverlapsNodes&&a instanceof Ur&&a.data instanceof Xt&&(s.node.isDescendantOf(a.data.graph)||n.node.isDescendantOf(a.data))))return o}return Number.MAX_VALUE}ConflictIndex(t,e,i){const s=Z.creatRectangleWithSize(new De(i.width*2,i.height*2),t),n=e*e;for(let o=0;o<this.obstacleMaps.length;o++)if(this.obstacleMaps[o]!=null){for(let a=0;a<this.obstacleMaps.length;a++)if(this.obstacleMaps[a]!=null)for(const h of this.obstacleMaps[a].GetAllIntersecting(s))if(h instanceof $l){if(t.sub(h.location).lengthSquared<n)return a}else return a;return Number.MAX_VALUE}}}Ft.MinGranularity=5,Ft.MaxGranularity=50,Ft.LowerEdgeBound=500,Ft.UpperEdgeBound=3e3;class ds extends fe{constructor(t,e=null){super(t,Et.AlgorithmDataIndex),this.data=e}clone(){throw new Error("Method not implemented.")}rebind(t){this.entity=t,this.bind(Et.AlgorithmDataIndex)}static getAlgData(t){return t.getAttr(Et.AlgorithmDataIndex)}}function Ta(l){const t=ds.getAlgData(l.node);return t==null?null:t.data}class Du{constructor(t,e){this.force=new d(0,0),this.stayWeight=1,this.index=t,this.geomNode=e,this.ResetBounds()}get Center(){return this.center}set Center(t){this.geomNode.center=t,this.center=t}ResetBounds(){this.previousCenter=this.geomNode.center,this.center=this.geomNode.center,this.Width=this.geomNode.width,this.Height=this.geomNode.height}ToString(){return"FINode("+(this.index+("):"+this.geomNode))}}class Nu{constructor(t){this._length=1,this.mEdge=t,this.sourceFiNode=Ta(this.mEdge.source),this.targetFiNode=Ta(this.mEdge.target)}get source(){return this.sourceFiNode.index}get target(){return this.targetFiNode.index}get length(){return this._length}set length(t){this._length=t}vector(){return this.sourceFiNode.geomNode.center.sub(this.targetFiNode.geomNode.center)}}class be{get Center(){return this.c}get Radius(){return this.r}Distance2(t){const e=this.c.y-t.y,i=this.c.x-t.x;return i*i+e*e}Contains(t){return this.Distance2(t)-1e-7<=this.r2}ContainsPN(t,e){for(let i=0;i<t.length;i++)if(e.findIndex(s=>s==i)==-1&&!this.Contains(t[i]))return!1;return!0}static constructorP(t){const e=new be;return e.c=t,e.r=0,e.r2=0,e}static midPoint(t,e){return new d((e.x+t.x)/2,(e.y+t.y)/2)}static constructorPP(t,e){const i=new be;return i.c=be.midPoint(t,e),i.r2=i.Distance2(t),i.r=Math.sqrt(i.r2),Ht.assert(i.OnBoundary(t)),Ht.assert(i.OnBoundary(e)),i}OnBoundary(t){const e=this.Distance2(t);return Math.abs(e-this.r2)/(e+this.r2)<1e-5}static centre(t,e,i){Ht.assert(e.x!=t.x),Ht.assert(i.x!=e.x);const s=(e.y-t.y)/(e.x-t.x),n=(i.y-e.y)/(i.x-e.x);Ht.assert(n!=s);let o;const a=(s*n*(t.y-i.y)+n*(t.x+e.x)-s*(e.x+i.x))/(2*(n-s));return Math.abs(s)>Math.abs(n)?o=(t.y+e.y)/2-(a-(t.x+e.x)/2)/s:o=(e.y+i.y)/2-(a-(e.x+i.x)/2)/n,new d(a,o)}static Collinear(t,e,i){return t.x*(e.y-i.y)+(e.x*(i.y-t.y)+i.x*(t.y-e.y))==0}static constructorPPP(t,e,i){be.count++;const s=new be;if(be.Collinear(t,e,i)){const n=new d(Math.min(t.x,Math.min(e.x,i.x)),Math.min(t.y,Math.max(e.y,i.y))),o=new d(Math.max(t.x,Math.max(e.x,i.x)),Math.max(t.y,Math.max(e.y,i.y)));s.c=be.midPoint(n,o),s.r2=s.Distance2(o),s.r=Math.sqrt(s.r2)}else{const n=e.x-t.x,o=i.x-e.x,a=i.x-t.x;n!=0?o!=0?s.c=be.centre(t,e,i):(Ht.assert(a!=0),s.c=be.centre(e,t,i)):(Ht.assert(o!=0),s.c=be.centre(e,i,t)),s.r2=s.Distance2(t),s.r=Math.sqrt(s.r2),Ht.assert(s.OnBoundary(t)),Ht.assert(s.OnBoundary(e)),Ht.assert(s.OnBoundary(i))}return s}}be.count=0;class ku{constructor(t,e){switch(this.boundary=e,Ht.assert(e.length<=3),e.length){case 0:this.disc=null;break;case 1:this.disc=be.constructorP(t[e[0]]);break;case 2:this.disc=be.constructorPP(t[e[0]],t[e[1]]);break;case 3:this.disc=be.constructorPPP(t[e[0]],t[e[1]],t[e[2]]);break}}contains(t){return this.disc==null?!1:this.disc.Contains(t)}}class Gu{constructor(t){this.ps=t,this.L=new sr;for(let i=0;i<this.ps.length;i++)this.L.push(i);const e=this.mtf_md(null,new Array);this.disc=e.disc,this.boundary=e.boundary}collinear3(t){return t.length==3?be.Collinear(this.ps[t[0]],this.ps[t[1]],this.ps[t[2]]):!1}mtf_md(t,e){Ht.assert(e.length<=3);let i=new ku(this.ps,e);if(e.length==3)return i;let s=this.L.first;for(;s!=null&&s!=t;){const n=s.next,o=s.value;if(!i.contains(this.ps[o])){const a=Array.from(e);a.push(o),Ht.assert(!this.collinear3(a),"Collinear points on boundary of minimal enclosing disc"),i=this.mtf_md(s,a),this.L.deleteNode(s),this.L.insertNodeBefore(null,s)}s=n}return i}}class Mu{static LinearComputation(t){return new Gu(t).disc}static SlowComputation(t){const e=t.length;let i=null,s=null;for(let n=0;n<e;n++)for(let o=0;o<e;o++){if(n!=o){const a=be.constructorPP(t[n],t[o]);a.ContainsPN(t,[n,o])&&(i==null||i.Radius>a.Radius)&&(i=a,s=[n,o])}for(let a=0;a<e;a++)if(a!=n&&a!=o&&!be.Collinear(t[n],t[o],t[a])){const h=be.constructorPPP(t[n],t[o],t[a]);h.ContainsPN(t,[n,o,a])&&(i==null||i.Radius>h.Radius)&&(i=h,s=[n,o,a])}}return Ht.assert(s!=null),i}}class Oi{static constructorNPA(t,e,i){const s=new Oi;s.p=t,s.z0=new ce(e.x,e.y),s.a=new Array(t);for(let n=0;n<t;n++)s.a[n]=s.compute(n,i);return s}static constructorPMM(t,e,i){const s=new Oi;Ht.assert(e.p==i.p),s.p=e.p,s.z0=new ce(t.x,t.y);const n=i.shift(s.z0),o=e.shift(s.z0);s.a=new Array(s.p);for(let a=0;a<s.p;a++)s.a[a]=xa(o[a],n[a]);return s}static factorial(t){let e=1;for(let i=2;i<=t;i++)e*=i;return e}static binomial(t,e){return Oi.factorial(t)/(Oi.factorial(e)*Oi.factorial(t-e))}sum(t,e){let i=ce.constructorN(0);for(let s=1;s<=t;s++){const n=ce.constructorN(Oi.binomial(t-1,s-1));i=xa(i,Vs(this.a[s],Vs(ce.Pow(e,t-s),n)))}return i}shift(t){const e=new Array(this.p),i=e[0]=this.a[0],s=jr(this.z0,t);for(let n=1;n<this.p;n++){const o=ce.constructorN(n);e[n]=xa(Vs(Wu(i),Oa(ce.Pow(s,n),o)),this.sum(n,s))}return e}compute(t,e){const i=e.length;let s=ce.constructorN(0);if(t==0)s.re=i;else{for(let n=0;n<i;n++){const o=e[n],a=new ce(o.x,o.y);s=jr(s,ce.Pow(jr(a,this.z0),t))}s.divideBy(t)}return s}ApproximateForce(t){const e=new ce(t.x,t.y),i=jr(e,this.z0);let s=Oa(this.a[0],i),n=i,o=0;for(;s=jr(s,Oa(Vu(this.a[o],o),n)),o++,o!=this.p;)n=Vs(n,i);return new d(s.re,-s.im)}static Force(t,e){const i=e.sub(t),s=i.lengthSquared;return s<.1?s!=0?i.div(.1):new d(1,0):i.div(s)}}class ce{constructor(t,e){this.re=t,this.im=e}static constructorN(t){return new ce(t,0)}divideBy(t){this.re/=t,this.im/=t}static Pow(t,e){switch(Ht.assert(e>=0),e){case 0:return ce.constructorN(1);case 1:return t;case 2:return Vs(t,t);case 3:return Vs(t,Vs(t,t));default:return Vs(ce.Pow(t,e/2),ce.Pow(t,e/2+e%2))}}}function xa(l,t){return new ce(l.re+t.re,l.im+t.im)}function Vs(l,t){return new ce(l.re*t.re-l.im*t.im,l.re*t.im+t.re*l.im)}function Vu(l,t){return new ce(l.re*t,l.im*t)}function jr(l,t){return new ce(l.re-t.re,l.im-t.im)}function Wu(l){return new ce(-l.re,-l.im)}function Oa(l,t){const e=t.re*t.re+t.im*t.im;if(e==0)return ce.constructorN(0);const i=l.re*t.re+l.im*t.im,s=l.im*t.re-l.re*t.im;return new ce(i/e,s/e)}var Li;(function(l){l[l.Horizontal=0]="Horizontal",l[l.Vertical=1]="Vertical"})(Li||(Li={}));class Xl{intersects(t){return t.med.Center.sub(this.med.Center).length<t.med.Radius+this.med.Radius}}class Hu extends Xl{constructor(t,e,i){super(),this.med=t,this.parent=e.parent,this.parent!=null&&(this.parent.leftChild==e?this.parent.leftChild=this:this.parent.rightChild=this),this.leftChild=e,this.rightChild=i,e.parent=this,i.parent=this}computeMultipoleCoefficients(t){this.leftChild.computeMultipoleCoefficients(t),this.rightChild.computeMultipoleCoefficients(t),this.multipoleCoefficients=Oi.constructorPMM(this.med.Center,this.leftChild.multipoleCoefficients,this.rightChild.multipoleCoefficients)}}class zo extends Xl{constructor(t){super(),this.particles=t,this.ComputeMinimumEnclosingDisc()}computeMultipoleCoefficients(t){this.multipoleCoefficients=Oi.constructorNPA(t,this.med.Center,this.ps)}ComputeMinimumEnclosingDisc(){const t=this.Size();this.ps=new Array(t);for(let e=0;e<t;e++)this.ps[e]=this.particles[0][e].point;return this.med=Mu.LinearComputation(this.ps)}Min(t){return this.particles[t][0].pos(t)}Size(){return this.particles[0].length}Max(t){return this.particles[t][this.Size()-1].pos(t)}Dimension(t){return this.Max(t)-this.Min(t)}Split(t){const e=this.Dimension(Li.Horizontal)>this.Dimension(Li.Vertical)?Li.Horizontal:Li.Vertical,i=e==Li.Horizontal?Li.Vertical:Li.Horizontal,s=this.Size(),n=s>>1,o=s-n,a=[new Array(n),new Array(n)],h=[new Array(o),new Array(o)];let u=0,c=0;for(let S=0;S<s;S++){const A=this.particles[e][S];S<n?(a[e][S]=A,A.splitLeft=!0):(h[e][S-n]=A,A.splitLeft=!1)}for(let S=0;S<s;S++){const A=this.particles[i][S];A.splitLeft?a[i][c++]=A:h[i][u++]=A}const m=this.med;return this.particles=a,this.ComputeMinimumEnclosingDisc(),t.rightSibling=new zo(h),new Hu(m,this,t.rightSibling)}ComputeForces(){for(const t of this.particles[0])for(const e of this.particles[0])t!=e&&(t.force=t.force.add(Oi.Force(t.point,e.point)))}}class zu{constructor(t){this.point=t,this.force=new d(0,0)}pos(t){return t==Li.Horizontal?this.point.x:this.point.y}}class qu{constructor(t,e){this.particles=t;const i=new Array;i.push(this.particlesBy(Li.Horizontal)),i.push(this.particlesBy(Li.Vertical)),this.leaves=new Array;let s=new zo(i);this.leaves.push(s);const n={rightSibling:null};this.root=s.Split(n),this.leaves.push(n.rightSibling);const o=new Uu(e);for(o.EnqueueLL(s,n.rightSibling);o.length>0;)s=o.dequeue(),s.Split(n),this.leaves.push(n.rightSibling),o.EnqueueLL(s,n.rightSibling)}particlesBy(t){return this.particles.map(e=>e).sort((e,i)=>e.pos(t)-i.pos(t))}ComputeForces(t){this.root.computeMultipoleCoefficients(t);for(const e of this.leaves){e.ComputeForces();const i=new Array;for(i.push(this.root);i.length>0;){const s=i.pop();if(e.intersects(s))if(s instanceof zo)for(const n of e.particles[0])for(const o of s.particles[0])n!=o&&(n.force=n.force.add(Oi.Force(n.point,o.point)));else{const n=s;i.push(n.leftChild),i.push(n.rightChild)}else for(const n of e.particles[0])n.force=n.force.sub(s.multipoleCoefficients.ApproximateForce(n.point))}}}}class Uu extends hi.o{constructor(t){super(),this.B=t}EnqueueLL(t,e){t.Size()>this.B&&this.enqueue(t),e.Size()>this.B&&this.enqueue(e)}}class $r extends zt{constructor(t,e,i){if(super(null),this.clustersInfo=new Map,this.clusterEdges=new Array,this.graph=t,this.settings=e,this.initFiNodesEdges(),this.edges=Array.from(this.graph.shallowEdges).map(s=>ds.getAlgData(s.edge).data),this.nodes=Array.from(this.graph.shallowNodes).map(s=>ds.getAlgData(s.node).data),this.components=new Array,this.settings.InterComponentForces)this.components.push(this.nodes);else{this.basicGraph=ni(this.edges,this.nodes.length);for(const s of Vi(this.basicGraph)){const n=new Array(s.length);let o=0;for(const a of s)n[o++]=this.nodes[a];this.components.push(n)}}this.computeWeight(t),this.setCurrentConstraintLevel(i)}initFiNodesEdges(){let t=0;for(const e of this.graph.shallowNodes){const i=new Du(t++,e);new ds(e.node,i)}for(const e of this.graph.shallowEdges){const i=new Nu(e);new ds(e.edge,i)}}getCurrentConstraintLevel(){return this.currentConstraintLevel}setCurrentConstraintLevel(t){this.currentConstraintLevel=t,this.settings.Unconverge()}ResetNodePositions(){for(const t of this.nodes)t.ResetBounds()}AddRepulsiveForce(t,e){t.force=e.mul(10*this.settings.RepulsiveForceConstant)}AddLogSpringForces(t,e,i){const s=e.length,n=7e-4*this.settings.AttractiveForceConstant*s*Math.log((s+.1)/(i+.1));t.sourceFiNode.force=t.sourceFiNode.force.add(e.mul(n)),t.targetFiNode.force=t.targetFiNode.force.sub(e.mul(n))}AddSquaredSpringForces(t,e,i){const s=e.length,n=i*i+.1,o=this.settings.AttractiveForceConstant*(s-i)/n;t.sourceFiNode.force=t.sourceFiNode.force.add(e.mul(o)),t.targetFiNode.force=t.targetFiNode.force.sub(e.mul(o))}AddSpringForces(t){let e;if(this.settings.RespectEdgePorts){let i=t.sourceFiNode.Center,s=t.targetFiNode.Center;const n=t.mEdge.sourcePort;n instanceof ii&&(i=n.Location);const o=t.mEdge.targetPort;o instanceof ii&&(s=o.Location),e=i.sub(s)}else e=t.vector();this.settings.LogScaleEdgeForces?this.AddLogSpringForces(t,e,t.length):this.AddSquaredSpringForces(t,e,t.length)}static AddGravityForce(t,e,i){i!=null&&(i.force=i.force.sub(t.sub(i.Center).mul(e*1e-4)))}ComputeRepulsiveForces(t){const e=t.length;if(e>16&&this.settings.ApproximateRepulsion){const i=new Array(t.length),s=2*(Math.PI/e);let n=0;for(let a=0;a<e;a++)i[a]=new zu(t[a].Center.add(new d(Math.cos(n),Math.sin(n)).mul(1e-5))),n+=s;new qu(i,8).ComputeForces(5);for(let a=0;a<t.length;a++)this.AddRepulsiveForce(t[a],i[a].force)}else for(const i of t){let s=new d(0,0);for(const n of t)i!=n&&(s=s.add(Oi.Force(i.Center,n.Center)));this.AddRepulsiveForce(i,s)}}SetBarycenter(t){const e=this.clustersInfo.get(t);if(e!=null)return e.barycenter;let i=new d(0,0);if(t.shallowNodeCount||ju(t)){const s=this.clustersInfo.get(t);if((s==null||s.weight==null)&&this.computeWeight(t),s.weight!=null){for(const n of t.shallowNodes)n instanceof Pe?i=i.add(n.center):i=i.add(this.SetBarycenter(n).mul(this.clustersInfo.get(n).weight));this.clustersInfo.get(t).barycenter=i=i.div(s.weight)}}else this.clustersInfo.get(t).barycenter=i;return i}computeWeight(t){let e=0;for(const s of t.shallowNodes)s.entity instanceof Gt?e+=this.computeWeight(s):e++;let i=this.clustersInfo.get(t);return i==null&&this.clustersInfo.set(t,i={barycenter:new d(0,0)}),i.weight=e,e}AddClusterForces(t){if(t!=null){this.SetBarycenter(t);for(const e of this.clusterEdges){const i=gt.getGeom(e.source),s=gt.getGeom(e.target),n=ds.getAlgData(e.source).data,o=ds.getAlgData(e.target).data,a=i.hasOwnProperty("shallowNodes"),h=a?this.clustersInfo.get(i).barycenter:i.center,u=s.hasOwnProperty("shallowNodes"),c=u?this.clustersInfo.get(s).barycenter:s.center;let m=h.sub(c);const S=m.length,A=1e-8*(this.settings.AttractiveInterClusterForceConstant*(S*Math.log(S+.1)));if(m=m.mul(A),a){const I=i;for(const B of I.shallowNodes){const q=ds.getAlgData(B.node).data;q.force=q.force.add(m)}}else n.force=n.force.add(m);if(u){const I=s;for(const B of I.shallowNodes){const q=ds.getAlgData(B.node).data;q.force=q.force.sub(m)}}else o.force=o.force.sub(m)}for(const e of t.subgraphsDepthFirst){const i=this.clustersInfo.get(e).barycenter;for(const s of e.shallowNodes)$r.AddGravityForce(i,this.settings.ClusterGravity,Ta(s))}}}ComputeForces(){if(this.components!=null)for(const t of this.components)this.ComputeRepulsiveForces(t);else this.ComputeRepulsiveForces(this.nodes);this.edges.forEach(t=>this.AddSpringForces(t));for(const t of this.components){let e=new d(0,0);for(let s=0;s<t.length;s++)e=e.add(t[s].Center);e=e.div(t.length);let i=Number.NEGATIVE_INFINITY;for(let s=0;s<t.length;s++){const n=t[s];$r.AddGravityForce(e,this.settings.GravityConstant,n),n.force.length>i&&(i=n.force.length)}if(i>100)for(let s=0;s<t.length;s++)t[s].force=t[s].force.mul(100/i)}this.AddClusterForces(this.graph)}VerletIntegration(){const t=this.energy;this.energy=this.ComputeDescentDirection(1),this.UpdateStepSize(t);let e=0;for(let i=0;i<this.nodes.length;i++){const s=this.nodes[i];e+=s.Center.sub(s.previousCenter).lengthSquared}return e}ComputeDescentDirection(t){this.ResetForceVectors(),this.settings.ApplyForces&&this.ComputeForces();let e=0;for(const i of this.nodes){e=e+i.force.lengthSquared;let s=i.Center.sub(i.previousCenter).mul(this.settings.Friction);const n=i.force.mul(-this.stepSize*t);i.previousCenter=i.Center,Ht.assert(!Number.isNaN(n.x),"!double.IsNaN(a.X)"),Ht.assert(!Number.isNaN(n.y),"!double.IsNaN(a.Y)"),Ht.assert(Number.isFinite(n.x),"!double.IsInfinity(a.X)"),Ht.assert(Number.isFinite(n.y),"!double.IsInfinity(a.Y)"),s=s.add(n),s=s.div(i.stayWeight),i.Center=i.Center.add(s)}return e}ResetForceVectors(){for(const t of this.nodes)t.force=new d(0,0)}UpdateStepSize(t){this.energy<t?++this.progress>=3&&(this.progress=0,this.stepSize/=this.settings.Decay):(this.progress=0,this.stepSize*=this.settings.Decay)}RungeKuttaIntegration(){const t=new Array(this.nodes.length),e=new Array(this.nodes.length),i=new Array(this.nodes.length),s=new Array(this.nodes.length),n=new Array(this.nodes.length),o=this.energy;for(let h=0;h<this.nodes.length;h++)this.nodes[h].previousCenter=this.nodes[h].Center,t[h]=this.nodes[h].Center;const a=3;this.ComputeDescentDirection(a);for(let h=0;h<this.nodes.length;h++)e[h]=this.nodes[h].Center.sub(this.nodes[h].previousCenter),this.nodes[h].Center=t[h].add(e[h].mul(.5));this.ComputeDescentDirection(a);for(let h=0;h<this.nodes.length;h++)i[h]=this.nodes[h].Center.sub(this.nodes[h].previousCenter),this.nodes[h].previousCenter=t[h],this.nodes[h].Center=t[h].add(i[h].mul(.5));this.ComputeDescentDirection(a);for(let h=0;h<this.nodes.length;h++)s[h]=this.nodes[h].Center.sub(this.nodes[h].previousCenter),this.nodes[h].previousCenter=t[h],this.nodes[h].Center=t[h].add(s[h]);this.energy=this.ComputeDescentDirection(a);for(let h=0;h<this.nodes.length;h++){n[h]=this.nodes[h].Center.sub(this.nodes[h].previousCenter),this.nodes[h].previousCenter=t[h];const u=e[h].add(i[h].mul(2).add(s[h].mul(2)).add(n[h])).div(6);this.nodes[h].Center=t[h].add(u)}return this.UpdateStepSize(o),this.nodes.reduce((h,u)=>u.Center.sub(u.previousCenter).lengthSquared+h,0)}run(){this.settings.Converged=!1,this.settings.EdgeRoutesUpToDate=!1,this.settings.Iterations++==0&&(this.stepSize=this.settings.InitialStepSize,this.energy=Number.MAX_VALUE,this.progress=0);for(let t=0;t<this.settings.MinorIterations;t++){if((this.settings.RungeKuttaIntegration?this.RungeKuttaIntegration():this.VerletIntegration())<this.settings.DisplacementThreshold||this.settings.Iterations>this.settings.MaxIterations){this.settings.Converged=!0;break}this.ProgressStep()}}}function ju(l){for(const t of l.Clusters)return!0;return!1}class Ws{constructor(){this.commonSettings=new tr,this.maxIterations=100,this.clusterMargin=10,this.minorIterations=3,this.projectionIterations=5,this.approximateRepulsion=!0,this.RungeKuttaIntegration=!1,this.initialStepSize=1.4,this.decay=.9,this.friction=.8,this.repulsiveForceConstant=1,this.attractiveForceConstant=1,this.gravity=1,this.interComponentForces=!0,this.applyForces=!0,this.AvoidOverlaps=!0,this.approximateRouting=!0,this.logScaleEdgeForces=!0,this.displacementThreshold=.1,this.maxConstraintLevel=2,this.minConstraintLevel=0,this.attractiveInterClusterForceConstant=1,this.clusterGravity=1,this.commonSettings.NodeSeparation*=2}get edgeRoutingSettings(){return this.commonSettings.edgeRoutingSettings}set edgeRoutingSettings(t){this.commonSettings.edgeRoutingSettings=t}get PackingAspectRatio(){return this.commonSettings.PackingAspectRatio}set PackingAspectRatio(t){this.commonSettings.PackingAspectRatio=t}get NodeSeparation(){return this.commonSettings.NodeSeparation}set NodeSeparation(t){this.commonSettings.NodeSeparation=t}get MaxIterations(){return this.maxIterations}set MaxIterations(t){this.maxIterations=t}get MinorIterations(){return this.minorIterations}set MinorIterations(t){this.minorIterations=t}get Iterations(){return this.iterations}set Iterations(t){this.iterations=t}get ProjectionIterations(){return this.projectionIterations}set ProjectionIterations(t){this.projectionIterations=t}get ApproximateRepulsion(){return this.approximateRepulsion}set ApproximateRepulsion(t){this.approximateRepulsion=t}get InitialStepSize(){return this.initialStepSize}set InitialStepSize(t){if(t<=0||t>2)throw new Error("ForceScalar should be greater than 0 and less than 2 (if we let you set it to 0 nothing would happen, greater than 2 would most likely be very unstable!)");this.initialStepSize=t}get Decay(){return this.decay}set Decay(t){if(t<.1||t>1)throw new Error("Setting decay too small gives no progress. 1==no decay, 0.1==minimum allowed value");this.decay=t}get Friction(){return this.friction}set Friction(t){if(t<0||t>1)throw new Error("Setting friction less than 0 or greater than 1 would just be strange. 1==no friction, 0==no conservation of velocity");this.friction=t}get RepulsiveForceConstant(){return this.repulsiveForceConstant}set RepulsiveForceConstant(t){this.repulsiveForceConstant=t}get AttractiveForceConstant(){return this.attractiveForceConstant}set AttractiveForceConstant(t){this.attractiveForceConstant=t}get GravityConstant(){return this.gravity}set GravityConstant(t){this.gravity=t}get InterComponentForces(){return this.interComponentForces}set InterComponentForces(t){this.interComponentForces=t}get ApplyForces(){return this.applyForces}set ApplyForces(t){this.applyForces=t}ResetLayout(){this.Unconverge(),this.algorithm!=null&&this.algorithm.ResetNodePositions()}Unconverge(){this.iterations=0,this.converged=!1}InitializeLayoutGN(t,e){this.InitializeLayout(t,e)}InitializeLayout(t,e){this.algorithm=new $r(t,this,e),this.ResetLayout()}Uninitialize(){this.algorithm=null}get IsInitialized(){return this.algorithm!=null}IncrementalRunG(t){this.IncrementalRunGF(t)}SetupIncrementalRun(t){this.IsInitialized?this.IsDone&&this.ResetLayout():this.InitializeLayout(t,this.MaxConstraintLevel)}IncrementalRunGF(t){this.SetupIncrementalRun(t),this.algorithm.run()}IncrementalRun(t,e){t?.throwIfCanceled(),this.SetupIncrementalRun(e),this.algorithm.cancelToken=t,this.algorithm.run()}Clone(){return Ws.ctorClone(this)}get ApproximateRouting(){return this.approximateRouting}set ApproximateRouting(t){this.approximateRouting=t}get LogScaleEdgeForces(){return this.logScaleEdgeForces}set LogScaleEdgeForces(t){this.logScaleEdgeForces=t}get DisplacementThreshold(){return this.displacementThreshold}set DisplacementThreshold(t){this.displacementThreshold=t}get Converged(){return this.converged}set Converged(t){this.converged=t}get PercentDone(){return this.Converged?100:100*this.iterations/this.MaxIterations}get IsDone(){return this.Converged||this.iterations>=this.MaxIterations}get Energy(){return this.algorithm!=null?this.algorithm.energy:0}get MaxConstraintLevel(){return this.maxConstraintLevel}set MaxConstraintLevel(t){this.maxConstraintLevel!=t&&(this.maxConstraintLevel=t,this.IsInitialized&&this.Uninitialize())}get MinConstraintLevel(){return this.minConstraintLevel}set MinConstraintLevel(t){this.minConstraintLevel=t}getCurrentConstraintLevel(){return this.algorithm==null?0:this.algorithm.getCurrentConstraintLevel()}setCurrentConstraintLevel(t){this.algorithm.setCurrentConstraintLevel(t)}get AttractiveInterClusterForceConstant(){return this.attractiveInterClusterForceConstant}set AttractiveInterClusterForceConstant(t){this.attractiveInterClusterForceConstant=t}static ctorClone(t){const e=new Ws;return e.maxIterations=t.maxIterations,e.minorIterations=t.minorIterations,e.projectionIterations=t.projectionIterations,e.approximateRepulsion=t.approximateRepulsion,e.initialStepSize=t.initialStepSize,e.RungeKuttaIntegration=t.RungeKuttaIntegration,e.decay=t.decay,e.friction=t.friction,e.repulsiveForceConstant=t.repulsiveForceConstant,e.attractiveForceConstant=t.attractiveForceConstant,e.gravity=t.gravity,e.interComponentForces=t.interComponentForces,e.applyForces=t.applyForces,e.AvoidOverlaps=t.AvoidOverlaps,e.RespectEdgePorts=t.RespectEdgePorts,e.RouteEdges=t.RouteEdges,e.approximateRouting=t.approximateRouting,e.logScaleEdgeForces=t.logScaleEdgeForces,e.displacementThreshold=t.displacementThreshold,e.minConstraintLevel=t.minConstraintLevel,e.maxConstraintLevel=t.maxConstraintLevel,e.attractiveInterClusterForceConstant=t.attractiveInterClusterForceConstant,e.clusterGravity=t.clusterGravity,e.PackingAspectRatio=t.PackingAspectRatio,e.NodeSeparation=t.NodeSeparation,e.clusterMargin=t.clusterMargin,e}get ClusterGravity(){return this.clusterGravity}set ClusterGravity(t){this.clusterGravity=t}static CreateFastIncrementalLayoutSettings(){const t=new Ws;return t.ApplyForces=!1,t.ApproximateRepulsion=!0,t.ApproximateRouting=!0,t.AttractiveForceConstant=1,t.AttractiveInterClusterForceConstant=1,t.AvoidOverlaps=!0,t.ClusterGravity=1,t.Decay=.9,t.DisplacementThreshold=5e-8,t.Friction=.8,t.GravityConstant=1,t.InitialStepSize=2,t.InterComponentForces=!1,t.Iterations=0,t.LogScaleEdgeForces=!1,t.MaxConstraintLevel=2,t.MaxIterations=20,t.MinConstraintLevel=0,t.MinorIterations=1,t.ProjectionIterations=5,t.RepulsiveForceConstant=2,t.RespectEdgePorts=!1,t.RouteEdges=!1,t.RungeKuttaIntegration=!0,t.NodeSeparation=20,t}}class $u{constructor(t){this.topNodes=t}get nodesBreadthFirst(){return this.nodesBreadthFirst_()}*nodesBreadthFirst_(){for(const t of this.topNodes)if(yield Pe.getGeom(t),t instanceof Gt)for(const e of t.nodesBreadthFirst)yield Pe.getGeom(e)}get Clusters(){return this.clusters()}*clusters(){for(const t of this.topNodes)t instanceof Gt&&(yield Xt.getGeom(t))}get subgraphsDepthFirst(){return this.subgraphsDepthFirst_()}*subgraphsDepthFirst_(){for(const t of this.topNodes)if(t instanceof Gt){const e=Xt.getGeom(t);yield*e.subgraphsDepthFirst,yield e}}get shallowEdges(){return this.edges_()}*edges_(){for(const t of this.topNodes){for(const e of t.outEdges)yield Ne.getGeom(e);for(const e of t.selfEdges)yield Ne.getGeom(e)}}get shallowNodes(){return this.shallowNodes_()}*shallowNodes_(){for(const t of this.topNodes)yield Pe.getGeom(t)}pumpTheBoxToTheGraphWithMargins(){const t={b:Z.mkEmpty()};return yr(this,t),this.boundingBox=t.b}get shallowNodeCount(){return this.topNodes.length}translate(t){this.boundingBox&&(this.boundingBox.center=this.boundingBox.center.add(t));for(const e of this.topNodes)Pe.getGeom(e).translate(t)}}class Ql{static LinearInterpolation(t,e,i,s,n){if(t<e)return s;if(t>i)return n;const o=(t-e)/(i-e);return s+o*(n-s)}static NegativeLinearInterpolation(t,e,i,s,n){if(t<e)return n;if(t>i)return s;const o=(t-e)/(i-e);return s+(1-o)*(n-s)}}class Xu extends zt{constructor(t,e){super(null),this.SingleComponent=!1,this.graph=t,this.settings=Ws.ctorClone(e),this.settings.ApplyForces=!0,this.settings.InterComponentForces=!0,this.settings.RungeKuttaIntegration=!1,this.settings.RespectEdgePorts=!1}run(){if(this.SingleComponent)this.componentCount=1,this.LayoutComponent(this.graph);else{const t=Array.from(this.graph.graph.getClusteredConnectedComponents()).map(e=>new $u(e));this.componentCount=t.length;for(const e of t)this.LayoutComponent(e);this.graph.boundingBox=zr.PackGraphs(t,this.settings.commonSettings)}}LayoutComponent(t){if(t.shallowNodeCount>1){if(this.settings.MaxIterations=Ql.NegativeLinearInterpolation(t.shallowNodeCount,50,500,5,10),this.settings.MinorIterations=Ql.NegativeLinearInterpolation(t.shallowNodeCount,50,500,3,20),this.settings.MinConstraintLevel==0){const i=new qr;i.removeOverlaps=!1,i.IterationsWithMajorization=0,new wa(t,null,()=>1,new qr).run()}const e=new $r(t,this.settings,this.settings.MinConstraintLevel);for(const i of this.GetConstraintLevels(t)){if(i>this.settings.MaxConstraintLevel)break;i>this.settings.MinConstraintLevel&&e.setCurrentConstraintLevel(i);do e.run();while(!this.settings.IsDone)}this.settings.AvoidOverlaps&&Xi.RemoveOverlaps(Array.from(this.graph.shallowNodes),this.settings.NodeSeparation)}t.pumpTheBoxToTheGraphWithMargins(),t.uniformMargins=this.settings.NodeSeparation,t.translate(t.boundingBox.leftBottom.mul(-1))}GetConstraintLevels(t){const e=new Set;return e.add(0),this.settings.AvoidOverlaps&&t.shallowNodeCount<2e3&&e.add(2),e}}function Yl(l){if(l instanceof SugiyamaLayoutSettings)return 0;if(l instanceof IPsepColaSetting)return 1;if(l instanceof MdsLayoutSettings)return 2;if(l instanceof FastIncrementalLayoutSettings)return 3;throw new Error("not implemented")}function Qu(l,t){(!l.layoutSettings||Yl(l.layoutSettings)!==Yl(t))&&(l.layoutSettings=t);for(const e of l.shallowNodes)e instanceof GeomGraph&&Qu(e,l.layoutSettings)}function Kl(l){l.layoutSettings||(l.layoutSettings=Jl(l))}function Yu(l){let t=l.parent;for(;t;){if(t.layoutSettings)return t.layoutSettings;t=t.parent}return null}function Jl(l){const t=Yu(l);if(t)return t;if(l.graph.shallowNodeCount>2e3||l.graph.deepEdgesCount>4e3)return new Ws;let i=!1;for(const s of l.deepEdges)if(s.sourceArrowhead!=null||s.targetArrowhead!=null){i=!0;break}return i?new Sn:new Ws}function Ku(l,t,e=()=>1){if(Kl(l),l.layoutSettings instanceof Sn)new ka(l,l.layoutSettings,t).run();else if(l.layoutSettings instanceof qr)new wa(l,t,e,l.layoutSettings).run();else if(l.layoutSettings instanceof Ws){const i=new Xu(l,l.layoutSettings);i.SingleComponent=!0,i.run()}else throw new Error("not implemented")}function Ju(l,t=null){Kl(l),th(l,t,Ku,_l,ha),nc(l)}function Zl(l){do{if(l.layoutSettings&&l.layoutSettings.commonSettings.edgeRoutingSettings)return l.layoutSettings.commonSettings.edgeRoutingSettings;const e=l.graph.parent;if(e)l=gt.getGeom(e);else break}while(!0);const t=new Vr;return t.EdgeRoutingMode=He.Spline,t}function _l(l,t,e){const i=Zl(l);i.EdgeRoutingMode===He.Rectilinear?tc(l,t,e):i.EdgeRoutingMode===He.Spline||i.EdgeRoutingMode===He.SplineBundling?Cc(l,t,e):i.EdgeRoutingMode===He.StraightLine?Ml(l,t,e):i.EdgeRoutingMode!==He.None&&new Zt(l,t).run(),eh(l,t)}function th(l,t,e,i,s,n=1,o=()=>1){if(l.graph.isEmpty())return;const a=l.shallowNodes.next();l.parent==null&&(Os(n),ec(l));const h=A();S(l);const u=Zu(l.graph),c=_u(l);if(I(),u.forEach(B=>{B[0].edge.remove(),B[1].add()}),c.forEach(B=>{for(const q of B.graph.shallowNodes)q.parent=l.graph}),h.forEach(B=>B.add()),l.graph.parent==null){const B=m(l);i(l,B,t),eh(l,B),l.pumpTheBoxToTheGraphWithMargins()}function m(B){const q=[];for(const rt of B.nodesBreadthFirst){for(const ct of rt.outEdges())ct.curve==null&&q.push(ct);for(const ct of rt.selfEdges())ct.curve==null&&q.push(ct)}return q}function S(B){for(const q of B.shallowNodes)q instanceof Xt&&th(q,t,e,i,s)}function A(){const B=new Set,q=l.graph;if(q.parent==null)return B;for(const rt of q.shallowNodes){for(const ct of rt.outEdges){const Q=q.liftNode(ct.target);(Q==null||Q===rt)&&B.add(ct)}for(const ct of rt.inEdges){const Q=q.liftNode(ct.source);(Q==null||Q===rt)&&B.add(ct)}}for(const rt of B)rt.remove();return B}function I(){if(c.length===1)e(l,t,o);else{for(const B of c)e(B,t,o),B.boundingBox=B.pumpTheBoxToTheGraphWithMargins();s(l,c)}}}function Zu(l){const t=new Array;for(const e of l.nodesBreadthFirst){const i=l.liftNode(e);if(i!=null)for(const s of e.outEdges.values()){const n=s.target,o=l.liftNode(n);if(o==null||i===e&&o===n||i===o)continue;s.remove();const a=new rs(i,o),h=new Ne(a);t.push([h,s])}}return t}function _u(l){var t;const e=l.graph,i=ra(e),s=[];let n=0;for(const o of i){const a=new Gt(e.id+n++);a.parent=e;const h=new Xt(a);h.layoutSettings=(t=l.layoutSettings)!==null&&t!==void 0?t:Jl(l);for(const u of o)u.parent=a,a.addNode(u);s.push(h)}return s}function tc(l,t,e,i=1,s=3,n=3){const o=me.constructorGNAN(l,t,i,s);o.edgeSeparatian=n,o.run()}function eh(l,t){if(t.length===0)return;Ft.constructorGA(l,t).run()}function ec(l){for(const t of l.deepEdges)t.label&&(t.label.isPositioned=!1)}function ic(l){if(GeomGraph.getGeom(l)==null)return!1;for(const t of l.shallowNodes){const e=GeomObject.getGeom(t);if(e==null||e.boundaryCurve==null||t instanceof Graph&&ic(t)===!1)return!1}for(const t of l.edges)if(GeomEdge.getGeom(t)==null)return!1;return!0}function sc(l){const t=GeomGraph.getGeom(l);if(t==null||t.boundingBox==null||t.boundingBox.isEmpty())return!1;for(const e of l.shallowNodes){const i=GeomObject.getGeom(e);if(i==null||i.boundaryCurve==null||e instanceof Graph&&sc(e)===!1)return!1}for(const e of l.deepEdges){const i=GeomEdge.getGeom(e);if(i==null||i.curve==null)return!1}return!0}function nc(l){const t=l.boundingBox.leftBottom;if(t.x<0||t.y<0){const e=new d(-t.x,-t.y);l.translate(e)}}class La{static constructorStatic(t,e){const i=new La;i.edges=t,i.nodeBoundaries=e,i.boundingBox=Z.mkEmpty();for(const s of i.nodeBoundaries)i.boundingBox=i.boundingBox.addRec(s.boundingBox);return i}AddGraph(t){this.edges=this.edges.concat(t.edges),this.nodeBoundaries=Ss(this.nodeBoundaries,t.nodeBoundaries),this.boundingBox.addRec(t.boundingBox)}AddNodeBoundary(t){this.nodeBoundaries.add(t),this.boundingBox.addRec(t.boundingBox)}}var Ba;(function(l){l[l.Success=0]="Success",l[l.Overlaps=1]="Overlaps",l[l.EdgeSeparationIsTooLarge=2]="EdgeSeparationIsTooLarge"})(Ba||(Ba={}));class qo{constructor(t,e,i){this.currentTriangle=t,this.start=e,this.end=i}get CurrentPiercedEdge(){return this.currentPiercedEdge}get CurrentTriangle(){return this.currentTriangle}FindFirstPiercedEdge(){const t=this.GetHyperplaneSign(this.currentTriangle.Sites.item0),e=this.GetHyperplaneSign(this.currentTriangle.Sites.item1);if(t!==e&&d.getTriangleOrientation(this.end,this.currentTriangle.Sites.item0.point,this.currentTriangle.Sites.item1.point)==k.Clockwise)return this.positiveSign=t,this.negativeSign=e,this.currentTriangle.Edges.item0;const i=this.GetHyperplaneSign(this.currentTriangle.Sites.item2);return e!==i&&d.getTriangleOrientation(this.end,this.currentTriangle.Sites.item1.point,this.currentTriangle.Sites.item2.point)==k.Clockwise?(this.positiveSign=e,this.negativeSign=i,this.currentTriangle.Edges.item1):(this.positiveSign=i,this.negativeSign=t,this.currentTriangle.Edges.item2)}FindNextPierced(){if(this.currentTriangle=this.currentPiercedEdge.GetOtherTriangle_T(this.currentTriangle),this.currentTriangle==null){this.currentPiercedEdge=null;return}const t=this.currentTriangle.Edges.index(this.currentPiercedEdge);let e;const i=this.currentTriangle.Sites.getItem(t+2),s=this.GetHyperplaneSign(i);this.negativeSign===0?s===-1||s===0?(this.negativeSign=s,e=t+1):e=t+2:this.positiveSign===0?s===1||s===0?(this.positiveSign=s,e=t+2):e=t+1:s!==this.positiveSign?(this.negativeSign=s,e=t+1):(this.positiveSign=s,e=t+2),this.currentPiercedEdge=d.signedDoubledTriangleArea(this.end,this.currentTriangle.Sites.getItem(e).point,this.currentTriangle.Sites.getItem(e+1).point)<-C.distanceEpsilon?this.currentTriangle.Edges.getItem(e):null}GetHyperplaneSign(t){const e=d.signedDoubledTriangleArea(this.start,t.point,this.end);return e>C.distanceEpsilon?1:e<-C.distanceEpsilon?-1:0}MoveNext(){return this.currentPiercedEdge==null?this.currentPiercedEdge=this.FindFirstPiercedEdge():this.FindNextPierced(),this.currentPiercedEdge!=null}}class Fa{constructor(t,e){this.ComputeForcesForBundles=!1,this.metroGraphData=t,this.bundlingSettings=e}EdgeIsLegal_(t,e,i,s){if(ue.PointIsInsideOfTriangle(e,i))return!0;const n=new qo(i,t,e);for(;n.MoveNext();){const o=n.CurrentPiercedEdge;if(o.constrained){const a=o.lowerSite.Owner;if(!s.has(a))return!1}}return!0}BundleAvoidsObstacles(t,e,i,s,n,o){o.closestDist=new Array;const a=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(t,e),h=this.FindCloseObstaclesForBundle(e.cdtTriangle,s,i,a,n);if(h==null)return!1;for(const u of h){const c=u[1];o.closestDist.push(c)}return!0}FindCloseObstaclesForBundle(t,e,i,s,n){const o=new Map,a=[];if(!this.ThreadLineSegmentThroughTriangles(t,e,i,s,a))return null;if(!this.ComputeForcesForBundles&&!this.bundlingSettings.HighestQuality)return o;const h=new Ho;for(const u of a)for(const c of u.Sites){if(h.has(c))continue;h.add(c);const m=c.Owner;if(s.has(m))continue;const S=Fa.FindPolylinePoint(m,c.point),A=D.minDistBetweenLineSegments(S.point,S.nextOnPolyline.point,e,i),I=A.dist,B=A.parab,q=A.parcd,rt=D.minDistBetweenLineSegments(S.point,S.prevOnPolyline.point,e,i),ct=rt.dist,Q=rt.parab,pt=rt.parcd;let Lt,Bt,_t;if(I<ct){if(_t=I,_t>n)continue;Lt=S.point.add(S.nextOnPolyline.point.sub(S.point).mul(B)),Bt=e.add(i.sub(e).mul(q))}else{if(_t=ct,_t>n)continue;Lt=S.point.add(S.prevOnPolyline.point.sub(S.point).mul(Q)),Bt=e.add(i.sub(e).mul(pt))}o.get(m)||o.set(m,[Lt,Bt])}return o}ThreadLineSegmentThroughTriangles(t,e,i,s,n){if(ue.PointIsInsideOfTriangle(i,t))return n.push(t),!0;const o=new qo(t,e,i);for(n.push(t);o.MoveNext();){n.push(o.CurrentTriangle);const a=o.CurrentPiercedEdge;if(a.constrained){const h=a.lowerSite.Owner;if(!s.has(h))return!1}}return o.CurrentTriangle!=null&&n.push(o.CurrentTriangle),!0}static PointLocationInsideTriangle(t,e){let i=!1;for(let s=0;s<3;s++){const n=d.signedDoubledTriangleArea(t,e.Sites.getItem(s).point,e.Sites.getItem(s+1).point);if(n<C.distanceEpsilon*-1)return ft.Outside;n<C.distanceEpsilon&&(i=!0)}return i?ft.Boundary:ft.Inside}static FindPolylinePoint(t,e){for(const i of t.polylinePoints())if(i.point.equal(e))return i;throw new Error("polyline point "+e+" not found")}EdgeIsLegal(t,e,i,s){const n=[],o=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(t,e);return this.ThreadLineSegmentThroughTriangles(t.cdtTriangle,i,s,o,n)}EdgeIsLegalSSPPS(t,e,i){const s=t.Position,n=t.cdtTriangle,o=e.Position;if(ue.PointIsInsideOfTriangle(o,n))return!0;const a=new qo(n,s,o);for(;a.MoveNext();){const h=a.CurrentPiercedEdge;if(h.constrained){const u=h.lowerSite.Owner;if(!i.has(u))return!1}}return!0}}class Qi{constructor(t,e,i,s){this.metroGraphData=t,this.obstaclesToIgnoreLambda=s,this.bundlingSettings=e,this.obstacleTree=i}ObstaclesToIgnoreForBundle(t,e){return t!=null&&e!=null?Ss(this.obstaclesToIgnoreLambda(t),this.obstaclesToIgnoreLambda(e)):t==null&&e==null?new Set:t!=null?this.obstaclesToIgnoreLambda(t):this.obstaclesToIgnoreLambda(e)}HubAvoidsObstaclesSPNBA(t,e,i,s){const n={minimalDistance:i};return Qi.IntersectCircleWithTree(this.obstacleTree,e,i,this.obstaclesToIgnoreLambda(t),s.touchedObstacles,n)}HubAvoidsObstaclesPNS__(t,e,i){const s={touchedObstacles:Array()},n={minimalDistance:0};return this.HubAvoidsObstaclesPNSTT(t,e,i,s,n)}GetMinimalDistanceToObstacles(t,e,i){const s=new Array,n={minimalDistance:i};return Qi.IntersectCircleWithTree(this.obstacleTree,e,i,this.obstaclesToIgnoreLambda(t),s,n)?n.minimalDistance:0}HubAvoidsObstaclesPNSTT(t,e,i,s,n){return s.touchedObstacles=new Array,n.minimalDistance=e,Qi.IntersectCircleWithTree(this.obstacleTree,t,e,i,s.touchedObstacles,n)}static IntersectCircleWithTree(t,e,i,s,n,o){if(!t.irect.contains_point_radius(e,i))return!0;if(t.UserData==null){let a=Qi.IntersectCircleWithTree(t.Left,e,i,s,n,o);if(!a||(a=Qi.IntersectCircleWithTree(t.Right,e,i,s,n,o),!a))return!1}else{const a=t.UserData;if(s.has(a))return!0;if(w.PointRelativeToCurveLocation(e,a)!==ft.Outside)return Qi.containingPoly=a,!1;const u=a.value(a.closestParameter(e)),c=u.sub(e).length;c<=i&&n.push([a,u]),o.minimalDistance=Math.min(c,o.minimalDistance)}return!0}static Create4gon(t,e,i,s){let n=e.sub(t).normalize();return n=new d(n.y,n.x*-1),at.mkFromPoints([t.add(n.mul(i/2)),t.sub(n.mul(i/2)),e.sub(n.mul(s/2)),e.add(n.mul(s/2))])}}class rc{constructor(t,e,i,s){this.Width=e,this.Polyline=t,this.sourceAndTargetLoosePolylines=i,this.Index=s}UpdateLengths(){let t=0;for(let e=this.Polyline.startPoint;e.next!=null;e=e.next)t+=e.next.point.sub(e.point).length;this.Length=t,this.IdealLength=this.Polyline.end.sub(this.Polyline.start).length}}class oc{constructor(t,e,i){this.metroline=t,this.station=e,this.polyPoint=i}get Metroline(){return this.metroline}get PolyPoint(){return this.polyPoint}}class ac{constructor(t,e,i){this.Radius=0,this.BundleBases=new Map,this.MetroNodeInfos=new Array,this._cachedIdealRadius=0,this.SerialNumber=t,this.IsReal=e,this.Position=i}debStop(){return this.SerialNumber===28&&this.Position.sub(new d(841.2662778763244,303.3817005853006)).length<.001}get Position(){return this._Position}set Position(t){this._Position=t}getELP(){return this.EnterableLoosePolylines}setELP(t){this.EnterableLoosePolylines=t}addEL(t){this.EnterableLoosePolylines.add(t)}get cachedIdealRadius(){return this._cachedIdealRadius}set cachedIdealRadius(t){this._cachedIdealRadius=t}AddEnterableLoosePolyline(t){this.EnterableLoosePolylines==null&&(this.EnterableLoosePolylines=new Set),this.EnterableLoosePolylines.add(t)}AddEnterableTightPolyline(t){this.EnterableTightPolylines==null&&(this.EnterableTightPolylines=new Set),this.EnterableTightPolylines.add(t)}}class lc{constructor(){this.Width=0,this.Metrolines=new Array,this.cachedBundleCost=0}get Count(){return this.Metrolines.length}}class qe{constructor(t,e){this.metroGraphData=t,this.bundlingSettings=e}CreateNodeRadii(){for(const t of this.metroGraphData.VirtualStations())t.Radius=0,t.cachedIdealRadius=qe.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,t);this.GrowHubs(!1),this.GrowHubs(!0);for(const t of this.metroGraphData.VirtualStations())t.Radius=Math.max(t.Radius,this.bundlingSettings.MinHubRadius)}GrowHubs(t){const e=new es(W);for(const s of this.metroGraphData.VirtualStations())e.Enqueue(s,-this.CalculatePotential(s,t));let i=!1;for(;!e.IsEmpty();){const s={priority:0},n=e.DequeueAndGetPriority(s);if(s.priority>=0)break;this.TryGrowHub(n,t)&&(e.Enqueue(n,-this.CalculatePotential(n,t)),i=!0)}return i}TryGrowHub(t,e){const i=this.CalculateAllowedHubRadius(t);if(t.Radius>=i)return!1;const s=e?qe.CalculateIdealHubRadiusWithAdjacentEdges(this.bundlingSettings,t):t.cachedIdealRadius;if(t.Radius>=s)return!1;let o=.05*(s-t.Radius);o<1&&(o=1);const a=Math.min(t.Radius+o,i);return a<=t.Radius?!1:(t.Radius=a,!0)}CalculatePotential(t,e){const i=e?qe.CalculateIdealHubRadiusWithAdjacentEdges(this.bundlingSettings,t):t.cachedIdealRadius;return i<=t.Radius?0:(i-t.Radius)/i}CalculateAllowedHubRadius(t){let e=this.bundlingSettings.MaxHubRadius;for(const s of t.Neighbors){const n=s.Position.sub(t.Position).length;e=Math.min(e,n/1.05-s.Radius)}const i=this.metroGraphData.tightIntersections.GetMinimalDistanceToObstacles(t,t.Position,e);return i<e&&(e=i-.001),Math.max(e,.1)}static CalculateIdealHubRadius(t,e,i){let s=1;for(const n of i.Neighbors){const a=t.GetWidthSSN(n,i,e.EdgeSeparation)/2+e.EdgeSeparation;s=Math.max(s,a)}return s=Math.min(s,2*e.MaxHubRadius),s}static CalculateIdealHubRadiusWithNeighborsMBS(t,e,i){return qe.CalculateIdealHubRadiusWithNeighborsMBNP(t,e,i,i.Position)}static CalculateIdealHubRadiusWithNeighborsMBNP(t,e,i,s){let n=qe.CalculateIdealHubRadius(t,e,i);if(i.Neighbors.length>1){const o=i.Neighbors;for(let a=0;a<o.length;a++){const h=o[a],u=o[(a+1)%o.length];n=Math.max(n,qe.GetMinRadiusForTwoAdjacentBundles(n,i,s,h,u,t,e))}}return n=Math.min(n,2*e.MaxHubRadius),n}static CalculateIdealHubRadiusWithAdjacentEdges(t,e){let i=t.MaxHubRadius;for(const s of e.Neighbors)i=Math.min(i,e.Position.sub(s.Position).length/2);return i}static GetMinRadiusForTwoAdjacentBundles(t,e,i,s,n,o,a){const h=o.GetWidthSSN(e,s,a.EdgeSeparation),u=o.GetWidthSSN(e,n,a.EdgeSeparation);return qe.GetMinRadiusForTwoAdjacentBundlesNPPPNNB(t,i,s.Position,n.Position,h,u,a)}static GetMinRadiusForTwoAdjacentBundlesNPPPNNB(t,e,i,s,n,o,a){if(n<C.distanceEpsilon||o<C.distanceEpsilon)return t;let h=d.anglePCP(i,e,s);if(h=Math.min(h,Math.PI*2-h),h<C.distanceEpsilon)return 2*a.MaxHubRadius;if(h>=Math.PI/2)return t*1.05;const u=Math.sin(h),c=Math.cos(h),m=n/(4*u),S=o/(4*u);let A=2*Math.sqrt(m*m+(S*S+2*(m*(S*c))));return A=Math.min(A,2*a.MaxHubRadius),A=Math.max(A,t),A}}class Uo{constructor(t,e,i,s){this.metroGraphData=t,this.bundlingSettings=e,this.costCalculator=i,this.cdt=s}InitializeCostCache(){for(const t of this.metroGraphData.VirtualStations())t.cachedIdealRadius=qe.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,t),t.cachedRadiusCost=this.costCalculator.RadiusCost(t,t.Position),t.cachedBundleCost=0;for(const t of this.metroGraphData.VirtualEdges()){const e=t[0],i=t[1],s=this.metroGraphData.GetIjInfo(e,i);s.cachedBundleCost=this.costCalculator.BundleCost(e,i,e.Position),e.cachedBundleCost+=s.cachedBundleCost,i.cachedBundleCost+=s.cachedBundleCost}}UpdateCostCache(t){const e=this.cdt.getRectangleNodeOnTriangles();t.cdtTriangle=e.FirstHitNodeWithPredicate(t.Position,Uo.testPointInside).UserData,t.cachedIdealRadius=qe.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,t),t.cachedRadiusCost=this.costCalculator.RadiusCost(t,t.Position),t.cachedBundleCost=0;for(const i of t.Neighbors){i.IsReal||(i.cachedIdealRadius=qe.CalculateIdealHubRadiusWithNeighborsMBS(this.metroGraphData,this.bundlingSettings,i),i.cachedRadiusCost=this.costCalculator.RadiusCost(i,i.Position));const s=this.metroGraphData.GetIjInfo(t,i);i.cachedBundleCost-=s.cachedBundleCost,s.cachedBundleCost=this.costCalculator.BundleCost(t,i,t.Position),t.cachedBundleCost+=s.cachedBundleCost,i.cachedBundleCost+=s.cachedBundleCost}}static testPointInside(t,e){return ue.PointIsInsideOfTriangle(t,e)?$t.Stop:$t.Continue}}class ih{constructor(){this.mainMap=new Map}get isEmpty(){return this.mainMap.size===0||this.everyMapIsEmpty()}everyMapIsEmpty(){for(const t of this.mainMap.values())if(t.size)return!1;return!0}get(t,e){const i=this.mainMap.get(t);if(i)return i.get(e)}has(t,e){const i=this.mainMap.get(t);return i?i.has(e):!1}set(t,e,i){let s=this.mainMap.get(t);s||(s=new Map,this.mainMap.set(t,s)),s.set(e,i)}*[Symbol.iterator](){for(const[t,e]of this.mainMap)for(const[i,s]of e)yield[t,i,s]}*keys(){for(const[t,e]of this.mainMap)for(const[i]of e)yield[t,i]}}class hc{constructor(t,e,i,s,n,o,a,h){this.cachedEnterableLooseForEnd=new si,this.bundlingSettings=s,this.regularEdges=t,n!=null?this.cdt=n:this.cdt=Nl(e),this.EdgeLooseEnterable=o,this.EdgeTightEnterable=a,this.LoosePolylineOfPort=h,this.looseIntersections=new Qi(this,s,e,u=>u.getELP()),this.tightIntersections=new Qi(this,s,i,u=>u.EnterableTightPolylines),this.cdtIntersections=new Fa(this,s),this.Initialize(!1)}get Ink(){return this.ink}get Edges(){return this.regularEdges}VirtualStations(){return Array.from(this.Stations).filter(t=>!t.IsReal)}get Metrolines(){return this.metrolines}get LooseTree(){return this.looseIntersections.obstacleTree}get TightTree(){return this.tightIntersections.obstacleTree}*VirtualEdges(){for(const t of this.edgeInfoDictionary.keys())yield t}RealEdgeCount(t,e){const i=t.SerialNumber<e.SerialNumber?[t,e]:[e,t],s=this.edgeInfoDictionary.get(i[0],i[1]);return s?s.Count:0}MetroNodeInfosOfNode(t){return t.MetroNodeInfos}GetIjInfo(t,e){const i=t.SerialNumber<e.SerialNumber?[t,e]:[e,t];return this.edgeInfoDictionary.get(i[0],i[1])}MoveNode(t,e){const i=t.Position;this.PointToStations.deleteP(i),this.PointToStations.set(e,t),t.Position=e;for(const s of this.MetroNodeInfosOfNode(t))s.PolyPoint.point=e;for(const s of this.MetroNodeInfosOfNode(t)){const n=s.Metroline,o=s.PolyPoint.prev.point,a=s.PolyPoint.next.point;n.Length+=a.sub(e).length+o.sub(e).length-a.sub(i).length-o.sub(i).length}for(const s of t.Neighbors)this.ink+=e.sub(s.Position).length-i.sub(s.Position).length;this.SortNeighbors(t);for(const s of t.Neighbors)this.SortNeighbors(s)}GetWidthSSN(t,e,i){const s=t.SerialNumber<e.SerialNumber?[t,e]:[e,t],n=this.edgeInfoDictionary.get(s[0],s[1]);return n?n.Width+(n.Count-1)*i:0}GetWidthAN(t,e){let i=0;for(const n of t)i+=n.Width;const s=t.length;return i+=s>0?(s-1)*e:0,i}Initialize(t){this.SimplifyRegularEdges(),this.InitializeStationData(),this.InitializeEdgeData(),this.InitializeVirtualGraph(),this.InitializeEdgeNodeInfo(t),this.InitializeCdtInfo()}SimplifyRegularEdges(){for(const t of this.regularEdges)this.SimplifyRegularEdge(t)}SimplifyRegularEdge(t){const e=t.curve,i=new Yt.B,s=new ie;for(let n=e.endPoint;n!=null;n=n.prev){const o=n.point;if(s.has(n.point)){let a=n.next;do{const h=i.top;if(!h.equal(o))s.delete(h),i.pop(),a=a.next;else break}while(!0);a.prev=n.prev,a.prev.next=a}else i.push(o),s.add(o)}}InitializeStationData(){this.Stations=[],this.PointToStations=new si;for(const t of this.regularEdges){const e=t.curve;this.ProcessPolylinePoints(e)}}ProcessPolylinePoints(t){let e=t.startPoint;for(this.RegisterStation(e,!0),e=e.next;e!==t.endPoint;e=e.next)this.RegisterStation(e,!1);this.RegisterStation(e,!0)}RegisterStation(t,e){if(!this.PointToStations.has(t.point)){const i=new ac(this.Stations.length,e,t.point);this.PointToStations.set(t.point,i),this.Stations.push(i)}}InitializeEdgeData(){this.metrolines=new Array;for(let t=0;t<this.regularEdges.length;t++){const e=this.regularEdges[t];this.InitEdgeData(e,t)}}InitEdgeData(t,e){const i=new rc(t.curve,this.bundlingSettings.ActualEdgeWidth(t),this.EdgeSourceAndTargetFunc(t),e);this.metrolines.push(i),this.PointToStations.get(i.Polyline.start).BoundaryCurve=t.sourcePort.Curve,this.PointToStations.get(i.Polyline.end).BoundaryCurve=t.targetPort.Curve}EdgeSourceAndTargetFunc(t){return()=>[this.LoosePolylineOfPort(t.sourcePort),this.LoosePolylineOfPort(t.targetPort)]}InitializeVirtualGraph(){const t=new Map;for(const e of this.metrolines){let i=this.PointToStations.get(e.Polyline.start),s;for(let n=e.Polyline.startPoint;n.next!=null;n=n.next,i=s)s=this.PointToStations.get(n.next.point),Nn(t,i,s),Nn(t,s,i)}for(const e of this.Stations)e.Neighbors=Array.from(t.get(e))}GetUnorderedIjInfo(t,e){return t.SerialNumber<e.SerialNumber?this.GetCreateOrderedIjInfo(t,e):this.GetCreateOrderedIjInfo(e,t)}static closedeb(t,e){return t.Position.sub(new d(360.561,428.416)).length<.1&&e.Position.sub(new d(414.281,440.732)).length<.1}GetCreateOrderedIjInfo(t,e){let i=this.edgeInfoDictionary.get(t,e);return i||(i=new lc,this.edgeInfoDictionary.set(t,e,i),i)}InitializeEdgeNodeInfo(t){this.edgeInfoDictionary=new ih,this.InitAllMetroNodeInfos(t),this.SortAllNeighbors(),this.InitEdgeIjInfos(),this.ink=0;for(const e of this.VirtualEdges())this.ink+=e[0].Position.sub(e[1].Position).length}InitAllMetroNodeInfos(t){for(let e=0;e<this.metrolines.length;e++){const i=this.metrolines[e];this.InitMetroNodeInfos(i),this.InitNodeEnterableLoosePolylines(i,this.regularEdges[e]),t&&this.InitNodeEnterableTightPolylines(i,this.regularEdges[e]),i.UpdateLengths()}}InitMetroNodeInfos(t){for(let e=t.Polyline.startPoint;e!=null;e=e.next){const i=this.PointToStations.get(e.point);i.MetroNodeInfos.push(new oc(t,i,e))}}InitNodeEnterableLoosePolylines(t,e){const i=this.EdgeLooseEnterable!=null?this.EdgeLooseEnterable.get(e):new Set;for(let s=t.Polyline.startPoint.next;s!=null&&s.next!=null;s=s.next){const n=this.PointToStations.get(s.point);n.getELP()!=null?n.setELP(Ji(n.getELP(),i)):n.setELP(new Set(i))}this.AddLooseEnterableForMetrolineStartEndPoints(t)}AddLooseEnterableForMetrolineStartEndPoints(t){this.AddLooseEnterableForEnd(t.Polyline.start),this.AddLooseEnterableForEnd(t.Polyline.end)}AddTightEnterableForMetrolineStartEndPoints(t){this.AddTightEnterableForEnd(t.Polyline.start),this.AddTightEnterableForEnd(t.Polyline.end)}AddLooseEnterableForEnd(t){const e=this.PointToStations.get(t);if(this.cachedEnterableLooseForEnd.has(t))e.setELP(this.cachedEnterableLooseForEnd.get(t));else{for(const i of this.LooseTree.AllHitItems_(t))w.PointRelativeToCurveLocation(t,i)===ft.Inside&&e.AddEnterableLoosePolyline(i);this.cachedEnterableLooseForEnd.set(t,e.getELP())}}AddTightEnterableForEnd(t){const e=this.PointToStations.get(t);for(const i of this.TightTree.AllHitItems_(t))w.PointRelativeToCurveLocation(t,i)===ft.Inside&&e.AddEnterableTightPolyline(i)}InitNodeEnterableTightPolylines(t,e){const i=this.EdgeTightEnterable!=null?this.EdgeTightEnterable.get(e):new Set;for(let s=t.Polyline.startPoint.next;s!=null&&s.next!=null;s=s.next){const n=this.PointToStations.get(s.point),o=n.EnterableTightPolylines;o!=null?n.EnterableTightPolylines=Ji(o,i):n.EnterableTightPolylines=new Set(i)}this.AddTightEnterableForMetrolineStartEndPoints(t)}SortAllNeighbors(){for(const t of this.Stations)this.SortNeighbors(t)}SortNeighbors(t){if(t.Neighbors.length<=2)return;const e=t.Neighbors[0].Position,i=t.Position;t.Neighbors.sort((s,n)=>bn(e.sub(i),s.Position.sub(i),n.Position.sub(i)))}InitEdgeIjInfos(){for(const t of this.metrolines){const e=t.Polyline;let i=this.PointToStations.get(e.start),s;for(let n=t.Polyline.startPoint;n.next!=null;n=n.next,i=s){s=this.PointToStations.get(n.next.point);const o=this.GetUnorderedIjInfo(i,s);o.Width+=t.Width,o.Metrolines.push(t)}}}InitializeCdtInfo(){const t=this.cdt.getRectangleNodeOnTriangles();for(const e of this.Stations)e.cdtTriangle=t.FirstHitNodeWithPredicate(e.Position,Uo.testPointInside).UserData}PointIsAcceptableForEdge(t,e){if(this.LoosePolylineOfPort==null)return!0;const i=t.sourceAndTargetLoosePolylines();return w.PointRelativeToCurveLocation(e,i[0])===ft.Outside&&w.PointRelativeToCurveLocation(e,i[1])===ft.Outside}}function bn(l,t,e){const i=d.crossProduct(l,e),s=l.dot(e),n=d.crossProduct(l,t),o=l.dot(t);return N(n,0)&&jo(o,0)?N(i,0)&&jo(s,0)?0:1:N(i,0)&&jo(s,0)?-1:N(n,0)||N(i,0)||n*i>0?_(d.crossProduct(e,t),0):-_(Math.sign(n),0)}function jo(l,t){return _(l,t)>=0}class de{constructor(t,e){this.metroGraphData=t,this.bundlingSettings=e}static InkError(t,e,i){return(t-e)*i.InkImportance}static PathLengthsError(t,e,i,s){return(t-e)*(s.PathLengthImportance/i)}static RError(t,e,i){return t<=e?0:i.HubRepulsionImportance*((1-e/t)*(t-e))}static BundleError(t,e,i){return t<=e?0:i.BundleRepulsionImportance*((1-e/t)*(t-e))}static Cost(t,e){let i=e.InkImportance*t.Ink;for(const s of t.Metrolines)i+=e.PathLengthImportance*s.Length/s.IdealLength;return i+=this.CostOfForces(t),i}static CostOfForces(t){let e=0;for(const i of t.VirtualStations())e=e+i.cachedRadiusCost;for(const i of t.VirtualEdges()){const s=i[0],n=i[1];e+=t.GetIjInfo(s,n).cachedBundleCost}return e}InkGain(t,e){const i=this.metroGraphData.Ink;let s=this.metroGraphData.Ink;for(const n of t.Neighbors){const o=n.Position;s-=o.sub(t.Position).length,s+=o.sub(e).length}return de.InkError(i,s,this.bundlingSettings)}PathLengthsGain(t,e){let i=0;for(const s of this.metroGraphData.MetroNodeInfosOfNode(t)){const n=s.Metroline.Length,o=s.PolyPoint.prev.point,a=s.PolyPoint.next.point,h=s.Metroline.Length+a.sub(e).length+o.sub(e).length-a.sub(t.Position).length-o.sub(t.Position).length;i+=de.PathLengthsError(n,h,s.Metroline.IdealLength,this.bundlingSettings)}return i}RadiusGain(t,e){let i=0;return i=i+t.cachedRadiusCost,i=i-this.RadiusCost(t,e),i}RadiusCost(t,e){let i;d.closeDistEps(t.Position,e)?i=t.cachedIdealRadius:i=qe.CalculateIdealHubRadiusWithNeighborsMBNP(this.metroGraphData,this.bundlingSettings,t,e);const s={touchedObstacles:[]};if(!this.metroGraphData.looseIntersections.HubAvoidsObstaclesSPNBA(t,e,i,s))return de.Inf;let n=0;for(const o of s.touchedObstacles){const a=o[1].sub(e).length;n+=de.RError(i,a,this.bundlingSettings)}return n}BundleGain(t,e){let i=t.cachedBundleCost;for(const s of t.Neighbors){const n=this.BundleCost(t,s,e);if(jo(n,de.Inf))return-de.Inf;i-=n}return i}BundleCost(t,e,i){const s=this.metroGraphData.GetWidthSSN(t,e,this.bundlingSettings.EdgeSeparation),n={closestDist:[]};if(!this.metroGraphData.cdtIntersections.BundleAvoidsObstacles(t,e,i,e.Position,s,n))return de.Inf;let o=0;for(const a of n.closestDist){const h=a[0].sub(a[1]).length;o+=de.BundleError(s/2,h,this.bundlingSettings)}return o}}de.Inf=1e9;class uc{constructor(t){this.polylineToEdgeGeom=new Map,this.pathsThroughPoints=new si,this.interestingPoints=new ie,this.metroGraphData=t}get Polylines(){return Array.from(this.polylineToEdgeGeom.keys())}Run(){this.Init(),this.SwitchFlips()}Init(){for(const t of this.metroGraphData.Edges)this.polylineToEdgeGeom.set(t.curve,t);for(const t of this.Polylines)this.RegisterPolylinePointInPathsThrough(t.polylinePoints())}RegisterPolylinePointInPathsThrough(t){for(const e of t)this.RegisterPolylinePointInPathsThroughP(e)}RegisterPolylinePointInPathsThroughP(t){cc(this.pathsThroughPoints,t.point,t)}UnregisterPolylinePointsInPathsThrough(t){for(const e of t)this.UnregisterPolylinePointInPathsThrough(e)}UnregisterPolylinePointInPathsThrough(t){dc(this.pathsThroughPoints,t.point,t)}SwitchFlips(){const t=new Set(this.Polylines),e=new hi.o;for(const i of this.Polylines)e.enqueue(i);for(;e.length>0;){const i=e.dequeue();t.delete(i);const s=this.ProcessPolyline(i);s!=null&&(t.has(i)||(t.add(i),e.enqueue(i)),t.has(s)||(t.add(s),e.enqueue(s)))}}ProcessPolyline(t){const e=new Map;for(let i=t.startPoint.next;i!=null;i=i.next){this.FillDepartedPolylinePoints(i,e);for(const s of this.pathsThroughPoints.get(i.point)){const n=e.get(s.polyline);if(n){if(this.ProcessFlip(i,n))return s.polyline;e.delete(s.polyline)}}}return null}FillDepartedPolylinePoints(t,e){const i=t.prev.point;for(const s of this.pathsThroughPoints.get(i))this.IsNeighborOnTheSamePolyline(s,t)||e.has(s.polyline)||e.set(s.polyline,s)}ProcessFlip(t,e){const i=t.polyline,s=e.polyline,n=t.point,o=e.point,a=this.polylineToEdgeGeom.get(i),h=this.polylineToEdgeGeom.get(s);if(a.lineWidth!==h.lineWidth||this.metroGraphData.EdgeLooseEnterable==null||!Dn(this.metroGraphData.EdgeLooseEnterable.get(a),this.metroGraphData.EdgeLooseEnterable.get(h)))return!1;let u=this.FindPointsOnPolyline(i,n,o);const c=u[0],m=u[1],S=u[2];u=this.FindPointsOnPolyline(s,n,o);const A=u[0],I=u[1],B=u[2],q=this.FindRelationOnFirstPoint(c,A,S,B),rt=this.FindRelationOnLastPoint(m,I,S,B);return q!==2&&rt!==2||q===1||rt===1?!1:(this.UnregisterPolylinePointsInPathsThrough(i.polylinePoints()),this.UnregisterPolylinePointsInPathsThrough(s.polylinePoints()),this.Swap(c,A,m,I,S,B),this.RegisterPolylinePointInPathsThrough(i.polylinePoints()),this.RegisterPolylinePointInPathsThrough(s.polylinePoints()),this.RegisterInterestingPoint(c.point),this.RegisterInterestingPoint(m.point),this.numberOfReducedCrossings++,!0)}FindPointsOnPolyline(t,e,i){let s,n;for(let o=t.startPoint;o!=null;o=o.next)if(s==null)if(o.point.equal(e)){if(n!=null)return[o,n,!1];s=o}else n==null&&o.point.equal(i)&&(n=o);else if(o.point.equal(i))return[s,o,!0]}PolylinePointsAreInForwardOrder(t,e){for(let i=t;i!=null;i=i.next)if(i===e)return!0;return!1}Next(t,e){return e?t.next:t.prev}Prev(t,e){return e?t.prev:t.next}FindRelationOnFirstPoint(t,e,i,s){const n=t,o=e;for(;;){const a=this.Prev(t,i),h=this.Prev(e,s);if(a==null||h==null)return 0;if(!a.point.equal(h.point))break;t=a,e=h}return this.PolylinesIntersect(n,o,t,e,i,s)}FindRelationOnLastPoint(t,e,i,s){const n=t,o=e;for(;;){const a=this.Next(t,i),h=this.Next(e,s);if(a==null||h==null)return 0;if(!a.point.equal(h.point))break;t=a,e=h}for(;this.Next(t,i).point.equal(this.Prev(e,s).point);)t=this.Next(t,i),e=this.Prev(e,s);return this.PolylinesIntersect(t,e,n,o,i,s)}PolylinesIntersect(t,e,i,s,n,o){const a=this.Prev(t,n),h=this.Next(t,n),u=this.Next(i,n),c=this.Prev(i,n),m=this.Next(e,o),S=this.Prev(s,o);if(t.point.equal(i.point)){const A=t.point,I=bn(c.point.sub(A),S.point.sub(A),h.point.sub(A)),B=bn(c.point.sub(A),m.point.sub(A),h.point.sub(A));return I===B?1:2}else{const A=bn(a.point.sub(t.point),h.point.sub(t.point),m.point.sub(t.point)),I=bn(u.point.sub(i.point),S.point.sub(i.point),c.point.sub(i.point));return A===I?1:2}}Swap(t,e,i,s,n,o){const a=this.GetRangeOnPolyline(this.Next(t,n),i,n),h=this.GetRangeOnPolyline(this.Next(e,o),s,o);this.ChangePolylineSegment(t,i,n,h),this.ChangePolylineSegment(e,s,o,a),Xr.RemoveSelfCyclesFromPolyline(t.polyline),Xr.RemoveSelfCyclesFromPolyline(e.polyline)}ChangePolylineSegment(t,e,i,s){let n=t;for(const o of s){const a=qt.mkFromPoint(o.point);a.polyline=n.polyline,i?(a.prev=n,n.next=a):(a.next=n,n.prev=a),n=a}i?(n.next=e,e.prev=n):(n.prev=e,e.next=n)}GetRangeOnPolyline(t,e,i){const s=new Array;for(let n=t;n!==e;n=this.Next(n,i))s.push(n);return s}IsNeighborOnTheSamePolyline(t,e){return t.prev!=null&&t.prev.point.equal(e.point)||t.next!=null&&t.next.point.equal(e.point)}RegisterInterestingPoint(t){this.interestingPoints.has(t)||this.interestingPoints.add(t)}GetChangedHubs(){return this.interestingPoints}NumberOfReducedCrossings(){return this.numberOfReducedCrossings}PolylineIsOK(t){const e=new ie;for(let i=t.startPoint;i!=null;i=i.next){if(i===t.startPoint){if(i.prev!=null)return!1}else if(i.prev.next!==i)return!1;if(i===t.endPoint){if(i.next!=null)return!1}else if(i.next.prev!==i)return!1;if(e.has(i.point))return!1;e.add(i.point)}return!(t.startPoint.prev!=null||t.endPoint.next!=null)}}function cc(l,t,e){let i=l.get(t);i||(i=new Set,l.set(t,i)),i.add(e)}function dc(l,t,e){const i=l.get(t);i&&(i.delete(e),i.size===0&&l.deleteP(t))}class Xr{constructor(t,e){this.foundCrossings=new ie,this.crossingsThatShouldBecomeHubs=new ie,this.metroGraphData=t,this.polylineAcceptsPoint=e}*Vertices(){for(const t of this.Polylines)for(const e of t.polylinePoints())yield e}get Polylines(){return this.metroGraphData.Edges.map(t=>t.curve)}Edges(){const t=new Bs;for(const e of this.Vertices())e.next&&t.set(new ve(e.point,e.next.point),0);return Array.from(t.keys())}run(){if(this.metroGraphData.Edges.length===0)return!1;const t=new Bs,e=new Mn(null);for(const a of this.Vertices()){const h=Z.mkOnPoints([a.point]);h.pad(C.intersectionEpsilon),e.Add(h,a.point)}const i=Rn(this.Edges(),a=>Z.mkPP(a.first,a.second));Ae(i,i,(a,h)=>this.IntersectTwoEdges.bind(a,h,t,e)),this.SortInsertedPoints(t);const s=this.InsertPointsIntoPolylines(t),n=this.FixPaths(),o=this.RemoveUnimportantCrossings();return n||s||o}FixPaths(){let t=!1;return this.RemoveSelfCycles()&&(t=!0),this.ReduceEdgeCrossings()&&(t=!0),t}SortInsertedPoints(t){for(const e of t)this.SortInsideSegment(e[0],e[1])}SortInsideSegment(t,e){e.sort((i,s)=>W(tt(i,t.first),tt(s,t.first)))}InsertPointsIntoPolylines(t){let e=!1;for(const i of this.metroGraphData.Metrolines)return this.InsertPointsIntoPolyline(i,t)&&(e=!0),e}InsertPointsIntoPolyline(t,e){let i=!1;for(let s=t.Polyline.startPoint;s.next!=null;s=s.next)this.InsertPointsOnPolypoint(s,e,t)&&(i=!0);return i}InsertPointsOnPolypoint(t,e,i){const s=new ve(t.point,t.next.point),n=t.point!==s.first,o=e.get(s);if(!o)return!1;const a=t.next,h=t.polyline;if(n)for(let u=o.length-1;u>=0;u--){if(this.polylineAcceptsPoint!=null&&!this.polylineAcceptsPoint(i,o[u]))continue;const c=qt.mkFromPoint(o[u]);c.prev=t,c.polyline=h,t.next=c,t=c}else for(let u=0;u<o.length;u++){if(this.polylineAcceptsPoint!=null&&!this.polylineAcceptsPoint(i,o[u]))continue;const c=qt.mkFromPoint(o[u]);c.prev=t,c.polyline=h,t.next=c,t=c}return t.next=a,a.prev=t,!0}RemoveSelfCycles(){let t=!1;for(const e of this.Polylines)Xr.RemoveSelfCyclesFromPolyline(e)&&(t=!0);return t}static RemoveSelfCyclesFromPolyline(t){let e=!1;const i=new si;for(let s=t.startPoint;s!=null;s=s.next){const n=s.point,o=i.get(n);if(o){for(let a=o.next;a!==s.next;a=a.next)i.deleteP(a.point);o.next=s.next,s.next.prev=o,e=!0}else i.set(s.point,s)}return e}ReduceEdgeCrossings(){const t=new uc(this.metroGraphData);t.Run();for(const e of t.GetChangedHubs())this.crossingsThatShouldBecomeHubs.add(e);return t.NumberOfReducedCrossings()>0}RemoveUnimportantCrossings(){let t=!1;this.pointsToDelete=sa(this.foundCrossings,this.crossingsThatShouldBecomeHubs);for(const e of this.Polylines)this.RemoveUnimportantCrossingsFromPolyline(e)&&(t=!0);return t}RemoveUnimportantCrossingsFromPolyline(t){let e=!1;for(let i=t.startPoint.next;i!=null&&i.next!=null;i=i.next)if(this.pointsToDelete.has(i.point)&&d.getTriangleOrientation(i.prev.point,i.point,i.next.point)===k.Collinear){const s=i.prev,n=i.next;s.next=n,n.prev=s,i=s,e=!0}return e}IntersectTwoEdges(t,e,i,s){const n=D.IntersectPPPP(t.first,t.second,e.first,e.second);if(n){const o=this.FindExistingVertexOrCreateNew(s,n);(this.AddVertexToSplittingList(t,i,o)||this.AddVertexToSplittingList(e,i,o))&&this.foundCrossings.add(o)}}FindExistingVertexOrCreateNew(t,e){const i=t.RootNode.FirstHitNode(e);if(i!=null)return i.UserData;const s=Z.mkOnPoints([e]);return s.pad(C.intersectionEpsilon),t.Add(s,e),e}AddVertexToSplittingList(t,e,i){if(!w.closeIntersectionPoints(i,t.first)&&!w.closeIntersectionPoints(i,t.second)){let s=e.get(t);if(s||(s=new Array,e.set(t,s)),!s.find(n=>n.equal(i)))return s.push(i),!0}return!1}}class sh{constructor(t,e,i,s){this.BelongsToRealNode=s,this.Curve=e,this.Position=i,this.points=new Array(t),this.tangents=new Array(t),this.OrientedHubSegments=new Array(t)}isCorrectlyOrienected(){return d.getTriangleOrientation(this.Curve.boundingBox.center,this.Curve.value(this.parEnd),this.Curve.value(this.parStart))!==k.Counterclockwise}get Count(){return this.points.length}get CurveCenter(){return this.Curve.boundingBox.center}get OppositeBase(){return this.OutgoingBundleInfo!=null?this.OutgoingBundleInfo.TargetBase:this.IncomingBundleInfo.SourceBase}get length(){return this.points.length}get Points(){return this.points}get Tangents(){return this.tangents}get InitialMidParameter(){return this.initialMidParameter}set InitialMidParameter(t){this.initialMidParameter=t,this.InitialMidPoint=this.Curve.value(t)}get ParStart(){return this.parStart}set ParStart(t){this.parStart=t,this.StartPoint=this.Curve.value(this.parStart)}get ParEnd(){return this.parEnd}set ParEnd(t){this.parEnd=t,this.EndPoint=this.Curve.value(this.parEnd)}get ParMid(){return(this.parStart+this.parEnd)/2}get MidPoint(){return d.middle(this.StartPoint,this.EndPoint)}get Span(){return this.SpanBetweenTwoParameters(this.parStart,this.parEnd)}SpanBetweenTwoParameters(t,e){return t<=e?e-t:e-t+K(this.Curve)}RotateLeftPoint(t,e){return t===0?this.EndPoint:this.RotatePoint(t,this.parEnd,e)}RotateRigthPoint(t,e){return t===0?this.StartPoint:this.RotatePoint(t,this.parStart,e)}RotatePoint(t,e,i){const s=K(this.Curve)*i;return e+=t*s,e=this.AdjustParam(e),this.Curve.value(e)}AdjustParam(t){return t>this.Curve.parEnd?t=this.Curve.parStart+(t-this.Curve.parEnd):t<this.Curve.parStart&&(t=this.Curve.parEnd-(this.Curve.parStart-t)),t}RotateBy(t,e,i){const s=K(this.Curve)*i;t!==0&&(this.ParStart=this.AdjustParam(this.ParStart+t*s)),e!==0&&(this.ParEnd=this.AdjustParam(this.ParEnd+e*s))}RelativeOrderOfBasesIsPreserved(t,e,i){const s=K(this.Curve)*i,n=this.parStart+t*s,o=this.parStart<this.parEnd?this.parEnd+e*s:this.parEnd+K(this.Curve)+e*s;if(n>o||this.SpanBetweenTwoParameters(n,o)>K(this.Curve)/2)return!1;if(this.Prev==null||this.SpanBetweenTwoParameters(this.Prev.ParMid,this.ParMid)>s&&this.SpanBetweenTwoParameters(this.ParMid,this.Next.ParMid)>s)return!0;const a=this.RotateLeftPoint(e,i),h=this.RotateRigthPoint(t,i),u=d.middle(a,h),c=this.MidPoint;return!(d.getTriangleOrientation(this.CurveCenter,this.Prev.MidPoint,c)!=d.getTriangleOrientation(this.CurveCenter,this.Prev.MidPoint,u)||d.getTriangleOrientation(this.CurveCenter,this.Next.MidPoint,c)!=d.getTriangleOrientation(this.CurveCenter,this.Next.MidPoint,u))}}class Hs{constructor(t,e,i,s){this.SourceBase=t,this.TargetBase=e,this.obstaclesToIgnore=i,this.HalfWidthArray=s,this.TotalRequiredWidth=this.HalfWidthArray.reduce((o,a)=>o+a,0)*2,this.longEnoughSideLength=t.Curve.boundingBox.addRec(e.Curve.boundingBox).diagonal;const n=Math.max(t.Curve.boundingBox.diagonal,e.Curve.boundingBox.diagonal);if(this.TotalRequiredWidth>n){const o=this.TotalRequiredWidth/n;for(let a=0;a<this.HalfWidthArray.length;a++)this.HalfWidthArray[a]/=o;this.TotalRequiredWidth/=o}}SetParamsFeasiblySymmetrically(t){this.CalculateTightObstaclesForBundle(t,this.obstaclesToIgnore),this.SetEndParamsSymmetrically()}CalculateTightObstaclesForBundle(t,e){const i=this.SourceBase.Curve.boundingBox.diagonal/2,s=this.TargetBase.Curve.boundingBox.diagonal/2,n=Qi.Create4gon(this.SourceBase.Position,this.TargetBase.Position,i*2,s*2);this.tightObstaclesInTheBoundingBox=Array.from(t.AllHitItems(n.boundingBox,o=>!e.has(o)&&w.ClosedCurveInteriorsIntersect(n,o)))}SetEndParamsSymmetrically(){const t=this.TargetBase.Position,e=this.SourceBase.Position,i=t.sub(e).normalize(),s=i.rotate90Ccw(),n=d.middle(t,e),o=i.mul(this.longEnoughSideLength),a=n.add(o),h=n.sub(o);if(this.SetRLParamsIfWidthIsFeasible(s.mul(this.TotalRequiredWidth/2),a,h)){this.SetInitialMidParams();return}let u=this.TotalRequiredWidth,c=0,m=u/2;for(;u-c>Hs.FeasibleWidthEpsilon;)this.SetRLParamsIfWidthIsFeasible(s.mul(m/2),a,h)?c=m:u=m,m=.5*(u+c);m<=Hs.FeasibleWidthEpsilon&&(this.SetRLParamsIfWidthIsFeasible_(s.mul(Hs.FeasibleWidthEpsilon),new d(0,0),a,h)||this.SetRLParamsIfWidthIsFeasible_(new d(0,0),s.mul(-Hs.FeasibleWidthEpsilon),a,h))&&(m=2*Hs.FeasibleWidthEpsilon),this.SourceBase.InitialMidParameter=this.SourceBase.AdjustParam(this.SourceBase.ParStart+this.SourceBase.Span/2),this.TargetBase.InitialMidParameter=this.TargetBase.AdjustParam(this.TargetBase.ParStart+this.TargetBase.Span/2)}mkNameFromLRST(){return"./tmp/leftRight"+this.SourceBase.Position.toString()+"_"+this.TargetBase.Position.toString()+".svg"}SetRLParamsIfWidthIsFeasible(t,e,i){return this.SetRLParamsIfWidthIsFeasible_(t,t.neg(),e,i)}SetRLParamsIfWidthIsFeasible_(t,e,i,s){const n={par:0},o={par:0},a={par:0},h={par:0};let u=this.TrimSegWithBoundaryCurves(D.mkPP(i.add(t),s.add(t)),o,a);return u==null||this.tightObstaclesInTheBoundingBox.find(m=>w.intersectionOne(u,m,!1)!=null)||(u=this.TrimSegWithBoundaryCurves(D.mkPP(i.add(e),s.add(e)),h,n),u==null)||this.tightObstaclesInTheBoundingBox.find(m=>w.intersectionOne(u,m,!1)!=null)?!1:(this.SourceBase.IsParent?(this.SourceBase.ParStart=o.par,this.SourceBase.ParEnd=h.par):(this.SourceBase.ParStart=h.par,this.SourceBase.ParEnd=o.par),this.TargetBase.IsParent?(this.TargetBase.ParStart=n.par,this.TargetBase.ParEnd=a.par):(this.TargetBase.ParStart=a.par,this.TargetBase.ParEnd=n.par),!0)}SetInitialMidParams(){const t={par:0},e={par:0};this.TrimSegWithBoundaryCurves(D.mkPP(this.TargetBase.CurveCenter,this.TargetBase.CurveCenter),e,t)!=null?(this.SourceBase.InitialMidParameter=e.par,this.TargetBase.InitialMidParameter=t.par):(this.SourceBase.InitialMidParameter=this.SourceBase.AdjustParam(this.SourceBase.ParStart+this.SourceBase.Span/2),this.TargetBase.InitialMidParameter=this.TargetBase.AdjustParam(this.TargetBase.ParStart+this.TargetBase.Span/2))}mkNameFromST(){return"./tmp/mparam"+this.SourceBase.Position.toString()+"_"+this.TargetBase.Position.toString()+".svg"}TrimSegWithBoundaryCurves(t,e,i){let s=w.getAllIntersections(t,this.SourceBase.Curve,!0);if(s.length===0)return i.par=0,e.par=0,null;let n;if(s.length===1?n=s[0]:this.SourceBase.IsParent?n=s[0].par0<s[1].par0?s[1]:s[0]:n=s[0].par0<s[1].par0?s[0]:s[1],s=w.getAllIntersections(t,this.TargetBase.Curve,!0),s.length===0)return i.par=0,e.par=0,null;let o;return s.length===1?o=s[0]:this.TargetBase.IsParent?o=s[0].par0>s[1].par0?s[1]:s[0]:o=s[0].par0>s[1].par0?s[0]:s[1],e.par=n.par1,i.par=o.par1,D.mkPP(n.x,o.x)}RotateBy(t,e,i,s,n){const o=t!==0||e!==0,a=i!==0||s!==0;o&&this.SourceBase.RotateBy(t,e,n),a&&this.TargetBase.RotateBy(i,s,n),this.UpdateSourceAndTargetBases(o,a)}UpdateSourceAndTargetBases(t,e){t&&this.UpdatePointsOnBundleBase(this.SourceBase),e&&this.UpdatePointsOnBundleBase(this.TargetBase),this.UpdateTangentsOnBases()}UpdateTangentsOnBases(){const t=this.TargetBase.length;for(let e=0;e<t;e++){let i=this.TargetBase.Points[e].sub(this.SourceBase.Points[t-1-e]);const s=i.length;s>=C.tolerance&&(i=i.div(s),this.TargetBase.Tangents[e]=i,this.SourceBase.Tangents[t-1-e]=i.neg())}}UpdatePointsOnBundleBase(t){const e=t.length,i=t.Points,s=D.mkPP(t.EndPoint,t.StartPoint),n=1/this.TotalRequiredWidth;let o=this.HalfWidthArray[0];i[0]=s.value(o*n);for(let a=1;a<e;a++)o+=this.HalfWidthArray[a-1]+this.HalfWidthArray[a],i[a]=s.value(o*n)}RotationIsLegal(t,e,i,s,n){if(!this.SourceBase.IsParent&&!this.TargetBase.IsParent){if(e!==0||i!==0){const o=this.SourceBase.RotateLeftPoint(e,n),a=this.TargetBase.RotateRigthPoint(i,n);if(!this.LineIsLegal(o,a))return!1}if(t!==0||s!==0){const o=this.SourceBase.RotateRigthPoint(t,n),a=this.TargetBase.RotateLeftPoint(s,n);if(!this.LineIsLegal(o,a))return!1}}else{if(e!==0||s!==0){const o=this.SourceBase.RotateLeftPoint(e,n),a=this.TargetBase.RotateLeftPoint(s,n);if(!this.LineIsLegal(o,a))return!1}if(t!==0||i!==0){const o=this.SourceBase.RotateRigthPoint(t,n),a=this.TargetBase.RotateRigthPoint(i,n);if(!this.LineIsLegal(o,a))return!1}}return!((t!==0||e!==0)&&!this.SourceBase.RelativeOrderOfBasesIsPreserved(t,e,n)||(i!==0||s!==0)&&!this.TargetBase.RelativeOrderOfBasesIsPreserved(i,s,n))}LineIsLegal(t,e){return this.tightObstaclesInTheBoundingBox.find(i=>w.intersectionOne(D.mkPP(t,e),i,!1)!=null)==null}}Hs.FeasibleWidthEpsilon=.1;class nh{constructor(t,e,i,s){this.Segment=t,this.Reversed=e,this.Index=i,this.BundleBase=s}get Segment(){return this.segment}set Segment(t){this.segment=t}value(t){return this.Reversed?this.Segment.value(this.Segment.parEnd-t):this.Segment.value(t)}}class wt{constructor(t,e,i){this.fixedBundles=new Ho,this.stepsWithProgress=0,this.metroOrdering=t,this.metroGraphData=e,this.bundlingSettings=i}Run(){this.AllocateBundleBases(),this.SetBasesRightLeftParamsToTheMiddles(),this.bundlingSettings.KeepOverlaps?(this.UpdateSourceAndTargetBases(),this.CreateOrientedSegs()):(this.SetRightLeftParamsFeasiblySymmetrically(),this.AdjustStartEndParamsToAvoidBaseOverlaps(),this.UpdateSourceAndTargetBases(),this.CreateOrientedSegs(),this.bundlingSettings.RotateBundles&&this.RotateBundlesToDiminishCost(),this.AdjustStartEndParamsToAvoidBaseOverlaps(),this.UpdateSourceAndTargetBases())}AllocateBundleBases(){this.externalBases=new Map,this.internalBases=new Map,this.Bundles=new Array;for(const t of this.metroGraphData.Stations)t.BoundaryCurve==null&&(t.BoundaryCurve=vt.mkCircle(t.Radius,t.Position));for(const t of this.metroGraphData.Stations)for(const e of t.Neighbors)if(t.SerialNumber<e.SerialNumber){const i=new sh(this.metroGraphData.RealEdgeCount(t,e),t.BoundaryCurve,t.Position,t.IsReal);t.BundleBases.set(e,i);const s=new sh(this.metroGraphData.RealEdgeCount(t,e),e.BoundaryCurve,e.Position,e.IsReal);e.BundleBases.set(t,s),w.PointRelativeToCurveLocation(e.Position,t.BoundaryCurve)!==ft.Outside?(i.IsParent=!0,ys(this.internalBases,t,i),ys(this.externalBases,e,s)):w.PointRelativeToCurveLocation(t.Position,e.BoundaryCurve)!==ft.Outside?(s.IsParent=!0,ys(this.externalBases,t,i),ys(this.internalBases,e,s)):(ys(this.externalBases,t,i),ys(this.externalBases,e,s));const n=this.metroGraphData.tightIntersections.ObstaclesToIgnoreForBundle(t,e),o=new Hs(i,s,n,Array.from(this.metroOrdering.GetOrder(t,e)).map(a=>a.Width/2));i.OutgoingBundleInfo=s.IncomingBundleInfo=o,this.Bundles.push(o)}this.SetBundleBaseNeighbors()}SetBundleBaseNeighbors(){for(const t of this.externalBases.keys()){const e=this.externalBases.get(t);this.SortBundlesCounterClockwise(e),this.SetLeftRightBases(e)}for(const t of this.internalBases.keys()){const e=this.internalBases.get(t);this.SortBundlesCounterClockwise(e),this.SetLeftRightBases(e)}}SortBundlesCounterClockwise(t){if(t.length>2){const e=t[0].OppositeBase.Position,i=t[0].CurveCenter;t.sort((s,n)=>bn(e.sub(i),s.OppositeBase.Position.sub(i),n.OppositeBase.Position.sub(i)))}}SetLeftRightBases(t){const e=t.length;if(!(e<=1))for(let i=0;i<e;i++)t[i].Prev=t[(i-1+e)%e],t[i].Next=t[(i+1)%e]}CreateOrientedSegs(){for(const t of this.metroGraphData.Metrolines)this.CreateOrientedSegsOnLine(t)}CreateOrientedSegsOnLine(t){for(let e=t.Polyline.startPoint.next;e.next!=null;e=e.next)this.CreateOrientedSegsOnLineVertex(t,e)}CreateOrientedSegsOnLineVertex(t,e){const i=this.metroGraphData.PointToStations.get(e.prev.point),s=this.metroGraphData.PointToStations.get(e.point),n=this.metroGraphData.PointToStations.get(e.next.point),o=s.BundleBases.get(i),a=s.BundleBases.get(n),h=this.metroOrdering.GetLineIndexInOrder(i,s,t),u=this.metroOrdering.GetLineIndexInOrder(n,s,t),c=o.OrientedHubSegments[h]=new nh(null,!1,h,o),m=a.OrientedHubSegments[u]=new nh(null,!0,u,a);m.Other=c,c.Other=m}UpdateSourceAndTargetBases(){for(const t of this.Bundles)t.UpdateSourceAndTargetBases(!0,!0)}SetBasesRightLeftParamsToTheMiddles(){for(const t of this.Bundles){const e=t.SourceBase,i=t.TargetBase;e.ParEnd=e.ParStart=this.GetBaseMiddleParamInDirection(e,e.Position,i.Position),i.ParEnd=i.ParStart=this.GetBaseMiddleParamInDirection(i,i.Position,e.Position)}}GetBaseMiddleParamInDirection(t,e,i){const s=t.Curve;if(s instanceof vt){const a=s;if(a.isArc())return d.angle(a.aAxis,i.sub(e))}const o=w.getAllIntersections(s,D.mkPP(e,i),!0);for(const a of o){const h=a.x;if(h.sub(e).dot(h.sub(i))<=0)return a.par0}throw new Error}SetRightLeftParamsFeasiblySymmetrically(){for(const t of this.Bundles)t.SetParamsFeasiblySymmetrically(this.metroGraphData.TightTree)}AdjustStartEndParamsToAvoidBaseOverlaps(){for(const t of this.externalBases.values())this.AdjustCurrentBundleWidthsOnCurve(t);for(const t of this.internalBases.values())this.AdjustCurrentBundleWidthsOnCurve(t)}AdjustCurrentBundleWidthsOnCurve(t){const e=t.length;if(!(e<=1))for(let i=0;i<e;i++){const s=t[i],n=s.Next;this.ShrinkBasesToMakeTwoConsecutiveNeighborsHappy(s,n)}}ShrinkBasesToMakeTwoConsecutiveNeighborsHappy(t,e){const i=gc(t,e);if(i==null||N(i.start,i.end))return;const s=i.rbaseMiddle,n=i.lbaseMiddle;if(s<n){const u=t;t=e,e=u}const o=t.Span,a=e.Span,h=(i.end*o+i.start*a)/(a+o);t.ParStart=t.AdjustParam(h+C.distanceEpsilon),e.ParEnd=e.AdjustParam(h-C.distanceEpsilon)}RegularCut(t,e,i,s,n,o){let a=(n*s+o*t)/(n+o);const h=Math.min(e,s),u=Math.max(t,i);return a<u&&(a=u),a>h&&(a=h),a}RotateBundlesToDiminishCost(){let t=wt.MaxParameterChange;const e={cost:this.Cost()};let i=0;for(;i++<wt.MaxIterations;){const s=e.cost;if(this.RotateBundlesToDiminishCostOneIteration(t,e),t=this.UpdateParameterChange(t,s,e.cost),t<wt.MinParameterChange)break}}UpdateParameterChange(t,e,i){return i+1<e?(this.stepsWithProgress++,this.stepsWithProgress>=5&&(this.stepsWithProgress=0,this.fixedBundles.clear())):(this.stepsWithProgress=0,t*=.8,this.fixedBundles.clear()),t}RotateBundlesToDiminishCostOneIteration(t,e){let i=!1;for(const s of this.Bundles)this.fixedBundles.has(s)||(this.OptimizeBundle(s,t,e)?i=!0:this.fixedBundles.add(s));return i}OptimizeBundle(t,e,i){const s=this.CostBi(t);if(s<wt.CostThreshold)return!1;let n=0,o=-1,a=-1;for(let h=0;h<wt.Deltas.length-1;h++){let u=this.DeltaWithChangedAngles(wt.Deltas[h][0],wt.Deltas[h][1],0,0,t,s,e);u>wt.CostDeltaThreshold&&u>n&&(a=h,o=wt.Deltas.length-1,n=u),u=this.DeltaWithChangedAngles(0,0,wt.Deltas[h][0],wt.Deltas[h][1],t,s,e),u>wt.CostDeltaThreshold&&u>n&&(a=wt.Deltas.length-1,o=h,n=u)}return n<wt.CostDeltaThreshold?!1:(i.cost-=n,t.RotateBy(wt.Deltas[a][0],wt.Deltas[a][1],wt.Deltas[o][0],wt.Deltas[o][1],e),!0)}DeltaWithChangedAngles(t,e,i,s,n,o,a){if(!n.RotationIsLegal(t,e,i,s,a))return 0;n.RotateBy(t,e,i,s,a);const h=this.CostBN(n,o);return n.RotateBy(t*-1,e*-1,i*-1,s*-1,a),o-h}CostBi(t){return wt.SeparationCoeff*this.SeparationCost(t)+(wt.SqueezeCoeff*this.SqueezeCost(t)+(wt.AssymetryCoeff*this.AssymetryCost(t)+wt.CenterCoeff*this.CenterCostBi(t)))}CostBN(t,e){let i=0;return i=i+wt.CenterCoeff*this.CenterCostBi(t),i>e||(i=i+wt.SeparationCoeff*this.SeparationCost(t),i>e)||(i=i+wt.SqueezeCoeff*this.SqueezeCost(t),i>e)||(i=i+wt.AssymetryCoeff*this.AssymetryCost(t)),i}SqueezeCost(t){const i=t.TargetBase.MidPoint.sub(t.SourceBase.MidPoint).normalize().rotate90Ccw(),s=Math.abs(t.SourceBase.StartPoint.sub(t.SourceBase.EndPoint).dot(i)),n=Math.abs(t.TargetBase.StartPoint.sub(t.TargetBase.EndPoint).dot(i)),o=Math.abs(t.TotalRequiredWidth-s)/t.TotalRequiredWidth,a=Math.abs(t.TotalRequiredWidth-n)/t.TotalRequiredWidth,h=Math.abs(s-n)/t.TotalRequiredWidth;return Math.exp(o*10)-1+(Math.exp(a*10)-1)+h}CenterCostBi(t){return!t.SourceBase.BelongsToRealNode&&!t.TargetBase.BelongsToRealNode?0:this.CenterCostBb(t.SourceBase)+this.CenterCostBb(t.TargetBase)}CenterCostBb(t){if(!t.BelongsToRealNode)return 0;const e=t.ParMid,i=Math.min(t.InitialMidParameter,e),s=Math.max(t.InitialMidParameter,e),n=Math.min(s-i,i+(K(t.Curve)-s));return t.CurveCenter.equal(t.Position)||t.IsParent?25*(n*n):500*(n*n)}AssymetryCost(t){return this.GetAssymetryCostForBase(t.SourceBase)+this.GetAssymetryCostForBase(t.TargetBase)}GetAssymetryCostForBase(t){if(t.BelongsToRealNode)return 0;const e=t.OppositeBase.BelongsToRealNode?200:500;let i=0;for(const s of t.OrientedHubSegments){const n=s.Index,o=s.Other.Index,a=t.Points[n],h=t.Tangents[n],u=s.Other.BundleBase,c=u.Points[o],m=u.Tangents[o],S=t.Count+u.Count;i+=this.GetAssymetryCostOnData(a,h,c,m,e)/S}return i}GetAssymetryCostOnData(t,e,i,s,n){const o=t.sub(i),a=o.length;if(a<C.distanceEpsilon)return 0;const h=e.add(s).dot(o),u=d.crossProduct(o,e),c=d.crossProduct(o,s),m=u-c,S=h*h+m*m,A=u*u+c*c;return 10*S+n*A}SeparationCost(t){return this.SeparationCostForBundleBase(t.SourceBase)+this.SeparationCostForBundleBase(t.TargetBase)}SeparationCostForBundleBase(t){return t.Prev==null?0:this.SeparationCostForAdjacentBundleBases(t,t.Prev)+this.SeparationCostForAdjacentBundleBases(t,t.Next)}SeparationCostForAdjacentBundleBases(t,e){const i=t.Curve,s=this.IntervalsOverlapLength(t.ParStart,t.ParEnd,e.ParStart,e.ParEnd,i),n=Math.min(t.Span,e.Span);return Math.exp(s/(n*10))-1}IntervalsOverlapLength(t,e,i,s,n){const o=n.parStart,a=n.parEnd;return t<e?i<s?this.IntersectRegularIntervals(t,e,i,s):this.IntersectRegularIntervals(t,e,i,a)+this.IntersectRegularIntervals(t,e,o,s):i<s?this.IntersectRegularIntervals(t,a,i,s)+this.IntersectRegularIntervals(o,e,i,s):this.IntersectRegularIntervals(t,a,i,a)+this.IntersectRegularIntervals(o,e,o,s)}IntersectRegularIntervals(t,e,i,s){const n=Math.max(t,i),o=Math.min(e,s);return n<o?o-n:0}Cost(){let t=0;for(const e of this.Bundles){const i=wt.SeparationCoeff*this.SeparationCost(e),s=wt.AssymetryCoeff*this.AssymetryCost(e),n=wt.SqueezeCoeff*this.SqueezeCost(e),o=wt.CenterCoeff*this.CenterCostBi(e);t+=(i+s)/2+n+o}return t}}wt.Deltas=[[1,-1],[1,-1]],wt.SeparationCoeff=1,wt.SqueezeCoeff=1,wt.CenterCoeff=10,wt.AssymetryCoeff=1,wt.MaxIterations=200,wt.MaxParameterChange=8/360,wt.MinParameterChange=.1/360,wt.CostThreshold=1e-5,wt.CostDeltaThreshold=.01;function gc(l,t){const e=K(l.Curve);let i=l.ParEnd,s=l.ParStart<l.ParEnd?l.ParStart:l.ParStart-e,n=t.ParEnd,o=t.ParStart<t.ParEnd?t.ParStart:t.ParStart-e;i>n?i-o>e&&(o+=e,n+=e):n-s>e&&(s+=e,i+=e);const a=Math.min(i,n),h=Math.max(s,o);return h<=a?{start:h,end:a,rbaseMiddle:(s+i)/2,lbaseMiddle:(o+n)/2}:null}class fc{constructor(){this.Metrolines=new Array}Add(t){this.Metrolines.push(t)}}class $o{constructor(t){this.Metrolines=t,this.BuildOrder()}*GetOrder(t,e){const i=new ve(t.Position,e.Position),s=this.bundles.get(i).Metrolines;if(t.Position===i.first)for(let n=0;n<s.length;n++)yield s[n];else for(let n=s.length-1;n>=0;n--)yield s[n]}GetLineIndexInOrder(t,e,i){const s=new ve(t.Position,e.Position),n=t.Position!==s.first,o=this.bundles.get(s).LineIndexInOrder;return n?o.size-1-o.get(i):o.get(i)}BuildOrder(){this.bundles=new Bs;for(const t of this.Metrolines)for(let e=t.Polyline.startPoint;e.next!=null;e=e.next){const i=new ve(e.point,e.next.point);let s=this.bundles.get(i);s||this.bundles.set(i,s=new fc),s.Add(t)}for(const t of this.bundles)this.BuildOrderPP(t[0],t[1])}BuildOrderPP(t,e){if(!e.orderFixed){e.Metrolines.sort((i,s)=>this.CompareLines(i,s,t.first,t.second)),e.orderFixed=!0,e.LineIndexInOrder=new Map;for(let i=0;i<e.Metrolines.length;i++)e.LineIndexInOrder.set(e.Metrolines[i],i)}}CompareLines(t,e,i,s){const n={polyPoint:null,next:null,prev:null};this.FindStationOnLine(i,s,t,n);const o=n.polyPoint,a=n.next,h=n.prev;this.FindStationOnLine(i,s,e,n);const u=n.polyPoint,c=n.next,m=n.prev;let S=o,A=u,I,B;for(;(B=h(S))!=null&&(I=m(A))!=null&&B.point.equal(I.point);){const q=new ve(B.point,S.point);if(this.bundles.get(q).orderFixed)return this.CompareOnFixedOrder(q,t,e,!B.point.equal(q.first));S=B,A=I}if(B!=null&&I!=null){const q=S.point;return-$o.IsLeft(a(S).point.sub(q),B.point.sub(q),I.point.sub(q))}for(S=o,A=u;(B=a(S))!=null&&(I=c(A))!=null&&B.point.equal(I.point);){const q=new ve(B.point,S.point);if(this.bundles.get(q).orderFixed)return this.CompareOnFixedOrder(q,t,e,!S.point.equal(q.first));S=B,A=I}if(B!=null&&I!=null){const q=S.point;return $o.IsLeft(h(S).point.sub(q),B.point.sub(q),I.point.sub(q))}return W(t.Index,e.Index)}CompareOnFixedOrder(t,e,i,s){const n=this.bundles.get(t).LineIndexInOrder;return(s?-1:1)*W(n.get(e),n.get(i))}FindStationOnLine(t,e,i,s){for(let n=i.Polyline.startPoint;n.next!=null;n=n.next){if(n.point.equal(t)&&n.next.point.equal(e)){s.next=o=>o.next,s.prev=o=>o.prev,s.polyPoint=n;return}if(n.point.equal(e)&&n.next.point.equal(t)){s.next=o=>o.prev,s.prev=o=>o.next,s.polyPoint=n.next;return}}throw new Error}static IsLeft(t,e,i){return bn(t,e,i)}}class kt extends zt{constructor(t,e){super(null),this.metroGraphData=t,this.bundlingSettings=e}run(){this.CreateMetroOrdering(),this.InitRadii(),this.FinalizePaths()}InitRadii(){new qe(this.metroGraphData,this.bundlingSettings).CreateNodeRadii()}CreateMetroOrdering(){this.metroOrdering=new $o(this.metroGraphData.Metrolines)}FinalizePaths(){this.CreateBundleBases(),this.CreateSegmentsInsideHubs(),this.CreateCurves()}CreateBundleBases(){new wt(this.metroOrdering,this.metroGraphData,this.bundlingSettings).Run()}CreateCurves(){for(let t=0;t<this.metroGraphData.Metrolines.length;t++)this.CreateCurveLine(this.metroGraphData.Metrolines[t],this.metroGraphData.Edges[t])}CreateCurveLine(t,e){const i=new w;let n=kt.FindCurveStart(this.metroGraphData,this.metroOrdering,t);const o=kt.HubSegsOfLine(this.metroGraphData,this.metroOrdering,t);for(const a of o)a!=null&&(i.addSegment(D.mkPP(n,a.start)),i.addSegment(a),n=a.end);i.addSegment(D.mkPP(n,kt.FindCurveEnd(this.metroGraphData,this.metroOrdering,t))),e.curve=i}static FindCurveStart(t,e,i){const s=t.PointToStations.get(i.Polyline.startPoint.point),n=t.PointToStations.get(i.Polyline.startPoint.next.point),o=s.BundleBases.get(n),a=o.IsParent?e.GetLineIndexInOrder(s,n,i):e.GetLineIndexInOrder(n,s,i);return o.Points[a]}static FindCurveEnd(t,e,i){const s=t.PointToStations.get(i.Polyline.endPoint.prev.point),n=t.PointToStations.get(i.Polyline.endPoint.point),o=n.BundleBases.get(s),a=o.IsParent?e.GetLineIndexInOrder(n,s,i):e.GetLineIndexInOrder(s,n,i);return o.Points[a]}static*HubSegsOfLine(t,e,i){for(let s=i.Polyline.startPoint.next;s.next!=null;s=s.next)yield kt.SegOnLineVertex(t,e,i,s)}static SegOnLineVertex(t,e,i,s){const n=t.PointToStations.get(s.prev.point),o=t.PointToStations.get(s.point),a=o.BundleBases.get(n),h=e.GetLineIndexInOrder(n,o,i);if(a.OrientedHubSegments[h]==null||a.OrientedHubSegments[h].Segment==null){const u=t.PointToStations.get(s.next.point),c=o.BundleBases.get(u),m=e.GetLineIndexInOrder(u,o,i);return D.mkPP(a.Points[h],c.Points[m])}return a.OrientedHubSegments[h].Segment}CreateSegmentsInsideHubs(){for(const t of this.metroGraphData.Metrolines)this.CreateOrientedSegsOnLine(t);this.bundlingSettings.UseCubicBezierSegmentsInsideOfHubs&&this.FanBezierSegs()}CreateOrientedSegsOnLine(t){for(let e=t.Polyline.startPoint.next;e.next!=null;e=e.next)this.CreateICurveForOrientedSeg(t,e)}CreateICurveForOrientedSeg(t,e){const i=this.metroGraphData.PointToStations.get(e.prev.point),s=this.metroGraphData.PointToStations.get(e.point),n=this.metroGraphData.PointToStations.get(e.next.point),o=s.BundleBases.get(i),a=s.BundleBases.get(n),h=this.metroOrdering.GetLineIndexInOrder(i,s,t),u=this.metroOrdering.GetLineIndexInOrder(n,s,t),c=this.bundlingSettings.UseCubicBezierSegmentsInsideOfHubs?kt.StandardBezier(o.Points[h],o.Tangents[h],a.Points[u],a.Tangents[u]):kt.BiArc(o.Points[h],o.Tangents[h],a.Points[u],a.Tangents[u]);o.OrientedHubSegments[h].Segment=c,a.OrientedHubSegments[u].Segment=c}static ShowHubs(t,e,i,s,n=[]){let o=kt.GetAllDebugCurves(e,t);i!=null&&o.push(It.mkDebugCurveTWCI(255,1,"red",H.mkDiamond(5,25,i.Position))),o=o.concat(n)}static GetAllDebugCurves(t,e){return kt.GraphNodes(e).concat(kt.VertexDebugCurves(t,e)).concat(kt.DebugEdges(e))}static DebugEdges(t){return t.Edges.map(e=>It.mkDebugCurveTWCI(40,.1,"gray",e.curve))}static VertexDebugCurves(t,e){return kt.DebugCircles(e).concat(kt.DebugHubBases(e)).concat(kt.DebugSegs(e)).concat(kt.BetweenHubs(t,e))}static BetweenHubs(t,e){const i=[];for(const s of e.Metrolines){const n=kt.GetInterestingSegs(e,t,s),o=kt.GetMonotoneColor(s.Polyline.start,s.Polyline.end,n);for(const a of n)i.push(It.mkDebugCurveTWCI(100,s.Width,o,D.mkPP(a[0],a[1])))}return i}static GetInterestingSegs(t,e,i){const s=new Array;if(t.Stations.length===0||t.Stations[0].BundleBases==null||t.Stations[0].BundleBases.size===0)return[];let n=kt.FindCurveStart(t,e,i);const o=kt.HubSegsOfLine(t,e,i);for(const a of o)a!=null&&(s.push([n,a.start]),n=a.end);return s.push([n,kt.FindCurveEnd(t,e,i)]),s}static GetMonotoneColor(t,e,i){return"green"}static DebugHubBases(t){const e=new Array;for(const i of t.Stations)for(const s of i.BundleBases.values())e.push(It.mkDebugCurveTWCI(100,1,"red",D.mkPP(s.EndPoint,s.StartPoint)));return e}static DebugCircles(t){return t.Stations.map(e=>It.mkDebugCurveTWCI(100,.1,"blue",H.mkCircle(e.Radius,e.Position)))}static DebugSegs(t){const e=new Array;for(const i of t.VirtualStations())for(const s of i.BundleBases.values())for(const n of s.OrientedHubSegments)if(n!=null)if(n.Segment==null){const o=n.Other.BundleBase,a=n.Index,h=n.Other.Index;e.push(D.mkPP(s.Points[a],o.Points[h]))}else e.push(n.Segment);return e.map(i=>It.mkDebugCurveTWCI(100,.01,"green",i))}static GraphNodes(t){return t.Edges.map(i=>i.sourcePort.Curve).concat(t.Edges.map(i=>i.targetPort.Curve)).map(i=>It.mkDebugCurveTWCI(40,1,"black",i))}static BiArc(t,e,i,s){const n=t.sub(i);if(n.length<C.distanceEpsilon)return null;const o=n.dot(e.sub(s)),a=-e.dot(s);if(e.dot(i.sub(t))<=0&&e.dot(s)<=0)return kt.StandardBezier(t,e,i,s);const h=2*(a-1),u=2*o,c=n.dot(n);let m;if(Math.abs(h)<C.distanceEpsilon)if(Math.abs(u)>C.distanceEpsilon)m=-c/u;else return null;else{let ct=u*u-4*h*c;ct<0&&(ct=0),ct=Math.sqrt(ct),m=(-u+ct)/(2*h),m<0&&(m=(-u-ct)/(2*h))}const S=t.add(e.mul(m)),A=i.add(s.mul(m)),I=d.middle(S,A),B=d.getTriangleOrientation(t,S,I),q=d.getTriangleOrientation(I,A,i);if(B!==q)return kt.StandardBezier(t,e,i,s);const rt=new w;return rt.addSegs([kt.ArcOn(t,S,I),kt.ArcOn(I,A,i)]),rt}static ArcOn(t,e,i){const s={center:null};if(Math.abs(d.signedDoubledTriangleArea(t,e,i))<1e-4||!kt.FindArcCenter(t,e,i,s))return D.mkPP(t,i);const n=s.center,o=tt(t,n);if(tt(t,e)/o<1e-4)return D.mkPP(t,i);const h=t.sub(n);let u=Math.atan2(h.y,h.x);const c=i.sub(n);let m=Math.atan2(c.y,c.x),S=m-u;if(S<0&&(S+=2*Math.PI,m+=2*Math.PI),S<=Math.PI)return new vt(u,m,new d(o,0),new d(0,o),n);for(m>2*Math.PI&&(m-=2*Math.PI),u=Math.PI-u,m=Math.PI-m,u<0&&(u+=2*Math.PI);m<u;)m+=2*Math.PI;return S=m-u,new vt(u,m,new d(-o,0),new d(0,o),n)}static FindArcCenter(t,e,i,s){const n=e.sub(t).rotate90Cw(),o=e.sub(i).rotate90Cw();return s.center=d.lineLineIntersection(t,t.add(n),i,i.add(o)),s.center!=null}static StandardBezier(t,e,i,s){const n=tt(t,i)/4;return Nt.mkBezier([t,t.add(e.mul(n)),i.add(s.mul(n)),i])}FanBezierSegs(){let t=!0;const e=5;let i=0;for(;t&&i++<e;){t=!1;for(const s of this.metroGraphData.Stations)for(const n of s.BundleBases.values())t||(t=this.FanEdgesOfHubSegment(n))}}FanEdgesOfHubSegment(t){let e=!1;for(let i=0;i<t.Count-1;i++)e||(e=this.FanCouple(t,i,t.CurveCenter,t.Curve.boundingBox.diagonal/2));return e}FanCouple(t,e,i,s){const n=t.OrientedHubSegments[e],o=t.OrientedHubSegments[e+1];if(n==null||On(n.Segment.start,n.Segment.end,o.Segment.start,o.Segment.end)||d.getTriangleOrientation(n.value(0),n.value(.5),n.value(1))!=d.getTriangleOrientation(o.value(0),o.value(.5),o.value(1)))return!1;const h=this.BaseLength(n),u=this.BaseLength(o);return Math.abs(h-u)<C.intersectionEpsilon?!1:h>u?this.AdjustLongerSeg(n,o,i,s):this.AdjustLongerSeg(o,n,i,s)}AdjustLongerSeg(t,e,i,s){const n=t.value(0).sub(e.value(0)),o=t.value(1).sub(e.value(1)),a=Math.min(n.length,o.length),h=e.value(.5),u=Math.max(n.length,o.length);return this.NicelyAligned(t.Segment,n,o,h,a,u)===0?!1:this.FitLonger(t,n,o,h,a,u,i,s)}FitLonger(t,e,i,s,n,o,a,h){let u=t.Segment;const c=u.start,m=u.end;let S=0;const A=10;let I=u.start.mul(1-kt.SqueezeBound).add(u.B(1).mul(kt.SqueezeBound)),B=u.end.mul(1-kt.SqueezeBound).add(u.B(2).mul(kt.SqueezeBound)),q=u.B(1).mul(2).sub(u.start),rt=u.B(2).mul(2).sub(u.end);const ct={highP:q};this.PullControlPointToTheCircle(u.start,ct,a,h),q=ct.highP;let Q=this.NicelyAligned(u,e,i,s,n,o);do{if(Q===-1){const pt=d.middle(u.B(1),I),Lt=d.middle(u.B(2),B);q=u.B(1),rt=u.B(2),u=new Nt(c,pt,Lt,m)}else{const pt=d.middle(u.B(1),q),Lt=(u.B(2),rt);I=u.B(1),B=u.B(2),u=new Nt(c,pt,Lt,m)}if((Q=this.NicelyAligned(u,e,i,s,n,o))===0)return t.Segment=u,t.Other.Segment=u,!0;if(S++>A)return!1}while(!0)}PullControlPointToTheCircle(t,e,i,s){const n=d.ProjectionToLine(t,e.highP,i),o=Math.sqrt(s*s-n.sub(i).lengthSquared),a=e.highP.sub(n),h=a.length;h>o&&(e.highP=n.add(a.mul(o/h)))}NicelyAligned(t,e,i,s,n,o){const h=t.value(.5).sub(s),u=h.length;return e.dot(h)<0||i.dot(h)<0||u<n-.001?1:u>o+.001?-1:0}BaseLength(t){return t.value(0).sub(t.value(1)).lengthSquared}}kt.SqueezeBound=.2;class Ce{constructor(t,e){this.stepsWithProgress=0,this.metroGraphData=t,this.bundlingSettings=e,this.costCalculator=new de(this.metroGraphData,this.bundlingSettings),this.cache=new Uo(this.metroGraphData,this.bundlingSettings,this.costCalculator,this.metroGraphData.cdt)}static FixRouting(t,e){return this.FixRoutingMBP(t,e,null)}static FixRoutingMBP(t,e,i){return new Ce(t,e).FixRoutingP(i)}FixRoutingP(t){this.stationsForOptimizations=this.GetStationsForOptimizations(t),this.cache.InitializeCostCache();let e=Ce.MaxStep,i=Number.POSITIVE_INFINITY,s=this.metroGraphData.VirtualStations().map(o=>o.Position),n=0;for(;n++<Ce.MaxIterations;){const o=this.TryMoveStations();if(n<=1&&!o)return!1;if(!o)break;const a=i;i=de.Cost(this.metroGraphData,this.bundlingSettings),e=this.UpdateMaxStep(e,a,i);const h=s;if(s=this.metroGraphData.VirtualStations().map(u=>u.Position),e<Ce.MinStep||this.Converged(e,h,s))break}return!0}static stationsArePositionedCorrectly(t){for(const e of t.VirtualEdges())if(!this.edgeIsPositionedCorrectly(e,t))return!1;return!0}static edgeIsPositionedCorrectly(t,e){const i=t[0],s=t[1],n=e.looseIntersections.ObstaclesToIgnoreForBundle(i,s),o=D.mkPP(i.Position,s.Position),a=Array.from(e.looseIntersections.obstacleTree.GetNodeItemsIntersectingRectangle(o.boundingBox)).filter(h=>!n.has(h)).filter(h=>w.CurvesIntersect(o,h));return a.length>0?(kt.ShowHubs(e,null,null,"./tmp/badcross.svg",[It.mkDebugCurveTWCI(200,1,"Brown",o),It.mkDebugCurveTWCI(200,1,"Red",H.mkCircle(2,i.Position)),It.mkDebugCurveTWCI(200,1,"Blue",H.mkCircle(5,s.Position)),It.mkDebugCurveTWCI(100,1,"Blue",H.mkCircle(5,s.Position))].concat(a.map(h=>It.mkDebugCurveTWCI(100,1,"Pink",h)))),!1):!0}GetStationsForOptimizations(t){if(t==null)return new Set(this.metroGraphData.VirtualStations());{const e=new Set;for(const i of t){const s=this.metroGraphData.PointToStations.get(i);s&&!s.IsReal&&e.add(s)}return e}}Converged(t,e,i){let s=0,n=0;for(let a=0;a<e.length;a++)n+=e[a].sub(i[a]).lengthSquared,s+=e[a].lengthSquared;return Math.sqrt(n/s)<Ce.MinRelativeChange}UpdateMaxStep(t,e,i){return i+1<e?(this.stepsWithProgress++,this.stepsWithProgress>=5&&(this.stepsWithProgress=0,t=Math.min(Ce.MaxStep,t/.8))):(this.stepsWithProgress=0,t*=.8),t}TryMoveStations(){let t=!1;const e=new Set;for(const i of this.stationsForOptimizations)if(this.TryMoveStation(i)){t=!0,e.add(i);for(const s of i.Neighbors)s.IsReal||e.add(s)}return this.stationsForOptimizations=e,t}TryMoveStation(t){let e=this.BuildDirection(t);if(e.length===0)return!1;let i=this.BuildStepLength(t,e);if(i<Ce.MinStep&&(e=pc(),i=this.BuildStepLength(t,e),i<Ce.MinStep))return!1;const s=e.mul(i),n=t.Position.add(s);return this.metroGraphData.PointToStations.has(n)||!this.moveIsLegalForAdjacentBundles(t,n)?!1:(this.metroGraphData.MoveNode(t,n),this.cache.UpdateCostCache(t),!0)}moveIsLegalForAdjacentBundles(t,e){for(const i of this.metroGraphData.looseIntersections.obstacleTree.AllHitItems(Z.mkOnPoints([e]),s=>w.PointRelativeToCurveLocation(e,s)!==ft.Outside))if(t.getELP().has(i)===!1)return!1;for(const i of t.Neighbors){const s=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(i,t);if(!this.metroGraphData.cdtIntersections.EdgeIsLegal_(i.Position,e,i.cdtTriangle,s))return!1}return!0}BuildDirection(t){const e=this.BuildForceForInk(t),i=this.BuildForceForPathLengths(t),s=this.BuildForceForRadius(t),n=this.BuildForceForBundle(t),o=e.add(i.add(s.add(n)));return o.length<.1?new d(0,0):o.normalize()}BuildStepLength(t,e){let i=Ce.MinStep,s=this.CostGain(t,t.Position.add(e.mul(i)));if(s<.01)return 0;for(;2*i<=Ce.MaxStep;){const n=this.CostGain(t,t.Position.add(e.mul(i*2)));if(n<=s)break;i*=2,s=n}return i}CostGain(t,e){const s=this.costCalculator.RadiusGain(t,e);if(s<-12345678)return-12345678;const n=this.costCalculator.BundleGain(t,e);if(n<-12345678)return-12345678;const o=this.costCalculator.InkGain(t,e),a=this.costCalculator.PathLengthsGain(t,e);return s+o+a+n}BuildForceForInk(t){let e=new d(0,0);for(const s of t.Neighbors){const n=s.Position.sub(t.Position);e=e.add(n.normalize())}return e.mul(this.bundlingSettings.InkImportance)}BuildForceForPathLengths(t){let e=new d(0,0);for(const s of this.metroGraphData.MetroNodeInfosOfNode(t)){const n=s.Metroline,o=s.PolyPoint.next.point,a=s.PolyPoint.prev.point,h=o.sub(t.Position),u=a.sub(t.Position);e=e.add(h.div(h.length*n.IdealLength)),e=e.add(u.div(u.length*n.IdealLength))}return e.mul(this.bundlingSettings.PathLengthImportance)}BuildForceForRadius(t){let e=new d(0,0);const i=t.cachedIdealRadius,s={touchedObstacles:[]};if(!this.metroGraphData.looseIntersections.HubAvoidsObstaclesSPNBA(t,t.Position,i,s))throw kt.ShowHubs(this.metroGraphData,null,t,"./tmp/hubs.svg",[It.mkDebugCurveTWCI(255,1,"Brown",Qi.containingPoly),It.mkDebugCurveTWCI(100,1,"Blue",H.mkCircle(i,t.Position))]),new Error;for(const a of s.touchedObstacles){const u=2*(1-a[1].sub(t.Position).length/i),c=t.Position.sub(a[1]).normalize();e=e.add(c.mul(u))}return e.mul(this.bundlingSettings.HubRepulsionImportance)}BuildForceForBundle(t){let e=new d(0,0);for(const s of t.Neighbors){const n=this.metroGraphData.GetWidthSSN(t,s,this.bundlingSettings.EdgeSeparation),o={closestDist:[]},a=this.metroGraphData.cdtIntersections.BundleAvoidsObstacles(t,s,t.Position,s.Position,n/2,o);for(const h of o.closestDist){const c=2*(1-h[0].sub(h[1]).length/(n/2)),m=h[0].sub(h[1]).normalize().neg();e=e.add(m.mul(c))}}return e.mul(this.bundlingSettings.BundleRepulsionImportance)}}Ce.MaxIterations=100,Ce.MaxStep=50,Ce.MinStep=1,Ce.MinRelativeChange=5e-4;function pc(){return new d(1+2*ls(),1+2*ls())}class An{constructor(t,e){this.metroGraphData=t,this.bundlingSettings=e}static FixRouting(t,e){const i=new An(t,e);i.GlueConflictingStations(),i.UnglueEdgesFromBundleToSaveInk(!0);let s=0;const n=10;for(;++s<n;){let o=i.GlueConflictingStations();if(o||(o=i.RelaxConstrainedEdges()),o||(o=s<=3&&i.UnglueEdgesFromBundleToSaveInk(!1)),o||(o=i.GlueCollinearNeighbors(s)),o||(o=s===3&&i.RemoveDoublePathCrossings()),!o)break}for(t.cdtIntersections.ComputeForcesForBundles=!0,i.RemoveDoublePathCrossings(),i.UnglueEdgesFromBundleToSaveInk(!0);i.GlueConflictingStations(););t.Initialize(!0)}GlueConflictingStations(){const t=this.GetCirclesHierarchy();if(t==null)return!1;const e=new Map,i=new Set;if(Ae(t,t,(n,o)=>this.TryToGlueStations(n,o,e,i)),e.size===0)return!1;for(let n=0;n<this.metroGraphData.Edges.length;n++)this.RegenerateEdge(e,n);const s=new ie;for(const n of i){s.add(n.Position);for(const o of n.Neighbors)o.IsReal||s.add(o.Position)}return this.metroGraphData.Initialize(!1),Ce.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,s),!0}GetCirclesHierarchy(){for(const i of this.metroGraphData.VirtualStations())i.Radius=this.GetCurrentHubRadius(i);const t=this.metroGraphData.VirtualStations().map(e);return re(t);function e(i){const s=i.Position,n=Math.max(i.Radius,5),o=new d(n,n),a=Z.mkPP(s.add(o),s.sub(o));return pe(i,a)}}GetCurrentHubRadius(t){if(t.IsReal)return t.BoundaryCurve.boundingBox.diagonal/2;{const e=t.cachedIdealRadius;let i=this.metroGraphData.looseIntersections.GetMinimalDistanceToObstacles(t,t.Position,e);for(const s of t.Neighbors)i=Math.min(i,t.Position.sub(s.Position).length);return i}}TryToGlueStations(t,e,i,s){if(!Dn(t.getELP(),e.getELP()))return!1;const n=t.Position.sub(e.Position).length,o=Math.max(t.Radius,5),a=Math.max(e.Radius,5);n>=o+a||this.TryGlueOrdered(t,e,s,i)||this.TryGlueOrdered(e,t,s,i)}TryGlueOrdered(t,e,i,s){return!s.has(t)&&!i.has(t)&&this.StationGluingIsAllowed(t,e,s)?(this.Map(t,e,i,s),!0):!1}Map(t,e,i,s){s.set(t,e),i.add(e)}StationGluingIsAllowed(t,e,i){for(const n of t.Neighbors){const o=An.Glued(n,i),a=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(o,t);if(!this.metroGraphData.cdtIntersections.EdgeIsLegalSSPPS(o,e,a))return!1}return!(this.ComputeCostDeltaAfterStationGluing(t,e,i)<0)}ComputeCostDeltaAfterStationGluing(t,e,i){const s=t.Position.sub(e.Position).length;if(t.Radius>=s||e.Radius>=s)return 1;let n=0;const o=this.metroGraphData.Ink;let a=this.metroGraphData.Ink-e.Position.sub(t.Position).length;for(const h of t.Neighbors){const u=An.Glued(h,i);a-=u.Position.sub(t.Position).length,a+=this.metroGraphData.RealEdgeCount(u,e)===0?u.Position.sub(e.Position).length:0}n+=de.InkError(o,a,this.bundlingSettings);for(const h of this.metroGraphData.MetroNodeInfosOfNode(t)){const u=h.Metroline.Length;let c=h.Metroline.Length;const m=h.PolyPoint,S=m.prev,A=m.next;c-=S.point.sub(t.Position).length+A.point.sub(t.Position).length,c+=S.point.sub(e.Position).length+A.point.sub(e.Position).length,n+=de.PathLengthsError(u,c,h.Metroline.IdealLength,this.bundlingSettings)}return n}RegenerateEdge(t,e){const i=this.metroGraphData.Metrolines[e].Polyline;for(const o of i)if(!this.metroGraphData.PointToStations.has(o))return;let s=!1;for(const o of i)if(t.has(this.metroGraphData.PointToStations.get(o))){s=!0;break}if(!s)return;const n=Array.from(i).map(o=>this.metroGraphData.PointToStations.get(o));this.metroGraphData.Edges[e].curve=at.mkFromPoints(An.GluedPolyline(n,t))}static GluedPolyline(t,e){let i;const s=new Yt.B;s.push(t[0]);const n=new Set;for(i=1;i<t.length-1;i++){const o=An.Glued(t[i],e);if(n.has(o)){for(;s.top!==o;)n.delete(s.pop());continue}d.closeDistEps(o.Position,s.top.Position)||(n.add(o),s.push(o))}return s.push(t[i]),Array.from(s).reverse().map(o=>o.Position)}static Glued(t,e){var i;return(i=e.get(t))!==null&&i!==void 0?i:t}UnglueEdgesFromBundleToSaveInk(t){const e=new Bs;this.ink=this.metroGraphData.Ink,this.polylineLength=new Map;for(const n of this.metroGraphData.Metrolines){this.polylineLength.set(n,n.Length);for(let o=n.Polyline.startPoint;o.next!=null;o=o.next){const a=new ve(o.point,o.next.point);pr(e,a,n)}}const i=new ie;let s=!1;for(const n of this.metroGraphData.Metrolines){const o=Ji(this.metroGraphData.PointToStations.get(n.Polyline.start).getELP(),this.metroGraphData.PointToStations.get(n.Polyline.end).getELP());this.TrySeparateOnPolyline(n,e,i,o)&&(s=!0)}return s&&this.metroGraphData.Initialize(!1),(t||s)&&Ce.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,t?null:i),s}TrySeparateOnPolyline(t,e,i,s){let n=!1,o=!0;for(;o;){o=!1;for(let a=t.Polyline.startPoint;a.next!=null&&a.next.next!=null;a=a.next)this.TryShortcutPolypoint(a,e,i,s)&&(o=!0);o&&(n=!0)}return n}TryShortcutPolypoint(t,e,i,s){return this.SeparationShortcutAllowed(t,e,s)?(i.add(t.point),i.add(t.next.point),i.add(t.next.next.point),this.RemoveShortcuttedPolypoint(t,e),!0):!1}SeparationShortcutAllowed(t,e,i){const s=t.point,n=t.next.point,o=t.next.next.point,a=this.metroGraphData.PointToStations.get(s),h=this.metroGraphData.PointToStations.get(n),u=this.metroGraphData.PointToStations.get(o),c=Ss(a.getELP(),u.getELP()),m=na([i,h.getELP(),c]);return!(!this.metroGraphData.cdtIntersections.EdgeIsLegalSSPPS(a,u,m)||this.GetInkgain(t,e,s,n,o)<0)}GetInkgain(t,e,i,s,n){const[o,a,h]=this.FindPolylines(t,e);let u=0;const c=this.ink;let m=this.ink;const S=i.sub(s).length,A=s.sub(n).length,I=i.sub(n).length;o.size===h.size&&(m-=S),a.size===h.size&&(m-=A);const B=e.get(new ve(i,n));(!B||B.size===0)&&(m+=I),u+=de.InkError(c,m,this.bundlingSettings);for(const Lt of h){const Bt=this.polylineLength.get(Lt),_t=Bt-(S+A-I);u+=de.PathLengthsError(Bt,_t,Lt.IdealLength,this.bundlingSettings)}let q=this.GetCurrentHubRadius(this.metroGraphData.PointToStations.get(i));const rt=this.metroGraphData.GetWidthAN(Array.from(h),this.bundlingSettings.EdgeSeparation),ct=this.metroGraphData.GetWidthAN(Array.from(Ps(o,h)),this.bundlingSettings.EdgeSeparation);let Q=qe.GetMinRadiusForTwoAdjacentBundlesNPPPNNB(q,i,n,s,rt,ct,this.bundlingSettings);Q>q&&(u-=de.RError(Q,q,this.bundlingSettings)),q=this.GetCurrentHubRadius(this.metroGraphData.PointToStations.get(n));const pt=this.metroGraphData.GetWidthAN(Array.from(Ps(a,h)),this.bundlingSettings.EdgeSeparation);return Q=qe.GetMinRadiusForTwoAdjacentBundlesNPPPNNB(q,n,s,i,pt,rt,this.bundlingSettings),Q>q&&(u-=de.RError(Q,q,this.bundlingSettings)),u}RemoveShortcuttedPolypoint(t,e){const i=t.point,s=t.next.point,n=t.next.next.point,[o,a,h]=this.FindPolylines(t,e),u=tt(i,s),c=tt(s,n),m=tt(i,n);o.size===h.size&&(this.ink-=u),a.size===h.size&&(this.ink-=c);const S=e.get(new ve(i,n));(!S||S.size===0)&&(this.ink+=m);for(const A of h){const I=this.polylineLength.get(A);this.polylineLength.set(A,I-(u+c-m))}for(const A of h){const I=Array.from(A.Polyline.polylinePoints()).find(B=>B.point.equal(s));this.RemovePolypoint(I),ns(e,[i,s],A),ns(e,[s,n],A),io(e,[i,n],A)}}FindPolylines(t,e){const i=t.point,s=t.next.point,n=t.next.next.point,o=e.getPP(i,s),a=e.getPP(s,n),h=Ji(o,a);return[o,a,h]}RemovePolypoint(t){const e=t.prev,i=t.next;e.next=i,i.prev=e}GlueCollinearNeighbors(t){const e=new ie;let i=!1;for(const s of this.metroGraphData.Stations)this.GlueCollinearNeighborsSPN(s,e,t)&&(i=!0);return i&&(this.metroGraphData.Initialize(!1),Ce.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,e)),i}GlueCollinearNeighborsSPN(t,e,i){if(t.Neighbors.length<=1)return!1;const s=new ih,n=t.Neighbors;for(let o=0;o<n.length;o++)this.TryToGlueEdges(t,n[o],n[(o+1)%n.length],s,i);if(s.isEmpty)return!1;for(const o of s)this.GlueEdge(o),e.add(o[0].Position),e.add(o[1].Position),e.add(o[2]);return!0}TryToGlueEdges(t,e,i,s,n){if(d.anglePCP(e.Position,t.Position,i.Position)<this.bundlingSettings.AngleThreshold){const a=tt(e.Position,t.Position),h=tt(i.Position,t.Position),u=Math.min(a,h)/Math.max(a,h);if(u<.05)return;if(a<h){if(this.EdgeGluingIsAllowedSSS(t,e,i)){this.AddEdgeToGlue(t,i,e,e.Position,s);return}}else if(this.EdgeGluingIsAllowedSSS(t,i,e)){this.AddEdgeToGlue(t,e,i,i.Position,s);return}if(n<5&&u>.5){const c=this.ConstructGluingPoint(t,e,i);this.EdgeGluingIsAllowedSSSP(t,e,i,c)&&this.AddEdgeToGlue(t,i,e,c,s)}}}ConstructGluingPoint(t,e,i){const s=Math.min(tt(e.Position,t.Position),tt(i.Position,t.Position)/2),n=e.Position.sub(t.Position).normalize().add(i.Position.sub(t.Position).normalize());return t.Position.add(n.mul(s/2))}EdgeGluingIsAllowedSSS(t,e,i){if(e.IsReal||i.IsReal||!Dn(e.getELP(),i.getELP())||!this.metroGraphData.cdtIntersections.EdgeIsLegal(e,i,e.Position,i.Position))return!1;const s=this.metroGraphData.looseIntersections.ObstaclesToIgnoreForBundle(t,i);return!(Pt.IntersectionsOfLineAndRectangleNodeOverPolylineLR(D.mkPP(t.Position,e.Position),this.metroGraphData.LooseTree).find(h=>!s.has(h.seg1))||Pt.IntersectionsOfLineAndRectangleNodeOverPolylineLR(D.mkPP(e.Position,i.Position),this.metroGraphData.LooseTree).find(h=>!s.has(h.seg1))||this.ComputeCostDeltaAfterEdgeGluing(t,e,i,e.Position)<0)}EdgeGluingIsAllowedSSSP(t,e,i,s){return!(!this.metroGraphData.looseIntersections.HubAvoidsObstaclesPNS__(s,0,Ji(e.getELP(),i.getELP()))||!this.metroGraphData.cdtIntersections.EdgeIsLegal(t,null,t.Position,s)||!this.metroGraphData.cdtIntersections.EdgeIsLegal(e,null,e.Position,s)||!this.metroGraphData.cdtIntersections.EdgeIsLegal(i,null,i.Position,s)||this.ComputeCostDeltaAfterEdgeGluing(t,e,i,s)<0)}ComputeCostDeltaAfterEdgeGluing(t,e,i,s){let n=0;const o=this.metroGraphData.Ink,a=this.metroGraphData.Ink-tt(t.Position,i.Position)-tt(t.Position,e.Position)+tt(t.Position,s)+tt(s,e.Position)+tt(s,i.Position);n+=de.InkError(o,a,this.bundlingSettings);for(const m of this.metroGraphData.GetIjInfo(t,i).Metrolines){const S=m.Length,A=m.Length-tt(t.Position,i.Position)+tt(t.Position,s)+tt(s,i.Position);n+=de.PathLengthsError(S,A,m.IdealLength,this.bundlingSettings)}for(const m of this.metroGraphData.GetIjInfo(t,e).Metrolines){const S=m.Length,A=m.Length-tt(t.Position,e.Position)+tt(t.Position,s)+tt(s,e.Position);n+=de.PathLengthsError(S,A,m.IdealLength,this.bundlingSettings)}const h=t.cachedIdealRadius,u=this.GetCurrentHubRadius(t),c=qe.GetMinRadiusForTwoAdjacentBundles(u,t,t.Position,e,i,this.metroGraphData,this.bundlingSettings);return c>u&&(n+=de.RError(c,u,this.bundlingSettings)),h>tt(t.Position,s)&&!t.IsReal&&(n-=de.RError(h,tt(t.Position,s),this.bundlingSettings)),n}AddEdgeToGlue(t,e,i,s,n){n.has(i,t)||n.has(e,t)||n.has(t,i)||n.has(t,e)||(n.set(t,i,s),n.set(t,e,s))}GlueEdge(t){const e=t[0],i=t[1],s=t[2];for(const n of e.MetroNodeInfos.map(o=>o.PolyPoint))n.next!=null&&n.next.point.equal(i.Position)?this.SplitPolylinePoint(n,s):n.prev!=null&&n.prev.point.equal(i.Position)&&this.SplitPolylinePoint(n.prev,s)}SplitPolylinePoint(t,e){if(t.point===e||t.next.point===e)return;const i=qt.mkFromPoint(e);i.polyline=t.polyline,i.next=t.next,i.prev=t,i.next.prev=i,i.prev.next=i}RelaxConstrainedEdges(){const t=new ie;let e=!1;for(const i of this.metroGraphData.VirtualEdges())this.RelaxConstrainedEdge(i[0],i[1],t)&&(e=!0);return e&&(this.metroGraphData.Initialize(!1),Ce.FixRoutingMBP(this.metroGraphData,this.bundlingSettings,t)),e}RelaxConstrainedEdge(t,e,i){const s=this.metroGraphData.GetWidthSSN(t,e,this.bundlingSettings.EdgeSeparation),n={closestDist:new Array};this.metroGraphData.cdtIntersections.BundleAvoidsObstacles(t,e,t.Position,e.Position,.99*s/2,n);const o=n.closestDist;if(o.length>0){let a=-1,h;for(const u of o){const c=Math.min(tt(t.Position,u[1]),tt(e.Position,u[1])),m=tt(t.Position,e.Position);if(c/m<.1)continue;const A=tt(u[0],u[1]);(a===-1||A<a)&&(a=A,h=u[1])}if(a===-1||!this.metroGraphData.looseIntersections.HubAvoidsObstaclesPNS__(h,0,Ji(t.getELP(),e.getELP())))return!1;i.add(h),i.add(t.Position),i.add(e.Position);for(const u of this.metroGraphData.GetIjInfo(t,e).Metrolines){let c=null;for(const m of u.Polyline.polylinePoints())if(m.point.equal(t.Position)){c=m;break}c.next!=null&&c.next.point.equal(e.Position)?this.SplitPolylinePoint(c,h):this.SplitPolylinePoint(c.prev,h)}return!0}return!1}RemoveDoublePathCrossings(){const t=new Xr(this.metroGraphData,this.metroGraphData.PointIsAcceptableForEdge.bind(this)).run();return t&&(this.metroGraphData.Initialize(!1),Ce.FixRouting(this.metroGraphData,this.bundlingSettings)),t}}class Xo{constructor(t,e,i){this.upperBound=Number.POSITIVE_INFINITY,this._visGraph=i,i.ClearPrevEdgesTable();for(const s of i.Vertices())s.Distance=Number.POSITIVE_INFINITY;this.sources=t,this.targets=new Set(e)}GetPath(){const t=new es;for(const e of this.sources)e.Distance=0,t.Enqueue(e,0);for(;!t.IsEmpty()&&(this._current=t.Dequeue(),!this.targets.has(this._current));){for(const e of this._current.OutEdges)this.PassableOutEdge(e)&&this.ProcessNeighbor(t,e,e.Target);for(const e of this._current.InEdges.filter(this.PassableInEdge.bind))this.ProcessNeighbor(t,e,e.Source)}return this._visGraph.PreviosVertex(this._current)==null?null:this.CalculatePath()}PassableOutEdge(t){return this.targets.has(t.Target)||!Xo.IsForbidden(t)}PassableInEdge(t){return this.targets.has(t.Source)||!Xo.IsForbidden(t)}static IsForbidden(t){return(t.IsPassable!=null&&!t.IsPassable()||t)instanceof wi}ProcessNeighbor(t,e,i){const s=e.Length,n=this._current.Distance+s;n>=this.upperBound||(this.targets.has(i)&&(this.upperBound=n,this.closestTarget=i),this._visGraph.PreviosVertex(i)==null?(i.Distance=n,this._visGraph.SetPreviousEdge(i,e),t.Enqueue(i,n)):n<i.Distance&&(i.Distance=n,this._visGraph.SetPreviousEdge(i,e),t.DecreasePriority(i,n)))}CalculatePath(){if(this.closestTarget==null)return null;const t=new Array;let e=this.closestTarget;do t.push(e),e=this._visGraph.PreviosVertex(e);while(e.Distance>0);return t.push(e),t.reverse()}}class Qr extends zt{constructor(t,e,i,s,n,o,a,h,u,c){super(null),this.bundlingSettings=s,this.bundlingSettings.edgeWidthShrinkCoeff=1,this.edgesToRoute=t,this.regularEdges=t.filter(m=>m.source!==m.target),this.VisibilityGraph=i,this.shortestPathRouter=e,this.LoosePadding=n,this.LooseHierarchy=a,this.TightHierarchy=o,this.EdgeLooseEnterable=h,this.EdgeTightEnterable=u,this.loosePolylineOfPort=c,Os(0)}ThereAreOverlaps(t){return oe(t,t,w.CurvesIntersect)}run(){if(this.ThereAreOverlaps(this.TightHierarchy)){this.Status=Ba.Overlaps;return}this.FixLocationsForHookAnywherePorts(this.edgesToRoute),this.RoutePathsWithSteinerDijkstra(),this.FixChildParentEdges(),this.bundlingSettings.StopAfterShortestPaths||this.OrderOptimizeNudgeEtc(),this.RouteSelfEdges(),this.FixArrowheads()}OrderOptimizeNudgeEtc(){const t=new hc(this.regularEdges,this.LooseHierarchy,this.TightHierarchy,this.bundlingSettings,this.shortestPathRouter.cdt,this.EdgeLooseEnterable,this.EdgeTightEnterable,this.loosePolylineOfPort);An.FixRouting(t,this.bundlingSettings),new kt(t,this.bundlingSettings).run()}FixChildParentEdges(){for(const t of this.regularEdges){const e=t.sourcePort,i=t.targetPort;if(e.Curve.boundingBox.containsRect(i.Curve.boundingBox)){const s=w.intersectionOne(e.Curve,D.mkPP(t.curve.start,t.curve.end),!1),n=t.curve;n.startPoint.point=s.x}if(i.Curve.boundingBox.containsRect(e.Curve.boundingBox)){const s=w.intersectionOne(i.Curve,D.mkPP(t.curve.start,t.curve.end),!0),n=t.curve;n.endPoint.point=s.x}}}FixLocationsForHookAnywherePorts(t){for(const e of t){let i=e.sourcePort instanceof Kt;if(i){const s=e.sourcePort;s.SetLocation(this.FigureOutHookLocation(s.LoosePolyline,e.targetPort,e))}else if(i=e.targetPort instanceof Kt,i){const s=e.targetPort;s.SetLocation(this.FigureOutHookLocation(s.LoosePolyline,e.sourcePort,e))}}}FigureOutHookLocation(t,e,i){return e instanceof Ge?this.FigureOutHookLocationForClusterOtherPort(t,e,i):this.FigureOutHookLocationForSimpleOtherPort(t,e,i)}FigureOutHookLocationForClusterOtherPort(t,e,i){const s=this.shortestPathRouter.MakeTransparentShapesOfEdgeGeometry(i),o=new Xo(Array.from(e.LoosePolyline).map(this.VisibilityGraph.FindVertex.bind),Array.from(t).map(this.VisibilityGraph.FindVertex.bind),this.VisibilityGraph).GetPath();for(const a of s)a.IsTransparent=!1;return o[o.length-1].point}FigureOutHookLocationForSimpleOtherPort(t,e,i){const s=e.Location,n=this.shortestPathRouter.MakeTransparentShapesOfEdgeGeometry(i),a=new Ls(this.VisibilityGraph.FindVertex(s),Array.from(t).map(h=>this.VisibilityGraph.FindVertex(h)),this.VisibilityGraph).GetPath();for(const h of n)h.IsTransparent=!1;return a[a.length-1].point}RoutePathsWithSteinerDijkstra(){this.shortestPathRouter.VisibilityGraph=this.VisibilityGraph,this.shortestPathRouter.BundlingSettings=this.bundlingSettings,this.shortestPathRouter.geomEdges=this.regularEdges,this.shortestPathRouter.ObstacleHierarchy=this.LooseHierarchy,this.shortestPathRouter.RouteEdges(),this.shortestPathRouter.cdt!=null&&this.AdjustEdgeSeparation()}AdjustEdgeSeparation(){const t=new Map;this.shortestPathRouter.FillCrossedCdtEdges(t);const e=this.GetPathsOnCdtEdge(t);this.bundlingSettings.edgeWidthShrinkCoeff=this.CalculateEdgeWidthShrinkCoeff(e)}GetPathsOnCdtEdge(t){const e=new Map;for(const i of t.keys())for(const s of t.get(i))Nn(e,s,i);return e}CalculateEdgeWidthShrinkCoeff(t){let e=0,i=this.bundlingSettings.edgeWidthShrinkCoeff;if(this.EdgeSeparationIsOkMN(t,i))return i;let s=!1;for(;!s||Math.abs(i-e)>.01;){const n=(e+i)/2;this.EdgeSeparationIsOkMN(t,n)?(e=n,s=!0):i=n}return e}EdgeSeparationIsOkMN(t,e){for(const i of t.keys())if(!this.EdgeSeparationIsOk(i,t.get(i),e))return!1;return!0}EdgeSeparationIsOk(t,e,i){return Array.from(e).map(n=>this.bundlingSettings.ActualEdgeWidth(n,i)).reduce((n,o)=>n+o,0)<=t.Capacity}RouteSelfEdges(){for(const t of this.edgesToRoute)if(t.source===t.target){const e={smoothedPolyline:null};t.curve=Ne.RouteSelfEdge(t.source.boundaryCurve,this.LoosePadding*2,e)}}FixArrowheads(){for(const t of this.edgesToRoute)Mt.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,t.curve,!1)}}Qr.SuperLoosePaddingCoefficient=1.1;class mc{constructor(t,e,i){this.numberOfPassedPaths=0,this.VisibilityEdge=t,this.Source=e,this.Target=i}get TargetPoint(){return this.Target.Point}get SourcePoint(){return this.Source.Point}get IsOccupied(){return this.numberOfPassedPaths>0}get IsPassable(){return this.Target.IsTargetOfRouting||this.Source.IsSourceOfRouting||this.VisibilityEdge.IsPassable==null||this.VisibilityEdge.IsPassable()}AddOccupiedEdge(){this.numberOfPassedPaths++}RemoveOccupiedEdge(){this.numberOfPassedPaths--}}class Pc{constructor(t){this.InBoneEdges=new Array,this.OutBoneEdges=new Array,this.VisibilityVertex=t}get Prev(){return this.PrevEdge==null?null:this.PrevEdge.Source===this?this.PrevEdge.Target:this.PrevEdge.Source}get Point(){return this.VisibilityVertex.point}get Cost(){return this.IsSourceOfRouting?this.cost:this.Prev==null?Number.POSITIVE_INFINITY:this.cost}set Cost(t){this.cost=t}SetPreviousToNull(){this.PrevEdge=null}}class zs{constructor(t,e,i){this.EdgesToRoutes=new Map,this.EdgesToRouteSources=new Map,this.MakeTransparentShapesOfEdgeGeometry=t,this.cdt=e,this.Gates=i}CreateGraphElements(){for(const t of this.vertexArray){const e=t.VisibilityVertex;for(const i of e.InEdges){const s=new mc(i,this.VisibilityVerticesToSdVerts.get(i.Source),this.VisibilityVerticesToSdVerts.get(i.Target)),n=this.VisibilityVerticesToSdVerts.get(i.Source);t.InBoneEdges.push(s),n.OutBoneEdges.push(s)}}}CreateRoutingGraph(){this.vertexArray=[],this.VisibilityVerticesToSdVerts=new Map;for(const t of this.VisibilityGraph.Vertices()){const e=new Pc(t);this.vertexArray.push(e),this.VisibilityVerticesToSdVerts.set(t,e)}this.CreateGraphElements()}RouteEdges(){this.Initialize(),this.RestoreCapacities();for(const t of this.geomEdges)this.EdgesToRoutes.set(t,this.RouteEdge(t));this.RerouteEdges();for(const t of this.geomEdges)this.SetEdgeGeometryCurve(t)}SetEdgeGeometryCurve(t){const e=new at;let i=this.EdgesToRouteSources.get(t);e.addPoint(i.Point);for(const o of this.EdgesToRoutes.get(t))o.SourcePoint.equal(i.Point)?(e.addPoint(o.TargetPoint),i=o.Target):(e.addPoint(o.SourcePoint),i=o.Source);t.curve=e,t.sourcePort instanceof Ge&&zs.ExtendPolylineStartToClusterBoundary(e,t.sourcePort.Curve),t.targetPort instanceof Ge&&zs.ExtendPolylineEndToClusterBoundary(e,t.targetPort.Curve)}static ExtendPolylineEndToClusterBoundary(t,e){const i=e.closestParameter(t.end);t.addPoint(e.value(i))}static ExtendPolylineStartToClusterBoundary(t,e){const i=e.closestParameter(t.start);t.PrependPoint(e.value(i))}RerouteEdges(){this.RestoreCapacities();for(const t of this.geomEdges){const e=this.RerouteEdge(t);this.EdgesToRoutes.set(t,e)}}RestoreCapacities(){this.cdt!=null&&this.cdt.RestoreEdgeCapacities()}RerouteEdge(t){const e=this.EdgesToRoutes.get(t);for(const i of e)i.RemoveOccupiedEdge();return this.RouteEdge(t)}RouteEdge(t){this.CurrentEdgeGeometry=t;for(let s=0;s<this.vertexArray.length;s++){const n=this.vertexArray[s];n.SetPreviousToNull(),n.IsTargetOfRouting=n.IsSourceOfRouting=!1}const e=this.MakeTransparentShapesOfEdgeGeometry(t),i=this.RouteEdgeWithGroups();for(const s of e)s.IsTransparent=!1;return i}RouteEdgeWithGroups(){for(let t=0;t<2;t++){this.SetLengthCoefficient(),this.Queue=new es,this.sourceLoosePoly=this.SetPortVerticesAndObstacles(this.CurrentEdgeGeometry.sourcePort,!0),this.targetLoosePoly=this.SetPortVerticesAndObstacles(this.CurrentEdgeGeometry.targetPort,!1);const e=this.RouteOnKnownSourceTargetVertices(this.CurrentEdgeGeometry.targetPort.Location.sub(this.CurrentEdgeGeometry.sourcePort.Location).normalize(),t===0);if(e!=null)return e;for(let i=0;i<this.vertexArray.length;i++)this.vertexArray[i].SetPreviousToNull()}throw new Error}RouteOnKnownSourceTargetVertices(t,e){for(this.LowestCostToTarget=Number.POSITIVE_INFINITY,this.ClosestTargetVertex=null;this.Queue.count>0;){const i={priority:0},s=this.Queue.DequeueAndGetPriority(i);if(!(i.priority>=this.LowestCostToTarget)){for(let n=0;n<s.OutBoneEdges.length;n++){const o=s.OutBoneEdges[n];o.IsPassable&&this.ProcessOutcomingBoneEdge(s,o,t,e)}for(let n=0;n<s.InBoneEdges.length;n++){const o=s.InBoneEdges[n];o.IsPassable&&this.ProcessIncomingBoneEdge(s,o,t,e)}}}return this.GetPathAndUpdateRelatedCosts()}ProcessOutcomingBoneEdge(t,e,i,s){s&&i.dot(e.TargetPoint.sub(e.SourcePoint))<0||this.ProcessBoneEdge(t,e.Target,e)}ProcessIncomingBoneEdge(t,e,i,s){s&&i.dot(e.SourcePoint.sub(e.TargetPoint))<0||this.ProcessBoneEdge(t,e.Source,e)}ProcessBoneEdge(t,e,i){const s=this.GetEdgeAdditionalCost(i,t.Cost);if(!(e.Cost<=s))if(e.Cost=s,e.PrevEdge=i,this.Queue.ContainsElement(e))this.Queue.DecreasePriority(e,s);else{if(e.IsTargetOfRouting){let n=0;this.CurrentEdgeGeometry.targetPort instanceof Ge&&(n=this.LengthCoefficient*e.Point.sub(this.CurrentEdgeGeometry.targetPort.Location).length),s+n<this.LowestCostToTarget&&(this.LowestCostToTarget=s+n,this.ClosestTargetVertex=e);return}this.Enqueue(e)}}GetPathAndUpdateRelatedCosts(){let t=this.ClosestTargetVertex;if(t==null)return null;const e=new Array;for(;t.PrevEdge!=null;)e.push(t.PrevEdge),this.RegisterPathInBoneEdge(t.PrevEdge),t=t.Prev;return this.EdgesToRouteSources.set(this.CurrentEdgeGeometry,t),e.reverse(),e}RegisterPathInBoneEdge(t){t.AddOccupiedEdge(),this.cdt!=null&&this.BundlingSettings.CapacityOverflowCoefficient!==0&&this.UpdateResidualCostsOfCrossedCdtEdges(t)}UpdateResidualCostsOfCrossedCdtEdges(t){for(const e of t.CrossedCdtEdges)this.AdjacentToSourceOrTarget(e)||(e.ResidualCapacity===e.Capacity?e.ResidualCapacity-=this.BundlingSettings.edgeWidthShrinkCoeff*this.CurrentEdgeGeometry.lineWidth:e.ResidualCapacity-=this.BundlingSettings.ActualEdgeWidth(this.CurrentEdgeGeometry))}H(t){return t.Cost+this.LengthCoefficient*t.Point.sub(this.CurrentEdgeGeometry.targetPort.Location).length}GetEdgeAdditionalCost(t,e){const i=t.TargetPoint.sub(t.SourcePoint).length;return this.LengthCoefficient*i+e+(t.IsOccupied?0:this.BundlingSettings.InkImportance*i)+this.CapacityOverflowCost(t)}CapacityOverflowCost(t){if(this.cdt==null||this.BundlingSettings.CapacityOverflowCoefficient===0)return 0;let e=0;for(const i of this.CrossedCdtEdgesOfBoneEdge(t))e+=this.CostOfCrossingCdtEdgeLocal(this.capacityOverlowPenaltyMultiplier,this.BundlingSettings,this.CurrentEdgeGeometry,i);return e}CrossedCdtEdgesOfBoneEdge(t){return t.CrossedCdtEdges!=null?Array.from(t.CrossedCdtEdges):Array.from(t.CrossedCdtEdges=this.ThreadBoneEdgeThroughCdt(t))}ThreadBoneEdgeThroughCdt(t){const e=t.SourcePoint,i=t.Source.Triangle,s=new Set,n=t.TargetPoint;if(ue.PointIsInsideOfTriangle(n,i))return s;const o=new qo(i,e,n);for(;o.MoveNext();){const a=o.CurrentPiercedEdge;this.Gates.has(a)&&s.add(a)}return s}static CostOfCrossingCdtEdge(t,e,i,s){let n=i.lineWidth*e.edgeWidthShrinkCoeff;s.Capacity!==s.ResidualCapacity&&(n+=e.EdgeSeparation*e.edgeWidthShrinkCoeff);const o=s.ResidualCapacity-n;return o>=0?0:-o*t}CostOfCrossingCdtEdgeLocal(t,e,i,s){return this.AdjacentToSourceOrTarget(s)?0:zs.CostOfCrossingCdtEdge(t,e,i,s)}AdjacentToSourceOrTarget(t){return t.upperSite.Owner===this.sourceLoosePoly||t.lowerSite.Owner===this.sourceLoosePoly||t.upperSite.Owner===this.targetLoosePoly||t.lowerSite.Owner===this.targetLoosePoly}SetLengthCoefficient(){const t=this.GetIdealDistanceBetweenSourceAndTarget(this.CurrentEdgeGeometry);this.LengthCoefficient=this.BundlingSettings.PathLengthImportance/t}GetIdealDistanceBetweenSourceAndTarget(t){return t.sourcePort.Location.sub(t.targetPort.Location).length}SetPortVerticesAndObstacles(t,e){let i;if(t instanceof Ge){i=t.LoosePolyline;for(const n of i){let o=0;e&&(o=this.LengthCoefficient*n.sub(this.CurrentEdgeGeometry.sourcePort.Location).length),this.AddAndEnqueueVertexToEnds(n,e,o)}}else if(t instanceof Kt){i=t.LoosePolyline;for(const n of i)this.AddAndEnqueueVertexToEnds(n,e,0)}else{this.AddAndEnqueueVertexToEnds(t.Location,e,0);const s=Array.from(this.ObstacleHierarchy.GetNodeItemsIntersectingRectangle(t.Curve.boundingBox));let n=s[0].boundingBox.diagonal;i=s[0];for(let o=1;o<s.length;o++){const a=s[o],h=a.boundingBox.diagonal;h<n&&(n=h,i=a)}}return i}Enqueue(t){this.Queue.Enqueue(t,this.H(t))}AddAndEnqueueVertexToEnds(t,e,i){const s=this.FindVertex(t),n=this.VisibilityVerticesToSdVerts.get(s);e?(n.IsSourceOfRouting=!0,n.Cost=i,this.Enqueue(n)):n.IsTargetOfRouting=!0}FindVertex(t){return this.VisibilityGraph.FindVertex(t)}Initialize(){this.CreateRoutingGraph(),this.cdt!=null&&(this.capacityOverlowPenaltyMultiplier=zs.CapacityOverflowPenaltyMultiplier(this.BundlingSettings),this.SetVertexTriangles(),this.CalculateCapacitiesOfTrianglulation())}CalculateCapacitiesOfTrianglulation(){for(const t of this.Gates)zs.CalculateCdtEdgeCapacityForEdge(t)}static CalculateCdtEdgeCapacityForEdge(t){if(t.constrained||t.CwTriangle==null||t.CcwTriangle==null)return;const e=t.upperSite.Owner,i=t.lowerSite.Owner;if(e!==i){const s=Te.DistancePoint(new Te(e),t.lowerSite.point),n=Te.DistancePoint(new Te(i),t.upperSite.point);t.Capacity=(s+n)/2}}SetVertexTriangles(){const t=re(Array.from(this.cdt.GetTriangles()).map(i=>pe(i,i.BoundingBox()))),e=re(this.vertexArray.map(i=>pe(i,Z.mkOnPoints([i.Point]))));Me(t,e,(i,s)=>this.TryToAssigenTriangleToVertex(i,s))}TryToAssigenTriangleToVertex(t,e){e.Triangle==null&&ue.PointIsInsideOfTriangle(e.Point,t)&&(e.Triangle=t)}static CapacityOverflowPenaltyMultiplier(t){return t.CapacityOverflowCoefficient*(t.PathLengthImportance+t.InkImportance)}FillCrossedCdtEdges(t){for(const e of this.geomEdges){this.sourceLoosePoly=this.SetPortVerticesAndObstacles(e.sourcePort,!0),this.targetLoosePoly=this.SetPortVerticesAndObstacles(e.targetPort,!1);for(const i of this.EdgesToRoutes.get(e))for(const s of this.CrossedCdtEdgesOfBoneEdge(i))this.AdjacentToSourceOrTarget(s)||Nn(t,e,s)}}}class Qo{constructor(t,e,i,s,n){this.multiEdges=t,this.interactiveEdgeRouter=e,this.bundlingSettings=s,this.bundlingSettings.edgeWidthShrinkCoeff=1,this.transparentShapeSetter=n,this.nodeTree=Rn(i,o=>o.boundingBox)}run(){for(const t of this.GetIndependantPreGraphs())new Qr(t.edges,new zs(this.transparentShapeSetter,null,null),this.interactiveEdgeRouter.VisibilityGraph,this.bundlingSettings,this.interactiveEdgeRouter.LoosePadding,this.interactiveEdgeRouter.TightHierarchy,this.interactiveEdgeRouter.LooseHierarchy,null,null,null).run()}GetPortCurve(t){return this.nodeTree.FirstHitNodeWithPredicate(t.Location,(i,s)=>w.PointRelativeToCurveLocation(i,s)!==ft.Outside?$t.Stop:$t.Continue).UserData}GetIndependantPreGraphs(){const t=this.CreateInitialPregraphs();do{const e=t.length,i={preGraphs:t};if(this.UniteConnectedPreGraphs(i),e<=t.length)break}while(!0);return t}UniteConnectedPreGraphs(t){const e=Qo.GetIntersectionGraphOfPreGraphs(t.preGraphs);if(e==null)return;const i=Vi(e),s=new Array;for(const n of i){let o=null;for(const a of n)o==null?(o=t.preGraphs[a],s.push(o)):o.AddGraph(t.preGraphs[a])}t.preGraphs=s;for(const n of t.preGraphs)this.AddIntersectingNodes(n)}AddIntersectingNodes(t){const e=t.boundingBox;for(const i of this.nodeTree.GetNodeItemsIntersectingRectangle(e))t.AddNodeBoundary(i)}static GetIntersectionGraphOfPreGraphs(t){const e=Qo.EnumeratePairsOfIntersectedPreGraphs(t);return e.length?ni(e,t.length):null}static EnumeratePairsOfIntersectedPreGraphs(t){const e=Array.from(Array(t.length).keys()),i=Rn(e,n=>t[n].boundingBox),s=new Array;return Ae(i,i,(n,o)=>s.push(new Ot(n,o))),s}CreateInitialPregraphs(){return this.multiEdges.map(t=>this.CreatePregraphFromSetOfEdgeGeometries(t))}CreatePregraphFromSetOfEdgeGeometries(t){const e=new Set,i=t[0],s=this.GetPortCurve(i.sourcePort),n=s.boundingBox;e.add(s),e.add(i.targetPort.Curve),n.addRec(i.targetPort.Curve.boundingBox);const o=this.nodeTree.GetNodeItemsIntersectingRectangle(n);for(const a of o)e.add(a);return La.constructorStatic(t,e)}}let Qd=0,Yd=0;class Sc{constructor(){this.triangles=new Set}setCdt(t){this.cdt=t,this.cdt.SetInEdges();const e=new Set;for(const i of t.GetTriangles())for(const s of i.Sites)s.Owner!=null&&e.add(s.Owner)}outsideOfObstacles(t){var e;if(t==null)return!1;const i=(e=t.Sites.item0.Owner)!==null&&e!==void 0?e:t.Sites.item1.Owner;return i===this.sourcePoly||i===this.targetPoly||!yc(t)}run(t){if(this.triangles.clear(),this.poly=t,this.d=[],t.count<=2||this.cdt==null)return;this.sourcePoly=this.findPoly(t.start),this.targetPoly=this.findPoly(t.end),this.findChannelTriangles();let e=this.getPerimeterEdges();e=this.fillTheCollapedSites(e);const i=new ue([],[],Array.from(e).map(n=>({A:n.lowerSite.point,B:n.upperSite.point})));i.run();const s=this.getSleeve(this.findSourceTriangle(i));if(s==null){console.log("failed to create sleeve");return}if(s.length==0){this.poly=at.mkFromPoints([t.start,t.end]);return}this.initDiagonals(s),this.refineFunnel()}getAllCrossedTriangles(t,e,i){let s=[],n=[],o=null;for(n.push(t);n.length>0;){let a=n.pop();if(o==null&&a.containsPoint(i)&&(o=a),a.intersectsLine(e,i,0)){s.push(a);for(const h of a.Edges){const u=h.GetOtherTriangle_T(a);u&&!s.includes(u)&&!n.includes(u)&&n.push(u)}}}return{triangles:s,containsEnd:o}}findChannelTriangles(){let e=this.cdt.FindSite(this.poly.start).Triangles().next().value;this.triangles.clear();for(let i=this.poly.startPoint;i.next!=null;i=i.next){const s=this.getAllCrossedTriangles(e,i.point,i.next.point);e=s.containsEnd;for(const n of s.triangles)this.outsideOfObstacles(n)&&this.triangles.add(n)}}findPoly(t){var e;const i=this.cdt.FindSite(t);for(const s of i.Edges)return(e=s.lowerSite.Owner)!==null&&e!==void 0?e:s.upperSite.Owner}fillTheCollapedSites(t){const e=new Map;for(const n of t)s(n.lowerSite,n),s(n.upperSite,n);const i=[];for(const[n,o]of e)o.length>2&&i.push(n);if(i.length==0)return t;for(const n of i)for(const o of n.Triangles())this.outsideOfObstacles(o)&&this.triangles.add(o);return this.getPerimeterEdges();function s(n,o){let a=e.get(n);a==null&&e.set(n,a=[]),a.push(o)}}findSourceTriangle(t){let e;for(const i of t.GetTriangles())if(i.containsPoint(this.poly.start)){e=i;break}return e}refineFunnel(){const t=[];let e=this.poly.start;const i={point:e},s={point:e};let n={point:this.d[0].left,prev:i},o={point:this.d[0].right,prev:s};i.next=n,s.next=o;let a;for(let Q=1;Q<this.d.length;Q++)u(Q,this.d);this.d.push({right:this.poly.end,left:n.point}),u(this.d.length-1,this.d);const h=at.mkFromPoints(t);for(let Q=s;Q!=null;Q=Q.next)h.addPoint(Q.point);this.poly=h;function u(Q,pt){if(pt[Q-1].left!==pt[Q].left){a=pt[Q].left;let Bt=n;for(;!(q(Bt)||S(Bt));Bt=Bt.prev);q(Bt)?I():ct(Bt)}else{a=pt[Q].right;let Bt=o;for(;!(q(Bt)||A(Bt));Bt=Bt.prev);q(Bt)?B():rt(Bt)}}function c(Q){return Q.next==null?!0:d.pointToTheLeftOfLineOrOnLine(a,Q.point,Q.next.point)}function m(Q){return Q.next==null?!0:d.pointToTheRightOfLineOrOnLine(a,Q.point,Q.next.point)}function S(Q){return d.pointToTheLeftOfLine(a,Q.prev.point,Q.point)}function A(Q){return d.pointToTheRightOfLine(a,Q.prev.point,Q.point)}function I(){let Q=s;for(;!c(Q);)Q=Q.next;if(!q(Q)){let pt=s;for(;!pt.point.equal(Q.point);pt=pt.next)t.push(pt.point);s.point=pt.point,s.next=pt.next,e=pt.point,o.point.equal(s.point)&&(o.prev=o.next=null)}i.point=e,n.point=a,n.prev=i,i.next=n}function B(){let Q=i;for(;!m(Q);)Q=Q.next;if(!q(Q)){let pt=i;for(;!pt.point.equal(Q.point);pt=pt.next)t.push(pt.point);i.point=pt.point,i.next=pt.next,e=pt.point,n.point.equal(i.point)&&(n.prev=i.next=null)}s.point=e,o.point=a,o.prev=s,s.next=o}function q(Q){return Q.point==e}function rt(Q){Q!=o?(o.point=a,o.prev=Q,Q.next=o):(o={point:a,prev:Q},Q.next=o)}function ct(Q){Q!=n?(n.point=a,n.prev=Q,Q.next=n):(n={point:a,prev:Q},Q.next=n)}}initDiagonals(t){for(const e of t){const i=e.edge,s=e.source.OppositeSite(i);d.getTriangleOrientation(s.point,i.lowerSite.point,i.upperSite.point)==k.Counterclockwise?this.d.push({left:i.upperSite.point,right:i.lowerSite.point}):this.d.push({right:i.upperSite.point,left:i.lowerSite.point})}}getSleeve(t){const e=new hi.o;e.enqueue(t);const i=new Map;for(i.set(t,void 0);e.length>0;){const s=e.dequeue(),n=i.get(s);if(s.containsPoint(this.poly.end))return this.recoverPath(t,i,s);for(const o of s.Edges){if(o.constrained||n!==void 0&&o===n)continue;const a=o.GetOtherTriangle_T(s);a!=null&&(i.has(a)||(i.set(a,o),e.enqueue(a)))}}}recoverPath(t,e,i){const s=[];for(let n=i;n!=t&&n!==t;){const o=e.get(n);n=o.GetOtherTriangle_T(n),s.push({source:n,edge:o})}return s.reverse()}getPerimeterEdges(){const t=new Set;for(const e of this.triangles)for(const i of e.Edges)this.triangles.has(i.GetOtherTriangle_T(e))||t.add(i);return t}}function yc(l){return l.Sites.item0.Owner==null||l.Sites.item1.Owner==null||l.Sites.item2.Owner==null?!0:l.Sites.item0.Owner==l.Sites.item1.Owner&&l.Sites.item0.Owner==l.Sites.item2.Owner}class Zt extends zt{constructor(t,e,i=1,s=2,n=30*(Math.PI/180),o=null,a=null){super(a),this.continueOnOverlaps=!0,this.shapesToTightLooseCouples=new Map,this.multiEdgesSeparation=.5,this.routeMultiEdgesAsBundles=!0,this.UsePolylineEndShortcutting=!0,this.UseInnerPolylingShortcutting=!0,this.AllowedShootingStraightLines=!0,this._overlapsDetected=!1,this.edges=e,this.BundlingSettings=o,this.geomGraph=t,this.LoosePadding=s,this.tightPadding=i,this.coneAngle=n,this.routeMultiEdgesAsBundles=e.length<1e3&&t.deepNodeCount<1e3}get ContinueOnOverlaps(){return this.continueOnOverlaps}set ContinueOnOverlaps(t){this.continueOnOverlaps=t}get LoosePadding(){return this.loosePadding}set LoosePadding(t){this.loosePadding=t}get MultiEdgesSeparation(){return this.multiEdgesSeparation}set MultiEdgesSeparation(t){this.multiEdgesSeparation=t}static mk2(t,e){return Zt.mk5(t,e.Padding,e.PolylinePadding,e.ConeAngle,e.bundlingSettings)}static mk4(t,e,i,s){return new Zt(t,Array.from(t.deepEdges),e,i,s,null)}static mk5(t,e,i,s,n){return new Zt(t,Array.from(t.deepEdges),e,i,s,n)}static mk6(t,e,i,s,n,o){const a=Zt.mk4(t,e,i,s),h=Ii.GetShapes(n,o);return a.Initialize(h,s),a}Initialize(t,e){this.rootShapes=t.filter(i=>i.Parents==null||i.Parents.length===0),this.coneAngle=e,this.coneAngle===0&&(this.coneAngle=Math.PI/6)}run(){if(this.edges.length==0||this.geomGraph.isEmpty())return;console.time("SplineRouter");const t=Ve.GetShapes(this.geomGraph,this.edges);this.BundlingSettings==null&&this.geomGraph.layoutSettings&&this.geomGraph.layoutSettings.commonSettings.edgeRoutingSettings&&this.geomGraph.layoutSettings.commonSettings.edgeRoutingSettings.bundlingSettings&&(this.BundlingSettings=this.geomGraph.layoutSettings.commonSettings.edgeRoutingSettings.bundlingSettings),this.Initialize(t,this.coneAngle),this.GetOrCreateRoot(),this.RouteOnRoot(),this.RemoveRoot(),console.timeEnd("SplineRouter")}rerouteOnSubsetOfNodes(t){this.RouteMultiEdgesAsBundles=!1,this.edges=Array.from(this.geomGraph.deepEdges).filter(i=>kn(i.edge,t));const e=Ve.GetShapes(this.geomGraph,this.edges);this.rootShapes=e.filter(i=>i.Parents==null||i.Parents.length===0),this.GetOrCreateRoot(),this.CalculateShapeToBoundaries(this.root),this.calcLooseShapesToNodes(),this.CalculatePortsToShapes(),this.rerouteOnActiveNodes(t),this.RemoveRoot()}calcLooseShapesToNodes(){if(this.loosePolylinesToNodes=new Map,!this.OverlapsDetected){for(const[i,s]of this.shapesToTightLooseCouples)this.loosePolylinesToNodes.set(s.LooseShape.BoundaryCurve,new Set([i.node.node]));return}const t=Rn(this.geomGraph.nodesBreadthFirst,i=>i.boundingBox),e=this.GetLooseHierarchy();Me(e,t,(i,s)=>{if(w.CurveIsInsideOther(s.boundaryCurve,i)){let n=this.loosePolylinesToNodes.get(i);for(const o of s.getAncestors())if(!(o instanceof Xt&&o.parent==null)&&o.boundaryCurve!=null&&w.CurveIsInsideOther(o.boundaryCurve,i))return;n==null&&this.loosePolylinesToNodes.set(i,n=new Set),n.add(s.node)}})}RouteOnRoot(){Os(0),this.CalculatePortsToShapes(),this.CalculatePortsToEnterableShapes(),this.CalculateShapeToBoundaries(this.root),!(this.OverlapsDetected&&!this.ContinueOnOverlaps)&&(this.BindLooseShapes(),this.SetLoosePolylinesForAnywherePorts(),this.CalculateVisibilityGraph(),this.RouteOnVisGraph())}CalculatePortsToEnterableShapes(){this.portsToEnterableShapes=new Map;for(const[t,e]of this.portsToShapes){const i=new Set;Zt.EdgesAttachedToPortAvoidTheNode(t)||i.add(e),this.portsToEnterableShapes.set(t,i)}for(const t of this.rootShapes)for(const e of t.Descendants())for(const i of e.Ports){const s=this.portsToEnterableShapes.get(i);Js(s,Array.from(e.Ancestors()).filter(n=>n.BoundaryCurve!=null))}}static EdgesAttachedToPortAvoidTheNode(t){return t instanceof R||t instanceof Ge}SetLoosePolylinesForAnywherePorts(){for(const[t,e]of this.shapesToTightLooseCouples)for(const i of t.Ports){if(i instanceof Kt){const n=i;n.LoosePolyline=e.LooseShape.BoundaryCurve}if(i instanceof Ge){const n=i;n.LoosePolyline=e.LooseShape.BoundaryCurve}}}BindLooseShapes(){this.looseRoot=new Es;for(const t of this.root.Children){const e=this.shapesToTightLooseCouples.get(t).LooseShape;this.BindLooseShapesUnderShape(t),this.looseRoot.AddChild(e)}}BindLooseShapesUnderShape(t){const e=this.shapesToTightLooseCouples.get(t).LooseShape;for(const i of t.Children){const s=this.shapesToTightLooseCouples.get(i).LooseShape;e.AddChild(s),this.BindLooseShapesUnderShape(i)}}CalculateShapeToBoundaries(t){if(this.ProgressStep(),t.Children.length===0)return;for(const i of t.Children)this.CalculateShapeToBoundaries(i);let e=Number.POSITIVE_INFINITY;if(t instanceof rn){const s=t.node.padding;this.tightPadding=Math.min(this.tightPadding,.4*s),e=.4*s}this.obstacleCalculator=new hn(t,this.tightPadding,Math.min(this.AdjustedLoosePadding,e),this.shapesToTightLooseCouples),this.obstacleCalculator.Calculate(.01),this.OverlapsDetected||(this.OverlapsDetected=this.obstacleCalculator.OverlapsDetected)}get OverlapsDetected(){return this._overlapsDetected}set OverlapsDetected(t){this._overlapsDetected=t}get AdjustedLoosePadding(){return this.BundlingSettings==null?this.LoosePadding:this.LoosePadding*Qr.SuperLoosePaddingCoefficient}GroupEdgesByPassport(){const t=new Array;for(const e of this.edges){const i=this.EdgePassport(e);let s=t.find(n=>Dn(n.passport,i));s||(s={passport:i,edges:[]},t.push(s)),s.edges.push(e)}return t}RouteOnVisGraph(){if(this.ancestorSets=Zt.GetAncestorSetsMap(Array.from(this.root.Descendants())),this.BundlingSettings==null){const t=this.GroupEdgesByPassport();for(let e=0;e<t.length;e++){const i=t[e],s=i.passport,n=this.GetObstaclesFromPassport(s),o=this.CreateInteractiveEdgeRouter(Array.from(n));this.RouteEdgesWithTheSamePassport(i,o,n)}}else this.RouteBundles()}rerouteOnActiveNodes(t){if(this.ancestorSets=Zt.GetAncestorSetsMap(Array.from(this.root.Descendants())),this.BundlingSettings==null)for(const e of this.GroupEdgesByPassport()){const i=e.passport,s=this.GetObstaclesFromPassport(i),n=new Set;for(const a of s){const h=this.LooseShapeOfOriginalShape(a);for(const u of this.loosePolylinesToNodes.get(h.BoundaryCurve))t.has(u)&&n.add(a)}const o=this.CreateInteractiveEdgeRouter(Array.from(n));this.rerouteEdgesWithTheSamePassportActiveNodes(e,o,n,t)}else this.RouteBundles()}getDebugCurvesFromEdgesAndCdt(t){const e=Array.from(this.geomGraph.deepEdges).map(i=>i.curve).filter(i=>i!=null).filter(i=>i.count>5).map(i=>It.mkDebugCurveTWCI(200,1,"Red",i));for(const i of t.PointsToSites.values())for(const s of i.Edges)e.push(It.mkDebugCurveTWCI(200,.5,s.constrained?"Blue":"Green",D.mkPP(s.lowerSite.point,s.upperSite.point)));return e}RouteEdgesWithTheSamePassport(t,e,i){const s={regularEdges:[],multiEdges:[]};try{const n=this.getCdtFromPassport(i);e.pathOptimizer.setCdt(n)}catch{e.pathOptimizer.setCdt(null)}if(this.RouteMultiEdgesAsBundles){if(this.SplitOnRegularAndMultiedges(t.edges,s),s.regularEdges.length>0)for(let n=0;n<s.regularEdges.length;n++)this.routeEdge(e,s.regularEdges[n]);s.multiEdges!=null&&(this.ScaleDownLooseHierarchy(e,i),this.RouteMultiEdges(s.multiEdges,e,t.passport))}else for(let n=0;n<t.edges.length;n++)this.routeEdge(e,t.edges[n])}rerouteEdgesWithTheSamePassportActiveNodes(t,e,i,s){const n={regularEdges:[],multiEdges:[]};try{const o=this.getCdtFromPassport(i);e.pathOptimizer.setCdt(o)}catch(o){console.log(o),e.pathOptimizer.setCdt(null)}if(this.RouteMultiEdgesAsBundles){if(this.SplitOnRegularAndMultiedges(t.edges,n),n.regularEdges.length>0)for(let o=0;o<n.regularEdges.length;o++){const a=n.regularEdges[o];Ht.assert(kn(a.edge,s)),this.rerouteEdge(e,a)}n.multiEdges!=null&&(this.ScaleDownLooseHierarchy(e,i),this.RouteMultiEdges(n.multiEdges,e,t.passport))}else for(let o=0;o<t.edges.length;o++){const a=t.edges[o];kn(a.edge,s)&&this.rerouteEdge(e,a)}}rerouteEdge(t,e){try{t.rerouteEdge(e),Mt.trimSplineAndCalculateArrowheadsII(e,e.sourcePort.Curve,e.targetPort.Curve,e.curve,!1)}catch{console.log("failed")}}getCdtFromPassport(t){const e=new Set,i=[],s=Z.mkEmpty();for(const a of t){const h=this.LoosePolyOfOriginalShape(a);if(h!=null){e.add(h);for(const u of a.Ports)i.push(u.Location);s.addRecSelf(h.boundingBox)}}s.pad(Math.max(s.diagonal/4,100));const n=Array.from(e);n.push(s.perimeter());const o=new ue(i,n,[]);return o.run(),o}get RouteMultiEdgesAsBundles(){return this.routeMultiEdgesAsBundles}set RouteMultiEdgesAsBundles(t){this.routeMultiEdgesAsBundles=t}routeEdge(t,e){const i=this.makeTransparentShapesOfEdgeAndGetTheShapes(e);this.ProgressStep(),this.RouteEdgeInternal(e,t),Zt.SetTransparency(i,!1)}ScaleDownLooseHierarchy(t,e){const i=new Array;for(const s of e){const n=this.shapesToTightLooseCouples.get(s);i.push(mt.LoosePolylineWithFewCorners(n.TightPolyline,n.Distance/1.1,0))}t.LooseHierarchy=Zt.CreateLooseObstacleHierarachy(i),t.ClearActivePolygons(),t.AddActivePolygons(i.map(s=>new Te(s)))}RouteMultiEdges(t,e,i){const s=[];for(const a of i)for(const h of a.Children)s.push(h.BoundaryCurve);const n=new ge;n.InkImportance=1e-5,n.EdgeSeparation=this.MultiEdgesSeparation,new Qo(t,e,s,n,a=>this.makeTransparentShapesOfEdgeAndGetTheShapes(a)).run()}SplitOnRegularAndMultiedges(t,e){const i=new Bs;for(const s of t)Zt.IsEdgeToParent(s)?e.regularEdges.push(s):Zt.RegisterInPortLocationsToEdges(s,i);e.multiEdges=null;for(const s of i.values())s.length===1||this.OverlapsDetected?Ki(e.regularEdges,s):(e.multiEdges==null&&(e.multiEdges=new Array),e.multiEdges.push(s))}static RegisterInPortLocationsToEdges(t,e){let i;const s=new ve(t.sourcePort.Location,t.targetPort.Location);i=e.get(s),i||(i=new Array,e.set(s,i)),i.push(t)}static IsEdgeToParent(t){return t.sourcePort instanceof Kt||t.targetPort instanceof Kt}CreateInteractiveEdgeRouter(t){const e=new Set(t.map(s=>this.shapesToTightLooseCouples.get(s).LooseShape.BoundaryCurve)),i=new Pt(this.cancelToken);return i.pathOptimizer=new Sc,i.ObstacleCalculator=new mt(t.map(s=>s.BoundaryCurve),this.tightPadding,this.loosePadding,!1),i.VisibilityGraph=this.visGraph,i.TightHierarchy=this.CreateTightObstacleHierarachy(t),i.LooseHierarchy=Zt.CreateLooseObstacleHierarachy(Array.from(e)),i.UseSpanner=!0,i.LookForRoundedVertices=!0,i.TightPadding=this.tightPadding,i.LoosePadding=this.LoosePadding,i.UseEdgeLengthMultiplier=this.UseEdgeLengthMultiplier,i.UsePolylineEndShortcutting=this.UsePolylineEndShortcutting,i.UseInnerPolylingShortcutting=this.UseInnerPolylingShortcutting,i.AllowedShootingStraightLines=this.AllowedShootingStraightLines,i.AddActivePolygons(Array.from(e).map(s=>new Te(s))),i}GetObstaclesFromPassport(t){if(t.size===0)return new Set(this.root.Children);const e=this.GetCommonAncestorsAbovePassport(t),i=this.GetAllAncestors(t),s=new Set;for(const a of t)for(const h of a.Children)i.has(h)||s.add(h);const n=Ss(new Set(t),s),o=new hi.o;for(const a of t)e.has(a)||o.enqueue(a);for(;o.length>0;){const a=o.dequeue();for(const h of a.Parents){for(const u of h.Children)i.has(u)||s.add(u);!e.has(h)&&!n.has(h)&&(o.enqueue(h),n.add(h))}}return s}GetAllAncestors(t){if(t.size===0)return new Set;let e=new Set(t);for(const i of t)e=Ss(e,this.ancestorSets.get(i));return e}GetCommonAncestorsAbovePassport(t){if(t.size===0)return new Set;const e=Array.from(t);let i=this.ancestorSets.get(e[0]);for(let s=1;s<e.length;s++){const n=e[s];i=Ji(i,this.ancestorSets.get(n))}return i}RouteBundles(){this.ScaleLooseShapesDown(),this.CalculateEdgeEnterablePolylines();const t=this.GetLooseHierarchy(),e=Nl(t),i=new zs(n=>this.makeTransparentShapesOfEdgeAndGetTheShapes(n),e,this.FindCdtGates(e));new Qr(this.edges,i,this.visGraph,this.BundlingSettings,this.LoosePadding,this.GetTightHierarchy(),t,this.enterableLoose,this.enterableTight,n=>this.LoosePolyOfOriginalShape(this.portsToShapes.get(n))).run()}CreateTheMapToParentLooseShapes(t,e){for(const i of t.Children){const n=this.shapesToTightLooseCouples.get(i).LooseShape.BoundaryCurve;e.set(n,t),this.CreateTheMapToParentLooseShapes(i,e)}}FindCdtGates(t){const e=new Map;this.CreateTheMapToParentLooseShapes(this.root,e);const i=new Set;for(const s of t.PointsToSites.values())for(const n of s.Edges){if(n.CwTriangle==null&&n.CcwTriangle==null)continue;const o=s.Owner,a=n.lowerSite.Owner;if(o===a)continue;const h=e.get(o);if(h){const u=e.get(a);h===u&&i.add(n)}}return i}CalculateEdgeEnterablePolylines(){this.enterableLoose=new Map,this.enterableTight=new Map;for(const t of this.edges){const e=new Set,i=new Set;this.GetEdgeEnterablePolylines(t,e,i),this.enterableLoose.set(t,e),this.enterableTight.set(t,i)}}GetEdgeEnterablePolylines(t,e,i){const s=this.portsToShapes.get(t.sourcePort),n=this.portsToShapes.get(t.targetPort);s!==this.root&&this.GetEnterablesForShape(s,e,i),n!==this.root&&this.GetEnterablesForShape(n,e,i)}GetEnterablesForShape(t,e,i){for(const s of this.ancestorSets.get(t)){const n=this.LoosePolyOfOriginalShape(s);n&&e.add(n);const o=this.TightPolyOfOriginalShape(s);o&&i.add(o)}}GetTightHierarchy(){return re(Array.from(this.shapesToTightLooseCouples.values()).map(t=>pe(t.TightPolyline,t.TightPolyline.boundingBox)))}GetLooseHierarchy(){const t=new Set;for(const e of this.shapesToTightLooseCouples.values())t.add(e.LooseShape.BoundaryCurve);return re(Array.from(t).map(e=>pe(e,e.boundingBox)))}ScaleLooseShapesDown(){for(const[,t]of this.shapesToTightLooseCouples)t.LooseShape.BoundaryCurve=mt.LoosePolylineWithFewCorners(t.TightPolyline,t.Distance/Qr.SuperLoosePaddingCoefficient,0)}EdgePassport(t){const e=new Set,i=this.portsToShapes.get(t.sourcePort),s=this.portsToShapes.get(t.targetPort);return this.IsAncestor(i,s)?(Js(e,s.Parents),e.add(i),e):this.IsAncestor(s,i)?(Js(e,i.Parents),e.add(s),e):(i!==this.looseRoot&&Js(e,i.Parents),s!==this.looseRoot&&Js(e,s.Parents),e)}*AllPorts(){for(const t of this.edges)yield t.sourcePort,yield t.targetPort}CalculatePortsToShapes(){this.portsToShapes=new Map;for(const t of this.root.Descendants())for(const e of t.Ports)this.portsToShapes.set(e,t);for(const t of this.AllPorts())this.portsToShapes.has(t)||(this.root.Ports.add(t),this.portsToShapes.set(t,this.root))}RouteEdgeInternal(t,e){const i=new Array;t.sourcePort instanceof Kt||Ki(i,this.AddVisibilityEdgesFromPort(t.sourcePort)),t.targetPort instanceof Kt||Ki(i,this.AddVisibilityEdgesFromPort(t.targetPort));const s={smoothedPolyline:null};if(d.closeDistEps(t.sourcePort.Location,t.targetPort.Location)?t.curve=Ne.RouteSelfEdge(t.sourcePort.Curve,Math.max(this.LoosePadding*2,t.GetMaxArrowheadLength()),s):t.curve=e.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(t.sourcePort,t.targetPort,!0,s),t.smoothedPolyline=null,t.curve==null)throw new Error;for(const n of i)se.RemoveEdge(n);Mt.trimSplineAndCalculateArrowheadsII(t,t.sourcePort.Curve,t.targetPort.Curve,t.curve,!1)}*AddVisibilityEdgesFromPort(t){let e,i;if(t instanceof R||!(e=this.portsToShapes.get(t))||!(i=this.shapesToTightLooseCouples.get(e)))return;const s=i.LooseShape;for(const n of s.BoundaryCurve)this.visGraph.FindEdgePP(t.Location,n)==null&&(yield this.visGraph.AddEdgePP(t.Location,n))}makeTransparentShapesOfEdgeAndGetTheShapes(t){const e=this.portsToShapes.get(t.sourcePort),i=this.portsToShapes.get(t.targetPort),s=new Array;for(const n of this.GetTransparentShapes(t.sourcePort,t.targetPort,e,i))n!=null&&s.push(this.LooseShapeOfOriginalShape(n));for(const n of this.portsToEnterableShapes.get(t.sourcePort))s.push(this.LooseShapeOfOriginalShape(n));for(const n of this.portsToEnterableShapes.get(t.targetPort))s.push(this.LooseShapeOfOriginalShape(n));return Zt.SetTransparency(s,!0),s}LooseShapeOfOriginalShape(t){return t===this.root?this.looseRoot:this.shapesToTightLooseCouples.get(t).LooseShape}LoosePolyOfOriginalShape(t){return this.LooseShapeOfOriginalShape(t).BoundaryCurve}TightPolyOfOriginalShape(t){return t===this.root?null:this.shapesToTightLooseCouples.get(t).TightPolyline}*GetTransparentShapes(t,e,i,s){for(const n of this.ancestorSets.get(i))yield n;for(const n of this.ancestorSets.get(s))yield n;Zt.EdgesAttachedToPortAvoidTheNode(t)||(yield i),Zt.EdgesAttachedToPortAvoidTheNode(e)||(yield s)}static SetTransparency(t,e){for(const i of t)i.IsTransparent=e}IsAncestor(t,e){let i;return e!=null&&(i=this.ancestorSets.get(e))!=null&&i.has(t)}static CreateLooseObstacleHierarachy(t){return re(t.map(e=>pe(e,e.boundingBox)))}CreateTightObstacleHierarachy(t){const e=t.map(i=>this.shapesToTightLooseCouples.get(i).TightPolyline);return re(e.map(i=>pe(i,i.boundingBox)))}CalculateVisibilityGraph(){const t=this.LineSweeperPorts!=null?ie.mk(this.LineSweeperPorts):new ie;this.ProcessHookAnyWherePorts(t),this.portRTree=tn(Array.from(t.values()).map(e=>[Z.rectangleOnPoint(e),e])),this.visGraph=new se,this.FillVisibilityGraphUnderShape(this.root)}static ShowVisGraph(t,e,i,s=null,n=null){const o=Array.from(e.Edges).map(a=>It.mkDebugCurveTWCI(100,1,a.IsPassable!=null&&a.IsPassable()?"green":"black",D.mkPP(a.SourcePoint,a.TargetPoint)));if(i!=null)for(const a of i){o.push(It.mkDebugCurveTWCI(100,.3,"brown",a));for(const h of a)o.push(It.mkDebugCurveTWCI(100,1,"green",H.mkCircle(1,h)))}if(s!=null)for(const a of s)o.push(It.mkDebugCurveTWCI(100,10,"navy",a));if(n!=null)for(const a of n)o.push(It.mkDebugCurveTWCI(100,10,"red",a))}ProcessHookAnyWherePorts(t){for(const e of this.edges)e.sourcePort instanceof Kt||e.sourcePort instanceof Ge||t.add(e.sourcePort.Location),e.targetPort instanceof Kt||e.targetPort instanceof Ge||t.add(e.targetPort.Location)}FillVisibilityGraphUnderShape(t){const e=t.Children;for(let c=0;c<e.length;c++){const m=e[c];this.FillVisibilityGraphUnderShape(m)}const i=this.shapesToTightLooseCouples.get(t),s=i?i.LooseShape.BoundaryCurve:null,n=i?i.LooseShape:this.looseRoot,o=new Set(n.Children.map(c=>c.BoundaryCurve)),a=this.RemoveInsidePortsAndSplitBoundaryIfNeeded(s);let h=new se,u=Mi.mk([],h,this.coneAngle,a,s);u.run(),h=new se,u=Mi.mk(Array.from(o),h,this.coneAngle,a,s),u.run(),this.ProgressStep();for(const c of h.Edges)this.TryToCreateNewEdgeAndSetIsPassable(c,n);this.AddBoundaryEdgesToVisGraph(s)}TryToCreateNewEdgeAndSetIsPassable(t,e){let i=this.visGraph.FindEdgePP(t.SourcePoint,t.TargetPoint);i==null&&(i=this.visGraph.AddEdgePP(t.SourcePoint,t.TargetPoint),e!=null&&(i.IsPassable=()=>e.IsTransparent))}AddBoundaryEdgesToVisGraph(t){if(t==null)return;let e;for(let i=t.startPoint;e=i.nextOnPolyline,this.visGraph.AddEdgePP(i.point,e.point),e!==t.startPoint;i=e);}RemoveInsidePortsAndSplitBoundaryIfNeeded(t){const e=new ie;if(t==null){for(const n of this.portRTree.GetAllLeaves())e.add(n);return this.portRTree.clear(),e}const i=t.boundingBox,s=this.portRTree.GetAllIntersecting(i);for(const n of s)switch(w.PointRelativeToCurveLocation(n,t)){case ft.Inside:e.add(n),this.portRTree.Remove(Z.rectangleOnPoint(n),n);break;case ft.Boundary:this.portRTree.Remove(Z.rectangleOnPoint(n),n);const o=Zt.FindPointOnPolylineToInsertAfter(t,n);if(o!=null)ht.InsertPointIntoPolylineAfter(t,o,n);else throw new Error;break}return e}static FindPointOnPolylineToInsertAfter(t,e){for(let i=t.startPoint;;){const s=i.nextOnPolyline;if(d.closeDistEps(e,i.point)||d.closeDistEps(e,s.point))return null;const n=d.distToLineSegment(e,i.point,s.point).dist;if(N(n,0))return i;if(i=s,i===t.startPoint)throw new Error}}GetOrCreateRoot(){if(this.rootShapes.length===1){const t=this.rootShapes[0];if(t.BoundaryCurve==null){this.root=t;return}}this.rootWasCreated=!0,this.root=new Es(null);for(const t of this.rootShapes)this.root.AddChild(t)}RemoveRoot(){if(this.rootWasCreated){for(const t of this.rootShapes)t.RemoveParent(this.root);this.root=null,this.rootWasCreated=!1}}static GetAncestorSetsMap(t){const e=new Map;for(const i of t.filter(s=>!e.has(s)))e.set(i,Zt.GetAncestorSet(i,e));return e}static GetAncestorSet(t,e){const i=new Set(t.Parents);for(const s of t.Parents){let n=e.get(s);n||e.set(s,n=Zt.GetAncestorSet(s,e));for(const o of n)i.add(o)}return i}static CreatePortsIfNeeded(t){for(const e of t){if(e.sourcePort==null){const i=e;new Xe(()=>i.source.boundaryCurve,()=>i.source.center,new d(0,0))}if(e.targetPort==null){const i=e;new Xe(()=>i.target.boundaryCurve,()=>i.target.center,new d(0,0))}}}}function Cc(l,t,e){const i=Zl(l);new Zt(l,t,i.Padding,i.PolylinePadding,i.coneAngle,i.bundlingSettings,e).run()}class Kd{constructor(t,e){this.numberOfNodesOnLevel=[],this.nodeScales=[],this.tileCapacity=500,this.levels=[],this.nodeIndexInSortedNodes=new Map,this.geomGraph=t,this.topLevelTileRect=e,this.tileSizes=[],this.tileSizes.push(e.size)}getTileData(t,e,i){const s=this.levels[i];return s?s.get(t,e):null}*getTilesOfLevel(t){const e=this.levels[t];if(e!=null)for(const[i,s]of e.keyValues())yield{x:i.x,y:i.y,data:s}}getMinTileSize(){let t=0,e=0,i=0;for(const s of this.geomGraph.nodesBreadthFirst)s instanceof GeomGraph||(i==0?(t=s.width,e=s.height):(t=(i*t+s.width)/(i+1),e=(i*e+s.height)/(i+1)),i++);return new Size(t*10,e*10)}fillTheLowestLayer(){const t=new IntPairMap,e=new Tile(this.topLevelTileRect),i=e.arrowheads,s=e.labels;for(const o of this.geomGraph.graph.deepEdges)n(o);e.nodes=Array.from(this.geomGraph.nodesBreadthFirst),t.set(0,0,e),this.levels.push(t);function n(o){const a=GeomEdge.getGeom(o),h=GeomEdge.getGeom(o).curve;if(h instanceof Curve)for(const u of h.segs)e.addElement({edge:o,curve:u,startPar:u.parStart,endPar:u.parEnd});else e.addElement({edge:o,curve:h,startPar:h.parStart,endPar:h.parEnd});a.sourceArrowhead&&i.push({edge:a.edge,tip:a.sourceArrowhead.tipPosition,base:a.curve.start}),a.targetArrowhead&&i.push({edge:a.edge,tip:a.targetArrowhead.tipPosition,base:a.curve.end}),a.label&&s.push(a.label)}}buildUpToLevel(t){if(this.fillTheLowestLayer(),this.minTileSize=this.getMinTileSize(),this.pageRank=pagerank(this.geomGraph.graph,.85),!this.needToSubdivide())return 1;for(let i=1;i<=t&&!this.subdivideLevel(i);i++);this.sortedNodes=Array.from(this.pageRank.keys()).sort(this.compareByPagerank.bind(this));for(let i=0;i<this.sortedNodes.length;i++)this.nodeIndexInSortedNodes.set(this.sortedNodes[i],i);for(let i=0;i<this.levels.length-1;i++)this.numberOfNodesOnLevel.push(this.filterOutEntities(this.levels[i],i));this.numberOfNodesOnLevel.push(this.sortedNodes.length);const e=new SplineRouter(this.geomGraph,[]);for(let i=this.levels.length-2;i>=0;i--){const s=this.setOfNodesOnTheLevel(i);e.rerouteOnSubsetOfNodes(s),this.regenerateCurveClipsUpToLevel(i,s)}return this.calculateNodeRank(),this.levels.length}keepInsideGraphBoundingBox(t){const e=this.geomGraph.boundingBox,i=t.width/2,s=t.height/2;return Math.min((t.center.x-e.left)/i,(e.top-t.center.y)/s,(e.right-t.center.x)/i,(t.center.y-e.bottom)/s)}diminishScaleToAvoidTree(t,e,i){Assert.assert(e.intersects(i));let s;const n=i.center.x,o=i.center.y,a=i.height/2,h=i.width/2;if(n<e.left)s=(e.left-n)/a;else if(n>e.right)s=(n-e.right)/a;else return 1;let u;if(o<e.bottom)u=(e.bottom-o)/h;else if(o>e.top)u=(o-e.top)/h;else return s;return Math.min(s,u)}needToSubdivide(){let t=!1;for(const e of this.levels[0].values())if(e.entityCount>this.tileCapacity){t=!0;break}return t}setOfNodesOnTheLevel(t){const e=new Set;for(const i of this.levels[t].values())for(const s of i.nodes)e.add(s.node);return e}regenerateCurveClipsUpToLevel(t,e){this.clearCurveClipsInLevelsUpTo(t);for(const i of this.levels[0].values())this.regenerateCurveClipsUnderTileUpToLevel(i,t,e)}clearCurveClipsInLevelsUpTo(t){for(let e=0;e<=t;e++)for(const i of this.levels[e].values())i.initCurveClips()}regenerateCurveClipsUnderTileUpToLevel(t,e,i){t.arrowheads=[],t.initCurveClips();for(const s of this.geomGraph.deepEdges)if(edgeNodesBelongToSet(s.edge,i)){if(s.curve instanceof Curve)for(const n of s.curve.segs)t.addElement({edge:s.edge,curve:n,startPar:n.parStart,endPar:n.parEnd});else t.addElement({edge:s.edge,curve:s.curve,startPar:s.curve.parStart,endPar:s.curve.parEnd});s.sourceArrowhead&&t.arrowheads.push({edge:s.edge,tip:s.sourceArrowhead.tipPosition,base:s.curve.start}),s.targetArrowhead&&t.arrowheads.push({edge:s.edge,tip:s.targetArrowhead.tipPosition,base:s.curve.end})}for(let s=1;s<=e;s++)this.regenerateCurveClipsWhenPreviosLayerIsDone(s),this.removeEmptyTiles(s)}removeEmptyTiles(t){const e=this.levels[t],i=[];for(const[s,n]of e.keyValues())n.isEmpty()&&i.push(s);for(const s of i)e.delete(s.x,s.y)}regenerateCurveClipsWhenPreviosLayerIsDone(t){for(const[e,i]of this.levels[t-1].keyValues())this.subdivideTile(e,t,i,!0)}calculateNodeRank(){this.nodeRank=new Map;const t=this.sortedNodes.length,e=Math.log10(t);for(let i=0;i<t;i++)this.nodeRank.set(this.sortedNodes[i],e-Math.log10(i+1))}compareByPagerank(t,e){return this.pageRank.get(e)-this.pageRank.get(t)}filterOutEntities(t,e){const i=this.transferDataOfLevelToMap(t);let s=0;for(;s<this.sortedNodes.length;s++){const n=this.sortedNodes[s];if(!this.addNodeToLevel(t,n,i))break}return this.removeEmptyTiles(e),s}addNodeToLevel(t,e,i){const s=i.get(e);for(const o of s)if(o.tile.entityCount>=this.tileCapacity)return!1;for(const o of s){const a=o.tile,h=o.data;a.addElement(h)}for(const o of e.selfEdges){const a=i.get(o);for(const h of a){const u=h.tile,c=h.data;u.addElement(c)}if(o.label)for(const h of i.get(o.label)){const u=h.tile,c=h.data;u.addElement(c)}}const n=this.nodeIndexInSortedNodes.get(e);for(const o of e.inEdges){const a=o.source;if(!(this.nodeIndexInSortedNodes.get(a)>n)){for(const u of i.get(o)){const c=u.tile,m=u.data;c.addElement(m)}if(o.label)for(const u of i.get(o.label)){const c=u.tile,m=u.data;c.addElement(m)}}}for(const o of e.outEdges){const a=o.target;if(!(this.nodeIndexInSortedNodes.get(a)>n)){for(const u of i.get(o)){const c=u.tile,m=u.data;c.addElement(m)}if(o.label)for(const u of i.get(o.label)){const c=u.tile,m=u.data;c.addElement(m)}}}return!0}transferDataOfLevelToMap(t){const e=new Map;for(const s of t.values()){for(const n of s.curveClips){const o=n.edge;i(o).push({tile:s,data:n})}for(const n of s.labels){const o=n.parent.edge;i(o).push({tile:s,data:n})}for(const n of s.nodes){const o=n.node;i(o).push({tile:s,data:n})}for(const n of s.arrowheads){const o=n.edge;i(o).push({tile:s,data:n})}s.clear()}return e;function i(s){let n=e.get(s);return n||e.set(s,n=new Array),n}}subdivideLevel(t){console.log("subdivideLevel",t);const e=Math.pow(2,t);if(this.levels[t]=new IntPairMap,this.subdivideTilesOnLevel(t))return console.log("done subdividing at level",t,"because each tile contains less than",this.tileCapacity),!0;const{w:s,h:n}=this.getWHOnLevel(t);return s<=this.minTileSize.width&&n<=this.minTileSize.height?(console.log("done subdividing at level",t," because of tile size = ",s,n,"is less than ",this.minTileSize),!0):!1}countClips(t){let e=0;for(const i of this.levels[t].values())e+=i.curveClips.length;return e}getWHOnLevel(t){for(let e=this.tileSizes.length;e<=t;e++){const i=this.tileSizes[e-1];this.tileSizes.push(new Size(i.width/2,i.height/2))}return{w:this.tileSizes[t].width,h:this.tileSizes[t].height}}subdivideTilesOnLevel(t){let i=!0;for(const[s,n]of this.levels[t-1].keyValues()){const o=this.subdivideTile(s,t,n,!1);i&&(i=o.allSmall)}return this.removeEmptyTiles(t),console.log("generated",this.levels[t].size,"tiles"),i}subdivideTile(t,e,i,s){const{w:n,h:o}=this.getWHOnLevel(e),a=this.levels[e],h=t.x,u=t.y,c=this.topLevelTileRect.left+h*n*2,m=this.topLevelTileRect.bottom+u*o*2,S=new Array(4);for(let Q=0;Q<2;Q++)for(let pt=0;pt<2;pt++)S[Q*2+pt]=new IntPair(h*2+Q,u*2+pt);s||this.generateSubtilesWithoutTileClips(c,n,m,o,S,i,e);const A=new LineSegment(c,m+o,c+2*n,m+o),I=new LineSegment(c+n,m,c+n,m+2*o);rt();let B=0,q=!0;for(const Q of S){const pt=a.get(Q.x,Q.y);pt!=null&&(B++,pt.entityCount>this.tileCapacity&&(q=!1))}return{count:B,allSmall:q};function rt(){for(const Q of i.curveClips){const pt=Q.curve,Lt=ct(pt,Q.startPar,Q.endPar);if(Assert.assert(Lt.length>=2),Lt.length==2){const Bt=(Lt[0]+Lt[1])/2,_t=pt.value(Bt),Fi=_t.x<=c+n?0:1,fs=_t.y<=m+o?0:1,V=2*Fi+fs,F=S[V];let X=a.getI(F);if(!X){const J=c+Fi*n,dt=m+fs*o;X=new Tile(new Rectangle({left:J,bottom:dt,top:dt+o,right:J+n})),a.setPair(F,X)}X.addCurveClip({curve:pt,edge:Q.edge,startPar:Lt[0],endPar:Lt[1]})}else for(let Bt=0;Bt<Lt.length-1;Bt++){const _t=(Lt[Bt]+Lt[Bt+1])/2,Fi=pt.value(_t),fs=Fi.x<=c+n?0:1,V=Fi.y<=m+o?0:1,F=2*fs+V,X=S[F];let J=a.getI(X);if(!J){const dt=c+fs*n,ut=m+V*o;J=new Tile(new Rectangle({left:dt,bottom:ut,top:ut+o,right:dt+n})),a.setPair(X,J)}J.addCurveClip({curve:pt,edge:Q.edge,startPar:Lt[Bt],endPar:Lt[Bt+1]})}}}function ct(Q,pt,Lt){let Bt=Array.from(Curve.getAllIntersections(Q,A,!0)).concat(Array.from(Curve.getAllIntersections(Q,I,!0))).map(_t=>_t.par0);return Bt.sort((_t,Fi)=>_t-Fi),[pt].concat(Bt.filter(_t=>_t>=pt&&_t<=Lt)).concat(Lt)}}addSubtilesToLevel(t,e,i,s,n){for(let o=0;o<2;o++)for(let a=0;a<2;a++){const h=t[o*2+a];h.isEmpty()||(e.set(2*i+o,2*s+a,h),n&&h.entityCount>this.tileCapacity&&(n=!1))}return n}generateSubtilesWithoutTileClips(t,e,i,s,n,o,a){let h=0;for(let u=0;u<2;u++)for(let c=0;c<2;c++){const m=new Rectangle({left:t+e*u,right:t+e*(u+1),bottom:i+s*c,top:i+s*(c+1)}),S=this.generateOneSubtileExceptEdgeClips(o,m);S&&this.levels[a].set(n[h].x,n[h].y,S),h++}}innerClips(t,e,i){const s=[],n=Array.from(Curve.getAllIntersections(t,i,!0)).concat(Array.from(Curve.getAllIntersections(t,e,!0)));n.sort((a,h)=>a.par0-h.par0);const o=[t.parStart];for(let a=0;a<n.length;a++){const h=n[a];h.par0>o[o.length-1]+GeomConstants.distanceEpsilon&&o.push(h.par0)}if(t.parEnd>o[o.length-1]+GeomConstants.distanceEpsilon&&o.push(t.parEnd),o.length<=2)return s.push(t),s;for(let a=0;a<o.length-1;a++)s.push(t.trim(o[a],o[a+1]));return s}generateOneSubtileExceptEdgeClips(t,e){const i=new Tile(e);for(const s of t.nodes)s.boundingBox.intersects(e)&&i.nodes.push(s);for(const s of t.labels)s.boundingBox.intersects(e)&&i.labels.push(s);for(const s of t.arrowheads){const n=Rectangle.mkPP(s.base,s.tip),a=s.tip.sub(s.base).div(3).rotate90Cw();n.add(s.base.add(a)),n.add(s.base.sub(a)),n.intersects(e)&&i.arrowheads.push(s)}return i.isEmpty()?null:i}}class rh extends _s{toString(){return"label of "+(this.parent?this.parent.toString():"null")}constructor(t){super(),this.parent=t}}class Pi{static CreatePortsAndRouteEdges(t,e,i,s,n,o=null){Pi.FillRouter(t,e,i,s,n).run(),Pi.CreateSelfEdges(Array.from(s).filter(h=>h.sourcePort.Location===h.targetPort.Location),t)}static CreatePortsAndRouteEdges_(t,e,i,s,n,o,a){Pi.CreatePortsAndRouteEdges(t,e,i,s,n)}static CreatePortsAndRouteEdges__(t,e,i,s,n,o){Pi.CreatePortsAndRouteEdges(t,e,i,s,n)}static FillRouter(t,e,i,s,n){const o=new Map;Pi.FillNodeShapesMap(i,s,o);const a=new RectilinearEdgeRouter(o.values(),e,t);for(const h of s)h.sourcePort=oh(o.get(h.source).Ports),h.targetPort=oh(o.get(h.target).Ports),a.AddEdgeGeometryToRoute(h);return a}static FillNodeShapesMap(t,e,i){for(const s of t){const n=Pi.CreateShapeWithRelativeNodeAtCenter(s);i.set(s,n)}for(const s of e){let n=s.source;i.has(n)||i.set(n,Pi.CreateShapeWithRelativeNodeAtCenter(n)),n=s.target,i.has(n)||i.set(n,Pi.CreateShapeWithRelativeNodeAtCenter(n))}}static CreateSelfEdges(t,e){for(const i of t)Pi.CreateSimpleEdgeCurveWithGivenFitRadius(i,e)}static CreateSimpleEdgeCurveWithGivenFitRadius(t,e){const i=t.source.center,s=t.target.center;if(t.source===t.target){const n=t.source.boundaryCurve.boundingBox.width/2,o=t.source.boundingBox.height/4;t.smoothedPolyline=Pi.CreateUnderlyingPolylineForSelfEdge(i,n,o);for(let a=t.smoothedPolyline.headSite.next;a.next!=null;a=a.next)Pi.CalculateCoefficiensUnderSite(a,e);t.curve=t.smoothedPolyline.createCurve()}else t.smoothedPolyline=SmoothedPolyline.mkFromPoints([i,s]),t.curve=t.smoothedPolyline.createCurve();Arrowhead.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,t.curve,!0)||Arrowhead.createBigEnoughSpline(t)}static CreateSimpleEdgeCurve(t){const e=t.source.center,i=t.target.center;if(t.source===t.target){const s=t.source.boundaryCurve.boundingBox.width/2,n=t.source.boundingBox.height/4;t.smoothedPolyline=Pi.CreateUnderlyingPolylineForSelfEdge(e,s,n),t.curve=t.smoothedPolyline.createCurve()}else t.smoothedPolyline=SmoothedPolyline.mkFromPoints([e,i]),t.curve=t.smoothedPolyline.createCurve();Arrowhead.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,t.curve,!0)||Arrowhead.createBigEnoughSpline(t)}static CreateUnderlyingPolylineForSelfEdge(t,e,i){const s=t.add(new Point(0,i)),n=t.add(new Point(e,i)),o=t.add(new Point(e,i*-1)),a=t.add(new Point(0,i*-1));let h=CornerSite.mkSiteP(t);const u=new SmoothedPolyline(h);return h=CornerSite.mkSiteSP(h,s),h=CornerSite.mkSiteSP(h,n),h=CornerSite.mkSiteSP(h,o),h=CornerSite.mkSiteSP(h,a),CornerSite.mkSiteSP(h,t),u}static CreateShapeWithRelativeNodeAtCenter(t){const e=new RelativeShape(t);return e.Ports.add(new RelativeFloatingPort(()=>t.boundaryCurve,()=>t.center,new Point(0,0))),e}static CalculateCoefficiensUnderSite(t,e){let i=e/t.point.sub(t.prev.point).length;i=Math.min(.5,i),t.previouisBezierCoefficient=i,i=e/t.next.point.sub(t.point).length,i=Math.min(.5,i),t.nextBezierCoefficient=i}}function oh(l){for(const t of l)return t}class Yr extends Ie{constructor(t,e){super(),this.SetEdges(t,e)}}class Ec{constructor(t){this.MultipleMiddles=new Set,this.Multiedges=new Fs}*RegularMultiedges(){for(const[t,e]of this.Multiedges.keyValues())t.x!==t.y&&(yield e)}*AllIntEdges(){for(const t of this.Multiedges.values())for(const e of t)yield e}addFeedbackSet(t){for(const e of t){const i=new Ot(e.source,e.target),s=new Ot(e.target,e.source),n=this.Multiedges.get(i.x,i.y);for(const o of n)o.reverse();if(this.Multiedges.has(s.x,s.y)){const o=this.Multiedges.get(s.x,s.y);for(const a of n)o.push(a)}else this.Multiedges.set(s.x,s.y,n);this.Multiedges.delete(i.x,i.y)}}registerOriginalEdgeInMultiedges(t){let e=this.Multiedges.get(t.source,t.target);e==null&&this.Multiedges.set(t.source,t.target,e=[]),e.push(t)}*SkeletonEdges(){for(const[t,e]of this.Multiedges.keyValues())t.x!==t.y&&(yield e[0])}GetMultiedge(t,e){return this.GetMultiedgeI(new Ot(t,e))}GetMultiedgeI(t){return this.Multiedges.has(t.x,t.y)?this.Multiedges.get(t.x,t.y):new Array}}function Ra(l,t){for(let e=0;e<l.length;e++)t[e]=l[e]}class gs{constructor(t){this.initialize(t)}initialize(t){this.y=t,this.verticesToX=null,this.layers=null}DropEmptyLayers(){const t=new Array(this.Layers.length);let e=0;for(let o=0;o<this.Layers.length;o++)t[o]=e,this.Layers[o].length===0&&e++;if(e===0)return this;const i=new Array(this.y.length);for(let o=0;o<i.length;o++)i[o]=this.y[o]-t[this.y[o]];const s=new Array(this.layers.length-e);for(let o=0;o<this.layers.length;o++)this.layers[o].length>0&&(s[o-t[o]]=Array.from(this.layers[o]));const n=new gs(i);return n.layers=s,n}updateLayers(t){this.layers==null&&this.InitLayers();for(let e=0;e<this.layers.length;e++)Ra(t[e],this.layers[e]);this.UpdateXFromLayers()}UpdateXFromLayers(){this.layers==null&&this.InitLayers(),this.verticesToX==null&&(this.verticesToX=new Array(this.y.length));for(const t of this.layers){let e=0;for(const i of t)this.verticesToX[i]=e++}}get x(){return this.verticesToX!=null?this.verticesToX:(this.verticesToX=new Array(this.y.length),this.UpdateXFromLayers(),this.verticesToX)}ReversedClone(){const t=new Array(this.y.length),e=this.Layers.length-1;for(let i=0;i<this.y.length;i++)t[i]=e-this.y[i];return new gs(t)}get Layers(){return this.layers!=null?this.layers:(this.InitLayers(),this.layers)}set Layers(t){this.layers=t}InitLayers(){let t=0;for(const i of this.y)i+1>t&&(t=i+1);const e=new Array(t).fill(0);for(const i of this.y)e[i]++;this.layers=new Array(t);for(let i=0;i<t;i++)this.layers[i]=new Array(e[i]),e[i]=0;for(let i=0;i<this.y.length;i++){const s=this.y[i];this.layers[s][e[s]++]=i}}}function Jd(l){if(l.layers==null)return!0;for(const t of l.layers)if(bc(t))return!1;return!0}function bc(l){const t=new Set;for(const e of l){if(e==null||t.has(e))return!0;t.add(e)}return!1}class Da extends zt{constructor(t,e,i,s){super(s),this.jumpers=new Set,this.possibleJumperFeasibleIntervals=new Map,this.nodeCount=i,this.dag=t,this.layering=e,this.Init()}static Balance(t,e,i,s){new Da(t,e,i,s).run()}run(){for(;this.jumpers.size>0;)this.Jump(this.ChooseJumper())}Init(){this.CalculateLayerCounts(),this.InitJumpers()}Jump(t){this.jumpers.delete(t);const e=this.possibleJumperFeasibleIntervals.get(t),i=this.CalcJumpInfo(e.x,e.y,t);if(i==null)return;this.layering[t]=i.layerToJumpTo;const s=this.nodeCount[t];this.vertsCounts[i.jumperLayer]-=s,this.vertsCounts[i.layerToJumpTo]+=s,this.UpdateRegionsForPossibleJumpersAndInsertJumpers(i.jumperLayer,t)}IsJumper(t){return this.possibleJumperFeasibleIntervals.has(t)}UpdateRegionsForPossibleJumpersAndInsertJumpers(t,e){const i=new Set;for(const n of this.dag.pred(e))this.IsJumper(n)&&(this.CalculateRegionAndInsertJumper(n),i.add(n));for(const n of this.dag.succ(e))this.IsJumper(n)&&(this.CalculateRegionAndInsertJumper(n),i.add(n));const s=new Array;for(const n of this.possibleJumperFeasibleIntervals)i.has(n[0])||n[1].x>t&&n[1].y<t&&s.push(n[0]);for(const n of s)this.CalculateRegionAndInsertJumper(n)}InitJumpers(){const t=new Array(this.dag.nodeCount).fill(0);for(const e of this.dag.edges)t[e.source]-=e.weight,t[e.target]+=e.weight;this.possibleJumperFeasibleIntervals=new Map;for(let e=0;e<this.dag.nodeCount;e++)t[e]===0&&this.CalculateRegionAndInsertJumper(e)}CalculateRegionAndInsertJumper(t){const e=new Ot(this.Up(t),this.Down(t));this.possibleJumperFeasibleIntervals.set(t,e),this.InsertJumper(e.x,e.y,t)}InsertJumper(t,e,i){this.CalcJumpInfo(t,e,i)!=null&&this.jumpers.add(i)}CalcJumpInfo(t,e,i){const s=this.layering[i];let n=-1,o=this.vertsCounts[s]-2*this.nodeCount[i];for(let a=t-1;a>s;a--)this.vertsCounts[a]<o&&(o=this.vertsCounts[a],n=a);for(let a=s-1;a>e;a--)this.vertsCounts[a]<o&&(o=this.vertsCounts[a],n=a);if(n!==-1)return{jumperLayer:s,layerToJumpTo:n}}Up(t){let e=Number.MAX_SAFE_INTEGER;for(const i of this.dag.inEdges[t]){const s=this.layering[i.source]-i.separation+1;s<e&&(e=s)}return e===Number.MAX_SAFE_INTEGER&&(e=this.layering[t]+1),e}Down(t){let e=Number.NEGATIVE_INFINITY;for(const i of this.dag.outEdges[t]){const s=this.layering[i.target]+i.separation-1;s>e&&(e=s)}return e===Number.NEGATIVE_INFINITY&&(e=this.layering[t]-1),e}CalculateLayerCounts(){this.vertsCounts=new Array(Math.max(...this.layering)+1).fill(0);for(const t of this.layering)this.vertsCounts[t]+=this.nodeCount[t]}ChooseJumper(){for(const t of this.jumpers)return t;throw new Error("there are no jumpers to choose")}}class wn{constructor(t){this.Initialize(t)}Initialize(t){this.BaseGraph=t,this.totalNumberOfNodes=t.nodeCount;for(const e of this.BaseGraph.edges)if(e.LayerEdges!=null)for(const i of e.LayerEdges){const s=Math.max(i.Source,i.Target)+1;s>this.totalNumberOfNodes&&(this.totalNumberOfNodes=s)}this.firstVirtualNode=Number.POSITIVE_INFINITY;for(const e of this.BaseGraph.edges)if(e.LayerEdges!=null)for(let i=1;i<e.LayerEdges.length;i++){const s=e.LayerEdges[i];this.firstVirtualNode=Math.min(this.firstVirtualNode,s.Source)}this.firstVirtualNode===Number.POSITIVE_INFINITY&&(this.firstVirtualNode=this.BaseGraph.nodeCount,this.totalNumberOfNodes=this.BaseGraph.nodeCount),this.virtualNodesToInEdges=new Array(this.totalNumberOfNodes-this.firstVirtualNode),this.virtualNodesToOutEdges=new Array(this.totalNumberOfNodes-this.firstVirtualNode);for(const e of this.BaseGraph.edges)if(e.LayerSpan>0)for(const i of e.LayerEdges)i.Target!==e.target&&(this.virtualNodesToInEdges[i.Target-this.firstVirtualNode]=i),i.Source!==e.source&&(this.virtualNodesToOutEdges[i.Source-this.firstVirtualNode]=i)}*edges_(){for(const t of this.BaseGraph.edges)if(t.LayerSpan>0)for(const e of t.LayerEdges)yield e}get Edges(){return this.edges_()}*InEdges(t){if(t<this.BaseGraph.nodeCount)for(const e of this.BaseGraph.inEdges[t])e.source!==e.target&&e.LayerEdges!=null&&(yield wn.LastEdge(e));else t>=this.firstVirtualNode&&(yield this.InEdgeOfVirtualNode(t))}static LastEdge(t){return t.LayerEdges[t.LayerEdges.length-1]}InEdgeOfVirtualNode(t){return this.virtualNodesToInEdges[t-this.firstVirtualNode]}*OutEdges(t){if(t<this.BaseGraph.nodeCount)for(const e of this.BaseGraph.outEdges[t])e.source!==e.target&&e.LayerEdges!=null&&(yield wn.FirstEdge(e));else t>=this.firstVirtualNode&&(yield this.OutEdgeOfVirtualNode(t))}OutDegreeIsMoreThanOne(t){return t<this.BaseGraph.nodeCount?this.BaseGraph.outEdges[t].length>1:!1}InDegreeIsMoreThanOne(t){return t<this.BaseGraph.nodeCount?this.BaseGraph.inEdges[t].length>1:!1}OutEdgeOfVirtualNode(t){return this.virtualNodesToOutEdges[t-this.firstVirtualNode]}static FirstEdge(t){return t.LayerEdges[0]}InEdgesCount(t){return this.RealInEdgesCount(t)}RealInEdgesCount(t){return t<this.BaseGraph.nodeCount?this.BaseGraph.inEdges[t].filter(e=>e.LayerEdges!=null).length:1}OutEdgesCount(t){return this.RealOutEdgesCount(t)}RealOutEdgesCount(t){return t<this.BaseGraph.nodeCount?this.BaseGraph.outEdges[t].filter(e=>e.LayerEdges!=null).length:1}get NodeCount(){return this.totalNumberOfNodes}IsRealNode(t){return t<this.BaseGraph.nodeCount}IsVirtualNode(t){return!this.IsRealNode(t)}ReversedClone(){const t=this.CreateReversedEdges();return new wn(new Yr(t,this.BaseGraph.nodeCount))}CreateReversedEdges(){const t=new Array;for(const e of this.BaseGraph.edges)e.isSelfEdge()||t.push(e.reversedClone());return t}*Succ(t){for(const e of this.OutEdges(t))yield e.Target}*Pred(t){for(const e of this.InEdges(t))yield e.Source}}class Kr{constructor(t,e,i,s){this.la=e,this.database=i,this.layeredGraph=t,this.intGraph=s}static InsertLayers(t,e,i,s){const n=new Kr(t,e,i,s);return n.InsertLayers(),{layeredGraph:n.nLayeredGraph,la:n.Nla.DropEmptyLayers()}}get NLayering(){return this.Nla.y}InsertLayers(){this.EditOldLayering(),this.CreateFullLayeredGraph(),this.InitNewLayering(),this.MapVirtualNodesToEdges(),this.FillUnsortedNewOddLayers(),this.WidenOriginalLayers(),this.SortNewOddLayers()}EditOldLayering(){let t=this.intGraph.nodeCount;for(const e of this.database.RegularMultiedges()){let i=0;const s=e[0];if(i=s.LayerSpan*2,i>0){for(const n of s.LayerEdges)n.Target!==s.target&&(t++,this.UpdateOldLayer(t++,n.Target));t+=(i-1)*(e.length-1)+1}}}UpdateOldLayer(t,e){const i=this.la.x[e],s=this.la.y[e],n=this.la.Layers[s];n[i]=t}WidenOriginalLayers(){for(let t=0;t<this.la.Layers.length;t++){const e=this.Nla.Layers[t*2];let i=0;for(const s of this.la.Layers[t]){const n=this.virtNodesToIntEdges[s];if(n!=null){const o=this.NLayering[n.source]-this.NLayering[s],a=this.database.Multiedges.get(n.source,n.target);for(const h of a)if(h!==n){const u=h.LayerEdges[o].Source;e[i]=u,this.Nla.x[u]=i++}else e[i]=s,this.Nla.x[s]=i++}else e[i]=s,this.Nla.x[s]=i++}}}FillUnsortedNewOddLayers(){const t=new Array(this.Nla.Layers.length).fill(0);for(let e=this.intGraph.nodeCount;e<this.nLayeredGraph.NodeCount;e++){const i=this.NLayering[e];i%2===1&&(this.Nla.Layers[i][t[i]++]=e)}}MapVirtualNodesToEdges(){this.virtNodesToIntEdges=new Array(this.NLayering.length);for(const t of this.database.AllIntEdges())if(t.source!==t.target&&t.LayerEdges!=null)for(const e of t.LayerEdges)e.Target!==t.target&&(this.virtNodesToIntEdges[e.Target]=t)}CreateFullLayeredGraph(){this.totalNodes=this.intGraph.nodeCount;for(const t of this.database.RegularMultiedges()){let e=0,i=!0;for(const s of t)if(i&&(i=!1,e=s.LayerSpan*2),e>0){s.LayerEdges=new Array(e);for(let n=0;n<e;n++){const o={currentVV:this.totalNodes},a=vn.GetSource(o,s,n);this.totalNodes=o.currentVV;const h=vn.GetTarget(this.totalNodes,s,n,e);s.LayerEdges[n]=new ks(a,h,s.CrossingWeight)}Kr.RegisterDontStepOnVertex(this.database,s)}}this.nLayeredGraph=new wn(this.intGraph)}SortNewOddLayers(){for(let t=1;t<this.Nla.Layers.length;t+=2){const e=new Go,i=this.Nla.Layers[t];for(const n of i){let o=-1;for(const u of this.nLayeredGraph.InEdges(n))o=u.Source;let a=-1;for(const u of this.nLayeredGraph.OutEdges(n))a=u.Target;const h=this.Nla.x[o]+this.Nla.x[a];if(e.has(h)){const u=e.get(h);if(typeof u=="number"){const c=new Array;c.push(u),c.push(n),e.set(h,c)}else u.push(n)}else e.set(h,n)}let s=0;for(const n of e.values())if(typeof n=="number")i[s++]=n;else for(const o of n)i[s++]=o;for(let n=0;n<i.length;n++)this.Nla.x[i[n]]=n}}InitNewLayering(){this.Nla=new gs(new Array(this.totalNodes));for(let i=0;i<this.layeredGraph.NodeCount;i++)this.NLayering[i]=this.la.y[i]*2;for(const[i,s]of this.database.Multiedges.keyValues())if(i.x!==i.y&&this.la.y[i.x]!==this.la.y[i.y]){const n=this.la.y[i.x]*2;for(const o of s){let a=n-1;for(const h of o.LayerEdges)h.Target!==o.target&&(this.NLayering[h.Target]=a--)}}const t=new Array(2*this.la.Layers.length-1),e=new Array(t.length).fill(0);for(const i of this.NLayering)e[i]++;for(let i=0;i<e.length;i++)t[i]=new Array(e[i]);this.Nla=new gs(this.NLayering),this.Nla.Layers=t}static RegisterDontStepOnVertex(t,e){if(t.Multiedges.get(e.source,e.target).length>1){const i=e.LayerEdges[Math.floor(e.LayerEdges.length/2)];t.MultipleMiddles.add(i.Source)}}}class vn{constructor(t,e,i,s){this.virtNodesToIntEdges=new Map,this.la=e,this.database=i,this.layeredGraph=t,this.intGraph=s}get NLayering(){return this.Nla.y}static InsertPaths(t,e,i,s){const n=new vn(t,e,i,s);return n.InsertPaths(),{layeredGraph:n.NLayeredGraph,la:n.Nla}}InsertPaths(){this.CreateFullLayeredGraph(),this.InitNewLayering(),this.MapVirtualNodesToEdges(),this.WidenOriginalLayers()}WidenOriginalLayers(){for(let t=0;t<this.la.Layers.length;t++){const e=this.Nla.Layers[t];let i=0;for(const s of this.la.Layers[t]){const n=this.virtNodesToIntEdges.get(s);if(n!=null){const o=this.NLayering[n.source]-this.NLayering[s],a=this.database.Multiedges.get(n.source,n.target);for(const h of a)if(!this.EdgeIsFlat(h))if(h!==n){const u=h.LayerEdges[o].Source;e[i]=u,this.Nla.x[u]=i++}else e[i]=s,this.Nla.x[s]=i++}else e[i]=s,this.Nla.x[s]=i++}}}EdgeIsFlat(t){return this.la.y[t.source]===this.la.y[t.target]}MapVirtualNodesToEdges(){for(const t of this.database.RegularMultiedges())for(const e of t)if(!this.EdgeIsFlat(e))for(const i of e.LayerEdges)i.Target!==e.target&&this.virtNodesToIntEdges.set(i.Target,e)}CreateFullLayeredGraph(){let t=this.layeredGraph.NodeCount;for(const[e,i]of this.database.Multiedges.keyValues())if(e.x!==e.y){let s=!0,n=0;for(const o of i){if(s)s=!1,n=o.LayerSpan;else if(o.LayerEdges=new Array(n),n===1)o.LayerEdges[0]=new ks(o.source,o.target,o.CrossingWeight);else for(let a=0;a<n;a++){const h={currentVV:t},u=vn.GetSource(h,o,a);t=h.currentVV;const c=vn.GetTarget(t,o,a,n);o.LayerEdges[a]=new ks(u,c,o.CrossingWeight)}Kr.RegisterDontStepOnVertex(this.database,o)}}this.NLayeredGraph=new wn(this.intGraph)}static GetTarget(t,e,i,s){return i<s-1?t:e.target}static GetSource(t,e,i){return i===0?e.source:t.currentVV++}InitNewLayering(){this.Nla=new gs(new Array(this.NLayeredGraph.NodeCount));for(let i=0;i<this.layeredGraph.NodeCount;i++)this.NLayering[i]=this.la.y[i];for(const[i,s]of this.database.Multiedges.keyValues())if(i.x!==i.y&&this.la.y[i.x]!==this.la.y[i.y]){let n=0,o=!0;for(const a of s){o&&(o=!1,n=this.la.y[a.source]);let h=n-1;for(const u of a.LayerEdges)this.NLayering[u.Target]=h--}}const t=new Array(this.la.Layers.length),e=new Array(t.length).fill(0);for(const i of this.NLayering)e[i]++;for(let i=0;i<e.length;i++)t[i]=new Array(e[i]);this.Nla=new gs(this.NLayering),this.Nla.Layers=t}}class Jr{constructor(t,e,i){this.numberOfCrossings=e,this.la=t,this.virtVertexStart=i}LayerGroupDisbalance(t,e,i){return e===1?this.LayerGroupDisbalanceWithOrigSeparators(t,i):this.LayerGroupDisbalanceWithVirtSeparators(t,e)}LayerGroupDisbalanceWithVirtSeparators(t,e){let i=0;for(let s=0;s<t.length;){const n=this.CurrentOrigGroupDelta(s,t,e);s=n.i,i+=n.ret}return i}CurrentOrigGroupDelta(t,e,i){let s=0,n=t;for(;n<e.length&&e[n]<this.virtVertexStart;n++)s++;return t=n+1,{ret:Math.abs(i-s),i:t}}LayerGroupDisbalanceWithOrigSeparators(t,e){let i=0;for(let s=0;s<t.length;){const n=this.CurrentVirtGroupDelta(s,t,e);i+=n.ret,s=n.i}return i}CurrentVirtGroupDelta(t,e,i){let s=0,n=t;for(;n<e.length&&e[n]>=this.virtVertexStart;n++)s++;return t=n+1,{ret:Math.abs(i-s),i:t}}static less(t,e){return t.numberOfCrossings<e.numberOfCrossings}static greater(t,e){return t.numberOfCrossings>e.numberOfCrossings}IsPerfect(){return this.numberOfCrossings===0}}class Ac{constructor(t){this.x=t}Compare(t,e){const i=this.x[t.Source]-this.x[e.Source];return i!==0?i:this.x[t.Target]-this.x[e.Target]}}class wc{constructor(t){this.x=t}Compare(t,e){const i=this.x[t.Target]-this.x[e.Target];return i!==0?i:this.x[t.Source]-this.x[e.Source]}}function Yo(){return xs(2)===0}function vc(l,t,e){const i=e.Layers[l+1],s=e.Layers[l];return s.length<=i.length?Tc(s,t,e):Ic(i,s,t,e)}function Ic(l,t,e,i){const s=ah(t,e),n=new wc(i.x);s.sort((u,c)=>n.Compare(u,c));let o=1;for(;o<l.length;)o*=2;const a=new Array(2*o-1).fill(0);o--;let h=0;for(const u of s){let c=o+i.x[u.Source];const m=u.CrossingWeight;for(a[c]+=m;c>0;)c%2!==0&&(h+=m*a[c+1]),c=Math.floor((c-1)/2),a[c]+=m}return h}function Tc(l,t,e){const i=ah(l,t),s=new Ac(e.x);i.sort((h,u)=>s.Compare(h,u));let n=1;for(;n<l.length;)n*=2;const o=new Array(2*n-1).fill(0);n--;let a=0;for(const h of i){let u=n+e.x[h.Target];const c=h.CrossingWeight;for(o[u]+=c;u>0;)u%2!==0&&(a+=c*o[u+1]),u=Math.floor((u-1)/2),o[u]+=c}return a}function ah(l,t){return Zs(l,e=>t.InEdges(e))}function lh(l,t){let e=0;for(let i=0;i<t.Layers.length-1;i++)e+=vc(i,l,t);return e}class rr extends zt{constructor(t,e,i,s,n,o,a){super(a),this.tryReverse=!0,this.MaxNumberOfAdjacentExchanges=50,this.cancelToken=a,this.tryReverse=e,this.startOfVirtNodes=s,this.layerArrays=i,this.layering=i.y,this.nOfLayers=i.Layers.length,this.layers=i.Layers,this.properLayeredGraph=t,this.hasCrossWeights=n,this.SugSettings=o}get NoGainStepsBound(){return this.SugSettings.NoGainAdjacentSwapStepsBound*this.SugSettings.NoGainStepsForOrderingMultiplier}get SeedOfRandom(){return xs(100)}get MaxOfIterations(){return this.SugSettings.MaxNumberOfPassesInOrdering*this.SugSettings.NoGainStepsForOrderingMultiplier}static OrderLayers(t,e,i,s,n){let o=!1;for(const h of t.Edges)if(h.CrossingWeight!==1){o=!0;break}new rr(t,!0,e,i,o,s,n).run()}run(){if(this.Calculate(),this.tryReverse){const t=this.layerArrays.ReversedClone(),e=new rr(this.properLayeredGraph.ReversedClone(),!1,t,this.startOfVirtNodes,this.hasCrossWeights,this.SugSettings,this.cancelToken);if(e.run(),Jr.less(e.measure,this.measure)){for(let i=0;i<this.nOfLayers;i++)Ra(t.Layers[i],this.layerArrays.Layers[this.nOfLayers-1-i]);this.layerArrays.UpdateXFromLayers()}}}Calculate(){this.Init(),this.layerArraysCopy=rr.CloneLayers(this.layers,this.layerArraysCopy);let t=0;this.measure=new Jr(this.layerArraysCopy,lh(this.properLayeredGraph,this.layerArrays),this.startOfVirtNodes);for(let e=0;e<this.MaxOfIterations&&t<this.NoGainStepsBound&&!this.measure.IsPerfect();e++){const i=e%2===0;this.LayerByLayerSweep(i),this.AdjacentExchange();const s=new Jr(this.layerArrays.Layers,lh(this.properLayeredGraph,this.layerArrays),this.startOfVirtNodes);Jr.less(this.measure,s)?(this.Restore(),t++):(Jr.less(s,this.measure)||Yo())&&(t=0,this.layerArraysCopy=rr.CloneLayers(this.layers,this.layerArraysCopy),this.measure=s)}}static CloneLayers(t,e){if(e==null){e=new Array(t.length);for(let i=0;i<t.length;i++)e[i]=t[i].map(s=>s)}else for(let i=0;i<t.length;i++)Ra(t[i],e[i]);return e}Restore(){this.layerArrays.updateLayers(this.layerArraysCopy)}LayerByLayerSweep(t){if(t)for(let e=1;e<this.nOfLayers;e++)this.SweepLayer(e,!0);else for(let e=this.nOfLayers-2;e>=0;e--)this.SweepLayer(e,!1)}SweepLayer(t,e){const i=this.layers[t],s=new Array(i.length);for(let o=0;o<s.length;o++)s[o]=this.WMedian(i[o],e);this.Sort(t,s);const n=this.layerArrays.Layers[t];for(let o=0;o<n.length;o++)this.layerArrays.x[n[o]]=o}Sort(t,e){const i=new Go,s=this.layers[t];let n=0;for(const a of e){const h=s[n++];if(a!==-1)if(!i.has(a))i.set(a,h);else{const u=i.get(a);if(typeof u!="number"){const c=u;if(Yo())c.push(h);else{const m=xs(c.length),S=c[m];c[m]=h,c.push(S)}}else{const c=u,m=new Array;i.set(a,m),Yo()?(m.push(c),m.push(h)):(m.push(h),m.push(c))}}}const o=i.values();for(n=0;n<s.length;)if(e[n]!==-1){const a=o.next().value;if(typeof a=="number")s[n++]=a;else{const h=a;for(const u of h){for(;e[n]===-1;)n++;s[n++]=u}}}else n++}WMedian(t,e){let i,s;if(e?(i=this.properLayeredGraph.OutEdges(t),s=this.properLayeredGraph.OutEdgesCount(t)):(i=this.properLayeredGraph.InEdges(t),s=this.properLayeredGraph.InEdgesCount(t)),s===0)return-1;const n=new Array(s);let o=0;if(e)for(const c of i)n[o++]=this.X[c.Target];else for(const c of i)n[o++]=this.X[c.Source];n.sort((c,m)=>c-m);const a=Math.floor(s/2);if(s%2===1)return n[a];if(s===2)return .5*(n[0]+n[1]);const h=n[a-1]-n[0],u=n[s-1]-n[a];return Math.floor((n[a-1]*h+n[a]*u)/(h+u))}Init(){const t=new Array(this.nOfLayers).fill(0),e=new Yt.B;for(let s=0;s<this.properLayeredGraph.NodeCount;s++)this.properLayeredGraph.InEdgesCount(s)===0&&e.push(s);const i=new Array(this.properLayeredGraph.NodeCount).fill(!1);for(;e.size>0;){const s=e.pop(),n=this.layerArrays.y[s];this.layerArrays.Layers[n][t[n]]=s,this.layerArrays.x[s]=t[n],t[n]++;for(const o of this.properLayeredGraph.Succ(s))i[o]||(i[o]=!0,e.push(o))}this.X=this.layerArrays.x}AdjacentExchange(){this.InitArrays();let t=0,e=!0;for(;e&&t++<this.MaxNumberOfAdjacentExchanges;){e=!1;for(let i=0;i<this.layers.length;i++)e=this.AdjExchangeLayer(i)||e;for(let i=this.layers.length-2;i>=0;i--)e=this.AdjExchangeLayer(i)||e}}AllocArrays(){const t=this.properLayeredGraph.NodeCount;this.predecessors=new Array(t),this.successors=new Array(t),this.pOrder=new Array(t),this.sOrder=new Array(t),this.hasCrossWeights&&(this.outCrossingCount=new Array(t),this.inCrossingCount=new Array(t));for(let e=0;e<t;e++){let i=this.properLayeredGraph.InEdgesCount(e);if(this.predecessors[e]=new Array(i),this.hasCrossWeights){const s=this.inCrossingCount[e]=new Map;for(const n of this.properLayeredGraph.InEdges(e))s.set(n.Source,n.CrossingWeight)}if(this.pOrder[e]=new Map,i=this.properLayeredGraph.OutEdgesCount(e),this.successors[e]=new Array(i),this.sOrder[e]=new Map,this.hasCrossWeights){const s=this.outCrossingCount[e]=new Map;for(const n of this.properLayeredGraph.OutEdges(e))s.set(n.Target,n.CrossingWeight)}}}InitArrays(){this.successors==null&&this.AllocArrays();for(let t=0;t<this.properLayeredGraph.NodeCount;t++)this.pOrder[t]=new Map,this.sOrder[t]=new Map;for(const t of this.layers)this.InitPsArraysForLayer(t)}CalcPair(t,e){const i=this.successors[t],s=this.successors[e],n=this.predecessors[t],o=this.predecessors[e];if(this.hasCrossWeights){const a=this.outCrossingCount[t],h=this.outCrossingCount[e],u=this.inCrossingCount[t],c=this.inCrossingCount[e];return{cuv:this.CountOnArraysUV(i,s,a,h)+this.CountOnArraysUV(n,o,u,c),cvu:this.CountOnArraysUV(s,i,h,a)+this.CountOnArraysUV(o,n,c,u)}}else return{cuv:this.CountOnArrays(i,s)+this.CountOnArrays(n,o),cvu:this.CountOnArrays(s,i)+this.CountOnArrays(o,n)}}InitPsArraysForLayer(t){for(const e of t){for(const i of this.properLayeredGraph.Pred(e)){const s=this.sOrder[i],n=s.size;this.successors[i][n]=e,s.set(e,n)}for(const i of this.properLayeredGraph.Succ(e)){const s=this.pOrder[i],n=s.size;this.predecessors[i][n]=e,s.set(e,n)}}}CountOnArrays(t,e){let i=0;const s=e.length-1;let n=-1,o=0;for(const a of t){const h=this.X[a];for(;n<s&&this.X[e[n+1]]<h;n++)o++;i+=o}return i}CountOnArraysUV(t,e,i,s){let n=0;const o=e.length-1;let a=-1,h=0;for(const u of t){const c=this.X[u];let m;for(;a<o&&this.X[m=e[a+1]]<c;a++)h+=s.get(m);n+=h*i.get(u)}return n}AdjExchangeLayer(t){const e=this.layers[t];return this.ExchangeWithGainWithNoDisturbance(e)?!0:(this.DisturbLayer(e),this.ExchangeWithGainWithNoDisturbance(e))}Swap(t,e){const i=this.X[t],s=this.X[e],n=this.layering[t],o=this.layers[n];o[i]=e,o[s]=t,this.X[t]=s,this.X[e]=i,this.UpdateSsContainingUv(t,e),this.UpdatePsContainingUv(t,e)}UpdatePsContainingUv(t,e){if(this.successors[t].length<=this.successors[e].length)for(const i of this.successors[t]){const s=this.pOrder[i];if(s.has(e)){const n=s.get(e),o=this.predecessors[i];o[n-1]=e,o[n]=t,s.set(e,n-1),s.set(t,n)}}else for(const i of this.successors[e]){const s=this.pOrder[i];if(s.has(t)){const n=s.get(e),o=this.predecessors[i];o[n-1]=e,o[n]=t,s.set(e,n-1),s.set(t,n)}}}UpdateSsContainingUv(t,e){if(this.predecessors[t].length<=this.predecessors[e].length)for(const i of this.predecessors[t]){const s=this.sOrder[i];if(s.has(e)){const n=s.get(e),o=this.successors[i];o[n-1]=e,o[n]=t,s.set(e,n-1),s.set(t,n)}}else for(const i of this.predecessors[e]){const s=this.sOrder[i];if(s.has(t)){const n=s.get(e),o=this.successors[i];o[n-1]=e,o[n]=t,s.set(e,n-1),s.set(t,n)}}}DisturbLayer(t){for(let e=0;e<t.length-1;e++)this.AdjacentSwapToTheRight(t,e)}ExchangeWithGainWithNoDisturbance(t){let e=!1,i;do i=this.ExchangeWithGain(t),e=e||i;while(i);return e}ExchangeWithGain(t){for(let e=0;e<t.length-1;e++)if(this.SwapWithGain(t[e],t[e+1]))return this.SwapToTheLeft(t,e),this.SwapToTheRight(t,e+1),!0;return!1}SwapToTheLeft(t,e){for(let i=e-1;i>=0;i--)this.AdjacentSwapToTheRight(t,i)}SwapToTheRight(t,e){for(let i=e;i<t.length-1;i++)this.AdjacentSwapToTheRight(t,i)}AdjacentSwapToTheRight(t,e){const i=t[e],s=t[e+1],n=this.SwapGain(i,s);(n>0||n===0&&Yo())&&this.Swap(i,s)}SwapGain(t,e){const i=this.CalcPair(t,e);return i.cuv-i.cvu}UvAreOfSameKind(t,e){return t<this.startOfVirtNodes&&e<this.startOfVirtNodes||t>=this.startOfVirtNodes&&e>=this.startOfVirtNodes}NeighborsForbidTheSwap(t,e){return this.UpperNeighborsForbidTheSwap(t,e)||this.LowerNeighborsForbidTheSwap(t,e)}LowerNeighborsForbidTheSwap(t,e){let i,s;return(i=this.properLayeredGraph.OutEdgesCount(t))===0||(s=this.properLayeredGraph.OutEdgesCount(e))===0?!1:this.X[this.successors[t][i>>1]]<this.X[this.successors[e][s>>1]]}UpperNeighborsForbidTheSwap(t,e){const i=this.properLayeredGraph.InEdgesCount(t),s=this.properLayeredGraph.InEdgesCount(e);return i===0||s===0?!1:this.X[this.predecessors[t][i>>1]]<this.X[this.predecessors[e][s>>1]]}CalcDeltaBetweenGroupsToTheLeftAndToTheRightOfTheSeparator(t,e,i){const s=this.GetKindDelegate(i);let n=0;for(let a=e-1;a>=0&&!s(t[a]);a--)n++;let o=0;for(let a=e+1;a<t.length&&!s(t[a]);a++)o++;return n-o}IsOriginal(t){return t<this.startOfVirtNodes}IsVirtual(t){return t>=this.startOfVirtNodes}GetKindDelegate(t){return this.IsVirtual(t)?this.IsVirtual:this.IsOriginal}SwapWithGain(t,e){return this.SwapGain(t,e)>0?(this.Swap(t,e),!0):!1}}class Ko{constructor(t,e,i){this.properLayeredGraph=t,this.layerArrays=e,this.nodePositions=i}static UpdateLayerArrays0(t,e,i){new Ko(t,e,i).UpdateLayerArrays()}static UpdateLayerArrays1(t,e){const i=Ko.BuildInitialNodePositions(t,e);this.UpdateLayerArrays0(t,e,i)}static BuildInitialNodePositions(t,e){const i=new Map;for(let s=0;s<e.Layers.length;s++){let n=0,o=0;for(;n<e.Layers[s].length;){for(;n<e.Layers[s].length&&t.IsVirtualNode(e.Layers[s][n]);)n++;for(let a=o;a<n;a++)i.set(e.Layers[s][a],new d(s,o));n<e.Layers[s].length&&i.set(e.Layers[s][n],new d(s,n)),n++,o=n}}return i}UpdateLayerArrays(){let t=this.CreateInitialOrdering();t=this.BuildOrdering(t),this.RestoreLayerArrays(t)}CreateInitialOrdering(){const t=new si;for(const e of this.layerArrays.Layers)for(const i of e){const s=this.nodePositions.get(i);t.hasxy(s.x,s.y)||t.setxy(s.x,s.y,[]),t.getxy(s.x,s.y).push(i)}return t}BuildOrdering(t){const e=new si,i=new Map;for(const s of this.layerArrays.Layers)for(const n of s){const o=this.nodePositions.get(n);e.hasxy(o.x,o.y)||(this.BuildNodeOrdering(t.get(o),i),e.set(o,t.get(o)))}return e}BuildNodeOrdering(t,e){t.sort(this.Comparison(e));for(let i=0;i<t.length;i++)e.set(t[i],i)}firstSucc(t){for(const e of this.properLayeredGraph.Succ(t))return e}firstPred(t){for(const e of this.properLayeredGraph.Pred(t))return e}Comparison(t){return(e,i)=>{const s=this.firstSucc(e),n=this.firstSucc(i);let o=this.firstPred(e),a=this.firstPred(i);const h=this.nodePositions.get(s),u=this.nodePositions.get(n),c=this.nodePositions.get(o),m=this.nodePositions.get(a);if(!h.equal(u))return c.equal(m)?h.compareTo(u):c.compareTo(m);if(this.properLayeredGraph.IsVirtualNode(s)){if(!c.equal(m))return c.compareTo(m);const S=t.get(s),A=t.get(n);return W(S,A)}for(;this.nodePositions.get(o).equal(this.nodePositions.get(a))&&this.properLayeredGraph.IsVirtualNode(o);)o=this.firstPred(o),a=this.firstPred(a);return this.nodePositions.get(o).equal(this.nodePositions.get(a))?W(e,i):this.nodePositions.get(o).compareTo(this.nodePositions.get(a))}}RestoreLayerArrays(t){for(const e of this.layerArrays.Layers){let i=0,s=0;for(;i<e.length;){for(;i<e.length&&this.nodePositions.get(e[s]).equal(this.nodePositions.get(e[i]));)i++;const n=t.get(this.nodePositions.get(e[s]));for(let o=s;o<i;o++)e[o]=n[o-s];s=i}}this.layerArrays.UpdateXFromLayers()}}function Zd(l){const t=new Array(l.nodeCount).fill(!1),e=new Array(l.nodeCount).fill(!1);for(let i=0;i<l.nodeCount;i++)if(hh(l,i,t,e))return!0;return!1}class Jo{static getOrder(t,e){const i=ni(e.map(([s,n])=>new Ot(s,n)),t);return Jo.getOrderOnGraph(i)}static getOrderOnGraph(t){const e=new Array(t.nodeCount).fill(!1),i=new Yt.B,s=[];let n;for(let o=0;o<t.nodeCount;o++){if(e[o])continue;let a=o;e[a]=!0;let h=0;n=t.outEdges[o];do{for(;h<n.length;h++){const u=n[h].target;e[u]||(e[u]=!0,i.push({edges:n,index:h+1,current_u:a}),a=u,n=t.outEdges[a],h=-1)}if(s.push(a),i.length>0){const u=i.pop();n=u.edges,h=u.index,a=u.current_u}else break}while(!0)}return s.reverse()}}function hh(l,t,e,i){if(i[t])return!0;if(e[t])return!1;i[t]=!0,e[t]=!0;for(const s of l.outEdges[t])if(hh(l,s.target,e,i))return!0;return i[t]=!1,!1}class xc{constructor(t){this.graph=t}GetLayers(){const t=Jo.getOrderOnGraph(this.graph),e=new Array(this.graph.nodeCount).fill(0);let i=this.graph.nodeCount;for(;i-- >0;){const s=t[i];for(const n of this.graph.inEdges[s]){const o=n.source,a=e[s]+n.separation;e[o]<a&&(e[o]=a)}}return e}checkTopoOrder(t){for(const e of this.graph.edges)if(Oc(e,t))return!1;return!0}}function Oc(l,t){const e=t.findIndex(s=>s===l.source),i=t.findIndex(s=>s===l.target);return e===-1||i===-1||e>=i}class li{constructor(t){this.inTree=!1,this.cut=li.infinity,this.iedge=t}get source(){return this.iedge.source}get target(){return this.iedge.target}get separation(){return this.iedge.separation}get crossingWeight(){return this.iedge.CrossingWeight}get weight(){return this.iedge.weight}}li.infinity=Number.MAX_SAFE_INTEGER;function Lc(l){const t=new Array;for(const e of l.edges)t.push(new li(e));return ni(t,l.nodeCount)}class Na{constructor(t,e,i,s,n){this.v=t,this.outEnum=e,this.i=i,this.inEnum=s,this.j=n}}class uh{constructor(t,e){this.layers=null,this.treeVertices=[],this.vertices=[],this.leaves=[],this.graph=Lc(t),this.networkCancelToken=e;for(let i=0;i<this.graph.nodeCount;i++)this.vertices.push({inTree:!1,lim:-1,low:-1,parent:null})}get weight(){return this.graph.edges.map(t=>t.weight*(this.layers[t.source]-this.layers[t.target])).reduce((t,e)=>t+e,0)}get nodeCount(){return this.vertices.length}setLow(t,e){this.vertices[t].low=e}setLim(t,e){this.vertices[t].lim=e}setParent(t,e){this.vertices[t].parent=e}GetLayers(){return this.layers==null&&this.run(),this.layers}shiftLayerToZero(){const t=Math.min(...this.layers);for(let e=0;e<this.layers.length;e++)this.layers[e]-=t}addVertexToTree(t){this.vertices[t].inTree=!0}vertexInTree(t){return this.vertices[t].inTree}lim(t){return this.vertices[t].lim}low(t){return this.vertices[t].low}parent(t){return this.vertices[t].parent}feasibleTree(){for(this.initLayers();this.tightTree()<this.nodeCount;){const t=this.getNonTreeEdgeIncidentToTheTreeWithMinimalAmountOfSlack();if(t==null)break;let e=this.slack(t);this.vertexInTree(t.source)&&(e=-e);for(const i of this.treeVertices)this.layers[i]+=e}this.initCutValues()}vertexSourceTargetVal(t,e){const i=e.source,s=e.target;return this.lim(i)>this.lim(s)?this.lim(t)<=this.lim(s)&&this.low(s)<=this.lim(t)?0:1:this.lim(t)<=this.lim(i)&&this.low(i)<=this.lim(t)?1:0}incidentEdges(t){return this.graph.incidentEdges(t)}allLowCutsHaveBeenDone(t){for(const e of this.incidentEdges(t))if(e.inTree&&e.cut===li.infinity&&e!==this.parent(t))return!1;return!0}edgeSourceTargetVal(t,e){return this.vertexSourceTargetVal(t.source,e)-this.vertexSourceTargetVal(t.target,e)}initCutValues(){this.initLimLowAndParent();let t=new Yt.B;for(const i of this.leaves)t.push(i);let e=new Yt.B;for(;t.length>0;){for(;t.length>0;){const s=t.pop(),n=this.parent(s);if(n==null)continue;let o=0;for(const h of this.incidentEdges(s))if(h.inTree===!1){const u=this.edgeSourceTargetVal(h,n);u!==0&&(o+=u*h.weight)}else if(h===n)o+=h.weight;else{const u=n.source===h.target||n.target===h.source?1:-1,c=this.edgeContribution(h,s);o+=c*u}n.cut=o;const a=n.source===s?n.target:n.source;this.allLowCutsHaveBeenDone(a)&&e.push(a)}const i=t;t=e,e=i}}edgeContribution(t,e){let i=t.cut-t.weight;for(const s of this.incidentEdges(e))if(s.inTree===!1){const n=this.edgeSourceTargetVal(s,t);n===-1?i+=s.weight:n===1&&(i-=s.weight)}return i}initLimLowAndParent(){this.initLowLimParentAndLeavesOnSubtree(1,0)}initLowLimParentAndLeavesOnSubtree(t,e){const i=new Yt.B;let s=this.graph.outEdges[e],n=-1,o=this.graph.inEdges[e],a=-1;for(i.push(new Na(e,s,n,o,a)),this.vertices[e].low=t;i.length>0;){const h=i.pop();e=h.v,s=h.outEnum,n=h.i,o=h.inEnum,a=h.j;let u;do{for(u=!0;++n<s.length;){const c=s[n];!c.inTree||this.vertices[c.target].low>0||(i.push(new Na(e,s,n,o,a)),e=c.target,this.setParent(e,c),this.setLow(e,t),s=this.graph.outEdges[e],n=-1,o=this.graph.inEdges[e],a=-1)}for(;++a<o.length;){const c=o[a];if(!(!c.inTree||this.vertices[c.source].low>0)){i.push(new Na(e,s,n,o,a)),e=c.source,this.setLow(e,t),this.setParent(e,c),s=this.graph.outEdges[e],n=-1,o=this.graph.inEdges[e],a=-1,u=!1;break}}}while(!u);this.setLim(e,t++),this.lim(e)===this.low(e)&&this.leaves.push(e)}}updateLimLowLeavesAndParentsUnderNode(t){const e=this.vertices[t].low,i=this.vertices[t].lim;this.leaves=[];for(let s=0;s<this.nodeCount;s++)e<=this.vertices[s].lim&&this.vertices[s].lim<=i?this.setLow(s,0):this.low(s)===this.lim(s)&&this.leaves.push(s);this.initLowLimParentAndLeavesOnSubtree(e,t)}slack(t){return this.layers[t.source]-this.layers[t.target]-t.separation}getNonTreeEdgeIncidentToTheTreeWithMinimalAmountOfSlack(){let t=null,e=li.infinity;for(const i of this.treeVertices){for(const s of this.graph.outEdges[i]){if(this.vertexInTree(s.source)&&this.vertexInTree(s.target))continue;const n=this.slack(s);if(n<e&&(t=s,e=n,n===1))return s}for(const s of this.graph.inEdges[i]){if(this.vertexInTree(s.source)&&this.vertexInTree(s.target))continue;const n=this.slack(s);if(n<e&&(t=s,e=n,n===1))return s}}return t}tightTree(){this.treeVertices=[];for(const e of this.graph.edges)e.inTree=!1;for(let e=1;e<this.nodeCount;e++)this.vertices[e].inTree=!1;this.vertices[0].inTree=!0,this.treeVertices.push(0);const t=new Yt.B;for(t.push(0);t.length>0;){const e=t.pop();for(const i of this.graph.outEdges[e])this.vertexInTree(i.target)||this.layers[i.source]-this.layers[i.target]===i.separation&&(t.push(i.target),this.addVertexToTree(i.target),this.treeVertices.push(i.target),i.inTree=!0);for(const i of this.graph.inEdges[e])this.vertexInTree(i.source)||this.layers[i.source]-this.layers[i.target]===i.separation&&(t.push(i.source),this.addVertexToTree(i.source),this.treeVertices.push(i.source),i.inTree=!0)}return this.treeVertices.length}leaveEnterEdge(){let t,e,i=0;for(const o of this.graph.edges)o.inTree&&o.cut<i&&(i=o.cut,t=o);if(t==null)return null;let s=!1,n=li.infinity;for(const o of this.graph.edges){const a=this.slack(o);if(o.inTree===!1&&this.edgeSourceTargetVal(o,t)===-1&&(a<n||a===n&&(s=xs(2)===1))){if(n=a,e=o,n===0&&!s)break;s=!1}}if(e==null)throw new Error;return{leaving:t,entering:e}}exchange(t,e){const i=this.commonPredecessorOfSourceAndTargetOfF(e);this.createPathForCutUpdates(t,e,i),this.updateLimLowLeavesAndParentsUnderNode(i),this.updateCuts(t),this.updateLayersUnderNode(i)}updateLayersUnderNode(t){const e=new Yt.B;e.push(t);for(let i=0;i<this.nodeCount;i++)this.low(t)<=this.lim(i)&&this.lim(i)<=this.lim(t)&&i!==t&&(this.layers[i]=li.infinity);for(;e.length>0;){const i=e.pop();for(const s of this.graph.outEdges[i])s.inTree&&this.layers[s.target]===li.infinity&&(this.layers[s.target]=this.layers[i]-s.separation,e.push(s.target));for(const s of this.graph.inEdges[i])s.inTree&&this.layers[s.source]===li.infinity&&(this.layers[s.source]=this.layers[i]+s.separation,e.push(s.source))}}updateCuts(t){let e=new Yt.B,i=new Yt.B;for(e.push(t.source),e.push(t.target);e.length>0;){for(;e.length>0;){const n=e.pop(),o=this.parent(n);if(o==null||o.cut!==li.infinity)continue;let a=0;for(const u of this.incidentEdges(n))if(u.inTree===!1)a+=this.edgeSourceTargetVal(u,o)*u.weight;else if(u===o)a+=u.weight;else{const c=o.source===u.target||o.target===u.source?1:-1,m=this.edgeContribution(u,n);a+=m*c}o.cut=a;const h=o.source===n?o.target:o.source;this.allLowCutsHaveBeenDone(h)&&i.push(h)}const s=e;e=i,i=s}}createPathForCutUpdates(t,e,i){let s=e.target;for(;s!==i;){const n=this.parent(s);n.cut=li.infinity,s=n.source===s?n.target:n.source}e.cut=li.infinity,t.inTree=!1,e.inTree=!0}commonPredecessorOfSourceAndTargetOfF(t){let e,i;this.lim(t.source)<this.lim(t.target)?(e=this.lim(t.source),i=this.lim(t.target)):(e=this.lim(t.target),i=this.lim(t.source));let s=t.source;for(;!(this.low(s)<=e&&i<=this.lim(s));){const n=this.parent(s);n.cut=li.infinity,s=n.source===s?n.target:n.source}return s}checkCutValues(){for(const t of this.graph.edges)if(t.inTree){let e=0;for(const i of this.graph.edges)e+=this.edgeSourceTargetVal(i,t)*i.weight;t.cut!==e&&console.log(Se.Qf.Format("cuts are wrong for {0}; should be {1} but is {2}",t,e,t.cut))}}initLayers(){const t=new xc(this.graph);return this.layers=t.GetLayers()}run(){if(this.graph.edges.length===0&&this.graph.nodeCount===0)this.layers=[];else{this.feasibleTree();let t;for(;(t=this.leaveEnterEdge())!=null;)this.exchange(t.leaving,t.entering);this.shiftLayerToZero()}}}class Bc{constructor(t,e){this.graph=t,this.Cancel=e}GetLayers(){return new uh(this.graph,this.Cancel).GetLayers()}ShrunkComponent(t){const e=[];for(const i of t){const s=i[0],n=i[1];for(const o of this.graph.outEdges[s]){const a=new $i(n,t.get(o.target),o.edge);a.separation=o.separation,a.weight=o.weight,e.push(a)}}return new Yr(e,t.size)}}class Si{constructor(t){this.padding=0,this.alreadySitsOnASpline=!1,this.labelIsToTheLeftOfTheSpline=!1,this.labelIsToTheRightOfTheSpline=!1,this.labelCornersPreserveCoefficient=t}toString(){return"la:ra "+this.la+" "+this.ra+" ta:ba "+this.ta+" "+this.ba+" x:y "+this.x_+" "+this.y_}get leftAnchor(){return this.la}set leftAnchor(t){this.la=Math.max(t,0)}get rightAnchor(){return this.ra}set rightAnchor(t){this.ra=Math.max(t,0)}get topAnchor(){return this.ta}set topAnchor(t){this.ta=Math.max(t,0)}get bottomAnchor(){return this.ba}set bottomAnchor(t){this.ba=Math.max(t,0)}get left(){return this.x_-this.la}get right(){return this.x_+this.ra}get top(){return this.y_+this.ta}set top(t){this.y_+=t-this.ta}get bottom(){return this.y_-this.ba}set bottom(t){this.y_+=t-this.ba}get leftTop(){return new d(this.left,this.top)}get leftBottom(){return new d(this.left,this.bottom)}get rightBottom(){return new d(this.right,this.bottom)}get node(){return this.node_}set node(t){this.node_=t,this.polygonalBoundary_=null}get rightTop(){return new d(this.right,this.top)}static mkAnchor(t,e,i,s,n,o){const a=new Si(o);return a.la=t,a.ra=e,a.ta=i,a.ba=s,a.node=n,a}get x(){return this.x_}set x(t){this.polygonalBoundary_=null,this.x_=t}get y(){return this.y_}set y(t){this.polygonalBoundary_=null,this.y_=t}get origin(){return new d(this.x,this.y)}get width(){return this.la+this.ra}get height(){return this.ta+this.ba}get hasLabel(){return this.labelIsToTheLeftOfTheSpline||this.labelIsToTheLeftOfTheSpline}get LabelWidth(){if(this.labelIsToTheLeftOfTheSpline)return this.leftAnchor;if(this.labelIsToTheRightOfTheSpline)return this.rightAnchor;throw new Error}get polygonalBoundary(){return this.polygonalBoundary_!=null?this.polygonalBoundary_:this.polygonalBoundary_=Si.pad(this.creatPolygonalBoundaryWithoutPadding(),this.padding)}static pad(t,e){return e===0?t:Si.curveIsConvex(t)?Si.padConvexCurve(t,e):Si.padConvexCurve(t.boundingBox.perimeter(),e)}static padCorner(t,e,i,s,n){const o=Si.getPaddedCorner(e,i,s,n);t.addPoint(o.a),o.numberOfPoints===2&&t.addPoint(o.b)}static padConvexCurve(t,e){const i=new at;Si.padCorner(i,t.endPoint.prev,t.endPoint,t.startPoint,e),Si.padCorner(i,t.endPoint,t.startPoint,t.startPoint.next,e);for(let s=t.startPoint;s.next.next!=null;s=s.next)Si.padCorner(i,s,s.next,s.next.next,e);return i.closed=!0,i}static getPaddedCorner(t,e,i,s){const n=t.point,o=e.point,a=i.point,h=d.getTriangleOrientation(n,o,a)===k.Counterclockwise,u=o.sub(n),c=u.rotate((h?-Math.PI:Math.PI)/2).normalize(),m=u.normalize().add(o.sub(a).normalize());if(m.length<C.intersectionEpsilon)return{a:o.add(c.mul(s)),b:null,numberOfPoints:1};const S=m.normalize().mul(s),A=S.rotate(Math.PI/2),I=(s-S.dot(c))/A.dot(c);return{a:S.add(A.mul(I)).add(o),b:S.sub(A.mul(I)).add(o),numberOfPoints:2}}static*orientations(t){yield d.getTriangleOrientation(t.endPoint.point,t.startPoint.point,t.startPoint.next.point),yield d.getTriangleOrientation(t.endPoint.prev.point,t.endPoint.point,t.startPoint.point);let e=t.startPoint;for(;e.next.next!=null;)yield d.getTriangleOrientation(e.point,e.next.point,e.next.next.point),e=e.next}static curveIsConvex(t){let e=k.Collinear;for(const i of Si.orientations(t))if(i!==k.Collinear){if(e===k.Collinear)e=i;else if(i!==e)return!1}return!0}creatPolygonalBoundaryWithoutPadding(){return this.hasLabel?this.labelIsToTheLeftOfTheSpline?this.polygonOnLeftLabel():this.polygonOnRightLabel():this.nodeBoundary==null?this.standardRectBoundary():w.polylineAroundClosedCurve(this.nodeBoundary)}get nodeBoundary(){return this.node==null?null:this.node.boundaryCurve}standardRectBoundary(){const t=new at;return t.addPoint(this.leftTop),t.addPoint(this.rightTop),t.addPoint(this.rightBottom),t.addPoint(this.leftBottom),t.closed=!0,t}polygonOnLeftLabel(){const t=this.left+(1-this.labelCornersPreserveCoefficient)*this.LabelWidth;return at.mkClosedFromPoints([new d(t,this.top),this.rightTop,this.rightBottom,new d(t,this.bottom),new d(this.left,this.y)])}polygonOnRightLabel(){const t=this.right-(1-this.labelCornersPreserveCoefficient)*this.LabelWidth;return at.mkClosedFromPoints([new d(t,this.top),new d(this.right,this.y),new d(t,this.bottom),this.leftBottom,this.leftTop])}move(t){this.x+=t.x,this.y+=t.y}}class In{constructor(t,e,i,s,n){this.xCoords=new Array(4),this.la=t,this.graph=e,this.nOfOriginalVertices=i,this.nOfVertices=this.graph.NodeCount,this.markedEdges=new ji,this.h=this.la.Layers.length,this.root=new Array(this.nOfVertices),this.align=new Array(this.nOfVertices),this.anchors=s,this.nodeSep=n}get CurrentEnumRightUp(){return(this.LR?0:1)+2*(this.BT?0:1)}IsVirtual(t){return t>=this.nOfOriginalVertices}Source(t){return this.BT?t.Source:t.Target}Target(t){return this.BT?t.Target:t.Source}static CalculateXCoordinates(t,e,i,s,n){new In(t,e,i,s,n).Calculate()}Calculate(){this.SortInAndOutEdges(),this.RightUpSetup(),this.CalcBiasedAlignment(),this.LeftUpSetup(),this.CalcBiasedAlignment(),this.RightDownSetup(),this.CalcBiasedAlignment(),this.LeftDownSetup(),this.CalcBiasedAlignment(),this.HorizontalBalancing()}SortInAndOutEdges(){this.FillLowMedians(),this.FillUpperMedins()}FillUpperMedins(){this.upperMedians=new Array(this.graph.NodeCount);for(let t=0;t<this.graph.NodeCount;t++)this.FillUpperMediansForNode(t)}CompareByX(t,e){return this.la.x[t]-this.la.x[e]}FillUpperMediansForNode(t){let e=this.graph.InEdgesCount(t);if(e>0){const i=new Array(e);e=0;for(const n of this.graph.InEdges(t))i[e++]=n.Source;i.sort((n,o)=>this.CompareByX(n,o));const s=Math.floor(e/2);s*2===e?this.upperMedians[t]=new Ot(i[s-1],i[s]):this.upperMedians[t]=i[s]}else this.upperMedians[t]=-1}FillLowMedians(){this.lowMedians=new Array(this.graph.NodeCount);for(let t=0;t<this.graph.NodeCount;t++)this.FillLowMediansForNode(t)}FillLowMediansForNode(t){let e=this.graph.OutEdgesCount(t);if(e>0){const i=new Array(e);e=0;for(const n of this.graph.OutEdges(t))i[e++]=n.Target;i.sort((n,o)=>this.CompareByX(n,o));const s=Math.floor(e/2);s*2===e?this.lowMedians[t]=new Ot(i[s-1],i[s]):this.lowMedians[t]=i[s]}else this.lowMedians[t]=-1}HorizontalBalancing(){let t=-1;const e=new Array(4),i=new Array(4);let s=Number.MAX_VALUE;for(let o=0;o<4;o++){const a={a:0,b:0};this.AssignmentBounds(o,a),e[o]=a.a,i[o]=a.b;const h=i[o]-e[o];h<s&&(t=o,s=h)}for(let o=0;o<4;o++){let a;if(In.IsLeftMostAssignment(o)?a=e[t]-e[o]:a=i[t]-i[o],this.x=this.xCoords[o],a!==0)for(let h=0;h<this.nOfVertices;h++)this.x[h]=this.x[h]+a}const n=new Array(4);for(let o=0;o<this.nOfVertices;o++)n[0]=this.xCoords[0][o],n[1]=this.xCoords[1][o],n[2]=this.xCoords[2][o],n[3]=this.xCoords[3][o],n.sort((a,h)=>a-h),this.anchors[o].x=(n[1]+n[2])/2}static IsLeftMostAssignment(t){return t===0||t===2}AssignmentBounds(t,e){if(this.nOfVertices===0)e.a=0,e.b=0;else{this.x=this.xCoords[t],e.a=e.b=this.x[0];for(let i=1;i<this.nOfVertices;i++){const s=this.x[i];s<e.a?e.a=s:s>e.b&&(e.b=s)}}}CalcBiasedAlignment(){this.ConflictElimination(),this.Align()}LeftUpSetup(){this.LR=!1,this.BT=!0}LeftDownSetup(){this.LR=!1,this.BT=!1}RightDownSetup(){this.LR=!0,this.BT=!1}RightUpSetup(){this.LR=!0,this.BT=!0}ConflictElimination(){this.RemoveMarksFromEdges(),this.MarkConflictingEdges()}*UpperEdgeMedians(t){const e=this.BT?this.upperMedians[t]:this.lowMedians[t];if(typeof e!="number"){const s=e;this.LR?(yield s.x,yield s.y):(yield s.y,yield s.x)}else{const s=e;s>=0&&(yield s)}}MarkConflictingEdges(){let t=this.LowerOf(0,this.h-1);const e=t,i=this.UpperOf(0,this.h-1),s=this.NextLower(i);for(;this.IsBelow(t,i);t=this.NextUpper(t))this.IsBelow(e,t)&&this.IsBelow(t,s)&&this.ConflictsWithAtLeastOneInnerEdgeForALayer(t)}NextUpper(t){return this.BT?t+1:t-1}NextLower(t){return this.BT?t-1:t+1}UpperOf(t,e){return this.BT?Math.max(t,e):Math.min(t,e)}LowerOf(t,e){return this.BT?Math.min(t,e):Math.max(t,e)}IsBelow(t,e){return this.BT?t<e:e<t}LeftMost(t,e){return this.LR?Math.min(t,e):Math.max(t,e)}RightMost(t,e){return this.LR?Math.max(t,e):Math.min(t,e)}IsNotRightFrom(t,e){return this.LR?t<=e:e<=t}IsLeftFrom(t,e){return this.LR?t<e:e<t}NextRight(t){return this.LR?t+1:t-1}NextLeft(t){return this.LR?t-1:t+1}ConflictsWithAtLeastOneInnerEdgeForALayer(t){if(t>=0&&t<this.la.Layers.length){const e=this.la.Layers[t];let i=null,s=this.LeftMost(0,e.length-1);const n=this.RightMost(0,e.length-1);for(;this.IsNotRightFrom(s,n)&&i==null;s=this.NextRight(s))i=this.InnerEdgeByTarget(e[s]);if(i!=null){const o=this.Pos(this.Source(i));for(let h=this.LeftMost(0,e.length-1);this.IsLeftFrom(h,s);h=this.NextRight(h))for(const u of this.InEdges(e[h]))this.IsLeftFrom(o,this.Pos(this.Source(u)))&&this.MarkEdge(u);let a=this.Pos(this.Source(i));for(;this.IsNotRightFrom(s,n);){const h=this.AlignmentToTheRightOfInner(e,s,o);if(s=this.NextRight(s),h!=null){const u=this.Pos(this.Source(h));this.MarkEdgesBetweenInnerAndNewInnerEdges(e,i,h,a,u),i=h,a=u}}for(let h=this.NextRight(this.Pos(this.Target(i)));this.IsNotRightFrom(h,n);h=this.NextRight(h))for(const u of this.InEdges(e[h]))this.IsLeftFrom(this.Pos(this.Source(u)),this.Pos(this.Source(i)))&&this.MarkEdge(u)}}}InEdgeOfVirtualNode(t){return this.BT?this.graph.InEdgeOfVirtualNode(t):this.graph.OutEdgeOfVirtualNode(t)}InEdges(t){return this.BT?this.graph.InEdges(t):this.graph.OutEdges(t)}MarkEdgesBetweenInnerAndNewInnerEdges(t,e,i,s,n){let o=this.NextRight(this.Pos(this.Target(e)));for(;this.IsLeftFrom(o,this.Pos(this.Target(i)));o=this.NextRight(o))for(const a of this.InEdges(t[o])){const h=this.Pos(this.Source(a));this.IsLeftFrom(h,s)?this.MarkEdge(a):this.IsLeftFrom(n,h)&&this.MarkEdge(a)}}AlignmentToTheRightOfInner(t,e,i){if(this.NumberOfInEdges(t[e])===1){let n=null;for(const o of this.InEdges(t[e]))n=o;return this.IsInnerEdge(n)&&this.IsLeftFrom(i,this.Pos(n.Source))?n:null}return null}NumberOfInEdges(t){return this.BT?this.graph.InEdgesCount(t):this.graph.OutEdgesCount(t)}Pos(t){return this.la.x[t]}InnerEdgeByTarget(t){if(this.IsVirtual(t)){const e=this.InEdgeOfVirtualNode(t);if(this.IsVirtual(this.Source(e)))return e}return null}IsInnerEdge(t){return this.IsVirtual(t.Source)&&this.IsVirtual(t.Target)}RemoveMarksFromEdges(){this.markedEdges.clear()}Align(){this.CreateBlocks(),this.AssignCoordinatesByLongestPath()}AssignCoordinatesByLongestPath(){this.x=this.xCoords[this.CurrentEnumRightUp]=new Array(this.nOfVertices);const t=new Array;for(let s=0;s<this.nOfVertices;s++)if(s===this.root[s]){let n=s;do{const o={neighbor:0};this.TryToGetRightNeighbor(n,o)&&t.push(new $i(s,this.root[o.neighbor],null)),n=this.align[n]}while(n!==s)}const e=ni(t,this.nOfVertices),i=Jo.getOrderOnGraph(e);for(const s of i)if(s===this.root[s]){let n=0,o=!0,a=s;do{const h={neighbor:0};this.TryToGetLeftNeighbor(a,h)&&(o?(n=this.x[this.root[h.neighbor]]+this.DeltaBetweenVertices(h.neighbor,a),o=!1):n=this.RightMost(n,this.x[this.root[h.neighbor]]+this.DeltaBetweenVertices(h.neighbor,a))),a=this.align[a]}while(a!==s);this.x[s]=n}for(const s of i)if(s===this.root[s]&&e.inEdges[s].length===0){let n=s,o=this.RightMost(-In.infinity,In.infinity);const a=o;do{const h={neighbor:0};this.TryToGetRightNeighbor(n,h)&&(o=this.LeftMost(o,this.x[this.root[h.neighbor]]-this.DeltaBetweenVertices(n,h.neighbor))),n=this.align[n]}while(n!==s);a!==o&&(this.x[s]=o)}for(let s=0;s<this.nOfVertices;s++)s!==this.root[s]&&(this.x[s]=this.x[this.root[s]])}TryToGetRightNeighbor(t,e){const i=this.NextRight(this.Pos(t)),s=this.la.Layers[this.la.y[t]];return i>=0&&i<s.length?(e.neighbor=s[i],!0):!1}TryToGetLeftNeighbor(t,e){const i=this.NextLeft(this.Pos(t)),s=this.la.Layers[this.la.y[t]];return i>=0&&i<s.length?(e.neighbor=s[i],!0):!1}CreateBlocks(){for(let e=0;e<this.nOfVertices;e++)this.root[e]=this.align[e]=e;const t=this.LowerOf(0,this.h-1);for(let e=this.NextLower(this.UpperOf(0,this.h-1));!this.IsBelow(e,t);e=this.NextLower(e)){const i=this.la.Layers[e];let s=this.LeftMost(-1,this.la.Layers[this.NextUpper(e)].length);const n=this.RightMost(0,i.length-1);for(let o=this.LeftMost(0,i.length-1);this.IsNotRightFrom(o,n);o=this.NextRight(o)){const a=i[o];for(const h of this.UpperEdgeMedians(a))if(!this.IsMarked(a,h)&&this.IsLeftFrom(s,this.Pos(h))){this.align[h]=a,this.root[a]=this.root[h],this.align[a]=this.root[h],s=this.Pos(h);break}}}}IsMarked(t,e){return this.BT?this.markedEdges.hasxy(e,t):this.markedEdges.hasxy(t,e)}MarkEdge(t){this.markedEdges.addNN(t.Source,t.Target)}DeltaBetweenVertices(t,e){let i;if(this.Pos(t)>this.Pos(e)){const s=t;t=e,e=s,i=-1}else i=1;return(this.anchors[t].rightAnchor+this.anchors[e].leftAnchor+this.nodeSep)*i}}In.infinity=1e7;class Fc extends Ie{constructor(t,e,i,s,n){super(),this.weightMultiplierOfOriginalOriginal=1,this.weightMultOfOneVirtual=3,this.weightMultiplierOfTwoVirtual=8,this.SetEdges(s,n),this.virtualVerticesStart=t.nodeCount,this.virtualVerticesEnd=e.NodeCount-1,this.layeredGraph=e,this.layerArrays=i}EdgeWeightMultiplier(t){const e=t.source,i=t.target;if(e<this.layeredGraph.NodeCount&&this.layerArrays.y[e]===this.layerArrays.y[i]&&this.layerArrays.x[e]===this.layerArrays.x[i]+1)return 0;let s=0,n=-1,o=-1;for(const h of this.outEdges[e])o===-1?o=h.target:n=h.target;return o>=this.virtualVerticesStart&&o<=this.virtualVerticesEnd&&s++,n>=this.virtualVerticesStart&&n<=this.virtualVerticesEnd&&s++,s===0?this.weightMultiplierOfOriginalOriginal:s===1?this.weightMultOfOneVirtual:this.weightMultiplierOfTwoVirtual}SetEdgeWeights(){for(const t of this.edges)t.weight=t.weight*this.EdgeWeightMultiplier(t)}}var Be;(function(l){l[l.Top=0]="Top",l[l.Internal=1]="Internal",l[l.Bottom=2]="Bottom"})(Be||(Be={}));class or{constructor(t,e){this.groupSplitThreshold=2,this.initialNodes=t,this.groupSplitThreshold=e}static Calculate(t,e=0){return new or(t,e).Calculate()}Calculate(){return this.Calc(this.initialNodes)}Calc(t){if(t.length===0)return null;if(t.length===1)return t[0];const e=t[0].parallelogram;let i=1,s=At.parallelogramOfTwo(e,t[i].parallelogram).area;for(let c=2;c<t.length;c++){const m=At.parallelogramOfTwo(e,t[c].parallelogram).area;m>s&&(i=c,s=m)}let n;for(let c=0;c<t.length;c++)if(c!==i){n=c;break}s=At.parallelogramOfTwo(t[i].parallelogram,t[n].parallelogram).area;for(let c=0;c<t.length;c++){if(c===i)continue;const m=At.parallelogramOfTwo(t[i].parallelogram,t[c].parallelogram).area;m>s&&(n=c,s=m)}const o=new Array,a=new Array;o.push(t[i]),a.push(t[n]);let h=t[i].parallelogram,u=t[n].parallelogram;for(let c=0;c<t.length;c++){if(c===i||c===n)continue;const m=At.parallelogramOfTwo(h,t[c].parallelogram),S=m.area-h.area,A=At.parallelogramOfTwo(u,t[c].parallelogram),I=A.area-u.area;o.length*this.groupSplitThreshold<a.length?(o.push(t[c]),h=m):a.length*this.groupSplitThreshold<o.length?(a.push(t[c]),u=A):S<I?(o.push(t[c]),h=m):(a.push(t[c]),u=A)}return{parallelogram:At.parallelogramOfTwo(h,u),node:{children:[this.Calc(o),this.Calc(a)]},seg:void 0,leafBoxesOffset:void 0}}}class yi{constructor(t,e,i,s,n,o,a,h){this.topNode=t,this.bottomNode=e,this.topSite=i,this.bottomSite=i.next,this.currentTopSite=i,this.currentBottomSite=i.next,this.layerArrays=s,this.layeredGraph=n,this.originalGraph=o,this.anchors=a,this.layerSeparation=h}static Refine(t,e,i,s,n,o,a,h){new yi(t,e,i,n,o,a,s,h).Refine()}Refine(){for(this.Init();this.InsertSites(););}FixCorner(t,e,i){if(t.equal(e))return e;const s=d.ClosestPointAtLineSegment(e,t,i);let n=e.sub(s);const o=Math.abs(n.y),a=this.layerSeparation/2;return o>a&&(n=n.mul(a/(o*2))),n.add(e)}InsertSites(){return xs(2)===0?this.CalculateNewTopSite()||this.CalculateNewBottomSite():this.CalculateNewBottomSite()||this.CalculateNewTopSite()}CalculateNewBottomSite(){const t=this.currentBottomSite.point.sub(this.currentTopSite.point);let e=yi.absCotan(t),i,s=!1;for(const n of this.bottomCorners()){const o=yi.absCotan(n.sub(this.currentBottomSite.point));o<e&&(e=o,i=n,s=!0)}return s?N(e,yi.absCotan(t))?!1:(this.currentBottomSite=Ut.mkSiteSPS(this.currentTopSite,this.FixCorner(this.currentTopSite.point,i,this.currentBottomSite.point),this.currentBottomSite),!0):!1}static absCotan(t){return Math.abs(t.x/t.y)}CalculateNewTopSite(){const t=this.currentBottomSite.point.sub(this.currentTopSite.point);let e=yi.absCotan(t),i,s=!1;for(const n of this.topCorners()){const o=yi.absCotan(n.sub(this.currentTopSite.point));o<e&&(e=o,i=n,s=!0)}return s?N(e,yi.absCotan(t))?!1:(this.currentTopSite=Ut.mkSiteSPS(this.currentTopSite,this.FixCorner(this.currentTopSite.point,i,this.currentBottomSite.point),this.currentBottomSite),!0):!1}Init(){this.IsTopToTheLeftOfBottom()?(this.topCorners=()=>this.CornersToTheRightOfTop(),this.bottomCorners=()=>this.CornersToTheLeftOfBottom()):(this.topCorners=()=>this.CornersToTheLeftOfTop(),this.bottomCorners=()=>this.CornersToTheRightOfBottom())}IsTopToTheLeftOfBottom(){return this.topSite.point.x<this.topSite.next.point.x}*NodeCorners(t){for(const e of this.anchors[t].polygonalBoundary.polylinePoints())yield e.point}*CornersToTheLeftOfBottom(){const t=this.layerArrays.x[this.bottomNode],e=this.currentTopSite.point.x,i=this.currentBottomSite.point.x;for(const s of this.LeftFromTheNode(this.NodeLayer(this.bottomNode),t,Be.Bottom,e,i))for(const n of this.NodeCorners(s))n.y>this.currentBottomSite.point.y&&yi.PossibleCorner(e,i,n)&&(yield n)}*CornersToTheLeftOfTop(){const t=this.layerArrays.x[this.topNode],e=this.currentBottomSite.point.x,i=this.currentTopSite.point.x;for(const s of this.LeftFromTheNode(this.NodeLayer(this.topNode),t,Be.Top,e,i))for(const n of this.NodeCorners(s))n.y<this.currentTopSite.point.y&&yi.PossibleCorner(e,i,n)&&(yield n)}*CornersToTheRightOfBottom(){const t=this.layerArrays.x[this.bottomNode],e=this.currentBottomSite.point.x,i=this.currentTopSite.point.x;for(const s of this.RightFromTheNode(this.NodeLayer(this.bottomNode),t,Be.Bottom,e,i))for(const n of this.NodeCorners(s))n.y>this.currentBottomSite.point.y&&yi.PossibleCorner(e,i,n)&&(yield n)}*CornersToTheRightOfTop(){const t=this.layerArrays.x[this.topNode],e=this.currentTopSite.point.x,i=this.currentBottomSite.point.x;for(const s of this.RightFromTheNode(this.NodeLayer(this.topNode),t,Be.Top,e,i))for(const n of this.NodeCorners(s))n.y<this.currentTopSite.point.y&&yi.PossibleCorner(e,i,n)&&(yield n)}static PossibleCorner(t,e,i){return i.x>t&&i.x<e}NodeLayer(t){return this.layerArrays.Layers[this.layerArrays.y[t]]}IsLabel(t){return this.anchors[t].hasLabel}NodeUCanBeCrossedByNodeV(t,e){return this.IsLabel(t)||this.IsLabel(e)?!1:!!(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e)&&this.AdjacentEdgesIntersect(t,e))}AdjacentEdgesIntersect(t,e){return this.Intersect(this.IncomingEdge(t),this.IncomingEdge(e))||this.Intersect(this.OutcomingEdge(t),this.OutcomingEdge(e))}Intersect(t,e){return(this.layerArrays.x[t.Source]-this.layerArrays.x[e.Source])*(this.layerArrays.x[t.Target]-this.layerArrays.x[e.Target])<0}IncomingEdge(t){for(const e of this.layeredGraph.InEdges(t))return e;throw new Error}OutcomingEdge(t){for(const e of this.layeredGraph.OutEdges(t))return e;throw new Error}IsVirtualVertex(t){return t>=this.originalGraph.shallowNodeCount}*RightFromTheNode(t,e,i,s,n){let o=0,a=0;i===Be.Bottom&&(o=Number.MAX_VALUE),i===Be.Top&&(a=Number.MAX_VALUE);const h=t[e];for(let u=e+1;u<t.length;u++){const c=t[u];if(this.NodeUCanBeCrossedByNodeV(c,h))continue;const m=this.anchors[c];if(m.left>=n)break;m.right>s&&(m.topAnchor>a+C.distanceEpsilon?(a=m.topAnchor,yield c):m.bottomAnchor>o+C.distanceEpsilon&&(o=m.bottomAnchor,yield c))}}*LeftFromTheNode(t,e,i,s,n){let o=0,a=0;i===Be.Bottom&&(o=Number.MAX_VALUE),i===Be.Top&&(a=Number.MAX_VALUE);const h=t[e];for(let u=e-1;u>-1;u--){const c=t[u];if(this.NodeUCanBeCrossedByNodeV(c,h))continue;const m=this.anchors[c];if(m.right<=s)break;m.left<n&&(m.topAnchor>a+C.distanceEpsilon?(a=m.topAnchor,yield c):m.bottomAnchor>o+C.distanceEpsilon&&(o=m.bottomAnchor,yield c))}}}function _d(l){return DebugCurve.mkDebugCurveTWCI(100,1,"black",l.polygonalBoundary)}function tg(l,t){return DebugCurve.mkDebugCurveTWCI(200,2,t,CurveFactory.mkCircle(10,l))}class Ue{constructor(t,e,i,s,n,o,a){this.thinRightNodes=new Array,this.thinWestNodes=new Array,this.database=a,this.edgePath=t,this.anchors=e,this.layerArrays=n,this.originalGraph=i,this.settings=s,this.layeredGraph=o,this.eastHierarchy=this.BuildEastHierarchy(),this.westHierarchy=this.BuildWestHierarchy()}BuildEastHierarchy(){const t=this.FindEastBoundaryAnchorCurves(),e=new Array;for(const i of t)e.push(i.pNodeOverICurve());return this.thinEastHierarchy=or.Calculate(this.thinRightNodes),or.Calculate(e)}BuildWestHierarchy(){const t=this.FindWestBoundaryAnchorCurves(),e=new Array;for(const i of t)e.push(i.pNodeOverICurve());return this.thinWestHierarchy=or.Calculate(this.thinWestNodes),or.Calculate(e)}FindEastBoundaryAnchorCurves(){const t=new Array;let e=0;for(const i of this.edgePath){let s=null;for(const n of this.EastBoundaryNodesOfANode(i,qs.GetNodeKind(e,this.edgePath))){const o=this.anchors[n];(s==null||s.origin.x>o.origin.x)&&(s=o),t.push(o.polygonalBoundary)}s!=null&&this.thinRightNodes.push(D.mkLinePXY(s.origin,this.originalGraph.right,s.y).pNodeOverICurve()),e++}return t}FindWestBoundaryAnchorCurves(){const t=[];let e=0;for(const i of this.edgePath.nodes()){let s=-1;for(const n of this.LeftBoundaryNodesOfANode(i,qs.GetNodeKind(e,this.edgePath)))(s===-1||this.layerArrays.x[n]>this.layerArrays.x[s])&&(s=n),t.push(this.anchors[n].polygonalBoundary);if(s!==-1){const n=this.anchors[s];this.thinWestNodes.push(D.mkLinePXY(n.origin,this.originalGraph.left,n.origin.y).pNodeOverICurve())}e++}return t}*FillRightTopAndBottomVerts(t,e,i){let s=0,n=0;i===Be.Bottom?s=Number.MAX_VALUE:i===Be.Top&&(n=Number.MAX_VALUE);const o=t[e];for(let a=e+1;a<t.length;a++){const h=t[a],u=this.anchors[h];u.topAnchor>n?this.NodeUCanBeCrossedByNodeV(h,o)||(n=u.topAnchor,u.bottomAnchor>s&&(s=u.bottomAnchor),yield h):u.bottomAnchor>s&&(this.NodeUCanBeCrossedByNodeV(h,o)||(s=u.bottomAnchor,u.topAnchor>n&&(n=u.topAnchor),yield h))}}*FillLeftTopAndBottomVerts(t,e,i){let s=0,n=0;i===Be.Top?n=Number.MAX_VALUE:i===Be.Bottom&&(s=Number.MAX_VALUE);const o=t[e];for(let a=e-1;a>=0;a--){const h=t[a],u=this.anchors[h];u.topAnchor>n+C.distanceEpsilon?this.NodeUCanBeCrossedByNodeV(h,o)||(n=u.topAnchor,s=Math.max(s,u.bottomAnchor),yield h):u.bottomAnchor>s+C.distanceEpsilon&&(this.NodeUCanBeCrossedByNodeV(h,o)||(n=Math.max(n,u.topAnchor),s=u.bottomAnchor,yield h))}}IsVirtualVertex(t){return t>=this.originalGraph.shallowNodeCount}IsLabel(t){return this.anchors[t].hasLabel}NodeUCanBeCrossedByNodeV(t,e){return this.IsLabel(t)||this.IsLabel(e)?!1:!!(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e)&&this.EdgesIntersectSomewhere(t,e))}EdgesIntersectSomewhere(t,e){return this.UVAreMiddlesOfTheSameMultiEdge(t,e)?!1:this.IntersectAbove(t,e)||this.IntersectBelow(t,e)}UVAreMiddlesOfTheSameMultiEdge(t,e){return!!(this.database.MultipleMiddles.has(t)&&this.database.MultipleMiddles.has(e)&&this.SourceOfTheOriginalEdgeContainingAVirtualNode(t)===this.SourceOfTheOriginalEdgeContainingAVirtualNode(e))}SourceOfTheOriginalEdgeContainingAVirtualNode(t){for(;this.IsVirtualVertex(t);)t=this.IncomingEdge(t).Source;return t}IntersectBelow(t,e){do{const i=this.OutcomingEdge(t),s=this.OutcomingEdge(e);if(this.Intersect(i,s))return!0;t=i.Target,e=s.Target}while(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e));return t===e}IntersectAbove(t,e){do{const i=this.IncomingEdge(t),s=this.IncomingEdge(e);if(this.Intersect(i,s))return!0;t=i.Source,e=s.Source}while(this.IsVirtualVertex(t)&&this.IsVirtualVertex(e));return t===e}Intersect(t,e){const i=this.layerArrays.x[t.Source]-this.layerArrays.x[e.Source],s=this.layerArrays.x[t.Target]-this.layerArrays.x[e.Target];return i>0&&s<0||i<0&&s>0}IncomingEdge(t){return this.layeredGraph.InEdgeOfVirtualNode(t)}OutcomingEdge(t){return this.layeredGraph.OutEdgeOfVirtualNode(t)}EastBoundaryNodesOfANode(t,e){return this.FillRightTopAndBottomVerts(this.NodeLayer(t),this.layerArrays.x[t],e)}NodeLayer(t){return this.layerArrays.Layers[this.layerArrays.y[t]]}LeftBoundaryNodesOfANode(t,e){return this.FillLeftTopAndBottomVerts(this.NodeLayer(t),this.layerArrays.x[t],e)}getSpline(t){return this.createRefinedPolyline(t),this.createSmoothedPolyline()}get GetPolyline(){return new G(this.headSite)}LineSegIntersectBound(t,e){const i=D.mkPP(t,e);return Ue.CurveIntersectsHierarchy(i,this.westHierarchy)||Ue.CurveIntersectsHierarchy(i,this.thinWestHierarchy)||Ue.CurveIntersectsHierarchy(i,this.eastHierarchy)||Ue.CurveIntersectsHierarchy(i,this.thinEastHierarchy)}SegIntersectWestBound(t,e){return Ue.SegIntersectsBound(t,e,this.westHierarchy)||Ue.SegIntersectsBound(t,e,this.thinWestHierarchy)}SegIntersectEastBound(t,e){return Ue.SegIntersectsBound(t,e,this.eastHierarchy)||Ue.SegIntersectsBound(t,e,this.thinEastHierarchy)}TryToRemoveInflectionCorner(t){if(!t.s.next||!t.s.prev||t.s.turn===k.Counterclockwise&&this.SegIntersectEastBound(t.s.prev,t.s.next)||t.s.turn===k.Clockwise&&this.SegIntersectWestBound(t.s.prev,t.s.next)){t.cut=!1,t.s=t.s.next;return}const e=t.s.next;t.s.prev.next=e,e.prev=t.s.prev,t.s=e,t.cut=!0}static SegIntersectsBound(t,e,i){return Ue.CurveIntersectsHierarchy(D.mkPP(t.point,e.point),i)}static CurveIntersectsHierarchy(t,e){if(e==null||!At.intersect(t.pNodeOverICurve().parallelogram,e.parallelogram))return!1;if(e.node.hasOwnProperty("children")){const i=e.node;return Ue.CurveIntersectsHierarchy(t,i.children[0])||Ue.CurveIntersectsHierarchy(t,i.children[1])}return w.intersectionOne(t,e.seg,!1)!=null}static Flat(t){return d.getTriangleOrientation(t.prev.point,t.point,t.next.point)===k.Collinear}Reverse(){const t=new Ue(this.edgePath,this.anchors,this.originalGraph,this.settings,this.layerArrays,this.layeredGraph,this.database);let e=this.headSite,i=null;for(;e!=null;)t.headSite=e.clone(),t.headSite.next=i,i!=null&&(i.prev=t.headSite),i=t.headSite,e=e.next;return t}createRefinedPolyline(t){this.CreateInitialListOfSites();let e=this.headSite,i;for(let s=0;s<this.edgePath.count;s++)i=e.next,this.RefineBeetweenNeighborLayers(e,this.EdgePathNode(s),this.EdgePathNode(s+1)),e=i;this.TryToRemoveInflections(),t&&this.OptimizeShortPath()}RefineBeetweenNeighborLayers(t,e,i){yi.Refine(e,i,t,this.anchors,this.layerArrays,this.layeredGraph,this.originalGraph,this.settings.LayerSeparation)}CreateInitialListOfSites(){let t=this.headSite=Ut.mkSiteP(this.EdgePathPoint(0));for(let e=1;e<=this.edgePath.count;e++)t=Ut.mkSiteSP(t,this.EdgePathPoint(e))}get TailSite(){let t=this.headSite;for(;t.next!=null;)t=t.next;return t}OptimizeForThreeSites(){const t=this.EdgePathNode(0),e=this.EdgePathNode(2),i=this.anchors[t],s=this.anchors[e];if(N(i.x,s.x))return;const n={ax:i.x,bx:s.x,sign:0};if(!this.FindLegalPositions(i,s,n))return;const o=(i.y-s.y)/(i.bottom-s.top),a=.5*(n.ax+n.bx),h=n.sign*((n.ax-n.bx)*.5);n.ax=a+o*(h*n.sign),n.bx=a-o*(h*n.sign),this.headSite.point=new d(n.ax,i.y);const u=this.headSite.next,c=u.point.y;u.point=new d(this.MiddlePos(n.ax,n.bx,i,s,c),c),u.next.point=new d(n.bx,s.y);const m=this.anchors[this.EdgePathNode(1)];m.x=u.point.x}OptimizeForTwoSites(){const t=this.EdgePathNode(0),e=this.EdgePathNode(1),i=this.anchors[t],s=this.anchors[e];if(N(i.x,s.x))return;const n={ax:i.x,bx:s.x,sign:0};if(!this.FindPositions(i,s,n))return;const o=(i.y-s.y)/(i.bottom-s.top),a=.5*(n.ax+n.bx),h=n.sign*((n.ax-n.bx)*.5);n.ax=a+o*(h*n.sign),n.bx=a-o*(h*n.sign),this.headSite.point=new d(n.ax,i.y),this.headSite.next.point=new d(n.bx,s.y)}FindLegalPositions(t,e,i){return this.FindPositions(t,e,i)?this.PositionsAreLegal(i.ax,i.bx,i.sign,t,e,this.EdgePathNode(1)):!1}FindPositions(t,e,i){let s,n;if(i.ax<i.bx?(i.sign=1,n=Math.max(i.ax,e.left),s=Math.min(t.right,i.bx)):(i.sign=-1,n=Math.max(t.left,i.bx),s=Math.min(e.right,i.ax)),n<=s)i.bx=.5*(n+s),i.ax=.5*(n+s);else{if(this.OriginToOriginSegCrossesAnchorSide(t,e))return!1;i.sign===1?(i.ax=t.right-.1*t.rightAnchor,i.bx=e.left):(i.ax=t.left+.1*t.leftAnchor,i.bx=e.right)}return!0}OriginToOriginSegCrossesAnchorSide(t,e){const i=D.mkPP(t.origin,e.origin);return t.x<e.x&&w.CurvesIntersect(i,D.mkPP(t.rightBottom,t.rightTop))||w.CurvesIntersect(i,D.mkPP(e.leftBottom,t.leftTop))||t.x>e.x&&w.CurvesIntersect(i,D.mkPP(t.leftBottom,t.leftTop))||w.CurvesIntersect(i,D.mkPP(e.rightBottom,t.rightTop))}OptimizeShortPath(){this.edgePath.count>2||(this.edgePath.count===2&&this.headSite.next.next!=null&&this.headSite.next.next.next==null&&this.anchors[this.EdgePathNode(1)].node==null?this.OptimizeForThreeSites():this.edgePath.count===1&&this.OptimizeForTwoSites())}PositionsAreLegal(t,e,i,s,n,o){if(!N(t,e)&&(t-e)*i>0)return!1;const a=this.anchors[o],h=this.MiddlePos(t,e,s,n,a.y);return this.MiddleAnchorLegal(h,o,a)?!this.LineSegIntersectBound(new d(t,s.bottom),new d(e,n.top)):!1}MiddleAnchorLegal(t,e,i){const s=this.NodeLayer(e),n=this.layerArrays.x[e],o=t-i.x;return!(n>0&&this.anchors[s[n-1]].right>o+i.left||n<s.length-1&&this.anchors[s[n+1]].left<o+i.right)}MiddlePos(t,e,i,s,n){const o=i.y-n,a=n-s.y;return(t*o+e*a)/(o+a)}TryToRemoveInflections(){if(this.TurningAlwaySameDirection())return;let t=!0;for(;t;){t=!1;for(const e={s:this.headSite,cut:!1};e.s;)this.TryToRemoveInflectionCorner(e),t=e.cut||t}}TurningAlwaySameDirection(){let t=0;for(let e=this.headSite.next;e!=null&&e.next!=null;e=e.next){const i=e.turn;if(t===0)i>0?t=1:i<0&&(t=-1);else if(t*i<0)return!1}return!0}EdgePathPoint(t){return this.anchors[this.EdgePathNode(t)].origin}EdgePathNode(t){return t===this.edgePath.count?this.edgePath.LayerEdges[this.edgePath.count-1].Target:this.edgePath.LayerEdges[t].Source}createSmoothedPolyline(){this.RemoveVerticesWithNoTurns();let t=new w;const e=this.headSite,i=w.findCorner(e);return i!==void 0?(this.createFilletCurve(t,{a:e,b:i.b,c:i.c}),t=this.ExtendCurveToEndpoints(t)):t.addSegment(D.mkPP(this.headSite.point,this.TailSite.point)),t}curveIsLegal(t){return!0}RemoveVerticesWithNoTurns(){for(;this.RemoveVerticesWithNoTurnsOnePass(););}RemoveVerticesWithNoTurnsOnePass(){let t=!1;for(let e=this.headSite;e.next!=null&&e.next.next!=null;e=e.next)Ue.Flat(e.next)&&(t=!0,e.next=e.next.next,e.next.prev=e);return t}ExtendCurveToEndpoints(t){let e=this.headSite.point;if(!d.closeDistEps(e,t.start)){const i=new w;i.addSegs([D.mkPP(e,t.start),t]),t=i}return e=this.TailSite.point,d.closeDistEps(e,t.end)||t.addSegment(D.mkPP(t.end,e)),t}createFilletCurve(t,e){for(;this.AddSmoothedCorner(e.a,e.b,e.c,t),e.a=e.b,e.b=e.c,e.b.next!=null;)e.c=e.b.next}AddSmoothedCorner(t,e,i,s){let n=.5,o;do o=w.createBezierSeg(n,n,t,e,i),e.previouisBezierCoefficient=n,n/=2;while(this.BezierSegIntersectsBoundary(o));if(n*=2,n<.5){n=.5*(n+n*2);const a=w.createBezierSeg(n,n,t,e,i);this.BezierSegIntersectsBoundary(a)||(e.nextBezierCoefficient=n,e.previouisBezierCoefficient=n,o=a)}s.segs.length>0&&!d.closeDistEps(s.end,o.start)&&s.addSegment(D.mkPP(s.end,o.start)),s.addSegment(o)}BezierSegIntersectsBoundary(t){return d.signedDoubledTriangleArea(t.B(0),t.B(1),t.B(2))<0?this.BezierSegIntersectsTree(t,this.thinWestHierarchy)||this.BezierSegIntersectsTree(t,this.westHierarchy):this.BezierSegIntersectsTree(t,this.thinEastHierarchy)||this.BezierSegIntersectsTree(t,this.eastHierarchy)}BezierSegIntersectsTree(t,e){if(e==null)return!1;if(At.intersect(t.pNodeOverICurve().parallelogram,e.parallelogram))if(e.node.hasOwnProperty("children")){const i=e.node;return this.BezierSegIntersectsTree(t,i.children[0])||this.BezierSegIntersectsTree(t,i.children[1])}else return Ue.BezierSegIntersectsBoundary(t,e.seg);else return!1}static BezierSegIntersectsBoundary(t,e){for(const i of w.getAllIntersections(t,e,!1))if(e instanceof w){const s=e;if(w.realCutWithClosedCurve(i,s,!1))return!0}else return!0;return!1}}class qs extends zt{constructor(t,e,i,s,n,o){super(null),this.settings=t,this.OriginalGraph=e,this.Database=i,this.ProperLayeredGraph=n,this.LayerArrays=s,this.IntGraph=o}run(){this.createSplines()}createSplines(){this.createRegularSplines(),this.createSelfSplines(),this.IntGraph!=null&&this.RouteFlatEdges(),this.OriginalGraph.graph.parent==null&&this.RouteUnroutedEdges()}RouteUnroutedEdges(){const t=[];for(const o of this.OriginalGraph.deepEdges)o.curve||t.push(o);if(t.length==0)return;const i=(this.OriginalGraph.layoutSettings?this.OriginalGraph.layoutSettings:new Sn).commonSettings.edgeRoutingSettings;new Zt(this.OriginalGraph,t,i.padding,i.polylinePadding,i.coneAngle,i.bundlingSettings,this.cancelToken).run(),Ft.constructorGA(this.OriginalGraph,t).run()}RouteFlatEdges(){}createRegularSplines(){for(const t of this.Database.RegularMultiedges()){if(Rc(t))continue;const e=t.length,i=e===1&&this.MayOptimizeEdge(t[0]);for(let s=Math.floor(e/2);s<e;s++)this.createSplineForNonSelfEdge(t[s],i);for(let s=Math.floor(e/2)-1;s>=0;s--)this.createSplineForNonSelfEdge(t[s],i)}}MayOptimizeEdge(t){return!(this.ProperLayeredGraph.OutDegreeIsMoreThanOne(t.source)||this.ProperLayeredGraph.InDegreeIsMoreThanOne(t.target)||ch(t.edge.source)||ch(t.edge.target))}createSelfSplines(){for(const[t,e]of this.Database.Multiedges.keyValues()){const i=t;if(i.x===i.y){const s=this.Database.Anchors[i.x];let n=s.leftAnchor;for(const o of e){const a=this.settings.NodeSeparation+(this.settings.MinNodeWidth+n),h=s.bottomAnchor/2,u=s.origin,c=u.add(new d(0,h)),m=u.add(new d(a,h)),S=u.add(new d(a,-h)),A=u.add(new d(0,-h));let I=Ut.mkSiteP(u);const B=new G(I);I=Ut.mkSiteSP(I,c),I=Ut.mkSiteSP(I,m),I=Ut.mkSiteSP(I,S),I=Ut.mkSiteSP(I,A),Ut.mkSiteSP(I,u);const q=B.createCurve();if(o.curve=q,n=a,o.edge.label!=null){n+=o.edge.label.width;const rt=q.value((q.parStart+q.parEnd)/2),ct=new d(rt.x+o.labelWidth/2,s.y),Q=new d(o.edge.label.width/2,o.edge.label.height/2),pt=Z.mkPP(ct.add(Q),ct.sub(Q));o.edge.label.width=pt.width,o.edge.label.height=pt.height,o.edge.label.positionCenter(ct)}Mt.trimSplineAndCalculateArrowheadsII(o.edge,o.edge.source.boundaryCurve,o.edge.target.boundaryCurve,q,!1)}}}}createSplineForNonSelfEdge(t,e){t.LayerEdges!=null&&(this.drawSplineBySmothingThePolyline(t,e),t.IsVirtualEdge||(t.updateEdgeLabelPosition(this.Database.Anchors),Mt.trimSplineAndCalculateArrowheadsII(t.edge,t.edge.source.boundaryCurve,t.edge.target.boundaryCurve,t.curve,!0)))}drawSplineBySmothingThePolyline(t,e){const s=new Ue(t,this.Database.Anchors,this.OriginalGraph,this.settings,this.LayerArrays,this.ProperLayeredGraph,this.Database).getSpline(e);t.reversed?t.curve=s.reverse():t.curve=s}static UpdateLabel(t,e){let i=null;e.labelIsToTheRightOfTheSpline?(t.label.positionCenter(new d(e.x+e.rightAnchor/2,e.y)),i=D.mkPP(t.label.boundingBox.leftTop,t.label.boundingBox.leftBottom)):e.labelIsToTheLeftOfTheSpline&&(t.label.positionCenter(new d(e.x-e.leftAnchor/2,e.y)),i=D.mkPP(t.label.boundingBox.rightTop,t.label.boundingBox.rightBottom));const s=qs.GetSegmentInFrontOfLabel(t.curve,t.label.center.y);if(s!=null&&w.getAllIntersections(t.curve,w.polyFromBox(t.label.boundingBox),!1).length===0){const n={curveClosestPoint:void 0,labelSideClosest:void 0};if(qs.FindClosestPoints(n,s,i))qs.ShiftLabel(t,n);else{const o=s.closestParameter(i.start),a=s.closestParameter(i.end);s.value(o).sub(i.start).length<s.value(a).sub(i.end).length?(n.curveClosestPoint=s.value(o),n.labelSideClosest=i.start):(n.curveClosestPoint=s.value(a),n.labelSideClosest=i.end),qs.ShiftLabel(t,n)}}}static ShiftLabel(t,e){const i=t.lineWidth/2,s=e.curveClosestPoint.sub(e.labelSideClosest),n=s.length;n>i&&t.label.positionCenter(t.label.center.add(s.div(n*(n-i))))}static FindClosestPoints(t,e,i){const s=w.minDistWithinIntervals(e,i,e.parStart,e.parEnd,i.parStart,i.parEnd,(e.parStart+e.parEnd)/2,(i.parStart+i.parEnd)/2);return s?(t.curveClosestPoint=s.aX,t.labelSideClosest=s.bX,!0):!1}static GetSegmentInFrontOfLabel(t,e){if(t instanceof w){const i=t;for(const s of i.segs)if((s.start.y-e)*(s.end.y-e)<=0)return s}return null}static GetNodeKind(t,e){return t===0?Be.Top:t<e.count?Be.Internal:Be.Bottom}}function Rc(l){if(l.length<4)return!1;for(const t of l)if(t.edge.label)return!1;return!0}function ch(l){return l.node.selfEdges.size>0}function Dc(l,t){new ka(l,l.layoutSettings,t).run()}function eg(l,t,e){const i=l.layoutSettings?l.layoutSettings:new SugiyamaLayoutSettings;if(enforceLayoutSettings(l,i),layoutGeomGraphDetailed(l,t,Dc,routeEdges,optimalPackingRunner),e){const s=new PlaneTransformation(1,0,-l.boundingBox.left,0,-1,l.top);l.transform(s)}}class ka extends zt{constructor(t,e,i){if(super(i),this.LayersAreDoubled=!1,t==null)return;this.originalGraph=t,this.sugiyamaSettings=e;const s=Array.from(t.shallowNodes);this.nodeIdToIndex=new Map;let n=0;for(const a of s)this.nodeIdToIndex.set(a.id,n++);const o=[];for(const a of this.originalGraph.shallowEdges){const h=this.nodeIdToIndex.get(a.source.id);if(h==null)continue;const u=this.nodeIdToIndex.get(a.target.id);if(u==null)continue;const c=new $i(h,u,a);o.push(c)}this.IntGraph=new Yr(o,t.shallowNodeCount),this.IntGraph.nodes=s,this.database=new Ec(s.length);for(const a of this.IntGraph.edges)this.database.registerOriginalEdgeInMultiedges(a);this.cycleRemoval()}get extremeAspectRatio(){const t=this.originalGraph.boundingBox,e=t.width/t.height;return e<1/50||e>50}get verticalConstraints(){return this.sugiyamaSettings.verticalConstraints}get HorizontalConstraints(){return this.sugiyamaSettings.horizontalConstraints}run(){if(this.originalGraph.shallowNodeCount===0){this.originalGraph.boundingBox=Z.mkEmpty();return}Yc(this.originalGraph,this.sugiyamaSettings.transform),this.engineLayerArrays=this.calculateLayers(),this.sugiyamaSettings.edgeRoutingSettings.EdgeRoutingMode===He.SugiyamaSplines&&this.runPostLayering(),Kc(this.originalGraph,this.sugiyamaSettings.transform)}runPostLayering(){const t=this.sugiyamaSettings.commonSettings.edgeRoutingSettings,e=this.constrainedOrdering!=null?He.Spline:t.EdgeRoutingMode;this.extremeAspectRatio?Ml(this.originalGraph,Array.from(this.originalGraph.deepEdges),this.cancelToken):e===He.SugiyamaSplines?this.calculateEdgeSplines():_l(this.originalGraph,Array.from(this.originalGraph.deepEdges),this.cancelToken)}SetLabels(){throw new Error("not implementedt")}cycleRemoval(){const t=this.sugiyamaSettings.verticalConstraints,e=t.isEmpty?y.getFeedbackSet(this.IntGraph):t.getFeedbackSetExternal(this.IntGraph,this.nodeIdToIndex);this.database.addFeedbackSet(e)}calculateLayers(){this.CreateGluedDagSkeletonForLayering();const t=this.CalculateLayerArrays();return this.UpdateNodePositionData(),t}UpdateNodePositionData(){for(let t=0;t<this.IntGraph.nodeCount&&t<this.database.Anchors.length;t++)this.IntGraph.nodes[t].center=this.database.Anchors[t].origin;if(this.sugiyamaSettings.GridSizeByX>0)for(let t=0;t<this.originalGraph.shallowNodeCount;t++)this.SnapLeftSidesOfTheNodeToGrid(t,this.sugiyamaSettings.GridSizeByX)}SnapLeftSidesOfTheNodeToGrid(t,e){const i=this.IntGraph.nodes[t],s=this.database.Anchors[t];s.leftAnchor-=e/2,s.rightAnchor-=e/2;const n=i.boundingBox.left,o=Math.floor(n/e),a=n-o*e;Math.abs(a)<.001||(Math.abs(a)<=e/2?i.center=i.center.add(new d(-a,0)):i.center=i.center.add(new d(e-a,0)),s.x=i.center.x)}GetCurrentHeight(){const t=new x;for(const e of this.NodeAnchors())t.AddValue(e.top),t.AddValue(e.bottom);return t.length}*NodeAnchors(){const t=Math.min(this.IntGraph.nodeCount,this.anchors.length);for(let e=0;e<t;e++)yield this.anchors[e]}GetCurrentWidth(){const t=new x;for(const e of this.NodeAnchors())t.AddValue(e.left),t.AddValue(e.right);return t.length}ExtendLayeringToUngluedSameLayerVertices(t){const e=this.verticalConstraints;for(let i=0;i<t.length;i++)t[i]=t[e.nodeToRepr(i)];return t}calculateEdgeSplines(){new qs(this.sugiyamaSettings,this.originalGraph,this.database,this.engineLayerArrays,this.properLayeredGraph,this.IntGraph).run()}YLayeringAndOrdering(t){let e=t.GetLayers();Da.Balance(this.gluedDagSkeletonForLayering,e,this.GetNodeCountsOfGluedDag(),null),e=this.ExtendLayeringToUngluedSameLayerVertices(e);let i=new gs(e);if(this.HorizontalConstraints==null||this.HorizontalConstraints.IsEmpty)return i=this.YLayeringAndOrderingWithoutHorizontalConstraints(i),i;throw new Error("not implemented")}CreateProperLayeredGraph(t){const e=t.length;let i=0;for(const n of this.database.SkeletonEdges()){const o=Vc(t,n);o>0&&(n.LayerEdges=new Array(o));let a=0;if(o>1){let h=e+i++,u=new ks(n.source,h,n.CrossingWeight,n.weight);n.LayerEdges[a++]=u;for(let c=0;c<o-2;c++)h++,i++,u=new ks(h-1,h,n.CrossingWeight,n.weight),n.LayerEdges[a++]=u;u=new ks(h,n.target,n.CrossingWeight,n.weight),n.LayerEdges[a]=u}else if(o===1){const h=new ks(n.source,n.target,n.CrossingWeight,n.weight);n.LayerEdges[a]=h}}const s=new Array(this.originalGraph.shallowNodeCount+i).fill(0);for(const n of this.database.SkeletonEdges())if(n.LayerEdges!=null){let o=t[n.source];s[n.source]=o--;for(const a of n.LayerEdges)s[a.Target]=o--}else s[n.source]=t[n.source],s[n.target]=t[n.target];return this.properLayeredGraph=new wn(new Yr(Array.from(this.database.SkeletonEdges()),t.length)),this.properLayeredGraph.BaseGraph.nodes=this.IntGraph.nodes,new gs(s)}YLayeringAndOrderingWithoutHorizontalConstraints(t){const e=this.CreateProperLayeredGraph(t.y);return rr.OrderLayers(this.properLayeredGraph,e,this.originalGraph.shallowNodeCount,this.sugiyamaSettings,this.cancelToken),Ko.UpdateLayerArrays1(this.properLayeredGraph,e),e}CalculateYLayers(){const t=this.YLayeringAndOrdering(new Bc(this.gluedDagSkeletonForLayering,this.cancelToken));return this.constrainedOrdering!=null?t:this.InsertLayersIfNeeded(t)}InsertLayersIfNeeded(t){this.InsertVirtualEdgesIfNeeded(t);const e=this.AnalyzeNeedToInsertLayersAndHasMultiedges(t);if(e.needToInsertLayers){const i=Kr.InsertLayers(this.properLayeredGraph,t,this.database,this.IntGraph);this.properLayeredGraph=i.layeredGraph,t=i.la,this.LayersAreDoubled=!0}else if(e.multipleEdges){const i=vn.InsertPaths(this.properLayeredGraph,t,this.database,this.IntGraph);this.properLayeredGraph=i.layeredGraph,t=i.la}return this.RecreateIntGraphFromDataBase(),t}RecreateIntGraphFromDataBase(){let t=new Array;for(const e of this.database.Multiedges.values())t=t.concat(e);this.IntGraph.SetEdges(t,this.IntGraph.nodeCount)}InsertVirtualEdgesIfNeeded(t){if(this.constrainedOrdering==null){for(const[e,i]of this.database.Multiedges.keyValues())if(i.length%2===0&&t.y[e.x]-1===t.y[e.y]){const s=new Ne(null),n=new $i(e.x,e.y,s);n.IsVirtualEdge=!0,i.splice(i.length/2,0,n),this.IntGraph.addEdge(n)}}}AnalyzeNeedToInsertLayersAndHasMultiedges(t){let e=!1,i=!1;for(const s of this.IntGraph.edges)if(s.hasLabel&&t.y[s.source]!==t.y[s.target]){e=!0;break}if(e===!1&&this.constrainedOrdering==null){for(const[s,n]of this.database.Multiedges.keyValues())if(n.length>1&&(i=!0,t.y[s.x]-t.y[s.y]===1)){e=!0;break}}return{needToInsertLayers:e,multipleEdges:i}}UseBrandesXCalculations(t){return t.x.length>=this.sugiyamaSettings.BrandesThreshold}CalculateAnchorsAndYPositions(t){this.anchors=kc(this.database,this.properLayeredGraph,this.originalGraph,this.IntGraph,this.sugiyamaSettings),Gc(t,500,this.originalGraph,this.database,this.IntGraph,this.sugiyamaSettings,this.LayersAreDoubled)}OptimizeEdgeLabelsLocations(){for(let t=0;t<this.anchors.length;t++){const e=this.anchors[t];if(e.labelIsToTheRightOfTheSpline){const i=this.GetSuccessorAndPredecessor(t);if(!qc(e,i.predecessor,i.successor)){const s=i.predecessor.origin.sub(e.origin).length+i.successor.origin.sub(e.origin).length,n=e.right-e.leftAnchor,o=new d(n,e.y);i.predecessor.origin.sub(o).length+i.successor.origin.sub(o).length<s&&ph(e)}}}}GetSuccessorAndPredecessor(t){let e;for(const s of this.properLayeredGraph.InEdges(t))e=s.Source;let i;for(const s of this.properLayeredGraph.OutEdges(t))i=s.Target;return{predecessor:this.anchors[e],successor:this.anchors[i]}}CalculateLayerArrays(){const t=this.CalculateYLayers();return this.constrainedOrdering==null?(this.CalculateAnchorsAndYPositions(t),this.UseBrandesXCalculations(t)?this.CalculateXPositionsByBrandes(t):this.CalculateXLayersByGansnerNorth(t)):this.anchors=this.database.Anchors,this.OptimizeEdgeLabelsLocations(),this.engineLayerArrays=t,this.StraightensShortEdges(),this.CalculateOriginalGraphBox(),t}StretchToDesiredAspectRatio(t,e){t>e?this.StretchInYDirection(t/e):t<e&&this.StretchInXDirection(e/t)}StretchInYDirection(t){const e=(this.originalGraph.boundingBox.top+this.originalGraph.boundingBox.bottom)/2;for(const s of this.database.Anchors)s.bottomAnchor=s.bottomAnchor*t,s.topAnchor=s.topAnchor*t,s.y=e+t*(s.y-e);const i=this.originalGraph.height*t;this.originalGraph.boundingBox=new Z({left:this.originalGraph.boundingBox.left,top:e+i/2,right:this.originalGraph.boundingBox.right,bottom:e-i/2})}StretchInXDirection(t){const e=(this.originalGraph.boundingBox.left+this.originalGraph.boundingBox.right)/2;for(const s of this.database.Anchors)s.leftAnchor=s.leftAnchor*t,s.rightAnchor=s.rightAnchor*t,s.x=e+t*(s.x-e);const i=this.originalGraph.width*t;this.originalGraph.boundingBox=new Z({left:e-i/2,top:this.originalGraph.boundingBox.top,right:e+i/2,bottom:this.originalGraph.boundingBox.bottom})}CalculateOriginalGraphBox(){if(this.anchors.length===0)return;const t=new Z({left:this.anchors[0].left,top:this.anchors[0].top,right:this.anchors[0].right,bottom:this.anchors[0].bottom});for(let e=1;e<this.anchors.length;e++){const i=this.anchors[e];t.add(i.leftTop),t.add(i.rightBottom)}this.originalGraph.labelSize&&this.originalGraph.addLabelToGraphBB(t),t.padEverywhere(this.originalGraph.margins),this.originalGraph.boundingBox=t}StraightensShortEdges(){for(;this.StraightenEdgePaths(););}StraightenEdgePaths(){let t=!1;for(const e of this.database.AllIntEdges())e.LayerSpan===2&&(t=this.ShiftVertexWithNeighbors(e.LayerEdges[0].Source,e.LayerEdges[0].Target,e.LayerEdges[1].Target)||t);return t}ShiftVertexWithNeighbors(t,e,i){const s=this.database.Anchors[t],n=this.database.Anchors[i],o=this.database.Anchors[e],a=(o.y-s.y)*((n.x-s.x)/(n.y-s.y))+s.x,h=1e-4;return a>o.x+h?this.TryShiftToTheRight(a,e):a<o.x-h?this.TryShiftToTheLeft(a,e):!1}TryShiftToTheLeft(t,e){const i=this.engineLayerArrays.Layers[this.engineLayerArrays.y[e]],s=this.engineLayerArrays.x[e];if(s>0){const n=this.database.Anchors[i[s-1]],o=Math.max(n.right+(this.sugiyamaSettings.NodeSeparation+this.database.Anchors[e].leftAnchor),t);return o<this.database.Anchors[e].x-1?(this.database.Anchors[e].x=o,!0):!1}return this.database.Anchors[e].x=t,!0}TryShiftToTheRight(t,e){const i=this.engineLayerArrays.Layers[this.engineLayerArrays.y[e]],s=this.engineLayerArrays.x[e];if(s<i.length-1){const n=this.database.Anchors[i[s+1]],o=Math.min(n.left-(this.sugiyamaSettings.NodeSeparation-this.database.Anchors[e].rightAnchor),t);return o>this.database.Anchors[e].x+1?(this.database.Anchors[e].x=o,!0):!1}return this.database.Anchors[e].x=t,!0}CalculateXLayersByGansnerNorth(t){this.xLayoutGraph=this.CreateXLayoutGraph(t),this.CalculateXLayersByGansnerNorthOnProperLayeredGraph()}CalculateXLayersByGansnerNorthOnProperLayeredGraph(){const t=new uh(this.xLayoutGraph,null).GetLayers();for(let e=0;e<this.database.Anchors.length;e++)this.anchors[e].x=t[e]}CreateXLayoutGraph(t){let e=this.properLayeredGraph.NodeCount;const i=new Array;for(const n of this.properLayeredGraph.Edges){const o=new $i(e,n.Source,null),a=new $i(e,n.Target,null);a.weight=n.Weight,o.weight=n.Weight,o.separation=0,a.separation=0,e++,i.push(o),i.push(a)}for(const n of t.Layers)for(let o=n.length-1;o>0;o--){const a=n[o],h=n[o-1],u=new $i(a,h,null),c=this.database.Anchors[a],m=this.database.Anchors[h],S=c.leftAnchor+(m.rightAnchor+this.sugiyamaSettings.NodeSeparation);u.separation=Math.ceil(S+.5),i.push(u)}const s=new Fc(this.IntGraph,this.properLayeredGraph,t,i,e);return s.SetEdgeWeights(),s}CalculateXPositionsByBrandes(t){In.CalculateXCoordinates(t,this.properLayeredGraph,this.originalGraph.shallowNodeCount,this.database.Anchors,this.sugiyamaSettings.NodeSeparation)}GluedDagSkeletonEdges(){const t=new Fs;for(const[i,s]of this.database.Multiedges.keyValues()){if(i.isDiagonal())continue;const n=this.verticalConstraints.gluedIntEdge(s[0]);n.source!==n.target&&t.set(n.source,n.target,n)}const e=Array.from(this.verticalConstraints.gluedUpDownIntConstraints.values()).map(i=>Mc(i,null));for(const i of e)t.set(i.source,i.target,i);return Array.from(t.values())}static CalcAnchorsForOriginalNode(t,e,i,s,n){const o={leftAnchor:0,rightAnchor:0,topAnchor:0,bottomAnchor:0};if(e.nodes!=null){const u=e.nodes[t];$c(o,u,n)}Xc(t,o,s,n);const a=n.MinNodeWidth/2;o.leftAnchor<a&&(o.leftAnchor=a),o.rightAnchor<a&&(o.rightAnchor=a);const h=n.MinNodeHeight/2;o.topAnchor<h&&(o.topAnchor=h),o.bottomAnchor<h&&(o.bottomAnchor=h),i[t]=Si.mkAnchor(o.leftAnchor,o.rightAnchor,o.topAnchor,o.bottomAnchor,e.nodes[t],n.LabelCornersPreserveCoefficient),i[t].padding=e.nodes[t].padding}CreateGluedDagSkeletonForLayering(){this.gluedDagSkeletonForLayering=new Yr(this.GluedDagSkeletonEdges(),this.originalGraph.shallowNodeCount),this.SetGluedEdgesWeights()}SetGluedEdgesWeights(){const t=new Fs;for(const e of this.gluedDagSkeletonForLayering.edges)t.set(e.source,e.target,e);for(const[e,i]of this.database.Multiedges.keyValues())if(e.x!==e.y){const s=this.verticalConstraints.gluedIntPair(e);if(s.x===s.y)continue;const n=t.get(s.x,s.y);for(const o of i)n.weight+=o.weight}}GetNodeCountsOfGluedDag(){return this.verticalConstraints.isEmpty?new Array(this.IntGraph.nodeCount).fill(1):this.verticalConstraints.getGluedNodeCounts()}}function dh(l,t){if(t===0)return 0;const e=Math.floor(l/t),i=l-e*t;return Math.abs(i)<1e-4?0:t-i}function Nc(l,t){for(const e of l)if(e<t)return!0;return!1}function kc(l,t,e,i,s){const n=l.Anchors=new Array(t.NodeCount);for(let o=0;o<n.length;o++)n[o]=new Si(s.LabelCornersPreserveCoefficient);for(let o=0;o<e.shallowNodeCount;o++)ka.CalcAnchorsForOriginalNode(o,i,n,l,s);for(const o of l.AllIntEdges())if(o.LayerEdges!=null){for(const a of o.LayerEdges){const h=a.Target;if(h!==o.target){const u=n[h];l.MultipleMiddles.has(h)?(u.leftAnchor=u.rightAnchor=Ga()*4,u.topAnchor=u.bottomAnchor=gh(s)/2):(u.leftAnchor=u.rightAnchor=Ga()/2,u.topAnchor=u.bottomAnchor=gh(s)/2)}}if(o.hasLabel){const a=o.LayerEdges[o.LayerEdges.length/2].Source,h=n[a],u=o.labelWidth,c=o.labelHeight;h.rightAnchor=u,h.leftAnchor=Ga()*8,h.topAnchor<c/2&&(h.topAnchor=h.bottomAnchor=c/2),h.labelIsToTheRightOfTheSpline=!0}}return n}function Ga(){return 1}function gh(l){return l.MinNodeHeight*1.5/8}function fh(l,t,e,i,s,n){let o=0;if(e>0){const a=Uc(t.Layers[e-1],t.y,i);if(a.length){const h=s.LayerSeparation/3,u=n;o=Math.max(...a.map(c=>jc(c,u,h,l)))}}return o}function Gc(l,t,e,i,s,n,o){const a=i.Anchors;let h=e.margins.top+t,u=0;for(const c of l.Layers){let m=0,S=0;for(const rt of c){const ct=a[rt];ct.bottomAnchor>m&&(m=ct.bottomAnchor),ct.topAnchor>S&&(S=ct.topAnchor)}Wc(c,m,S,e.shallowNodeCount,i.Anchors);const A=fh(i,l,u,s,n,h),I=h+m+A;let B=I+S;if(Hc(n)){B+=dh(B,n.GridSizeByY);for(const rt of c)a[rt].top=B}else if(zc(n)){let rt=I-m;rt+=dh(rt,rt);for(const ct of c)a[ct].bottom=rt,B=Math.max(a[ct].top,B)}else for(const rt of c)a[rt].y=I;const q=n.ActualLayerSeparation(o);h=B+q,u++}fh(i,l,u,s,n,h)}function Mc(l,t){const e=new $i(l.x,l.y,t);return e.weight=0,e.separation=1,e}function Vc(l,t){return l[t.source]-l[t.target]}function Wc(l,t,e,i,s){if(Nc(l,i)){for(const n of l)if(n>=i){const o=s[n];o.bottomAnchor=t,o.topAnchor=e}}}function Hc(l){return l.SnapToGridByY===er.Top}function zc(l){return l.SnapToGridByY===er.Bottom}function qc(l,t,e){if(l.labelIsToTheRightOfTheSpline){if(d.getTriangleOrientation(t.origin,l.origin,e.origin)===k.Clockwise)return!0;const i=l.leftAnchor,s=l.rightAnchor,n=l.x;return ph(l),d.getTriangleOrientation(t.origin,l.origin,e.origin)===k.Counterclockwise?!0:(l.x=n,l.leftAnchor=i,l.rightAnchor=s,l.labelIsToTheRightOfTheSpline=!0,l.labelIsToTheLeftOfTheSpline=!1,!1)}return!1}function ph(l){const t=l.right,e=l.leftAnchor;l.leftAnchor=l.rightAnchor,l.rightAnchor=e,l.x=t-l.rightAnchor,l.labelIsToTheLeftOfTheSpline=!0,l.labelIsToTheRightOfTheSpline=!1}function Uc(l,t,e){const i=new ji;for(const s of l)if(!(s>=e.nodeCount))for(const n of e.outEdges[s])t[n.source]===t[n.target]&&i.addNN(n.source,n.target);return Array.from(i.values())}function jc(l,t,e,i){let s=0;const n=i.GetMultiedgeI(l);for(const o of n){s+=e;const a=o.edge.label;a!=null&&(a.positionCenter(new d(a.center.x,t+s+a.height/2)),s+=a.height)}return s}function $c(l,t,e){l.rightAnchor=l.leftAnchor=(t.width+e.GridSizeByX)/2,l.topAnchor=l.bottomAnchor=t.height/2}function Xc(l,t,e,i){const s=Qc(e,l,t,i);t.rightAnchor+=s}function Qc(l,t,e,i){let s=0;const n=l.GetMultiedge(t,t);if(n.length>0){for(const o of n)o.edge.label!=null&&(e.rightAnchor+=o.edge.label.width,e.topAnchor<o.edge.label.height/2&&(e.topAnchor=e.bottomAnchor=o.edge.label.height/2));s+=(i.NodeSeparation+i.MinNodeWidth)*n.length}return s}function Yc(l,t){if(t.isIdentity())return;const e=t.inverse();for(const i of l.shallowNodes)i.transform(e);for(const i of l.shallowEdges)if(i.label!=null){const s=Z.mkPP(e.multiplyPoint(new d(0,0)),e.multiplyPoint(new d(i.label.width,i.label.height)));i.label.width=s.width,i.label.height=s.height}}function Kc(l,t){if(!t.isIdentity()){for(const e of l.shallowNodes)e.transform(t);for(const e of l.shallowEdges)if(e.label!=null){const i=Z.mkPP(t.multiplyPoint(new d(0,0)),t.multiplyPoint(new d(e.label.width,e.label.height)));e.label.width=i.width,e.label.height=i.height}Jc(l,t),l.graph.parent==null&&(l.boundingBox=null)}}function Jc(l,t){for(const e of l.shallowEdges)e.label&&e.label.transform(t),Zc(t,e)}function Zc(l,t){if(t.curve!=null){t.curve=t.curve.transform(l);const e=t;e.sourceArrowhead!=null&&(e.sourceArrowhead.tipPosition=l.multiplyPoint(e.sourceArrowhead.tipPosition)),e.targetArrowhead!=null&&(e.targetArrowhead.tipPosition=l.multiplyPoint(e.targetArrowhead.tipPosition)),_c(t,l)}}function _c(l,t){if(l.smoothedPolyline!=null)for(let e=l.smoothedPolyline.headSite;e!=null;e=e.next)e.point=t.multiplyPoint(e.point)}var td=xn(79275),Us;(function(l){l[l.normal=0]="normal",l[l.inv=1]="inv",l[l.dot=2]="dot",l[l.invdot=3]="invdot",l[l.odot=4]="odot",l[l.invodot=5]="invodot",l[l.none=6]="none",l[l.tee=7]="tee",l[l.empty=8]="empty",l[l.invempty=9]="invempty",l[l.diamond=10]="diamond",l[l.odiamond=11]="odiamond",l[l.ediamond=12]="ediamond",l[l.crow=13]="crow",l[l.box=14]="box",l[l.obox=15]="obox",l[l.open=16]="open",l[l.halfopen=17]="halfopen",l[l.vee=18]="vee"})(Us||(Us={}));var ne;(function(l){l[l.diamond=0]="diamond",l[l.ellipse=1]="ellipse",l[l.box=2]="box",l[l.circle=3]="circle",l[l.record=4]="record",l[l.plaintext=5]="plaintext",l[l.point=6]="point",l[l.mdiamond=7]="mdiamond",l[l.msquare=8]="msquare",l[l.polygon=9]="polygon",l[l.doublecircle=10]="doublecircle",l[l.house=11]="house",l[l.invhouse=12]="invhouse",l[l.parallelogram=13]="parallelogram",l[l.octagon=14]="octagon",l[l.tripleoctagon=15]="tripleoctagon",l[l.triangle=16]="triangle",l[l.trapezium=17]="trapezium",l[l.drawFromGeometry=18]="drawFromGeometry",l[l.hexagon=19]="hexagon"})(ne||(ne={}));var Ma;(function(l){l[l.same=0]="same",l[l.min=1]="min",l[l.source=2]="source",l[l.max=3]="max",l[l.sink=4]="sink"})(Ma||(Ma={}));var Va;(function(l){l[l.none=0]="none",l[l.dashed=1]="dashed",l[l.solid=2]="solid",l[l.invis=3]="invis",l[l.bold=4]="bold",l[l.filled=5]="filled",l[l.diagonals=6]="diagonals",l[l.dotted=7]="dotted",l[l.rounded=8]="rounded"})(Va||(Va={}));var Wa;(function(l){l[l.forward=0]="forward",l[l.back=1]="back",l[l.both=2]="both",l[l.none=3]="none"})(Wa||(Wa={}));var Ha;(function(l){l[l.in=0]="in",l[l.out=1]="out"})(Ha||(Ha={}));class E{constructor(t,e,i,s){this.a=t,this.r=e,this.g=i,this.b=s}static mkWithKeyword(t,e,i,s,n){const o=new E(t,e,i,s);return o.keyword=n,o}static parse(t){switch(t.toLowerCase()){case"aliceblue":return E.AliceBlue;case"antiquewhite":return E.AntiqueWhite;case"aqua":return E.Aqua;case"aquamarine":return E.Aquamarine;case"azure":return E.Azure;case"beige":return E.Beige;case"bisque":return E.Bisque;case"black":return E.Black;case"blanchedalmond":return E.BlanchedAlmond;case"blue":return E.Blue;case"blueviolet":return E.BlueViolet;case"brown":return E.Brown;case"burlywood":return E.BurlyWood;case"cadetblue":return E.CadetBlue;case"chartreuse":return E.Chartreuse;case"chocolate":return E.Chocolate;case"coral":return E.Coral;case"cornflowerblue":return E.CornflowerBlue;case"cornsilk":return E.Cornsilk;case"crimson":return E.Crimson;case"cyan":return E.Cyan;case"darkblue":return E.DarkBlue;case"darkcyan":return E.DarkCyan;case"darkgoldenrod":return E.DarkGoldenrod;case"darkgray":return E.DarkGray;case"darkgreen":return E.DarkGreen;case"darkkhaki":return E.DarkKhaki;case"darkmagenta":return E.DarkMagenta;case"darkolivegreen":return E.DarkOliveGreen;case"darkorange":return E.DarkOrange;case"darkorchid":return E.DarkOrchid;case"darkred":return E.DarkRed;case"darksalmon":return E.DarkSalmon;case"darkseagreen":return E.DarkSeaGreen;case"darkslateblue":return E.DarkSlateBlue;case"darkslategray":return E.DarkSlateGray;case"darkturquoise":return E.DarkTurquoise;case"darkviolet":return E.DarkViolet;case"deeppink":return E.DeepPink;case"deepskyblue":return E.DeepSkyBlue;case"dimgray":return E.DimGray;case"dodgerblue":return E.DodgerBlue;case"firebrick":return E.Firebrick;case"floralwhite":return E.FloralWhite;case"forestgreen":return E.ForestGreen;case"fuchsia":return E.Fuchsia;case"gainsboro":return E.Gainsboro;case"ghostwhite":return E.GhostWhite;case"gold":return E.Gold;case"goldenrod":return E.Goldenrod;case"gray":return E.Gray;case"green":return E.Green;case"greenyellow":return E.GreenYellow;case"honeydew":return E.Honeydew;case"hotpink":return E.HotPink;case"indianred":return E.IndianRed;case"indigo":return E.Indigo;case"ivory":return E.Ivory;case"khaki":return E.Khaki;case"lavender":return E.Lavender;case"lavenderblush":return E.LavenderBlush;case"lawngreen":return E.LawnGreen;case"lemonchiffon":return E.LemonChiffon;case"lightblue":return E.LightBlue;case"lightcoral":return E.LightCoral;case"lightcyan":return E.LightCyan;case"lightgoldenrodyellow":return E.LightGoldenrodYellow;case"lightgray":case"lightgrey":return E.LightGray;case"lightgreen":return E.LightGreen;case"lightpink":return E.LightPink;case"lightsalmon":return E.LightSalmon;case"lightseagreen":return E.LightSeaGreen;case"lightskyblue":return E.LightSkyBlue;case"lightslategray":return E.LightSlateGray;case"lightsteelblue":return E.LightSteelBlue;case"lightyellow":return E.LightYellow;case"lime":return E.Lime;case"limegreen":return E.LimeGreen;case"linen":return E.Linen;case"magenta":return E.Magenta;case"maroon":return E.Maroon;case"mediumaquamarine":return E.MediumAquamarine;case"mediumblue":return E.MediumBlue;case"mediumorchid":return E.MediumOrchid;case"mediumpurple":return E.MediumPurple;case"mediumseagreen":return E.MediumSeaGreen;case"mediumslateblue":return E.MediumSlateBlue;case"mediumspringgreen":return E.MediumSpringGreen;case"mediumturquoise":return E.MediumTurquoise;case"mediumvioletred":return E.MediumVioletRed;case"midnightblue":return E.MidnightBlue;case"mintcream":return E.MintCream;case"mistyrose":return E.MistyRose;case"moccasin":return E.Moccasin;case"navajowhite":return E.NavajoWhite;case"navy":return E.Navy;case"oldlace":return E.OldLace;case"olive":return E.Olive;case"olivedrab":return E.OliveDrab;case"orange":return E.Orange;case"orangered":return E.OrangeRed;case"orchid":return E.Orchid;case"palegoldenrod":return E.PaleGoldenrod;case"palegreen":return E.PaleGreen;case"paleturquoise":return E.PaleTurquoise;case"palevioletred":return E.PaleVioletRed;case"papayawhip":return E.PapayaWhip;case"peachpuff":return E.PeachPuff;case"peru":return E.Peru;case"pink":return E.Pink;case"plum":return E.Plum;case"powderblue":return E.PowderBlue;case"purple":return E.Purple;case"red":return E.Red;case"rosybrown":return E.RosyBrown;case"royalblue":return E.RoyalBlue;case"saddlebrown":return E.SaddleBrown;case"salmon":return E.Salmon;case"sandybrown":return E.SandyBrown;case"seagreen":return E.SeaGreen;case"seashell":return E.SeaShell;case"sienna":return E.Sienna;case"silver":return E.Silver;case"skyblue":return E.SkyBlue;case"slateblue":return E.SlateBlue;case"slategray":return E.SlateGray;case"snow":return E.Snow;case"springgreen":return E.SpringGreen;case"steelblue":return E.SteelBlue;case"tan":return E.Tan;case"teal":return E.Teal;case"thistle":return E.Thistle;case"tomato":return E.Tomato;case"transparent":return E.Transparent;case"turquoise":return E.Turquoise;case"violet":return E.Violet;case"wheat":return E.Wheat;case"white":return E.White;case"whitesmoke":return E.WhiteSmoke;case"yellow":return E.Yellow;case"yellowgreen":return E.YellowGreen;default:return}}get keyword(){return this.keyword_}set keyword(t){this.keyword_=t}static mkRGB(t,e,i){return new E(255,t,e,i)}get A(){return this.a}set A(t){this.a=t}get R(){return this.r}set R(t){this.r=t}get G(){return this.g}set G(t){this.g=t}get B(){return this.b}set B(t){this.b=t}static Xex(t){const e=t.toString(16);return e.length===1?"0"+e:e.substring(e.length-2,2)}static equal(t,e){return t.a===e.a&&t.r===e.r&&t.b===e.b&&t.g===e.g}toString(){return this.keyword?this.keyword:'"#'+E.Xex(this.R)+E.Xex(this.G)+E.Xex(this.B)+(this.A===255?"":E.Xex(this.A))+'"'}static get AliceBlue(){return E.mkWithKeyword(255,240,248,255,"aliceblue")}static get AntiqueWhite(){return E.mkWithKeyword(255,250,235,215,"antiquewhite")}static get Aqua(){return E.mkWithKeyword(255,0,255,255,"aqua")}static get Aquamarine(){return E.mkWithKeyword(255,127,255,212,"aquamarine")}static get Azure(){return E.mkWithKeyword(255,240,255,255,"azure")}static get Beige(){return E.mkWithKeyword(255,245,245,220,"beige")}static get Bisque(){return E.mkWithKeyword(255,255,228,196,"bisque")}static get Black(){return E.mkWithKeyword(255,0,0,0,"black")}static get BlanchedAlmond(){return E.mkWithKeyword(255,255,235,205,"blanchedalmond")}static get Blue(){return E.mkWithKeyword(255,0,0,255,"blue")}static get BlueViolet(){return E.mkWithKeyword(255,138,43,226,"blueviolet")}static get Brown(){return E.mkWithKeyword(255,165,42,42,"brown")}static get BurlyWood(){return E.mkWithKeyword(255,222,184,135,"burlywood")}static get CadetBlue(){return E.mkWithKeyword(255,95,158,160,"cadetblue")}static get Chartreuse(){return E.mkWithKeyword(255,127,255,0,"chartreuse")}static get Chocolate(){return E.mkWithKeyword(255,210,105,30,"chocolate")}static get Coral(){return E.mkWithKeyword(255,255,127,80,"coral")}static get CornflowerBlue(){return E.mkWithKeyword(255,100,149,237,"cornflowerblue")}static get Cornsilk(){return E.mkWithKeyword(255,255,248,220,"cornsilk")}static get Crimson(){return E.mkWithKeyword(255,220,20,60,"crimson")}static get Cyan(){return E.mkWithKeyword(255,0,255,255,"cyan")}static get DarkBlue(){return E.mkWithKeyword(255,0,0,139,"darkblue")}static get DarkCyan(){return E.mkWithKeyword(255,0,139,139,"darkcyan")}static get DarkGoldenrod(){return E.mkWithKeyword(255,184,134,11,"darkgoldenrod")}static get DarkGray(){return E.mkWithKeyword(255,169,169,169,"darkgray")}static get DarkGreen(){return E.mkWithKeyword(255,0,100,0,"darkgreen")}static get DarkKhaki(){return E.mkWithKeyword(255,189,183,107,"darkkhaki")}static get DarkMagenta(){return E.mkWithKeyword(255,139,0,139,"darkmagenta")}static get DarkOliveGreen(){return E.mkWithKeyword(255,85,107,47,"darkolivegreen")}static get DarkOrange(){return E.mkWithKeyword(255,255,140,0,"darkorange")}static get DarkOrchid(){return E.mkWithKeyword(255,153,50,204,"darkorchid")}static get DarkRed(){return E.mkWithKeyword(255,139,0,0,"darkred")}static get DarkSalmon(){return E.mkWithKeyword(255,233,150,122,"darksalmon")}static get DarkSeaGreen(){return E.mkWithKeyword(255,143,188,139,"darkseagreen")}static get DarkSlateBlue(){return E.mkWithKeyword(255,72,61,139,"darkslateblue")}static get DarkSlateGray(){return E.mkWithKeyword(255,47,79,79,"darkslategray")}static get DarkTurquoise(){return E.mkWithKeyword(255,0,206,209,"darkturquoise")}static get DarkViolet(){return E.mkWithKeyword(255,148,0,211,"darkviolet")}static get DeepPink(){return E.mkWithKeyword(255,255,20,147,"deeppink")}static get DeepSkyBlue(){return E.mkWithKeyword(255,0,191,255,"deepskyblue")}static get DimGray(){return E.mkWithKeyword(255,105,105,105,"dimgray")}static get DodgerBlue(){return E.mkWithKeyword(255,30,144,255,"dodgerblue")}static get Firebrick(){return E.mkWithKeyword(255,178,34,34,"firebrick")}static get FloralWhite(){return E.mkWithKeyword(255,255,250,240,"floralwhite")}static get ForestGreen(){return E.mkWithKeyword(255,34,139,34,"forestgreen")}static get Fuchsia(){return E.mkWithKeyword(255,255,0,255,"fuchsia")}static get Gainsboro(){return E.mkWithKeyword(255,220,220,220,"gainsboro")}static get GhostWhite(){return E.mkWithKeyword(255,248,248,255,"ghostwhite")}static get Gold(){return E.mkWithKeyword(255,255,215,0,"gold")}static get Goldenrod(){return E.mkWithKeyword(255,218,165,32,"goldenrod")}static get Gray(){return E.mkWithKeyword(255,128,128,128,"gray")}static get Green(){return E.mkWithKeyword(255,0,128,0,"green")}static get GreenYellow(){return E.mkWithKeyword(255,173,255,47,"greenyellow")}static get Honeydew(){return E.mkWithKeyword(255,240,255,240,"honeydew")}static get HotPink(){return E.mkWithKeyword(255,255,105,180,"hotpink")}static get IndianRed(){return E.mkWithKeyword(255,205,92,92,"indianred")}static get Indigo(){return E.mkWithKeyword(255,75,0,130,"indigo")}static get Ivory(){return E.mkWithKeyword(255,255,255,240,"ivory")}static get Khaki(){return E.mkWithKeyword(255,240,230,140,"khaki")}static get Lavender(){return E.mkWithKeyword(255,230,230,250,"lavender")}static get LavenderBlush(){return E.mkWithKeyword(255,255,240,245,"lavenderblush")}static get LawnGreen(){return E.mkWithKeyword(255,124,252,0,"lawngreen")}static get LemonChiffon(){return E.mkWithKeyword(255,255,250,205,"lemonchiffon")}static get LightBlue(){return E.mkWithKeyword(255,173,216,230,"lightblue")}static get LightCoral(){return E.mkWithKeyword(255,240,128,128,"lightcoral")}static get LightCyan(){return E.mkWithKeyword(255,224,255,255,"lightcyan")}static get LightGoldenrodYellow(){return E.mkWithKeyword(255,250,250,210,"lightgoldenrodyellow")}static get LightGray(){return E.mkWithKeyword(255,211,211,211,"lightgray")}static get LightGreen(){return E.mkWithKeyword(255,144,238,144,"lightgreen")}static get LightPink(){return E.mkWithKeyword(255,255,182,193,"lightpink")}static get LightSalmon(){return E.mkWithKeyword(255,255,160,122,"lightsalmon")}static get LightSeaGreen(){return E.mkWithKeyword(255,32,178,170,"lightseagreen")}static get LightSkyBlue(){return E.mkWithKeyword(255,135,206,250,"lightskyblue")}static get LightSlateGray(){return E.mkWithKeyword(255,119,136,153,"lightslategray")}static get LightSteelBlue(){return E.mkWithKeyword(255,176,196,222,"lightsteelblue")}static get LightYellow(){return E.mkWithKeyword(255,255,255,224,"lightyellow")}static get Lime(){return E.mkWithKeyword(255,0,255,0,"lime")}static get LimeGreen(){return E.mkWithKeyword(255,50,205,50,"limegreen")}static get Linen(){return E.mkWithKeyword(255,250,240,230,"linen")}static get Magenta(){return E.mkWithKeyword(255,255,0,255,"magenta")}static get Maroon(){return E.mkWithKeyword(255,128,0,0,"maroon")}static get MediumAquamarine(){return E.mkWithKeyword(255,102,205,170,"mediumaquamarine")}static get MediumBlue(){return E.mkWithKeyword(255,0,0,205,"mediumblue")}static get MediumOrchid(){return E.mkWithKeyword(255,186,85,211,"mediumorchid")}static get MediumPurple(){return E.mkWithKeyword(255,147,112,219,"mediumpurple")}static get MediumSeaGreen(){return E.mkWithKeyword(255,60,179,113,"mediumseagreen")}static get MediumSlateBlue(){return E.mkWithKeyword(255,123,104,238,"mediumslateblue")}static get MediumSpringGreen(){return E.mkWithKeyword(255,0,250,154,"mediumspringgreen")}static get MediumTurquoise(){return E.mkWithKeyword(255,72,209,204,"mediumturquoise")}static get MediumVioletRed(){return E.mkWithKeyword(255,199,21,133,"mediumvioletred")}static get MidnightBlue(){return E.mkWithKeyword(255,25,25,112,"midnightblue")}static get MintCream(){return E.mkWithKeyword(255,245,255,250,"mintcream")}static get MistyRose(){return E.mkWithKeyword(255,255,228,225,"mistyrose")}static get Moccasin(){return E.mkWithKeyword(255,255,228,181,"moccasin")}static get NavajoWhite(){return E.mkWithKeyword(255,255,222,173,"navajowhite")}static get Navy(){return E.mkWithKeyword(255,0,0,128,"navy")}static get OldLace(){return E.mkWithKeyword(255,253,245,230,"oldlace")}static get Olive(){return E.mkWithKeyword(255,128,128,0,"olive")}static get OliveDrab(){return E.mkWithKeyword(255,107,142,35,"olivedrab")}static get Orange(){return E.mkWithKeyword(255,255,165,0,"orange")}static get OrangeRed(){return E.mkWithKeyword(255,255,69,0,"orangered")}static get Orchid(){return E.mkWithKeyword(255,218,112,214,"orchid")}static get PaleGoldenrod(){return E.mkWithKeyword(255,238,232,170,"palegoldenrod")}static get PaleGreen(){return E.mkWithKeyword(255,152,251,152,"palegreen")}static get PaleTurquoise(){return E.mkWithKeyword(255,175,238,238,"paleturquoise")}static get PaleVioletRed(){return E.mkWithKeyword(255,219,112,147,"palevioletred")}static get PapayaWhip(){return E.mkWithKeyword(255,255,239,213,"papayawhip")}static get PeachPuff(){return E.mkWithKeyword(255,255,218,185,"peachpuff")}static get Peru(){return E.mkWithKeyword(255,205,133,63,"peru")}static get Pink(){return E.mkWithKeyword(255,255,192,203,"pink")}static get Plum(){return E.mkWithKeyword(255,221,160,221,"plum")}static get PowderBlue(){return E.mkWithKeyword(255,176,224,230,"powderblue")}static get Purple(){return E.mkWithKeyword(255,128,0,128,"purple")}static get Red(){return E.mkWithKeyword(255,255,0,0,"red")}static get RosyBrown(){return E.mkWithKeyword(255,188,143,143,"rosybrown")}static get RoyalBlue(){return E.mkWithKeyword(255,65,105,225,"royalblue")}static get SaddleBrown(){return E.mkWithKeyword(255,139,69,19,"saddlebrown")}static get Salmon(){return E.mkWithKeyword(255,250,128,114,"salmon")}static get SandyBrown(){return E.mkWithKeyword(255,244,164,96,"sandybrown")}static get SeaGreen(){return E.mkWithKeyword(255,46,139,87,"seagreen")}static get SeaShell(){return E.mkWithKeyword(255,255,245,238,"seashell")}static get Sienna(){return E.mkWithKeyword(255,160,82,45,"sienna")}static get Silver(){return E.mkWithKeyword(255,192,192,192,"silver")}static get SkyBlue(){return E.mkWithKeyword(255,135,206,235,"skyblue")}static get SlateBlue(){return E.mkWithKeyword(255,106,90,205,"slateblue")}static get SlateGray(){return E.mkWithKeyword(255,112,128,144,"slategray")}static get Snow(){return E.mkWithKeyword(255,255,250,250,"snow")}static get SpringGreen(){return E.mkWithKeyword(255,0,255,127,"springgreen")}static get SteelBlue(){return E.mkWithKeyword(255,70,130,180,"steelblue")}static get Tan(){return E.mkWithKeyword(255,210,180,140,"tan")}static get Teal(){return E.mkWithKeyword(255,0,128,128,"teal")}static get Thistle(){return E.mkWithKeyword(255,216,191,216,"thistle")}static get Tomato(){return E.mkWithKeyword(255,255,99,71,"tomato")}static get Transparent(){return E.mkWithKeyword(0,255,255,255,"transparent")}static get Turquoise(){return E.mkWithKeyword(255,64,224,208,"turquoise")}static get Violet(){return E.mkWithKeyword(255,238,130,238,"violet")}static get Wheat(){return E.mkWithKeyword(255,245,222,179,"wheat")}static get White(){return E.mkWithKeyword(255,255,255,255,"white")}static get WhiteSmoke(){return E.mkWithKeyword(255,245,245,245,"whitesmoke")}static get Yellow(){return E.mkWithKeyword(255,255,255,0,"yellow")}static get YellowGreen(){return E.mkWithKeyword(255,154,205,50,"yellowgreen")}}class Fe extends fe{constructor(t){super(t,Et.DrawingObjectIndex),this.labelfontcolor=E.Black,this.styles=[],this.penwidth=1,this.fontname=Fe.defaultLabelFontName,this.fontsize=Fe.defaultLabelFontSize}rebind(t){this.entity=t,this.bind(Et.DrawingObjectIndex)}static copyValidFields(t,e){t==null||e==null||(t.color&&t.color.keyword&&t.color.keyword.toLowerCase()!=="black"&&(e.color=t.color),t.fillColor&&(e.fillColor=t.fillColor),t.labelfontcolor&&t.labelfontcolor.keyword.toLowerCase()!=="black"&&(e.labelfontcolor=t.labelfontcolor),t.labelText!=null&&t.labelText!==""&&t.labelText!==t.id&&(e.labelText=t.labelText),t.fontColor&&t.fontColor.keyword&&t.fontColor.keyword.toLowerCase()!=="black"&&(e.fontColor=t.fontColor),t.styles&&t.styles.length&&(e.styles=t.styles.map(i=>i)),t.pencolor&&t.pencolor.keyword!=="black"&&(e.pencolor=t.pencolor),t.penwidth&&t.penwidth!==1&&(e.penwidth=t.penwidth),t.rankdir&&(e.rankdir=t.rankdir),t.fontname&&t.fontname!==Fe.defaultLabelFontName&&(e.fontname=t.fontname),t.margin&&(e.margin=t.margin),t.fontsize&&t.fontsize!==Fe.defaultLabelFontSize&&(e.fontsize=t.fontsize),t.orientation&&(e.orientation=t.orientation),t.ranksep&&(e.ranksep=t.ranksep),t.arrowtail&&(e.arrowtail=t.arrowtail),t.arrowhead&&(e.arrowhead=t.arrowhead),t.ordering&&(e.ordering=t.ordering),t.bgcolor&&(e.bgcolor=t.bgcolor),t.pos&&(e.pos=t.pos),t.nodesep&&(e.nodesep=t.nodesep),t.arrowsize&&(e.arrowsize=t.arrowsize),t.samehead&&(e.samehead=t.samehead),t.layersep&&(e.layersep=t.layersep),t.clusterRank&&(e.clusterRank=t.clusterRank))}get labelText(){return this._labelText}set labelText(t){this._labelText=t}get arrowhead(){return this._arrowhead}set arrowhead(t){this._arrowhead=t}get id(){return this._id}set id(t){this._id=t}static getDrawingObj(t){return t==null?null:t.getAttr(Et.DrawingObjectIndex)}}Fe.defaultLabelFontName="Times-Roman",Fe.defaultLabelFontSize=12;class Bi extends Fe{constructor(t){super(t),this.shape=ne.box,this.padding=2,this.xRad=3,this.yRad=3,this.labelMargin=1,this.labelWidthToHeightRatio=1,t!=null&&(this.labelText=t.id)}clone(){throw new Error("Method not implemented.")}get Padding(){return this.padding}set Padding(t){this.padding=Math.max(0,t)}get XRadius(){return this.xRad}set XRadius(t){this.xRad=t}get YRadius(){return this.yRad}set YRadius(t){this.yRad=t}static get DefaultFillColor(){return Bi.defaultFillColor}static set DefaultFillColor(t){Bi.defaultFillColor=t}get ShapeEnum(){return this.shape}set ShapeEnum(t){this.shape=t}get LabelMargin(){return this.labelMargin}set LabelMargin(t){this.labelMargin=t}get LabelWidthToHeightRatio(){return this.labelWidthToHeightRatio}set LabelWidthToHeightRatio(t){this.labelWidthToHeightRatio=t}get node(){return this.entity}get id(){return this.node?this.node.id:""}}Bi.defaultFillColor=E.LightGray;class Zo extends Fe{constructor(t,e){super(t),this.directed=!0,this.directed=e,e?this.arrowhead=Us.normal:this.arrowhead=Us.none,this.arrowtail=Us.none}clone(){const t=new Zo(null,this.directed);return Fe.copyValidFields(this,t),t.directed=this.directed,t.arrowtail=this.arrowtail,t.arrowhead=this.arrowhead,t}}class Tn extends Bi{constructor(){super(...arguments),this.graphVisData={sameRanks:new Array,minRanks:new Array,maxRanks:new Array,sourceRanks:new Array,sinkRanks:new Array}}get defaultNodeObject(){return this._defaultNodeObject}set defaultNodeObject(t){this._defaultNodeObject=t}static getDrawingGraph(t){return Fe.getDrawingObj(t)}get graph(){return this.entity}findNode(t){const i=this.graph.findNode(t);return i==null?null:Fe.getDrawingObj(i)}hasDirectedEdge(){for(const t of this.graph.deepEdges)if(Fe.getDrawingObj(t).directed)return!0;return!1}createGeometry(t=e=>e?new De(e.length*8+8,20):null){const e=new Xt(this.graph);this.textMeasure=t;const i={fontFamily:this.fontname,fontSize:this.fontsize,fontStyle:"normal"};e.labelSize=t(this.labelText,i);for(const s of this.graph.nodesBreadthFirst)this.createNodeGeometry(s);for(const s of this.graph.deepEdges)this.createEdgeGeometry(s);if(this.rankdir){const s=e.layoutSettings=new Sn;s.layerDirection=this.rankdir}return e}createEdgeGeometry(t){const e=Zo.getDrawingObj(t),i=new Ne(t);if(e.arrowhead!=Us.none&&(i.targetArrowhead=new Mt),e.arrowtail!=Us.none&&(i.sourceArrowhead=new Mt),e.labelText){const s=this.textMeasure(e.labelText,{fontSize:e.fontsize,fontFamily:e.fontname,fontStyle:"normal"}),n=t.label=new rh(t);new Ks(n,Z.mkPP(new d(0,0),new d(s.width,s.height))),e.measuredTextSize=s}e.penwidth&&(i.lineWidth=e.penwidth)}curveByShape(t,e,i,s){let n;switch(s.shape){case ne.diamond:n=H.mkDiamond(t,e,i);break;case ne.ellipse:n=H.mkEllipse(t/1.6,e/1.6,i);break;case ne.record:case ne.box:n=H.mkRectangleWithRoundedCorners(t,e,s.XRadius,s.YRadius,i);break;case ne.circle:n=H.mkCircle(Math.sqrt(t*t+e*e),i);break;case ne.plaintext:break;case ne.point:break;case ne.mdiamond:break;case ne.msquare:break;case ne.polygon:break;case ne.doublecircle:n=H.mkCircle(Math.sqrt(t*t+e*e)+2*s.penwidth,i);break;case ne.house:n=H.createHouse(t,e,i);break;case ne.invhouse:n=H.createInvertedHouse(t,e,i);break;case ne.parallelogram:n=H.createParallelogram(t,e,i);break;case ne.octagon:n=H.createOctagon(t,e,i);break;case ne.tripleoctagon:break;case ne.triangle:break;case ne.trapezium:break;case ne.drawFromGeometry:break;case ne.hexagon:n=H.createHexagon(t,e,i);break}return n??H.mkRectangleWithRoundedCorners(t,e,s.XRadius,s.YRadius,i)}createNodeGeometry(t,e=new d(0,0)){if(t instanceof Gt){const i=Fe.getDrawingObj(t),s=new Xt(t);i.labelText&&(s.labelSize=i.measuredTextSize=za(i,this.textMeasure))}else{const i=Bi.getDrawingObj(t);let s=new De(1,1);i.labelText&&(s=za(i,this.textMeasure)),i.measuredTextSize=s;const n=new Pe(t),o=s.width+i.LabelMargin*2,a=s.height+i.LabelMargin*2;n.boundaryCurve=this.curveByShape(o,a,e,i)}}measureLabelSizes(t){var e;for(const i of this.graph.nodesBreadthFirst){const s=Bi.getDrawingObj(i);s.measuredTextSize=(e=za(s,t))!==null&&e!==void 0?e:new De(1,1)}}}function za(l,t){return l.labelText?t(l.labelText,{fontSize:l.fontsize,fontFamily:l.fontname,fontStyle:"normal"}):null}class qa{constructor(t,e,i){this.fixedNodes=new Set,this.separation=e,this.rtree=new RTree(createRectangleNodeOnData(t,s=>this.GetPaddedBoxOfNode(s))),this.pushingNodes=i}get FixedNodes(){return this.fixedNodes}GetPaddedBoxOfNode(t){const e=t.boundaryCurve.boundingBox.clone();return e.pad(this.separation/2),e}PushNodes(){this.fixedNodes.clear(),insertRange(this.fixedNodes,this.pushingNodes);const t=new Queue;for(const i of this.pushingNodes)t.enqueue(i);const e=new Array;for(;t.length>0;){const i=t.dequeue();for(const s of this.PushByNodeAndReportPushedAsFixed(i))t.enqueue(s),this.fixedNodes.add(s),e.push(s)}return e}PushByNodeAndReportPushedAsFixed(t){const e=[],i=this.GetPaddedBoxOfNode(t);for(const s of this.rtree.GetAllLeavesIntersectingRectangle(i))this.fixedNodes.has(s.UserData)||this.PushNodeAndUpdateRTree(t,s)&&e.push(s.UserData);return e}PushNodeAndUpdateRTree(t,e){const i=e.UserData.center.sub(t.center),s=t.width/2+e.UserData.width/2,n=t.height/2+e.UserData.height/2,o=Math.abs(i.x),a=Math.abs(i.y),h=o-s,u=a-n;if(h>=this.separation||u>=this.separation)return!1;if(o>=a){const c=i.x>0?this.separation-h:h-this.separation;this.PushByX(c,e)}else{const c=i.y>0?this.separation-u:u-this.separation;this.PushByY(c,e)}return this.UpdateBoundingBoxesOfPushedAndUpParents(e),!0}PushByX(t,e){const i=new Point(t,0);qa.PushByPoint(e,i)}static PushByPoint(t,e){t.UserData.center=t.UserData.center.add(e),t.UserData instanceof GeomGraph&&t.UserData.translate(e)}PushByY(t,e){const i=new Point(0,t);qa.PushByPoint(e,i)}UpdateBoundingBoxesOfPushedAndUpParents(t){t.irect=this.GetPaddedBoxOfNode(t.UserData);let e=t.Parent;for(;e!=null;)e.irect=e.Left.irect.add_rect(e.Right.irect),e=e.Parent}UpdateRTreeByChangedNodeBox(t,e){const i=this.FindClusterNode(t,e);this.UpdateBoundingBoxesOfPushedAndUpParents(i)}FindClusterNode(t,e){const i=this.rtree.RootNode;return this.FindClusterNodeRecurse(i,t,e)}FindClusterNodeRecurse(t,e,i){if(t.UserData!=null)return t.UserData===e?t:null;let s=null;return i.intersects(t.left.irect)&&(s=this.FindClusterNodeRecurse(t.Left,e,i)),s??(i.intersects(t.right.irect)?this.FindClusterNodeRecurse(t.Right,e,i):null)}FirstPushingNode(){return this.pushingNodes[0]}}class ig{constructor(t,e,i){this.listOfPushers=new Array,this.labelFixtures=new Map,this.geomGraph=e,this.nodeSeparation=i.NodeSeparation,this.layoutSettings=i,this.pushingNodesArray=t,this.InitBumperPushers()}get geomGraph(){return this.geomGraph_}set geomGraph(t){this.geomGraph_=t}InitBumperPushers(){if(this.pushingNodesArray.length===0)return;let t=GeomGraph.getGeom(this.pushingNodesArray[0].node.parent),e=this.pushingNodesArray;do if(this.listOfPushers.push(new BumperPusher(t.shallowNodes,this.nodeSeparation,e)),t.graph.parent)t=GeomGraph.getGeom(t.graph.parent),e=[t];else break;while(!0)}RunPushers(){for(let t=0;t<this.listOfPushers.length;t++){const e=this.listOfPushers[t];e.PushNodes();const i=e.FirstPushingNode().node.parent;if(i===this.geomGraph_.graph)break;const s=GeomGraph.getGeom(i),n=s.boundingBox;if(s.calculateBoundsFromChildren(),s.boundingBox.equalEps(n))break;this.listOfPushers[t+1].UpdateRTreeByChangedNodeBox(s,n)}}Drag(t){if(!(t.x==null&&t.y==null)){for(const e of this.pushingNodesArray)e.translate(t);this.RunPushers(),this.RouteChangedEdges()}}RouteChangedEdges(){this.changedEdges=this.GetChangedEdges(this.GetChangedNodes()),this.InitLabelFixtures(this.changedEdges),new SplineRouter(this.geomGraph_,this.changedEdges,this.layoutSettings.commonSettings.edgeRoutingSettings.Padding,this.layoutSettings.commonSettings.edgeRoutingSettings.PolylinePadding,this.layoutSettings.commonSettings.edgeRoutingSettings.ConeAngle,this.layoutSettings.commonSettings.edgeRoutingSettings.bundlingSettings).run(),this.PositionLabels(this.changedEdges)}PositionLabels(t){for(const e of t)this.PositionEdgeLabel(e)}PositionEdgeLabel(t){const e=this.labelFixtures.get(t);if(e==null)return;const i=t.curve,s=i.length*e.RelativeLengthOnCurve,n=i.getParameterAtLength(s),o=i.derivative(n),a=(e.RightSide?o.rotate90Cw():o.rotate90Ccw()).normalize().mul(e.NormalLength);t.label.positionCenter(i.value(n).add(a))}InitLabelFixtures(t){for(const e of t)this.InitLabelFixture(e)}InitLabelFixture(t){if(t.label==null||this.labelFixtures.has(t))return;const e=t.curve.closestParameter(t.label.center),i=t.curve,n=i.derivative(e).rotate90Cw(),o=t.label.center.sub(i.value(e)),a=new LabelFixture(i.lengthPartial(0,e)/i.length,o.dot(n)>0,o.length);this.labelFixtures.set(t,a)}GetChangedEdges(t){const e=[],i=Rectangle.mkOnRectangles(Array.from(t).map(n=>n.boundingBox)),s=i.perimeter();for(const n of this.geomGraph.deepEdges)this.EdgeNeedsRouting(i,n,s,t)&&e.push(n);return e}EdgeNeedsRouting(t,e,i,s){return e.curve==null||s.has(e.source)||s.has(e.target)||e.source.boundingBox.intersects(t)||e.target.boundaryCurve.boundingBox.intersects(t)?!0:e.boundingBox.intersects(t)?Curve.intersectionOne(i,e.curve,!1)!=null:!1}GetChangedNodes(){const t=new Set;for(const e of this.listOfPushers)for(const i of e.FixedNodes)t.add(i);return t}}class sg{constructor(){this._canUndo=!0}updateDeltaForDragUndo(t){const e=this.data;e.delta=t}registerUndoDrag(t){this.data==null&&(this.data={draggedEnts:new Set,delta:null,changeData:new Map}),"draggedEnts"in this.data&&this.data.draggedEnts.add(t)}undo(){if(Assert.assert(this.canUndo),this.data instanceof Map)for(const[t,e]of this.data)for(const i of e)i.new=t.getAttr(Ua(i.old)).clone(),i.old.rebind(t);else if(this.data&&"deletedEnts"in this.data)for(const t of this.data.deletedEnts)mh(t);else if("insertedEnts"in this.data)for(const t of this.data.insertedEnts){const e=t.parent;if(t instanceof Node)e.removeNode(t);else if(t instanceof Edge)t.remove();else throw new Error("not implemented")}else if("draggedEnts"in this.data){for(const t of this.data.draggedEnts)GeomObject.getGeom(t).translate(this.data.delta);for(const[t,e]of this.data.changeData)for(const i of e)i.new=t.getAttr(Ua(i.old)).clone(),i.old.rebind(t)}else throw new Error("not implemented");this.canUndo=!1}redo(){if(Assert.assert(this.canRedo),this.data instanceof Map)for(const[t,e]of this.data)for(const i of e)i.new.rebind(t);else if("deletedEnts"in this.data)for(const t of this.data.deletedEnts)if(t instanceof Graph)t.removeSubgraph();else if(t instanceof Node)t.parent.removeNode(t);else if(t instanceof Edge)t.remove();else if(t instanceof Label){const e=t.parent;e.label=null}else throw new Error("unexpected type in redo");else if("draggedEnts"in this.data){const t=this.data.delta.neg();for(const e of this.data.draggedEnts)GeomObject.getGeom(e).translate(t);for(const[e,i]of this.data.changeData)for(const s of i)s.new.rebind(e)}else if("insertedEnts"in this.data)for(const t of this.data.insertedEnts)mh(t);else throw new Error("not implemented");this.canUndo=!0}addOldNewPair(t,e){this.data||(this.data=new Map);const i="draggedEnts"in this.data?this.data.changeData:this.data;i.has(t)||i.set(t,[]);const s=Ua(e),n=i.get(t);n[s]==null&&(n[s]={old:e.clone(),new:null})}registerDelete(t){this.data||(this.data={deletedEnts:new Set}),this.data.deletedEnts.add(t)}registerAdd(t){this.data||(this.data={insertedEnts:new Set}),this.data.insertedEnts.add(t)}get canRedo(){return!this._canUndo}get canUndo(){return this._canUndo}set canUndo(t){this._canUndo=t}*entities(){if(this.data)if(this.data instanceof Map)yield*this.data.keys();else if("draggedEnts"in this.data)yield*this.data.changeData.keys(),yield*this.data.draggedEnts;else if("deletedEnts"in this.data)yield*this.data.deletedEnts;else if("insertedEnts"in this.data)yield*this.data.insertedEnts;else throw new Error("not implemented")}}function Ua(l){let t;return l instanceof GeomObject?t=AttributeRegistry.GeomObjectIndex:l instanceof DrawingObject?t=AttributeRegistry.DrawingObjectIndex:t=AttributeRegistry.ViewerIndex,t}function mh(l){if(l instanceof Label){const t=l.parent;t.label=l}else if(l instanceof Graph){l.parent.addNode(l);for(const e of l.edges)e.add();for(const e of l.nodesBreadthFirst){for(const i of e.outEdges)i.add();for(const i of e.inEdges)i.add()}}else l instanceof Node?l.parent.addNode(l):l instanceof Edge&&l.add()}class ng{updateDeltaForDragUndo(t){this.currentBridge.updateDeltaForDragUndo(t)}registerForUndoDrag(t){this.currentBridge==null&&(this.currentBridge=new UndoRedoAction),this.currentBridge.registerUndoDrag(t)}registerDelete(t){this.currentBridge==null&&(this.currentBridge=new UndoRedoAction),this.currentBridge.registerDelete(t)}registerAdd(t){this.createUndoPoint(),this.currentBridge.registerAdd(t)}*entitiesToBeChangedByRedo(){this.currentBridge!=null&&(this.currentBridge.canRedo?yield*this.currentBridge.entities():this.currentBridge.next!=null&&this.currentBridge.next.canRedo&&(yield*this.currentBridge.next.entities()))}*entitiesToBeChangedByUndo(){this.currentBridge!=null&&(this.currentBridge.canUndo?yield*this.currentBridge.entities():this.currentBridge.prev!=null&&this.currentBridge.prev.canUndo&&(yield*this.currentBridge.prev.entities()))}registerForUndo(t){this.currentBridge==null&&(this.currentBridge=new UndoRedoAction),this.currentBridge.addOldNewPair(t,t.getAttr(AttributeRegistry.GeomObjectIndex))}canUndo(){return this.currentBridge==null?!1:!!(this.currentBridge.canUndo||this.currentBridge.prev!=null&&this.currentBridge.prev.canUndo)}canRedo(){return this.currentBridge==null?!1:!!(this.currentBridge.canRedo||this.currentBridge.next!=null&&this.currentBridge.next.canRedo)}undo(){this.canUndo&&(this.currentBridge.canUndo?this.currentBridge.undo():this.currentBridge.prev.undo(),this.currentBridge.prev&&(this.currentBridge=this.currentBridge.prev))}redo(){this.canRedo&&(this.currentBridge.canRedo?this.currentBridge.redo():this.currentBridge.next.redo(),this.currentBridge.next&&(this.currentBridge=this.currentBridge.next))}createUndoPoint(){const t=new UndoRedoAction;if(!this.currentBridge)this.currentBridge=t;else if(this.currentBridge.canUndo)this.currentBridge.next=t,t.prev=this.currentBridge,this.currentBridge=t;else{Assert.assert(this.currentBridge.canRedo);const e=this.currentBridge.prev;e&&(t.prev=e,e.next=t),this.currentBridge=t}}}var _o;(function(l){l[l.Incremental=0]="Incremental",l[l.Default=1]="Default"})(_o||(_o={}));class Ci{constructor(){this.edgesToReroute=new Set,this.objectsToDrag=new Set,this.undoList=new UndoList}updateDeltaForDragUndo(t){this.undoList.updateDeltaForDragUndo(t)}registerDelete(t){this.undoList.registerDelete(t)}registerAdd(t){this.undoList.registerAdd(t)}*entitiesToBeChangedByRedo(){yield*this.undoList.entitiesToBeChangedByRedo()}*entitiesToBeChangedByUndo(){yield*this.undoList.entitiesToBeChangedByUndo()}createUndoPoint(){this.undoList.createUndoPoint()}get LayoutSettings(){return this.graph().layoutSettings}get EdgeRoutingMode(){return this.LayoutSettings.commonSettings.edgeRoutingSettings.EdgeRoutingMode}get canUndo(){return this.undoList.canUndo()}get canRedo(){return this.undoList.canRedo()}static calculateAttachmentSegment(t){const e=GeomObject.getGeom(t.parent.entity);if(e!=null)if(Ci.CalculateAttachedSegmentEnd(t,e),Point.closeDistEps(t.attachmentSegmentEnd,t.center))t.attachmentSegmentStart=t.center;else{const i=Curve.intersectionOne(t.boundingBox.perimeter(),LineSegment.mkPP(t.attachmentSegmentEnd,t.center),!1);t.attachmentSegmentStart=i!=null?i.x:t.center}}static CalculateAttachedSegmentEnd(t,e){t.attachmentSegmentEnd=e.curve.value(e.curve.closestParameter(t.center))}drag(t,e,i){if(!(t.x==0&&t.y==0)){for(const s of this.objectsToDrag)this.registerForUndoDrag(s.entity);this.geomEdgeWithSmoothedPolylineExposed==null?this.EdgeRoutingMode!==EdgeRoutingMode.Rectilinear&&this.EdgeRoutingMode!==EdgeRoutingMode.RectilinearToCenter?this.dragObjectsForNonRectilinearCase(t,e):this.DragObjectsForRectilinearCase(t):this.dragPolylineCorner(i,t)}}registerForUndoDrag(t){this.undoList.registerForUndoDrag(t)}DragObjectsForRectilinearCase(t){for(const e of this.objectsToDrag)e instanceof GeomNode&&e.translate(t);throw RectilinearInteractiveEditor.CreatePortsAndRouteEdges(this.LayoutSettings.commonSettings.NodeSeparation/3,1,this.graph().nodesBreadthFirst,this.graph().deepEdges,this.LayoutSettings.commonSettings.edgeRoutingSettings.EdgeRoutingMode),EdgeLabelPlacement.constructorG(this.graph()).run(),this.propagateChangesToClusterParents(),new Error("not implemented")}dragObjectsForNonRectilinearCase(t,e){e===_o.Incremental?this.DragIncrementally(t):this.dragWithStraightLines(t)}dragWithStraightLines(t){for(const e of this.objectsToDrag)e instanceof GeomGraph?e.deepTranslate(t):e.translate(t);this.propagateChangesToClusterParents(),this.routeEdgesAsStraightLines()}propagateChangesToClusterParents(){const t=new Set;for(const e of this.objectsToDrag){if(!(e instanceof GeomNode))continue;const i=e;for(const s of i.node.getAncestors()){const n=GeomObject.getGeom(s);n!==this.graph()&&!this.objectsToDrag.has(n)&&t.add(n)}}if(t.size>0)for(const e of this.graph().subgraphsDepthFirst){const i=e;if(t.has(i)){const s=i.getPumpedGraphWithMarginsBox();if(!s.equalEps(i.boundingBox)){this.registerForUndo(i.entity);for(const n of i.selfEdges())this.addToEdgesToReroute(n);for(const n of i.inEdges())this.addToEdgesToReroute(n);for(const n of i.outEdges())this.addToEdgesToReroute(n);i.boundingBox=s}}}}addToEdgesToReroute(t){this.edgesToReroute.add(t)}DragWithSplinesOrBundles(t){for(const e of this.objectsToDrag)e instanceof GeomNode&&e.translate(t);this.RunSplineRouterAndPutLabels()}RunSplineRouterAndPutLabels(){SplineRouter.mk5(this.graph(),this.LayoutSettings.commonSettings.edgeRoutingSettings.Padding,this.LayoutSettings.commonSettings.edgeRoutingSettings.PolylinePadding,this.LayoutSettings.commonSettings.edgeRoutingSettings.ConeAngle,this.LayoutSettings.commonSettings.edgeRoutingSettings.bundlingSettings).run(),EdgeLabelPlacement.constructorG(this.graph()).run()}registerForUndo(t){this.undoList.registerForUndo(t)}routeEdgesAsStraightLines(){for(const e of this.edgesToReroute)this.registerForUndo(e.entity),StraightLineEdges.CreateSimpleEdgeCurveWithUnderlyingPolyline(e),e.label&&this.registerForUndo(e.edge.label);EdgeLabelPlacement.constructorGA(this.graph(),Array.from(this.edgesToReroute)).run()}DragIncrementally(t){this.incrementalDragger==null&&this.InitIncrementalDragger(),this.incrementalDragger.Drag(t)}dragPolylineCorner(t,e){const i=Ci.findClosestCornerForEdit(this.geomEdgeWithSmoothedPolylineExposed.smoothedPolyline,t);i.point=i.point.add(e),i.prev==null?Ph(this.geomEdgeWithSmoothedPolylineExposed.source,i):i.next==null&&Ph(this.geomEdgeWithSmoothedPolylineExposed.target,i),Ci.createCurveOnChangedPolyline(this.geomEdgeWithSmoothedPolylineExposed)}static dragEdgeWithSite(t,e,i){i.point=i.point.add(t),Ci.createCurveOnChangedPolyline(e)}static createCurveOnChangedPolyline(t){const e=t.smoothedPolyline.createCurve();Arrowhead.trimSplineAndCalculateArrowheadsII(t,t.source.boundaryCurve,t.target.boundaryCurve,e,!1)||Arrowhead.createBigEnoughSpline(t),t.sourcePort=new RelativeFloatingPort(()=>t.source.boundaryCurve,()=>t.source.center,i().sub(t.source.center)),t.targetPort=new RelativeFloatingPort(()=>t.target.boundaryCurve,()=>t.target.center,s().sub(t.target.center));function i(){return t.sourceArrowhead?t.sourceArrowhead.tipPosition:t.curve.start}function s(){return t.targetArrowhead?t.targetArrowhead.tipPosition:t.curve.end}}prepareForObjectDragging(t,e){this.geomEdgeWithSmoothedPolylineExposed=null,this.calculateObjectToDragAndEdgesToReroute(t),this.undoList.createUndoPoint(),e===_o.Incremental&&this.InitIncrementalDragger()}PrepareForClusterCollapseChange(t){throw new Error("not implemented")}InitIncrementalDragger(){this.incrementalDragger=new IncrementalDragger(Array.from(this.objectsToDrag).filter(t=>t instanceof GeomNode),this.graph(),this.LayoutSettings)}clearDraggedSets(){this.objectsToDrag.clear(),this.edgesToReroute.clear()}addToObjectsToDrag(t){this.objectsToDrag.add(t)}calculateObjectToDragAndEdgesToReroute(t){this.clearDraggedSets();for(const e of t)this.addToObjectsToDrag(e),e instanceof GeomEdge&&(this.addToObjectsToDrag(e.source),this.addToObjectsToDrag(e.target));this.removeClusterSuccessorsFromObjectsToDrag(),this.calculateDragSetsForEdges()}removeClusterSuccessorsFromObjectsToDrag(){const t=new Array;for(const e of this.objectsToDrag)this.hasAncestorInObjectsToDrag(e)&&t.push(e);for(const e of t)this.objectsToDrag.delete(e)}calculateDragSetsForEdges(){for(const t of Array.from(this.objectsToDrag))t instanceof GeomGraph?this.addGeomGraphEdgesToRerouteOrDrag(t):t instanceof GeomNode?this.addNodeEdgesToRerouteOrDrag(t):t instanceof GeomEdge&&t.edge.label&&this.addToObjectsToDrag(t.edge.label.getAttr(AttributeRegistry.GeomObjectIndex))}addNodeEdgesToRerouteOrDrag(t){Assert.assert(!(t instanceof GeomGraph));for(const e of t.selfEdges())this.addToObjectsToDrag(e);for(const e of t.inEdges())this.hasSelfOrAncestorInObjectsToDrag(e.source)?this.addToObjectsToDrag(e):this.addToEdgesToReroute(e);for(const e of t.outEdges())this.hasSelfOrAncestorInObjectsToDrag(e.target)?this.addToObjectsToDrag(e):this.addToEdgesToReroute(e);if(t instanceof GeomGraph)for(const e of t.nodesBreadthFirst)this.addNodeEdgesToRerouteOrDrag(e)}addGeomGraphEdgesToRerouteOrDrag(t){Assert.assert(t instanceof GeomGraph);for(const e of t.selfEdges())this.addToObjectsToDrag(e);for(const e of t.inEdges())t.isAncestor(e.source)||(this.hasSelfOrAncestorInObjectsToDrag(e.source)?this.addToObjectsToDrag(e):this.addToEdgesToReroute(e));for(const e of t.outEdges())t.isAncestor(e.target)||(this.hasSelfOrAncestorInObjectsToDrag(e.target)?this.addToObjectsToDrag(e):this.addToEdgesToReroute(e));for(const e of t.nodesBreadthFirst){for(const i of e.outEdges()){const s=i.target;t.isAncestor(s)||(this.hasSelfOrAncestorInObjectsToDrag(s)?this.addToObjectsToDrag(i):this.addToEdgesToReroute(i))}for(const i of e.inEdges()){const s=i.source;t.isAncestor(s)||(this.hasSelfOrAncestorInObjectsToDrag(s)?this.addToObjectsToDrag(i):this.addToEdgesToReroute(i))}}}hasSelfOrAncestorInObjectsToDrag(t){for(;t;){if(this.objectsToDrag.has(t))return!0;t=t.parent}return!1}hasAncestorInObjectsToDrag(t){for(t=t.parent;t;){if(this.objectsToDrag.has(t))return!0;t=t.parent}return!1}static CalculateMiddleOffsetsForMultiedge(t,e,i,s){const n=Ci.GetMiddleAnglesOfMultiedge(t,e),o=Array.from(n.values()),a=s*6,h=o.length/2,u=h*2===o.length;let c;if(u){c=-(a/2);for(let m=h-1;m>=0;m--){const S=o[m];i.set(S,c),c-=a+(S.label?S.label.width:0)}c=a/2;for(let m=h;m<o.length;m++){const S=o[m];i.set(S,c),c+=a+(S.label?S.label.width:0)}}else{c=0;for(let m=h;m>=0;m--){const S=o[m];i.set(S,c),c=a+(S.label?S.label.width:0)}c=a;for(let m=h+1;m<o.length;m++){const S=o[m];i.set(S,c),c+=a+(S.label?S.label.width:0)}}}static GetMiddleAnglesOfMultiedge(t,e){const i=new SortedMap,s=t[0],n=e.center,o=Ci.Middle(s.curve);i.set(0,s);for(let a=1;a<t.length;a++){const h=t[a],u=Ci.Middle(h.curve);let c=Point.anglePCP(o,n,u);c>Math.PI&&(c-=Math.PI*2),i.set(c,h)}return i}static Middle(t){return t.value(.5*t.parStart+.5*t.parEnd)}static*GetMultiEdges(t){const e=new Map;for(const i of t.outEdges())Ci.GetOrCreateListOfMultiedge(e,i.target).push(i);for(const i of t.inEdges())Ci.GetOrCreateListOfMultiedge(e,i.source).push(i);for(const i of e.values())i.length>1&&(yield i)}static GetOrCreateListOfMultiedge(t,e){let i=t.get(e);return i||(t.set(e,i=[]),i)}prepareForGeomEdgeChange(t){Assert.assert(this.geomEdgeWithSmoothedPolylineExposed===t),this.createUndoPoint(),this.registerForUndo(t.edge)}undo(){this.undoList.undo()}redo(){this.undoList.redo()}clear(){this.objectsToDrag=new Set,this.edgesToReroute.clear(),this.undoList=new UndoList}static getPreviousCornerSite(t,e){let i=t.smoothedPolyline.headSite,s=i.next;for(;s!=null;){if(Ci.betweenSites(i,s,e))return i;i=s,s=s.next}return null}static betweenSites(t,e,i){const s=LineSegment.closestParameterOnLineSegment(i,t.point,e.point);return s>.1&&s<.9}insertSite(t,e,i){this.prepareForGeomEdgeChange(t);const s=CornerSite.mkSiteSPS(i,e,i.next);Ci.dragEdgeWithSite(new Point(0,0),t,s)}deleteSite(t,e){this.prepareForGeomEdgeChange(t),Assert.assert(this.geomEdgeWithSmoothedPolylineExposed===t),e.prev.next=e.next,e.next.prev=e.prev,Ci.dragEdgeWithSite(new Point(0,0),t,e.prev)}static findClosestCornerForEdit(t,e,i=Number.POSITIVE_INFINITY){i!==Number.POSITIVE_INFINITY&&(i*=i);let s=t.headSite,n=s,o=n.point.sub(e).lengthSquared;for(;s.next!=null;){s=s.next;const a=e.sub(s.point).lengthSquared;a<o&&(n=s,o=a)}return o>i?null:n}ReactOnViewChange(){}ForgetDragging(){this.incrementalDragger=null}}function Ph(l,t){const e=l.boundaryCurve;if(Curve.PointRelativeToCurveLocation(t.point,e)!=PointLocation.Outside)return;const s=LineSegment.mkPP(l.center,t.point),n=Curve.intersectionOne(s,e,!1);n&&(t.point=n.x)}var Sh;(function(l){l[l.Default=0]="Default",l[l.Node=1]="Node",l[l.Edge=2]="Edge"})(Sh||(Sh={}));var yh;(function(l){l[l.None=0]="None",l[l.Alt=1]="Alt",l[l.Control=2]="Control",l[l.Shift=4]="Shift",l[l.Windows=8]="Windows"})(yh||(yh={}));function je(l){return l.getAttr(AttributeRegistry.ViewerIndex)}function Zr(l){return GeomObject.getGeom(l.entity)}function ed(l){return l&&l.entity instanceof Node}class $e{constructor(t){this.RadiusOfPolylineCorner=10,this.geomEdge=new GeomEdge(null),this.EdgeAttr=new DrawingEdge(null,!0),this.arrowheadLength=Arrowhead.defaultArrowheadLength,this.dragGroup=new Set,this.geomGraphEditor=new GeometryGraphEditor,this.mouseMoveThreshold=.05,this.sourceLoosePolylineWrap={loosePolyline:null},this.sourceOfInsertedEdgeWrap={node:null},this.sourcePortWrap={port:null},this.targetOfInsertedEdgeWrap={node:null},this.targetPortWrap={port:null},this.dragging=!1,this.edgeAttr=new DrawingEdge(null,!0),this.viewer=t,this.decorateObjectForDragging=this.defaultObjectDecorator,this.removeObjDraggingDecorations=this.defaultObjectDecoratorRemover,this.DecorateEdgeForDragging=$e.TheDefaultEdgeDecoratorStub,this.decorateEdgeLabelForDragging=this.defaultEdgeLabelDecorator,this.RemoveEdgeDraggingDecorations=$e.TheDefaultEdgeDecoratorStub,this.geomGraphEditor.graph=()=>GeomGraph.getGeom(this._graph)}resizeLabel(t,e){const i=e.getAttr(AttributeRegistry.DrawingObjectIndex);i.labelText=t,this.viewer.invalidate(e.getAttr(AttributeRegistry.ViewerIndex))}get hasEdgeInsertionPort(){return this.SourcePort!=null||this.TargetPort!=null}get insertingEdge(){return this.insertionMode==InsertionMode.Edge}createUndoPoint(){this.geomGraphEditor.createUndoPoint()}registerDelete(t){this.geomGraphEditor.registerDelete(t)}registerAdd(t){this.geomGraphEditor.registerAdd(t)}forget(t){this.dragGroup.delete(t),this.edgeWithSmoothedPolylineExposed===t&&(this.edgeWithSmoothedPolylineExposed=null)}get edgeWithSmoothedPolylineExposed(){return this._edgeWithSmoothedPolylineExposed}set edgeWithSmoothedPolylineExposed(t){this._edgeWithSmoothedPolylineExposed!==t&&this._edgeWithSmoothedPolylineExposed&&(this._edgeWithSmoothedPolylineExposed.selectedForEditing=!1),this._edgeWithSmoothedPolylineExposed=t,t?(t.selectedForEditing=!0,this.geomGraphEditor.geomEdgeWithSmoothedPolylineExposed=GeomEdge.getGeom(t.edge)):this.geomGraphEditor.geomEdgeWithSmoothedPolylineExposed=null}get ActiveDraggedObject(){return this.aActiveDraggedObject}set ActiveDraggedObject(t){this.aActiveDraggedObject=t}get interactiveEdgeRouter(){return this._interactiveEdgeRouter}set interactiveEdgeRouter(t){this._interactiveEdgeRouter=t}ViewerObjectUnderMouseCursorChanged(t,e){this.TargetPort!=null&&(this.viewer.RemoveTargetPortEdgeRouting(),this.TargetPort=null)}ViewChangeEventHandler(t,e){this._graph!=null}get graph(){return this._graph}set graph(t){this._graph=t,this.geomGraphEditor.clear()}get MouseMoveThreshold(){return this.mouseMoveThreshold}set MouseMoveThreshold(t){this.mouseMoveThreshold=t}get DecorateEdgeForDragging(){return this.decorateEdgeForDragging}set DecorateEdgeForDragging(t){this.decorateEdgeForDragging=t}get RemoveEdgeDraggingDecorations(){return this.removeEdgeDraggingDecorations}set RemoveEdgeDraggingDecorations(t){this.removeEdgeDraggingDecorations=t}get NodeInsertPredicate(){return this.nodeInsertPredicate}set NodeInsertPredicate(t){this.nodeInsertPredicate=t}get SourceOfInsertedEdge(){return this.sourceOfInsertedEdgeWrap.node}set SourceOfInsertedEdge(t){this.sourceOfInsertedEdgeWrap.node=t}get TargetOfInsertedEdge(){return this.targetOfInsertedEdgeWrap.node}set TargetOfInsertedEdge(t){this.targetOfInsertedEdgeWrap.node=t}get SourcePort(){return this.sourcePortWrap.port}set SourcePort(t){this.sourcePortWrap.port=t}get TargetPort(){return this.targetPortWrap.port}set TargetPort(t){this.targetPortWrap.port=t}get CanUndo(){return this.geomGraphEditor.canUndo}get CanRedo(){return this.geomGraphEditor.canRedo}get insertionMode(){return this.viewer==null?InsertionMode.Default:this.viewer.insertionMode}set insertionMode(t){this.viewer!=null&&(this.viewer.insertionMode=t)}viewerGraphChanged(){this._graph=this.viewer.graph,this.geomGraphEditor.clear(),this._graph!=null&&GeomGraph.getGeom(this._graph)!=null&&this.geomGraphEditor.clear(),this.ActiveDraggedObject=null,this.dragGroup.clear(),this.cleanObstacles()}cleanObstacles(){this.interactiveEdgeRouter=null,this.looseObstaclesToTheirViewerNodes=null,this.SourceOfInsertedEdge=null,this.TargetOfInsertedEdge=null,this.SourcePort=null,this.TargetPort=null,this.viewer.RemoveSourcePortEdgeRouting(),this.viewer.RemoveTargetPortEdgeRouting()}RelayoutOnIsCollapsedChanged(t){this.geomGraphEditor.PrepareForClusterCollapseChange([t]);const e=GeomGraph.getGeom(t.node);e.isCollapsed?this.CollapseCluster(t.node):this.ExpandCluster(e);for(const i of this.geomGraphEditor.entitiesToBeChangedByUndo())this.invalidate(i)}relayout(t){let e=t;for(;e.parent!=null;)e=e.parent;layoutGeomGraph(e),this.MakeExpandedNodesVisible(t.entity)}ExpandCluster(t){t!=null&&this.relayout(t)}MakeExpandedNodesVisible(t){for(const e of t.shallowNodes){const i=je(e);$e.UnhideNodeEdges(e),i.isVisible=!0,e instanceof Graph&&e.getAttr(AttributeRegistry.GeomObjectIndex).isCollapsed==!1&&this.MakeExpandedNodesVisible(e)}}static UnhideNodeEdges(t){for(const e of t.selfEdges){const i=je(e);i.isVisible=!0}for(const e of t.outEdges)je(e.target).isVisible&&(je(e).isVisible=!0);for(const e of t.inEdges)je(e.source).isVisible&&(je(e).isVisible=!0)}CollapseCluster(t){$e.HideCollapsed(t);const e=GeomGraph.getGeom(t),i=e.center;e.boundingBox=Rectangle.mkSizeCenter(e.labelSize,i),this.relayout(e)}static HideCollapsed(t){for(const e of t.shallowNodes)je(e).isVisible=!1,e instanceof Graph&&GeomGraph.getGeom(e).isCollapsed==!1&&$e.HideCollapsed(e)}defaultObjectDecorator(t){if(t.entity instanceof Label){this.decorateEdgeLabelForDragging(t);return}const e=DrawingNode.getDrawingObj(t.entity),i=e.penwidth;t.unmarkedForDraggingCallback||(t.unmarkedForDraggingCallback=()=>DrawingObject.getDrawingObj(t.entity).penwidth=i),e.penwidth=Math.max(this.viewer.LineThicknessForEditing,i*2),this.invalidate(t.entity)}defaultObjectDecoratorRemover(t){const e=t.unmarkedForDraggingCallback;e&&(e(),t.unmarkedForDraggingCallback=null,this.invalidate(t.entity));const i=t.entity;if(i instanceof Node)for(const s of i.edges)this.removeObjDraggingDecorations(je(s))}static TheDefaultEdgeDecoratorStub(t){}defaultEdgeLabelDecorator(t){const e=t.entity.getAttr(AttributeRegistry.GeomObjectIndex);t.markedForDragging&&(GeometryGraphEditor.calculateAttachmentSegment(e),t.unmarkedForDraggingCallback=()=>{this.invalidate(t.entity)}),this.invalidate(t.entity)}static LeftButtonIsPressed(t){return(t.buttons&1)==1}static MiddleButtonIsPressed(t){return(t.buttons&4)==4}static RightButtonIsPressed(t){return(t.buttons&2)==2}MouseDownPointAndMouseUpPointsAreFarEnoughOnScreen(t){if(this.mouseDownScreenPoint==null)return!1;const e=t.clientX,i=t.clientY,s=(this.mouseDownScreenPoint.x-e)/this.viewer.DpiX,n=(this.mouseDownScreenPoint.y-i)/this.viewer.DpiY;return Math.sqrt(s*s+n*n)>this.MouseMoveThreshold/3}analyzeLeftMouseButtonClick(t){this.edgeWithSmoothedPolylineExposed?this.toggleCornerForSelectedEdge():this.viewer.objectUnderMouseCursor&&this.analyzeLeftMouseButtonClickOnObjectUnderCursor(t)}analyzeLeftMouseButtonClickOnObjectUnderCursor(t){const e=this.viewer.objectUnderMouseCursor,i=t.ctrlKey||t.shiftKey,s=e.entity;if(s instanceof Edge){const n=s.getAttr(AttributeRegistry.GeomObjectIndex);n!=null&&this.viewer.layoutEditingEnabled&&(n.smoothedPolyline==null&&(n.smoothedPolyline=$e.CreateUnderlyingPolyline(n)),this.edgeWithSmoothedPolylineExposed!==e&&this.switchToEdgeEditing(e))}else e.markedForDragging?this.unselectForDragging(e):(i||this.unselectEverything(),this.selectObjectForDragging(e)),this.unselectEdge()}toggleCornerForSelectedEdge(){const t=GeometryGraphEditor.findClosestCornerForEdit(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge).smoothedPolyline,this.mouseDownGraphPoint,this.edgeWithSmoothedPolylineExposed.radiusOfPolylineCorner);if(t==null)this.tryInsertCorner();else{if(t.prev==null||t.next==null)return;this.geomGraphEditor.createUndoPoint(),this.geomGraphEditor.registerForUndo(this.edgeWithSmoothedPolylineExposed.edge),this.geomGraphEditor.deleteSite(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge),t),this.invalidate(this.edgeWithSmoothedPolylineExposed.entity)}}tryInsertCorner(){if(!this.closeEnoughToSelectedEdge())this.unselectEdge();else{const t=GeometryGraphEditor.getPreviousCornerSite(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge),this.mouseDownGraphPoint);if(t==null||t.next==null)return;this.geomGraphEditor.insertSite(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge),this.mouseDownGraphPoint,t),this.invalidate(this.edgeWithSmoothedPolylineExposed.edge)}}closeEnoughToSelectedEdge(){const t=GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge).curve,e=t.closestParameter(this.mouseDownGraphPoint);return t.value(e).sub(this.mouseDownGraphPoint).length<this.edgeWithSmoothedPolylineExposed.radiusOfPolylineCorner}static CreateUnderlyingPolyline(t){return SmoothedPolyline.mkFromPoints($e.CurvePoints(t))}static*CurvePoints(t){if(yield t.source.center,t.curve instanceof Curve){const i=t.curve;i.segs.length>0&&(yield i.start);for(let s=0;s<i.segs.length;s++)yield i.segs[s].end}yield t.target.center}ModifierKeyIsPressed(){return(this.viewer.modifierKeys&ModifierKeysEnum.Control)==ModifierKeysEnum.Control||(this.viewer.modifierKeys&ModifierKeysEnum.Shift)==ModifierKeysEnum.Shift}switchToEdgeEditing(t){this.unselectEverything(),this.edgeWithSmoothedPolylineExposed=t,t.radiusOfPolylineCorner=this.viewer.smoothedPolylineCircleRadius,this.DecorateEdgeForDragging(t),this.invalidate(t.entity)}*ViewerNodes(){for(const t of this.viewer.entities)t.entity instanceof Node&&(yield t.entity.getAttr(AttributeRegistry.ViewerIndex))}selectObjectForDragging(t){t.markedForDragging==!1&&(t.markedForDragging=!0,this.dragGroup.add(t),this.decorateObjectForDragging(t))}prepareToRemoveFromDragGroup(t){t.markedForDragging=!1,this.removeObjDraggingDecorations(t)}unselectForDragging(t){this.prepareToRemoveFromDragGroup(t),this.dragGroup.delete(t)}unselectEverything(){for(const t of this.dragGroup)this.prepareToRemoveFromDragGroup(t);this.dragGroup.clear(),this.unselectEdge()}unselectEdge(){this.edgeWithSmoothedPolylineExposed!=null&&(this.edgeWithSmoothedPolylineExposed.selectedForEditing=!1,this.removeEdgeDraggingDecorations(this.edgeWithSmoothedPolylineExposed),this.invalidate(this.edgeWithSmoothedPolylineExposed.edge),this.edgeWithSmoothedPolylineExposed=null)}static*Edges(t){for(const e of t.entity.edges)yield je(e)}viewerMouseDown(t,e){if(!this.viewer.layoutEditingEnabled||this.viewer.graph==null||(this.viewer.setObjectUnderCursorFromEvent(e),this.mouseDownGraphPoint=this.viewer.screenToSource(e),this.mouseDownScreenPoint=new Point(e.clientX,e.clientY),!$e.LeftButtonIsPressed(e)))return!1;if(this.leftMouseButtonWasPressed=!0,this.insertingEdge)return!0;if(this.insertionMode==InsertionMode.Node)return this.insertNode(),!0;if(this.edgeWithSmoothedPolylineExposed!=null)return this.mouseIsInsideOfCornerSite(e)&&e.preventDefault(),!0;const i=this.viewer.objectUnderMouseCursor;return i&&!this.viewer.objectUnderMouseCursor.hasOwnProperty("edge")?(this.ActiveDraggedObject=i,!0):this.ActiveDraggedObject!=null?(e.preventDefault(),!0):!1}insertNode(){const t=this.findNodeID(),e=new Node(t);this._graph.addNode(e),new DrawingNode(e);const i=this.viewer.createIViewerNodeN(e,this.mouseDownGraphPoint);this.viewer.addNode(i,!0)}findNodeID(){let t=0,e="node"+t.toString();for(;this._graph.findNode(e);)e="node"+ ++t;return e}viewerMouseMove(t,e){this.viewer.layoutEditingEnabled&&($e.LeftButtonIsPressed(e)?this.ActiveDraggedObject!=null||this.activeCornerSite!=null?this.drag(e):this.insertingEdge?this.mouseMoveInsertEdgeLeftButtonOn(e):this.MouseMoveLiveSelectObjectsForDragging(e):this.insertingEdge&&this.mouseMoveInsertEdgeNoButtons(e))}setDraggingFlag(t){!this.dragging&&this.MouseDownPointAndMouseUpPointsAreFarEnoughOnScreen(t)&&(this.dragging=!0)}TrySetNodePort(t,e,i,s){if(this.graph==null)return;Assert.assert(this.insertingEdge);const n=this.viewer.screenToSource(t);return s.loosePolyline=null,this.DraggingStraightLine()?e.node=this.setPortWhenDraggingStraightLine(i,n):(this.interactiveEdgeRouter==null&&this.PrepareForEdgeDragging(),s.loosePolyline=this.interactiveEdgeRouter.GetHitLoosePolyline(n),s.loosePolyline!=null?this.SetPortUnderLoosePolyline(n,s.loosePolyline,e,i):(e.node=null,i.port=null)),i.port!=null}setPortWhenDraggingStraightLine(t,e){if(ed(this.viewer.objectUnderMouseCursor)){const i=this.viewer.objectUnderMouseCursor,s={portParameter:0},n=Zr(i);return this.NeedToCreateBoundaryPort(e,i,s)?t.port=this.CreateOrUpdateCurvePort(s.portParameter,n,t.port):$e.PointIsInside(e,n.boundaryCurve)?t.port=this.CreateFloatingPort(n,e):t.port=null,i}return t.port=null,null}CreateOrUpdateCurvePort(t,e,i){if(!(i instanceof CurvePort))return CurvePort.mk(e.boundaryCurve,t);const n=i;return n.parameter=t,n.curve=e.boundaryCurve,i}CreateFloatingPort(t,e){return new FloatingPort(t.boundaryCurve,e)}SetPortUnderLoosePolyline(t,e,i,s){let n=Number.POSITIVE_INFINITY,o=0;for(const a of this.GetViewerNodesInsideOfLooseObstacle(e)){const h=a.entity.getAttr(AttributeRegistry.GeomObjectIndex).boundaryCurve;if($e.PointIsInside(t,h)){i.node=a,this.SetPortForMousePositionInsideOfNode(t,i.node,s);return}const u=h.closestParameter(t),c=h.value(u).sub(t).length;c<n&&(o=u,n=c,i.node=a)}s.port=this.CreateOrUpdateCurvePort(o,Zr(i.node),s.port)}GetViewerNodesInsideOfLooseObstacle(t){return this.looseObstaclesToTheirViewerNodes==null&&this.InitLooseObstaclesToViewerNodeMap(),this.looseObstaclesToTheirViewerNodes.get(t)}InitLooseObstaclesToViewerNodeMap(){this.looseObstaclesToTheirViewerNodes=new Map;for(const t of this.ViewerNodes()){const e=this.interactiveEdgeRouter.GetHitLoosePolyline(Zr(t).center);let i=this.looseObstaclesToTheirViewerNodes.get(e);i==null&&this.looseObstaclesToTheirViewerNodes.set(e,i=new Array),i.push(t)}}SetPortForMousePositionInsideOfNode(t,e,i){const s=Zr(e),n={portParameter:0};this.NeedToCreateBoundaryPort(t,e,n)?i.port=this.CreateOrUpdateCurvePort(n.portParameter,s,i.port):i.port=this.CreateFloatingPort(s,t)}static PointIsInside(t,e){return Curve.PointRelativeToCurveLocation(t,e)==PointLocation.Inside}NeedToCreateBoundaryPort(t,e,i){const s=e.entity.getAttr(AttributeRegistry.DrawingObjectIndex),n=Zr(e).boundaryCurve;i.portParameter=n.closestParameter(t);const o=n.value(i.portParameter);return t.sub(o).length<=this.viewer.smoothedPolylineCircleRadius*2+s.penwidth/2?(this.TryToSnapToTheSegmentEnd(i,n,o),!0):!1}TryToSnapToTheSegmentEnd(t,e,i){if(e instanceof Curve){const s=e.getSegIndexParam(t.portParameter),n=s.par,o=e.segs[s.segIndex];n-o.parStart<o.parEnd-n&&(o.start.sub(i).length<this.viewer.smoothedPolylineCircleRadius*2?t.portParameter-=n-o.parStart:o.end.sub(i).length<this.viewer.smoothedPolylineCircleRadius*2&&(t.portParameter+=+(o.parEnd-n)))}}drag(t){if(!this.dragging)if(this.MouseDownPointAndMouseUpPointsAreFarEnoughOnScreen(t))this.prepareFirstTimeDragging();else return;const e=this.viewer.screenToSource(t);this.handleTheMouseCursorOutOfTheBoundingBox(e),this.geomGraphEditor.drag(e.sub(this._lastDragPoint),this.GetDraggingMode(),this._lastDragPoint);for(const i of this.geomGraphEditor.entitiesToBeChangedByUndo())this.invalidate(i);t.stopPropagation(),this._lastDragPoint=e}prepareFirstTimeDragging(){this.dragging=!0,this.activeCornerSite!=null?this.geomGraphEditor.prepareForGeomEdgeChange(this.edgeWithSmoothedPolylineExposed.edge.getAttr(AttributeRegistry.GeomObjectIndex)):this.ActiveDraggedObject!=null&&(this.unselectEdge(),this.ActiveDraggedObject.markedForDragging||this.unselectEverything(),this.prepareForDragging()),this._lastDragPoint=this.mouseDownGraphPoint}handleTheMouseCursorOutOfTheBoundingBox(t){const e=this.viewer.smoothedPolylineCircleRadius,i=Rectangle.mkSizeCenter(new Size(e,e),t),s=GeomGraph.getGeom(this._graph);s.boundingBox.containsRect(i)||(this.geomGraphEditor.registerForUndo(this._graph),s.boundingBox=s.boundingBox.addRec(i),this.invalidate(this._graph))}prepareForDragging(){this.selectObjectForDragging(this.ActiveDraggedObject),this.geomGraphEditor.prepareForObjectDragging(this.DraggedGeomObjects(),this.GetDraggingMode())}GetDraggingMode(){return(this.viewer.modifierKeys&ModifierKeysEnum.Shift)==ModifierKeysEnum.Shift||this.viewer.IncrementalDraggingModeAlways?DraggingMode.Incremental:DraggingMode.Default}static RouteEdgesRectilinearly(t){const e=t.graph.getAttr(AttributeRegistry.GeomObjectIndex),i=e.layoutSettings;RectilinearInteractiveEditor.CreatePortsAndRouteEdges(i.commonSettings.NodeSeparation/3,1,e.nodesBreadthFirst,e.deepEdges,i.commonSettings.edgeRoutingSettings.EdgeRoutingMode),EdgeLabelPlacement.constructorG(e).run()}*DraggedGeomObjects(){const t=$e.GetActiveObjectCluster(this.ActiveDraggedObject);for(const e of this.dragGroup)$e.GetActiveObjectCluster(e)==t&&(yield GeomObject.getGeom(e.entity))}static GetActiveObjectCluster(t){return t.entity.parent}viewerMouseUp(t,e){e.defaultPrevented||this.viewer.layoutEditingEnabled&&this.handleMouseUpOnLayoutEnabled(e)}handleMouseUpOnLayoutEnabled(t){if(!this.MouseDownPointAndMouseUpPointsAreFarEnoughOnScreen(t)&&this.leftMouseButtonWasPressed)this.viewer.objectUnderMouseCursor!=null||this.edgeWithSmoothedPolylineExposed!=null?(this.analyzeLeftMouseButtonClick(t),t.preventDefault()):this.unselectEverything();else if(this.dragging){this.insertingEdge?this.InsertEdgeOnMouseUp():(this.geomGraphEditor.updateDeltaForDragUndo(this.mouseDownGraphPoint.sub(this._lastDragPoint)),this.interactiveEdgeRouter=null,this.looseObstaclesToTheirViewerNodes=null);const i=GeomGraph.getGeom(this._graph),s=i.getPumpedGraphWithMarginsBox();s.equal(i.boundingBox)||(this.geomGraphEditor.registerForUndo(this._graph),i.boundingBox=s,this.invalidate(this._graph),t.preventDefault())}this.dragging=!1,this.geomGraphEditor.ForgetDragging(),this.activeCornerSite=null,this.ActiveDraggedObject=null,this.leftMouseButtonWasPressed=!1,this.TargetPort!=null&&this.viewer.RemoveTargetPortEdgeRouting(),this.SourcePort!=null&&this.viewer.RemoveSourcePortEdgeRouting(),this.TargetOfInsertedEdge=null,this.SourceOfInsertedEdge=null,this.TargetPort=null,this.SourcePort=null}InsertEdgeOnMouseUp(){if(this.viewer.stopDrawingRubberEdge(),this.TargetPort!=null){const t=this.FinishRoutingEdge();this.addEdgeToTheViewer(t)}this.interactiveEdgeRouter.Clean()}addEdgeToTheViewer(t){const e=this.viewer.createEdgeWithGivenGeometry(t);this.viewer.addEdge(e,!0)}mkArrowhead(){const t=new Arrowhead;return t.length=this.arrowheadLength,t}FinishRoutingEdge(){const t=new Edge(this.sourceOfInsertedEdgeWrap.node.entity,this.targetOfInsertedEdgeWrap.node.entity);t.add();const e=this.EdgeAttr.clone();return e.rebind(t),this.geomEdge.rebind(t),this.geomEdge.sourceArrowhead=e.arrowtail==ArrowTypeEnum.none?null:this.mkArrowhead(),this.geomEdge.targetArrowhead=e.arrowhead==ArrowTypeEnum.none?null:this.mkArrowhead(),this.TargetOfInsertedEdge!=this.SourceOfInsertedEdge?(this.geomEdge.curve instanceof LineSegment||(this.interactiveEdgeRouter.TryToRemoveInflectionsAndCollinearSegments(this.geomEdge.smoothedPolyline),this.interactiveEdgeRouter.SmoothenCorners(this.geomEdge.smoothedPolyline),this.geomEdge.curve=this.geomEdge.smoothedPolyline.createCurve()),Arrowhead.trimSplineAndCalculateArrowheads(this.geomEdge,this.geomEdge.curve,!0)):this.geomEdge=$e.CreateEdgeGeometryForSelfEdge(this.SourceOfInsertedEdge.entity),this.viewer.RemoveSourcePortEdgeRouting(),this.viewer.RemoveTargetPortEdgeRouting(),t}static CreateEdgeGeometryForSelfEdge(t){const e=new Edge(t,t),i=new GeomEdge(e);return StraightLineEdges.CreateSimpleEdgeCurveWithUnderlyingPolyline(i),i}SelectEntitiesForDraggingWithRectangle(t){}mouseIsInsideOfCornerSite(t){const e=this.viewer.screenToSource(t),i=this.edgeWithSmoothedPolylineExposed.edge.getAttr(AttributeRegistry.DrawingObjectIndex).penwidth;return this.activeCornerSite=GeometryGraphEditor.findClosestCornerForEdit(GeomEdge.getGeom(this.edgeWithSmoothedPolylineExposed.edge).smoothedPolyline,e,this.edgeWithSmoothedPolylineExposed.radiusOfPolylineCorner+i),this.activeCornerSite!==null}MouseScreenPointIsCloseEnoughToVertex(t,e){return t.sub(this.mouseDownGraphPoint).length<e}invalidate(t){const e=je(t);if(e){if(e.entity instanceof Label){if(e.markedForDragging){const i=GeomObject.getGeom(e.entity);GeometryGraphEditor.calculateAttachmentSegment(i)}}else e.entity instanceof Edge&&e.entity.label&&this.viewer.invalidate(je(e.entity.label));if(this.viewer.invalidate(e),t instanceof Graph){for(const i of t.nodesBreadthFirst)this.viewer.invalidate(je(i));for(const i of t.deepEdges)this.viewer.invalidate(je(i)),i.label&&this.viewer.invalidate(je(i.label))}}}undo(){if(this.geomGraphEditor.canUndo){const t=new Set(this.geomGraphEditor.entitiesToBeChangedByUndo());this.geomGraphEditor.undo();for(const e of t){const i=je(e);i.markedForDragging?this.dragGroup.add(i):this.dragGroup.delete(i),this.invalidate(e)}}}redo(){if(this.geomGraphEditor.canRedo){const t=new Set(this.geomGraphEditor.entitiesToBeChangedByRedo());this.geomGraphEditor.redo();for(const e of t){const i=je(e);i.markedForDragging?this.dragGroup.add(i):this.dragGroup.delete(i),this.invalidate(e)}}}static RectRouting(t){return t==EdgeRoutingMode.Rectilinear||t==EdgeRoutingMode.RectilinearToCenter}PrepareForEdgeDragging(){if(this.viewer.graph==null||this.DraggingStraightLine())return;const t=GeomGraph.getGeom(this.viewer.graph).layoutSettings;if(!$e.RectRouting(t.commonSettings.edgeRoutingSettings.EdgeRoutingMode)&&this.interactiveEdgeRouter==null){const e=t.commonSettings.NodeSeparation/3,i=.65*e;this.interactiveEdgeRouter=InteractiveEdgeRouter.constructorANNN(Array.from(this._graph.nodesBreadthFirst).map(s=>GeomNode.getGeom(s).boundaryCurve),e,i,0)}}mouseMoveInsertEdgeNoButtons(t){const e=this.SourceOfInsertedEdge;this.TrySetNodePort(t,this.sourceOfInsertedEdgeWrap,this.sourcePortWrap,this.sourceLoosePolylineWrap)?this.viewer.SetSourcePortForEdgeRouting(this.sourcePortWrap.port.Location):e!=null&&this.viewer.RemoveSourcePortEdgeRouting()}mouseMoveInsertEdgeLeftButtonOn(t){if(this.SourcePort!=null){if(this.setDraggingFlag(t),this.dragging){const e={loosePolyline:null};this.TrySetNodePort(t,this.targetOfInsertedEdgeWrap,this.targetPortWrap,e)?(this.viewer.setTargetPortForEdgeRouting(this.targetPortWrap.port.Location),this.drawEdgeInteractivelyToPort(e.loosePolyline,this.DraggingStraightLine())):(this.viewer.RemoveTargetPortEdgeRouting(),this.DrawEdgeInteractivelyToLocation(t,this.DraggingStraightLine()))}t.preventDefault()}}MouseMoveLiveSelectObjectsForDragging(t){this.unselectEverything(),id(t)&&(this.viewer.modifierKeys&ModifierKeysEnum.Shift)!=ModifierKeysEnum.Shift&&this.SelectEntitiesForDraggingWithRectangle(t)}DrawEdgeInteractivelyToLocation(t,e){this.DrawEdgeInteractivelyToLocationP(this.viewer.screenToSource(t),e)}DrawEdgeInteractivelyToLocationP(t,e){this.geomEdge=e?this.getStraightLineEdge(t):this.CalculateEdgeInteractivelyToLocation(t),this.viewer.drawRubberEdge(this.geomEdge)}getStraightLineEdge(t){const e=new GeomEdge(null);return e.curve=LineSegment.mkPP(this.SourcePort.Location,t),e}CalculateEdgeInteractivelyToLocation(t){return this.interactiveEdgeRouter.SourcePort==null&&this.interactiveEdgeRouter.SetSourcePortAndSourceLoosePolyline(this.SourcePort,this.sourceLoosePolylineWrap.loosePolyline),this.interactiveEdgeRouter.RouteEdgeToLocation(t)}drawEdgeInteractivelyToPort(t,e){this.geomEdge=e?this.getStraightLineEdge(this.TargetPort.Location):this.CalculateEdgeInteractively(this.TargetPort,t),this.viewer.drawRubberEdge(this.geomEdge)}DraggingStraightLine(){return this.viewer.graph==null?!0:this.interactiveEdgeRouter!=null&&this.interactiveEdgeRouter.OverlapsDetected}CalculateEdgeInteractively(t,e){this.interactiveEdgeRouter.SourcePort==null&&this.interactiveEdgeRouter.SetSourcePortAndSourceLoosePolyline(this.SourcePort,this.sourceLoosePolylineWrap.loosePolyline);let i,s=null;if(this.SourceOfInsertedEdge==this.TargetOfInsertedEdge)i=LineSegment.mkPP(this.SourcePort.Location,this.TargetPort.Location);else{const o={smoothedPolyline:null};i=this.interactiveEdgeRouter.RouteEdgeToPort(t,e,!1,o),s=o.smoothedPolyline}const n=new GeomEdge(null);return n.curve=i,n.smoothedPolyline=s,n}}function id(l){return(l.buttons&1)==1}var sd=xn(58982);function ar(l){const t=sd(l);if(t.keyword!=null)return E.parse(t.keyword.toString());if(t!=null){if(t.rgba!=null)return new E(t.rgba[3],t.rgba[0],t.rgba[1],t.rgba[2]);if(t.rgb!=null)return E.mkRGB(t.rgb[0],t.rgb[1],t.rgb[2])}return E.Black}function ja(l,t,e){for(const s of e.attr_list)if(s.type==="attr"){const n=s.eq;switch(s.id){case"edgeCurve":{const o=js(l),a=JSON.parse(n);o.curve=nt(a)}break;case"graphBoundingBox":{const o=js(l),a=JSON.parse(n);o.boundingBox=new Z(a)}break;case"boundaryCurve":{const o=js(l),a=JSON.parse(n),h=nt(a);o instanceof Xt?o.boundingBox=h.boundingBox:o.boundaryCurve=h}break;case"geomEdge":{const o=js(l);break}case"sourceArrowhead":{const o=js(l);o.sourceArrowhead==null&&(o.sourceArrowhead=new Mt);break}case"targetArrowhead":{const o=js(l);o.targetArrowhead==null&&(o.targetArrowhead=new Mt);break}case"sourceArrowheadTip":{const o=js(l);o.sourceArrowhead==null&&(o.sourceArrowhead=new Mt),n!=="none"&&(o.sourceArrowhead.tipPosition=d.fromJSON(JSON.parse(n)));break}case"targetArrowheadTip":{const o=js(l);o.targetArrowhead==null&&(o.targetArrowhead=new Mt),n!=="none"&&(o.targetArrowhead.tipPosition=d.fromJSON(JSON.parse(n)));break}case"geomEdgeLabel":{const o=JSON.parse(n),a=l;i(a),new Ks(a.label,new Z(o)).setBoundingBox(new Z(o));break}case"color":t.color=ar(n);break;case"pencolor":t.pencolor=ar(n);break;case"labelfontcolor":t.labelfontcolor=ar(n);break;case"fontcolor":t.fontColor=ar(n);break;case"fillcolor":t.fillColor=ar(n);break;case"style":for(const o of rd(n))t.styles.push(o);break;case"shape":{const o=t;o.shape=od(n);break}case"peripheries":t.peripheries=parseInt(n);break;case"headlabel":t.headlabel=n;break;case"label":if(typeof n=="string"){const o="\\n";let a=0;t.labelText="";do{const h=n.indexOf(o,a);if(h>=0)t.labelText+=n.substring(a,h)+` `,a=h+2;else{t.labelText+=n.substring(a);break}}while(!0)}else typeof n=="number"&&(t.labelText=n.toString());l instanceof rs&&i(l);break;case"size":t.size=Xa(n);break;case"pos":t.pos=Xa(n);break;case"rankdir":t.rankdir=ad(n);break;case"fontname":t.fontname=n;break;case"fontsize":t.fontsize=parseFloat(n);break;case"width":t.width=parseFloat(n);break;case"penwidth":t.penwidth=parseFloat(n);break;case"height":t.height=parseFloat(n);break;case"margin":t.margin=parseFloat(n);break;case"len":t.len=parseFloat(n);break;case"minlen":t.minlen=parseFloat(n);break;case"rank":t.rank=ld(n);break;case"charset":t.charset=n;break;case"orientation":t.orientation=n;break;case"ratio":t.ratio=n;break;case"weight":t.weight=parseFloat(n);break;case"nodesep":t.nodesep=parseFloat(n);break;case"layersep":t.layersep=parseFloat(n);break;case"arrowsize":t.arrowsize=parseFloat(n);break;case"rotate":t.rotate=parseFloat(n);break;case"ranksep":t.ranksep=parseFloat(n);break;case"splines":t.splines=n==="true";break;case"overlap":t.overlap=n==="true";break;case"arrowtail":t.arrowtail=Eh(n);break;case"taillabel":t.taillabel=n;break;case"arrowhead":t.arrowhead=Eh(n);break;case"ordering":t.ordering=hd(n);break;case"URL":t.URL=n;break;case"dir":t.dir=ud(n);break;case"concentrate":t.concentrate=n==="true";break;case"compound":t.compound=n==="true";break;case"lhead":t.lhead=n;break;case"ltail":t.ltail=n;break;case"bgcolor":t.bgcolor=ar(n);break;case"center":t.center=n===!0||parseInt(n)===1;break;case"colorscheme":t.colorscheme=n;break;case"sides":t.sides=parseInt(n);break;case"distortion":t.distortion=parseFloat(n);break;case"skew":t.skew=parseFloat(n);break;case"bb":t.bb=cd(n);break;case"labelloc":t.labelloc=n;break;case"decorate":t.decorate=n==="true";break;case"tailclip":t.tailclip=n==="true";break;case"headclip":t.headclip=n==="true";break;case"constraint":t.constraint=n==="true";break;case"gradientangle":t.gradientangle=parseFloat(n);break;case"samehead":t.samehead=n;break;case"href":t.href=n;break;case"imagepath":t.imagepath=n;break;case"image":t.image=n;break;case"labeljust":t.labejust=n;break;case"layers":t.layers=n.split(",");break;case"layer":t.layer=n;break;case"f":t.f=parseFloat(n);break;case"nojustify":t.nojustify=n==="true";break;case"root":t.root=n==="true";break;case"page":t.page=Xa(n);break;case"pname":t.pname=n;break;case"kind":t.kind=n;break;case"fname":t.fname=n;break;case"subkind":t.subkind=n;break;case"area":t.area=parseFloat(n);break;case"tailport":t.tailport=n;break;case"headport":t.headport=n;break;case"wt":t.wt=n;break;case"id":t instanceof Bi||(t.id=n);break;case"edgetooltip":t.edgetooltip=n;break;case"headtooltip":t.headtooltip=n;break;case"tailtooltip":t.tailtooltip=n;break;case"headURL":t.headURL=n;break;case"tailURL":t.tailURL=n;break;case"labelURL":t.labelURL=n;break;case"edgeurl":t.edgeurl=n;break;case"shapefile":t.shapefile=n;break;case"xlabel":t.xlabel=n;break;case"sametail":t.sametail=n;break;case"clusterrank":t.clusterRank=n;break;case"measuredTextSize":t.measuredTextSize=JSON.parse(n);break;default:break}}else throw new Error("unexpected type "+s.type);function i(s){s.label==null&&(s.label=new rh(s))}}function lr(l,t){const e=Fe.getDrawingObj(t);l.attr_list!=null&&ja(t,e,l)}class Ch{constructor(t){this.nodeMap=new Map,this.ast=t}parseEdge(t,e,i,s,n){let o,a;if(t.type==="node_id"){const u=t.id.toString();o=this.nodeMap.get(u),o==null?o=this.newNode(u,i,!1):this.tryToMoveToADeeperGraph(o,i)}else{const u=[];for(const c of t.children)if(c.type==="node_stmt")for(const m of this.parseEdge(c.node_id,e,i,s,n))u.push(m);else if(c.type!=="attr_stmt")throw new Error("not implemented");for(const c of t.children)if(c.type==="attr_stmt")for(const m of u)lr(c,m);return u}if(e.type==="node_id"){const u=e.id.toString();a=this.nodeMap.get(u),a==null?a=this.newNode(u,i,!1):this.tryToMoveToADeeperGraph(a,i)}else if(e.type==="subgraph"){const u=new Array;for(const c of e.children)if(c.type==="node_stmt")for(const m of this.parseEdge(t,c.node_id,i,s,n))u.push(m);else if(c.type!=="attr_stmt")throw new Error("not implemented");for(const c of e.children)if(c.type==="attr_stmt")for(const m of u)lr(c,m);return u}const h=new rs(o,a);return new Zo(h,s),lr(n,h),[h]}tryToMoveToADeeperGraph(t,e){Ht.assert(t.parent!=null);const i=t.parent;i!=e&&s(i)<s(e)&&(i.remove(t),e.addNode(t));function s(n){let o=0,a=n.parent;for(;a;)o++,a=a.parent;return o}}newNode(t,e,i){let s=this.nodeMap.get(t);if(s==null){s=new mr(t),this.nodeMap.set(t,s),e.addNode(s);const n=new Bi(s);n.labelText=t;const o=Tn.getDrawingObj(e);Fe.copyValidFields(o.defaultNodeObject,n)}else i&&Pr(e,s);return s}parseNode(t,e,i){const s=t.node_id.id.toString(),n=this.newNode(s,e,i);return Fe.getDrawingObj(n)==null&&new Bi(n),lr(t,n),n}parse(){return this.ast==null?null:(this.graph=new Gt(this.ast[0].id?this.ast[0].id.toString():"__graph__"),this.drawingGraph=new Tn(this.graph),this.parseUnderGraph(this.ast[0].children,this.graph,this.ast[0].type==="digraph",!1),gd(this.graph),fd(this.graph),this.graph)}parseGraphAttr(t,e){if(t.target==="node"){const i=Tn.getDrawingObj(e);i.defaultNodeObject==null&&(i.defaultNodeObject=new Bi(null)),ja(null,i.defaultNodeObject,t)}else t.target==="graph"&&lr(t,e)}getEntitiesSubg(t,e,i){let s=[];for(const n of t.children)if(n.type==="edge_stmt")for(let o=0;o<n.edge_list.length-1;o++)for(const a of this.parseEdge(n.edge_list[o],n.edge_list[o+1],e,i,n))s.push(a);else if(n.type!=="attr_stmt")if(n.type==="node_stmt")s.push(this.parseNode(n,e,!0));else if(n.type==="subgraph")if(n.id!=null){const o=new Gt(n.id.toString());e.addNode(o),this.nodeMap.set(o.id,o);const a=new Tn(o);this.parseUnderGraph(n.children,o,i,!0),s.push(a.graph),o.isEmpty&&(e.removeNode(o),this.nodeMap.delete(o.id))}else s=s.concat(this.getEntitiesSubg(n,e,i));else throw new Error("Function not implemented.");return s}parseUnderGraph(t,e,i,s){for(const n of t)switch(n.type){case"node_stmt":this.parseNode(n,e,s);break;case"edge_stmt":{const o=n.edge_list;for(let a=0;a<o.length-1;a++)this.parseEdge(o[a],o[a+1],e,i,n)}break;case"subgraph":if(!this.process_same_rank(n,Tn.getDrawingGraph(e)))if(n.id==null){const o=this.getEntitiesSubg(n,e,i);dd(n,Tn.getDrawingGraph(e),o)}else{const o=new Gt(n.id.toString());this.nodeMap.set(n.id.toString(),o),e.addNode(o),new Tn(o),this.parseUnderGraph(n.children,o,i,!0),o.isEmpty()&&(e.remove(o),this.nodeMap.delete(o.id))}break;case"attr_stmt":this.parseGraphAttr(n,e);break;default:throw new Error("not implemented")}}process_same_rank(t,e){const i=t.children[0];if(i==null||i.type!=="attr_stmt")return!1;const s=i.attr_list;if(s==null||s.length===0)return!1;const n=s[0];if(n.type!=="attr"||n.id!=="rank")return!1;switch(n.eq){case"min":for(let o=1;o<t.children.length;o++){const a=t.children[o];if(a.type==="node_stmt")e.graphVisData.minRanks.push(a.node_id.id.toString());else throw new Error}return!0;case"max":for(let o=1;o<t.children.length;o++){const a=t.children[o];if(a.type==="node_stmt")e.graphVisData.minRanks.push(a.node_id.id.toString());else throw new Error}return!0;case"same":{const o=[];for(let a=1;a<t.children.length;a++){const h=t.children[a];h.type==="node_stmt"?(this.newNode(h.node_id.id.toString(),e.graph,!1),o.push(h.node_id.id.toString())):h.type==="attr_stmt"&&h.target==="node"&&(e.defaultNodeObject==null&&(e.defaultNodeObject=new Bi(null)),ja(null,e.defaultNodeObject,h))}return e.graphVisData.sameRanks.push(o),!0}case"source":{for(let o=1;o<t.children.length;o++){const a=t.children[o];if(a.type==="node_stmt")e.graphVisData.sourceRanks.push(a.node_id.id.toString());else throw new Error}return!0}case"sink":for(let o=1;o<t.children.length;o++){const a=t.children[o];if(a.type==="node_stmt")e.graphVisData.sinkRanks.push(a.node_id.id.toString());else throw new Error}return!0;default:throw new Error("incorrect rank")}}}function $a(l){try{return new Ch(td(l)).parse()}catch{return console.log("cannot parse the graph"),null}}function nd(l){try{return new Ch([l]).parse()}catch(t){return console.log(t.message),null}}function*rd(l){const t=l.split(",");for(const e of t){const s=Va[e];s&&(yield s)}}function od(l){const t=l.toLowerCase();return ne[t]}function Xa(l){const t=l.split(",");return[parseFloat(t[0]),parseFloat(t[1])]}function ad(l){return xi[l]}function ld(l){return Ma[l]}function Eh(l){return Us[l]}function hd(l){return Ha[l]}function ud(l){return Wa[l]}function cd(l){const t=l.split(",");return[parseFloat(t[0]),parseFloat(t[1]),parseFloat(t[2]),parseFloat(t[3])]}function dd(l,t,e){for(const i of l.children)if(i.type==="attr_stmt")for(const s of e)lr(i,s)}function gd(l){const t=[];for(const e of l.subgraphsBreadthFirst())e.isEmpty()&&t.push(e);for(const e of t){const i=e.parent;i&&i.removeNode(e)}}function fd(l){for(const t of l.subgraphsBreadthFirst())Xt.getGeom(t)==null&&t.hasSomeAttrOnIndex(Et.GeomObjectIndex)&&new Xt(t);Xt.getGeom(l)==null&&l.hasSomeAttrOnIndex(Et.GeomObjectIndex)&&new Xt(l)}function rg(l){const t=Ad(l);return{type:Ed(l),id:l.id,children:md(l,t)}}function pd(l){return{type:"edge_stmt",edge_list:[{type:"node_id",id:l.source.id},{type:"node_id",id:l.target.id}],attr_list:Array.from(Pd(l))}}function md(l,t){const e=new Map,i=[],s=GeomGraph.getGeom(l);if(s){const n=Array.from(Ah(s));i.push({type:"attr_stmt",target:"graph",attr_list:n})}vd(i,l);for(const n of l.nodesBreadthFirst)e.set(n.id,Sd(n));for(const n of l.nodesBreadthFirst){if(n.parent===l)continue;e.get(n.parent.id).children.push(e.get(n.id))}for(const n of l.deepEdges){const o=pd(n),a=bd(n,t);a===l?i.push(o):e.get(a.id).children.push(o)}for(const n of l.shallowNodes)i.push(e.get(n.id));return i}function*Pd(l){const t=GeomObject.getGeom(l);if(t&&(yield{type:"attr",id:"geomEdge",eq:"none"},t.curve&&(yield{type:"attr",id:"edgeCurve",eq:JSON.stringify(iCurveToJSON(t.curve))}),t.sourceArrowhead&&(yield{type:"attr",id:"sourceArrowhead",eq:"none"},t.sourceArrowhead.tipPosition&&(yield{type:"attr",id:"sourceArrowheadTip",eq:JSON.stringify(t.sourceArrowhead.tipPosition.toJSON())})),t.targetArrowhead&&(yield{type:"attr",id:"targetArrowhead",eq:"none"},t.targetArrowhead.tipPosition&&(yield{type:"attr",id:"targetArrowheadTip",eq:JSON.stringify(t.targetArrowhead.tipPosition.toJSON())})),l.label)){const e=l.label.getAttr(AttributeRegistry.GeomObjectIndex).boundingBox,i={left:e.left,right:e.right,top:e.top,bottom:e.bottom};yield{type:"attr",id:"geomEdgeLabel",eq:JSON.stringify(i)}}yield*Qa(DrawingObject.getDrawingObj(l))}function Sd(l){if(l instanceof Graph){const e=Array.from(Ah(GeomGraph.getGeom(l))),i=[],s={type:"attr_stmt",target:"graph",attr_list:e};return i.push(s),{type:"subgraph",children:i,id:l.id}}else return{type:"node_stmt",node_id:{type:"node_id",id:l.id},attr_list:Array.from(Cd(l))}}function yd(l){const t=GeomNode.getGeom(l).boundaryCurve;return{type:"attr",id:"boundaryCurve",eq:JSON.stringify(iCurveToJSON(t))}}function*Cd(l){GeomObject.getGeom(l)&&(yield yd(l)),yield*Qa(DrawingObject.getDrawingObj(l))}function*Qa(l){l.color&&l.color.keyword.toLowerCase()!=="black"&&(yield{type:"attr",id:"color",eq:l.color.toString()}),l.fillColor&&(yield{type:"attr",id:"fillColor",eq:l.fillColor.toString()}),l.labelfontcolor&&l.labelfontcolor.keyword.toLowerCase()!=="black"&&(yield{type:"attr",id:"labelfontcolor",eq:l.labelfontcolor.toString()}),!(l.labelText==null||l.labelText==="")&&l.entity&&l.labelText!==l.id&&(yield{type:"attr",id:"label",eq:l.labelText}),l.fontColor&&l.fontColor.keyword.toLowerCase()!=="black"&&(yield{type:"attr",id:"fontColor",eq:l.fontColor.toString()}),l.styles&&l.styles.length&&(yield{type:"attr",id:"style",eq:l.styles.map(e=>StyleEnum[e]).reduce((e,i)=>e.concat(","+i))}),l.pencolor&&l.pencolor.keyword!=="black"&&(yield{type:"attr",id:"pencolor",eq:l.pencolor.toString()}),l.penwidth&&l.penwidth!==1&&(yield{type:"attr",id:"penwidth",eq:l.penwidth.toString()}),l.rankdir&&(yield{type:"attr",id:"rankdir",eq:l.rankdir.toString()}),l.fontname&&l.fontname!==DrawingObject.defaultLabelFontName&&(yield{type:"attr",id:"fontname",eq:l.fontname}),l.margin&&(yield{type:"attr",id:"margin",eq:l.margin.toString()}),l.fontsize&&l.fontsize!==DrawingObject.defaultLabelFontSize&&(yield{type:"attr",id:"fontsize",eq:l.fontsize.toString()}),l.orientation&&(yield{type:"attr",id:"orientation",eq:l.orientation.toString()}),l.ranksep&&(yield{type:"attr",id:"ranksep",eq:l.ranksep.toString()}),l.arrowtail&&(yield{type:"attr",id:"arrowtail",eq:ArrowTypeEnum[l.arrowtail]}),l.arrowhead&&(yield{type:"attr",id:"arrowhead",eq:ArrowTypeEnum[l.arrowhead]}),l.ordering&&(yield{type:"attr",id:"ordering",eq:l.ordering.toString()}),l.bgcolor&&(yield{type:"attr",id:"bgcolor",eq:l.bgcolor.toString()}),l.pos&&(yield{type:"attr",id:"pos",eq:l.pos.toString()}),l.nodesep&&(yield{type:"attr",id:"nodesep",eq:l.nodesep.toString()}),l.arrowsize&&(yield{type:"attr",id:"arrowsize",eq:l.arrowsize.toString()}),l.samehead&&(yield{type:"attr",id:"samehead",eq:l.samehead.toString()}),l.layersep&&(yield{type:"attr",id:"layersep",eq:l.layersep.toString()}),l.clusterRank&&(yield{type:"attr",id:"clusterrank",eq:l.clusterRank.toString()}),l.measuredTextSize&&(yield{type:"attr",id:"measuredTextSize",eq:JSON.stringify(l.measuredTextSize)}),l instanceof DrawingNode&&(l.shape&&l.shape!==ShapeEnum.box&&(yield{type:"attr",id:"shape",eq:l.shape.toString()}),l.xRad&&l.xRad!==3&&(yield{type:"attr",id:"xRad",eq:l.xRad.toString()}),l.yRad&&l.yRad!==3&&(yield{type:"attr",id:"yRad",eq:l.yRad.toString()}),l.padding&&l.padding!==2&&(yield{type:"attr",id:"padding",eq:l.padding.toString()}))}function Ed(l){return DrawingGraph.getDrawingGraph(l).hasDirectedEdge()?"digraph":"graph"}function bd(l,t){let e=l.source,i=l.target,s=t.get(e.id),n=t.get(i.id);for(;s>n;)e=e.parent,s--;for(;s<n;)i=i.parent,n--;for(;e.parent!==i.parent;)e=e.parent,i=i.parent;return e.parent}function Ad(l){const t=new Map;return t.set(l.id,0),bh(l,t),t}function bh(l,t){const e=t.get(l.id)+1;for(const i of l.shallowNodes)t.set(i.id,e),i instanceof Graph&&bh(i,t)}function js(l){var t;return(t=gt.getGeom(l))!==null&&t!==void 0?t:wd(l)}function wd(l){if(l instanceof Gt)return new Xt(l);if(l instanceof mr)return new Pe(l);if(l instanceof rs)return new Ne(l);throw new Error("unsupported type "+l)}function vd(l,t){const e=DrawingGraph.getDrawingObj(t);if(e==null)return;const i=e.defaultNodeObject;i&&l.push({type:"attr_stmt",target:"node",attr_list:Array.from(Qa(i))})}function*Ah(l){if(l==null)return;const t=l.boundingBox;if(t&&t.isEmpty()===!1){const e={left:t.left,right:t.right,top:t.top,bottom:t.bottom};yield{type:"attr",id:"graphBoundingBox",eq:JSON.stringify(e)}}l.radX!==10&&(yield{type:"attr",id:"radX",eq:l.radX.toString()}),l.radY!==10&&(yield{type:"attr",id:"radY",eq:l.radY.toString()})}function wh(l){const t=new Graph;try{const e=l.split(/\r\n|\r|\n/);for(const i of e){if(i.length==0||i.charAt(0)=="#")continue;const s=i.split(/\t| |,/);if(s.length<2)return console.log("cannot parse",i),null;const n=s[0],o=s[1],a=vh(t,n),h=vh(t,o),u=new Edge(a,h);new DrawingEdge(u,!0)}}catch(e){console.log(e.message)}return new DrawingGraph(t),t}function vh(l,t){let e=l.findNode(t);return e==null&&(e=l.addNode(new Node(t)),new DrawingNode(e)),e}async function og(l){const t=await l.text();let e;return l.name.toLowerCase().endsWith(".json")?e=Ih(JSON.parse(t)):l.name.toLowerCase().endsWith(".txt")||l.name.toLowerCase().endsWith(".tsv")||l.name.toLowerCase().endsWith(".csv")?e=wh(t):e=$a(t),e&&(e.id=l.name),e}async function ag(l){const t=l.slice(l.lastIndexOf("/")+1),e=await fetch(l);let i;if(t.endsWith(".json")){const s=await e.json();i=Ih(s)}else if(t.endsWith(".txt")){const s=await e.text();i=wh(s)}else{const s=await e.text();i=$a(s)}return i&&(i.id=t),i}function Ih(l){return"nodes"in l?Id(l):nd(l)}function Id(l){const t=new Graph;for(const e of l.nodes){const i=String(e.id),s=t.addNode(new Node(i)),n=new DrawingNode(s),{label:o=i,shape:a="box"}=e;n.labelText=o,n.ShapeEnum=ShapeEnum[a],"weight"in e&&(n.weight=e.weight),"color"in e&&(n.color=parseColor(e.color))}for(const e of l.edges){const i=t.setEdge(String(e.source),String(e.target)),s=new DrawingEdge(i,!1),{arrowhead:n="none",arrowtail:o="none",directed:a=!0}=e;s.arrowhead=ArrowTypeEnum[n],s.arrowtail=ArrowTypeEnum[o],s.directed=a,"weight"in e&&(s.weight=e.weight),"color"in e&&(s.color=parseColor(e.color))}return new DrawingGraph(t),t}addEventListener("message",async l=>{const{nodes:t,edges:e,config:i}=l.data,[s,n]=Td(t,e,i);postMessage({nodes:s,edges:n})});function Td(l,t){const{mappedEdges:e,DOTToIdMap:i}=xd(l,t),s=Ld(e),n=$a(s),o=new Xt(n);for(const A of n.deepEdges)new Ne(A);for(const A of n.nodesBreadthFirst){const I=new Pe(A);I.boundaryCurve=H.mkCircle(50,new d(0,0))}o.layoutSettings=new Sn,o.layoutSettings.layerDirection=xi.LR,o.layoutSettings.LayerSeparation=60,o.layoutSettings.commonSettings.NodeSeparation=40,Ju(o);const a={};for(const A of o.nodesBreadthFirst)a[i[A.id]]={obj:A};for(const A of l)a[A.id]={...a[A.id],datum:{...A,x:a[A.id].obj.center.x,y:a[A.id].obj.center.y}};const h=t.map(A=>({...A,source:a[A.source].datum,target:a[A.target].datum})),u=[];for(const A of h){const I=u.find(q=>q.nodes.has(A.source)),B=u.find(q=>q.nodes.has(A.target));I&&B?I!==B&&(B.nodes.forEach(I.nodes.add,I.nodes),u.splice(u.indexOf(B),1),I.top=Math.min(I.top,B.top),I.bottom=Math.max(I.bottom,B.bottom),I.left=Math.min(I.left,B.left),I.right=Math.max(I.right,B.right)):I?(I.nodes.add(A.target),I.top=Math.min(I.top,A.target.y),I.bottom=Math.max(I.bottom,A.target.y),I.left=Math.min(I.left,A.target.x),I.right=Math.max(I.right,A.target.x)):B?(B.nodes.add(A.source),B.top=Math.min(B.top,A.source.y),B.bottom=Math.max(B.bottom,A.source.y),B.left=Math.min(B.left,A.source.x),B.right=Math.max(B.right,A.source.x)):u.push({top:Math.min(A.source.y,A.target.y),bottom:Math.max(A.source.y,A.target.y),left:Math.min(A.source.x,A.target.x),right:Math.max(A.source.x,A.target.x),nodes:new Set([A.source,A.target])})}let c=0,m=0;for(const A of u)if(c===0)c=A.bottom+200,m=A.left;else{const I=c-A.top,B=m-A.left;for(const q of A.nodes)q.x+=B,q.y+=I;c+=A.bottom-A.top+200}const S=Object.values(a).map(A=>A.datum);return Fd(S),[S,h]}function xd(l,t){const e=[],i={},s={};let n=0;for(const o of t)i[o.source]||(i[o.source]=n.toString(10),s[n.toString(10)]=o.source,n++),i[o.target]||(i[o.target]=n.toString(10),s[n.toString(10)]=o.target,n++),e.push({source:i[o.source],target:i[o.target]});return{mappedEdges:e,DOTToIdMap:s}}function Od(l,t="",e=""){let i=` digraph G { ${t} `;for(const s of l)i+=s.source+"->"+s.target+" "+e+` `;return i+=Bd(l),i+="}",i}function Ld(l){return Od(l,'rankdir="LR"; TBbalance="min"',"[ minlen=3 ]")}function Bd(l){let t="";const e=new Set,i=`[fixedsize=true, width=1.2, height=1.7] `;for(const s of l)e.has(s.source)||(t+=s.source+i),e.has(s.target)||(t+=s.target+i);return t}function Fd(l){const t=Rd(l);for(let e of l)e.x=e.x-t.center.x,e.y=e.y-t.center.y}function Rd(l){if(l.length===0)return{top:0,right:0,bottom:0,left:0,center:{x:0,y:0}};const t=l.reduce((s,n)=>(n.x>s.right&&(s.right=n.x),n.x<s.left&&(s.left=n.x),n.y>s.bottom&&(s.bottom=n.y),n.y<s.top&&(s.top=n.y),s),{top:1/0,right:-1/0,bottom:-1/0,left:1/0}),e=t.top+(t.bottom-t.top)/2,i=t.left+(t.right-t.left)/2;return{...t,center:{x:i,y:e}}}})()})(); //# sourceMappingURL=6378.27b1e6d863a0a3b85962.js.map
Submit
FILE
FOLDER
INFO
Name
Size
Permission
Action
static
---
0755
0.c88fc16b6533c8976681.js
11857 bytes
0644
0.c88fc16b6533c8976681.js.map
46011 bytes
0644
1118.6d1cbbd2070e00a7483d.js
9459 bytes
0644
1118.6d1cbbd2070e00a7483d.js.map
22012 bytes
0644
1121.6c31bf81768d3312b0d4.js
11557 bytes
0644
1121.6c31bf81768d3312b0d4.js.map
40274 bytes
0644
1122.1b3b5a9bdf4a2fc70a83.js
4310 bytes
0644
1122.1b3b5a9bdf4a2fc70a83.js.map
9301 bytes
0644
1133.cd705902767ed2e9bf55.js
107191 bytes
0644
1133.cd705902767ed2e9bf55.js.map
459177 bytes
0644
1216.ddb58ad09e0c4e3f4079.js
12860 bytes
0644
1216.ddb58ad09e0c4e3f4079.js.map
47906 bytes
0644
1282.2347f27d5b3a18a42a1e.js
2965 bytes
0644
1282.2347f27d5b3a18a42a1e.js.map
6699 bytes
0644
1345.8570fef914aafab94513.js
2223 bytes
0644
1345.8570fef914aafab94513.js.map
5201 bytes
0644
1347.8ad23b870a6e21306189.js
32035 bytes
0644
1347.8ad23b870a6e21306189.js.map
89851 bytes
0644
1420.f2553cafc235b7c32261.js
14576 bytes
0644
1420.f2553cafc235b7c32261.js.map
32839 bytes
0644
1438.897db349b7f48a15b9eb.js
2830 bytes
0644
1438.897db349b7f48a15b9eb.js.map
6911 bytes
0644
1446.babd36e7134aac1046c4.js
1832 bytes
0644
1446.babd36e7134aac1046c4.js.map
3282 bytes
0644
1488.ff35935a06f41b02b6cc.js
316 bytes
0644
1488.ff35935a06f41b02b6cc.js.map
1206 bytes
0644
1560.30962127c91e5eae9982.js
8916 bytes
0644
1560.30962127c91e5eae9982.js.map
20515 bytes
0644
1660.e1f66118fb028d12074f.js
21866 bytes
0644
1660.e1f66118fb028d12074f.js.map
71039 bytes
0644
1698.68ff1ef08e94a87836b3.js
12570 bytes
0644
1698.68ff1ef08e94a87836b3.js.map
46006 bytes
0644
1708.f42a783c0f6c7a317d49.js
2249 bytes
0644
1708.f42a783c0f6c7a317d49.js.map
2954 bytes
0644
1710.d96221051fceaf8c89dd.js
10172 bytes
0644
1710.d96221051fceaf8c89dd.js.map
22097 bytes
0644
1740.e57d920c47a11759ade4.js
6204 bytes
0644
1740.e57d920c47a11759ade4.js.map
13740 bytes
0644
1888.0ede69d3190c536744b9.js
6822 bytes
0644
1888.0ede69d3190c536744b9.js.map
15421 bytes
0644
1914.58113477b565d57e8bfe.js
10710 bytes
0644
1914.58113477b565d57e8bfe.js.map
23555 bytes
0644
198.b84c0e4f5759344ae05a.js
8267 bytes
0644
198.b84c0e4f5759344ae05a.js.map
19446 bytes
0644
205.6c51b5e35c8147226738.js
3542 bytes
0644
205.6c51b5e35c8147226738.js.map
8376 bytes
0644
2058.0e5df44647184aaf02e2.js
1252 bytes
0644
2058.0e5df44647184aaf02e2.js.map
4744 bytes
0644
2077.12b2df3682085a92a810.js
34133 bytes
0644
2077.12b2df3682085a92a810.js.map
122011 bytes
0644
2094.259625d8acf28b9c7361.js
16518 bytes
0644
2094.259625d8acf28b9c7361.js.map
41269 bytes
0644
21.afca69f2d336e287a655.js
6172 bytes
0644
21.afca69f2d336e287a655.js.map
17305 bytes
0644
2136.9c8dcd43d3af327f51f5.js
498667 bytes
0644
2136.9c8dcd43d3af327f51f5.js.map
1908011 bytes
0644
2228.cf629cf4a83c5b6c2671.js
269 bytes
0644
2228.cf629cf4a83c5b6c2671.js.map
457 bytes
0644
2244.9324c28eca7d2ffb7568.js
3396 bytes
0644
2244.9324c28eca7d2ffb7568.js.map
7683 bytes
0644
2261.ac6a26854d5acee00776.js
106373 bytes
0644
2261.ac6a26854d5acee00776.js.map
478562 bytes
0644
2278.bdd73b14b6337c6b14e4.js
5754 bytes
0644
2278.bdd73b14b6337c6b14e4.js.map
13399 bytes
0644
2398.3de0e7aa3057b7dcf9da.js
8016 bytes
0644
2398.3de0e7aa3057b7dcf9da.js.map
18383 bytes
0644
2514.c86950e9813e27962050.js
1983 bytes
0644
2514.c86950e9813e27962050.js.map
4863 bytes
0644
2571.345ecfd2b82551018f2e.js
162139 bytes
0644
2571.345ecfd2b82551018f2e.js.map
2046 bytes
0644
2586.972e9a7d564398afee76.js
6385 bytes
0644
2586.972e9a7d564398afee76.js.map
14676 bytes
0644
2658.f4100815829c4d37d35c.js
5432 bytes
0644
2658.f4100815829c4d37d35c.js.map
13650 bytes
0644
2686.2fbaa7db9c01d59cad8d.js
2815 bytes
0644
2686.2fbaa7db9c01d59cad8d.js.map
6564 bytes
0644
2692.20098ad0182743d98d62.js
2282 bytes
0644
2692.20098ad0182743d98d62.js.map
5680 bytes
0644
2694.a31d749361a36eb167da.js
2726 bytes
0644
2694.a31d749361a36eb167da.js.map
3618 bytes
0644
2745.2e5ec1fdf377d2940fb4.js
33584 bytes
0644
2745.2e5ec1fdf377d2940fb4.js.map
120277 bytes
0644
2962.4c3147d8ee365fe296ef.js
7640 bytes
0644
2962.4c3147d8ee365fe296ef.js.map
17621 bytes
0644
3042.248a4194805a8500fd28.js
19010 bytes
0644
3042.248a4194805a8500fd28.js.map
38148 bytes
0644
3062.4e9a427c2a59d53f902e.js
4663 bytes
0644
3062.4e9a427c2a59d53f902e.js.map
10650 bytes
0644
3082.c09cff56c35d736ee8b6.js
52872 bytes
0644
3082.c09cff56c35d736ee8b6.js.map
56822 bytes
0644
3096.8d41728a4f5010bc56a2.js
4378 bytes
0644
3096.8d41728a4f5010bc56a2.js.map
10739 bytes
0644
3098.f22ad6dab13d06477be0.js
31462 bytes
0644
3098.f22ad6dab13d06477be0.js.map
85588 bytes
0644
3182.1d531f28507c00e391fc.js
13817 bytes
0644
3182.1d531f28507c00e391fc.js.map
26653 bytes
0644
3407.666eb88a718e66b93f72.js
34425 bytes
0644
3407.666eb88a718e66b93f72.js.map
103716 bytes
0644
3418.d31d882b87bd5a2ef66f.js
33061 bytes
0644
3418.d31d882b87bd5a2ef66f.js.map
114234 bytes
0644
3541.8d063e3d43d55745d89b.js
20582 bytes
0644
3541.8d063e3d43d55745d89b.js.map
67154 bytes
0644
3543.eecef49ce94da5ee0418.js
136752 bytes
0644
3543.eecef49ce94da5ee0418.js.map
446118 bytes
0644
3622.976b1aef94b333e450b9.js
1260 bytes
0644
3622.976b1aef94b333e450b9.js.map
2819 bytes
0644
3686.102abfc00452299017bb.js
87 bytes
0644
3718.3993946b7a0eb8f64b4d.js
23620 bytes
0644
3718.3993946b7a0eb8f64b4d.js.map
92024 bytes
0644
3726.3adfe210678d2cd26969.js
31765 bytes
0644
3726.3adfe210678d2cd26969.js.map
118227 bytes
0644
398.4e93ffb675609ea7a9c6.js
2990 bytes
0644
398.4e93ffb675609ea7a9c6.js.map
7145 bytes
0644
4114.953b39a9ce57caa0e87a.js
2536 bytes
0644
4114.953b39a9ce57caa0e87a.js.map
6028 bytes
0644
4120.67bf5d203ed4a2eb5f1b.js
3229 bytes
0644
4120.67bf5d203ed4a2eb5f1b.js.map
7533 bytes
0644
4209.c7060d489834063658f5.js
17352 bytes
0644
4209.c7060d489834063658f5.js.map
30980 bytes
0644
4254.c5f4a5512b252e3a5796.js
71716 bytes
0644
4254.c5f4a5512b252e3a5796.js.map
237783 bytes
0644
4289.d5662b0904798ff437e9.js
16496 bytes
0644
4289.d5662b0904798ff437e9.js.map
32015 bytes
0644
4334.bc078c368a20ed3257b6.js
2598 bytes
0644
4334.bc078c368a20ed3257b6.js.map
6308 bytes
0644
4630.b604ea691184ba563d59.js
5585 bytes
0644
4630.b604ea691184ba563d59.js.map
11866 bytes
0644
4680.358dfdd92851f69ecc97.js
4573 bytes
0644
4680.358dfdd92851f69ecc97.js.map
10841 bytes
0644
4698.696713071ff5d9929a11.js
3682 bytes
0644
4698.696713071ff5d9929a11.js.map
8967 bytes
0644
4787.bd938ea7cb58d64ee246.js
738 bytes
0644
4787.bd938ea7cb58d64ee246.js.map
2168 bytes
0644
4839.17a10e0ceca3eb8954b4.js
39585 bytes
0644
4839.17a10e0ceca3eb8954b4.js.map
145699 bytes
0644
494.8cf705bc1ea509187c88.js
3796 bytes
0644
494.8cf705bc1ea509187c88.js.map
8987 bytes
0644
4958.cd447d877778fc5af081.js
4923 bytes
0644
4958.cd447d877778fc5af081.js.map
11000 bytes
0644
4962.0da526ad79f816a15985.js
2242 bytes
0644
4962.0da526ad79f816a15985.js.map
4978 bytes
0644
50.7b1e44d5b9dbbed566be.js
617497 bytes
0644
50.7b1e44d5b9dbbed566be.js.map
2271464 bytes
0644
5017.003cacead1bba1cba035.js
3567142 bytes
0644
5017.003cacead1bba1cba035.js.map
13214665 bytes
0644
5130.4d31108de97088a3b014.js
2850 bytes
0644
5130.4d31108de97088a3b014.js.map
6536 bytes
0644
5196.064b914693b6a5591a48.js
4035 bytes
0644
5196.064b914693b6a5591a48.js.map
10273 bytes
0644
5240.eceb5f73f807ac22d800.js
704 bytes
0644
5240.eceb5f73f807ac22d800.js.map
2618 bytes
0644
5277.ce6608b6f47246e32767.js
269 bytes
0644
5277.ce6608b6f47246e32767.js.map
457 bytes
0644
5280.4348c762594edebf7d0e.js
16657 bytes
0644
5280.4348c762594edebf7d0e.js.map
89146 bytes
0644
5356.eabc0dc2021a3814a65f.js
10156 bytes
0644
5356.eabc0dc2021a3814a65f.js.map
25249 bytes
0644
5358.7c5e9e1b192582f3082d.js
6173 bytes
0644
5358.7c5e9e1b192582f3082d.js.map
19652 bytes
0644
5364.ac21c32fd45a27bc998a.js
3070 bytes
0644
5364.ac21c32fd45a27bc998a.js.map
7368 bytes
0644
5398.d0c11aa7c1232f4afe44.js
81872 bytes
0644
5398.d0c11aa7c1232f4afe44.js.map
769414 bytes
0644
5428.e85b0800b30feca9d7dc.js
330175 bytes
0644
5428.e85b0800b30feca9d7dc.js.map
530929 bytes
0644
5511.93023985e5c5efe49ae2.js
21275 bytes
0644
5511.93023985e5c5efe49ae2.js.map
93188 bytes
0644
5550.9284e42acc3f2bbdfc9d.js
7039 bytes
0644
5550.9284e42acc3f2bbdfc9d.js.map
16382 bytes
0644
558.701e8b4db7b852c4a10d.js
12211 bytes
0644
558.701e8b4db7b852c4a10d.js.map
24505 bytes
0644
5618.638c32d58d896f3f7261.js
3348 bytes
0644
5618.638c32d58d896f3f7261.js.map
8181 bytes
0644
5648.cb3fd92dbbc06f7d45d2.js
57392 bytes
0644
5648.cb3fd92dbbc06f7d45d2.js.map
60585 bytes
0644
5786.db7abc3b8e4f474a8f7b.js
5325 bytes
0644
5786.db7abc3b8e4f474a8f7b.js.map
11885 bytes
0644
5807.f05d997ece5811bbc849.js
2922915 bytes
0644
5807.f05d997ece5811bbc849.js.map
10524334 bytes
0644
5950.30ec6aaa9dcece6c3b3c.js
4616249 bytes
0644
5950.30ec6aaa9dcece6c3b3c.js.map
19277501 bytes
0644
6018.f4de7ac19ac8f0c774e6.js
5861 bytes
0644
6018.f4de7ac19ac8f0c774e6.js.map
13314 bytes
0644
6029.0549a3fcb50e73c4b256.js
409895 bytes
0644
6029.0549a3fcb50e73c4b256.js.map
998408 bytes
0644
6185.883629fcc773b4968b24.js
2258 bytes
0644
6185.883629fcc773b4968b24.js.map
4788 bytes
0644
6263.e4ef9aaa3073ebacc3a5.js
54594 bytes
0644
6263.e4ef9aaa3073ebacc3a5.js.map
242030 bytes
0644
6302.257b2eb06c25ee74090e.js
8440 bytes
0644
6302.257b2eb06c25ee74090e.js.map
19322 bytes
0644
6359.f824c85233ec703f8cea.js
11411 bytes
0644
6359.f824c85233ec703f8cea.js.map
41881 bytes
0644
6377.45d36c143a694fc45bd3.js
20571 bytes
0644
6377.45d36c143a694fc45bd3.js.map
79590 bytes
0644
6378.27b1e6d863a0a3b85962.js
977993 bytes
0644
6378.27b1e6d863a0a3b85962.js.map
3865587 bytes
0644
6414.192cf271de6ecbbbcb11.js
3984 bytes
0644
6414.192cf271de6ecbbbcb11.js.map
9134 bytes
0644
6446.b4b93ee91aa1bb57ea93.js
7731 bytes
0644
6446.b4b93ee91aa1bb57ea93.js.map
17485 bytes
0644
6464.f379e014f9909e621de6.js
34429 bytes
0644
6464.f379e014f9909e621de6.js.map
113303 bytes
0644
6499.9f52e0855fd4782a8b45.js
78297 bytes
0644
6499.9f52e0855fd4782a8b45.js.map
273155 bytes
0644
6587.bfb1ca0c32c6f325b0df.js
135004 bytes
0644
6587.bfb1ca0c32c6f325b0df.js.map
541974 bytes
0644
660.838743295c2108f3492d.js
43101 bytes
0644
660.838743295c2108f3492d.js.map
100340 bytes
0644
6678.a615dbe07b8a3e591e66.js
14725 bytes
0644
6678.a615dbe07b8a3e591e66.js.map
51145 bytes
0644
680.1a328432fae403eacab3.js
53846 bytes
0644
680.1a328432fae403eacab3.js.map
57615 bytes
0644
6830.0c200fec1efc2be388e2.js
5811 bytes
0644
6830.0c200fec1efc2be388e2.js.map
13972 bytes
0644
6934.fa19d392db34411fb300.js
168944 bytes
0644
6934.fa19d392db34411fb300.js.map
540337 bytes
0644
6940.9c5d3a2dcf9d7d58fa2c.js
3408 bytes
0644
6940.9c5d3a2dcf9d7d58fa2c.js.map
8039 bytes
0644
6969.f8f153735314f9426000.js
1119 bytes
0644
6969.f8f153735314f9426000.js.map
4230 bytes
0644
6990.cc2f5674128929a3f870.js
4418 bytes
0644
6990.cc2f5674128929a3f870.js.map
10503 bytes
0644
7048.117de444b1e1cb5a1360.js
4365 bytes
0644
7048.117de444b1e1cb5a1360.js.map
10316 bytes
0644
7166.480da6892ee84ee8bb53.js
593985 bytes
0644
7166.480da6892ee84ee8bb53.js.map
2430098 bytes
0644
7200.dc60128b9d612fc7b5b0.js
3634 bytes
0644
7200.dc60128b9d612fc7b5b0.js.map
8184 bytes
0644
7246.3adf293a34fa2043387b.js
4306 bytes
0644
7246.3adf293a34fa2043387b.js.map
9084 bytes
0644
7400.024c96bd5b99b8b47a63.js
14112 bytes
0644
7400.024c96bd5b99b8b47a63.js.map
64001 bytes
0644
7409.24316c87d08c1053c46a.js
3287 bytes
0644
7409.24316c87d08c1053c46a.js.map
11649 bytes
0644
7455.845968885abe369e6479.js
19801 bytes
0644
7455.845968885abe369e6479.js.map
77213 bytes
0644
7466.09e6e197d2507f62097d.js
11670 bytes
0644
7466.09e6e197d2507f62097d.js.map
24830 bytes
0644
7515.95323f0dfbd0de010e5c.js
1083 bytes
0644
7515.95323f0dfbd0de010e5c.js.map
1321 bytes
0644
7613.6334cff4df12cc157522.js
808779 bytes
0644
7613.6334cff4df12cc157522.js.map
991378 bytes
0644
7836.6a7e4207e70fc2dc235f.js
7192 bytes
0644
7836.6a7e4207e70fc2dc235f.js.map
17613 bytes
0644
7882.1a3cc418752c83396970.js
3743 bytes
0644
7882.1a3cc418752c83396970.js.map
14950 bytes
0644
7886.485c46f14540aa23cf70.js
8668 bytes
0644
7886.485c46f14540aa23cf70.js.map
20124 bytes
0644
7914.2b1a06c504df18e20fe4.js
2390 bytes
0644
7914.2b1a06c504df18e20fe4.js.map
6418 bytes
0644
7982.6761217193d3060dbf0e.js
188973 bytes
0644
7982.6761217193d3060dbf0e.js.map
1737667 bytes
0644
8054.094788468423bb88ee68.js
38124 bytes
0644
8054.094788468423bb88ee68.js.map
132296 bytes
0644
8107.92bd414247a1d05c014f.js
5144 bytes
0644
8107.92bd414247a1d05c014f.js.map
15320 bytes
0644
8230.2eedae6021a4715c6dea.js
2413 bytes
0644
8230.2eedae6021a4715c6dea.js.map
5812 bytes
0644
8332.f4b05d2f028641445650.js
3177 bytes
0644
8332.f4b05d2f028641445650.js.map
7186 bytes
0644
8334.c95ec0eb6900c0cf7e89.js
7803 bytes
0644
8334.c95ec0eb6900c0cf7e89.js.map
17714 bytes
0644
8390.1fd9505094c8cf8830ab.js
2096 bytes
0644
8390.1fd9505094c8cf8830ab.js.map
5157 bytes
0644
84.a6f8658e6a033d642231.js
30608 bytes
0644
84.a6f8658e6a033d642231.js.map
142543 bytes
0644
8494.4470c87b7093ddf70db7.js
2180 bytes
0644
8494.4470c87b7093ddf70db7.js.map
4863 bytes
0644
8542.1391ab96a455b01963a7.js
1514 bytes
0644
8542.1391ab96a455b01963a7.js.map
3249 bytes
0644
8566.e05562713181c6ca30fe.js
3852 bytes
0644
8566.e05562713181c6ca30fe.js.map
8781 bytes
0644
8730.3dcdd8cbf22c63b45d78.js
2109 bytes
0644
8730.3dcdd8cbf22c63b45d78.js.map
2893 bytes
0644
8786.1b0e43b80c82c73e2096.js
1535 bytes
0644
8786.1b0e43b80c82c73e2096.js.map
4055 bytes
0644
8902.37d0b14aa6ef24687b7b.js
2673 bytes
0644
8902.37d0b14aa6ef24687b7b.js.map
5993 bytes
0644
8990.5a822b8788ebf0bdba81.js
3969 bytes
0644
8990.5a822b8788ebf0bdba81.js.map
9161 bytes
0644
9034.200fc7a09b466256c9a9.js
3486 bytes
0644
9034.200fc7a09b466256c9a9.js.map
8180 bytes
0644
9038.7ae2448b9cc5c423aeca.js
4937 bytes
0644
9038.7ae2448b9cc5c423aeca.js.map
11973 bytes
0644
9118.3121c6b96ec7dc211973.js
48311 bytes
0644
9118.3121c6b96ec7dc211973.js.map
62149 bytes
0644
9150.9eb62d45f9b21cb38850.js
10056 bytes
0644
9150.9eb62d45f9b21cb38850.js.map
21143 bytes
0644
9199.9897e268d6d13e834d4c.js
2307 bytes
0644
9199.9897e268d6d13e834d4c.js.map
8853 bytes
0644
9320.c403e78b78aa6df1d0bd.js
336139 bytes
0644
9320.c403e78b78aa6df1d0bd.js.map
1624993 bytes
0644
9355.421530b20c759bb75633.js
22098 bytes
0644
9355.421530b20c759bb75633.js.map
66961 bytes
0644
9384.a0d5fc49f1b15b3e311e.js
2855 bytes
0644
9384.a0d5fc49f1b15b3e311e.js.map
3717 bytes
0644
9390.fa2af7f3d3d9600c08ee.js
4201 bytes
0644
9390.fa2af7f3d3d9600c08ee.js.map
9682 bytes
0644
946.f2494c0c39a9590349b9.js
9194 bytes
0644
946.f2494c0c39a9590349b9.js.map
22193 bytes
0644
9510.4cfa85a51931dc20573a.js
2949 bytes
0644
9510.4cfa85a51931dc20573a.js.map
6939 bytes
0644
9521.de2a74ca5eb365810ca5.js
46306 bytes
0644
9521.de2a74ca5eb365810ca5.js.map
51040 bytes
0644
9538.996ade7a03ccdb01942d.js
64493 bytes
0644
9538.996ade7a03ccdb01942d.js.map
49212 bytes
0644
9569.a8d60b39654a160cb917.js
27965 bytes
0644
9569.a8d60b39654a160cb917.js.map
99160 bytes
0644
9643.b408884004ca73c102bc.js
627 bytes
0644
9643.b408884004ca73c102bc.js.map
2195 bytes
0644
968.22e079d28acb4131d34c.js
4001 bytes
0644
968.22e079d28acb4131d34c.js.map
9740 bytes
0644
970.a61e37b9b897c8098261.js
5239 bytes
0644
970.a61e37b9b897c8098261.js.map
13858 bytes
0644
9711.d6e977bd60f0e5ba673d.js
13555 bytes
0644
9711.d6e977bd60f0e5ba673d.js.map
43973 bytes
0644
9737.3340c89ea96d33307cc7.js
1001 bytes
0644
9737.3340c89ea96d33307cc7.js.map
3504 bytes
0644
9739.5a801055fcf72bf4d06f.js
1147 bytes
0644
9739.5a801055fcf72bf4d06f.js.map
4390 bytes
0644
9772.49e918c9331237552c0b.js
141 bytes
0644
9772.49e918c9331237552c0b.js.map
416 bytes
0644
9838.b8f01dc360f0c2151291.js
4003 bytes
0644
9838.b8f01dc360f0c2151291.js.map
8118 bytes
0644
AdminAuthentication.b7044adf53b669e61a87.js
22504 bytes
0644
AdminAuthentication.b7044adf53b669e61a87.js.map
67352 bytes
0644
AdminEditOrgPage.96fb6c37346641f44246.js
6369 bytes
0644
AdminEditOrgPage.96fb6c37346641f44246.js.map
20602 bytes
0644
AdminFeatureTogglesPage.22157fe31f358f1c4f09.js
4939 bytes
0644
AdminFeatureTogglesPage.22157fe31f358f1c4f09.js.map
16531 bytes
0644
AdminListOrgsPage.f01c8496fd635e20124b.js
2702 bytes
0644
AdminListOrgsPage.f01c8496fd635e20124b.js.map
7735 bytes
0644
AdminSettings.845c6def917892a0c1f9.js
1903 bytes
0644
AdminSettings.845c6def917892a0c1f9.js.map
5580 bytes
0644
AlertAmRoutes.10a0d9a23a082caf12c8.js
54554 bytes
0644
AlertAmRoutes.10a0d9a23a082caf12c8.js.map
208792 bytes
0644
AlertGroups.efd523dc41621f9f7935.js
10088 bytes
0644
AlertGroups.efd523dc41621f9f7935.js.map
39108 bytes
0644
AlertRuleListIndex.f0b17a6119cc5ea575ed.js
44623 bytes
0644
AlertRuleListIndex.f0b17a6119cc5ea575ed.js.map
156842 bytes
0644
AlertRuleListLegacy.8e675db4469232c87308.js
6270 bytes
0644
AlertRuleListLegacy.8e675db4469232c87308.js.map
18086 bytes
0644
AlertSilences.4ff252ad4c0057124d5d.js
24687 bytes
0644
AlertSilences.4ff252ad4c0057124d5d.js.map
83377 bytes
0644
AlertTabCtrl.d3377d127a336a69beb5.js
9844 bytes
0644
AlertTabCtrl.d3377d127a336a69beb5.js.map
27934 bytes
0644
AlertingAdmin.e62f9c73a69abe6a1ac0.js
10523 bytes
0644
AlertingAdmin.e62f9c73a69abe6a1ac0.js.map
37393 bytes
0644
AlertingFeatureTogglePage.f971bb7b2ad4ceb0acbd.js
672 bytes
0644
AlertingFeatureTogglePage.f971bb7b2ad4ceb0acbd.js.map
1220 bytes
0644
AlertingHome.0d6be993ef4a3df37345.js
33492 bytes
0644
AlertingHome.0d6be993ef4a3df37345.js.map
106868 bytes
0644
AlertingRedirectToRule.37a0040f89e20b99b751.js
3648 bytes
0644
AlertingRedirectToRule.37a0040f89e20b99b751.js.map
10875 bytes
0644
AlertingRuleForm.66bb5b2724b31ae6a5a4.js
79931 bytes
0644
AlertingRuleForm.66bb5b2724b31ae6a5a4.js.map
292923 bytes
0644
AlertingUpgrade.c757b99e306db50cdb16.js
31333 bytes
0644
AlertingUpgrade.c757b99e306db50cdb16.js.map
98330 bytes
0644
AngularApp.7e72879caebef22a5217.js
72809 bytes
0644
AngularApp.7e72879caebef22a5217.js.map
102853 bytes
0644
ApiKeysPage.12b0cd511f7b1e9c50dc.js
8422 bytes
0644
ApiKeysPage.12b0cd511f7b1e9c50dc.js.map
23375 bytes
0644
BenchmarksPage.3a183df3d44714f9a96a.js
2941 bytes
0644
BenchmarksPage.3a183df3d44714f9a96a.js.map
9749 bytes
0644
ChangePasswordPage.5e0562f6a9674bd95cfe.js
470 bytes
0644
ChangePasswordPage.5e0562f6a9674bd95cfe.js.map
1195 bytes
0644
Connections.b53c715b9b9a782d8647.js
32448 bytes
0644
Connections.b53c715b9b9a782d8647.js.map
112998 bytes
0644
CorrelationsFeatureToggle.71addced22f59948b708.js
674 bytes
0644
CorrelationsFeatureToggle.71addced22f59948b708.js.map
1149 bytes
0644
CorrelationsPage.4e02feddf752bdf7cfe6.js
22725 bytes
0644
CorrelationsPage.4e02feddf752bdf7cfe6.js.map
69262 bytes
0644
CreateTeam.dbde5b87278cf087cc5e.js
3046 bytes
0644
CreateTeam.dbde5b87278cf087cc5e.js.map
9594 bytes
0644
DashboardImport.06e6c4c03113061aae6c.js
18153 bytes
0644
DashboardImport.06e6c4c03113061aae6c.js.map
58242 bytes
0644
DashboardListPage.dac1fe75fbaa4f9b1c23.js
30967 bytes
0644
DashboardListPage.dac1fe75fbaa4f9b1c23.js.map
108517 bytes
0644
DashboardPage.5e50193556ad6b828f5d.js
2786 bytes
0644
DashboardPage.5e50193556ad6b828f5d.js.map
8754 bytes
0644
DashboardPageProxy.9a6d60e5cac89c11c71c.js
65136 bytes
0644
DashboardPageProxy.9a6d60e5cac89c11c71c.js.map
226791 bytes
0644
DataTrailsPage.aa19ca6750eb3f91ac5d.js
331 bytes
0644
DataTrailsPage.aa19ca6750eb3f91ac5d.js.map
582 bytes
0644
EditNotificationChannelLegacy.75122e6dbfb215d89d81.js
10507 bytes
0644
EditNotificationChannelLegacy.75122e6dbfb215d89d81.js.map
37444 bytes
0644
EmbeddedDashboard.3856404d3d608c739864.js
1768 bytes
0644
EmbeddedDashboard.3856404d3d608c739864.js.map
5917 bytes
0644
FolderAlerting.a0fe69e3574320c8a74a.js
9633 bytes
0644
FolderAlerting.a0fe69e3574320c8a74a.js.map
29985 bytes
0644
FolderLibraryPanelsPage.95dd7bf6735e202a79d2.js
8599 bytes
0644
FolderLibraryPanelsPage.95dd7bf6735e202a79d2.js.map
25919 bytes
0644
LibraryPanelsPage.4a952d4aa9c21984995a.js
2704 bytes
0644
LibraryPanelsPage.4a952d4aa9c21984995a.js.map
7623 bytes
0644
ListPublicDashboardPage.469a693c4011a5193fcd.js
4713 bytes
0644
ListPublicDashboardPage.469a693c4011a5193fcd.js.map
14309 bytes
0644
MuteTimings.cb66b37f52c9ee3ce1da.js
20855 bytes
0644
MuteTimings.cb66b37f52c9ee3ce1da.js.map
58932 bytes
0644
NewNotificationChannelLegacy.1d57814bc534bb1a3681.js
9785 bytes
0644
NewNotificationChannelLegacy.1d57814bc534bb1a3681.js.map
32951 bytes
0644
NewOrgPage.2bb0e1cab09f0cbd0310.js
1325 bytes
0644
NewOrgPage.2bb0e1cab09f0cbd0310.js.map
3158 bytes
0644
NotificationsListLegacyPage.33212668898a6db361a8.js
2547 bytes
0644
NotificationsListLegacyPage.33212668898a6db361a8.js.map
6671 bytes
0644
NotificationsListPage.1eb9cb05bf88eee08291.js
1620 bytes
0644
NotificationsListPage.1eb9cb05bf88eee08291.js.map
3378 bytes
0644
NotificationsPage.d26b90d7348139106351.js
4646 bytes
0644
NotificationsPage.d26b90d7348139106351.js.map
25381 bytes
0644
OrgDetailsPage.2d5c98f188683c2e1d3b.js
6742 bytes
0644
OrgDetailsPage.2d5c98f188683c2e1d3b.js.map
17850 bytes
0644
PlaylistEditPage.d14b3673a1bb03ca0dbb.js
6892 bytes
0644
PlaylistEditPage.d14b3673a1bb03ca0dbb.js.map
19989 bytes
0644
PlaylistNewPage.13696f39b95b8416ede2.js
6583 bytes
0644
PlaylistNewPage.13696f39b95b8416ede2.js.map
19084 bytes
0644
PlaylistPage.8f45dcc09add615f90e8.js
7895 bytes
0644
PlaylistPage.8f45dcc09add615f90e8.js.map
25502 bytes
0644
PlaylistStartPage.8be462b13a24cddee188.js
275 bytes
0644
PlaylistStartPage.8be462b13a24cddee188.js.map
698 bytes
0644
PluginListPage.815b65d32380d0a800f7.js
12167 bytes
0644
PluginListPage.815b65d32380d0a800f7.js.map
43537 bytes
0644
PluginPage.c790de5e17a0b728dd3a.js
314 bytes
0644
PluginPage.c790de5e17a0b728dd3a.js.map
668 bytes
0644
ProfileFeatureTogglePage.a14257ebc5da1e8c85e0.js
552 bytes
0644
ProfileFeatureTogglePage.a14257ebc5da1e8c85e0.js.map
1012 bytes
0644
PublicDashboardPage.51c7c24941781e091898.js
4295 bytes
0644
PublicDashboardPage.51c7c24941781e091898.js.map
14393 bytes
0644
SelectOrgPage.695c19a5101a3a03ee28.js
1124 bytes
0644
SelectOrgPage.695c19a5101a3a03ee28.js.map
2993 bytes
0644
SendResetMailPage.f16b7172a87070f57227.js
1736 bytes
0644
SendResetMailPage.f16b7172a87070f57227.js.map
4350 bytes
0644
ServerStats.3fbd2493deb8f4598755.js
3863 bytes
0644
ServerStats.3fbd2493deb8f4598755.js.map
11534 bytes
0644
ServiceAccountCreatePage.4f989fb6cd2a41193ff0.js
2440 bytes
0644
ServiceAccountCreatePage.4f989fb6cd2a41193ff0.js.map
7939 bytes
0644
ServiceAccountPage.bc7c35b63b03ccc89628.js
14806 bytes
0644
ServiceAccountPage.bc7c35b63b03ccc89628.js.map
51593 bytes
0644
ServiceAccountsPage.baaa08c045390c05e276.js
14565 bytes
0644
ServiceAccountsPage.baaa08c045390c05e276.js.map
46399 bytes
0644
SignupInvited.81ad56aceb8dd1839e15.js
2360 bytes
0644
SignupInvited.81ad56aceb8dd1839e15.js.map
6096 bytes
0644
SnapshotListPage.519c760ed66124a771ff.js
3061 bytes
0644
SnapshotListPage.519c760ed66124a771ff.js.map
9043 bytes
0644
SoloPanelPage.c729750a88c3fa90d1cc.js
3229 bytes
0644
SoloPanelPage.c729750a88c3fa90d1cc.js.map
12316 bytes
0644
SoloPanelPageOld.6518c21ccaf29701fa97.js
1727 bytes
0644
SoloPanelPageOld.6518c21ccaf29701fa97.js.map
5509 bytes
0644
StoragePage.9b93a99e75f7f2842c11.js
14081 bytes
0644
StoragePage.9b93a99e75f7f2842c11.js.map
48740 bytes
0644
SupportBundles.567d512b3f919b8112e4.js
3058 bytes
0644
SupportBundles.567d512b3f919b8112e4.js.map
8751 bytes
0644
SupportBundlesCreate.fc6b6e4cf6366f751081.js
2779 bytes
0644
SupportBundlesCreate.fc6b6e4cf6366f751081.js.map
8882 bytes
0644
TeamList.2e23d37c91734f608f09.js
9019 bytes
0644
TeamList.2e23d37c91734f608f09.js.map
30348 bytes
0644
TeamPages.4f6177b4c6ec769c72d8.js
22839 bytes
0644
TeamPages.4f6177b4c6ec769c72d8.js.map
66001 bytes
0644
TestStuffPage.8ddabdd17d265b771b17.js
2654 bytes
0644
TestStuffPage.8ddabdd17d265b771b17.js.map
8058 bytes
0644
UserCreatePage.72e86cf2c9a3ce50cff3.js
1470 bytes
0644
UserCreatePage.72e86cf2c9a3ce50cff3.js.map
3788 bytes
0644
UserInvitePage.c8243c9cee4b06e10222.js
2576 bytes
0644
UserInvitePage.c8243c9cee4b06e10222.js.map
6594 bytes
0644
UserListPage.acbb5778a782ca90c7ba.js
25463 bytes
0644
UserListPage.acbb5778a782ca90c7ba.js.map
79671 bytes
0644
UserProfileEditPage.7cc4c218d9e4664250e3.js
14593 bytes
0644
UserProfileEditPage.7cc4c218d9e4664250e3.js.map
42901 bytes
0644
UsersListPage.1b61c82d62ca416b6f2f.js
8800 bytes
0644
UsersListPage.1b61c82d62ca416b6f2f.js.map
30059 bytes
0644
alert-rules-drawer-content.1fd9de3b496d077a5f3a.js
957 bytes
0644
alert-rules-drawer-content.1fd9de3b496d077a5f3a.js.map
3199 bytes
0644
alert-rules-toolbar-button.6f275f0d03748b6c297d.js
1429 bytes
0644
alert-rules-toolbar-button.6f275f0d03748b6c297d.js.map
4041 bytes
0644
alertmanagerPlugin.d13ca72afb3f996bb284.js
3810 bytes
0644
alertmanagerPlugin.d13ca72afb3f996bb284.js.map
10753 bytes
0644
app.b11fde05d43f9632a473.js
920821 bytes
0644
app.b11fde05d43f9632a473.js.map
69088 bytes
0644
assets-manifest.json
280835 bytes
0644
azureMonitorPlugin.0bc37a9d4e3bd8421cc0.js
232 bytes
0644
azureMonitorPlugin.0bc37a9d4e3bd8421cc0.js.map
600 bytes
0644
brace.fcd4b1c7e8b9264ab02c.js
371235 bytes
0644
brace.fcd4b1c7e8b9264ab02c.js.map
1132097 bytes
0644
canvasPanel.a46aa5e57d26b1fcc380.js
485254 bytes
0644
canvasPanel.a46aa5e57d26b1fcc380.js.map
2136916 bytes
0644
cloudMonitoringPlugin.c6ea431eae8e9ad2c7b1.js
198 bytes
0644
cloudMonitoringPlugin.c6ea431eae8e9ad2c7b1.js.map
555 bytes
0644
cloudwatchPlugin.06ef34f60000c4f7ea37.js
192 bytes
0644
cloudwatchPlugin.06ef34f60000c4f7ea37.js.map
544 bytes
0644
dark.7fa24d1908c1c96e6fcc.js
134 bytes
0644
elasticsearchPlugin.3f2edb012f5162b48903.js
214 bytes
0644
elasticsearchPlugin.3f2edb012f5162b48903.js.map
583 bytes
0644
explore-feature-toggle-page.897d9f08c342ad4c0702.js
612 bytes
0644
explore-feature-toggle-page.897d9f08c342ad4c0702.js.map
1280 bytes
0644
explore.476912733278e2a99729.js
165810 bytes
0644
explore.476912733278e2a99729.js.map
579148 bytes
0644
geomapPanel.14b9605971a38c51d262.js
417078 bytes
0644
geomapPanel.14b9605971a38c51d262.js.map
540371 bytes
0644
grafana.dark.8c716fbcf630eae84ced.css
209089 bytes
0644
grafana.light.b8b3904788f25480f4a1.css
209047 bytes
0644
grafanaPlugin.1cb208185a89de28dc3a.js
8654 bytes
0644
grafanaPlugin.1cb208185a89de28dc3a.js.map
28174 bytes
0644
graphPlugin.f47f722cdfc0ceb85136.js
70277 bytes
0644
graphPlugin.f47f722cdfc0ceb85136.js.map
243430 bytes
0644
graphitePlugin.d59175976346917781fe.js
75305 bytes
0644
graphitePlugin.d59175976346917781fe.js.map
272016 bytes
0644
heatmapPanel.f6f29a53ed0f682b4404.js
37545 bytes
0644
heatmapPanel.f6f29a53ed0f682b4404.js.map
158066 bytes
0644
influxdbPlugin.140a7777089f9559c11c.js
68843 bytes
0644
influxdbPlugin.140a7777089f9559c11c.js.map
265085 bytes
0644
jaegerPlugin.d254fd4a19ef0cb5b4f5.js
19727 bytes
0644
jaegerPlugin.d254fd4a19ef0cb5b4f5.js.map
65603 bytes
0644
light.af65e5ce03b9ed0aa2b1.js
134 bytes
0644
loki-query-field.a588d587d9d762b18f22.js
191 bytes
0644
loki-query-field.a588d587d9d762b18f22.js.map
548 bytes
0644
lokiPlugin.77364509de280321b6f8.js
185 bytes
0644
lokiPlugin.77364509de280321b6f8.js.map
536 bytes
0644
mixedPlugin.f36bd557a883d9a67538.js
180 bytes
0644
mssqlPlugin.88775f59ced74c2283c5.js
20457 bytes
0644
mssqlPlugin.88775f59ced74c2283c5.js.map
61420 bytes
0644
mysqlPlugin.72fb44411afd8165d201.js
17323 bytes
0644
mysqlPlugin.72fb44411afd8165d201.js.map
45415 bytes
0644
nodeGraphPanel.9a7cdd8efdae281cbe28.js
2107 bytes
0644
nodeGraphPanel.9a7cdd8efdae281cbe28.js.map
7132 bytes
0644
opentsdbPlugin.418b8c8ea0d97ed99edb.js
22866 bytes
0644
opentsdbPlugin.418b8c8ea0d97ed99edb.js.map
82180 bytes
0644
parcaPlugin.7f2e6dde7161b08ceed2.js
11184 bytes
0644
parcaPlugin.7f2e6dde7161b08ceed2.js.map
42340 bytes
0644
postgresPlugin.f88c598bae2653ae177b.js
18902 bytes
0644
postgresPlugin.f88c598bae2653ae177b.js.map
54304 bytes
0644
prom-query-field.ff217c474ea457bdd65e.js
14104 bytes
0644
prom-query-field.ff217c474ea457bdd65e.js.map
76811 bytes
0644
prometheusPlugin.2ba02c28d3f7293e903e.js
224 bytes
0644
prometheusPlugin.2ba02c28d3f7293e903e.js.map
699 bytes
0644
pyroscopePlugin.eb14b78419d619d90dca.js
22269 bytes
0644
pyroscopePlugin.eb14b78419d619d90dca.js.map
86896 bytes
0644
react-monaco-editor.988b1aa5e90b11f9941a.js
15759 bytes
0644
react-monaco-editor.988b1aa5e90b11f9941a.js.map
51544 bytes
0644
runtime.4b7e1b5735d2ed64b824.js
13640 bytes
0644
runtime.4b7e1b5735d2ed64b824.js.map
35122 bytes
0644
tableOldPlugin.8c72b8399d197aeebe16.js
25242 bytes
0644
tableOldPlugin.8c72b8399d197aeebe16.js.map
80497 bytes
0644
tempoPlugin.efa8c2a55984263b4b61.js
182 bytes
0644
tempoPlugin.efa8c2a55984263b4b61.js.map
529 bytes
0644
testDataDSPlugin.9717509b124d754e4f35.js
120550 bytes
0644
testDataDSPlugin.9717509b124d754e4f35.js.map
303302 bytes
0644
visjs-network.d93b3aa71ac24c8cde84.js
459653 bytes
0644
visjs-network.d93b3aa71ac24c8cde84.js.map
1951742 bytes
0644
zipkinPlugin.70f0f24b6d0b6e673ccb.js
13172 bytes
0644
zipkinPlugin.70f0f24b6d0b6e673ccb.js.map
46861 bytes
0644
N4ST4R_ID | Naxtarrr