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{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{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;_{"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{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{"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)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(nC.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=-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).lengtht.maxx&&(t.maxx=e.x),e.yt.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!(mu+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).lengthi&&(i=c),mn&&(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(e1?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 si&&(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;qrt&&(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)=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.lengths?!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)n+C.tolerance?(h=n,c++):hC.tolerance&&!(S=u>=5||c>=5));return S&&t.value(i).sub(e).lengththis.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(h0}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))this.aMax+C.distanceEpsilon||hthis.bMax+C.distanceEpsilon||uthis.aMax?this.si=this.aMax:this.sithis.bMax?this.ti=this.bMax:this.ti=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)this.aMax?e=(this.aMax-this.si)/t.s:this.si+t.sthis.bMax?i=(this.bMax-this.ti)/t.t:this.ti+t.tthis.bMax?t.t=this.bMax-this.ti:this.ti+t.tthis.aMax?t.s=this.aMax-this.si:this.si+t.sC.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(Sc)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)),mc)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);uC.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:cur(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=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.part.end){const e=t.start;t.start=t.end,t.end=e}t.startthis.parEnd&&(t.end=this.parEnd)}trimWithWrap(t,e){if(tn+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).lengthC.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=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(!(Ao+C.tolerance)&&(A=Math.min(A,o),!(Ih+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;B0;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.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;B0?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.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=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);Ia.par0-h.par0);for(let a=0;at.parEnd&&(o=t.parStart+(o-t.parEnd)),yield t.value(o)}static NonIntersectingCurveIsInsideOther(t,e){for(let i=t.parStart;is&&(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.par0u.par0c.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(;ns[s.length-1]+GeomConstants.distanceEpsilon&&s.push(o.par0)}for(l.parEnd>s[s.length-1]+GeomConstants.distanceEpsilon&&s.push(l.parEnd),n=0;nn.par0-o.par0);const i=[l.parStart];let s=0;for(;si[i.length-1]+GeomConstants.distanceEpsilon&&i.push(n.par0)}for(l.parEnd>i[i.length-1]+GeomConstants.distanceEpsilon&&i.push(l.parEnd),s=0;st.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);uthis.top_+C.distanceEpsilon||t.top_this.right_+C.distanceEpsilon||t.rightt.x&&(this.left_=t.x),this.top_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.DifferenceEpsilonL.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;ae&&(t.seed0=s,e=n)}let i;for(let s=0;se&&(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.sizei===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.height2&&Gi.GoldenSectionSearch(a=>this.PackLimit(a),t,s,e,n);const o=this.bestPacking.getRects();for(let a=0;aGi.GoldenSectionSearch(t,o,i,e,n),c=()=>Gi.GoldenSectionSearch(t,i,o,s,n);if(ha)return u();const m=c(),S=u();return t(S)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||a0?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.Counto?(this.AddNodeToTreeRecursive(t,e.Right),e.Right.irect=s):i.area[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[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)[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;h0}*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(;ithis.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 is?1:(i=this.directionPerp.dot(t),s=this.directionPerp.dot(e),is?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))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.distanceEpsilonC.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;es)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.ythis.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++),tthis.pivot.x+C.distanceEpsilon&&t.x{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(18)^t)>>BigInt(27),i=t>>BigInt(59),s=i^BigInt(31);return(e>>i|e<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;i0;){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;o0;){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)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;eMath.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=Math.PI?i>=Math.PI/2?t.p1=t.p2:t.q1=e:n>=Math.PI/2?t.q2=e:i=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:tt?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{const s=d.anglePCP(e,t,this.pnt(i));return sw.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;inew 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 hh!==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.lengthpe(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=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=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;t0&&(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){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)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).lengthSquared0;){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.lengthC.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;t0;){const a=n.pop();s=a.v,i[s]=qi.Visited,o=a.i;let h=t.outEdges[s];for(;othis.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.MaxConstraintTreeDepth0){for(const o of this.constraintPath)o.IsForward&&(e==null||o.Constraint.Lagrangian0?(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;e0;){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=0;o--)this.Variables[o].Block===t&&(o1?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)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)it&&(t=n,e=s)}return e}Insert(t,e){let i=0,s=e,n=e;for(let o=0;ot.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;sthis.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;m0&&(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;ethis.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.MaxInnerProjectIterationse&&(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;othis.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){tthis.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;tnew 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.yIt.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.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.ythis.end.y&&(this.end=t)}TryPointForStartAndEndEast(t){t.xthis.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.xi<=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.distanceEpsilon0)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>>21)*gn|0;while(t>>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>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>>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>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>>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>>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{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{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<>>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):sn?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{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>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;ti.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;n1&&We.InsertPoints(o,s,n,a)}}static InsertPoints(t,e,i,s){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.lengthn===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)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;ti&&(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 in.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.maxs.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;ei.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(;++o1?(e-t)/(o-1):1;for(let h=0;h=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){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=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)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;h1||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;_t0}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=this.vector[s].Coord)return s;for(;s-i>2;){const n=i+(s-i>>1),o=this.vector[n];if(to.Coord){i=n;continue}return n}for(i++;i<=s;i++){const n=this.vector[i];if(t0?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;a0){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;nthis.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=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;te){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(uthis.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)}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;t0){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=s||(this.AddSlotToSegmentIntersections(e,i),this.AddSlotToSegmentIntersections(e,s),n>i&&n1;){const a=n+Math.floor((o-n)/2);if(i<=a){o=a,in&&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.xi.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.ye.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.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"+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=0){if(te!==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;e0;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+1e[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;o0&&(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;h0&&(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;s0&&(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;s0)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;no.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;t0&&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.xt.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.x0&&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),tt===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)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.endthis.end?this.end:t}intersects(t){return t.start>this.end+C.distanceEpsilon?!1:!(t.end>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]]1&&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();t0;)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);onew Ot(a.source,a.target)),s=new Fs;for(let a=0;as.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;he(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;sC.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;c1&&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.righto.clone()),n=new Set;n.add(i);for(let o=0;os.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;s0&&(h/=a),h>0)for(let u=0;u0){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)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 in .NET Core. HashSet is derived from the implementation of HashSet 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=F)return J}for(let X=F|1;Xn&&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=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=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>>>00)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=(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=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 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 in .NET Core. HashSet is derived from the implementation of HashSet 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=V)return X}for(let F=V|1;Fn&&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=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>>00)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=(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=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: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.lengthc[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=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;os==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;ia.Radius)&&(i=a,s=[n,o])}for(let a=0;ah.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=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).lengththis.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;S0;)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;athis.AddSpringForces(t));for(const t of this.components){let e=new d(0,0);for(let s=0;si&&(i=n.force.length)}if(i>100)for(let s=0;s=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;hu.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;tthis.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(ti)return n;const o=(t-e)/(i-e);return s+o*(n-s)}static NegativeLinearInterpolation(t,e,i,s,n){if(ti)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(In)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=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 i1){const o=i.Neighbors;for(let a=0;a=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.SerialNumber0?(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.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.SerialNumberbn(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;u0}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):to||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!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].par0s[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