Make big networks fast: routing, panels and map drawing
A network with a hundred POPs and a thousand peering ports froze the game for most of a second every day and after every click, because routing checked all ~1,800 exits for each of ~14,000 flows. Now: - compute(): exits are asked once per network which networks they reach, each flow scans only those, and the first ECMP group is found without sorting. The graph runs on city indices with a typed-array Dijkstra (same heap moves, same ties), routers and per-link traffic are kept in typed arrays, the diverse-path check reuses one live-link graph, and R.ef is put together when a link is read. Results are bit-identical to before. - Panels and the NOC dashboard are patched in place (morph) instead of being rebuilt, so the browser no longer restyles 1,500 rows every tick. Buttons whose action changed are swapped out, keeping #44's tap protection. - The Networks tab works out each IX port's sessions once instead of once per network. - draw() reuses screen-point buffers, a per-frame pair index and cached label widths, strokes the dotted fiber line on the path it already has, and uses native roundRect: about a third fewer canvas calls per frame, same output.
This commit is contained in:
parent
6c2d5da5b8
commit
a887b65a2f
5 changed files with 347 additions and 126 deletions
|
|
@ -7,6 +7,8 @@ All notable changes to this project are documented here. The project follows
|
|||
## [Unreleased]
|
||||
|
||||
- Hamburg and Munich join the map, with the Moin-IX and the Brezn-IX. Stuttgart and Frankfurt are back where they belong on the map, with Stuttgart between Frankfurt and Zurich instead of halfway to Prague.
|
||||
- Big networks no longer lag: working out each day's traffic is more than ten times faster with a hundred POPs and a thousand peering ports, so the game stops freezing every day and after every click. The map needs about a third fewer drawing steps per frame, and open panels only update what changed, which keeps them smooth and lets the traffic bars glide to their new values.
|
||||
|
||||
## [1.28.0] — 2026-10-25
|
||||
|
||||
- Belgium and Luxembourg join the map: Brussels, Oostkamp and Bettembourg (#79). Belgian POPs and transit cost more, and Belgian homes stay with their two big ISPs unless you run an ad campaign there. Telenyet, Proxyminus, B.I.G.S., Citrus Belgium and CityMess join the networks, a new cable connects London to Oostkamp through some very busy fishing grounds, and Bettembourg's cooling depends on a steady supply of waste wood.
|
||||
|
|
|
|||
|
|
@ -90,6 +90,10 @@ never freezes the game.
|
|||
5. Layer-2 customers (L2VPN, SD-WAN, waves) are carved out of link capacity first.
|
||||
6. Totals costs (`R.cost`) and revenue (`R.rev`) per month.
|
||||
|
||||
It runs every day and after every action, so it is built for big networks: the graph works on city
|
||||
indices (`CIDX`), each exit is asked once per network what it can reach, and `R.ef` (what crosses each
|
||||
link) is only put together for a link when something reads it.
|
||||
|
||||
Served share per city (`sfOf`) drives eyeball revenue and customer mood.
|
||||
|
||||
## Actions and rendering
|
||||
|
|
@ -102,6 +106,8 @@ Served share per city (`sfOf`) drives eyeball revenue and customer mood.
|
|||
- `renderLeft()` draws the left tabs (deals, NOC, customers…), `renderPanel()` the
|
||||
selection panel (city, link, network). On phones these become bottom sheets
|
||||
controlled by `renderTabbar()`.
|
||||
- These panels and the dashboard are rebuilt as HTML every tick and written with `morph()`, which
|
||||
patches only what changed. Buttons whose action changed are replaced, so taps stay safe (#44).
|
||||
- The map is a canvas drawn every frame by `draw()`. Zoomed out (`lodFar()`) it uses
|
||||
a simplified style; parallel waves are grouped by `linkGroups()`.
|
||||
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
"homepage": "https://seriesoftub.es/",
|
||||
"repository": { "type": "git", "url": "git+https://github.com/fjaeckel/seriesoftubes.git" },
|
||||
"scripts": {
|
||||
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js tests/levels.test.js tests/i18n.test.js",
|
||||
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js tests/levels.test.js tests/speed.test.js tests/i18n.test.js",
|
||||
"build": "bash scripts/build.sh",
|
||||
"i18n:check": "node scripts/i18n-check.js",
|
||||
"serve": "npm run build && npx --yes serve@14.2.4 _site"
|
||||
|
|
|
|||
362
site/index.html
362
site/index.html
|
|
@ -732,7 +732,8 @@ const subCarrier=km=>Math.max(0,...Object.values(OPT).map(O=>{const m=(O.modes||
|
|||
const waveCar=i=>LT[i].car||LT[i].g;
|
||||
function subWaveWhy(i,km,sub){if(!sub)return '';const c=subCarrier(km);return waveCar(i)>c?tr('{km} km of cable carries at most {g} per carrier.',{km:Math.round(km).toLocaleString(),g:fmtCap(c)}):'';}
|
||||
const subMaxTier=km=>{let t=0;LT.forEach((T,i)=>{if(!subWaveWhy(i,km,true))t=i;});return t;};
|
||||
const optG=(o,l)=>{const m=optMode(o,l);return m?m.g:0;};
|
||||
// What an optic carries depends only on the optic, the span length and subsea or not; the map and compute() ask a lot.
|
||||
const OPTG={};const optG=(o,l)=>{const km=spanKm(l),m=OPTG[o]||(OPTG[o]=new Map()),k=km*2+(l.sub?1:0);let g=m.get(k);if(g===undefined){const x=optMode(o,l);m.set(k,g=x?x.g:0);}return g;};
|
||||
const regenNeed=(o,l)=>Math.max(0,Math.ceil(l.km/OPT[o].reach)-1);
|
||||
const dfCap=l=>{if(l.ready>S.day||l.eqDown>S.day)return 0;const ch=l.ch||[];let g=0;for(const c of ch)g+=optG(c,l);const f=l.chFail&&l.chFail.until>S.day?l.chFail:null;if(f){const fo=f.o&&ch.includes(f.o)?f.o:ch.slice().sort((a,b)=>optG(a,l)-optG(b,l))[0];if(fo)g-=optG(fo,l);}return Math.max(0,g);};
|
||||
const capOf=l=>(l.kind==='vxc'?VXC[l.vt].g:l.kind==='df'?dfCap(l):LT[l.tier].g)*(l.deg>S.day?0.5:1)*(l.loss&&l.loss.until>S.day?l.loss.f:1);
|
||||
|
|
@ -869,7 +870,7 @@ const CITIES=[
|
|||
// Display-only nudges for cities that sit on top of each other at map scale; distances still use real lon/lat.
|
||||
const CITY_NUDGE={stg:[7,1],zrh:[-3,3],bru:[1,3],oos:[-3,0],van:[-3,-6],sea:[1,4],ott:[-3,-3],bcn:[-6,-4],auh:[-5,6],dxb:[9,-7],fuj:[8,15],rio:[14,-16],tll:[-4,22],osa:[-10,6],khi:[-2,-6],hou:[0,6],dal:[0,-4],nyc:[.3,-.7],mia:[-.6,.4],mtl:[.8,0],cph:[-.7,.3],hel:[-.8,-.2],akl:[.6,.4],sin:[-1.3,-1.3],hkg:[.8,0],ist:[.8,0],lis:[.8,0]};
|
||||
for(const c of CITIES){const q=CITY_LL[c.id];if(q){c.lon=q[0];c.lat=q[1];const pt=proj(q[0],q[1]),n=CITY_NUDGE[c.id]||[0,0];c.x=pt[0]+n[0];c.y=pt[1]+n[1];}}
|
||||
const CITY=Object.fromEntries(CITIES.map(c=>[c.id,c]));
|
||||
const CITY=Object.fromEntries(CITIES.map(c=>[c.id,c])),CIDX=Object.fromEntries(CITIES.map((c,i)=>[c.id,i]));
|
||||
const CABLES=[
|
||||
{"id":"marea","name":"Marea Carey","price":0.8,"age":"new","blurb":tr("Hits the high notes across the Atlantic. Huge capacity, cheap waves."),"pairs":[["ash","mad",[[-74,36.5],[-50,40],[-25,43],[-10,44]]]]},
|
||||
{"id":"grace","name":"Grace Hopscotch","price":0.85,"age":"new","blurb":tr("Hops from New York to the UK and Spain."),"pairs":[["nyc","lon",[[-72,40],[-50,47],[-25,50],[-10,50.5]]],["nyc","mad",[[-72,39.8],[-50,42],[-25,43.2],[-10,43.8]]]]},
|
||||
|
|
@ -1162,7 +1163,9 @@ NETS.push(
|
|||
{id:'sky',name:'Sky-High Broadband',asn:5607,type:'eye',pol:'selective',minIx:6,minPni:25,share:.008,col:'#0072C9',pops:['lon','man','edi','dub'],ix:['lon','man','edi'],blurb:tr('Football, films and a router that looks like a spaceship.')},
|
||||
{id:'vmo',name:'Virgin Mediocre',asn:5089,type:'eye',pol:'selective',minIx:6,minPni:25,share:.007,col:'#E10A0A',pops:['lon','man','edi'],ix:['lon','man'],blurb:tr('Cable broadband for half of Britain. Fast on a good day.')},
|
||||
{id:'tnr',name:'Tele-Nor-Way',asn:2119,type:'eye',pol:'selective',minIx:5,minPni:20,share:.006,col:'#00A9E0',pops:['osl','svg','sto','cph'],ix:['osl','svg'],blurb:tr('Norway’s incumbent. Neither yes nor no, until you send enough traffic.')});
|
||||
const NET=Object.fromEntries(NETS.map(n=>[n.id,n]));
|
||||
const NET=Object.fromEntries(NETS.map(n=>[n.id,n])),NET_IDS=NETS.map(n=>n.id);
|
||||
// The networks a PNI with each upstream reaches: the upstream itself plus everyone who buys transit from it.
|
||||
const PNI_NETS={};for(const n of NETS)PNI_NETS[n.id]=[n.id].concat(NETS.filter(x=>x.up&&x.up.includes(n.id)).map(x=>x.id));
|
||||
for(const X of XIX){X.members=NETS.filter(n=>Array.isArray(n.ix)&&n.ix.includes(X.id)||!n.tail&&(X.core?X.core.includes(n.id):(n.ix==='ALL'||Array.isArray(n.ix)&&n.ix.includes(X.c))&&hstr(n.id+'|'+X.id)%100<(n.ix==='ALL'?72:X.take*100))).map(n=>n.id);}
|
||||
const NSH={}; {const t=NETS.reduce((a,n)=>a+n.share,0); NETS.forEach(n=>NSH[n.id]=n.share/t);}
|
||||
// After Glitch leaves Korea, Seoul viewers watch half as much of it and the rest moves to everyone else.
|
||||
|
|
@ -1664,14 +1667,22 @@ function tierLabel(){return S.won&&isTier1()?'Tier 1':isTier2()?'Tier 2':'Tier 3
|
|||
function t1Why(){if(S.transit.length)return tr('you buy transit again');const miss=t1Need().filter(n=>!S.pni.some(p=>p.net===n.id));if(miss.length)return tr('no PNI with {list}',{list:miss.map(n=>n.name).join(', ')});{const lost=NETS.filter(n=>!R.reachable[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id]);if(lost.length)return tr('you cannot reach {list}',{list:lost.slice(0,3).map(n=>n.name).join(', ')+(lost.length>3?' '+tr('and {n} more',{n:lost.length-3}):'')});}return tr('your reach is {p}, not 100%',{p:reachPct(R.reach)});}
|
||||
|
||||
/* ================= SIMULATION ================= */
|
||||
// Binary-heap Dijkstra over an adjacency map {city:[[neighbour,edge],...]}. wf(edge) gives the weight,
|
||||
// skip(v,edge) can rule edges out, and the search stops early once `stop` is settled.
|
||||
function hpush(h,x){h.push(x);let i=h.length-1;while(i>0){const p=(i-1)>>1;if(h[p][0]<=h[i][0])break;[h[p],h[i]]=[h[i],h[p]];i=p;}}
|
||||
function hpop(h){const top=h[0],last=h.pop();if(h.length){h[0]=last;let i=0;for(;;){const l=2*i+1,r=l+1;let m=i;if(l<h.length&&h[l][0]<h[m][0])m=l;if(r<h.length&&h[r][0]<h[m][0])m=r;if(m===i)break;[h[m],h[i]]=[h[i],h[m]];i=m;}}return top;}
|
||||
function dijkstra(adj,src,wf,skip,stop){const dist={[src]:0},prev={},done=new Set(),h=[[0,src]];
|
||||
while(h.length){const [d,u]=hpop(h);if(done.has(u)||d>dist[u])continue;done.add(u);if(u===stop)break;
|
||||
for(const [v,e] of adj[u]||[]){if(skip&&skip(v,e))continue;const nd=d+wf(e);if(nd<(dist[v]??Infinity)){dist[v]=nd;prev[v]=e;hpush(h,[nd,v]);}}}
|
||||
return {dist,prev};}
|
||||
// Binary-heap Dijkstra over city indices: adj[i] lists [neighbour, edge]. wf(edge) gives the weight, skip(v,edge) can
|
||||
// rule edges out, and the search stops early once `stop` is settled. D is the distance to each city (Infinity: no
|
||||
// path) and P the edge it was reached by. The heap lives in two typed arrays, and equal distances always settle in the
|
||||
// same order, so routes do not flip between runs.
|
||||
function dijkstra(adj,src,wf,skip,stop){const n=adj.length,D=new Float64Array(n).fill(Infinity),P=new Array(n),done=new Uint8Array(n);
|
||||
let cap=64,hd=new Float64Array(cap),hu=new Int32Array(cap),m=0;
|
||||
const put=(d,u)=>{if(m===cap){cap*=2;const a=new Float64Array(cap),b=new Int32Array(cap);a.set(hd);b.set(hu);hd=a;hu=b;}
|
||||
let i=m++;hd[i]=d;hu[i]=u;while(i>0){const p=(i-1)>>1;if(hd[p]<=hd[i])break;const td=hd[p],tu=hu[p];hd[p]=hd[i];hu[p]=hu[i];hd[i]=td;hu[i]=tu;i=p;}};
|
||||
D[src]=0;put(0,src);
|
||||
while(m){const d=hd[0],u=hu[0];m--;
|
||||
if(m){hd[0]=hd[m];hu[0]=hu[m];let i=0;for(;;){const l=2*i+1,r=l+1;let k=i;if(l<m&&hd[l]<hd[k])k=l;if(r<m&&hd[r]<hd[k])k=r;if(k===i)break;const td=hd[k],tu=hu[k];hd[k]=hd[i];hu[k]=hu[i];hd[i]=td;hu[i]=tu;i=k;}}
|
||||
if(done[u]||d>D[u])continue;done[u]=1;if(u===stop)break;
|
||||
for(const [v,e] of adj[u]||[]){if(skip&&skip(v,e))continue;const nd=d+wf(e);if(nd<D[v]){D[v]=nd;P[v]=e;put(nd,v);}}}
|
||||
return {D,P};}
|
||||
// The edges of a dijkstra() path back from city index B to A, and the cities on it (B first), as indices.
|
||||
function walkI(P,A,B){const path=[],ni=[B];let v=B;while(v!==A){const l=P[v];path.push(l);v=l.ai===v?l.bi:l.ai;ni.push(v);}return {path,ni};}
|
||||
/* ---------- RouteScript: a tiny, safe rule language for the Auto-TE controller ----------
|
||||
Player scripts are parsed into plain data and never executed, so a shared or imported
|
||||
save can't run code. One rule per line, # for comments. */
|
||||
|
|
@ -1717,39 +1728,55 @@ function teModal(msg){const src=UI.teDraft!==undefined?UI.teDraft:(S.te.script||
|
|||
function teTrial(src){const keep=S.te.script,on=S.te.on,before={served:R.served,tc:R.cost.transit||0,moved:R.teMoved||0};
|
||||
S.te.script=src;S.te.on=true;compute();const after={served:R.served,tc:R.cost.transit||0,moved:R.teMoved||0,bh:R.teBlack||0};
|
||||
S.te.script=keep;S.te.on=on;compute();return {before,after};}
|
||||
// tr() with one placeholder, remembered: compute() labels every port, PNI and cache on every run.
|
||||
const LABS=new Map();function labOf(s,k,v){const key=s+'|'+v;let o=LABS.get(key);if(o===undefined)LABS.set(key,o=tr(s,{[k]:v}));return o;}
|
||||
function compute(){
|
||||
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp);
|
||||
const remote=remoteCities(),adj={}; pops.concat(remote).forEach(p=>adj[p]=[]);
|
||||
const edges={},TRX=teRules();
|
||||
for(const l of S.links){if(linkDown(l)||!adj[l.a]||!adj[l.b])continue;const key=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let e=edges[key];
|
||||
if(!e){e=edges[key]={id:key,a:l.a,b:l.b,km:l.km,cap:0,w:Infinity,lat:Infinity,links:[]};adj[l.a].push([l.b,e]);adj[l.b].push([l.a,e]);}e.cap+=capOf(l);e.links.push(l);e.w=Math.min(e.w,(l.km+60)*MET[l.metric||'normal'].f*(TRX&&TRX.avoid.has(key)?60:1));e.lat=Math.min(e.lat,linkLat(l));}
|
||||
const SP={};
|
||||
const wW=e=>e.w;for(const s of pops)SP[s]=dijkstra(adj,s,wW);
|
||||
const prevU=e=>{let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;return e.cap?ld/e.cap:0;};
|
||||
const dijk=(s0,mode)=>dijkstra(adj,s0,mode==='fast'?e=>e.lat+0.05:e=>e.w*(1+10*prevU(e)));
|
||||
const day=S.day, R2=emptyR(), pops=Object.keys(S.pops).filter(popUp), NC=CITIES.length;
|
||||
// The graph works on city indices: adj[i] lists [neighbour, edge] in S.links order.
|
||||
const remote=remoteCities(),adj=new Array(NC); pops.concat(remote).forEach(p=>adj[CIDX[p]]=[]);
|
||||
const edges={},TRX=teRules(),live=[];let NE=0;
|
||||
for(const l of S.links){const ai=CIDX[l.a],bi=CIDX[l.b];if(linkDown(l)||!adj[ai]||!adj[bi])continue;live.push(l);const key=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;let e=edges[key];
|
||||
if(!e){e=edges[key]={id:key,a:l.a,b:l.b,ai,bi,i:NE++,km:l.km,cap:0,w:Infinity,lat:Infinity,links:[],res:0,ld:0,tr:null,pl:0};adj[ai].push([bi,e]);adj[bi].push([ai,e]);}e.cap+=capOf(l);e.links.push(l);e.w=Math.min(e.w,(l.km+60)*MET[l.metric||'normal'].f*(TRX&&TRX.avoid.has(key)?60:1));e.lat=Math.min(e.lat,linkLat(l));}
|
||||
// Shortest paths from every POP: SPD[pop] the distance to each city index (Infinity: no path), SPP[pop] the edge it arrives by.
|
||||
// ALONE[i]: no other city lies within 1e-6 of POP i (so only its own exits can be at distance 0 from it).
|
||||
const SPD={},SPP={},SDi=[],SPi=[],ALONE=new Uint8Array(NC),wW=e=>e.w,wLat=e=>e.lat+0.05;
|
||||
for(const s of pops){const i=CIDX[s],r=dijkstra(adj,i,wW);SDi[i]=SPD[s]=r.D;SPi[i]=SPP[s]=r.P;ALONE[i]=1;for(let x=0;x<NC;x++)if(x!==i&&r.D[x]<1e-6)ALONE[i]=0;}
|
||||
const E=[], ev=S.ev;
|
||||
const depeer=ev.depeer>day||scnRule('spat'), leak=ev.leak&&ev.leak.until>day?ev.leak.net:null;
|
||||
for(const t of S.transit){if(!popUp(t.city)||t.down>day||!liveN(t.city,t.site,t.n))continue;
|
||||
E.push({k:'t',prem:!!t.premium&&t.city==='hkg',pref:t.pref||'normal',lab:tr('{net} transit',{net:NET[t.net].name}),id:t.id,city:t.city,cap:Math.min(liveCap(PORT[t.tier].g,t.city,t.site,t.n)*lagF(t),TRX&&TRX.cap[t.net]!==undefined?TRX.cap[t.net]:Infinity),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak});}
|
||||
E.push({k:'t',prem:!!t.premium&&t.city==='hkg',pref:t.pref||'normal',lab:labOf(N_('{net} transit'),'net',NET[t.net].name),id:t.id,city:t.city,cap:Math.min(liveCap(PORT[t.tier].g,t.city,t.site,t.n)*lagF(t),TRX&&TRX.cap[t.net]!==undefined?TRX.cap[t.net]:Infinity),used:0,rank:3,ok:n=>!(depeer&&t.net==='cog'&&n==='ggl')&&n!==leak});}
|
||||
// `nets`: every network ok() can say yes to, so it need not be asked about the other hundred.
|
||||
for(const c in S.ixp){const ct=ixCity(c);if(!(popUp(ct)||remote.includes(ct))||(S.ev.ixdown&&S.ev.ixdown[c]>day)||!liveN(ct,(S.ixSite||{})[c],(S.ixn||{})[c]))continue;const set=ixSessions(c);R2.sessions+=set.size;
|
||||
E.push({k:'ix',pref:(S.ixPref&&S.ixPref[c])||'normal',lab:tr('{ix} peering',{ix:ixName(c)}),id:c,city:ct,cap:ixCap(c),used:0,rank:2,ok:n=>set.has(n)});}
|
||||
for(const p of S.pni){if(!popUp(p.city)||!liveN(p.city,p.site,p.n))continue;R2.sessions++;E.push({k:'p',pnc:!!NET[p.net].cn,pref:p.pref||'normal',lab:tr('PNI with {net}',{net:NET[p.net].name}),id:p.id,city:p.city,cap:liveCap(PORT[p.tier].g,p.city,p.site,p.n)*lagF(p)*(p.sacrif?0.5:1),used:0,rank:1,ok:n=>n===p.net||!!(NET[n].up&&NET[n].up.includes(p.net))});}
|
||||
for(const c of S.caches){if(!popUp(c.city)||siteDown(c.city,c.site==='b'?'b':'a'))continue;E.push({k:'c',pref:'normal',lab:tr('{name} cache',{name:NET[c.net].cache.name}),id:c.id,city:c.city,cap:CACHE_CAP,used:0,rank:0,ok:n=>n===c.net});}
|
||||
E.push({k:'ix',pref:(S.ixPref&&S.ixPref[c])||'normal',lab:labOf(N_('{ix} peering'),'ix',ixName(c)),id:c,city:ct,cap:ixCap(c),used:0,rank:2,ok:n=>set.has(n),nets:set});}
|
||||
for(const p of S.pni){if(!popUp(p.city)||!liveN(p.city,p.site,p.n))continue;R2.sessions++;E.push({k:'p',pnc:!!NET[p.net].cn,pref:p.pref||'normal',lab:labOf(N_('PNI with {net}'),'net',NET[p.net].name),id:p.id,city:p.city,cap:liveCap(PORT[p.tier].g,p.city,p.site,p.n)*lagF(p)*(p.sacrif?0.5:1),used:0,rank:1,ok:n=>n===p.net||!!(NET[n].up&&NET[n].up.includes(p.net)),nets:PNI_NETS[p.net]});}
|
||||
for(const c of S.caches){if(!popUp(c.city)||siteDown(c.city,c.site==='b'?'b':'a'))continue;E.push({k:'c',pref:'normal',lab:labOf(N_('{name} cache'),'name',NET[c.net].cache.name),id:c.id,city:c.city,cap:CACHE_CAP,used:0,rank:0,ok:n=>n===c.net,nets:[c.net]});}
|
||||
// After an update adds networks, a free courtesy route reaches the new ones you have no other way to (#46).
|
||||
R2.graceNets=0;if(S.grace&&S.grace.until>day){const gs=new Set(S.grace.nets.filter(n=>NET[n]&&!E.some(e=>e.k!=='c'&&e.ok(n)))),hc=popUp(S.home)?S.home:pops.find(popUp);
|
||||
R2.graceNets=gs.size;if(gs.size&&hc)E.push({k:'ix',pref:'normal',lab:tr('Courtesy route to new networks'),id:'~grace',city:hc,cap:1e9,used:0,rank:2,ok:n=>gs.has(n)});}
|
||||
R2.graceNets=gs.size;if(gs.size&&hc)E.push({k:'ix',pref:'normal',lab:tr('Courtesy route to new networks'),id:'~grace',city:hc,cap:1e9,used:0,rank:2,ok:n=>gs.has(n),nets:gs});}
|
||||
{const rp=ev.rpki&&ev.rpki.until>day?new Set(ev.rpki.nets):null;if(rp)for(const e of E){if(e.k==='c')continue;const o=e.ok;e.ok=n=>!rp.has(n)&&o(n);}}
|
||||
for(const n of NETS){R2.reachable[n.id]=E.some(e=>e.rank>0&&e.ok(n.id));if(R2.reachable[n.id])R2.reach+=NSH[n.id];}
|
||||
// ok() cannot change during one compute, so ask each exit once per network, not once per flow and rank.
|
||||
// okBy[net] lists the exits that reach it in E's order, like E.filter(e=>e.ok(net)).
|
||||
const okBy={};for(const id of NET_IDS)okBy[id]=[];
|
||||
const ekN={};for(const e of E){e.ek=e.k+':'+e.id;ekN[e.ek]=(ekN[e.ek]||0)+1;}
|
||||
// dup: shares its key with another exit (a hand-edited save), so R.egDesc shows whichever pushed last.
|
||||
for(const e of E){e.desc={lab:e.lab,city:e.city,k:e.k};e.dup=ekN[e.ek]>1;e.told=false;e.hp=e.pref==='high'?0:1;e.ci=CIDX[e.city];e.cn=cnCity(e.city);e.vis=0;for(const n of e.nets||NET_IDS){const L=okBy[n];if(L&&L[L.length-1]!==e&&e.ok(n))L.push(e);}}
|
||||
for(const n of NETS){R2.reachable[n.id]=okBy[n.id].some(e=>e.rank>0);if(R2.reachable[n.id])R2.reach+=NSH[n.id];}
|
||||
const cacheNets=new Set(S.caches.filter(c=>popUp(c.city)).map(c=>c.net));
|
||||
const viral=(ev.viral>day?1.25:1)*(ev.php&&ev.php>day?0.7:1);
|
||||
const flows=[];
|
||||
// Every flow has the same shape and carries what routing asks about it again and again (nj: its network's index).
|
||||
const NN=NETS.length,flows=[],flow=(c,ci,cn,j,rem,cache,junk)=>{const n=NETS[j];flows.push({c,n:n.id,rem,cache,junk,ci,cn,ncn:!!n.cn,nj:j,nr:junk?NN:j});};
|
||||
// Customer demand per city, added up in S.biz order (what filtering S.biz for each city would give).
|
||||
const bizBw={};for(const b of S.biz){const T=BIZ_T[b.type];if(!T.l2&&!T.fiber&&(!T.event||eventLive(b))){const v=bizBw[b.city];bizBw[b.city]=(v===undefined?0:v)+b.bw;}}
|
||||
// Traffic shares by network index, and their sums, for each share table (and with Russia's throttle).
|
||||
const shArr=new Map(),shSum=new Map(),DEMTO=new Float64Array(NN);
|
||||
for(const c of Object.keys(S.pops)){
|
||||
const p=S.pops[c],SH=cnCity(c)?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cnCity(c)&&ev.golden>day?1.4:1);const biz=S.biz.filter(b=>b.city===c&&!BIZ_T[b.type].l2&&!BIZ_T[b.type].fiber&&(!BIZ_T[b.type].event||eventLive(b))).reduce((a,b)=>a+b.bw,0);const d0=eye+biz;
|
||||
const p=S.pops[c],ci=CIDX[c],cn=cnCity(c),SH=cn?NSH_CN:ruCity(c)?NSH_RU:CITY[c].kr&&S.krExit?NSH_KRX:NSH;const eye=(p.bb?p.bb.d:0)*viral*(cn&&ev.golden>day?1.4:1);const biz=bizBw[c]??0;const d0=eye+biz;
|
||||
// Goggle video is throttled in Russia (#70): people there get half of it, so they ask for half. It is not
|
||||
// traffic you failed to deliver, and it does not cross your links only to be thrown away.
|
||||
const thr=n=>n==='ggl'&&ruCity(c)?0.5:1,d=d0*NETS.reduce((t,n)=>t+(SH[n.id]||0)*thr(n.id),0)/(NETS.reduce((t,n)=>t+(SH[n.id]||0),0)||1);
|
||||
const ru=ruCity(c),thr=n=>n==='ggl'&&ru?0.5:1;let sa=shArr.get(SH),sm=shSum.get(SH);if(!sa){shArr.set(SH,sa=NETS.map(n=>SH[n.id]||0));shSum.set(SH,sm=[]);}
|
||||
const tt=sm[+ru]||(sm[+ru]=[NETS.reduce((t,n,j)=>t+sa[j]*thr(n.id),0),NETS.reduce((t,n,j)=>t+sa[j],0)]),d=d0*tt[0]/(tt[1]||1);
|
||||
R2.cityEye[c]=eye;R2.cityDem[c]=d;R2.citySrv[c]=0;R2.demand+=d;
|
||||
for(const n of NETS)R2.demTo[n.id]=(R2.demTo[n.id]||0)+d0*(SH[n.id]||0)*thr(n.id);
|
||||
for(let j=0;j<NN;j++)DEMTO[j]=(DEMTO[j]||0)+d0*sa[j]*thr(NETS[j].id);
|
||||
if(!popUp(c))continue;
|
||||
// A shaped attack: `rtbh` is the player pulling the plug on the victim IP (junk gone, customer dark too);
|
||||
// `edge` is the crude RouteScript `blackhole ddos` filter (junk gone, 10% of real traffic with it). Flowspec
|
||||
|
|
@ -1766,95 +1793,143 @@ function compute(){
|
|||
dd=atk.gbps*mult;
|
||||
if(en.k==='p'){const p=S.pni.find(x=>x.id===en.id);if(p&&p.sacrif)dd=Math.min(dd,liveCap(PORT[p.tier].g,p.city,p.site,p.n)*0.9);}}
|
||||
const bh=rtbh||edge;
|
||||
if(dd>0)for(const n of NETS)flows.push({c,n:n.id,rem:dd*NSH[n.id],junk:true});
|
||||
if(dd>0)for(let j=0;j<NN;j++)flow(c,ci,cn,j,dd*NSH[NETS[j].id],false,true);
|
||||
if(edge)R2.teBlack+=atk.gbps*0.15+d*0.1;if(rtbh)R2.teBlack+=atk.gbps+d;
|
||||
R2.cityBlocked=R2.cityBlocked||{};
|
||||
const mtuH=ev.pmtud&&ev.pmtud.until>day?ev.pmtud:null,kr=CITY[c].kr;
|
||||
for(const n of NETS){const a=d0*(SH[n.id]||0)*thr(n.id)*(rtbh?0:edge?0.9:1)*(mtuH&&mtuH.net===n.id?mtuH.f:1)*(kr&&ev.krroute>day&&n.id==='fbk'?0.8:1);if(a<=0)continue;
|
||||
if(cacheNets.has(n.id)){flows.push({c,n:n.id,rem:a*0.85,cache:true});flows.push({c,n:n.id,rem:a*0.15});}
|
||||
else flows.push({c,n:n.id,rem:a});}
|
||||
for(let j=0;j<NN;j++){const n=NETS[j],a=d0*sa[j]*thr(n.id)*(rtbh?0:edge?0.9:1)*(mtuH&&mtuH.net===n.id?mtuH.f:1)*(kr&&ev.krroute>day&&n.id==='fbk'?0.8:1);if(a<=0)continue;
|
||||
if(cacheNets.has(n.id)){flow(c,ci,cn,j,a*0.85,true,false);flow(c,ci,cn,j,a*0.15,false,false);}
|
||||
else flow(c,ci,cn,j,a,false,false);}
|
||||
}
|
||||
const res={},eload={},nres={};for(const k in edges)res[k]=edges[k].cap;for(const c of pops){nres[c]=nodeCap(c);R2.nodeCap[c]=nres[c];}
|
||||
if(Object.keys(S.pops).length)for(let j=0;j<NN;j++)R2.demTo[NETS[j].id]=DEMTO[j];
|
||||
/* While routing, each edge keeps its own room (res) and load (ld). Routers only exist in POPs (HAS): their room,
|
||||
load and served traffic are kept per city index. What crosses each edge (R.ef) is added up by egress, and in
|
||||
arrays by network (then 'junk' and 'l2vpn') and by source city, each key in the order it first got traffic. */
|
||||
const NRES=new Float64Array(NC),HAS=new Uint8Array(NC),NLOAD=new Float64Array(NC),NSEEN=new Uint8Array(NC),NORD=[],SRV=new Float64Array(NC);
|
||||
for(const k in edges)edges[k].res=edges[k].cap;for(const c of pops){const i=CIDX[c];NRES[i]=nodeCap(c);HAS[i]=1;R2.nodeCap[c]=NRES[i];}
|
||||
const nodeTake=(i,a)=>{NRES[i]-=a;if(!NSEEN[i]){NSEEN[i]=1;NORD.push(i);}NLOAD[i]=(NLOAD[i]||0)+a;};
|
||||
const NKN=NN+2,ACN=new Float64Array(NE*NKN),SEN=new Uint8Array(NE*NKN),ACD=new Float64Array(NE*NC),SED=new Uint8Array(NE*NC),EL=[];
|
||||
const carry=(l,eg,nr,ci,a)=>{let t=l.tr;if(!t){t=l.tr={g:new Map(),n:[],d:[]};EL.push(l);}t.g.set(eg,(t.g.get(eg)||0)+a);
|
||||
let k=l.i*NKN+nr;if(!SEN[k]){SEN[k]=1;t.n.push(nr);}ACN[k]=(ACN[k]||0)+a;k=l.i*NC+ci;if(!SED[k]){SED[k]=1;t.d.push(ci);}ACD[k]=(ACD[k]||0)+a;};
|
||||
R2.l2route={};R2.l2split={};
|
||||
const l2walk=(sp,A,B)=>{const path=[],ns=[B];let v=B;while(v!==A){const l=sp.prev[v];path.push(l);v=l.a===v?l.b:l.a;ns.push(v);}return {path,ns};};
|
||||
/* Scenic routing (#28). "Busy" is judged without the customer's own traffic, or it flees its own load and
|
||||
flips paths every day. Two paths that are about as quiet share the load, and yesterday's choice is kept
|
||||
unless today's is clearly better. */
|
||||
const l2Routes=(A,B,b)=>{const m=b.route||'normal';
|
||||
if(m!=='scenic')return [{...l2walk(m==='fast'?dijk(A,'fast'):SP[A],A,B),share:1}];
|
||||
const ek='l2:'+b.id,own=e=>(R.ef&&R.ef[e.id]&&R.ef[e.id].eg[ek])||0;
|
||||
const wf=e=>{let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;return e.w*(1+10*(e.cap?Math.max(0,ld-own(e))/e.cap:0));};
|
||||
const fastSP={},divMemo={},cityIds=ni=>ni.map(i=>CITIES[i].id);
|
||||
// disjointRoutes() over today's live links, on city indices: the links are listed per city once, not twice per customer.
|
||||
const LA=[];for(const l of live){const ai=CIDX[l.a],bi=CIDX[l.b];(LA[ai]||(LA[ai]=[])).push([bi,l]);(LA[bi]||(LA[bi]=[])).push([ai,l]);}
|
||||
const srlg=l=>l.kind==='vxc'?'fab:'+l.prov:(l.trench||l.id);
|
||||
const bfsI=(a,b,skip)=>{const prev=[],seen=new Uint8Array(NC),q=[a];seen[a]=1;
|
||||
for(let h=0;h<q.length;){const u=q[h++];if(u===b)break;for(const [v,l] of LA[u]||[])if(!seen[v]&&!(skip&&skip.has(srlg(l)))){seen[v]=1;prev[v]=l;q.push(v);}}
|
||||
if(!seen[b])return null;const path=[];let v=b;while(v!==a){const l=prev[v];path.push(l);v=CIDX[l.a]===v?CIDX[l.b]:CIDX[l.a];}return path;};
|
||||
const disjointI=(A,B)=>{const a=CIDX[A],b=CIDX[B],p1=bfsI(a,b,null);return !!p1&&!!bfsI(a,b,new Set(p1.map(srlg)));};
|
||||
for(const k in edges){const e=edges[k];let ld=0;for(const l of e.links)ld+=(R.load&&R.load[l.id])||0;e.pl=ld;}
|
||||
const l2Routes=(A,B,b)=>{const m=b.route||'normal',Ai=CIDX[A],Bi=CIDX[B];
|
||||
if(m!=='scenic')return [{...walkI(m==='fast'?(fastSP[A]||(fastSP[A]=dijkstra(adj,Ai,wLat))).P:SPP[A],Ai,Bi),share:1}];
|
||||
const ek='l2:'+b.id,own=e=>(R.efg&&R.efg[e.id]&&R.efg[e.id].get(ek))||0;
|
||||
const wf=e=>e.w*(1+10*(e.cap?Math.max(0,e.pl-own(e))/e.cap:0));
|
||||
const cost=r=>r.path.reduce((x,e)=>x+wf(e),0)*r.share;
|
||||
const s1=dijkstra(adj,A,wf,null,B);if(s1.dist[B]===undefined)return [{...l2walk(SP[A],A,B),share:1}];
|
||||
const p1=l2walk(s1,A,B),c1=cost({path:p1.path,share:1}),used=new Set(p1.path.map(e=>e.id));let pick2=[{...p1,share:1}];
|
||||
const s2=dijkstra(adj,A,wf,(v,e)=>used.has(e.id),B);
|
||||
if(s2.dist[B]!==undefined){const p2=l2walk(s2,A,B);if(cost({path:p2.path,share:1})<=c1*1.15)pick2=[{...p1,share:0.5},{...p2,share:0.5}];}
|
||||
const s1=dijkstra(adj,Ai,wf,null,Bi);if(s1.D[Bi]===Infinity)return [{...walkI(SPP[A],Ai,Bi),share:1}];
|
||||
const p1=walkI(s1.P,Ai,Bi),c1=cost({path:p1.path,share:1}),used=new Set(p1.path.map(e=>e.id));let pick2=[{...p1,share:1}];
|
||||
const s2=dijkstra(adj,Ai,wf,(v,e)=>used.has(e.id),Bi);
|
||||
if(s2.D[Bi]!==Infinity){const p2=walkI(s2.P,Ai,Bi);if(cost({path:p2.path,share:1})<=c1*1.15)pick2=[{...p1,share:0.5},{...p2,share:0.5}];}
|
||||
const key=b.id+'>'+A+'>'+B,old=R.l2route&&R.l2route[key];let out=pick2;
|
||||
if(old&&old.every(r=>r.keys.every(k=>edges[k]))){const prev=old.map(r=>{const path=r.keys.map(k=>edges[k]);return {path,ns:r.ns,share:r.share};});
|
||||
if(old&&old.every(r=>r.keys.every(k=>edges[k]))){const prev=old.map(r=>{const path=r.keys.map(k=>edges[k]);return {path,ni:r.ns.map(c=>CIDX[c]),share:r.share};});
|
||||
if(prev.reduce((x,r)=>x+cost(r),0)<=pick2.reduce((x,r)=>x+cost(r),0)*1.1)out=prev;}
|
||||
R2.l2route[key]=out.map(r=>({keys:r.path.map(e=>e.id),ns:r.ns,share:r.share}));return out;};
|
||||
R2.l2route[key]=out.map(r=>({keys:r.path.map(e=>e.id),ns:cityIds(r.ni),share:r.share}));return out;};
|
||||
for(const b of S.biz){if(!BIZ_T[b.type].l2)continue;
|
||||
// An SD-WAN is hub-and-spoke: one circuit from the first site to each of the others.
|
||||
const pairs=b.sites?b.sites.slice(1).map(x=>[b.sites[0],x]):[[b.city,b.city2]];let minF=1,maxLat=0,tot=0,noPath=false;
|
||||
for(const [A,B] of pairs){let amt=0;
|
||||
if(popUp(A)&&popUp(B)&&SP[A]&&SP[A].dist[B]!==undefined){
|
||||
const ek='l2:'+b.id;R2.egDesc[ek]={lab:b.sites?tr('SD-WAN for {name}',{name:b.name}):tr('L2VPN for {name}',{name:b.name}),city:A,k:'l2'};
|
||||
if(popUp(A)&&popUp(B)&&SPD[A]&&SPD[A][CIDX[B]]<Infinity){
|
||||
const ek='l2:'+b.id;R2.egDesc[ek]={lab:labOf(b.sites?N_('SD-WAN for {name}'):N_('L2VPN for {name}'),'name',b.name),city:A,k:'l2'};
|
||||
const routes=l2Routes(A,B,b);if(routes.length>1)R2.l2split[b.id]=routes.length;
|
||||
for(const {path,ns,share} of routes){let a=b.bw*share;for(const l of path)a=Math.min(a,res[l.id]);for(const n of ns)if(nres[n]!==undefined)a=Math.min(a,nres[n]);a=Math.max(0,a);amt+=a;maxLat=Math.max(maxLat,path.reduce((x,e)=>x+e.lat,0)+path.length*0.05);
|
||||
for(const n of ns)if(nres[n]!==undefined){nres[n]-=a;R2.nodeLoad[n]=(R2.nodeLoad[n]||0)+a;}
|
||||
for(const l of path){res[l.id]-=a;eload[l.id]=(eload[l.id]||0)+a;const rec=R2.ef[l.id]||(R2.ef[l.id]={eg:{},net:{},dst:{}});rec.eg[ek]=(rec.eg[ek]||0)+a;rec.net.l2vpn=(rec.net.l2vpn||0)+a;rec.dst[B]=(rec.dst[B]||0)+a;}}}
|
||||
for(const {path,ni,share} of routes){let a=b.bw*share;for(const l of path)a=Math.min(a,l.res);for(const i of ni)if(HAS[i])a=Math.min(a,NRES[i]);a=Math.max(0,a);amt+=a;maxLat=Math.max(maxLat,path.reduce((x,e)=>x+e.lat,0)+path.length*0.05);
|
||||
for(const i of ni)if(HAS[i])nodeTake(i,a);
|
||||
for(const l of path){l.res-=a;l.ld+=a;carry(l,ek,NN+1,CIDX[B],a);}}}
|
||||
else noPath=true;
|
||||
minF=Math.min(minF,amt/b.bw);tot+=amt;}
|
||||
R2.l2lat[b.id]=noPath?Infinity:maxLat;R2.l2[b.id]=b.bw*minF;R2.egT.l2=(R2.egT.l2||0)+tot;if((b.reqs||[]).includes('diverse'))R2.div[b.id]=diversePaths(b.city,b.city2);}
|
||||
const TE=!!(S.te&&S.te.on),TR=teRules();R2.teMoved=0;const teCache={},SPILL=TR&&TR.spill?TR.spill:1;
|
||||
const spPath=(sp,src,dst)=>{const path=[],ns=[dst];let v=dst;while(v!==src){const l=sp.prev[v];path.push(l);v=l.a===v?l.b:l.a;ns.push(v);}return {path,ns};};
|
||||
const altPath=(src,dst,base)=>{const key=src+'>'+dst,c0=teCache[key];
|
||||
if(c0===false)return null;if(c0&&c0.path.every(l=>res[l.id]>1e-3)&&c0.ns.every(n=>nres[n]===undefined||nres[n]>1e-3))return c0;
|
||||
const {dist,prev}=dijkstra(adj,src,wW,(v,e)=>res[e.id]<=1e-3||(nres[v]!==undefined&&nres[v]<=1e-3),dst);
|
||||
if(dist[dst]===undefined||dist[dst]>2*base+60){teCache[key]=false;return null;}
|
||||
const P=spPath({prev},src,dst);teCache[key]=P;return P;};
|
||||
R2.l2lat[b.id]=noPath?Infinity:maxLat;R2.l2[b.id]=b.bw*minF;R2.egT.l2=(R2.egT.l2||0)+tot;
|
||||
// Same answer as diversePaths(), which would rebuild today's live links for every customer.
|
||||
if((b.reqs||[]).includes('diverse')){const k=b.city+'>'+b.city2;R2.div[b.id]=divMemo[k]??(divMemo[k]=disjointI(b.city,b.city2));}}
|
||||
const TE=!!(S.te&&S.te.on),TR=teRules();R2.teMoved=0;const teCache=new Map(),SPILL=TR&&TR.spill?TR.spill:1;
|
||||
const altPath=(src,dst,base)=>{const key=src*NC+dst,c0=teCache.get(key);
|
||||
if(c0===false)return null;if(c0&&c0.path.every(l=>l.res>1e-3)&&c0.ni.every(i=>!HAS[i]||NRES[i]>1e-3))return c0;
|
||||
const {D,P}=dijkstra(adj,src,wW,(v,e)=>e.res<=1e-3||(HAS[v]&&NRES[v]<=1e-3),dst);
|
||||
if(D[dst]===Infinity||D[dst]>2*base+60){teCache.set(key,false);return null;}
|
||||
const Q=walkI(P,src,dst);teCache.set(key,Q);return Q;};
|
||||
const base=e=>e.pref==='low'?4:e.rank;
|
||||
const eff=(e,n)=>{let r=base(e);if(TR){if(e.k!=='c'&&TR.drain.has(e.city))r=4.6;const o=TR.net[n];if(o){if(o.prefer===e.k)r=0.5;else if(o.avoid===e.k)r=4.5;}}return r;};
|
||||
const RANKS=TR?[0,0.5,1,2,3,4,4.5,4.6]:[0,1,2,3,4];
|
||||
// Each network's exits by the rank they route at (RouteScript can move an exit per network), in E's order.
|
||||
// Each list also knows whether it holds a preferred exit (hi) and its exits by city (at), in list order.
|
||||
const byRank={};for(const id of NET_IDS){const m=byRank[id]={};for(const e of okBy[id]){const r=TR?eff(e,id):base(e);(m[r]||(m[r]=[])).push(e);}
|
||||
for(const r in m){const L=m[r];L.hi=L.some(e=>e.hp===0);L.at=new Map();for(const e of L){const h=L.at.get(e.ci);if(h)h.push(e);else L.at.set(e.ci,[e]);}}}
|
||||
// The flow being routed, and from its POP: distances, arriving edges and the paths walked so far, by city index.
|
||||
let f=null,Dv=null,Pv=null,PP=null,vis=0;const walked=[],G=[],NEG=[];
|
||||
// An exit the flow can still try: not visited yet, not full when the flow started, and reachable from the POP.
|
||||
const usable=e=>e.vis!==vis&&e.used<e.cap&&Dv[e.ci]<Infinity,byDist=(a,b)=>a.hp-b.hp||Dv[a.ci]-Dv[b.ci];
|
||||
// Push up to `want` along one path to exit e; returns what fitted.
|
||||
const push=(e,P,want,keep=0)=>{const path=P.path,ni=P.ni;let amt=want;
|
||||
for(const l of path)amt=Math.min(amt,l.res-l.cap*keep);for(const i of ni)if(HAS[i])amt=Math.min(amt,NRES[i]);
|
||||
if(amt<=1e-6)return 0;
|
||||
for(const i of ni)if(HAS[i])nodeTake(i,amt);
|
||||
const ek=e.ek,nr=f.nr,ci=f.ci;if(!e.told||e.dup){R2.egDesc[ek]=e.desc;e.told=true;}
|
||||
for(const l of path){l.res-=amt;l.ld+=amt;carry(l,ek,nr,ci,amt);}
|
||||
e.used+=amt;f.rem-=amt;
|
||||
if(!f.junk){let ok=amt;const cf=f.cn,ce=e.cn,cn=f.ncn;
|
||||
if(cf!==ce||(cf&&!cn)||(!cf&&cn&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);}
|
||||
SRV[f.ci]+=ok;R2.served+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const m=R2.tNet[e.id]||(R2.tNet[e.id]={});m[f.n]=(m[f.n]||0)+ok;}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=NEG[f.nj]||(NEG[f.nj]=R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok;}
|
||||
return amt;
|
||||
};
|
||||
// Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths
|
||||
// with free capacity, as long as they are no more than twice as long.
|
||||
const send=(e,want)=>{
|
||||
let room=Math.min(want,f.rem,e.cap-e.used);if(room<=1e-6)return;
|
||||
room-=push(e,PP[e.ci]||(PP[e.ci]=walkI(Pv,f.ci,e.ci)),room,TE&&SPILL<1?1-SPILL:0);
|
||||
if(TE&&room>1e-6&&f.rem>1e-6&&e.used<e.cap&&e.city!==f.c)for(let k=0;k<2&&room>1e-6;k++){const P=altPath(f.ci,e.ci,Dv[e.ci]);if(!P)break;const m=push(e,P,Math.min(room,e.cap-e.used));if(m<=1e-6)break;room-=m;R2.teMoved+=m;}
|
||||
};
|
||||
// Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over
|
||||
// them by free capacity (like several transits in one city), then top up in order if one fills.
|
||||
const sendGroup=g=>{for(const e of g)e.vis=vis;
|
||||
if(g.length>1){const room=g.map(e=>Math.max(0,e.cap-e.used)),tot=room.reduce((a,b)=>a+b,0),want=f.rem;if(tot>1e-6)g.forEach((e,k)=>send(e,want*room[k]/tot));}
|
||||
for(const e of g){if(f.rem<=1e-6)break;send(e,f.rem);}};
|
||||
for(const rank of RANKS){
|
||||
const Er=TR?E:E.filter(e=>base(e)===rank);if(!Er.length)continue;const sorted={};
|
||||
for(const f of flows){
|
||||
if(TR?!E.length:!E.some(e=>base(e)===rank))continue;
|
||||
for(f of flows){
|
||||
if(f.rem<=1e-6||(rank===0&&!f.cache))continue;
|
||||
const sp=SP[f.c];
|
||||
const srt=sorted[f.c]||(sorted[f.c]=Er.filter(e=>sp.dist[e.city]!==undefined).sort((a,b)=>(a.pref==='high'?0:1)-(b.pref==='high'?0:1)||sp.dist[a.city]-sp.dist[b.city]));
|
||||
const cands=srt.filter(e=>e.used<e.cap&&e.ok(f.n)&&(!TR||eff(e,f.n)===rank));
|
||||
// Exits with the same preference and the same IGP distance form an ECMP group: spread the flow over
|
||||
// them by free capacity (like several transits in one city), then top up in order if one fills.
|
||||
// Push up to `want` along one path to exit e; returns what fitted.
|
||||
const push=(e,P,want,keep=0)=>{const path=P.path,ns=P.ns;let amt=want;
|
||||
for(const l of path)amt=Math.min(amt,res[l.id]-l.cap*keep);for(const n of ns)if(nres[n]!==undefined)amt=Math.min(amt,nres[n]);
|
||||
if(amt<=1e-6)return 0;
|
||||
for(const n of ns)if(nres[n]!==undefined){nres[n]-=amt;R2.nodeLoad[n]=(R2.nodeLoad[n]||0)+amt;}
|
||||
const ek=e.k+':'+e.id;R2.egDesc[ek]={lab:e.lab,city:e.city,k:e.k};
|
||||
for(const l of path){res[l.id]-=amt;eload[l.id]=(eload[l.id]||0)+amt;const rec=R2.ef[l.id]||(R2.ef[l.id]={eg:{},net:{},dst:{}});rec.eg[ek]=(rec.eg[ek]||0)+amt;const nk=f.junk?'junk':f.n;rec.net[nk]=(rec.net[nk]||0)+amt;rec.dst[f.c]=(rec.dst[f.c]||0)+amt;}
|
||||
e.used+=amt;f.rem-=amt;
|
||||
if(!f.junk){let ok=amt;const fc=cnCity(f.c),ec=cnCity(e.city),nc=!!NET[f.n].cn;
|
||||
if(fc!==ec||(fc&&!nc)||(!fc&&nc&&e.k==='t')){const prem=(e.k==='t'&&e.prem)||(e.k==='p'&&e.pnc)||path.some(x=>x.links&&x.links.some(y=>y.premium));const loss=prem?0.03:(ev.gfw>day?0.35:0.2);R2.gfwLost+=amt*loss;R2.gfwCross+=amt;ok=amt*(1-loss);}
|
||||
R2.citySrv[f.c]+=ok;R2.served+=ok;if(e.rank<=2)R2.peered+=ok;if(e.k==='t'){const m=R2.tNet[e.id]||(R2.tNet[e.id]={});m[f.n]=(m[f.n]||0)+ok;}R2.egT[e.k]=(R2.egT[e.k]||0)+ok;const ne=R2.netEg[f.n]||(R2.netEg[f.n]={c:0,p:0,ix:0,t:0});ne[e.k]+=ok;}
|
||||
return amt;
|
||||
};
|
||||
// Shortest path first. With Auto-TE, whatever does not fit spills onto up to two alternate paths
|
||||
// with free capacity, as long as they are no more than twice as long.
|
||||
const send=(e,want)=>{
|
||||
let room=Math.min(want,f.rem,e.cap-e.used);if(room<=1e-6)return;
|
||||
room-=push(e,spPath(sp,f.c,e.city),room,TE&&SPILL<1?1-SPILL:0);
|
||||
if(TE&&room>1e-6&&f.rem>1e-6&&e.used<e.cap&&e.city!==f.c)for(let k=0;k<2&&room>1e-6;k++){const P=altPath(f.c,e.city,sp.dist[e.city]);if(!P)break;const m=push(e,P,Math.min(room,e.cap-e.used));if(m<=1e-6)break;room-=m;R2.teMoved+=m;}
|
||||
};
|
||||
const gk=e=>(e.pref==='high'?0:1);
|
||||
for(let i=0;i<cands.length&&f.rem>1e-6;){
|
||||
let j=i+1;while(j<cands.length&&gk(cands[j])===gk(cands[i])&&Math.abs(sp.dist[cands[j].city]-sp.dist[cands[i].city])<1e-6)j++;
|
||||
const g=cands.slice(i,j);i=j;
|
||||
if(g.length>1){const room=g.map(e=>Math.max(0,e.cap-e.used)),tot=room.reduce((a,b)=>a+b,0),want=f.rem;if(tot>1e-6)g.forEach((e,k)=>send(e,want*room[k]/tot));}
|
||||
for(const e of g){if(f.rem<=1e-6)break;send(e,f.rem);}
|
||||
const lst=byRank[f.n][rank];if(!lst)continue;
|
||||
Dv=SDi[f.ci];Pv=SPi[f.ci];PP=walked[f.ci]||(walked[f.ci]=[]);vis++;
|
||||
/* Groups are tried nearest first, preferred exits before the rest, in the order a stable sort of the usable
|
||||
exits gives. Exits only fill up once tried, so the usable ones stay the same until then. Nearly every flow
|
||||
fits in its first group: find that one with a scan (nothing is visited yet), and sort only what is left
|
||||
when it does not fit. Most often the group is the POP's own exits: with no preferred exit on the list
|
||||
and no other city at distance 0, the usable ones here are exactly the first group, already in order. */
|
||||
G.length=0;
|
||||
if(!lst.hi&&ALONE[f.ci]){const here=lst.at.get(f.ci);if(here)for(const e of here)if(e.used<e.cap)G.push(e);}
|
||||
if(!G.length){
|
||||
let bh=2,bd=Infinity;for(const e of lst)if(e.used<e.cap){const d=Dv[e.ci];if(d<Infinity&&(e.hp<bh||(e.hp===bh&&d<bd))){bh=e.hp;bd=d;}}
|
||||
if(bh>1)continue;
|
||||
for(const e of lst)if(e.hp===bh&&e.used<e.cap){const d=Dv[e.ci];if(d<Infinity&&d-bd<1e-6)G.push(e);}
|
||||
if(G.length>1)G.sort(byDist);}
|
||||
sendGroup(G);
|
||||
if(f.rem<=1e-6)continue;
|
||||
const rest=lst.filter(usable).sort(byDist);
|
||||
for(let i=0;i<rest.length&&f.rem>1e-6;){
|
||||
let j=i+1;while(j<rest.length&&rest[j].hp===rest[i].hp&&Math.abs(Dv[rest[j].ci]-Dv[rest[i].ci])<1e-6)j++;
|
||||
sendGroup(rest.slice(i,j));i=j;
|
||||
}
|
||||
}
|
||||
}
|
||||
for(const k in edges){const e=edges[k],ld=eload[k]||0;for(const l of e.links)R2.load[l.id]=ld*capOf(l)/e.cap;}
|
||||
for(const i of NORD)R2.nodeLoad[CITIES[i].id]=NLOAD[i];
|
||||
for(const c of Object.keys(S.pops))R2.citySrv[c]=SRV[CIDX[c]];
|
||||
// R.ef is read for the link you inspect: each edge's record is put together the first time it is asked for. Scenic
|
||||
// routing only needs the egress amounts, so R.efg keeps those as they are (not listed, so R reads the same).
|
||||
{const efg={};for(const l of EL){const t=l.tr,i=l.i;let rec=null;efg[l.id]=t.g;
|
||||
Object.defineProperty(R2.ef,l.id,{enumerable:true,configurable:true,get(){if(!rec){rec={eg:{},net:{},dst:{}};for(const [k,v] of t.g)rec.eg[k]=v;
|
||||
for(const j of t.n)rec.net[j<NN?NETS[j].id:j===NN?'junk':'l2vpn']=ACN[i*NKN+j];for(const ci of t.d)rec.dst[CITIES[ci].id]=ACD[i*NC+ci];}return rec;}});}
|
||||
Object.defineProperty(R2,'efg',{value:efg});}
|
||||
for(const k in edges){const e=edges[k],ld=e.ld||0;for(const l of e.links)R2.load[l.id]=ld*capOf(l)/e.cap;}
|
||||
R2.peerShare=R2.served>0?R2.peered/R2.served:0;
|
||||
for(const e of E){if(e.k==='t')R2.useT[e.id]=e.used;else if(e.k==='ix')R2.useIx[e.id]=e.used;else if(e.k==='p')R2.usePni[e.id]=e.used;else R2.useCache[e.id]=e.used;}
|
||||
// money
|
||||
|
|
@ -2883,6 +2958,25 @@ const $=id=>document.getElementById(id);
|
|||
const btn=(label,act,args={},cls='',dis=false,title='')=>`<button class="b ${cls}" data-act="${act}" data-args="${esc(JSON.stringify(args))}"${dis?' disabled':''}${title?` title="${esc(title)}"`:''}>${label}</button>`;
|
||||
const logo=n=>`<span class="logo" style="--c:${n.col}">${initials(n)}</span>`;
|
||||
const barCls=u=>u>=0.9?'bad':u>=0.65?'warn':'';
|
||||
/* Panels are rebuilt from state every tick. Replacing a thousand rows makes the browser style and lay out every one
|
||||
of them again, so patch what changed instead: same HTML, far less work. A button that now does something else, and
|
||||
any form field that changed, is swapped out whole, so a tap that started on the old one still cannot fire it (#44). */
|
||||
const SWAP={INPUT:1,SELECT:1,TEXTAREA:1,OPTION:1};
|
||||
function morph(el,html){const t=document.createElement(el.tagName);t.innerHTML=html;morphKids(el,t);}
|
||||
function sameNode(x,y){if(x.nodeType!==y.nodeType||x.nodeName!==y.nodeName)return false;if(x.nodeType!==1)return true;
|
||||
if(SWAP[x.nodeName])return x.outerHTML===y.outerHTML;
|
||||
return x.getAttribute('data-act')===y.getAttribute('data-act')&&x.getAttribute('data-args')===y.getAttribute('data-args');}
|
||||
function morphKids(a,b){let x=a.firstChild,y=b.firstChild;
|
||||
while(y){const ny=y.nextSibling;
|
||||
if(!x)a.appendChild(y);
|
||||
else if(!sameNode(x,y)){a.replaceChild(y,x);x=y;}
|
||||
else if(x.nodeType===1){if(!SWAP[x.nodeName]){const ya=y.attributes,xa=x.attributes;
|
||||
for(let i=0;i<ya.length;i++){const {name,value}=ya[i];if(x.getAttribute(name)!==value)x.setAttribute(name,value);}
|
||||
for(let i=xa.length-1;i>=0;i--)if(!y.hasAttribute(xa[i].name))x.removeAttribute(xa[i].name);
|
||||
morphKids(x,y);}}
|
||||
else if(x.nodeValue!==y.nodeValue)x.nodeValue=y.nodeValue;
|
||||
x=x&&x.nextSibling;y=ny;}
|
||||
while(x){const nx=x.nextSibling;a.removeChild(x);x=nx;}}
|
||||
function renderAll(){if(isTablet()&&!UI.sel)UI.leftOpen=false;renderHUD();renderLeft();renderPanel();renderHint();renderMega();renderCoach();}
|
||||
function renderMega(){const el=$('mega');if(!el)return;const on=!!(S&&S.ev&&S.ev.php>S.day);if(el.hidden===!on)return;el.hidden=!on;}
|
||||
|
||||
|
|
@ -3000,20 +3094,20 @@ function renderLeft(){checkLayer();
|
|||
h+=`<div class="kv" style="margin-top:8px"><span>${tr('Incidents so far')}</span><b>${S.stats.incidents}</b></div><div class="kv"><span>${tr('Survived with no impact')}</span><b>${S.stats.survived}</b></div>`;
|
||||
}else{
|
||||
h+=`<p class="lead">${tr("Every network on the map. Traffic share is how much of your users' traffic goes to them. Tap a connection to jump to its POP.")}</p>`;
|
||||
if(conns().length)h+=`<div class="btns" style="margin-bottom:8px">${btn(tr('All connections <small>{n}</small>',{n:conns().length}),'connOpen',{},'pink sm')}</div>`;
|
||||
const tl=NETS.filter(n=>n.tail),tlOn=tl.filter(n=>Object.keys(S.ixp).some(c=>ixSessions(c).has(n.id))).length;
|
||||
{const nc=conns().length;if(nc)h+=`<div class="btns" style="margin-bottom:8px">${btn(tr('All connections <small>{n}</small>',{n:nc}),'connOpen',{},'pink sm')}</div>`;}
|
||||
const where=netWhereIdx(),tl=NETS.filter(n=>n.tail),tlOn=tl.filter(n=>where(n.id).some(x=>x[2]==='ix')).length;
|
||||
for(const n of NETS){if(n.tail&&!UI.tailOpen)continue;
|
||||
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="meta">AS${n.asn}</span></div><div class="meta"><span class="tag ${n.type}">${TYPE_L[n.type]}</span> <span class="tag ${n.pol}">${n.pol}</span> · ${tr('{p}% of traffic',{p:(NSH[n.id]*100).toFixed(1)})}${n.price?` · ${tr('transit ${price}/Gbps',{price:(n.price*S.priceMul).toFixed(2)})}`:''}</div><div class="meta">${esc(n.blurb)}</div>${netWhere(n)}</div></div>`;}
|
||||
h+=`<div class="row">${logo(n)}<div class="grow"><div class="nm">${esc(n.name)} <span class="meta">AS${n.asn}</span></div><div class="meta"><span class="tag ${n.type}">${TYPE_L[n.type]}</span> <span class="tag ${n.pol}">${n.pol}</span> · ${tr('{p}% of traffic',{p:(NSH[n.id]*100).toFixed(1)})}${n.price?` · ${tr('transit ${price}/Gbps',{price:(n.price*S.priceMul).toFixed(2)})}`:''}</div><div class="meta">${esc(n.blurb)}</div>${netWhere(n,where)}</div></div>`;}
|
||||
h+=`<div class="row"><div class="grow"><div class="nm">${tr('The long tail')} <span class="meta">${tr('{n} small networks',{n:tl.length})}</span></div><div class="meta">${tr('{p}% of traffic between them, scattered across exchanges. You peer with {n}.',{p:(tl.reduce((a,n)=>a+NSH[n.id],0)*100).toFixed(1),n:tlOn})}</div></div>${btn(UI.tailOpen?tr('Hide'):tr('Show'),'tailTog',{},'ghost sm')}</div>`;
|
||||
}
|
||||
if(h!==UI._lh){UI._lh=h;$('leftBody').innerHTML=h;}
|
||||
if(h!==UI._lh){UI._lh=h;morph($('leftBody'),h);}
|
||||
}
|
||||
function renderPanel(){checkLayer();
|
||||
const P=$('panel');
|
||||
if(!S||!UI.sel){P.hidden=true;return;}
|
||||
P.hidden=false;
|
||||
const scrollEl=$('panelBody').querySelector('.scroll');const st=scrollEl?scrollEl.scrollTop:0;
|
||||
const html=UI.sel.type==='city'?cityPanel(UI.sel.id):linkPanel(UI.sel.id);if(html===UI._ph&&!P.hidden&&$('panelBody').firstChild)return;UI._ph=html;$('panelBody').innerHTML=html;
|
||||
const html=UI.sel.type==='city'?cityPanel(UI.sel.id):linkPanel(UI.sel.id);if(html===UI._ph&&!P.hidden&&$('panelBody').firstChild)return;UI._ph=html;morph($('panelBody'),html);
|
||||
const ns=$('panelBody').querySelector('.scroll');if(ns)ns.scrollTop=st;
|
||||
}
|
||||
function cityPanel(c){
|
||||
|
|
@ -3380,11 +3474,15 @@ function connSection(){const all=conns(),F=UI.cf||{};
|
|||
h+=`</tbody><tfoot><tr><td colspan="4"><b>${trn('{n} connection','{n} connections',rows.length)}</b></td><td class="r"><b>${fmtG(tu)} / ${fmtCap(Math.round(tc))}</b></td><td class="r"><b>${fmt$(tm)}</b></td><td></td></tr></tfoot></table></div></div>`;
|
||||
return h;}
|
||||
// Where you connect to one network, as buttons that jump to the POP (Networks tab).
|
||||
function netWhere(n){const ch=[];
|
||||
for(const t of S.transit)if(t.net===n.id)ch.push([tr('Transit'),t.city,'t']);
|
||||
for(const x of S.pni)if(x.net===n.id)ch.push(['PNI',x.city,'p']);
|
||||
for(const c in S.ixp)if(ixSessions(c).has(n.id))ch.push([ixName(c),ixCity(c),'ix']);
|
||||
for(const c of new Set(S.caches.filter(x=>x.net===n.id).map(x=>x.city)))ch.push([tr('Cache'),c,'c']);
|
||||
// Where you connect to each network, as [label, city, kind]: transit, PNIs, IX sessions, then caches. Built for all
|
||||
// networks at once, so the network list works out each IX port's sessions a single time, not once per network.
|
||||
function netWhereIdx(){const B={t:{},p:{},ix:{},c:{}},add=(k,id,x)=>(B[k][id]||(B[k][id]=[])).push(x);
|
||||
for(const t of S.transit)add('t',t.net,[tr('Transit'),t.city,'t']);
|
||||
for(const x of S.pni)add('p',x.net,['PNI',x.city,'p']);
|
||||
for(const c in S.ixp){const nm=ixName(c),ct=ixCity(c);for(const id of ixSessions(c))add('ix',id,[nm,ct,'ix']);}
|
||||
const seen=new Set();for(const x of S.caches){const k=x.net+'|'+x.city;if(!seen.has(k)){seen.add(k);add('c',x.net,[tr('Cache'),x.city,'c']);}}
|
||||
return id=>[].concat(B.t[id]||[],B.p[id]||[],B.ix[id]||[],B.c[id]||[]);}
|
||||
function netWhere(n,where){const ch=(where||netWhereIdx())(n.id);
|
||||
if(!ch.length)return '';const MAX=6;
|
||||
return `<div class="btns">${ch.slice(0,MAX).map(([l,c,k])=>btn(`${esc(l)} <small>${esc(CITY[c].name)}</small>`,'goConn',{city:c,k},'ghost sm')).join('')}${ch.length>MAX?btn(tr('+{n} more',{n:ch.length-MAX}),'connFor',{net:n.id},'ghost sm'):''}</div>`;}
|
||||
const DTABS=['overview','cust','conn','traffic','infra','lease'];
|
||||
|
|
@ -3454,7 +3552,7 @@ function renderDash(){checkLayer();
|
|||
<div class="panel2"><h3>${tr('Router load')}</h3>${rs.map(({c,u})=>`<div class="row"><div class="grow"><div class="nm">${CITY[c].name} <span class="meta">${(S.pops[c].routers||1)} × ${esc(RG[S.pops[c].rgen||0].n)}</span></div><div class="bar ${barCls(u)}"><i style="width:${Math.min(100,u*100)}%"></i></div></div><b class="num" style="min-width:42px;text-align:right">${pct(u)}</b></div>`).join('')}
|
||||
<h3 style="margin-top:10px">${tr('Your AS')}</h3><div class="kv"><span>${tr('AS number')}</span><b>AS${S.asn}</b></div><div class="kv"><span>${tr('Prefixes')}</span><b>${Math.max(1,Math.ceil(Object.keys(S.pops).length/3))} × /22 IPv4, 1 × /32 IPv6</b></div><div class="kv"><span>${tr('BGP sessions')}</span><b>${R.sessions}</b></div><div class="kv"><span>${tr('Upstreams')}</span><b>${new Set(S.transit.map(t=>t.net)).size}</b></div><div class="kv"><span>${tr('Reach')}</span><b>${pct(R.reach)}</b></div><div class="kv"><span>${tr('Customers')}</span><b>${tr('{n} businesses',{n:S.biz.length})}</b></div></div></div>`;
|
||||
if(DT==='lease')h+=leaseTab();
|
||||
if(h!==UI._dh){UI._dh=h;$('dashCard').innerHTML=h;}
|
||||
if(h!==UI._dh){UI._dh=h;morph($('dashCard'),h);}
|
||||
}
|
||||
function loanSummary(o){return o.model==='transit'?tr('You pay {pct} of your transit bill until {price} is repaid.',{pct:pct(o.cut||0.3),price:fmt$(o.owe||o.amount)}):o.model==='balloon'?tr('Nothing to pay for {n} months. Then everything.',{n:o.term}):tr('{pay}/mo for {n} months.',{pay:fmt$(o.pay),n:o.term})+(o.share?' '+tr('Plus {pct} of your revenue until it is repaid.',{pct:pct(o.share)}):'');}
|
||||
function loanLine(l){const sh=l.share?' · '+tr('plus {pct} of revenue',{pct:pct(l.share)}):'',fee=loanFees(l)?' · '+tr('{price}/mo in extras',{price:fmt$(loanFees(l))}):'';
|
||||
|
|
@ -3753,17 +3851,20 @@ const iconScale=()=>clamp(Math.sqrt(cam.z),0.7,1.35);
|
|||
/* Level of detail (#37): zoomed out the map turns into a network map, with dots for cities, small
|
||||
router pills for your POPs and thinner links. Phones switch a little earlier, the screen is small. */
|
||||
const lodFar=()=>cam.z<(innerWidth<=760?0.95:0.72);
|
||||
function rr(x,y,w,h,r){ctx.beginPath();ctx.moveTo(x+r,y);ctx.arcTo(x+w,y,x+w,y+h,r);ctx.arcTo(x+w,y+h,x,y+h,r);ctx.arcTo(x,y+h,x,y,r);ctx.arcTo(x,y,x+w,y,r);ctx.closePath();}
|
||||
// One native call draws the same rounded box where the browser has it and the corners fit (hundreds per frame).
|
||||
function rr(x,y,w,h,r){ctx.beginPath();if(ctx.roundRect&&2*r<=w&&2*r<=h){ctx.roundRect(x,y,w,h,r);return;}ctx.moveTo(x+r,y);ctx.arcTo(x+w,y,x+w,y+h,r);ctx.arcTo(x+w,y+h,x,y+h,r);ctx.arcTo(x,y+h,x,y,r);ctx.arcTo(x,y,x+w,y,r);ctx.closePath();}
|
||||
// Enough world copies to cover any screen width at any zoom (the map wraps horizontally).
|
||||
function visibleKs(){const ks=[];for(let k=-5;k<=5;k++){const a=toS(0,0,k)[0],b=toS(W,0,k)[0];if(b>-200&&a<CW+200)ks.push(k);}return ks;}
|
||||
const GEO=new Map();
|
||||
/* Parallel waves on the same cable (or in the same trench) draw as one line with a combined label (#19). */
|
||||
// Links drawn as one line share a key; the map spaces lines apart by drawn line, not by link (#64).
|
||||
const gKey=l=>{const pr=l.a<l.b?l.a+'|'+l.b:l.b+'|'+l.a;return l.kind==='wave'?pr+'|'+(l.sub?'c:'+(l.cable||''):'t:'+(l.trench||l.id)):l.id;};
|
||||
const lineIdx=l=>{const ks=[];for(const x of pairLinks(l.a,l.b)){const k=gKey(x);if(!ks.includes(k))ks.push(k);}return ks.indexOf(gKey(l));};
|
||||
const lineIdx=(l,pl)=>{const ks=[];for(const x of pl||pairLinks(l.a,l.b)){const k=gKey(x);if(!ks.includes(k))ks.push(k);}return ks.indexOf(gKey(l));};
|
||||
// pairLinks() for every pair at once (same links, same order), for code that asks about all of them.
|
||||
function pairIdx(){const m=new Map();for(const l of S.links){const k=edgeKey(l),a=m.get(k);if(a)a.push(l);else m.set(k,[l]);}return m;}
|
||||
function linkGroups(){const m=new Map();for(const l of S.links){const key=gKey(l);const g=m.get(key);if(g)g.push(l);else m.set(key,[l]);}return [...m.values()];}
|
||||
function groupLabel(grp,up){const t=grp[0].tier,same=grp.every(x=>x.tier===t),tot=grp.reduce((a,x)=>a+LT[x.tier].g,0);return (same?`${grp.length}×${LT[t].n}`:`${grp.length} × ${fmtCap(tot)}`)+(up.length<grp.length?` · ${up.length}/${grp.length} ${tr('up')}`:'');}
|
||||
function linkGeom(l){const i=lineIdx(l);const key=l.id+'|'+i+'|'+(l.cable||'');const h=GEO.get(key);if(h)return h;
|
||||
function linkGeom(l,pl){const i=lineIdx(l,pl);const key=l.id+'|'+i+'|'+(l.cable||'');const h=GEO.get(key);if(h)return h;
|
||||
let pts=null;if(l.cable){const cp=cablePair(l.cable,l.a,l.b);if(cp){pts=cp.pts.map(p=>p.slice());const same=pairLinks(l.a,l.b).filter(x=>x.cable===l.cable).indexOf(l);if(same>0)for(let j=1;j<pts.length-1;j++){pts[j][1]+=same*5;}}}
|
||||
// Your own subsea cable (#64) follows the shortest commercial cable on the same route, drawn alongside it; with
|
||||
// none, a gentle curve. Its shape must not depend on how many waves already run between the two cities.
|
||||
|
|
@ -3777,6 +3878,9 @@ function linkGeom(l){const i=lineIdx(l);const key=l.id+'|'+i+'|'+(l.cable||'');c
|
|||
function besideLine(sp,d){const c=[0];for(let j=1;j<sp.length;j++)c.push(c[j-1]+Math.hypot(sp[j][0]-sp[j-1][0],sp[j][1]-sp[j-1][1]));const L=c[c.length-1]||1,N=24,out=[];
|
||||
for(let j=0;j<=N;j++){const t=j/N,q=polyAt(sp,c.map(v=>v/L),t),a=polyAt(sp,c.map(v=>v/L),Math.max(0,t-.02)),b=polyAt(sp,c.map(v=>v/L),Math.min(1,t+.02)),dx=b[0]-a[0],dy=b[1]-a[1],n=Math.hypot(dx,dy)||1,f=d*Math.sin(Math.PI*t);out.push([q[0]+dy/n*f,q[1]-dx/n*f]);}return out;}
|
||||
function polyAt(sp,cum,t){let i=1;while(i<cum.length-1&&cum[i]<t)i++;const t0=cum[i-1],t1=cum[i],f=t1>t0?(t-t0)/(t1-t0):0;return [sp[i-1][0]+(sp[i][0]-sp[i-1][0])*f,sp[i-1][1]+(sp[i][1]-sp[i-1][1])*f];}
|
||||
// polyAt() on screen points kept in two arrays (draw() reuses them for every link instead of making new points).
|
||||
function polyAtXY(X,Y,cum,t){let i=1;while(i<cum.length-1&&cum[i]<t)i++;const t0=cum[i-1],t1=cum[i],f=t1>t0?(t-t0)/(t1-t0):0;return [X[i-1]+(X[i]-X[i-1])*f,Y[i-1]+(Y[i]-Y[i-1])*f];}
|
||||
let SX=new Float64Array(64),SY=new Float64Array(64);
|
||||
function segDist(x,y,a,b){const dx=b[0]-a[0],dy=b[1]-a[1],L=dx*dx+dy*dy||1;const t=clamp(((x-a[0])*dx+(y-a[1])*dy)/L,0,1);return Math.hypot(x-a[0]-t*dx,y-a[1]-t*dy);}
|
||||
// `cached`: the cables are already painted into the world layer. Zoomed in, the layer is painted without
|
||||
// them (#49), so they are drawn here every frame instead.
|
||||
|
|
@ -3828,27 +3932,31 @@ function draw(now){
|
|||
// cable systems
|
||||
drawCables(ks);
|
||||
// links
|
||||
const far=lodFar(),PI=pairIdx();
|
||||
for(const grp of linkGroups()){const l=grp[0],many=grp.length>1,up=many?grp.filter(x=>!linkDown(x)):null;
|
||||
const gm=linkGeom(l),cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc';
|
||||
const gm=linkGeom(l,PI.get(edgeKey(l))),cap=many?up.reduce((a,x)=>a+capOf(x),0):capOf(l),load=many?grp.reduce((a,x)=>a+(R.load[x.id]||0),0):(R.load[l.id]||0),u=cap?load/cap:0,df=l.kind==='df',bld=df&&l.ready>day,cut=!bld&&(many?!up.length:linkDown(l))&&!(df&&!(l.ch||[]).length),dark=df&&!bld&&!(l.ch||[]).length,vx=l.kind==='vxc';
|
||||
const sel=UI.sel&&UI.sel.type==='link'&&grp.some(x=>x.id===UI.sel.id);
|
||||
const far=lodFar(),w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)))*sc*(far?0.5:1);
|
||||
const w=(vx?2.2:(2.5+Math.max(...grp.map(tierW))*1.8+(many?Math.min(1.5,(grp.length-1)*0.5):0)))*sc*(far?0.5:1),np=gm.pts.length;
|
||||
if(SX.length<np){SX=new Float64Array(np*2);SY=new Float64Array(np*2);}
|
||||
for(const k of ks){
|
||||
const sp=gm.pts.map(p=>toS(p[0],p[1],k));let mn=Infinity,mx=-Infinity;for(const q of sp){if(q[0]<mn)mn=q[0];if(q[0]>mx)mx=q[0];}
|
||||
// Screen points as toS() gives them, kept in SX/SY.
|
||||
let mn=Infinity,mx=-Infinity;for(let i=0;i<np;i++){const p=gm.pts[i],x=(p[0]+k*W-cam.x)*cam.z+CW/2;SX[i]=x;SY[i]=(p[1]-cam.y)*cam.z+CH/2;if(x<mn)mn=x;if(x>mx)mx=x;}
|
||||
if(mx<-40||mn>CW+40)continue;
|
||||
const path=()=>{ctx.beginPath();ctx.moveTo(sp[0][0],sp[0][1]);for(let i=1;i<sp.length;i++)ctx.lineTo(sp[i][0],sp[i][1]);};
|
||||
const path=()=>{ctx.beginPath();ctx.moveTo(SX[0],SY[0]);for(let i=1;i<np;i++)ctx.lineTo(SX[i],SY[i]);};
|
||||
ctx.lineCap='round';ctx.lineJoin='round';
|
||||
if(sel){ctx.strokeStyle='rgba(255,79,154,.35)';ctx.lineWidth=w+14;path();ctx.stroke();}
|
||||
ctx.strokeStyle='#1E2640';ctx.lineWidth=w+4;ctx.setLineDash(cut?[8,8]:vx?[2,7]:bld?[10,8]:[]);path();ctx.stroke();
|
||||
ctx.strokeStyle=bld?'#C9B27C':dark?'#5D6788':cut?'#FF4D5E':vx?FAB[l.prov].col:l.sub?(u>0.001?utilCol(u):'#7FD8EE'):utilCol(u);ctx.lineWidth=w;ctx.stroke();ctx.setLineDash([]);
|
||||
if(df&&!bld&&!dark){ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=Math.max(1,w*0.25);ctx.setLineDash([1,6]);path();ctx.stroke();ctx.setLineDash([]);}
|
||||
const at=t=>polyAt(sp,gm.cum,t);
|
||||
// Still the same path: strokes keep it, so the dotted fiber line goes on top without building it again.
|
||||
if(df&&!bld&&!dark){ctx.strokeStyle='rgba(255,255,255,.75)';ctx.lineWidth=Math.max(1,w*0.25);ctx.setLineDash([1,6]);ctx.stroke();ctx.setLineDash([]);}
|
||||
const at=t=>polyAtXY(SX,SY,gm.cum,t);
|
||||
if(!cut&&load>0.01){const n=clamp(Math.round(2+u*10),2,12)>>(far?1:0)||1,len=gm.len*z,spd=90;
|
||||
ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=far?1:1.5;
|
||||
const rr2=far?1.6:Math.max(2.2,w*.42),base=now/1000*spd/Math.max(len,40);ctx.beginPath();for(let i=0;i<n;i++){let t=(base+i/n)%1;if(i%2)t=1-t;const [px,py]=at(t);ctx.moveTo(px+rr2,py);ctx.arc(px,py,rr2,0,7);}ctx.fill();ctx.stroke();}
|
||||
const [mx2,my]=at(.5);const mxx=mx2;
|
||||
if(bld){if(far){ctx.fillStyle='#FF8A3D';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,4,0,7);ctx.fill();ctx.stroke();}else drawCone(mxx,my,now);}
|
||||
else if(cut&&!vx){if(far){ctx.fillStyle='#FF4D5E';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(mxx,my,5,0,7);ctx.fill();ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',mxx,my+0.5);}else drawBackhoe(mxx,my,now,l.sub);}
|
||||
else if(z>0.9||sel){const t=many?groupLabel(grp,up):capName(l);ctx.font='800 11px "Baloo 2", sans-serif';const tw=ctx.measureText(t).width+10;ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);}
|
||||
else if(z>0.9||sel){const t=many?groupLabel(grp,up):capName(l);ctx.font='800 11px "Baloo 2", sans-serif';let tw=LINKW.get(t);if(tw===undefined)LINKW.set(t,tw=ctx.measureText(t).width+10);ctx.fillStyle='#fff';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(mxx-tw/2,my-9,tw,17,8);ctx.fill();ctx.stroke();ctx.fillStyle='#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,mxx,my+1);}
|
||||
}
|
||||
}
|
||||
// drag preview
|
||||
|
|
@ -3878,6 +3986,9 @@ function draw(now){
|
|||
for(const y of [below,above]){const r={x:v.sx-tw/2-2,y:y-10,w:tw+4,h:21};if(!hit(r)){ly=y;rects.push(r);break;}}
|
||||
if(ly===null&&prio(v)<2){ly=below;rects.push({x:v.sx-tw/2,y:below-10,w:tw,h:21});}
|
||||
v.ly=ly;}
|
||||
// Which cities show an offer bubble (a big one?) or an incident marker, worked out once for all of them.
|
||||
CM.off=new Set();CM.big=new Set();for(const o of S.offers){const big=BIZ_T[o.type].lv>=3||BIZ_T[o.type].event;for(const c of bCities(o)){CM.off.add(c);if(big)CM.big.add(c);}}
|
||||
CM.inc=new Set(S.inc.filter(i=>i.type!=='leak').map(i=>i.ref));CM.far=farL;
|
||||
for(const v of vis.slice().reverse())drawCity(v.C,v.sx,v.sy,sc,now,v.ly);
|
||||
// floaters
|
||||
for(let i=FLOATS.length-1;i>=0;i--){const f=FLOATS[i],a=(now-f.t)/1600;if(a>1){FLOATS.splice(i,1);continue;}
|
||||
|
|
@ -3930,8 +4041,9 @@ function drawBackhoe(x,y,now,sub){
|
|||
}
|
||||
ctx.restore();
|
||||
}
|
||||
const LBLW={};
|
||||
try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];});}catch(e){}
|
||||
// Label widths by text (city labels by id, link labels and far-view labels by text): measuring text every frame is slow.
|
||||
const LBLW={},LINKW=new Map(),LBLF=new Map(),CM={off:new Set(),big:new Set(),inc:new Set(),far:false};
|
||||
try{document.fonts&&document.fonts.ready.then(()=>{for(const k in LBLW)delete LBLW[k];LINKW.clear();LBLF.clear();});}catch(e){}
|
||||
function drawCityFar(C,sx,sy,sc,now,lyOverride){
|
||||
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
|
||||
ctx.save();ctx.translate(sx,sy);ctx.strokeStyle='#1E2640';
|
||||
|
|
@ -3943,15 +4055,15 @@ function drawCityFar(C,sx,sy,sc,now,lyOverride){
|
|||
if((p.routers||1)>=2){ctx.fillStyle=down?'#6E7590':'#D63B7F';rr(-6,-7,15,10,4);ctx.fill();ctx.stroke();}
|
||||
ctx.fillStyle=col;rr(-8,-5,16,10,4);ctx.fill();ctx.stroke();
|
||||
}else{ctx.fillStyle=hasIxAt(C.id)?'#FFD23F':'#FFFFFF';ctx.lineWidth=1.5;ctx.beginPath();ctx.arc(0,0,hov?4.5:3.4,0,7);ctx.fill();ctx.stroke();}
|
||||
if(S.offers.some(o=>bCities(o).includes(C.id))){ctx.fillStyle='#16A866';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?9:5,p?-7:-5,3,0,7);ctx.fill();ctx.stroke();}
|
||||
if(S.inc.some(i=>i.ref===C.id&&i.type!=='leak')){ctx.fillStyle='#FF4D5E';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?-9:-5,p?-7:-5,3.4,0,7);ctx.fill();ctx.stroke();}
|
||||
if(CM.off.has(C.id)){ctx.fillStyle='#16A866';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?9:5,p?-7:-5,3,0,7);ctx.fill();ctx.stroke();}
|
||||
if(CM.inc.has(C.id)){ctx.fillStyle='#FF4D5E';ctx.lineWidth=1.2;ctx.beginPath();ctx.arc(p?-9:-5,p?-7:-5,3.4,0,7);ctx.fill();ctx.stroke();}
|
||||
ctx.restore();
|
||||
if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,tw=ctx.measureText(t).width+12,ly=lyOverride==null?sy+15:lyOverride;
|
||||
if(lyOverride!==null&&(p||sel||hov)){ctx.font=`800 ${p?12:11}px "Baloo 2", sans-serif`;const t=C.name,wk=C.id+(p?1:0);let tw=LBLF.get(wk);if(tw===undefined)LBLF.set(wk,tw=ctx.measureText(t).width+12);const ly=lyOverride==null?sy+15:lyOverride;
|
||||
ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=1.6;rr(sx-tw/2,ly-8,tw,16,8);ctx.fill();ctx.stroke();
|
||||
ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);}
|
||||
}
|
||||
function drawCity(C,sx,sy,sc,now,lyOverride){
|
||||
if(lodFar())return drawCityFar(C,sx,sy,sc,now,lyOverride);
|
||||
if(CM.far)return drawCityFar(C,sx,sy,sc,now,lyOverride);
|
||||
const hot=(UI.hotMap||{})[C.id];
|
||||
const p=S.pops[C.id],down=p&&p.down>S.day,sel=UI.sel&&UI.sel.type==='city'&&UI.sel.id===C.id,hov=UI.hover===C.id||(UI.snap&&UI.snap.id===C.id);
|
||||
const k=sc*(hov?1.15:1);
|
||||
|
|
@ -3987,14 +4099,14 @@ function drawCity(C,sx,sy,sc,now,lyOverride){
|
|||
if(ixn){const mine=!!S.myIx[C.id],joined=hasIxAt(C.id);const ixHot=hot&&hot.ix;ctx.fillStyle=ixHot?(Math.sin(now/180)>0?'#FF4D5E':'#FF8A3D'):mine?'#FF4F9A':joined?'#FFD23F':'#FFFFFF';ctx.beginPath();for(let i=0;i<6;i++){const a=Math.PI/3*i+Math.PI/6;ctx.lineTo(19+8.5*Math.cos(a),-h+2+8.5*Math.sin(a));}ctx.closePath();ctx.fill();ctx.lineWidth=2;ctx.stroke();
|
||||
ctx.fillStyle=mine||ixHot?'#fff':'#1E2640';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('IX',19,-h+2.5);}
|
||||
if(hot&&p){let y=-14;const pulse=.75+.25*Math.sin(now/200);for(const k of ['r','t','p','c']){if(!hot[k])continue;ctx.globalAlpha=pulse;ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-29,y,6.5,0,7);ctx.fill();ctx.globalAlpha=1;ctx.lineWidth=2;ctx.strokeStyle='#1E2640';ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 8px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(HOTL[k],-29,y+0.5);y+=14;}}
|
||||
const off=S.offers.some(o=>bCities(o).includes(C.id));
|
||||
if(off){const by=-h-16+Math.sin(now/250)*3;ctx.fillStyle='#fff';ctx.lineWidth=2.2;ctx.beginPath();ctx.ellipse(-2,by,11,9,0,0,7);ctx.fill();ctx.stroke();ctx.beginPath();ctx.moveTo(-5,by+8);ctx.lineTo(-7,by+14);ctx.lineTo(0,by+8);ctx.fillStyle='#fff';ctx.fill();const big=S.offers.some(o=>bCities(o).includes(C.id)&&(BIZ_T[o.type].lv>=3||BIZ_T[o.type].event));ctx.fillStyle=big?'#FF4F9A':'#16A866';ctx.font='900 13px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(big?'$$':'$',-2,by+1);}
|
||||
const inc=S.inc.some(i=>i.ref===C.id&&i.type!=='leak');
|
||||
const off=CM.off.has(C.id);
|
||||
if(off){const by=-h-16+Math.sin(now/250)*3;ctx.fillStyle='#fff';ctx.lineWidth=2.2;ctx.beginPath();ctx.ellipse(-2,by,11,9,0,0,7);ctx.fill();ctx.stroke();ctx.beginPath();ctx.moveTo(-5,by+8);ctx.lineTo(-7,by+14);ctx.lineTo(0,by+8);ctx.fillStyle='#fff';ctx.fill();const big=CM.big.has(C.id);ctx.fillStyle=big?'#FF4F9A':'#16A866';ctx.font='900 13px "Baloo 2", sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(big?'$$':'$',-2,by+1);}
|
||||
const inc=CM.inc.has(C.id);
|
||||
if(inc){ctx.fillStyle='#FF4D5E';ctx.beginPath();ctx.arc(-20,-h+2,7,0,7);ctx.fill();ctx.lineWidth=2;ctx.stroke();ctx.fillStyle='#fff';ctx.font='900 11px Nunito, sans-serif';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText('!',-20,-h+3);}
|
||||
ctx.restore();
|
||||
// label
|
||||
if((cam.z>=0.62||p||sel||hov)&&(lyOverride!==null||hov)){
|
||||
ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=ctx.measureText(t).width+14,ly=lyOverride==null?sy+16*sc+8:lyOverride;
|
||||
ctx.font=`800 ${p?13:12}px "Baloo 2", sans-serif`;const t=C.name,tw=LBLW[C.id+(p?1:0)]||(LBLW[C.id+(p?1:0)]=ctx.measureText(t).width+14),ly=lyOverride==null?sy+16*sc+8:lyOverride;
|
||||
ctx.fillStyle=p?'#FF4F9A':'#FFFFFF';ctx.strokeStyle='#1E2640';ctx.lineWidth=2;rr(sx-tw/2,ly-9,tw,19,9);ctx.fill();ctx.stroke();
|
||||
ctx.fillStyle=p?'#FFFFFF':'#1E2640';ctx.textAlign='center';ctx.textBaseline='middle';ctx.fillText(t,sx,ly+1);
|
||||
}
|
||||
|
|
@ -4002,7 +4114,7 @@ function drawCity(C,sx,sy,sc,now,lyOverride){
|
|||
|
||||
/* ---------- hit tests & input ---------- */
|
||||
function hitCity(x,y,r=28){let best=null,bd=r*iconScale();const KS=visibleKs();for(const C of CITIES)for(const k of KS){const [sx,sy]=toS(C.x,C.y,k);const d=Math.hypot(sx-x,sy+4-y);if(d<bd){bd=d;best={id:C.id,sx,sy};}}return best;}
|
||||
function hitLink(x,y){if(!S)return null;let best=null,bd=12;const KS=visibleKs();for(const grp of linkGroups()){const l=grp[0];const g=linkGeom(l);for(const k of KS){let prev=null;for(const p of g.pts){const q=toS(p[0],p[1],k);if(prev){const d=segDist(x,y,prev,q);if(d<bd){bd=d;best=l.id;}}prev=q;}}}return best;}
|
||||
function hitLink(x,y){if(!S)return null;let best=null,bd=12;const KS=visibleKs(),PI=pairIdx();for(const grp of linkGroups()){const l=grp[0];const g=linkGeom(l,PI.get(edgeKey(l)));for(const k of KS){let prev=null;for(const p of g.pts){const q=toS(p[0],p[1],k);if(prev){const d=segDist(x,y,prev,q);if(d<bd){bd=d;best=l.id;}}prev=q;}}}return best;}
|
||||
function wrapCam(){cam.x=((cam.x%W)+W)%W;cam.y=clamp(cam.y,0,H);}
|
||||
const ptrs=new Map();
|
||||
cv.addEventListener('pointerdown',e=>{audioInit();cv.setPointerCapture(e.pointerId);ptrs.set(e.pointerId,{x:e.clientX,y:e.clientY});
|
||||
|
|
|
|||
101
tests/speed.test.js
Normal file
101
tests/speed.test.js
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { load } = require('./harness');
|
||||
|
||||
// A network on four continents: POPs, waves, transit, IX ports, PNIs, caches and customers.
|
||||
function bigNet(ev) {
|
||||
ev("ACT.start({});S.cash=1e10;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'})");
|
||||
ev("for(const c of ['ams','lon','par','nyc','ash','chi','sjc','tok','hkg','sin','syd','sao'])ACT.buildPop({city:c})");
|
||||
ev("for(const [a,b] of [['fra','ams'],['ams','lon'],['lon','par'],['par','fra'],['lon','nyc'],['nyc','ash'],['ash','chi'],['chi','sjc'],['sjc','syd'],['tok','hkg'],['hkg','sin'],['sin','syd'],['nyc','sao']]){UI.via=null;openLinkModal(a,b);ACT.buildLink({tier:1});closeModal();}");
|
||||
ev("for(const c in S.pops){S.pops[c].bb=S.pops[c].bb||{d:0};S.pops[c].bb.d=500;}");
|
||||
ev("for(const [c,n] of [['fra','cog'],['nyc','lvl'],['sin','cog'],['tok','lvl']])ACT.buyTransit({city:c,net:n,tier:1})");
|
||||
ev("for(const c of ['fra','ams','lon','nyc','sin','tok'])ACT.buyIx({city:c,tier:1,signed:true});for(const c in S.ixp)ACT.rs({city:c});compute()");
|
||||
ev("for(const n of ['ggl','nfx','fbk','amz','akm'])for(const c of ['fra','nyc','sin'])ACT.pni({city:c,net:n,tier:1});compute()");
|
||||
ev("for(const n of ['nfx','ggl'])for(const c of ['fra','nyc','sin','lon'])ACT.cache({city:c,net:n})");
|
||||
ev("for(let i=0;i<150;i++){S.offers=[];spawnOffer();for(const o of S.offers.slice())if(bHas(o))ACT.accept({id:o.id});}closeModal();compute()");
|
||||
}
|
||||
|
||||
test('a preferred exit far away still wins over a normal one next door', () => {
|
||||
const { ev, errors } = load();
|
||||
ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0;ACT.launchBB({city:'fra'});ACT.buildPop({city:'ams'})");
|
||||
ev("UI.via=null;openLinkModal('fra','ams');ACT.buildLink({tier:1});closeModal();ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyTransit({city:'ams',net:'tly',tier:1});compute()");
|
||||
assert.equal(ev('S.links.length'), 1);
|
||||
const use = () => JSON.parse(ev("JSON.stringify(S.transit.map(t=>R.useT[t.id]||0))"));
|
||||
assert.equal(use()[1], 0, 'normal: the local transit carries it all');
|
||||
ev("S.transit[1].pref='high';compute()");
|
||||
const [fra, ams] = use();
|
||||
assert.ok(ams > 0 && ams > fra, `preferred: Amsterdam's transit comes first (${fra} / ${ams})`);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('what crosses each link adds up, and is put together when it is looked at', () => {
|
||||
const { ev, errors } = load();
|
||||
bigNet(ev);
|
||||
assert.ok(ev("Object.keys(R.ef).length") > 5, 'traffic on many links');
|
||||
// every push adds the same amount to one egress, one network and one source city
|
||||
const bad = ev(`Object.keys(R.ef).filter(k=>{const r=R.ef[k],s=o=>Object.values(o).reduce((a,b)=>a+b,0),n=s(r.net);
|
||||
const load=S.links.filter(l=>edgeKey(l)===k).reduce((a,l)=>a+(R.load[l.id]||0),0);
|
||||
return Math.abs(n-s(r.eg))>1e-6*(1+n)||Math.abs(n-s(r.dst))>1e-6*(1+n)||Math.abs(n-load)>1e-6*(1+n);}).join()`);
|
||||
assert.equal(bad, '', 'per network, per egress, per source city and the link load agree');
|
||||
assert.equal(ev("const k=Object.keys(R.ef)[0];R.ef[k]===R.ef[k]"), true, 'the same record every time');
|
||||
assert.equal(ev("JSON.parse(JSON.stringify(R)).ef[Object.keys(R.ef)[0]].net!==undefined"), true);
|
||||
// the link panel reads it
|
||||
ev("const k=Object.keys(R.ef)[0],l=S.links.find(x=>edgeKey(x)===k);selectLink(l.id)");
|
||||
assert.match(ev("document.getElementById('panelBody').textContent"), /Content from/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('a big network routes every flow to an exit with room, and caches serve their own city', () => {
|
||||
const { ev, errors } = load();
|
||||
bigNet(ev);
|
||||
for (let d = 0; d < 20; d++) ev('dayTick()');
|
||||
assert.ok(ev('R.served>0&&R.served<=R.demand+1e-6'));
|
||||
assert.equal(ev(`[...S.transit.map(t=>[R.useT[t.id]||0,lagCap(PORT[t.tier].g,t.n)]),...S.pni.map(p=>[R.usePni[p.id]||0,lagCap(PORT[p.tier].g,p.n)]),...S.caches.map(c=>[R.useCache[c.id]||0,CACHE_CAP])].filter(([u,c])=>u>c+1e-6).length`), 0, 'no port over capacity');
|
||||
assert.equal(ev("Object.keys(S.pops).filter(c=>R.citySrv[c]>R.cityDem[c]+1e-6).length"), 0, 'no city served more than it asked for');
|
||||
assert.ok(ev('S.caches.length>0&&S.caches.every(c=>R.useCache[c.id]>0)'), 'every cache serves its own city');
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('panels are patched in place: the same HTML, and buttons that now do something else are new', () => {
|
||||
const { ev, errors } = load();
|
||||
bigNet(ev);
|
||||
ev("selectCity('fra');ACT.tab({t:'peer'})");
|
||||
const fresh = "(()=>{const d=document.createElement('div');d.innerHTML=UI._ph;return d.innerHTML;})()";
|
||||
const same = () => ev(`(()=>{const a=[...document.getElementById('panelBody').querySelectorAll('*')],d=document.createElement('div');d.innerHTML=UI._ph;const b=[...d.querySelectorAll('*')];
|
||||
return a.length===b.length&&a.every((x,i)=>x.nodeName===b[i].nodeName&&x.attributes.length===b[i].attributes.length&&[...b[i].attributes].every(t=>x.getAttribute(t.name)===t.value)&&(x.children.length||x.textContent===b[i].textContent));})()`);
|
||||
assert.equal(same(), true);
|
||||
ev("window.__tab=document.querySelector('#panelBody [data-act=\"tab\"]')");
|
||||
for (let d = 0; d < 3; d++) ev('dayTick();renderPanel()');
|
||||
assert.equal(same(), true, 'patched panel matches a fresh render');
|
||||
assert.equal(ev("window.__tab===document.querySelector('#panelBody [data-act=\"tab\"]')"), true, 'an unchanged button stays the same button');
|
||||
// another city: its buttons act on that city, so a tap that started on the old ones cannot fire them (#44)
|
||||
ev("window.__btn=[...document.querySelectorAll('#panelBody [data-act]')].find(b=>(b.dataset.args||'').includes('\"fra\"'))");
|
||||
ev("selectCity('nyc');ACT.tab({t:'peer'})");
|
||||
assert.equal(same(), true);
|
||||
assert.equal(ev("document.getElementById('panelBody').contains(window.__btn)"), false);
|
||||
assert.ok(ev(fresh).length > 1000);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the network list shows where you connect to each network', () => {
|
||||
const { ev, errors } = load();
|
||||
bigNet(ev);
|
||||
// one index for the whole list says the same as asking network by network
|
||||
assert.equal(ev("const w=netWhereIdx();NETS.filter(n=>netWhere(n,w)!==netWhere(n)).length"), 0);
|
||||
assert.ok(ev("netWhere(NET.ggl).includes('goConn')"));
|
||||
ev("UI.leftOpen=true;ACT.leftTab({t:'nets'})");
|
||||
assert.match(ev("document.getElementById('leftBody').textContent"), /Goggle/);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test('the map draws a big network at every zoom, with a city or a link selected', () => {
|
||||
const { ev, errors } = load();
|
||||
bigNet(ev);
|
||||
ev("localStorage.setItem('sot-anim','on');UI.anim='on'");
|
||||
for (const sel of ['null', "{type:'city',id:'fra'}", "{type:'link',id:S.links[2].id}"]) {
|
||||
for (const z of [0.35, 0.6, 1.2, 2.5, 6]) ev(`UI.sel=${sel};cam.z=${z};draw(1000);draw(1016)`);
|
||||
}
|
||||
assert.ok(ev('ctx.calls.n') > 1000);
|
||||
assert.ok(ev("hitLink(...toS(CITY.fra.x,CITY.fra.y,0))!==undefined"));
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue